blob: 3f2523533e886f2eb2fae63ccc4ac2cd1cd04a39 [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
Nick Piggine2867812008-07-25 19:45:30 -07001407/*
Andrew Morton1742f192006-03-22 00:08:21 -08001408 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001409 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001410static unsigned int shrink_page_list(struct list_head *page_list,
1411 struct pglist_data *pgdat,
1412 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001413 struct reclaim_stat *stat,
1414 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001415{
1416 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001417 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001418 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001419 unsigned int nr_reclaimed = 0;
1420 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001421 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001422
Kirill Tkhai060f0052019-03-05 15:48:15 -08001423 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001424 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001425 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001426
Dave Hansen26aa2d12021-09-02 14:59:16 -07001427retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001428 while (!list_empty(page_list)) {
1429 struct address_space *mapping;
1430 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001431 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001432 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001433 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001434
1435 cond_resched();
1436
1437 page = lru_to_page(page_list);
1438 list_del(&page->lru);
1439
Nick Piggin529ae9a2008-08-02 12:01:03 +02001440 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001441 goto keep;
1442
Sasha Levin309381fea2014-01-23 15:52:54 -08001443 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001444
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001445 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001446
1447 /* Account the number of base pages even though THP */
1448 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001449
Hugh Dickins39b5f292012-10-08 16:33:18 -07001450 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001451 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001452
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001453 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001454 goto keep_locked;
1455
Yu Zhao0182f922022-09-18 02:00:04 -06001456 /* page_update_gen() tried to promote this page? */
1457 if (lru_gen_enabled() && !ignore_references &&
1458 page_mapped(page) && PageReferenced(page))
1459 goto keep_locked;
1460
Andy Whitcroftc661b072007-08-22 14:01:26 -07001461 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1462 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1463
Mel Gorman283aba92013-07-03 15:01:51 -07001464 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001465 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001466 * reclaim_congested which affects wait_iff_congested. kswapd
1467 * will stall and start writing pages if the tail of the LRU
1468 * is all dirty unqueued pages.
1469 */
1470 page_check_dirty_writeback(page, &dirty, &writeback);
1471 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001472 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001473
1474 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001475 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001476
Mel Gormand04e8ac2013-07-03 15:02:03 -07001477 /*
1478 * Treat this page as congested if the underlying BDI is or if
1479 * pages are cycling through the LRU so quickly that the
1480 * pages marked for immediate reclaim are making it to the
1481 * end of the LRU a second time.
1482 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001483 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001484 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001485 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001486 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001487 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001488
1489 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001490 * If a page at the tail of the LRU is under writeback, there
1491 * are three cases to consider.
1492 *
1493 * 1) If reclaim is encountering an excessive number of pages
1494 * under writeback and this page is both under writeback and
1495 * PageReclaim then it indicates that pages are being queued
1496 * for IO but are being recycled through the LRU before the
1497 * IO can complete. Waiting on the page itself risks an
1498 * indefinite stall if it is impossible to writeback the
1499 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001500 * note that the LRU is being scanned too quickly and the
1501 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001502 *
Tejun Heo97c93412015-05-22 18:23:36 -04001503 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001504 * not marked for immediate reclaim, or the caller does not
1505 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1506 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001507 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001508 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001509 * Require may_enter_fs because we would wait on fs, which
1510 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001511 * enter reclaim, and deadlock if it waits on a page for
1512 * which it is needed to do the write (loop masks off
1513 * __GFP_IO|__GFP_FS for this reason); but more thought
1514 * would probably show more reasons.
1515 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001516 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001517 * PageReclaim. memcg does not have any dirty pages
1518 * throttling so we could easily OOM just because too many
1519 * pages are in writeback and there is nothing else to
1520 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001521 *
1522 * In cases 1) and 2) we activate the pages to get them out of
1523 * the way while we continue scanning for clean pages on the
1524 * inactive list and refilling from the active list. The
1525 * observation here is that waiting for disk writes is more
1526 * expensive than potentially causing reloads down the line.
1527 * Since they're marked for immediate reclaim, they won't put
1528 * memory pressure on the cache working set any longer than it
1529 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001530 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001531 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001532 /* Case 1 above */
1533 if (current_is_kswapd() &&
1534 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001535 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001536 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001537 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001538
1539 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001540 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001541 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001542 /*
1543 * This is slightly racy - end_page_writeback()
1544 * might have just cleared PageReclaim, then
1545 * setting PageReclaim here end up interpreted
1546 * as PageReadahead - but that does not matter
1547 * enough to care. What we do want is for this
1548 * page to have PageReclaim set next time memcg
1549 * reclaim reaches the tests above, so it will
1550 * then wait_on_page_writeback() to avoid OOM;
1551 * and it's also appropriate in global reclaim.
1552 */
1553 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001554 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001555 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001556
1557 /* Case 3 above */
1558 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001559 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001560 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001561 /* then go back and try same page again */
1562 list_add_tail(&page->lru, page_list);
1563 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001564 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001565 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001566
Minchan Kim8940b342019-09-25 16:49:11 -07001567 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001568 references = page_check_references(page, sc);
1569
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001570 switch (references) {
1571 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001572 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001573 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001574 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001575 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001576 case PAGEREF_RECLAIM:
1577 case PAGEREF_RECLAIM_CLEAN:
1578 ; /* try to reclaim the page below */
1579 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001580
Linus Torvalds1da177e2005-04-16 15:20:36 -07001581 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001582 * Before reclaiming the page, try to relocate
1583 * its contents to another node.
1584 */
1585 if (do_demote_pass &&
1586 (thp_migration_supported() || !PageTransHuge(page))) {
1587 list_add(&page->lru, &demote_pages);
1588 unlock_page(page);
1589 continue;
1590 }
1591
1592 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001593 * Anonymous process memory has backing store?
1594 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001595 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001596 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001597 if (PageAnon(page) && PageSwapBacked(page)) {
1598 if (!PageSwapCache(page)) {
1599 if (!(sc->gfp_mask & __GFP_IO))
1600 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001601 if (page_maybe_dma_pinned(page))
1602 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001603 if (PageTransHuge(page)) {
1604 /* cannot split THP, skip it */
1605 if (!can_split_huge_page(page, NULL))
1606 goto activate_locked;
1607 /*
1608 * Split pages without a PMD map right
1609 * away. Chances are some or all of the
1610 * tail pages can be freed without IO.
1611 */
1612 if (!compound_mapcount(page) &&
1613 split_huge_page_to_list(page,
1614 page_list))
1615 goto activate_locked;
1616 }
1617 if (!add_to_swap(page)) {
1618 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001619 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001620 /* Fallback to swap normal pages */
1621 if (split_huge_page_to_list(page,
1622 page_list))
1623 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001624#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1625 count_vm_event(THP_SWPOUT_FALLBACK);
1626#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001627 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001628 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001629 }
Minchan Kim0f074652017-07-06 15:37:24 -07001630
Kirill Tkhai4b793062020-04-01 21:10:18 -07001631 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001632
1633 /* Adding to swap updated mapping */
1634 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001635 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001636 } else if (unlikely(PageTransHuge(page))) {
1637 /* Split file THP */
1638 if (split_huge_page_to_list(page, page_list))
1639 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001640 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001641
1642 /*
Yang Shi98879b32019-07-11 20:59:30 -07001643 * THP may get split above, need minus tail pages and update
1644 * nr_pages to avoid accounting tail pages twice.
1645 *
1646 * The tail pages that are added into swap cache successfully
1647 * reach here.
1648 */
1649 if ((nr_pages > 1) && !PageTransHuge(page)) {
1650 sc->nr_scanned -= (nr_pages - 1);
1651 nr_pages = 1;
1652 }
1653
1654 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001655 * The page is mapped into the page tables of one or more
1656 * processes. Try to unmap it here.
1657 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001658 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001659 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001660 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001661
1662 if (unlikely(PageTransHuge(page)))
1663 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001664
Yang Shi1fb08ac2021-06-30 18:52:01 -07001665 try_to_unmap(page, flags);
1666 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001667 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001668 if (!was_swapbacked && PageSwapBacked(page))
1669 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001670 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001671 }
1672 }
1673
1674 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001675 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001676 * Only kswapd can writeback filesystem pages
1677 * to avoid risk of stack overflow. But avoid
1678 * injecting inefficient single-page IO into
1679 * flusher writeback as much as possible: only
1680 * write pages when we've encountered many
1681 * dirty pages, and when we've already scanned
1682 * the rest of the LRU for clean pages and see
1683 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001684 */
Huang Ying9de4f222020-04-06 20:04:41 -07001685 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001686 (!current_is_kswapd() || !PageReclaim(page) ||
1687 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001688 /*
1689 * Immediately reclaim when written back.
1690 * Similar in principal to deactivate_page()
1691 * except we already have the page isolated
1692 * and know it's dirty
1693 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001694 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001695 SetPageReclaim(page);
1696
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001697 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001698 }
1699
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001700 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001701 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001702 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001703 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001704 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001705 goto keep_locked;
1706
Mel Gormand950c942015-09-04 15:47:35 -07001707 /*
1708 * Page is dirty. Flush the TLB if a writable entry
1709 * potentially exists to avoid CPU writes after IO
1710 * starts and then write it out here.
1711 */
1712 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001713 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001714 case PAGE_KEEP:
1715 goto keep_locked;
1716 case PAGE_ACTIVATE:
1717 goto activate_locked;
1718 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001719 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001720
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001721 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001722 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001723 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001724 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001725
Linus Torvalds1da177e2005-04-16 15:20:36 -07001726 /*
1727 * A synchronous write - probably a ramdisk. Go
1728 * ahead and try to reclaim the page.
1729 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001730 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001731 goto keep;
1732 if (PageDirty(page) || PageWriteback(page))
1733 goto keep_locked;
1734 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001735 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001736 case PAGE_CLEAN:
1737 ; /* try to free the page below */
1738 }
1739 }
1740
1741 /*
1742 * If the page has buffers, try to free the buffer mappings
1743 * associated with this page. If we succeed we try to free
1744 * the page as well.
1745 *
1746 * We do this even if the page is PageDirty().
1747 * try_to_release_page() does not perform I/O, but it is
1748 * possible for a page to have PageDirty set, but it is actually
1749 * clean (all its buffers are clean). This happens if the
1750 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001751 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001752 * try_to_release_page() will discover that cleanness and will
1753 * drop the buffers and mark the page clean - it can be freed.
1754 *
1755 * Rarely, pages can have buffers and no ->mapping. These are
1756 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001757 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001758 * and if that worked, and the page is no longer mapped into
1759 * process address space (page_count == 1) it can be freed.
1760 * Otherwise, leave the page on the LRU so it is swappable.
1761 */
David Howells266cf652009-04-03 16:42:36 +01001762 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001763 if (!try_to_release_page(page, sc->gfp_mask))
1764 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001765 if (!mapping && page_count(page) == 1) {
1766 unlock_page(page);
1767 if (put_page_testzero(page))
1768 goto free_it;
1769 else {
1770 /*
1771 * rare race with speculative reference.
1772 * the speculative reference will free
1773 * this page shortly, so we may
1774 * increment nr_reclaimed here (and
1775 * leave it off the LRU).
1776 */
1777 nr_reclaimed++;
1778 continue;
1779 }
1780 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001781 }
1782
Shaohua Li802a3a92017-05-03 14:52:32 -07001783 if (PageAnon(page) && !PageSwapBacked(page)) {
1784 /* follow __remove_mapping for reference */
1785 if (!page_ref_freeze(page, 1))
1786 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001787 /*
1788 * The page has only one reference left, which is
1789 * from the isolation. After the caller puts the
1790 * page back on lru and drops the reference, the
1791 * page will be freed anyway. It doesn't matter
1792 * which lru it goes. So we don't bother checking
1793 * PageDirty here.
1794 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001795 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001796 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001797 } else if (!mapping || !__remove_mapping(mapping, page, true,
1798 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001799 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001800
1801 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001802free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001803 /*
1804 * THP may get swapped out in a whole, need account
1805 * all base pages.
1806 */
1807 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001808
1809 /*
1810 * Is there need to periodically free_page_list? It would
1811 * appear not as the counts should be low
1812 */
Yang Shi7ae88532019-09-23 15:38:09 -07001813 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001814 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001815 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001816 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001817 continue;
1818
Yang Shi98879b32019-07-11 20:59:30 -07001819activate_locked_split:
1820 /*
1821 * The tail pages that are failed to add into swap cache
1822 * reach here. Fixup nr_scanned and nr_pages.
1823 */
1824 if (nr_pages > 1) {
1825 sc->nr_scanned -= (nr_pages - 1);
1826 nr_pages = 1;
1827 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001828activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001829 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001830 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1831 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001832 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001833 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001834 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001835 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001836 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001837 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001838 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001839 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001840keep_locked:
1841 unlock_page(page);
1842keep:
1843 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001844 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001845 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001846 /* 'page_list' is always empty here */
1847
1848 /* Migrate pages selected for demotion */
1849 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1850 /* Pages that could not be demoted are still in @demote_pages */
1851 if (!list_empty(&demote_pages)) {
1852 /* Pages which failed to demoted go back on @page_list for retry: */
1853 list_splice_init(&demote_pages, page_list);
1854 do_demote_pass = false;
1855 goto retry;
1856 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001857
Yang Shi98879b32019-07-11 20:59:30 -07001858 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1859
Johannes Weiner747db952014-08-08 14:19:24 -07001860 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001861 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001862 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001863
Linus Torvalds1da177e2005-04-16 15:20:36 -07001864 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001865 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001866
Andrew Morton05ff5132006-03-22 00:08:20 -08001867 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001868}
1869
Maninder Singh730ec8c2020-06-03 16:01:18 -07001870unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001871 struct list_head *page_list)
1872{
1873 struct scan_control sc = {
1874 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001875 .may_unmap = 1,
1876 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001877 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001878 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001879 struct page *page, *next;
1880 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001881 unsigned int noreclaim_flag;
Tao Zeng54f845e2022-01-26 16:04:08 +08001882#ifdef CONFIG_AMLOGIC_CMA
1883 LIST_HEAD(high_active_pages);
1884#endif
Minchan Kim02c6de82012-10-08 16:31:55 -07001885
1886 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001887 if (!PageHuge(page) && page_is_file_lru(page) &&
1888 !PageDirty(page) && !__PageMovable(page) &&
1889 !PageUnevictable(page)) {
Tao Zeng54f845e2022-01-26 16:04:08 +08001890 #ifdef CONFIG_AMLOGIC_CMA
1891 cma_keep_high_active(page, &high_active_pages,
1892 &clean_pages);
1893 #else
Minchan Kim02c6de82012-10-08 16:31:55 -07001894 ClearPageActive(page);
1895 list_move(&page->lru, &clean_pages);
Tao Zeng54f845e2022-01-26 16:04:08 +08001896 #endif
Minchan Kim02c6de82012-10-08 16:31:55 -07001897 }
1898 }
1899
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001900 /*
1901 * We should be safe here since we are only dealing with file pages and
1902 * we are not kswapd and therefore cannot write dirty file pages. But
1903 * call memalloc_noreclaim_save() anyway, just in case these conditions
1904 * change in the future.
1905 */
1906 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001907 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001908 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001909 memalloc_noreclaim_restore(noreclaim_flag);
1910
Minchan Kim02c6de82012-10-08 16:31:55 -07001911 list_splice(&clean_pages, page_list);
Tao Zeng54f845e2022-01-26 16:04:08 +08001912#ifdef CONFIG_AMLOGIC_CMA
1913 list_splice(&high_active_pages, page_list);
1914#endif
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001915 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1916 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001917 /*
1918 * Since lazyfree pages are isolated from file LRU from the beginning,
1919 * they will rotate back to anonymous LRU in the end if it failed to
1920 * discard so isolated count will be mismatched.
1921 * Compensate the isolated count for both LRU lists.
1922 */
1923 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1924 stat.nr_lazyfree_fail);
1925 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001926 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001927 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001928}
1929
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001930/*
Mel Gorman7ee36a12016-07-28 15:47:17 -07001931 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001932 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001933 */
1934static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001935 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001936{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001937 int zid;
1938
Mel Gorman7ee36a12016-07-28 15:47:17 -07001939 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1940 if (!nr_zone_taken[zid])
1941 continue;
1942
Wei Yanga892cb62020-06-03 16:01:12 -07001943 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001944 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001945
Mel Gorman7ee36a12016-07-28 15:47:17 -07001946}
1947
Zhaoyang Huang45022652023-05-31 10:51:01 +08001948#ifdef CONFIG_CMA
1949/*
1950 * It is waste of effort to scan and reclaim CMA pages if it is not available
1951 * for current allocation context. Kswapd can not be enrolled as it can not
1952 * distinguish this scenario by using sc->gfp_mask = GFP_KERNEL
1953 */
1954static bool skip_cma(struct page *page, struct scan_control *sc)
1955{
1956 return !current_is_kswapd() &&
1957 gfp_migratetype(sc->gfp_mask) != MIGRATE_MOVABLE &&
1958 get_pageblock_migratetype(page) == MIGRATE_CMA;
1959}
1960#else
1961static bool skip_cma(struct page *page, struct scan_control *sc)
1962{
1963 return false;
1964}
1965#endif
1966
Mel Gormanf611fab2021-06-30 18:53:19 -07001967/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001968 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1969 *
1970 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001971 * shrink the lists perform better by taking out a batch of pages
1972 * and working on them outside the LRU lock.
1973 *
1974 * For pagecache intensive workloads, this function is the hottest
1975 * spot in the kernel (apart from copy_*_user functions).
1976 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001977 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001978 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001979 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001980 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001981 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001982 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001983 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001984 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001985 *
1986 * returns how many pages were moved onto *@dst.
1987 */
Andrew Morton69e05942006-03-22 00:08:19 -08001988static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001989 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001990 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001991 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001992{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001993 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001994 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001995 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001996 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07001997 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001998 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07001999 LIST_HEAD(pages_skipped);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002000
Yang Shi98879b32019-07-11 20:59:30 -07002001 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002002 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07002003 while (scan < nr_to_scan && !list_empty(src)) {
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002004 struct list_head *move_to = src;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002005 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002006
Linus Torvalds1da177e2005-04-16 15:20:36 -07002007 page = lru_to_page(src);
2008 prefetchw_prev_lru_page(page, src, flags);
2009
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002010 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002011 total_scan += nr_pages;
2012
Zhaoyang Huang45022652023-05-31 10:51:01 +08002013 if (page_zonenum(page) > sc->reclaim_idx ||
2014 skip_cma(page, sc)) {
Yang Shi98879b32019-07-11 20:59:30 -07002015 nr_skipped[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002016 move_to = &pages_skipped;
2017 goto move;
Mel Gormanb2e18752016-07-28 15:45:37 -07002018 }
2019
Minchan Kim791b48b2017-05-12 15:47:06 -07002020 /*
2021 * Do not count skipped pages because that makes the function
2022 * return with no isolated pages if the LRU mostly contains
2023 * ineligible pages. This causes the VM to not reclaim any
2024 * pages, triggering a premature OOM.
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002025 * Account all tail pages of THP.
Minchan Kim791b48b2017-05-12 15:47:06 -07002026 */
Yang Shi98879b32019-07-11 20:59:30 -07002027 scan += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002028
2029 if (!PageLRU(page))
2030 goto move;
2031 if (!sc->may_unmap && page_mapped(page))
2032 goto move;
2033
Alex Shic2135f72021-02-24 12:08:01 -08002034 /*
2035 * Be careful not to clear PageLRU until after we're
2036 * sure the page is not being freed elsewhere -- the
2037 * page release code relies on it.
2038 */
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002039 if (unlikely(!get_page_unless_zero(page)))
2040 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002041
2042 if (!TestClearPageLRU(page)) {
2043 /* Another thread is already isolating this page */
2044 put_page(page);
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002045 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002046 }
2047
2048 nr_taken += nr_pages;
2049 nr_zone_taken[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002050 move_to = dst;
2051move:
2052 list_move(&page->lru, move_to);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002053 }
2054
Mel Gormanb2e18752016-07-28 15:45:37 -07002055 /*
2056 * Splice any skipped pages to the start of the LRU list. Note that
2057 * this disrupts the LRU order when reclaiming for lower zones but
2058 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2059 * scanning would soon rescan the same pages to skip and put the
2060 * system at risk of premature OOM.
2061 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002062 if (!list_empty(&pages_skipped)) {
2063 int zid;
2064
Johannes Weiner3db65812017-05-03 14:52:13 -07002065 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002066 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2067 if (!nr_skipped[zid])
2068 continue;
2069
2070 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002071 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002072 }
2073 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002074 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002075 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002076 total_scan, skipped, nr_taken,
2077 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002078 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002079 return nr_taken;
2080}
2081
Nick Piggin62695a82008-10-18 20:26:09 -07002082/**
2083 * isolate_lru_page - tries to isolate a page from its LRU list
2084 * @page: page to isolate from its LRU list
2085 *
2086 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2087 * vmstat statistic corresponding to whatever LRU list the page was on.
2088 *
2089 * Returns 0 if the page was removed from an LRU list.
2090 * Returns -EBUSY if the page was not on an LRU list.
2091 *
2092 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002093 * the active list, it will have PageActive set. If it was found on
2094 * the unevictable list, it will have the PageUnevictable bit set. That flag
2095 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002096 *
2097 * The vmstat statistic corresponding to the list on which the page was
2098 * found will be decremented.
2099 *
2100 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002101 *
Nick Piggin62695a82008-10-18 20:26:09 -07002102 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002103 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002104 * without a stable reference).
2105 * (2) the lru_lock must not be held.
2106 * (3) interrupts must be enabled.
2107 */
2108int isolate_lru_page(struct page *page)
2109{
2110 int ret = -EBUSY;
2111
Sasha Levin309381fea2014-01-23 15:52:54 -08002112 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002113 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002114
Alex Shid25b5bd2020-12-15 12:34:16 -08002115 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002116 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002117
Alex Shid25b5bd2020-12-15 12:34:16 -08002118 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002119 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002120 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002121 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002122 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002123 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002124
Nick Piggin62695a82008-10-18 20:26:09 -07002125 return ret;
2126}
2127
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002128/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002129 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002130 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002131 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2132 * the LRU list will go small and be scanned faster than necessary, leading to
2133 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002134 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002135static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002136 struct scan_control *sc)
2137{
2138 unsigned long inactive, isolated;
2139
2140 if (current_is_kswapd())
2141 return 0;
2142
Johannes Weinerb5ead352019-11-30 17:55:40 -08002143 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002144 return 0;
2145
2146 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002147 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2148 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002149 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002150 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2151 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002152 }
2153
Fengguang Wu3cf23842012-12-18 14:23:31 -08002154 /*
2155 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2156 * won't get blocked by normal direct-reclaimers, forming a circular
2157 * deadlock.
2158 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002159 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002160 inactive >>= 3;
2161
Tao Zeng54f845e2022-01-26 16:04:08 +08002162#ifdef CONFIG_AMLOGIC_CMA
2163 check_cma_isolated(&isolated, inactive, inactive);
2164#endif
Rik van Riel35cd7812009-09-21 17:01:38 -07002165 return isolated > inactive;
2166}
2167
Kirill Tkhaia222f342019-05-13 17:17:00 -07002168/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002169 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2170 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002171 *
2172 * Returns the number of pages moved to the given lruvec.
2173 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002174static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2175 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002176{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002177 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002178 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002179 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002180
Kirill Tkhaia222f342019-05-13 17:17:00 -07002181 while (!list_empty(list)) {
2182 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002183 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002184 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002185 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002186 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002187 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002188 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002189 continue;
2190 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002191
Alex Shi3d06afa2020-12-15 12:33:37 -08002192 /*
2193 * The SetPageLRU needs to be kept here for list integrity.
2194 * Otherwise:
2195 * #0 move_pages_to_lru #1 release_pages
2196 * if !put_page_testzero
2197 * if (put_page_testzero())
2198 * !PageLRU //skip lru_lock
2199 * SetPageLRU()
2200 * list_add(&page->lru,)
2201 * list_add(&page->lru,)
2202 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002203 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002204
Alex Shi3d06afa2020-12-15 12:33:37 -08002205 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002206 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002207
2208 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002209 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002210 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002211 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002212 } else
2213 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002214
2215 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002216 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002217
Alex Shiafca9152020-12-15 12:34:02 -08002218 /*
2219 * All pages were isolated from the same lruvec (and isolation
2220 * inhibits memcg migration).
2221 */
Muchun Song7467c392021-06-28 19:37:59 -07002222 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002223 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002224 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002225 nr_moved += nr_pages;
2226 if (PageActive(page))
2227 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002228 }
Mel Gorman66635622010-08-09 17:19:30 -07002229
Hugh Dickins3f797682012-01-12 17:20:07 -08002230 /*
2231 * To save our caller's stack, now use input list for pages to free.
2232 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002233 list_splice(&pages_to_free, list);
2234
2235 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002236}
2237
2238/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002239 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002240 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002241 * In that case we should only throttle if the backing device it is
2242 * writing to is congested. In other cases it is safe to throttle.
2243 */
2244static int current_may_throttle(void)
2245{
NeilBrowna37b0712020-06-01 21:48:18 -07002246 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002247 current->backing_dev_info == NULL ||
2248 bdi_write_congested(current->backing_dev_info);
2249}
2250
2251/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002252 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002253 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002254 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002255static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002256shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002257 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002258{
2259 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002260 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002261 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002262 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002263 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002264 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002265 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002266 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002267 bool stalled = false;
Minchan Kim7df45e52022-10-27 08:29:17 -07002268 struct blk_plug plug;
2269 bool do_plug = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002270
Mel Gorman599d0c92016-07-28 15:45:31 -07002271 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002272 if (stalled)
2273 return 0;
2274
2275 /* wait a bit for the reclaimer. */
2276 msleep(100);
2277 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002278
2279 /* We are about to die and free our memory. Return now. */
2280 if (fatal_signal_pending(current))
2281 return SWAP_CLUSTER_MAX;
2282 }
2283
Linus Torvalds1da177e2005-04-16 15:20:36 -07002284 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002285
Alex Shi6168d0d2020-12-15 12:34:29 -08002286 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002287
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002288 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002289 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002290
Mel Gorman599d0c92016-07-28 15:45:31 -07002291 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002292 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002293 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002294 __count_vm_events(item, nr_scanned);
2295 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002296 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2297
Alex Shi6168d0d2020-12-15 12:34:29 -08002298 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002299
Hillf Dantond563c052012-03-21 16:34:02 -07002300 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002301 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002302
Minchan Kim7df45e52022-10-27 08:29:17 -07002303 trace_android_vh_shrink_inactive_list_blk_plug(&do_plug);
2304 if (do_plug)
2305 blk_start_plug(&plug);
Shakeel Butt013339d2020-12-14 19:06:39 -08002306 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002307
Alex Shi6168d0d2020-12-15 12:34:29 -08002308 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002309 move_pages_to_lru(lruvec, &page_list);
2310
2311 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002312 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002313 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002314 __count_vm_events(item, nr_reclaimed);
2315 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002316 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002317 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002318
Minchan Kim7df45e52022-10-27 08:29:17 -07002319 if (do_plug)
2320 blk_finish_plug(&plug);
2321
Alex Shi75cc3c92020-12-15 14:20:50 -08002322 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002323 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002324 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002325
Mel Gorman92df3a72011-10-31 17:07:56 -07002326 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002327 * If dirty pages are scanned that are not queued for IO, it
2328 * implies that flushers are not doing their job. This can
2329 * happen when memory pressure pushes dirty pages to the end of
2330 * the LRU before the dirty limits are breached and the dirty
2331 * data has expired. It can also happen when the proportion of
2332 * dirty pages grows not through writes but through memory
2333 * pressure reclaiming all the clean cache. And in some cases,
2334 * the flushers simply cannot keep up with the allocation
2335 * rate. Nudge the flusher threads in case they are asleep.
2336 */
2337 if (stat.nr_unqueued_dirty == nr_taken)
2338 wakeup_flusher_threads(WB_REASON_VMSCAN);
2339
Andrey Ryabinind108c772018-04-10 16:27:59 -07002340 sc->nr.dirty += stat.nr_dirty;
2341 sc->nr.congested += stat.nr_congested;
2342 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2343 sc->nr.writeback += stat.nr_writeback;
2344 sc->nr.immediate += stat.nr_immediate;
2345 sc->nr.taken += nr_taken;
2346 if (file)
2347 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002348
Mel Gorman599d0c92016-07-28 15:45:31 -07002349 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002350 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002351 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002352}
2353
Hugh Dickins15b44732020-12-15 14:21:31 -08002354/*
2355 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2356 *
2357 * We move them the other way if the page is referenced by one or more
2358 * processes.
2359 *
2360 * If the pages are mostly unmapped, the processing is fast and it is
2361 * appropriate to hold lru_lock across the whole operation. But if
2362 * the pages are mapped, the processing is slow (page_referenced()), so
2363 * we should drop lru_lock around each page. It's impossible to balance
2364 * this, so instead we remove the pages from the LRU while processing them.
2365 * It is safe to rely on PG_active against the non-LRU pages in here because
2366 * nobody will play with that bit on a non-LRU page.
2367 *
2368 * The downside is that we have to touch page->_refcount against each page.
2369 * But we had to alter page->flags anyway.
2370 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002371static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002372 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002373 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002374 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002375{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002376 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002377 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002378 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002379 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002380 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002381 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002382 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002383 unsigned nr_deactivate, nr_activate;
2384 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002385 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002386 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002387 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002388
2389 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002390
Alex Shi6168d0d2020-12-15 12:34:29 -08002391 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002392
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002393 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002394 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002395
Mel Gorman599d0c92016-07-28 15:45:31 -07002396 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002397
Shakeel Butt912c0572020-08-06 23:26:32 -07002398 if (!cgroup_reclaim(sc))
2399 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002400 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002401
Alex Shi6168d0d2020-12-15 12:34:29 -08002402 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002403
Linus Torvalds1da177e2005-04-16 15:20:36 -07002404 while (!list_empty(&l_hold)) {
2405 cond_resched();
2406 page = lru_to_page(&l_hold);
2407 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002408
Hugh Dickins39b5f292012-10-08 16:33:18 -07002409 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002410 putback_lru_page(page);
2411 continue;
2412 }
2413
Mel Gormancc715d92012-03-21 16:34:00 -07002414 if (unlikely(buffer_heads_over_limit)) {
2415 if (page_has_private(page) && trylock_page(page)) {
2416 if (page_has_private(page))
2417 try_to_release_page(page, 0);
2418 unlock_page(page);
2419 }
2420 }
2421
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002422 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2423 if (bypass)
2424 goto skip_page_referenced;
2425
Minchan Kimf74aca72022-05-19 14:08:54 -07002426 /* Referenced or rmap lock contention: rotate */
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002427 if (page_referenced(page, 0, sc->target_mem_cgroup,
Minchan Kimf74aca72022-05-19 14:08:54 -07002428 &vm_flags) != 0) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002429 /*
2430 * Identify referenced, file-backed active pages and
2431 * give them one more trip around the active list. So
2432 * that executable code get better chances to stay in
2433 * memory under moderate memory pressure. Anon pages
2434 * are not likely to be evicted by use-once streaming
2435 * IO, plus JVM can create lots of anon VM_EXEC pages,
2436 * so we ignore them here.
2437 */
Huang Ying9de4f222020-04-06 20:04:41 -07002438 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002439 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002440 list_add(&page->lru, &l_active);
2441 continue;
2442 }
2443 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002444skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002445 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002446 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002447 list_add(&page->lru, &l_inactive);
2448 }
2449
Andrew Mortonb5557492009-01-06 14:40:13 -08002450 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002451 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002452 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002453 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002454
Kirill Tkhaia222f342019-05-13 17:17:00 -07002455 nr_activate = move_pages_to_lru(lruvec, &l_active);
2456 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002457 /* Keep all free pages in l_active list */
2458 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002459
2460 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2461 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2462
Mel Gorman599d0c92016-07-28 15:45:31 -07002463 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002464 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002465
Kirill Tkhaif372d892019-05-13 17:16:57 -07002466 mem_cgroup_uncharge_list(&l_active);
2467 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002468 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2469 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002470}
2471
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002472unsigned long reclaim_pages(struct list_head *page_list)
2473{
Yang Shif661d002020-04-01 21:10:05 -07002474 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002475 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002476 LIST_HEAD(node_page_list);
2477 struct reclaim_stat dummy_stat;
2478 struct page *page;
Minchan Kim7df45e52022-10-27 08:29:17 -07002479 struct blk_plug plug;
2480 bool do_plug = false;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002481 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002482 struct scan_control sc = {
2483 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002484 .may_writepage = 1,
2485 .may_unmap = 1,
2486 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002487 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002488 };
2489
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002490 noreclaim_flag = memalloc_noreclaim_save();
2491
Minchan Kim7df45e52022-10-27 08:29:17 -07002492 trace_android_vh_reclaim_pages_plug(&do_plug);
2493 if (do_plug)
2494 blk_start_plug(&plug);
2495
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002496 while (!list_empty(page_list)) {
2497 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002498 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002499 nid = page_to_nid(page);
2500 INIT_LIST_HEAD(&node_page_list);
2501 }
2502
2503 if (nid == page_to_nid(page)) {
2504 ClearPageActive(page);
2505 list_move(&page->lru, &node_page_list);
2506 continue;
2507 }
2508
2509 nr_reclaimed += shrink_page_list(&node_page_list,
2510 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002511 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002512 while (!list_empty(&node_page_list)) {
2513 page = lru_to_page(&node_page_list);
2514 list_del(&page->lru);
2515 putback_lru_page(page);
2516 }
2517
Yang Shif661d002020-04-01 21:10:05 -07002518 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002519 }
2520
2521 if (!list_empty(&node_page_list)) {
2522 nr_reclaimed += shrink_page_list(&node_page_list,
2523 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002524 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002525 while (!list_empty(&node_page_list)) {
2526 page = lru_to_page(&node_page_list);
2527 list_del(&page->lru);
2528 putback_lru_page(page);
2529 }
2530 }
2531
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002532 memalloc_noreclaim_restore(noreclaim_flag);
2533
Minchan Kim7df45e52022-10-27 08:29:17 -07002534 if (do_plug)
2535 blk_finish_plug(&plug);
2536
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002537 return nr_reclaimed;
2538}
2539
Johannes Weinerb91ac372019-11-30 17:56:02 -08002540static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2541 struct lruvec *lruvec, struct scan_control *sc)
2542{
2543 if (is_active_lru(lru)) {
2544 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2545 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2546 else
2547 sc->skipped_deactivate = 1;
2548 return 0;
2549 }
2550
2551 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2552}
2553
Rik van Riel59dc76b2016-05-20 16:56:31 -07002554/*
2555 * The inactive anon list should be small enough that the VM never has
2556 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002557 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002558 * The inactive file list should be small enough to leave most memory
2559 * to the established workingset on the scan-resistant active list,
2560 * but large enough to avoid thrashing the aggregate readahead window.
2561 *
2562 * Both inactive lists should also be large enough that each inactive
2563 * page has a chance to be referenced again before it is reclaimed.
2564 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002565 * If that fails and refaulting is observed, the inactive list grows.
2566 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002567 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002568 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002569 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2570 *
2571 * total target max
2572 * memory ratio inactive
2573 * -------------------------------------
2574 * 10MB 1 5MB
2575 * 100MB 1 50MB
2576 * 1GB 3 250MB
2577 * 10GB 10 0.9GB
2578 * 100GB 31 3GB
2579 * 1TB 101 10GB
2580 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002581 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002582static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002583{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002584 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002585 unsigned long inactive, active;
2586 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002587 unsigned long gb;
2588
Johannes Weinerb91ac372019-11-30 17:56:02 -08002589 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2590 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002591
Johannes Weinerb91ac372019-11-30 17:56:02 -08002592 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002593 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002594 inactive_ratio = int_sqrt(10 * gb);
2595 else
2596 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002597
Rik van Riel59dc76b2016-05-20 16:56:31 -07002598 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002599}
2600
Johannes Weiner9a265112013-02-22 16:32:17 -08002601enum scan_balance {
2602 SCAN_EQUAL,
2603 SCAN_FRACT,
2604 SCAN_ANON,
2605 SCAN_FILE,
2606};
2607
Yu Zhao6d313442022-09-18 02:00:00 -06002608static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2609{
2610 unsigned long file;
2611 struct lruvec *target_lruvec;
2612
Yu Zhao37397872022-09-18 02:00:03 -06002613 if (lru_gen_enabled())
2614 return;
2615
Yu Zhao6d313442022-09-18 02:00:00 -06002616 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2617
2618 /*
2619 * Flush the memory cgroup stats, so that we read accurate per-memcg
2620 * lruvec stats for heuristics.
2621 */
2622 mem_cgroup_flush_stats();
2623
2624 /*
2625 * Determine the scan balance between anon and file LRUs.
2626 */
2627 spin_lock_irq(&target_lruvec->lru_lock);
2628 sc->anon_cost = target_lruvec->anon_cost;
2629 sc->file_cost = target_lruvec->file_cost;
2630 spin_unlock_irq(&target_lruvec->lru_lock);
2631
2632 /*
2633 * Target desirable inactive:active list ratios for the anon
2634 * and file LRU lists.
2635 */
2636 if (!sc->force_deactivate) {
2637 unsigned long refaults;
2638
2639 refaults = lruvec_page_state(target_lruvec,
2640 WORKINGSET_ACTIVATE_ANON);
2641 if (refaults != target_lruvec->refaults[0] ||
2642 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2643 sc->may_deactivate |= DEACTIVATE_ANON;
2644 else
2645 sc->may_deactivate &= ~DEACTIVATE_ANON;
2646
2647 /*
2648 * When refaults are being observed, it means a new
2649 * workingset is being established. Deactivate to get
2650 * rid of any stale active pages quickly.
2651 */
2652 refaults = lruvec_page_state(target_lruvec,
2653 WORKINGSET_ACTIVATE_FILE);
2654 if (refaults != target_lruvec->refaults[1] ||
2655 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2656 sc->may_deactivate |= DEACTIVATE_FILE;
2657 else
2658 sc->may_deactivate &= ~DEACTIVATE_FILE;
2659 } else
2660 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2661
2662 /*
2663 * If we have plenty of inactive file pages that aren't
2664 * thrashing, try to reclaim those first before touching
2665 * anonymous pages.
2666 */
2667 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2668 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2669 sc->cache_trim_mode = 1;
2670 else
2671 sc->cache_trim_mode = 0;
2672
2673 /*
2674 * Prevent the reclaimer from falling into the cache trap: as
2675 * cache pages start out inactive, every cache fault will tip
2676 * the scan balance towards the file LRU. And as the file LRU
2677 * shrinks, so does the window for rotation from references.
2678 * This means we have a runaway feedback loop where a tiny
2679 * thrashing file LRU becomes infinitely more attractive than
2680 * anon pages. Try to detect this based on file LRU size.
2681 */
2682 if (!cgroup_reclaim(sc)) {
2683 unsigned long total_high_wmark = 0;
2684 unsigned long free, anon;
2685 int z;
2686
2687 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2688 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2689 node_page_state(pgdat, NR_INACTIVE_FILE);
2690
2691 for (z = 0; z < MAX_NR_ZONES; z++) {
2692 struct zone *zone = &pgdat->node_zones[z];
2693
2694 if (!managed_zone(zone))
2695 continue;
2696
2697 total_high_wmark += high_wmark_pages(zone);
2698 }
2699
2700 /*
2701 * Consider anon: if that's low too, this isn't a
2702 * runaway file reclaim problem, but rather just
2703 * extreme pressure. Reclaim as per usual then.
2704 */
2705 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2706
2707 sc->file_is_tiny =
2708 file + free <= total_high_wmark &&
2709 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2710 anon >> sc->priority;
2711 }
2712}
2713
Linus Torvalds1da177e2005-04-16 15:20:36 -07002714/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002715 * Determine how aggressively the anon and file LRU lists should be
2716 * scanned. The relative value of each set of LRU lists is determined
2717 * by looking at the fraction of the pages scanned we did rotate back
2718 * onto the active list instead of evict.
2719 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002720 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2721 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002722 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002723static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2724 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002725{
Keith Buscha2a36482021-09-02 14:59:26 -07002726 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002727 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002728 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002729 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002730 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002731 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002732 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002733 unsigned long ap, fp;
2734 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002735 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002736
2737 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002738 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002739 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002740 goto out;
2741 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002742
Johannes Weiner10316b32013-02-22 16:32:14 -08002743 /*
2744 * Global reclaim will swap to prevent OOM even with no
2745 * swappiness, but memcg users want to use this knob to
2746 * disable swapping for individual groups completely when
2747 * using the memory controller's swap limit feature would be
2748 * too expensive.
2749 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002750 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002751 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002752 goto out;
2753 }
2754
2755 /*
2756 * Do not apply any pressure balancing cleverness when the
2757 * system is close to OOM, scan both anon and file equally
2758 * (unless the swappiness setting disagrees with swapping).
2759 */
Johannes Weiner02695172014-08-06 16:06:17 -07002760 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002761 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002762 goto out;
2763 }
2764
Johannes Weiner11d16c22013-02-22 16:32:15 -08002765 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002766 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002767 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002768 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002769 scan_balance = SCAN_ANON;
2770 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002771 }
2772
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002773 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2774
Johannes Weiner62376252014-05-06 12:50:07 -07002775 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002776 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002777 * anything from the anonymous working right now. But when balancing
2778 * anon and page cache files for reclaim, allow swapping of anon pages
2779 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002780 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002781 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002782 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002783 goto out;
2784 }
2785
Johannes Weiner9a265112013-02-22 16:32:17 -08002786 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002787 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002788 * Calculate the pressure balance between anon and file pages.
2789 *
2790 * The amount of pressure we put on each LRU is inversely
2791 * proportional to the cost of reclaiming each list, as
2792 * determined by the share of pages that are refaulting, times
2793 * the relative IO cost of bringing back a swapped out
2794 * anonymous page vs reloading a filesystem page (swappiness).
2795 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002796 * Although we limit that influence to ensure no list gets
2797 * left behind completely: at least a third of the pressure is
2798 * applied, before swappiness.
2799 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002800 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002801 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002802 total_cost = sc->anon_cost + sc->file_cost;
2803 anon_cost = total_cost + sc->anon_cost;
2804 file_cost = total_cost + sc->file_cost;
2805 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002806
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002807 ap = swappiness * (total_cost + 1);
2808 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002809
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002810 fp = (200 - swappiness) * (total_cost + 1);
2811 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002812
Shaohua Li76a33fc2010-05-24 14:32:36 -07002813 fraction[0] = ap;
2814 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002815 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002816out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002817 for_each_evictable_lru(lru) {
2818 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002819 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002820 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002821 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002822
Chris Down9783aa92019-10-06 17:58:32 -07002823 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002824 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2825 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002826
Johannes Weinerf56ce412021-08-19 19:04:21 -07002827 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002828 /*
2829 * Scale a cgroup's reclaim pressure by proportioning
2830 * its current usage to its memory.low or memory.min
2831 * setting.
2832 *
2833 * This is important, as otherwise scanning aggression
2834 * becomes extremely binary -- from nothing as we
2835 * approach the memory protection threshold, to totally
2836 * nominal as we exceed it. This results in requiring
2837 * setting extremely liberal protection thresholds. It
2838 * also means we simply get no protection at all if we
2839 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002840 *
2841 * If there is any protection in place, we reduce scan
2842 * pressure by how much of the total memory used is
2843 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002844 *
Chris Down9de7ca42019-10-06 17:58:35 -07002845 * There is one special case: in the first reclaim pass,
2846 * we skip over all groups that are within their low
2847 * protection. If that fails to reclaim enough pages to
2848 * satisfy the reclaim goal, we come back and override
2849 * the best-effort low protection. However, we still
2850 * ideally want to honor how well-behaved groups are in
2851 * that case instead of simply punishing them all
2852 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002853 * memory they are using, reducing the scan pressure
2854 * again by how much of the total memory used is under
2855 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002856 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002857 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002858 unsigned long protection;
2859
2860 /* memory.low scaling, make sure we retry before OOM */
2861 if (!sc->memcg_low_reclaim && low > min) {
2862 protection = low;
2863 sc->memcg_low_skipped = 1;
2864 } else {
2865 protection = min;
2866 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002867
2868 /* Avoid TOCTOU with earlier protection check */
2869 cgroup_size = max(cgroup_size, protection);
2870
2871 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002872 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002873
2874 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002875 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002876 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002877 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002878 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002879 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002880 } else {
2881 scan = lruvec_size;
2882 }
2883
2884 scan >>= sc->priority;
2885
Johannes Weiner688035f2017-05-03 14:52:07 -07002886 /*
2887 * If the cgroup's already been deleted, make sure to
2888 * scrape out the remaining cache.
2889 */
2890 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002891 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002892
Johannes Weiner688035f2017-05-03 14:52:07 -07002893 switch (scan_balance) {
2894 case SCAN_EQUAL:
2895 /* Scan lists relative to size */
2896 break;
2897 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002898 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002899 * Scan types proportional to swappiness and
2900 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002901 * Make sure we don't miss the last page on
2902 * the offlined memory cgroups because of a
2903 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002904 */
Gavin Shan76073c62020-02-20 20:04:24 -08002905 scan = mem_cgroup_online(memcg) ?
2906 div64_u64(scan * fraction[file], denominator) :
2907 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002908 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002909 break;
2910 case SCAN_FILE:
2911 case SCAN_ANON:
2912 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002913 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002914 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002915 break;
2916 default:
2917 /* Look ma, no brain */
2918 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002919 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002920
Johannes Weiner688035f2017-05-03 14:52:07 -07002921 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002922 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002923}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002924
Dave Hansen2f368a92021-09-02 14:59:23 -07002925/*
2926 * Anonymous LRU management is a waste if there is
2927 * ultimately no way to reclaim the memory.
2928 */
2929static bool can_age_anon_pages(struct pglist_data *pgdat,
2930 struct scan_control *sc)
2931{
2932 /* Aging the anon LRU is valuable if swap is present: */
2933 if (total_swap_pages > 0)
2934 return true;
2935
2936 /* Also valuable if anon pages can be demoted: */
2937 return can_demote(pgdat->node_id, sc);
2938}
2939
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002940#ifdef CONFIG_LRU_GEN
2941
Yu Zhaobaeb9a02022-09-18 02:00:07 -06002942#ifdef CONFIG_LRU_GEN_ENABLED
2943DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2944#define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2945#else
2946DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2947#define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2948#endif
2949
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002950/******************************************************************************
2951 * shorthand helpers
2952 ******************************************************************************/
2953
Yu Zhao37397872022-09-18 02:00:03 -06002954#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2955
2956#define DEFINE_MAX_SEQ(lruvec) \
2957 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2958
2959#define DEFINE_MIN_SEQ(lruvec) \
2960 unsigned long min_seq[ANON_AND_FILE] = { \
2961 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2962 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2963 }
2964
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002965#define for_each_gen_type_zone(gen, type, zone) \
2966 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2967 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2968 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2969
Yu Zhaoa3eb6512022-12-21 21:19:04 -07002970#define get_memcg_gen(seq) ((seq) % MEMCG_NR_GENS)
2971#define get_memcg_bin(bin) ((bin) % MEMCG_NR_BINS)
2972
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002973static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002974{
2975 struct pglist_data *pgdat = NODE_DATA(nid);
2976
2977#ifdef CONFIG_MEMCG
2978 if (memcg) {
2979 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2980
2981 /* for hotadd_new_pgdat() */
2982 if (!lruvec->pgdat)
2983 lruvec->pgdat = pgdat;
2984
2985 return lruvec;
2986 }
2987#endif
2988 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2989
2990 return pgdat ? &pgdat->__lruvec : NULL;
2991}
2992
Yu Zhao37397872022-09-18 02:00:03 -06002993static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2994{
2995 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2996 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2997
Yu Zhaof8b57162022-12-21 21:19:05 -07002998 if (!sc->may_swap)
2999 return 0;
3000
Kalesh Singhb8d031e2023-04-03 15:28:17 -07003001 if (!can_demote(pgdat->node_id, sc) &&
3002 mem_cgroup_get_nr_swap_pages(memcg) <= 0)
Yu Zhao37397872022-09-18 02:00:03 -06003003 return 0;
3004
3005 return mem_cgroup_swappiness(memcg);
3006}
3007
3008static int get_nr_gens(struct lruvec *lruvec, int type)
3009{
3010 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3011}
3012
3013static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3014{
Yu Zhao3c6c3592022-12-21 21:18:59 -07003015 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06003016 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3017 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3018 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3019}
3020
3021/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003022 * mm_struct list
3023 ******************************************************************************/
3024
3025static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3026{
3027 static struct lru_gen_mm_list mm_list = {
3028 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3029 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3030 };
3031
3032#ifdef CONFIG_MEMCG
3033 if (memcg)
3034 return &memcg->mm_list;
3035#endif
3036 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3037
3038 return &mm_list;
3039}
3040
3041void lru_gen_add_mm(struct mm_struct *mm)
3042{
3043 int nid;
3044 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3045 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3046
3047 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3048#ifdef CONFIG_MEMCG
3049 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3050 mm->lru_gen.memcg = memcg;
3051#endif
3052 spin_lock(&mm_list->lock);
3053
3054 for_each_node_state(nid, N_MEMORY) {
3055 struct lruvec *lruvec = get_lruvec(memcg, nid);
3056
3057 if (!lruvec)
3058 continue;
3059
3060 /* the first addition since the last iteration */
3061 if (lruvec->mm_state.tail == &mm_list->fifo)
3062 lruvec->mm_state.tail = &mm->lru_gen.list;
3063 }
3064
3065 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3066
3067 spin_unlock(&mm_list->lock);
3068}
3069
3070void lru_gen_del_mm(struct mm_struct *mm)
3071{
3072 int nid;
3073 struct lru_gen_mm_list *mm_list;
3074 struct mem_cgroup *memcg = NULL;
3075
3076 if (list_empty(&mm->lru_gen.list))
3077 return;
3078
3079#ifdef CONFIG_MEMCG
3080 memcg = mm->lru_gen.memcg;
3081#endif
3082 mm_list = get_mm_list(memcg);
3083
3084 spin_lock(&mm_list->lock);
3085
3086 for_each_node(nid) {
3087 struct lruvec *lruvec = get_lruvec(memcg, nid);
3088
3089 if (!lruvec)
3090 continue;
3091
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003092 /* where the current iteration continues after */
3093 if (lruvec->mm_state.head == &mm->lru_gen.list)
3094 lruvec->mm_state.head = lruvec->mm_state.head->prev;
3095
3096 /* where the last iteration ended before */
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003097 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3098 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003099 }
3100
3101 list_del_init(&mm->lru_gen.list);
3102
3103 spin_unlock(&mm_list->lock);
3104
3105#ifdef CONFIG_MEMCG
3106 mem_cgroup_put(mm->lru_gen.memcg);
3107 mm->lru_gen.memcg = NULL;
3108#endif
3109}
3110
3111#ifdef CONFIG_MEMCG
3112void lru_gen_migrate_mm(struct mm_struct *mm)
3113{
3114 struct mem_cgroup *memcg;
3115 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3116
3117 VM_WARN_ON_ONCE(task->mm != mm);
3118 lockdep_assert_held(&task->alloc_lock);
3119
3120 /* for mm_update_next_owner() */
3121 if (mem_cgroup_disabled())
3122 return;
3123
Yu Zhao578a3a32023-01-15 20:44:05 -07003124 /* migration can happen before addition */
3125 if (!mm->lru_gen.memcg)
3126 return;
3127
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003128 rcu_read_lock();
3129 memcg = mem_cgroup_from_task(task);
3130 rcu_read_unlock();
3131 if (memcg == mm->lru_gen.memcg)
3132 return;
3133
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003134 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3135
3136 lru_gen_del_mm(mm);
3137 lru_gen_add_mm(mm);
3138}
3139#endif
3140
3141/*
3142 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3143 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3144 * bits in a bitmap, k is the number of hash functions and n is the number of
3145 * inserted items.
3146 *
3147 * Page table walkers use one of the two filters to reduce their search space.
3148 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3149 * aging uses the double-buffering technique to flip to the other filter each
3150 * time it produces a new generation. For non-leaf entries that have enough
3151 * leaf entries, the aging carries them over to the next generation in
3152 * walk_pmd_range(); the eviction also report them when walking the rmap
3153 * in lru_gen_look_around().
3154 *
3155 * For future optimizations:
3156 * 1. It's not necessary to keep both filters all the time. The spare one can be
3157 * freed after the RCU grace period and reallocated if needed again.
3158 * 2. And when reallocating, it's worth scaling its size according to the number
3159 * of inserted entries in the other filter, to reduce the memory overhead on
3160 * small systems and false positives on large systems.
3161 * 3. Jenkins' hash function is an alternative to Knuth's.
3162 */
3163#define BLOOM_FILTER_SHIFT 15
3164
3165static inline int filter_gen_from_seq(unsigned long seq)
3166{
3167 return seq % NR_BLOOM_FILTERS;
3168}
3169
3170static void get_item_key(void *item, int *key)
3171{
3172 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3173
3174 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3175
3176 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3177 key[1] = hash >> BLOOM_FILTER_SHIFT;
3178}
3179
3180static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3181{
3182 unsigned long *filter;
3183 int gen = filter_gen_from_seq(seq);
3184
3185 filter = lruvec->mm_state.filters[gen];
3186 if (filter) {
3187 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3188 return;
3189 }
3190
3191 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3192 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3193 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3194}
3195
3196static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3197{
3198 int key[2];
3199 unsigned long *filter;
3200 int gen = filter_gen_from_seq(seq);
3201
3202 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3203 if (!filter)
3204 return;
3205
3206 get_item_key(item, key);
3207
3208 if (!test_bit(key[0], filter))
3209 set_bit(key[0], filter);
3210 if (!test_bit(key[1], filter))
3211 set_bit(key[1], filter);
3212}
3213
3214static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3215{
3216 int key[2];
3217 unsigned long *filter;
3218 int gen = filter_gen_from_seq(seq);
3219
3220 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3221 if (!filter)
3222 return true;
3223
3224 get_item_key(item, key);
3225
3226 return test_bit(key[0], filter) && test_bit(key[1], filter);
3227}
3228
3229static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3230{
3231 int i;
3232 int hist;
3233
3234 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3235
3236 if (walk) {
3237 hist = lru_hist_from_seq(walk->max_seq);
3238
3239 for (i = 0; i < NR_MM_STATS; i++) {
3240 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3241 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3242 walk->mm_stats[i] = 0;
3243 }
3244 }
3245
3246 if (NR_HIST_GENS > 1 && last) {
3247 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3248
3249 for (i = 0; i < NR_MM_STATS; i++)
3250 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3251 }
3252}
3253
3254static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3255{
3256 int type;
3257 unsigned long size = 0;
3258 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3259 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3260
3261 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3262 return true;
3263
3264 clear_bit(key, &mm->lru_gen.bitmap);
3265
3266 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3267 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3268 get_mm_counter(mm, MM_ANONPAGES) +
3269 get_mm_counter(mm, MM_SHMEMPAGES);
3270 }
3271
3272 if (size < MIN_LRU_BATCH)
3273 return true;
3274
3275 return !mmget_not_zero(mm);
3276}
3277
3278static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3279 struct mm_struct **iter)
3280{
3281 bool first = false;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003282 bool last = false;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003283 struct mm_struct *mm = NULL;
3284 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3285 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3286 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3287
3288 /*
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003289 * mm_state->seq is incremented after each iteration of mm_list. There
3290 * are three interesting cases for this page table walker:
3291 * 1. It tries to start a new iteration with a stale max_seq: there is
3292 * nothing left to do.
3293 * 2. It started the next iteration: it needs to reset the Bloom filter
3294 * so that a fresh set of PTE tables can be recorded.
3295 * 3. It ended the current iteration: it needs to reset the mm stats
3296 * counters and tell its caller to increment max_seq.
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003297 */
3298 spin_lock(&mm_list->lock);
3299
3300 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003301
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003302 if (walk->max_seq <= mm_state->seq)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003303 goto done;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003304
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003305 if (!mm_state->head)
3306 mm_state->head = &mm_list->fifo;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003307
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003308 if (mm_state->head == &mm_list->fifo)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003309 first = true;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003310
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003311 do {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003312 mm_state->head = mm_state->head->next;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003313 if (mm_state->head == &mm_list->fifo) {
3314 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3315 last = true;
3316 break;
3317 }
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003318
3319 /* force scan for those added after the last iteration */
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003320 if (!mm_state->tail || mm_state->tail == mm_state->head) {
3321 mm_state->tail = mm_state->head->next;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003322 walk->force_scan = true;
3323 }
3324
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003325 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003326 if (should_skip_mm(mm, walk))
3327 mm = NULL;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003328 } while (!mm);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003329done:
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003330 if (*iter || last)
3331 reset_mm_stats(lruvec, walk, last);
3332
3333 spin_unlock(&mm_list->lock);
3334
3335 if (mm && first)
3336 reset_bloom_filter(lruvec, walk->max_seq + 1);
3337
3338 if (*iter)
3339 mmput_async(*iter);
3340
3341 *iter = mm;
3342
3343 return last;
3344}
3345
3346static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3347{
3348 bool success = false;
3349 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3350 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3351 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3352
3353 spin_lock(&mm_list->lock);
3354
3355 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3356
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003357 if (max_seq > mm_state->seq) {
3358 mm_state->head = NULL;
3359 mm_state->tail = NULL;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003360 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3361 reset_mm_stats(lruvec, NULL, true);
3362 success = true;
3363 }
3364
3365 spin_unlock(&mm_list->lock);
3366
3367 return success;
3368}
3369
3370/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003371 * refault feedback loop
3372 ******************************************************************************/
3373
3374/*
3375 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3376 *
3377 * The P term is refaulted/(evicted+protected) from a tier in the generation
3378 * currently being evicted; the I term is the exponential moving average of the
3379 * P term over the generations previously evicted, using the smoothing factor
3380 * 1/2; the D term isn't supported.
3381 *
3382 * The setpoint (SP) is always the first tier of one type; the process variable
3383 * (PV) is either any tier of the other type or any other tier of the same
3384 * type.
3385 *
3386 * The error is the difference between the SP and the PV; the correction is to
3387 * turn off protection when SP>PV or turn on protection when SP<PV.
3388 *
3389 * For future optimizations:
3390 * 1. The D term may discount the other two terms over time so that long-lived
3391 * generations can resist stale information.
3392 */
3393struct ctrl_pos {
3394 unsigned long refaulted;
3395 unsigned long total;
3396 int gain;
3397};
3398
3399static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3400 struct ctrl_pos *pos)
3401{
Yu Zhao3c6c3592022-12-21 21:18:59 -07003402 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003403 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3404
3405 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3406 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3407 pos->total = lrugen->avg_total[type][tier] +
3408 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3409 if (tier)
3410 pos->total += lrugen->protected[hist][type][tier - 1];
3411 pos->gain = gain;
3412}
3413
3414static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3415{
3416 int hist, tier;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003417 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003418 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3419 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3420
3421 lockdep_assert_held(&lruvec->lru_lock);
3422
3423 if (!carryover && !clear)
3424 return;
3425
3426 hist = lru_hist_from_seq(seq);
3427
3428 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3429 if (carryover) {
3430 unsigned long sum;
3431
3432 sum = lrugen->avg_refaulted[type][tier] +
3433 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3434 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3435
3436 sum = lrugen->avg_total[type][tier] +
3437 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3438 if (tier)
3439 sum += lrugen->protected[hist][type][tier - 1];
3440 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3441 }
3442
3443 if (clear) {
3444 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3445 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3446 if (tier)
3447 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3448 }
3449 }
3450}
3451
3452static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3453{
3454 /*
3455 * Return true if the PV has a limited number of refaults or a lower
3456 * refaulted/total than the SP.
3457 */
3458 return pv->refaulted < MIN_LRU_BATCH ||
3459 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3460 (sp->refaulted + 1) * pv->total * pv->gain;
3461}
3462
3463/******************************************************************************
3464 * the aging
3465 ******************************************************************************/
3466
Yu Zhao0182f922022-09-18 02:00:04 -06003467/* promote pages accessed through page tables */
3468static int page_update_gen(struct page *page, int gen)
3469{
3470 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3471
3472 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3473 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3474
3475 do {
3476 /* lru_gen_del_page() has isolated this page? */
3477 if (!(old_flags & LRU_GEN_MASK)) {
3478 /* for shrink_page_list() */
3479 new_flags = old_flags | BIT(PG_referenced);
3480 continue;
3481 }
3482
3483 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3484 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3485 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3486
3487 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3488}
3489
Yu Zhao37397872022-09-18 02:00:03 -06003490/* protect pages accessed multiple times through file descriptors */
3491static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3492{
3493 int type = page_is_file_lru(page);
Yu Zhao3c6c3592022-12-21 21:18:59 -07003494 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003495 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3496 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3497
3498 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3499
3500 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003501 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3502 /* page_update_gen() has promoted this page? */
3503 if (new_gen >= 0 && new_gen != old_gen)
3504 return new_gen;
3505
Yu Zhao37397872022-09-18 02:00:03 -06003506 new_gen = (old_gen + 1) % MAX_NR_GENS;
3507
3508 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3509 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3510 /* for end_page_writeback() */
3511 if (reclaiming)
3512 new_flags |= BIT(PG_reclaim);
3513 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3514
3515 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3516
3517 return new_gen;
3518}
3519
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003520static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3521 int old_gen, int new_gen)
3522{
3523 int type = page_is_file_lru(page);
3524 int zone = page_zonenum(page);
3525 int delta = thp_nr_pages(page);
3526
3527 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3528 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3529
3530 walk->batched++;
3531
3532 walk->nr_pages[old_gen][type][zone] -= delta;
3533 walk->nr_pages[new_gen][type][zone] += delta;
3534}
3535
3536static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3537{
3538 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003539 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003540
3541 walk->batched = 0;
3542
3543 for_each_gen_type_zone(gen, type, zone) {
3544 enum lru_list lru = type * LRU_INACTIVE_FILE;
3545 int delta = walk->nr_pages[gen][type][zone];
3546
3547 if (!delta)
3548 continue;
3549
3550 walk->nr_pages[gen][type][zone] = 0;
3551 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3552 lrugen->nr_pages[gen][type][zone] + delta);
3553
3554 if (lru_gen_is_active(lruvec, gen))
3555 lru += LRU_ACTIVE;
3556 __update_lru_size(lruvec, lru, zone, delta);
3557 }
3558}
3559
3560static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3561{
3562 struct address_space *mapping;
3563 struct vm_area_struct *vma = args->vma;
3564 struct lru_gen_mm_walk *walk = args->private;
3565
3566 if (!vma_is_accessible(vma))
3567 return true;
3568
3569 if (is_vm_hugetlb_page(vma))
3570 return true;
3571
Yu Zhao3b9ab092022-12-30 14:52:51 -07003572 if (!vma_has_recency(vma))
3573 return true;
3574
3575 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003576 return true;
3577
3578 if (vma == get_gate_vma(vma->vm_mm))
3579 return true;
3580
3581 if (vma_is_anonymous(vma))
3582 return !walk->can_swap;
3583
3584 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3585 return true;
3586
3587 mapping = vma->vm_file->f_mapping;
3588 if (mapping_unevictable(mapping))
3589 return true;
3590
3591 if (shmem_mapping(mapping))
3592 return !walk->can_swap;
3593
3594 /* to exclude special mappings like dax, etc. */
3595 return !mapping->a_ops->readpage;
3596}
3597
3598/*
3599 * Some userspace memory allocators map many single-page VMAs. Instead of
3600 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3601 * table to reduce zigzags and improve cache performance.
3602 */
3603static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3604 unsigned long *vm_start, unsigned long *vm_end)
3605{
3606 unsigned long start = round_up(*vm_end, size);
3607 unsigned long end = (start | ~mask) + 1;
3608
3609 VM_WARN_ON_ONCE(mask & size);
3610 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3611
3612 while (args->vma) {
3613 if (start >= args->vma->vm_end) {
3614 args->vma = args->vma->vm_next;
3615 continue;
3616 }
3617
3618 if (end && end <= args->vma->vm_start)
3619 return false;
3620
3621 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3622 args->vma = args->vma->vm_next;
3623 continue;
3624 }
3625
3626 *vm_start = max(start, args->vma->vm_start);
3627 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3628
3629 return true;
3630 }
3631
3632 return false;
3633}
3634
Yu Zhao0182f922022-09-18 02:00:04 -06003635static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3636{
3637 unsigned long pfn = pte_pfn(pte);
3638
3639 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3640
3641 if (!pte_present(pte) || is_zero_pfn(pfn))
3642 return -1;
3643
3644 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3645 return -1;
3646
3647 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3648 return -1;
3649
3650 return pfn;
3651}
3652
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003653#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3654static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3655{
3656 unsigned long pfn = pmd_pfn(pmd);
3657
3658 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3659
3660 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3661 return -1;
3662
3663 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3664 return -1;
3665
3666 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3667 return -1;
3668
3669 return pfn;
3670}
3671#endif
3672
Yu Zhao0182f922022-09-18 02:00:04 -06003673static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003674 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003675{
3676 struct page *page;
3677
3678 /* try to avoid unnecessary memory loads */
3679 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3680 return NULL;
3681
3682 page = compound_head(pfn_to_page(pfn));
3683 if (page_to_nid(page) != pgdat->node_id)
3684 return NULL;
3685
3686 if (page_memcg_rcu(page) != memcg)
3687 return NULL;
3688
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003689 /* file VMAs can contain anon pages from COW */
3690 if (!page_is_file_lru(page) && !can_swap)
3691 return NULL;
3692
Yu Zhao0182f922022-09-18 02:00:04 -06003693 return page;
3694}
3695
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003696static bool suitable_to_scan(int total, int young)
3697{
3698 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3699
3700 /* suitable if the average number of young PTEs per cacheline is >=1 */
3701 return young * n >= total;
3702}
3703
3704static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3705 struct mm_walk *args)
3706{
3707 int i;
3708 pte_t *pte;
3709 spinlock_t *ptl;
3710 unsigned long addr;
3711 int total = 0;
3712 int young = 0;
3713 struct lru_gen_mm_walk *walk = args->private;
3714 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3715 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3716 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3717
3718 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3719
3720 ptl = pte_lockptr(args->mm, pmd);
3721 if (!spin_trylock(ptl))
3722 return false;
3723
3724 arch_enter_lazy_mmu_mode();
3725
3726 pte = pte_offset_map(pmd, start & PMD_MASK);
3727restart:
3728 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3729 unsigned long pfn;
3730 struct page *page;
3731
3732 total++;
3733 walk->mm_stats[MM_LEAF_TOTAL]++;
3734
3735 pfn = get_pte_pfn(pte[i], args->vma, addr);
3736 if (pfn == -1)
3737 continue;
3738
3739 if (!pte_young(pte[i])) {
3740 walk->mm_stats[MM_LEAF_OLD]++;
3741 continue;
3742 }
3743
3744 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3745 if (!page)
3746 continue;
3747
3748 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3749 VM_WARN_ON_ONCE(true);
3750
3751 young++;
3752 walk->mm_stats[MM_LEAF_YOUNG]++;
3753
3754 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3755 !(PageAnon(page) && PageSwapBacked(page) &&
3756 !PageSwapCache(page)))
3757 set_page_dirty(page);
3758
3759 old_gen = page_update_gen(page, new_gen);
3760 if (old_gen >= 0 && old_gen != new_gen)
3761 update_batch_size(walk, page, old_gen, new_gen);
3762 }
3763
3764 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3765 goto restart;
3766
3767 pte_unmap(pte);
3768
3769 arch_leave_lazy_mmu_mode();
3770 spin_unlock(ptl);
3771
3772 return suitable_to_scan(total, young);
3773}
3774
3775#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3776static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3777 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3778{
3779 int i;
3780 pmd_t *pmd;
3781 spinlock_t *ptl;
3782 struct lru_gen_mm_walk *walk = args->private;
3783 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3784 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3785 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3786
3787 VM_WARN_ON_ONCE(pud_leaf(*pud));
3788
3789 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3790 if (*start == -1) {
3791 *start = next;
3792 return;
3793 }
3794
3795 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3796 if (i && i <= MIN_LRU_BATCH) {
3797 __set_bit(i - 1, bitmap);
3798 return;
3799 }
3800
3801 pmd = pmd_offset(pud, *start);
3802
3803 ptl = pmd_lockptr(args->mm, pmd);
3804 if (!spin_trylock(ptl))
3805 goto done;
3806
3807 arch_enter_lazy_mmu_mode();
3808
3809 do {
3810 unsigned long pfn;
3811 struct page *page;
3812 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3813
3814 pfn = get_pmd_pfn(pmd[i], vma, addr);
3815 if (pfn == -1)
3816 goto next;
3817
3818 if (!pmd_trans_huge(pmd[i])) {
Juergen Gross23811792022-11-23 07:45:10 +01003819 if (arch_has_hw_nonleaf_pmd_young() &&
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003820 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003821 pmdp_test_and_clear_young(vma, addr, pmd + i);
3822 goto next;
3823 }
3824
3825 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3826 if (!page)
3827 goto next;
3828
3829 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3830 goto next;
3831
3832 walk->mm_stats[MM_LEAF_YOUNG]++;
3833
3834 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3835 !(PageAnon(page) && PageSwapBacked(page) &&
3836 !PageSwapCache(page)))
3837 set_page_dirty(page);
3838
3839 old_gen = page_update_gen(page, new_gen);
3840 if (old_gen >= 0 && old_gen != new_gen)
3841 update_batch_size(walk, page, old_gen, new_gen);
3842next:
3843 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3844 } while (i <= MIN_LRU_BATCH);
3845
3846 arch_leave_lazy_mmu_mode();
3847 spin_unlock(ptl);
3848done:
3849 *start = -1;
3850 bitmap_zero(bitmap, MIN_LRU_BATCH);
3851}
3852#else
3853static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3854 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3855{
3856}
3857#endif
3858
3859static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3860 struct mm_walk *args)
3861{
3862 int i;
3863 pmd_t *pmd;
3864 unsigned long next;
3865 unsigned long addr;
3866 struct vm_area_struct *vma;
3867 unsigned long pos = -1;
3868 struct lru_gen_mm_walk *walk = args->private;
3869 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3870
3871 VM_WARN_ON_ONCE(pud_leaf(*pud));
3872
3873 /*
3874 * Finish an entire PMD in two passes: the first only reaches to PTE
3875 * tables to avoid taking the PMD lock; the second, if necessary, takes
3876 * the PMD lock to clear the accessed bit in PMD entries.
3877 */
3878 pmd = pmd_offset(pud, start & PUD_MASK);
3879restart:
3880 /* walk_pte_range() may call get_next_vma() */
3881 vma = args->vma;
3882 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3883 pmd_t val = pmd_read_atomic(pmd + i);
3884
3885 /* for pmd_read_atomic() */
3886 barrier();
3887
3888 next = pmd_addr_end(addr, end);
3889
3890 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3891 walk->mm_stats[MM_LEAF_TOTAL]++;
3892 continue;
3893 }
3894
3895#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3896 if (pmd_trans_huge(val)) {
3897 unsigned long pfn = pmd_pfn(val);
3898 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3899
3900 walk->mm_stats[MM_LEAF_TOTAL]++;
3901
3902 if (!pmd_young(val)) {
3903 walk->mm_stats[MM_LEAF_OLD]++;
3904 continue;
3905 }
3906
3907 /* try to avoid unnecessary memory loads */
3908 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3909 continue;
3910
3911 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3912 continue;
3913 }
3914#endif
3915 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3916
Juergen Gross23811792022-11-23 07:45:10 +01003917 if (arch_has_hw_nonleaf_pmd_young() &&
3918 get_cap(LRU_GEN_NONLEAF_YOUNG)) {
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003919 if (!pmd_young(val))
3920 continue;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003921
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003922 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3923 }
Juergen Gross23811792022-11-23 07:45:10 +01003924
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003925 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3926 continue;
3927
3928 walk->mm_stats[MM_NONLEAF_FOUND]++;
3929
3930 if (!walk_pte_range(&val, addr, next, args))
3931 continue;
3932
3933 walk->mm_stats[MM_NONLEAF_ADDED]++;
3934
3935 /* carry over to the next generation */
3936 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3937 }
3938
3939 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3940
3941 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3942 goto restart;
3943}
3944
3945static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3946 struct mm_walk *args)
3947{
3948 int i;
3949 pud_t *pud;
3950 unsigned long addr;
3951 unsigned long next;
3952 struct lru_gen_mm_walk *walk = args->private;
3953
3954 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3955
3956 pud = pud_offset(p4d, start & P4D_MASK);
3957restart:
3958 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3959 pud_t val = READ_ONCE(pud[i]);
3960
3961 next = pud_addr_end(addr, end);
3962
3963 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3964 continue;
3965
3966 walk_pmd_range(&val, addr, next, args);
3967
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003968 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3969 end = (addr | ~PUD_MASK) + 1;
3970 goto done;
3971 }
3972 }
3973
3974 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3975 goto restart;
3976
3977 end = round_up(end, P4D_SIZE);
3978done:
3979 if (!end || !args->vma)
3980 return 1;
3981
3982 walk->next_addr = max(end, args->vma->vm_start);
3983
3984 return -EAGAIN;
3985}
3986
3987static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3988{
3989 static const struct mm_walk_ops mm_walk_ops = {
3990 .test_walk = should_skip_vma,
3991 .p4d_entry = walk_pud_range,
3992 };
3993
3994 int err;
3995 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3996
3997 walk->next_addr = FIRST_USER_ADDRESS;
3998
3999 do {
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004000 DEFINE_MAX_SEQ(lruvec);
4001
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004002 err = -EBUSY;
4003
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004004 /* another thread might have called inc_max_seq() */
4005 if (walk->max_seq != max_seq)
4006 break;
4007
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004008 /* page_update_gen() requires stable page_memcg() */
4009 if (!mem_cgroup_trylock_pages(memcg))
4010 break;
4011
4012 /* the caller might be holding the lock for write */
4013 if (mmap_read_trylock(mm)) {
4014 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
4015
4016 mmap_read_unlock(mm);
4017 }
4018
4019 mem_cgroup_unlock_pages();
4020
4021 if (walk->batched) {
4022 spin_lock_irq(&lruvec->lru_lock);
4023 reset_batch_size(lruvec, walk);
4024 spin_unlock_irq(&lruvec->lru_lock);
4025 }
4026
4027 cond_resched();
4028 } while (err == -EAGAIN);
4029}
4030
Yu Zhaof8b57162022-12-21 21:19:05 -07004031static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004032{
4033 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4034
4035 if (pgdat && current_is_kswapd()) {
4036 VM_WARN_ON_ONCE(walk);
4037
4038 walk = &pgdat->mm_walk;
Yu Zhaof8b57162022-12-21 21:19:05 -07004039 } else if (!walk && force_alloc) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004040 VM_WARN_ON_ONCE(current_is_kswapd());
4041
4042 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4043 }
4044
4045 current->reclaim_state->mm_walk = walk;
4046
4047 return walk;
4048}
4049
4050static void clear_mm_walk(void)
4051{
4052 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4053
4054 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4055 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4056
4057 current->reclaim_state->mm_walk = NULL;
4058
4059 if (!current_is_kswapd())
4060 kfree(walk);
4061}
4062
Yu Zhao4983c522022-09-18 02:00:09 -06004063static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004064{
Yu Zhao4983c522022-09-18 02:00:09 -06004065 int zone;
4066 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004067 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06004068 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
Yu Zhao37397872022-09-18 02:00:03 -06004069
Yu Zhao4983c522022-09-18 02:00:09 -06004070 if (type == LRU_GEN_ANON && !can_swap)
4071 goto done;
4072
4073 /* prevent cold/hot inversion if force_scan is true */
4074 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004075 struct list_head *head = &lrugen->pages[old_gen][type][zone];
Yu Zhao4983c522022-09-18 02:00:09 -06004076
4077 while (!list_empty(head)) {
4078 struct page *page = lru_to_page(head);
4079
4080 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4081 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4082 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4083 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4084
4085 new_gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004086 list_move_tail(&page->lru, &lrugen->pages[new_gen][type][zone]);
Yu Zhao4983c522022-09-18 02:00:09 -06004087
4088 if (!--remaining)
4089 return false;
4090 }
4091 }
4092done:
Yu Zhao37397872022-09-18 02:00:03 -06004093 reset_ctrl_pos(lruvec, type, true);
4094 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
Yu Zhao4983c522022-09-18 02:00:09 -06004095
4096 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004097}
4098
4099static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4100{
4101 int gen, type, zone;
4102 bool success = false;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004103 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004104 DEFINE_MIN_SEQ(lruvec);
4105
4106 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4107
4108 /* find the oldest populated generation */
4109 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4110 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4111 gen = lru_gen_from_seq(min_seq[type]);
4112
4113 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004114 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhao37397872022-09-18 02:00:03 -06004115 goto next;
4116 }
4117
4118 min_seq[type]++;
4119 }
4120next:
4121 ;
4122 }
4123
Yu Zhao3c6c3592022-12-21 21:18:59 -07004124 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06004125 if (can_swap) {
4126 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4127 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4128 }
4129
4130 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4131 if (min_seq[type] == lrugen->min_seq[type])
4132 continue;
4133
4134 reset_ctrl_pos(lruvec, type, true);
4135 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4136 success = true;
4137 }
4138
4139 return success;
4140}
4141
Yu Zhao4983c522022-09-18 02:00:09 -06004142static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
Yu Zhao37397872022-09-18 02:00:03 -06004143{
4144 int prev, next;
4145 int type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004146 struct lru_gen_page *lrugen = &lruvec->lrugen;
Kalesh Singh12fb1c32023-08-01 19:56:03 -07004147restart:
Yu Zhao37397872022-09-18 02:00:03 -06004148 spin_lock_irq(&lruvec->lru_lock);
4149
4150 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4151
Yu Zhao37397872022-09-18 02:00:03 -06004152 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4153 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4154 continue;
4155
Yu Zhao4983c522022-09-18 02:00:09 -06004156 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
Yu Zhao37397872022-09-18 02:00:03 -06004157
Kalesh Singh12fb1c32023-08-01 19:56:03 -07004158 if (inc_min_seq(lruvec, type, can_swap))
4159 continue;
4160
4161 spin_unlock_irq(&lruvec->lru_lock);
4162 cond_resched();
4163 goto restart;
Yu Zhao37397872022-09-18 02:00:03 -06004164 }
4165
4166 /*
4167 * Update the active/inactive LRU sizes for compatibility. Both sides of
4168 * the current max_seq need to be covered, since max_seq+1 can overlap
4169 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4170 * overlap, cold/hot inversion happens.
4171 */
4172 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4173 next = lru_gen_from_seq(lrugen->max_seq + 1);
4174
4175 for (type = 0; type < ANON_AND_FILE; type++) {
4176 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4177 enum lru_list lru = type * LRU_INACTIVE_FILE;
4178 long delta = lrugen->nr_pages[prev][type][zone] -
4179 lrugen->nr_pages[next][type][zone];
4180
4181 if (!delta)
4182 continue;
4183
4184 __update_lru_size(lruvec, lru, zone, delta);
4185 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4186 }
4187 }
4188
4189 for (type = 0; type < ANON_AND_FILE; type++)
4190 reset_ctrl_pos(lruvec, type, false);
4191
Yu Zhao430499c2022-09-18 02:00:08 -06004192 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhao37397872022-09-18 02:00:03 -06004193 /* make sure preceding modifications appear */
4194 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004195
Yu Zhao37397872022-09-18 02:00:03 -06004196 spin_unlock_irq(&lruvec->lru_lock);
4197}
4198
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004199static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
Yu Zhao4983c522022-09-18 02:00:09 -06004200 struct scan_control *sc, bool can_swap, bool force_scan)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004201{
4202 bool success;
4203 struct lru_gen_mm_walk *walk;
4204 struct mm_struct *mm = NULL;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004205 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004206
4207 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4208
4209 /* see the comment in iterate_mm_list() */
4210 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4211 success = false;
4212 goto done;
4213 }
4214
4215 /*
4216 * If the hardware doesn't automatically set the accessed bit, fallback
4217 * to lru_gen_look_around(), which only clears the accessed bit in a
4218 * handful of PTEs. Spreading the work out over a period of time usually
4219 * is less efficient, but it avoids bursty page faults.
4220 */
Yu Zhao18580ef2022-12-21 21:19:06 -07004221 if (!arch_has_hw_pte_young() || !get_cap(LRU_GEN_MM_WALK)) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004222 success = iterate_mm_list_nowalk(lruvec, max_seq);
4223 goto done;
4224 }
4225
Yu Zhaof8b57162022-12-21 21:19:05 -07004226 walk = set_mm_walk(NULL, true);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004227 if (!walk) {
4228 success = iterate_mm_list_nowalk(lruvec, max_seq);
4229 goto done;
4230 }
4231
4232 walk->lruvec = lruvec;
4233 walk->max_seq = max_seq;
4234 walk->can_swap = can_swap;
Yu Zhao4983c522022-09-18 02:00:09 -06004235 walk->force_scan = force_scan;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004236
4237 do {
4238 success = iterate_mm_list(lruvec, walk, &mm);
4239 if (mm)
4240 walk_mm(lruvec, mm, walk);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004241 } while (mm);
4242done:
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004243 if (success)
4244 inc_max_seq(lruvec, can_swap, force_scan);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004245
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004246 return success;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004247}
4248
Yu Zhaoa5998f92022-12-21 21:19:02 -07004249static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
Yu Zhao37397872022-09-18 02:00:03 -06004250{
Yu Zhaoa5998f92022-12-21 21:19:02 -07004251 int gen, type, zone;
4252 unsigned long total = 0;
4253 bool can_swap = get_swappiness(lruvec, sc);
4254 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004255 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4256 DEFINE_MAX_SEQ(lruvec);
4257 DEFINE_MIN_SEQ(lruvec);
4258
Yu Zhaoa5998f92022-12-21 21:19:02 -07004259 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4260 unsigned long seq;
4261
4262 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4263 gen = lru_gen_from_seq(seq);
4264
4265 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4266 total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4267 }
4268 }
4269
4270 /* whether the size is big enough to be helpful */
4271 return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4272}
4273
4274static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
4275 unsigned long min_ttl)
4276{
4277 int gen;
4278 unsigned long birth;
4279 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4280 DEFINE_MIN_SEQ(lruvec);
4281
Yu Zhaoa5998f92022-12-21 21:19:02 -07004282 /* see the comment on lru_gen_page */
4283 gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4284 birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4285
4286 if (time_is_after_jiffies(birth + min_ttl))
4287 return false;
4288
4289 if (!lruvec_is_sizable(lruvec, sc))
4290 return false;
4291
Yu Zhao37397872022-09-18 02:00:03 -06004292 mem_cgroup_calculate_protection(NULL, memcg);
4293
Yu Zhaoa5998f92022-12-21 21:19:02 -07004294 return !mem_cgroup_below_min(memcg);
Yu Zhao37397872022-09-18 02:00:03 -06004295}
4296
Yu Zhao430499c2022-09-18 02:00:08 -06004297/* to protect the working set of the last N jiffies */
4298static unsigned long lru_gen_min_ttl __read_mostly;
4299
Yu Zhao37397872022-09-18 02:00:03 -06004300static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4301{
4302 struct mem_cgroup *memcg;
Yu Zhao430499c2022-09-18 02:00:08 -06004303 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhao37397872022-09-18 02:00:03 -06004304
4305 VM_WARN_ON_ONCE(!current_is_kswapd());
4306
Yu Zhaoa5998f92022-12-21 21:19:02 -07004307 /* check the order to exclude compaction-induced reclaim */
4308 if (!min_ttl || sc->order || sc->priority == DEF_PRIORITY)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004309 return;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004310
Yu Zhao37397872022-09-18 02:00:03 -06004311 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4312 do {
4313 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4314
Yu Zhaoa5998f92022-12-21 21:19:02 -07004315 if (lruvec_is_reclaimable(lruvec, sc, min_ttl)) {
4316 mem_cgroup_iter_break(NULL, memcg);
4317 return;
4318 }
Yu Zhao37397872022-09-18 02:00:03 -06004319
4320 cond_resched();
4321 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004322
Yu Zhao430499c2022-09-18 02:00:08 -06004323 /*
4324 * The main goal is to OOM kill if every generation from all memcgs is
4325 * younger than min_ttl. However, another possibility is all memcgs are
Yu Zhaoa5998f92022-12-21 21:19:02 -07004326 * either too small or below min.
Yu Zhao430499c2022-09-18 02:00:08 -06004327 */
4328 if (mutex_trylock(&oom_lock)) {
4329 struct oom_control oc = {
4330 .gfp_mask = sc->gfp_mask,
4331 };
4332
4333 out_of_memory(&oc);
4334
4335 mutex_unlock(&oom_lock);
4336 }
Yu Zhao37397872022-09-18 02:00:03 -06004337}
4338
Yu Zhao0182f922022-09-18 02:00:04 -06004339/*
4340 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004341 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4342 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4343 * the PTE table to the Bloom filter. This forms a feedback loop between the
4344 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004345 */
4346void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4347{
4348 int i;
4349 pte_t *pte;
4350 unsigned long start;
4351 unsigned long end;
4352 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004353 struct lru_gen_mm_walk *walk;
4354 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004355 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4356 struct page *page = pvmw->page;
Kalesh Singh0f986fa2023-08-01 19:56:04 -07004357 bool can_swap = !page_is_file_lru(page);
Yu Zhao0182f922022-09-18 02:00:04 -06004358 struct mem_cgroup *memcg = page_memcg(page);
4359 struct pglist_data *pgdat = page_pgdat(page);
4360 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4361 DEFINE_MAX_SEQ(lruvec);
4362 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4363
4364 lockdep_assert_held(pvmw->ptl);
4365 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4366
4367 if (spin_is_contended(pvmw->ptl))
4368 return;
4369
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004370 /* avoid taking the LRU lock under the PTL when possible */
4371 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4372
Yu Zhao0182f922022-09-18 02:00:04 -06004373 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4374 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4375
4376 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4377 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4378 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4379 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4380 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4381 else {
4382 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4383 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4384 }
4385 }
4386
4387 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4388
4389 rcu_read_lock();
4390 arch_enter_lazy_mmu_mode();
4391
4392 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4393 unsigned long pfn;
4394
4395 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4396 if (pfn == -1)
4397 continue;
4398
4399 if (!pte_young(pte[i]))
4400 continue;
4401
Kalesh Singh0f986fa2023-08-01 19:56:04 -07004402 page = get_pfn_page(pfn, memcg, pgdat, can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004403 if (!page)
4404 continue;
4405
4406 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4407 VM_WARN_ON_ONCE(true);
4408
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004409 young++;
4410
Yu Zhao0182f922022-09-18 02:00:04 -06004411 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4412 !(PageAnon(page) && PageSwapBacked(page) &&
4413 !PageSwapCache(page)))
4414 set_page_dirty(page);
4415
4416 old_gen = page_lru_gen(page);
4417 if (old_gen < 0)
4418 SetPageReferenced(page);
4419 else if (old_gen != new_gen)
4420 __set_bit(i, bitmap);
4421 }
4422
4423 arch_leave_lazy_mmu_mode();
4424 rcu_read_unlock();
4425
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004426 /* feedback from rmap walkers to page table walkers */
4427 if (suitable_to_scan(i, young))
4428 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4429
4430 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004431 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4432 page = pte_page(pte[i]);
4433 activate_page(page);
4434 }
4435 return;
4436 }
4437
4438 /* page_update_gen() requires stable page_memcg() */
4439 if (!mem_cgroup_trylock_pages(memcg))
4440 return;
4441
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004442 if (!walk) {
4443 spin_lock_irq(&lruvec->lru_lock);
4444 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4445 }
Yu Zhao0182f922022-09-18 02:00:04 -06004446
4447 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4448 page = compound_head(pte_page(pte[i]));
4449 if (page_memcg_rcu(page) != memcg)
4450 continue;
4451
4452 old_gen = page_update_gen(page, new_gen);
4453 if (old_gen < 0 || old_gen == new_gen)
4454 continue;
4455
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004456 if (walk)
4457 update_batch_size(walk, page, old_gen, new_gen);
4458 else
4459 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004460 }
4461
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004462 if (!walk)
4463 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004464
4465 mem_cgroup_unlock_pages();
4466}
4467
Yu Zhao37397872022-09-18 02:00:03 -06004468/******************************************************************************
4469 * the eviction
4470 ******************************************************************************/
4471
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004472static bool sort_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc,
4473 int tier_idx)
Yu Zhao37397872022-09-18 02:00:03 -06004474{
4475 bool success;
4476 int gen = page_lru_gen(page);
4477 int type = page_is_file_lru(page);
4478 int zone = page_zonenum(page);
4479 int delta = thp_nr_pages(page);
4480 int refs = page_lru_refs(page);
4481 int tier = lru_tier_from_refs(refs);
Yu Zhao3c6c3592022-12-21 21:18:59 -07004482 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004483
4484 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4485
4486 /* unevictable */
4487 if (!page_evictable(page)) {
4488 success = lru_gen_del_page(lruvec, page, true);
4489 VM_WARN_ON_ONCE_PAGE(!success, page);
4490 SetPageUnevictable(page);
4491 add_page_to_lru_list(page, lruvec);
4492 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4493 return true;
4494 }
4495
4496 /* dirty lazyfree */
4497 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4498 success = lru_gen_del_page(lruvec, page, true);
4499 VM_WARN_ON_ONCE_PAGE(!success, page);
4500 SetPageSwapBacked(page);
4501 add_page_to_lru_list_tail(page, lruvec);
4502 return true;
4503 }
4504
Yu Zhao0182f922022-09-18 02:00:04 -06004505 /* promoted */
4506 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004507 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao0182f922022-09-18 02:00:04 -06004508 return true;
4509 }
4510
Yu Zhao37397872022-09-18 02:00:03 -06004511 /* protected */
4512 if (tier > tier_idx) {
4513 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4514
4515 gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004516 list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004517
4518 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4519 lrugen->protected[hist][type][tier - 1] + delta);
Yu Zhao37397872022-09-18 02:00:03 -06004520 return true;
4521 }
4522
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004523 /* ineligible */
Charan Teja Kallaa8455252023-08-09 13:35:44 +05304524 if (zone > sc->reclaim_idx || skip_cma(page, sc)) {
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004525 gen = page_inc_gen(lruvec, page, false);
4526 list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
4527 return true;
4528 }
4529
Yu Zhao37397872022-09-18 02:00:03 -06004530 /* waiting for writeback */
4531 if (PageLocked(page) || PageWriteback(page) ||
4532 (type == LRU_GEN_FILE && PageDirty(page))) {
4533 gen = page_inc_gen(lruvec, page, true);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004534 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004535 return true;
4536 }
4537
4538 return false;
4539}
4540
4541static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4542{
4543 bool success;
4544
Yu Zhao37397872022-09-18 02:00:03 -06004545 /* swapping inhibited */
Yu Zhaof8b57162022-12-21 21:19:05 -07004546 if (!(sc->gfp_mask & __GFP_IO) &&
Yu Zhao37397872022-09-18 02:00:03 -06004547 (PageDirty(page) ||
4548 (PageAnon(page) && !PageSwapCache(page))))
4549 return false;
4550
4551 /* raced with release_pages() */
4552 if (!get_page_unless_zero(page))
4553 return false;
4554
4555 /* raced with another isolation */
4556 if (!TestClearPageLRU(page)) {
4557 put_page(page);
4558 return false;
4559 }
4560
4561 /* see the comment on MAX_NR_TIERS */
4562 if (!PageReferenced(page))
4563 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4564
4565 /* for shrink_page_list() */
4566 ClearPageReclaim(page);
4567 ClearPageReferenced(page);
4568
4569 success = lru_gen_del_page(lruvec, page, true);
4570 VM_WARN_ON_ONCE_PAGE(!success, page);
4571
4572 return true;
4573}
4574
4575static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4576 int type, int tier, struct list_head *list)
4577{
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004578 int i;
4579 int gen;
Yu Zhao37397872022-09-18 02:00:03 -06004580 enum vm_event_item item;
4581 int sorted = 0;
4582 int scanned = 0;
4583 int isolated = 0;
4584 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004585 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004586 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4587
4588 VM_WARN_ON_ONCE(!list_empty(list));
4589
4590 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4591 return 0;
4592
4593 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4594
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004595 for (i = MAX_NR_ZONES; i > 0; i--) {
Yu Zhao37397872022-09-18 02:00:03 -06004596 LIST_HEAD(moved);
4597 int skipped = 0;
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004598 int zone = (sc->reclaim_idx + i) % MAX_NR_ZONES;
Yu Zhaodf91dc92022-12-21 21:19:00 -07004599 struct list_head *head = &lrugen->pages[gen][type][zone];
Yu Zhao37397872022-09-18 02:00:03 -06004600
4601 while (!list_empty(head)) {
4602 struct page *page = lru_to_page(head);
4603 int delta = thp_nr_pages(page);
4604
4605 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4606 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4607 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4608 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4609
4610 scanned += delta;
4611
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004612 if (sort_page(lruvec, page, sc, tier))
Yu Zhao37397872022-09-18 02:00:03 -06004613 sorted += delta;
4614 else if (isolate_page(lruvec, page, sc)) {
4615 list_add(&page->lru, list);
4616 isolated += delta;
4617 } else {
4618 list_move(&page->lru, &moved);
4619 skipped += delta;
4620 }
4621
4622 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4623 break;
4624 }
4625
4626 if (skipped) {
4627 list_splice(&moved, head);
4628 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4629 }
4630
4631 if (!remaining || isolated >= MIN_LRU_BATCH)
4632 break;
4633 }
4634
4635 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4636 if (!cgroup_reclaim(sc)) {
4637 __count_vm_events(item, isolated);
4638 __count_vm_events(PGREFILL, sorted);
4639 }
4640 __count_memcg_events(memcg, item, isolated);
4641 __count_memcg_events(memcg, PGREFILL, sorted);
4642 __count_vm_events(PGSCAN_ANON + type, isolated);
4643
4644 /*
Yu Zhaof8b57162022-12-21 21:19:05 -07004645 * There might not be eligible pages due to reclaim_idx. Check the
4646 * remaining to prevent livelock if it's not making progress.
Yu Zhao37397872022-09-18 02:00:03 -06004647 */
4648 return isolated || !remaining ? scanned : 0;
4649}
4650
4651static int get_tier_idx(struct lruvec *lruvec, int type)
4652{
4653 int tier;
4654 struct ctrl_pos sp, pv;
4655
4656 /*
4657 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4658 * This value is chosen because any other tier would have at least twice
4659 * as many refaults as the first tier.
4660 */
4661 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4662 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4663 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4664 if (!positive_ctrl_err(&sp, &pv))
4665 break;
4666 }
4667
4668 return tier - 1;
4669}
4670
4671static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4672{
4673 int type, tier;
4674 struct ctrl_pos sp, pv;
4675 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4676
4677 /*
4678 * Compare the first tier of anon with that of file to determine which
4679 * type to scan. Also need to compare other tiers of the selected type
4680 * with the first tier of the other type to determine the last tier (of
4681 * the selected type) to evict.
4682 */
4683 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4684 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4685 type = positive_ctrl_err(&sp, &pv);
4686
4687 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4688 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4689 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4690 if (!positive_ctrl_err(&sp, &pv))
4691 break;
4692 }
4693
4694 *tier_idx = tier - 1;
4695
4696 return type;
4697}
4698
4699static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4700 int *type_scanned, struct list_head *list)
4701{
4702 int i;
4703 int type;
4704 int scanned;
4705 int tier = -1;
4706 DEFINE_MIN_SEQ(lruvec);
4707
4708 /*
4709 * Try to make the obvious choice first. When anon and file are both
4710 * available from the same generation, interpret swappiness 1 as file
4711 * first and 200 as anon first.
4712 */
4713 if (!swappiness)
4714 type = LRU_GEN_FILE;
4715 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4716 type = LRU_GEN_ANON;
4717 else if (swappiness == 1)
4718 type = LRU_GEN_FILE;
4719 else if (swappiness == 200)
4720 type = LRU_GEN_ANON;
4721 else
4722 type = get_type_to_scan(lruvec, swappiness, &tier);
4723
4724 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4725 if (tier < 0)
4726 tier = get_tier_idx(lruvec, type);
4727
4728 scanned = scan_pages(lruvec, sc, type, tier, list);
4729 if (scanned)
4730 break;
4731
4732 type = !type;
4733 tier = -1;
4734 }
4735
4736 *type_scanned = type;
4737
4738 return scanned;
4739}
4740
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004741static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
Yu Zhao37397872022-09-18 02:00:03 -06004742{
4743 int type;
4744 int scanned;
4745 int reclaimed;
4746 LIST_HEAD(list);
Yu Zhao79e66ea2022-11-15 18:38:07 -07004747 LIST_HEAD(clean);
Yu Zhao37397872022-09-18 02:00:03 -06004748 struct page *page;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004749 struct page *next;
Yu Zhao37397872022-09-18 02:00:03 -06004750 enum vm_event_item item;
4751 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004752 struct lru_gen_mm_walk *walk;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004753 bool skip_retry = false;
Yu Zhao37397872022-09-18 02:00:03 -06004754 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4755 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4756
4757 spin_lock_irq(&lruvec->lru_lock);
4758
4759 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4760
4761 scanned += try_to_inc_min_seq(lruvec, swappiness);
4762
4763 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4764 scanned = 0;
4765
4766 spin_unlock_irq(&lruvec->lru_lock);
4767
4768 if (list_empty(&list))
4769 return scanned;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004770retry:
Yu Zhao37397872022-09-18 02:00:03 -06004771 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
Yu Zhao79e66ea2022-11-15 18:38:07 -07004772 sc->nr_reclaimed += reclaimed;
Yu Zhao37397872022-09-18 02:00:03 -06004773
Yu Zhao79e66ea2022-11-15 18:38:07 -07004774 list_for_each_entry_safe_reverse(page, next, &list, lru) {
4775 if (!page_evictable(page)) {
4776 list_del(&page->lru);
4777 putback_lru_page(page);
4778 continue;
4779 }
Yu Zhao37397872022-09-18 02:00:03 -06004780
Yu Zhao37397872022-09-18 02:00:03 -06004781 if (PageReclaim(page) &&
Yu Zhao79e66ea2022-11-15 18:38:07 -07004782 (PageDirty(page) || PageWriteback(page))) {
4783 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4784 if (PageWorkingset(page))
4785 SetPageReferenced(page);
4786 continue;
4787 }
4788
4789 if (skip_retry || PageActive(page) || PageReferenced(page) ||
4790 page_mapped(page) || PageLocked(page) ||
4791 PageDirty(page) || PageWriteback(page)) {
4792 /* don't add rejected pages to the oldest generation */
4793 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
4794 BIT(PG_active));
4795 continue;
4796 }
4797
4798 /* retry pages that may have missed rotate_reclaimable_page() */
4799 list_move(&page->lru, &clean);
4800 sc->nr_scanned -= thp_nr_pages(page);
Yu Zhao37397872022-09-18 02:00:03 -06004801 }
4802
4803 spin_lock_irq(&lruvec->lru_lock);
4804
4805 move_pages_to_lru(lruvec, &list);
4806
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004807 walk = current->reclaim_state->mm_walk;
4808 if (walk && walk->batched)
4809 reset_batch_size(lruvec, walk);
4810
Yu Zhao37397872022-09-18 02:00:03 -06004811 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4812 if (!cgroup_reclaim(sc))
4813 __count_vm_events(item, reclaimed);
4814 __count_memcg_events(memcg, item, reclaimed);
4815 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4816
4817 spin_unlock_irq(&lruvec->lru_lock);
4818
4819 mem_cgroup_uncharge_list(&list);
4820 free_unref_page_list(&list);
4821
Yu Zhao79e66ea2022-11-15 18:38:07 -07004822 INIT_LIST_HEAD(&list);
4823 list_splice_init(&clean, &list);
4824
4825 if (!list_empty(&list)) {
4826 skip_retry = true;
4827 goto retry;
4828 }
Yu Zhao37397872022-09-18 02:00:03 -06004829
4830 return scanned;
4831}
4832
Yu Zhaocb3958d2022-12-21 21:19:03 -07004833static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
4834 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4835{
4836 int gen, type, zone;
4837 unsigned long old = 0;
4838 unsigned long young = 0;
4839 unsigned long total = 0;
4840 struct lru_gen_page *lrugen = &lruvec->lrugen;
4841 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4842 DEFINE_MIN_SEQ(lruvec);
4843
4844 /* whether this lruvec is completely out of cold pages */
4845 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
4846 *nr_to_scan = 0;
4847 return true;
4848 }
4849
4850 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4851 unsigned long seq;
4852
4853 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4854 unsigned long size = 0;
4855
4856 gen = lru_gen_from_seq(seq);
4857
4858 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4859 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4860
4861 total += size;
4862 if (seq == max_seq)
4863 young += size;
4864 else if (seq + MIN_NR_GENS == max_seq)
4865 old += size;
4866 }
4867 }
4868
4869 /* try to scrape all its memory if this memcg was deleted */
4870 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4871
4872 /*
4873 * The aging tries to be lazy to reduce the overhead, while the eviction
4874 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4875 * ideal number of generations is MIN_NR_GENS+1.
4876 */
4877 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4878 return false;
4879
4880 /*
4881 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4882 * of the total number of pages for each generation. A reasonable range
4883 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4884 * aging cares about the upper bound of hot pages, while the eviction
4885 * cares about the lower bound of cold pages.
4886 */
4887 if (young * MIN_NR_GENS > total)
4888 return true;
4889 if (old * (MIN_NR_GENS + 2) < total)
4890 return true;
4891
4892 return false;
4893}
4894
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004895/*
4896 * For future optimizations:
4897 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4898 * reclaim.
4899 */
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004900static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004901{
Yu Zhao37397872022-09-18 02:00:03 -06004902 unsigned long nr_to_scan;
4903 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4904 DEFINE_MAX_SEQ(lruvec);
Yu Zhao37397872022-09-18 02:00:03 -06004905
Yu Zhaof8b57162022-12-21 21:19:05 -07004906 if (mem_cgroup_below_min(memcg))
Yu Zhao37397872022-09-18 02:00:03 -06004907 return 0;
4908
Yu Zhaoa5998f92022-12-21 21:19:02 -07004909 if (!should_run_aging(lruvec, max_seq, sc, can_swap, &nr_to_scan))
Yu Zhao37397872022-09-18 02:00:03 -06004910 return nr_to_scan;
4911
4912 /* skip the aging path at the default priority */
4913 if (sc->priority == DEF_PRIORITY)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004914 return nr_to_scan;
Yu Zhaoa5998f92022-12-21 21:19:02 -07004915
Yu Zhaoa5998f92022-12-21 21:19:02 -07004916 /* skip this lruvec as it's low on cold pages */
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004917 return try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false) ? -1 : 0;
Yu Zhao37397872022-09-18 02:00:03 -06004918}
4919
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004920static unsigned long get_nr_to_reclaim(struct scan_control *sc)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004921{
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004922 /* don't abort memcg reclaim to ensure fairness */
4923 if (!global_reclaim(sc))
4924 return -1;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004925
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004926 return max(sc->nr_to_reclaim, compact_gap(sc->order));
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004927}
4928
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004929static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Yu Zhao37397872022-09-18 02:00:03 -06004930{
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004931 long nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004932 unsigned long scanned = 0;
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004933 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
Yu Zhaof8b57162022-12-21 21:19:05 -07004934 int swappiness = get_swappiness(lruvec, sc);
4935
4936 /* clean file pages are more likely to exist */
4937 if (swappiness && !(sc->gfp_mask & __GFP_IO))
4938 swappiness = 1;
Yu Zhao37397872022-09-18 02:00:03 -06004939
Yu Zhao37397872022-09-18 02:00:03 -06004940 while (true) {
4941 int delta;
Yu Zhao37397872022-09-18 02:00:03 -06004942
Yu Zhaoa5998f92022-12-21 21:19:02 -07004943 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004944 if (nr_to_scan <= 0)
Yu Zhaoa5998f92022-12-21 21:19:02 -07004945 break;
Yu Zhao37397872022-09-18 02:00:03 -06004946
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004947 delta = evict_pages(lruvec, sc, swappiness);
Yu Zhao37397872022-09-18 02:00:03 -06004948 if (!delta)
Yu Zhaoa5998f92022-12-21 21:19:02 -07004949 break;
Yu Zhao37397872022-09-18 02:00:03 -06004950
4951 scanned += delta;
4952 if (scanned >= nr_to_scan)
4953 break;
4954
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004955 if (sc->nr_reclaimed >= nr_to_reclaim)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004956 break;
4957
Yu Zhao37397872022-09-18 02:00:03 -06004958 cond_resched();
4959 }
4960
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004961 /* whether try_to_inc_max_seq() was successful */
4962 return nr_to_scan < 0;
4963}
4964
4965static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
4966{
4967 bool success;
4968 unsigned long scanned = sc->nr_scanned;
4969 unsigned long reclaimed = sc->nr_reclaimed;
4970 int seg = lru_gen_memcg_seg(lruvec);
4971 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4972 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4973
4974 /* see the comment on MEMCG_NR_GENS */
4975 if (!lruvec_is_sizable(lruvec, sc))
4976 return seg != MEMCG_LRU_TAIL ? MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG;
4977
4978 mem_cgroup_calculate_protection(NULL, memcg);
4979
4980 if (mem_cgroup_below_min(memcg))
4981 return MEMCG_LRU_YOUNG;
4982
4983 if (mem_cgroup_below_low(memcg)) {
4984 /* see the comment on MEMCG_NR_GENS */
4985 if (seg != MEMCG_LRU_TAIL)
4986 return MEMCG_LRU_TAIL;
4987
4988 memcg_memory_event(memcg, MEMCG_LOW);
4989 }
4990
4991 success = try_to_shrink_lruvec(lruvec, sc);
4992
4993 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority);
4994
4995 vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned,
4996 sc->nr_reclaimed - reclaimed);
4997
4998 sc->nr_reclaimed += current->reclaim_state->reclaimed_slab;
4999 current->reclaim_state->reclaimed_slab = 0;
5000
5001 return success ? MEMCG_LRU_YOUNG : 0;
5002}
5003
5004#ifdef CONFIG_MEMCG
5005
5006static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5007{
Yu Zhaof7909cb2023-02-13 00:53:22 -07005008 int op;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005009 int gen;
5010 int bin;
5011 int first_bin;
5012 struct lruvec *lruvec;
5013 struct lru_gen_page *lrugen;
Yu Zhaof7909cb2023-02-13 00:53:22 -07005014 struct mem_cgroup *memcg;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005015 const struct hlist_nulls_node *pos;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005016 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
5017
5018 bin = first_bin = prandom_u32_max(MEMCG_NR_BINS);
5019restart:
Yu Zhaof7909cb2023-02-13 00:53:22 -07005020 op = 0;
5021 memcg = NULL;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005022 gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq));
5023
5024 rcu_read_lock();
5025
5026 hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) {
5027 if (op)
5028 lru_gen_rotate_memcg(lruvec, op);
5029
5030 mem_cgroup_put(memcg);
5031
5032 lruvec = container_of(lrugen, struct lruvec, lrugen);
5033 memcg = lruvec_memcg(lruvec);
5034
5035 if (!mem_cgroup_tryget(memcg)) {
5036 op = 0;
5037 memcg = NULL;
5038 continue;
5039 }
5040
5041 rcu_read_unlock();
5042
5043 op = shrink_one(lruvec, sc);
5044
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005045 rcu_read_lock();
Yu Zhaof7909cb2023-02-13 00:53:22 -07005046
5047 if (sc->nr_reclaimed >= nr_to_reclaim)
5048 break;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005049 }
5050
5051 rcu_read_unlock();
5052
Yu Zhaof7909cb2023-02-13 00:53:22 -07005053 if (op)
5054 lru_gen_rotate_memcg(lruvec, op);
5055
5056 mem_cgroup_put(memcg);
5057
5058 if (sc->nr_reclaimed >= nr_to_reclaim)
5059 return;
5060
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005061 /* restart if raced with lru_gen_rotate_memcg() */
5062 if (gen != get_nulls_value(pos))
5063 goto restart;
5064
5065 /* try the rest of the bins of the current generation */
5066 bin = get_memcg_bin(bin + 1);
5067 if (bin != first_bin)
5068 goto restart;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005069}
5070
5071static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5072{
5073 struct blk_plug plug;
5074
5075 VM_WARN_ON_ONCE(global_reclaim(sc));
Yu Zhaof8b57162022-12-21 21:19:05 -07005076 VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005077
5078 lru_add_drain();
5079
5080 blk_start_plug(&plug);
5081
Yu Zhaof8b57162022-12-21 21:19:05 -07005082 set_mm_walk(NULL, false);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005083
5084 if (try_to_shrink_lruvec(lruvec, sc))
5085 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG);
5086
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005087 clear_mm_walk();
5088
Yu Zhao37397872022-09-18 02:00:03 -06005089 blk_finish_plug(&plug);
5090}
5091
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005092#else /* !CONFIG_MEMCG */
5093
5094static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5095{
5096 BUILD_BUG();
5097}
5098
5099static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5100{
5101 BUILD_BUG();
5102}
5103
5104#endif
5105
5106static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc)
5107{
5108 int priority;
5109 unsigned long reclaimable;
5110 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5111
5112 if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH)
5113 return;
5114 /*
5115 * Determine the initial priority based on ((total / MEMCG_NR_GENS) >>
5116 * priority) * reclaimed_to_scanned_ratio = nr_to_reclaim, where the
5117 * estimated reclaimed_to_scanned_ratio = inactive / total.
5118 */
5119 reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE);
5120 if (get_swappiness(lruvec, sc))
5121 reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON);
5122
5123 reclaimable /= MEMCG_NR_GENS;
5124
5125 /* round down reclaimable and round up sc->nr_to_reclaim */
5126 priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1);
5127
5128 sc->priority = clamp(priority, 0, DEF_PRIORITY);
5129}
5130
5131static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5132{
5133 struct blk_plug plug;
5134 unsigned long reclaimed = sc->nr_reclaimed;
5135
5136 VM_WARN_ON_ONCE(!global_reclaim(sc));
5137
Yu Zhaof8b57162022-12-21 21:19:05 -07005138 /*
5139 * Unmapped clean pages are already prioritized. Scanning for more of
5140 * them is likely futile and can cause high reclaim latency when there
5141 * is a large number of memcgs.
5142 */
5143 if (!sc->may_writepage || !sc->may_unmap)
5144 goto done;
5145
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005146 lru_add_drain();
5147
5148 blk_start_plug(&plug);
5149
Yu Zhaof8b57162022-12-21 21:19:05 -07005150 set_mm_walk(pgdat, false);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005151
5152 set_initial_priority(pgdat, sc);
5153
5154 if (current_is_kswapd())
5155 sc->nr_reclaimed = 0;
5156
5157 if (mem_cgroup_disabled())
5158 shrink_one(&pgdat->__lruvec, sc);
5159 else
5160 shrink_many(pgdat, sc);
5161
5162 if (current_is_kswapd())
5163 sc->nr_reclaimed += reclaimed;
5164
5165 clear_mm_walk();
5166
5167 blk_finish_plug(&plug);
Yu Zhaof8b57162022-12-21 21:19:05 -07005168done:
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005169 /* kswapd should never fail */
5170 pgdat->kswapd_failures = 0;
5171}
5172
5173#ifdef CONFIG_MEMCG
5174void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
5175{
5176 int seg;
5177 int old, new;
5178 int bin = prandom_u32_max(MEMCG_NR_BINS);
5179 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5180
5181 spin_lock(&pgdat->memcg_lru.lock);
5182
5183 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
5184
5185 seg = 0;
5186 new = old = lruvec->lrugen.gen;
5187
5188 /* see the comment on MEMCG_NR_GENS */
5189 if (op == MEMCG_LRU_HEAD)
5190 seg = MEMCG_LRU_HEAD;
5191 else if (op == MEMCG_LRU_TAIL)
5192 seg = MEMCG_LRU_TAIL;
5193 else if (op == MEMCG_LRU_OLD)
5194 new = get_memcg_gen(pgdat->memcg_lru.seq);
5195 else if (op == MEMCG_LRU_YOUNG)
5196 new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
5197 else
5198 VM_WARN_ON_ONCE(true);
5199
5200 hlist_nulls_del_rcu(&lruvec->lrugen.list);
5201
5202 if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
5203 hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
5204 else
5205 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
5206
5207 pgdat->memcg_lru.nr_memcgs[old]--;
5208 pgdat->memcg_lru.nr_memcgs[new]++;
5209
5210 lruvec->lrugen.gen = new;
5211 WRITE_ONCE(lruvec->lrugen.seg, seg);
5212
5213 if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
5214 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
5215
5216 spin_unlock(&pgdat->memcg_lru.lock);
5217}
5218#endif
5219
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005220/******************************************************************************
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005221 * state change
5222 ******************************************************************************/
5223
5224static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5225{
Yu Zhao3c6c3592022-12-21 21:18:59 -07005226 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005227
5228 if (lrugen->enabled) {
5229 enum lru_list lru;
5230
5231 for_each_evictable_lru(lru) {
5232 if (!list_empty(&lruvec->lists[lru]))
5233 return false;
5234 }
5235 } else {
5236 int gen, type, zone;
5237
5238 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005239 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005240 return false;
5241 }
5242 }
5243
5244 return true;
5245}
5246
5247static bool fill_evictable(struct lruvec *lruvec)
5248{
5249 enum lru_list lru;
5250 int remaining = MAX_LRU_BATCH;
5251
5252 for_each_evictable_lru(lru) {
5253 int type = is_file_lru(lru);
5254 bool active = is_active_lru(lru);
5255 struct list_head *head = &lruvec->lists[lru];
5256
5257 while (!list_empty(head)) {
5258 bool success;
5259 struct page *page = lru_to_page(head);
5260
5261 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5262 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
5263 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5264 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
5265
5266 del_page_from_lru_list(page, lruvec);
5267 success = lru_gen_add_page(lruvec, page, false);
5268 VM_WARN_ON_ONCE(!success);
5269
5270 if (!--remaining)
5271 return false;
5272 }
5273 }
5274
5275 return true;
5276}
5277
5278static bool drain_evictable(struct lruvec *lruvec)
5279{
5280 int gen, type, zone;
5281 int remaining = MAX_LRU_BATCH;
5282
5283 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005284 struct list_head *head = &lruvec->lrugen.pages[gen][type][zone];
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005285
5286 while (!list_empty(head)) {
5287 bool success;
5288 struct page *page = lru_to_page(head);
5289
5290 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5291 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5292 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5293 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5294
5295 success = lru_gen_del_page(lruvec, page, false);
5296 VM_WARN_ON_ONCE(!success);
5297 add_page_to_lru_list(page, lruvec);
5298
5299 if (!--remaining)
5300 return false;
5301 }
5302 }
5303
5304 return true;
5305}
5306
5307static void lru_gen_change_state(bool enabled)
5308{
5309 static DEFINE_MUTEX(state_mutex);
5310
5311 struct mem_cgroup *memcg;
5312
5313 cgroup_lock();
5314 cpus_read_lock();
5315 get_online_mems();
5316 mutex_lock(&state_mutex);
5317
5318 if (enabled == lru_gen_enabled())
5319 goto unlock;
5320
5321 if (enabled)
5322 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5323 else
5324 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5325
5326 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5327 do {
5328 int nid;
5329
5330 for_each_node(nid) {
5331 struct lruvec *lruvec = get_lruvec(memcg, nid);
5332
5333 if (!lruvec)
5334 continue;
5335
5336 spin_lock_irq(&lruvec->lru_lock);
5337
5338 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5339 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5340
5341 lruvec->lrugen.enabled = enabled;
5342
5343 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5344 spin_unlock_irq(&lruvec->lru_lock);
5345 cond_resched();
5346 spin_lock_irq(&lruvec->lru_lock);
5347 }
5348
5349 spin_unlock_irq(&lruvec->lru_lock);
5350 }
5351
5352 cond_resched();
5353 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5354unlock:
5355 mutex_unlock(&state_mutex);
5356 put_online_mems();
5357 cpus_read_unlock();
5358 cgroup_unlock();
5359}
5360
5361/******************************************************************************
5362 * sysfs interface
5363 ******************************************************************************/
5364
Yu Zhao430499c2022-09-18 02:00:08 -06005365static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5366{
5367 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5368}
5369
Yu Zhao642d9862022-09-18 02:00:10 -06005370/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao430499c2022-09-18 02:00:08 -06005371static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5372 const char *buf, size_t len)
5373{
5374 unsigned int msecs;
5375
5376 if (kstrtouint(buf, 0, &msecs))
5377 return -EINVAL;
5378
5379 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5380
5381 return len;
5382}
5383
5384static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5385 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5386);
5387
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005388static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5389{
5390 unsigned int caps = 0;
5391
5392 if (get_cap(LRU_GEN_CORE))
5393 caps |= BIT(LRU_GEN_CORE);
5394
5395 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5396 caps |= BIT(LRU_GEN_MM_WALK);
5397
Juergen Gross23811792022-11-23 07:45:10 +01005398 if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005399 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5400
5401 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5402}
5403
Yu Zhao642d9862022-09-18 02:00:10 -06005404/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005405static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5406 const char *buf, size_t len)
5407{
5408 int i;
5409 unsigned int caps;
5410
5411 if (tolower(*buf) == 'n')
5412 caps = 0;
5413 else if (tolower(*buf) == 'y')
5414 caps = -1;
5415 else if (kstrtouint(buf, 0, &caps))
5416 return -EINVAL;
5417
5418 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5419 bool enabled = caps & BIT(i);
5420
5421 if (i == LRU_GEN_CORE)
5422 lru_gen_change_state(enabled);
5423 else if (enabled)
5424 static_branch_enable(&lru_gen_caps[i]);
5425 else
5426 static_branch_disable(&lru_gen_caps[i]);
5427 }
5428
5429 return len;
5430}
5431
5432static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5433 enabled, 0644, show_enabled, store_enabled
5434);
5435
5436static struct attribute *lru_gen_attrs[] = {
Yu Zhao430499c2022-09-18 02:00:08 -06005437 &lru_gen_min_ttl_attr.attr,
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005438 &lru_gen_enabled_attr.attr,
5439 NULL
5440};
5441
5442static struct attribute_group lru_gen_attr_group = {
5443 .name = "lru_gen",
5444 .attrs = lru_gen_attrs,
5445};
5446
5447/******************************************************************************
Yu Zhao4983c522022-09-18 02:00:09 -06005448 * debugfs interface
5449 ******************************************************************************/
5450
5451static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5452{
5453 struct mem_cgroup *memcg;
5454 loff_t nr_to_skip = *pos;
5455
5456 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5457 if (!m->private)
5458 return ERR_PTR(-ENOMEM);
5459
5460 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5461 do {
5462 int nid;
5463
5464 for_each_node_state(nid, N_MEMORY) {
5465 if (!nr_to_skip--)
5466 return get_lruvec(memcg, nid);
5467 }
5468 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5469
5470 return NULL;
5471}
5472
5473static void lru_gen_seq_stop(struct seq_file *m, void *v)
5474{
5475 if (!IS_ERR_OR_NULL(v))
5476 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5477
5478 kvfree(m->private);
5479 m->private = NULL;
5480}
5481
5482static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5483{
5484 int nid = lruvec_pgdat(v)->node_id;
5485 struct mem_cgroup *memcg = lruvec_memcg(v);
5486
5487 ++*pos;
5488
5489 nid = next_memory_node(nid);
5490 if (nid == MAX_NUMNODES) {
5491 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5492 if (!memcg)
5493 return NULL;
5494
5495 nid = first_memory_node;
5496 }
5497
5498 return get_lruvec(memcg, nid);
5499}
5500
5501static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5502 unsigned long max_seq, unsigned long *min_seq,
5503 unsigned long seq)
5504{
5505 int i;
5506 int type, tier;
5507 int hist = lru_hist_from_seq(seq);
Yu Zhao3c6c3592022-12-21 21:18:59 -07005508 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005509
5510 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5511 seq_printf(m, " %10d", tier);
5512 for (type = 0; type < ANON_AND_FILE; type++) {
5513 const char *s = " ";
5514 unsigned long n[3] = {};
5515
5516 if (seq == max_seq) {
5517 s = "RT ";
5518 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5519 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5520 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5521 s = "rep";
5522 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5523 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5524 if (tier)
5525 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5526 }
5527
5528 for (i = 0; i < 3; i++)
5529 seq_printf(m, " %10lu%c", n[i], s[i]);
5530 }
5531 seq_putc(m, '\n');
5532 }
5533
5534 seq_puts(m, " ");
5535 for (i = 0; i < NR_MM_STATS; i++) {
5536 const char *s = " ";
5537 unsigned long n = 0;
5538
5539 if (seq == max_seq && NR_HIST_GENS == 1) {
5540 s = "LOYNFA";
5541 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5542 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5543 s = "loynfa";
5544 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5545 }
5546
5547 seq_printf(m, " %10lu%c", n, s[i]);
5548 }
5549 seq_putc(m, '\n');
5550}
5551
Yu Zhao642d9862022-09-18 02:00:10 -06005552/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005553static int lru_gen_seq_show(struct seq_file *m, void *v)
5554{
5555 unsigned long seq;
5556 bool full = !debugfs_real_fops(m->file)->write;
5557 struct lruvec *lruvec = v;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005558 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005559 int nid = lruvec_pgdat(lruvec)->node_id;
5560 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5561 DEFINE_MAX_SEQ(lruvec);
5562 DEFINE_MIN_SEQ(lruvec);
5563
5564 if (nid == first_memory_node) {
5565 const char *path = memcg ? m->private : "";
5566
5567#ifdef CONFIG_MEMCG
5568 if (memcg)
5569 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5570#endif
5571 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5572 }
5573
5574 seq_printf(m, " node %5d\n", nid);
5575
5576 if (!full)
5577 seq = min_seq[LRU_GEN_ANON];
5578 else if (max_seq >= MAX_NR_GENS)
5579 seq = max_seq - MAX_NR_GENS + 1;
5580 else
5581 seq = 0;
5582
5583 for (; seq <= max_seq; seq++) {
5584 int type, zone;
5585 int gen = lru_gen_from_seq(seq);
5586 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5587
5588 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5589
5590 for (type = 0; type < ANON_AND_FILE; type++) {
5591 unsigned long size = 0;
5592 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5593
5594 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5595 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5596
5597 seq_printf(m, " %10lu%c", size, mark);
5598 }
5599
5600 seq_putc(m, '\n');
5601
5602 if (full)
5603 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5604 }
5605
5606 return 0;
5607}
5608
5609static const struct seq_operations lru_gen_seq_ops = {
5610 .start = lru_gen_seq_start,
5611 .stop = lru_gen_seq_stop,
5612 .next = lru_gen_seq_next,
5613 .show = lru_gen_seq_show,
5614};
5615
5616static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5617 bool can_swap, bool force_scan)
5618{
5619 DEFINE_MAX_SEQ(lruvec);
5620 DEFINE_MIN_SEQ(lruvec);
5621
5622 if (seq < max_seq)
5623 return 0;
5624
5625 if (seq > max_seq)
5626 return -EINVAL;
5627
5628 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5629 return -ERANGE;
5630
5631 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5632
5633 return 0;
5634}
5635
5636static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5637 int swappiness, unsigned long nr_to_reclaim)
5638{
5639 DEFINE_MAX_SEQ(lruvec);
5640
5641 if (seq + MIN_NR_GENS > max_seq)
5642 return -EINVAL;
5643
5644 sc->nr_reclaimed = 0;
5645
5646 while (!signal_pending(current)) {
5647 DEFINE_MIN_SEQ(lruvec);
5648
5649 if (seq < min_seq[!swappiness])
5650 return 0;
5651
5652 if (sc->nr_reclaimed >= nr_to_reclaim)
5653 return 0;
5654
Yu Zhao4fc3ef42022-12-21 21:19:01 -07005655 if (!evict_pages(lruvec, sc, swappiness))
Yu Zhao4983c522022-09-18 02:00:09 -06005656 return 0;
5657
5658 cond_resched();
5659 }
5660
5661 return -EINTR;
5662}
5663
5664static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5665 struct scan_control *sc, int swappiness, unsigned long opt)
5666{
5667 struct lruvec *lruvec;
5668 int err = -EINVAL;
5669 struct mem_cgroup *memcg = NULL;
5670
5671 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5672 return -EINVAL;
5673
5674 if (!mem_cgroup_disabled()) {
5675 rcu_read_lock();
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005676
Yu Zhao4983c522022-09-18 02:00:09 -06005677 memcg = mem_cgroup_from_id(memcg_id);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005678 if (!mem_cgroup_tryget(memcg))
Yu Zhao4983c522022-09-18 02:00:09 -06005679 memcg = NULL;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005680
Yu Zhao4983c522022-09-18 02:00:09 -06005681 rcu_read_unlock();
5682
5683 if (!memcg)
5684 return -EINVAL;
5685 }
5686
5687 if (memcg_id != mem_cgroup_id(memcg))
5688 goto done;
5689
5690 lruvec = get_lruvec(memcg, nid);
5691
5692 if (swappiness < 0)
5693 swappiness = get_swappiness(lruvec, sc);
5694 else if (swappiness > 200)
5695 goto done;
5696
5697 switch (cmd) {
5698 case '+':
5699 err = run_aging(lruvec, seq, sc, swappiness, opt);
5700 break;
5701 case '-':
5702 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5703 break;
5704 }
5705done:
5706 mem_cgroup_put(memcg);
5707
5708 return err;
5709}
5710
Yu Zhao642d9862022-09-18 02:00:10 -06005711/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005712static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5713 size_t len, loff_t *pos)
5714{
5715 void *buf;
5716 char *cur, *next;
5717 unsigned int flags;
5718 struct blk_plug plug;
5719 int err = -EINVAL;
5720 struct scan_control sc = {
5721 .may_writepage = true,
5722 .may_unmap = true,
5723 .may_swap = true,
5724 .reclaim_idx = MAX_NR_ZONES - 1,
5725 .gfp_mask = GFP_KERNEL,
5726 };
5727
5728 buf = kvmalloc(len + 1, GFP_KERNEL);
5729 if (!buf)
5730 return -ENOMEM;
5731
5732 if (copy_from_user(buf, src, len)) {
5733 kvfree(buf);
5734 return -EFAULT;
5735 }
5736
5737 set_task_reclaim_state(current, &sc.reclaim_state);
5738 flags = memalloc_noreclaim_save();
5739 blk_start_plug(&plug);
Yu Zhaof8b57162022-12-21 21:19:05 -07005740 if (!set_mm_walk(NULL, true)) {
Yu Zhao4983c522022-09-18 02:00:09 -06005741 err = -ENOMEM;
5742 goto done;
5743 }
5744
5745 next = buf;
5746 next[len] = '\0';
5747
5748 while ((cur = strsep(&next, ",;\n"))) {
5749 int n;
5750 int end;
5751 char cmd;
5752 unsigned int memcg_id;
5753 unsigned int nid;
5754 unsigned long seq;
5755 unsigned int swappiness = -1;
5756 unsigned long opt = -1;
5757
5758 cur = skip_spaces(cur);
5759 if (!*cur)
5760 continue;
5761
5762 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5763 &seq, &end, &swappiness, &end, &opt, &end);
5764 if (n < 4 || cur[end]) {
5765 err = -EINVAL;
5766 break;
5767 }
5768
5769 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5770 if (err)
5771 break;
5772 }
5773done:
5774 clear_mm_walk();
5775 blk_finish_plug(&plug);
5776 memalloc_noreclaim_restore(flags);
5777 set_task_reclaim_state(current, NULL);
5778
5779 kvfree(buf);
5780
5781 return err ? : len;
5782}
5783
5784static int lru_gen_seq_open(struct inode *inode, struct file *file)
5785{
5786 return seq_open(file, &lru_gen_seq_ops);
5787}
5788
5789static const struct file_operations lru_gen_rw_fops = {
5790 .open = lru_gen_seq_open,
5791 .read = seq_read,
5792 .write = lru_gen_seq_write,
5793 .llseek = seq_lseek,
5794 .release = seq_release,
5795};
5796
5797static const struct file_operations lru_gen_ro_fops = {
5798 .open = lru_gen_seq_open,
5799 .read = seq_read,
5800 .llseek = seq_lseek,
5801 .release = seq_release,
5802};
5803
5804/******************************************************************************
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005805 * initialization
5806 ******************************************************************************/
5807
5808void lru_gen_init_lruvec(struct lruvec *lruvec)
5809{
Yu Zhao430499c2022-09-18 02:00:08 -06005810 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005811 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005812 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005813
5814 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005815 lrugen->enabled = lru_gen_enabled();
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005816
Yu Zhao430499c2022-09-18 02:00:08 -06005817 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5818 lrugen->timestamps[i] = jiffies;
5819
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005820 for_each_gen_type_zone(gen, type, zone)
Yu Zhaodf91dc92022-12-21 21:19:00 -07005821 INIT_LIST_HEAD(&lrugen->pages[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005822
5823 lruvec->mm_state.seq = MIN_NR_GENS;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005824}
5825
5826#ifdef CONFIG_MEMCG
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005827
5828void lru_gen_init_pgdat(struct pglist_data *pgdat)
5829{
5830 int i, j;
5831
5832 spin_lock_init(&pgdat->memcg_lru.lock);
5833
5834 for (i = 0; i < MEMCG_NR_GENS; i++) {
5835 for (j = 0; j < MEMCG_NR_BINS; j++)
5836 INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i);
5837 }
5838}
5839
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005840void lru_gen_init_memcg(struct mem_cgroup *memcg)
5841{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005842 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5843 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005844}
5845
5846void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5847{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005848 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005849 int nid;
5850
5851 for_each_node(nid) {
5852 struct lruvec *lruvec = get_lruvec(memcg, nid);
5853
5854 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5855 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005856
5857 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5858 bitmap_free(lruvec->mm_state.filters[i]);
5859 lruvec->mm_state.filters[i] = NULL;
5860 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005861 }
5862}
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005863
5864void lru_gen_online_memcg(struct mem_cgroup *memcg)
5865{
5866 int gen;
5867 int nid;
5868 int bin = prandom_u32_max(MEMCG_NR_BINS);
5869
5870 for_each_node(nid) {
5871 struct pglist_data *pgdat = NODE_DATA(nid);
5872 struct lruvec *lruvec = get_lruvec(memcg, nid);
5873
5874 spin_lock(&pgdat->memcg_lru.lock);
5875
5876 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
5877
5878 gen = get_memcg_gen(pgdat->memcg_lru.seq);
5879
5880 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
5881 pgdat->memcg_lru.nr_memcgs[gen]++;
5882
5883 lruvec->lrugen.gen = gen;
5884
5885 spin_unlock(&pgdat->memcg_lru.lock);
5886 }
5887}
5888
5889void lru_gen_offline_memcg(struct mem_cgroup *memcg)
5890{
5891 int nid;
5892
5893 for_each_node(nid) {
5894 struct lruvec *lruvec = get_lruvec(memcg, nid);
5895
5896 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
5897 }
5898}
5899
5900void lru_gen_release_memcg(struct mem_cgroup *memcg)
5901{
5902 int gen;
5903 int nid;
5904
5905 for_each_node(nid) {
5906 struct pglist_data *pgdat = NODE_DATA(nid);
5907 struct lruvec *lruvec = get_lruvec(memcg, nid);
5908
5909 spin_lock(&pgdat->memcg_lru.lock);
5910
5911 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
5912
5913 gen = lruvec->lrugen.gen;
5914
5915 hlist_nulls_del_rcu(&lruvec->lrugen.list);
5916 pgdat->memcg_lru.nr_memcgs[gen]--;
5917
5918 if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
5919 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
5920
5921 spin_unlock(&pgdat->memcg_lru.lock);
5922 }
5923}
5924
5925#endif /* CONFIG_MEMCG */
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005926
5927static int __init init_lru_gen(void)
5928{
5929 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5930 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5931
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005932 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5933 pr_err("lru_gen: failed to create sysfs group\n");
5934
Yu Zhao4983c522022-09-18 02:00:09 -06005935 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5936 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5937
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005938 return 0;
5939};
5940late_initcall(init_lru_gen);
5941
Yu Zhao37397872022-09-18 02:00:03 -06005942#else /* !CONFIG_LRU_GEN */
5943
5944static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5945{
5946}
5947
5948static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5949{
5950}
5951
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005952static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5953{
5954}
5955
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005956#endif /* CONFIG_LRU_GEN */
5957
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005958static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005959{
5960 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005961 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005962 unsigned long nr_to_scan;
5963 enum lru_list lru;
5964 unsigned long nr_reclaimed = 0;
5965 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005966 bool proportional_reclaim;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005967 struct blk_plug plug;
Minchan Kima8962f62022-11-02 09:04:41 -07005968 bool do_plug = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005969
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005970 if (lru_gen_enabled() && !global_reclaim(sc)) {
Yu Zhao37397872022-09-18 02:00:03 -06005971 lru_gen_shrink_lruvec(lruvec, sc);
5972 return;
5973 }
5974
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005975 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005976
Mel Gormane82e0562013-07-03 15:01:44 -07005977 /* Record the original scan target for proportional adjustments later */
5978 memcpy(targets, nr, sizeof(nr));
5979
Mel Gorman1a501902014-06-04 16:10:49 -07005980 /*
5981 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5982 * event that can occur when there is little memory pressure e.g.
5983 * multiple streaming readers/writers. Hence, we do not abort scanning
5984 * when the requested number of pages are reclaimed when scanning at
5985 * DEF_PRIORITY on the assumption that the fact we are direct
5986 * reclaiming implies that kswapd is not keeping up and it is best to
5987 * do a batch of work at once. For memcg reclaim one check is made to
5988 * abort proportional reclaim if either the file or anon lru has already
5989 * dropped to zero at the first pass.
5990 */
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005991 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5992 sc->priority == DEF_PRIORITY);
Mel Gorman1a501902014-06-04 16:10:49 -07005993
Minchan Kima8962f62022-11-02 09:04:41 -07005994 trace_android_vh_shrink_lruvec_blk_plug(&do_plug);
5995 if (do_plug)
5996 blk_start_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005997 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5998 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005999 unsigned long nr_anon, nr_file, percentage;
6000 unsigned long nr_scanned;
6001
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006002 for_each_evictable_lru(lru) {
6003 if (nr[lru]) {
6004 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
6005 nr[lru] -= nr_to_scan;
6006
6007 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07006008 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006009 }
6010 }
Mel Gormane82e0562013-07-03 15:01:44 -07006011
Michal Hockobd041732016-12-02 17:26:48 -08006012 cond_resched();
6013
Johannes Weiner7b3c9402022-08-02 12:28:11 -04006014 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
Mel Gormane82e0562013-07-03 15:01:44 -07006015 continue;
6016
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006017 /*
Mel Gormane82e0562013-07-03 15:01:44 -07006018 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07006019 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07006020 * proportionally what was requested by get_scan_count(). We
6021 * stop reclaiming one LRU and reduce the amount scanning
6022 * proportional to the original scan target.
6023 */
6024 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
6025 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
6026
Mel Gorman1a501902014-06-04 16:10:49 -07006027 /*
6028 * It's just vindictive to attack the larger once the smaller
6029 * has gone to zero. And given the way we stop scanning the
6030 * smaller below, this makes sure that we only make one nudge
6031 * towards proportionality once we've got nr_to_reclaim.
6032 */
6033 if (!nr_file || !nr_anon)
6034 break;
6035
Mel Gormane82e0562013-07-03 15:01:44 -07006036 if (nr_file > nr_anon) {
6037 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
6038 targets[LRU_ACTIVE_ANON] + 1;
6039 lru = LRU_BASE;
6040 percentage = nr_anon * 100 / scan_target;
6041 } else {
6042 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
6043 targets[LRU_ACTIVE_FILE] + 1;
6044 lru = LRU_FILE;
6045 percentage = nr_file * 100 / scan_target;
6046 }
6047
6048 /* Stop scanning the smaller of the LRU */
6049 nr[lru] = 0;
6050 nr[lru + LRU_ACTIVE] = 0;
6051
6052 /*
6053 * Recalculate the other LRU scan count based on its original
6054 * scan target and the percentage scanning already complete
6055 */
6056 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
6057 nr_scanned = targets[lru] - nr[lru];
6058 nr[lru] = targets[lru] * (100 - percentage) / 100;
6059 nr[lru] -= min(nr[lru], nr_scanned);
6060
6061 lru += LRU_ACTIVE;
6062 nr_scanned = targets[lru] - nr[lru];
6063 nr[lru] = targets[lru] * (100 - percentage) / 100;
6064 nr[lru] -= min(nr[lru], nr_scanned);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006065 }
Minchan Kima8962f62022-11-02 09:04:41 -07006066 if (do_plug)
6067 blk_finish_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006068 sc->nr_reclaimed += nr_reclaimed;
6069
6070 /*
6071 * Even if we did not try to evict anon pages at all, we want to
6072 * rebalance the anon lru active/inactive ratio.
6073 */
Dave Hansen2f368a92021-09-02 14:59:23 -07006074 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
6075 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006076 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6077 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006078}
6079
Mel Gorman23b9da52012-05-29 15:06:20 -07006080/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006081static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07006082{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08006083 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07006084 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006085 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07006086 return true;
6087
6088 return false;
6089}
6090
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006091/*
Mel Gorman23b9da52012-05-29 15:06:20 -07006092 * Reclaim/compaction is used for high-order allocation requests. It reclaims
6093 * order-0 pages before compacting the zone. should_continue_reclaim() returns
6094 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07006095 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07006096 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08006097 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006098static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08006099 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08006100 struct scan_control *sc)
6101{
6102 unsigned long pages_for_compaction;
6103 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07006104 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006105
6106 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006107 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08006108 return false;
6109
Vlastimil Babka5ee04712019-09-23 15:37:29 -07006110 /*
6111 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
6112 * number of pages that were scanned. This will return to the caller
6113 * with the risk reclaim/compaction and the resulting allocation attempt
6114 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
6115 * allocations through requiring that the full LRU list has been scanned
6116 * first, by assuming that zero delta of sc->nr_scanned means full LRU
6117 * scan, but that approximation was wrong, and there were corner cases
6118 * where always a non-zero amount of pages were scanned.
6119 */
6120 if (!nr_reclaimed)
6121 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006122
Mel Gorman3e7d3442011-01-13 15:45:56 -08006123 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006124 for (z = 0; z <= sc->reclaim_idx; z++) {
6125 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07006126 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07006127 continue;
6128
6129 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07006130 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07006131 case COMPACT_CONTINUE:
6132 return false;
6133 default:
6134 /* check next zone */
6135 ;
6136 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08006137 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07006138
6139 /*
6140 * If we have not reclaimed enough pages for compaction and the
6141 * inactive lists are large enough, continue reclaiming
6142 */
6143 pages_for_compaction = compact_gap(sc->order);
6144 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07006145 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07006146 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
6147
Vlastimil Babka5ee04712019-09-23 15:37:29 -07006148 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006149}
6150
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006151static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006152{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006153 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08006154 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006155
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006156 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08006157 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006158 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006159 unsigned long reclaimed;
6160 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08006161 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08006162
Xunlei Pange3336ca2020-09-04 16:35:27 -07006163 /*
6164 * This loop can become CPU-bound when target memcgs
6165 * aren't eligible for reclaim - either because they
6166 * don't have any reclaimable pages, or because their
6167 * memory is explicitly protected. Avoid soft lockups.
6168 */
6169 cond_resched();
6170
Liujie Xieb7ea1c42022-06-01 15:38:17 +08006171 trace_android_vh_shrink_node_memcgs(memcg, &skip);
6172 if (skip)
6173 continue;
6174
Chris Down45c7f7e2020-08-06 23:22:05 -07006175 mem_cgroup_calculate_protection(target_memcg, memcg);
6176
6177 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08006178 /*
6179 * Hard protection.
6180 * If there is no reclaimable memory, OOM.
6181 */
6182 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07006183 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08006184 /*
6185 * Soft protection.
6186 * Respect the protection only as long as
6187 * there is an unprotected supply
6188 * of reclaimable memory from other cgroups.
6189 */
6190 if (!sc->memcg_low_reclaim) {
6191 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006192 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006193 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08006194 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08006195 }
6196
Johannes Weinerd2af3392019-11-30 17:55:43 -08006197 reclaimed = sc->nr_reclaimed;
6198 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006199
6200 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006201
Johannes Weinerd2af3392019-11-30 17:55:43 -08006202 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
6203 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07006204
Johannes Weinerd2af3392019-11-30 17:55:43 -08006205 /* Record the group's reclaim efficiency */
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006206 if (!sc->proactive)
6207 vmpressure(sc->gfp_mask, memcg, false,
6208 sc->nr_scanned - scanned,
6209 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006210
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006211 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
6212}
6213
Liu Song6c9e09072020-01-30 22:14:08 -08006214static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006215{
6216 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006217 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08006218 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006219 bool reclaimable = false;
6220
Yu Zhaoa3eb6512022-12-21 21:19:04 -07006221 if (lru_gen_enabled() && global_reclaim(sc)) {
6222 lru_gen_shrink_node(pgdat, sc);
6223 return;
6224 }
6225
Johannes Weiner1b051172019-11-30 17:55:52 -08006226 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
6227
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006228again:
6229 memset(&sc->nr, 0, sizeof(sc->nr));
6230
6231 nr_reclaimed = sc->nr_reclaimed;
6232 nr_scanned = sc->nr_scanned;
6233
Yu Zhao6d313442022-09-18 02:00:00 -06006234 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08006235
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006236 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006237
Johannes Weinerd2af3392019-11-30 17:55:43 -08006238 if (reclaim_state) {
6239 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
6240 reclaim_state->reclaimed_slab = 0;
6241 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07006242
Johannes Weinerd2af3392019-11-30 17:55:43 -08006243 /* Record the subtree's reclaim efficiency */
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006244 if (!sc->proactive)
6245 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
6246 sc->nr_scanned - nr_scanned,
6247 sc->nr_reclaimed - nr_reclaimed);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006248
6249 if (sc->nr_reclaimed - nr_reclaimed)
6250 reclaimable = true;
6251
6252 if (current_is_kswapd()) {
6253 /*
6254 * If reclaim is isolating dirty pages under writeback,
6255 * it implies that the long-lived page allocation rate
6256 * is exceeding the page laundering rate. Either the
6257 * global limits are not being effective at throttling
6258 * processes due to the page distribution throughout
6259 * zones or there is heavy usage of a slow backing
6260 * device. The only option is to throttle from reclaim
6261 * context which is not ideal as there is no guarantee
6262 * the dirtying process is throttled in the same way
6263 * balance_dirty_pages() manages.
6264 *
6265 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6266 * count the number of pages under pages flagged for
6267 * immediate reclaim and stall if any are encountered
6268 * in the nr_immediate check below.
6269 */
6270 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
6271 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006272
Johannes Weinerd2af3392019-11-30 17:55:43 -08006273 /* Allow kswapd to start writing pages during reclaim.*/
6274 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
6275 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07006276
6277 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006278 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08006279 * reclaim and under writeback (nr_immediate), it
6280 * implies that pages are cycling through the LRU
6281 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07006282 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08006283 if (sc->nr.immediate)
6284 congestion_wait(BLK_RW_ASYNC, HZ/10);
6285 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07006286
Johannes Weinerd2af3392019-11-30 17:55:43 -08006287 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08006288 * Tag a node/memcg as congested if all the dirty pages
6289 * scanned were backed by a congested BDI and
6290 * wait_iff_congested will stall.
6291 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08006292 * Legacy memcg will stall in page writeback so avoid forcibly
6293 * stalling in wait_iff_congested().
6294 */
Johannes Weiner1b051172019-11-30 17:55:52 -08006295 if ((current_is_kswapd() ||
6296 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08006297 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08006298 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006299
6300 /*
6301 * Stall direct reclaim for IO completions if underlying BDIs
6302 * and node is congested. Allow kswapd to continue until it
6303 * starts encountering unqueued dirty pages or cycling through
6304 * the LRU too quickly.
6305 */
Johannes Weiner1b051172019-11-30 17:55:52 -08006306 if (!current_is_kswapd() && current_may_throttle() &&
6307 !sc->hibernation_mode &&
6308 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08006309 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
6310
6311 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
6312 sc))
6313 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07006314
Johannes Weinerc73322d2017-05-03 14:51:51 -07006315 /*
6316 * Kswapd gives up on balancing particular nodes after too
6317 * many failures to reclaim anything from them and goes to
6318 * sleep. On reclaim progress, reset the failure counter. A
6319 * successful direct reclaim run will revive a dormant kswapd.
6320 */
6321 if (reclaimable)
6322 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006323}
6324
Vlastimil Babka53853e22014-10-09 15:27:02 -07006325/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006326 * Returns true if compaction should go ahead for a costly-order request, or
6327 * the allocation would already succeed without compaction. Return false if we
6328 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07006329 */
Mel Gorman4f588332016-07-28 15:46:38 -07006330static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006331{
Mel Gorman31483b62016-07-28 15:45:46 -07006332 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006333 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006334
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006335 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6336 if (suitable == COMPACT_SUCCESS)
6337 /* Allocation should succeed already. Don't reclaim. */
6338 return true;
6339 if (suitable == COMPACT_SKIPPED)
6340 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006341 return false;
6342
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006343 /*
6344 * Compaction is already possible, but it takes time to run and there
6345 * are potentially other callers using the pages just freed. So proceed
6346 * with reclaim to make a buffer of free pages available to give
6347 * compaction a reasonable chance of completing and allocating the page.
6348 * Note that we won't actually reclaim the whole buffer in one attempt
6349 * as the target watermark in should_continue_reclaim() is lower. But if
6350 * we are already above the high+gap watermark, don't reclaim at all.
6351 */
6352 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6353
6354 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006355}
6356
Linus Torvalds1da177e2005-04-16 15:20:36 -07006357/*
6358 * This is the direct reclaim path, for page-allocating processes. We only
6359 * try to reclaim pages from zones which will satisfy the caller's allocation
6360 * request.
6361 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07006362 * If a zone is deemed to be full of pinned pages then just give it a light
6363 * scan then give up on it.
6364 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07006365static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006366{
Mel Gormandd1a2392008-04-28 02:12:17 -07006367 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07006368 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07006369 unsigned long nr_soft_reclaimed;
6370 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07006371 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07006372 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006373
Mel Gormancc715d92012-03-21 16:34:00 -07006374 /*
6375 * If the number of buffer_heads in the machine exceeds the maximum
6376 * allowed level, force direct reclaim to scan the highmem zone as
6377 * highmem pages could be pinning lowmem pages storing buffer_heads
6378 */
Weijie Yang619d0d762014-04-07 15:36:59 -07006379 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07006380 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07006381 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07006382 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07006383 }
Mel Gormancc715d92012-03-21 16:34:00 -07006384
Mel Gormand4debc62010-08-09 17:19:29 -07006385 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07006386 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07006387 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006388 * Take care memory controller reclaiming has small influence
6389 * to global LRU.
6390 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08006391 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04006392 if (!cpuset_zone_allowed(zone,
6393 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006394 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006395
Johannes Weiner0b064962014-08-06 16:06:12 -07006396 /*
6397 * If we already have plenty of memory free for
6398 * compaction in this zone, don't free any more.
6399 * Even though compaction is invoked for any
6400 * non-zero order, only frequent costly order
6401 * reclamation is disruptive enough to become a
6402 * noticeable problem, like transparent huge
6403 * page allocations.
6404 */
6405 if (IS_ENABLED(CONFIG_COMPACTION) &&
6406 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07006407 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07006408 sc->compaction_ready = true;
6409 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07006410 }
Johannes Weiner0b064962014-08-06 16:06:12 -07006411
Andrew Morton0608f432013-09-24 15:27:41 -07006412 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07006413 * Shrink each node in the zonelist once. If the
6414 * zonelist is ordered by zone (not the default) then a
6415 * node may be shrunk multiple times but in that case
6416 * the user prefers lower zones being preserved.
6417 */
6418 if (zone->zone_pgdat == last_pgdat)
6419 continue;
6420
6421 /*
Andrew Morton0608f432013-09-24 15:27:41 -07006422 * This steals pages from memory cgroups over softlimit
6423 * and returns the number of reclaimed pages and
6424 * scanned pages. This works for global memory pressure
6425 * and balancing, not for a memcg's limit.
6426 */
6427 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006428 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006429 sc->order, sc->gfp_mask,
6430 &nr_soft_scanned);
6431 sc->nr_reclaimed += nr_soft_reclaimed;
6432 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006433 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006434 }
Nick Piggin408d8542006-09-25 23:31:27 -07006435
Mel Gorman79dafcd2016-07-28 15:45:53 -07006436 /* See comment about same check for global reclaim above */
6437 if (zone->zone_pgdat == last_pgdat)
6438 continue;
6439 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006440 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006441 }
Mel Gormane0c23272011-10-31 17:09:33 -07006442
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006443 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006444 * Restore to original mask to avoid the impact on the caller if we
6445 * promoted it to __GFP_HIGHMEM.
6446 */
6447 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006448}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006449
Johannes Weinerb9107182019-11-30 17:55:59 -08006450static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006451{
Johannes Weinerb9107182019-11-30 17:55:59 -08006452 struct lruvec *target_lruvec;
6453 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006454
Yu Zhao37397872022-09-18 02:00:03 -06006455 if (lru_gen_enabled())
6456 return;
6457
Johannes Weinerb9107182019-11-30 17:55:59 -08006458 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006459 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6460 target_lruvec->refaults[0] = refaults;
6461 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6462 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006463}
6464
Linus Torvalds1da177e2005-04-16 15:20:36 -07006465/*
6466 * This is the main entry point to direct page reclaim.
6467 *
6468 * If a full scan of the inactive list fails to free enough memory then we
6469 * are "out of memory" and something needs to be killed.
6470 *
6471 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6472 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006473 * caller can't do much about. We kick the writeback threads and take explicit
6474 * naps in the hope that some of these pages can be written. But if the
6475 * allocating task holds filesystem locks which prevent writeout this might not
6476 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006477 *
6478 * returns: 0, if no pages reclaimed
6479 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006480 */
Mel Gormandac1d272008-04-28 02:12:12 -07006481static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006482 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006483{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006484 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006485 pg_data_t *last_pgdat;
6486 struct zoneref *z;
6487 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006488retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006489 delayacct_freepages_start();
6490
Johannes Weinerb5ead352019-11-30 17:55:40 -08006491 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006492 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006493
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006494 do {
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006495 if (!sc->proactive)
6496 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6497 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006498 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006499 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006500
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006501 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006502 break;
6503
6504 if (sc->compaction_ready)
6505 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006506
6507 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006508 * If we're getting trouble reclaiming, start doing
6509 * writepage even in laptop mode.
6510 */
6511 if (sc->priority < DEF_PRIORITY - 2)
6512 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006513 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006514
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006515 last_pgdat = NULL;
6516 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6517 sc->nodemask) {
6518 if (zone->zone_pgdat == last_pgdat)
6519 continue;
6520 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006521
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006522 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006523
6524 if (cgroup_reclaim(sc)) {
6525 struct lruvec *lruvec;
6526
6527 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6528 zone->zone_pgdat);
6529 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6530 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006531 }
6532
Keika Kobayashi873b4772008-07-25 01:48:52 -07006533 delayacct_freepages_end();
6534
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006535 if (sc->nr_reclaimed)
6536 return sc->nr_reclaimed;
6537
Mel Gorman0cee34f2012-01-12 17:19:49 -08006538 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006539 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006540 return 1;
6541
Johannes Weinerb91ac372019-11-30 17:56:02 -08006542 /*
6543 * We make inactive:active ratio decisions based on the node's
6544 * composition of memory, but a restrictive reclaim_idx or a
6545 * memory.low cgroup setting can exempt large amounts of
6546 * memory from reclaim. Neither of which are very common, so
6547 * instead of doing costly eligibility calculations of the
6548 * entire cgroup subtree up front, we assume the estimates are
6549 * good, and retry with forcible deactivation if that fails.
6550 */
6551 if (sc->skipped_deactivate) {
6552 sc->priority = initial_priority;
6553 sc->force_deactivate = 1;
6554 sc->skipped_deactivate = 0;
6555 goto retry;
6556 }
6557
Johannes Weiner241994ed2015-02-11 15:26:06 -08006558 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006559 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006560 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006561 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006562 sc->memcg_low_reclaim = 1;
6563 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006564 goto retry;
6565 }
6566
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006567 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006568}
6569
Johannes Weinerc73322d2017-05-03 14:51:51 -07006570static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006571{
6572 struct zone *zone;
6573 unsigned long pfmemalloc_reserve = 0;
6574 unsigned long free_pages = 0;
6575 int i;
6576 bool wmark_ok;
6577
Johannes Weinerc73322d2017-05-03 14:51:51 -07006578 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6579 return true;
6580
Mel Gorman55150612012-07-31 16:44:35 -07006581 for (i = 0; i <= ZONE_NORMAL; i++) {
6582 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006583 if (!managed_zone(zone))
6584 continue;
6585
6586 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006587 continue;
6588
Mel Gorman55150612012-07-31 16:44:35 -07006589 pfmemalloc_reserve += min_wmark_pages(zone);
6590 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6591 }
6592
Mel Gorman675becc2014-06-04 16:07:35 -07006593 /* If there are no reserves (unexpected config) then do not throttle */
6594 if (!pfmemalloc_reserve)
6595 return true;
6596
Mel Gorman55150612012-07-31 16:44:35 -07006597 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6598
6599 /* kswapd must be awake if processes are being throttled */
6600 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006601 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6602 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006603
Mel Gorman55150612012-07-31 16:44:35 -07006604 wake_up_interruptible(&pgdat->kswapd_wait);
6605 }
6606
6607 return wmark_ok;
6608}
6609
6610/*
6611 * Throttle direct reclaimers if backing storage is backed by the network
6612 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6613 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006614 * when the low watermark is reached.
6615 *
6616 * Returns true if a fatal signal was delivered during throttling. If this
6617 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006618 */
Mel Gorman50694c22012-11-26 16:29:48 -08006619static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006620 nodemask_t *nodemask)
6621{
Mel Gorman675becc2014-06-04 16:07:35 -07006622 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006623 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006624 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006625
6626 /*
6627 * Kernel threads should not be throttled as they may be indirectly
6628 * responsible for cleaning pages necessary for reclaim to make forward
6629 * progress. kjournald for example may enter direct reclaim while
6630 * committing a transaction where throttling it could forcing other
6631 * processes to block on log_wait_commit().
6632 */
6633 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006634 goto out;
6635
6636 /*
6637 * If a fatal signal is pending, this process should not throttle.
6638 * It should return quickly so it can exit and free its memory
6639 */
6640 if (fatal_signal_pending(current))
6641 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006642
Mel Gorman675becc2014-06-04 16:07:35 -07006643 /*
6644 * Check if the pfmemalloc reserves are ok by finding the first node
6645 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6646 * GFP_KERNEL will be required for allocating network buffers when
6647 * swapping over the network so ZONE_HIGHMEM is unusable.
6648 *
6649 * Throttling is based on the first usable node and throttled processes
6650 * wait on a queue until kswapd makes progress and wakes them. There
6651 * is an affinity then between processes waking up and where reclaim
6652 * progress has been made assuming the process wakes on the same node.
6653 * More importantly, processes running on remote nodes will not compete
6654 * for remote pfmemalloc reserves and processes on different nodes
6655 * should make reasonable progress.
6656 */
6657 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006658 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006659 if (zone_idx(zone) > ZONE_NORMAL)
6660 continue;
6661
6662 /* Throttle based on the first usable node */
6663 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006664 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006665 goto out;
6666 break;
6667 }
6668
6669 /* If no zone was usable by the allocation flags then do not throttle */
6670 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006671 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006672
Mel Gorman68243e72012-07-31 16:44:39 -07006673 /* Account for the throttling */
6674 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6675
Mel Gorman55150612012-07-31 16:44:35 -07006676 /*
6677 * If the caller cannot enter the filesystem, it's possible that it
6678 * is due to the caller holding an FS lock or performing a journal
6679 * transaction in the case of a filesystem like ext[3|4]. In this case,
6680 * it is not safe to block on pfmemalloc_wait as kswapd could be
6681 * blocked waiting on the same lock. Instead, throttle for up to a
6682 * second before continuing.
6683 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006684 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006685 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006686 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006687 else
6688 /* Throttle until kswapd wakes the process */
6689 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6690 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006691
Mel Gorman50694c22012-11-26 16:29:48 -08006692 if (fatal_signal_pending(current))
6693 return true;
6694
6695out:
6696 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006697}
6698
Mel Gormandac1d272008-04-28 02:12:12 -07006699unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006700 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006701{
Mel Gorman33906bc2010-08-09 17:19:16 -07006702 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006703 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006704 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006705 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006706 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006707 .order = order,
6708 .nodemask = nodemask,
6709 .priority = DEF_PRIORITY,
6710 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006711 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006712 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006713 };
6714
Mel Gorman55150612012-07-31 16:44:35 -07006715 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006716 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6717 * Confirm they are large enough for max values.
6718 */
6719 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6720 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6721 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6722
6723 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006724 * Do not enter reclaim if fatal signal was delivered while throttled.
6725 * 1 is returned so that the page allocator does not OOM kill at this
6726 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006727 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006728 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006729 return 1;
6730
Andrew Morton1732d2b012019-07-16 16:26:15 -07006731 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006732 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006733
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006734 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006735
6736 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006737 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006738
6739 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006740}
6741
Andrew Mortonc255a452012-07-31 16:43:02 -07006742#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006743
Michal Hockod2e5fb92019-08-30 16:04:50 -07006744/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006745unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006746 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006747 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006748 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006749{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006750 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006751 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006752 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006753 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006754 .may_writepage = !laptop_mode,
6755 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006756 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006757 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006758 };
Ying Han0ae5e892011-05-26 16:25:25 -07006759
Michal Hockod2e5fb92019-08-30 16:04:50 -07006760 WARN_ON_ONCE(!current->reclaim_state);
6761
Balbir Singh4e416952009-09-23 15:56:39 -07006762 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6763 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006764
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006765 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006766 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006767
Balbir Singh4e416952009-09-23 15:56:39 -07006768 /*
6769 * NOTE: Although we can get the priority field, using it
6770 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006771 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006772 * will pick up pages from other mem cgroup's as well. We hack
6773 * the priority and make it zero.
6774 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006775 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006776
6777 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6778
Ying Han0ae5e892011-05-26 16:25:25 -07006779 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006780
Balbir Singh4e416952009-09-23 15:56:39 -07006781 return sc.nr_reclaimed;
6782}
6783
Johannes Weiner72835c82012-01-12 17:18:32 -08006784unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006785 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006786 gfp_t gfp_mask,
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006787 unsigned int reclaim_options)
Balbir Singh66e17072008-02-07 00:13:56 -08006788{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006789 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006790 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006791 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006792 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006793 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006794 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006795 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006796 .target_mem_cgroup = memcg,
6797 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006798 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006799 .may_unmap = 1,
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006800 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
6801 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
Ying Hana09ed5e2011-05-24 17:12:26 -07006802 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006803 /*
6804 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6805 * equal pressure on all the nodes. This is based on the assumption that
6806 * the reclaim does not bail out early.
6807 */
6808 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006809
Andrew Morton1732d2b012019-07-16 16:26:15 -07006810 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006811 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006812 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006813
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006814 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006815
Vlastimil Babka499118e2017-05-08 15:59:50 -07006816 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006817 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006818 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006819
6820 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006821}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006822EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006823#endif
6824
Yu Zhao37397872022-09-18 02:00:03 -06006825static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006826{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006827 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006828 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006829
Yu Zhao37397872022-09-18 02:00:03 -06006830 if (lru_gen_enabled()) {
6831 lru_gen_age_node(pgdat, sc);
6832 return;
6833 }
6834
Dave Hansen2f368a92021-09-02 14:59:23 -07006835 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006836 return;
6837
Johannes Weinerb91ac372019-11-30 17:56:02 -08006838 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6839 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6840 return;
6841
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006842 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6843 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006844 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6845 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6846 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006847 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6848 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006849}
6850
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006851static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006852{
6853 int i;
6854 struct zone *zone;
6855
6856 /*
6857 * Check for watermark boosts top-down as the higher zones
6858 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006859 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006860 * start prematurely when there is no boosting and a lower
6861 * zone is balanced.
6862 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006863 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006864 zone = pgdat->node_zones + i;
6865 if (!managed_zone(zone))
6866 continue;
6867
6868 if (zone->watermark_boost)
6869 return true;
6870 }
6871
6872 return false;
6873}
6874
Mel Gormane716f2e2017-05-03 14:53:45 -07006875/*
6876 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006877 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006878 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006879static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006880{
Mel Gormane716f2e2017-05-03 14:53:45 -07006881 int i;
6882 unsigned long mark = -1;
6883 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006884
Mel Gorman1c308442018-12-28 00:35:52 -08006885 /*
6886 * Check watermarks bottom-up as lower zones are more likely to
6887 * meet watermarks.
6888 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006889 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006890 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006891
Mel Gormane716f2e2017-05-03 14:53:45 -07006892 if (!managed_zone(zone))
6893 continue;
6894
6895 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006896 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006897 return true;
6898 }
6899
6900 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006901 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006902 * need balancing by definition. This can happen if a zone-restricted
6903 * allocation tries to wake a remote kswapd.
6904 */
6905 if (mark == -1)
6906 return true;
6907
6908 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006909}
6910
Mel Gorman631b6e02017-05-03 14:53:41 -07006911/* Clear pgdat state for congested, dirty or under writeback. */
6912static void clear_pgdat_congested(pg_data_t *pgdat)
6913{
Johannes Weiner1b051172019-11-30 17:55:52 -08006914 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6915
6916 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006917 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6918 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6919}
6920
Mel Gorman1741c872011-01-13 15:46:21 -08006921/*
Mel Gorman55150612012-07-31 16:44:35 -07006922 * Prepare kswapd for sleeping. This verifies that there are no processes
6923 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6924 *
6925 * Returns true if kswapd is ready to sleep
6926 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006927static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6928 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006929{
Mel Gorman55150612012-07-31 16:44:35 -07006930 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006931 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006932 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006933 * race between when kswapd checks the watermarks and a process gets
6934 * throttled. There is also a potential race if processes get
6935 * throttled, kswapd wakes, a large process exits thereby balancing the
6936 * zones, which causes kswapd to exit balance_pgdat() before reaching
6937 * the wake up checks. If kswapd is going to sleep, no process should
6938 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6939 * the wake up is premature, processes will wake kswapd and get
6940 * throttled again. The difference from wake ups in balance_pgdat() is
6941 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006942 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006943 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6944 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006945
Johannes Weinerc73322d2017-05-03 14:51:51 -07006946 /* Hopeless node, leave it to direct reclaim */
6947 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6948 return true;
6949
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006950 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006951 clear_pgdat_congested(pgdat);
6952 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006953 }
6954
Shantanu Goel333b0a42017-05-03 14:53:38 -07006955 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006956}
6957
Linus Torvalds1da177e2005-04-16 15:20:36 -07006958/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006959 * kswapd shrinks a node of pages that are at or below the highest usable
6960 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006961 *
6962 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006963 * reclaim or if the lack of progress was due to pages under writeback.
6964 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006965 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006966static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006967 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006968{
Mel Gorman1d82de62016-07-28 15:45:43 -07006969 struct zone *zone;
6970 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006971
Mel Gorman1d82de62016-07-28 15:45:43 -07006972 /* Reclaim a number of pages proportional to the number of zones */
6973 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006974 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006975 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006976 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006977 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006978
Mel Gorman1d82de62016-07-28 15:45:43 -07006979 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006980 }
6981
Mel Gorman1d82de62016-07-28 15:45:43 -07006982 /*
6983 * Historically care was taken to put equal pressure on all zones but
6984 * now pressure is applied based on node LRU order.
6985 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006986 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006987
6988 /*
6989 * Fragmentation may mean that the system cannot be rebalanced for
6990 * high-order allocations. If twice the allocation size has been
6991 * reclaimed then recheck watermarks only at order-0 to prevent
6992 * excessive reclaim. Assume that a process requested a high-order
6993 * can direct reclaim/compact.
6994 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006995 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006996 sc->order = 0;
6997
Mel Gormanb8e83b92013-07-03 15:01:45 -07006998 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006999}
7000
Mel Gormanc49c2c42021-06-28 19:42:21 -07007001/* Page allocator PCP high watermark is lowered if reclaim is active. */
7002static inline void
7003update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
7004{
7005 int i;
7006 struct zone *zone;
7007
7008 for (i = 0; i <= highest_zoneidx; i++) {
7009 zone = pgdat->node_zones + i;
7010
7011 if (!managed_zone(zone))
7012 continue;
7013
7014 if (active)
7015 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7016 else
7017 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7018 }
7019}
7020
7021static inline void
7022set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7023{
7024 update_reclaim_active(pgdat, highest_zoneidx, true);
7025}
7026
7027static inline void
7028clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7029{
7030 update_reclaim_active(pgdat, highest_zoneidx, false);
7031}
7032
Mel Gorman75485362013-07-03 15:01:42 -07007033/*
Mel Gorman1d82de62016-07-28 15:45:43 -07007034 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
7035 * that are eligible for use by the caller until at least one zone is
7036 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007037 *
Mel Gorman1d82de62016-07-28 15:45:43 -07007038 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007039 *
7040 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07007041 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08007042 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07007043 * or lower is eligible for reclaim until at least one usable zone is
7044 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007045 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007046static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007047{
Linus Torvalds1da177e2005-04-16 15:20:36 -07007048 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07007049 unsigned long nr_soft_reclaimed;
7050 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07007051 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08007052 unsigned long nr_boost_reclaim;
7053 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
7054 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07007055 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08007056 struct scan_control sc = {
7057 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07007058 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07007059 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08007060 };
Omar Sandoval93781322018-06-07 17:07:02 -07007061
Andrew Morton1732d2b012019-07-16 16:26:15 -07007062 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07007063 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007064 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007065
Christoph Lameterf8891e52006-06-30 01:55:45 -07007066 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007067
Mel Gorman1c308442018-12-28 00:35:52 -08007068 /*
7069 * Account for the reclaim boost. Note that the zone boost is left in
7070 * place so that parallel allocations that are near the watermark will
7071 * stall or direct reclaim until kswapd is finished.
7072 */
7073 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007074 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08007075 zone = pgdat->node_zones + i;
7076 if (!managed_zone(zone))
7077 continue;
7078
7079 nr_boost_reclaim += zone->watermark_boost;
7080 zone_boosts[i] = zone->watermark_boost;
7081 }
7082 boosted = nr_boost_reclaim;
7083
7084restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07007085 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007086 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007087 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07007088 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07007089 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08007090 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07007091 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07007092
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007093 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007094
Mel Gorman86c79f62016-07-28 15:45:59 -07007095 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07007096 * If the number of buffer_heads exceeds the maximum allowed
7097 * then consider reclaiming from all zones. This has a dual
7098 * purpose -- on 64-bit systems it is expected that
7099 * buffer_heads are stripped during active rotation. On 32-bit
7100 * systems, highmem pages can pin lowmem memory and shrinking
7101 * buffers can relieve lowmem pressure. Reclaim may still not
7102 * go ahead if all eligible zones for the original allocation
7103 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07007104 */
7105 if (buffer_heads_over_limit) {
7106 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
7107 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07007108 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07007109 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007110
Mel Gorman970a39a2016-07-28 15:46:35 -07007111 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08007112 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007113 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07007114 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08007115
Mel Gorman86c79f62016-07-28 15:45:59 -07007116 /*
Mel Gorman1c308442018-12-28 00:35:52 -08007117 * If the pgdat is imbalanced then ignore boosting and preserve
7118 * the watermarks for a later time and restart. Note that the
7119 * zone watermarks will be still reset at the end of balancing
7120 * on the grounds that the normal reclaim should be enough to
7121 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07007122 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007123 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007124 if (!balanced && nr_boost_reclaim) {
7125 nr_boost_reclaim = 0;
7126 goto restart;
7127 }
7128
7129 /*
7130 * If boosting is not active then only reclaim if there are no
7131 * eligible zones. Note that sc.reclaim_idx is not used as
7132 * buffer_heads_over_limit may have adjusted it.
7133 */
7134 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07007135 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08007136
Mel Gorman1c308442018-12-28 00:35:52 -08007137 /* Limit the priority of boosting to avoid reclaim writeback */
7138 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
7139 raise_priority = false;
7140
7141 /*
7142 * Do not writeback or swap pages for boosted reclaim. The
7143 * intent is to relieve pressure not issue sub-optimal IO
7144 * from reclaim context. If no pages are reclaimed, the
7145 * reclaim will be aborted.
7146 */
7147 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
7148 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08007149
Linus Torvalds1da177e2005-04-16 15:20:36 -07007150 /*
Yu Zhao37397872022-09-18 02:00:03 -06007151 * Do some background aging, to give pages a chance to be
7152 * referenced before reclaiming. All pages are rotated
7153 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07007154 */
Yu Zhao37397872022-09-18 02:00:03 -06007155 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07007156
7157 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007158 * If we're getting trouble reclaiming, start doing writepage
7159 * even in laptop mode.
7160 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07007161 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007162 sc.may_writepage = 1;
7163
Mel Gorman1d82de62016-07-28 15:45:43 -07007164 /* Call soft limit reclaim before calling shrink_node. */
7165 sc.nr_scanned = 0;
7166 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07007167 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07007168 sc.gfp_mask, &nr_soft_scanned);
7169 sc.nr_reclaimed += nr_soft_reclaimed;
7170
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007171 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07007172 * There should be no need to raise the scanning priority if
7173 * enough pages are already being scanned that that high
7174 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007175 */
Mel Gorman970a39a2016-07-28 15:46:35 -07007176 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07007177 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07007178
7179 /*
7180 * If the low watermark is met there is no need for processes
7181 * to be throttled on pfmemalloc_wait as they should not be
7182 * able to safely make forward progress. Wake them
7183 */
7184 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07007185 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08007186 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07007187
Mel Gormanb8e83b92013-07-03 15:01:45 -07007188 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007189 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007190 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007191 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007192 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07007193 break;
7194
7195 /*
7196 * Raise priority if scanning rate is too low or there was no
7197 * progress in reclaiming pages
7198 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07007199 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08007200 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
7201
7202 /*
7203 * If reclaim made no progress for a boost, stop reclaim as
7204 * IO cannot be queued and it could be an infinite loop in
7205 * extreme circumstances.
7206 */
7207 if (nr_boost_reclaim && !nr_reclaimed)
7208 break;
7209
Johannes Weinerc73322d2017-05-03 14:51:51 -07007210 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07007211 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07007212 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007213
Johannes Weinerc73322d2017-05-03 14:51:51 -07007214 if (!sc.nr_reclaimed)
7215 pgdat->kswapd_failures++;
7216
Mel Gormanb8e83b92013-07-03 15:01:45 -07007217out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07007218 clear_reclaim_active(pgdat, highest_zoneidx);
7219
Mel Gorman1c308442018-12-28 00:35:52 -08007220 /* If reclaim was boosted, account for the reclaim done in this pass */
7221 if (boosted) {
7222 unsigned long flags;
7223
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007224 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08007225 if (!zone_boosts[i])
7226 continue;
7227
7228 /* Increments are under the zone lock */
7229 zone = pgdat->node_zones + i;
7230 spin_lock_irqsave(&zone->lock, flags);
7231 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7232 spin_unlock_irqrestore(&zone->lock, flags);
7233 }
7234
7235 /*
7236 * As there is now likely space, wakeup kcompact to defragment
7237 * pageblocks.
7238 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007239 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007240 }
7241
Johannes Weiner2a2e4882017-05-03 14:55:03 -07007242 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007243 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07007244 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07007245 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07007246
Mel Gorman0abdee22011-01-13 15:46:22 -08007247 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07007248 * Return the order kswapd stopped reclaiming at as
7249 * prepare_kswapd_sleep() takes it into account. If another caller
7250 * entered the allocator slow path while kswapd was awake, order will
7251 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08007252 */
Mel Gorman1d82de62016-07-28 15:45:43 -07007253 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007254}
7255
Mel Gormane716f2e2017-05-03 14:53:45 -07007256/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007257 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7258 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7259 * not a valid index then either kswapd runs for first time or kswapd couldn't
7260 * sleep after previous reclaim attempt (node is still unbalanced). In that
7261 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07007262 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007263static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7264 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07007265{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007266 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007267
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007268 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07007269}
7270
Mel Gorman38087d92016-07-28 15:45:49 -07007271static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007272 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007273{
7274 long remaining = 0;
7275 DEFINE_WAIT(wait);
7276
7277 if (freezing(current) || kthread_should_stop())
7278 return;
7279
7280 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7281
Shantanu Goel333b0a42017-05-03 14:53:38 -07007282 /*
7283 * Try to sleep for a short interval. Note that kcompactd will only be
7284 * woken if it is possible to sleep for a short interval. This is
7285 * deliberate on the assumption that if reclaim cannot keep an
7286 * eligible zone balanced that it's also unlikely that compaction will
7287 * succeed.
7288 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007289 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07007290 /*
7291 * Compaction records what page blocks it recently failed to
7292 * isolate pages from and skips them in the future scanning.
7293 * When kswapd is going to sleep, it is reasonable to assume
7294 * that pages and compaction may succeed so reset the cache.
7295 */
7296 reset_isolation_suitable(pgdat);
7297
7298 /*
7299 * We have freed the memory, now we should compact it to make
7300 * allocation of the requested order possible.
7301 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007302 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07007303
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007304 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07007305
7306 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007307 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07007308 * order. The values will either be from a wakeup request or
7309 * the previous request that slept prematurely.
7310 */
7311 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007312 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7313 kswapd_highest_zoneidx(pgdat,
7314 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07007315
7316 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7317 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07007318 }
7319
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007320 finish_wait(&pgdat->kswapd_wait, &wait);
7321 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7322 }
7323
7324 /*
7325 * After a short sleep, check if it was a premature sleep. If not, then
7326 * go fully to sleep until explicitly woken up.
7327 */
Mel Gormand9f21d42016-07-28 15:46:41 -07007328 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007329 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007330 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7331
7332 /*
7333 * vmstat counters are not perfectly accurate and the estimated
7334 * value for counters such as NR_FREE_PAGES can deviate from the
7335 * true value by nr_online_cpus * threshold. To avoid the zone
7336 * watermarks being breached while under pressure, we reduce the
7337 * per-cpu vmstat threshold while kswapd is awake and restore
7338 * them before going back to sleep.
7339 */
7340 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07007341
7342 if (!kthread_should_stop())
7343 schedule();
7344
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007345 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7346 } else {
7347 if (remaining)
7348 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7349 else
7350 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7351 }
7352 finish_wait(&pgdat->kswapd_wait, &wait);
7353}
7354
Linus Torvalds1da177e2005-04-16 15:20:36 -07007355/*
7356 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07007357 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007358 *
7359 * This basically trickles out pages so that we have _some_
7360 * free memory available even if there is no other activity
7361 * that frees anything up. This is needed for things like routing
7362 * etc, where we otherwise might have all activity going on in
7363 * asynchronous contexts that cannot page things out.
7364 *
7365 * If there are applications that are active memory-allocators
7366 * (most normal use), this basically shouldn't matter.
7367 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307368int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007369{
Mel Gormane716f2e2017-05-03 14:53:45 -07007370 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007371 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07007372 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007373 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10307374 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007375
Rusty Russell174596a2009-01-01 10:12:29 +10307376 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07007377 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007378
7379 /*
7380 * Tell the memory management that we're a "memory allocator",
7381 * and that if we need more memory we should get access to it
7382 * regardless (see "__alloc_pages()"). "kswapd" should
7383 * never get caught in the normal page freeing logic.
7384 *
7385 * (Kswapd normally doesn't need memory anyway, but sometimes
7386 * you need a small amount of memory in order to be able to
7387 * page out something else, and this flag essentially protects
7388 * us from recursively trying to free more memory as we're
7389 * trying to free the first piece of memory in the first place).
7390 */
Christoph Lameter930d9152006-01-08 01:00:47 -08007391 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07007392 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07007393
Qian Cai5644e1fb2020-04-01 21:10:12 -07007394 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007395 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007396 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08007397 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07007398
Qian Cai5644e1fb2020-04-01 21:10:12 -07007399 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007400 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7401 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07007402
Mel Gorman38087d92016-07-28 15:45:49 -07007403kswapd_try_sleep:
7404 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007405 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07007406
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007407 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08007408 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007409 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7410 highest_zoneidx);
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
David Rientjes8fe23e02009-12-14 17:58:33 -08007414 ret = try_to_freeze();
7415 if (kthread_should_stop())
7416 break;
7417
7418 /*
7419 * We can speed up thawing tasks if we don't call balance_pgdat
7420 * after returning from the refrigerator
7421 */
Mel Gorman38087d92016-07-28 15:45:49 -07007422 if (ret)
7423 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07007424
Mel Gorman38087d92016-07-28 15:45:49 -07007425 /*
7426 * Reclaim begins at the requested order but if a high-order
7427 * reclaim fails then kswapd falls back to reclaiming for
7428 * order-0. If that happens, kswapd will consider sleeping
7429 * for the order it finished reclaiming at (reclaim_order)
7430 * but kcompactd is woken to compact for the original
7431 * request (alloc_order).
7432 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007433 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007434 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007435 reclaim_order = balance_pgdat(pgdat, alloc_order,
7436 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007437 if (reclaim_order < alloc_order)
7438 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007439 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007440
Johannes Weiner71abdc12014-06-06 14:35:35 -07007441 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007442
Linus Torvalds1da177e2005-04-16 15:20:36 -07007443 return 0;
7444}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307445EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007446
7447/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007448 * A zone is low on free memory or too fragmented for high-order memory. If
7449 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7450 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7451 * has failed or is not needed, still wake up kcompactd if only compaction is
7452 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007453 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007454void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007455 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007456{
7457 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007458 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007459
Mel Gorman6aa303d2016-09-01 16:14:55 -07007460 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007461 return;
7462
David Rientjes5ecd9d42018-04-05 16:25:16 -07007463 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007464 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007465
Qian Cai5644e1fb2020-04-01 21:10:12 -07007466 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007467 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007468
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007469 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7470 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007471
7472 if (READ_ONCE(pgdat->kswapd_order) < order)
7473 WRITE_ONCE(pgdat->kswapd_order, order);
7474
Con Kolivas8d0986e2005-09-13 01:25:07 -07007475 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007476 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007477
David Rientjes5ecd9d42018-04-05 16:25:16 -07007478 /* Hopeless node, leave it to direct reclaim if possible */
7479 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007480 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7481 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007482 /*
7483 * There may be plenty of free memory available, but it's too
7484 * fragmented for high-order allocations. Wake up kcompactd
7485 * and rely on compaction_suitable() to determine if it's
7486 * needed. If it fails, it will defer subsequent attempts to
7487 * ratelimit its work.
7488 */
7489 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007490 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007491 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007492 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007493
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007494 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007495 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007496 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007497}
7498
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007499#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007500/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007501 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007502 * freed pages.
7503 *
7504 * Rather than trying to age LRUs the aim is to preserve the overall
7505 * LRU order by reclaiming preferentially
7506 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007507 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007508unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007509{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007510 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007511 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007512 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007513 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007514 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007515 .may_writepage = 1,
7516 .may_unmap = 1,
7517 .may_swap = 1,
7518 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007519 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007520 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007521 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007522 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007523
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007524 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007525 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007526 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007527
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007528 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007529
Andrew Morton1732d2b012019-07-16 16:26:15 -07007530 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007531 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007532 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007533
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007534 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007535}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007536#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007537
Yasunori Goto3218ae12006-06-27 02:53:33 -07007538/*
7539 * This kswapd start function will be called by init and node-hot-add.
7540 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7541 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007542void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007543{
7544 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307545 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007546
7547 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007548 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007549
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307550 trace_android_vh_kswapd_per_node(nid, &skip, true);
7551 if (skip)
7552 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007553 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7554 if (IS_ERR(pgdat->kswapd)) {
7555 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007556 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007557 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007558 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007559 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007560}
7561
David Rientjes8fe23e02009-12-14 17:58:33 -08007562/*
Jiang Liud8adde12012-07-11 14:01:52 -07007563 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007564 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007565 */
7566void kswapd_stop(int nid)
7567{
7568 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307569 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007570
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307571 trace_android_vh_kswapd_per_node(nid, &skip, false);
7572 if (skip)
7573 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007574 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007575 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007576 NODE_DATA(nid)->kswapd = NULL;
7577 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007578}
7579
Linus Torvalds1da177e2005-04-16 15:20:36 -07007580static int __init kswapd_init(void)
7581{
Wei Yang6b700b52020-04-01 21:10:09 -07007582 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007583
Linus Torvalds1da177e2005-04-16 15:20:36 -07007584 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007585 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007586 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007587 return 0;
7588}
7589
7590module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007591
7592#ifdef CONFIG_NUMA
7593/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007594 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007595 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007596 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007597 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007598 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007599int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007600
Dave Hansen51998362021-02-24 12:09:15 -08007601/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007602 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007603 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7604 * a zone.
7605 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007606#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007607
Christoph Lameter9eeff232006-01-18 17:42:31 -08007608/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007609 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007610 * occur.
7611 */
7612int sysctl_min_unmapped_ratio = 1;
7613
7614/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007615 * If the number of slab pages in a zone grows beyond this percentage then
7616 * slab reclaim needs to occur.
7617 */
7618int sysctl_min_slab_ratio = 5;
7619
Mel Gorman11fb9982016-07-28 15:46:20 -07007620static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007621{
Mel Gorman11fb9982016-07-28 15:46:20 -07007622 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7623 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7624 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007625
7626 /*
7627 * It's possible for there to be more file mapped pages than
7628 * accounted for by the pages on the file LRU lists because
7629 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7630 */
7631 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7632}
7633
7634/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007635static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007636{
Alexandru Moised031a152015-11-05 18:48:08 -08007637 unsigned long nr_pagecache_reclaimable;
7638 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007639
7640 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007641 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007642 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007643 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007644 * a better estimate
7645 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007646 if (node_reclaim_mode & RECLAIM_UNMAP)
7647 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007648 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007649 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007650
7651 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007652 if (!(node_reclaim_mode & RECLAIM_WRITE))
7653 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007654
7655 /* Watch for any possible underflows due to delta */
7656 if (unlikely(delta > nr_pagecache_reclaimable))
7657 delta = nr_pagecache_reclaimable;
7658
7659 return nr_pagecache_reclaimable - delta;
7660}
7661
Christoph Lameter0ff38492006-09-25 23:31:52 -07007662/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007663 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007664 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007665static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007666{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007667 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007668 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007669 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007670 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007671 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007672 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007673 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007674 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007675 .priority = NODE_RECLAIM_PRIORITY,
7676 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7677 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007678 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007679 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007680 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007681 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007682
Yafang Shao132bb8c2019-05-13 17:17:53 -07007683 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7684 sc.gfp_mask);
7685
Christoph Lameter9eeff232006-01-18 17:42:31 -08007686 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007687 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007688 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007689 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007690 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007691 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007692 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007693 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007694 noreclaim_flag = memalloc_noreclaim_save();
7695 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007696 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007697
Mel Gormana5f5f912016-07-28 15:46:32 -07007698 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007699 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007700 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007701 * priorities until we have enough memory freed.
7702 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007703 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007704 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007705 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007706 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007707
Andrew Morton1732d2b012019-07-16 16:26:15 -07007708 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007709 current->flags &= ~PF_SWAPWRITE;
7710 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007711 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007712 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007713
7714 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7715
Rik van Riela79311c2009-01-06 14:40:01 -08007716 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007717}
Andrew Morton179e9632006-03-22 00:08:18 -08007718
Mel Gormana5f5f912016-07-28 15:46:32 -07007719int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007720{
David Rientjesd773ed62007-10-16 23:26:01 -07007721 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007722
7723 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007724 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007725 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007726 *
Christoph Lameter96146342006-07-03 00:24:13 -07007727 * A small portion of unmapped file backed pages is needed for
7728 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007729 * thrown out if the node is overallocated. So we do not reclaim
7730 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007731 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007732 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007733 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007734 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7735 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007736 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007737
7738 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007739 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007740 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007741 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007742 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007743
7744 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007745 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007746 * have associated processors. This will favor the local processor
7747 * over remote processors and spread off node memory allocations
7748 * as wide as possible.
7749 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007750 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7751 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007752
Mel Gormana5f5f912016-07-28 15:46:32 -07007753 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7754 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007755
Mel Gormana5f5f912016-07-28 15:46:32 -07007756 ret = __node_reclaim(pgdat, gfp_mask, order);
7757 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007758
Mel Gorman24cf725182009-06-16 15:33:23 -07007759 if (!ret)
7760 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7761
David Rientjesd773ed62007-10-16 23:26:01 -07007762 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007763}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007764#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007765
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007766/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007767 * check_move_unevictable_pages - check pages for evictability and move to
7768 * appropriate zone lru list
7769 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007770 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007771 * Checks pages for evictability, if an evictable page is in the unevictable
7772 * lru list, moves it to the appropriate evictable lru list. This function
7773 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007774 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007775void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007776{
Alex Shi6168d0d2020-12-15 12:34:29 -08007777 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007778 int pgscanned = 0;
7779 int pgrescued = 0;
7780 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007781
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007782 for (i = 0; i < pvec->nr; i++) {
7783 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007784 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007785
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007786 if (PageTransTail(page))
7787 continue;
7788
7789 nr_pages = thp_nr_pages(page);
7790 pgscanned += nr_pages;
7791
Alex Shid25b5bd2020-12-15 12:34:16 -08007792 /* block memcg migration during page moving between lru */
7793 if (!TestClearPageLRU(page))
7794 continue;
7795
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007796 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007797 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007798 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007799 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007800 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007801 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007802 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007803 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007804 }
Hugh Dickins24513262012-01-20 14:34:21 -08007805
Alex Shi6168d0d2020-12-15 12:34:29 -08007806 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007807 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7808 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007809 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007810 } else if (pgscanned) {
7811 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007812 }
Hugh Dickins850465792012-01-20 14:34:19 -08007813}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007814EXPORT_SYMBOL_GPL(check_move_unevictable_pages);