blob: c5ab1e73339f0b8a3517d923144b36d351db977e [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001// SPDX-License-Identifier: GPL-2.0
Linus Torvalds1da177e2005-04-16 15:20:36 -07002/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07003 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
4 *
5 * Swap reorganised 29.12.95, Stephen Tweedie.
6 * kswapd added: 7.1.96 sct
7 * Removed kswapd_ctl limits, and swap out as many pages as needed
8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
10 * Multiqueue VM started 5.8.00, Rik van Riel.
11 */
12
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070013#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
Linus Torvalds1da177e2005-04-16 15:20:36 -070015#include <linux/mm.h>
Ingo Molnar5b3cc152017-02-02 20:43:54 +010016#include <linux/sched/mm.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070017#include <linux/module.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090018#include <linux/gfp.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070019#include <linux/kernel_stat.h>
20#include <linux/swap.h>
21#include <linux/pagemap.h>
22#include <linux/init.h>
23#include <linux/highmem.h>
Anton Vorontsov70ddf632013-04-29 15:08:31 -070024#include <linux/vmpressure.h>
Andrew Mortone129b5c2006-09-27 01:50:00 -070025#include <linux/vmstat.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070026#include <linux/file.h>
27#include <linux/writeback.h>
28#include <linux/blkdev.h>
29#include <linux/buffer_head.h> /* for try_to_release_page(),
30 buffer_heads_over_limit */
31#include <linux/mm_inline.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070032#include <linux/backing-dev.h>
33#include <linux/rmap.h>
34#include <linux/topology.h>
35#include <linux/cpu.h>
36#include <linux/cpuset.h>
Mel Gorman3e7d3442011-01-13 15:45:56 -080037#include <linux/compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070038#include <linux/notifier.h>
39#include <linux/rwsem.h>
Rafael J. Wysocki248a0302006-03-22 00:09:04 -080040#include <linux/delay.h>
Yasunori Goto3218ae12006-06-27 02:53:33 -070041#include <linux/kthread.h>
Nigel Cunningham7dfb7102006-12-06 20:34:23 -080042#include <linux/freezer.h>
Balbir Singh66e17072008-02-07 00:13:56 -080043#include <linux/memcontrol.h>
Dave Hansen26aa2d12021-09-02 14:59:16 -070044#include <linux/migrate.h>
Keika Kobayashi873b4772008-07-25 01:48:52 -070045#include <linux/delayacct.h>
Lee Schermerhornaf936a12008-10-18 20:26:53 -070046#include <linux/sysctl.h>
KOSAKI Motohiro929bea72011-04-14 15:22:12 -070047#include <linux/oom.h>
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +000048#include <linux/pagevec.h>
Linus Torvalds268bb0c2011-05-20 12:50:29 -070049#include <linux/prefetch.h>
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070050#include <linux/printk.h>
Ross Zwislerf9fe48b2016-01-22 15:10:40 -080051#include <linux/dax.h>
Johannes Weinereb414682018-10-26 15:06:27 -070052#include <linux/psi.h>
Yu Zhao7f53b0e2022-09-18 02:00:05 -060053#include <linux/pagewalk.h>
54#include <linux/shmem_fs.h>
Yu Zhaobaeb9a02022-09-18 02:00:07 -060055#include <linux/ctype.h>
Yu Zhao4983c522022-09-18 02:00:09 -060056#include <linux/debugfs.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070057
58#include <asm/tlbflush.h>
59#include <asm/div64.h>
60
61#include <linux/swapops.h>
Rafael Aquini117aad12013-09-30 13:45:16 -070062#include <linux/balloon_compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070063
Nick Piggin0f8053a2006-03-22 00:08:33 -080064#include "internal.h"
65
Mel Gorman33906bc2010-08-09 17:19:16 -070066#define CREATE_TRACE_POINTS
67#include <trace/events/vmscan.h>
68
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -070069#undef CREATE_TRACE_POINTS
70#include <trace/hooks/vmscan.h>
71
Minchan Kim7df45e52022-10-27 08:29:17 -070072#undef CREATE_TRACE_POINTS
73#include <trace/hooks/mm.h>
74
Martin Liud705ab992021-06-23 12:20:18 +080075EXPORT_TRACEPOINT_SYMBOL_GPL(mm_vmscan_direct_reclaim_begin);
76EXPORT_TRACEPOINT_SYMBOL_GPL(mm_vmscan_direct_reclaim_end);
77
Linus Torvalds1da177e2005-04-16 15:20:36 -070078struct scan_control {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -080079 /* How many pages shrink_list() should reclaim */
80 unsigned long nr_to_reclaim;
81
Johannes Weineree814fe2014-08-06 16:06:19 -070082 /*
83 * Nodemask of nodes allowed by the caller. If NULL, all nodes
84 * are scanned.
85 */
86 nodemask_t *nodemask;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -070087
KOSAKI Motohiro5f53e762010-05-24 14:32:37 -070088 /*
Johannes Weinerf16015f2012-01-12 17:17:52 -080089 * The memory cgroup that hit its limit and as a result is the
90 * primary target of this reclaim invocation.
91 */
92 struct mem_cgroup *target_mem_cgroup;
Balbir Singh66e17072008-02-07 00:13:56 -080093
Johannes Weiner7cf111b2020-06-03 16:03:06 -070094 /*
95 * Scan pressure balancing between anon and file LRUs
96 */
97 unsigned long anon_cost;
98 unsigned long file_cost;
99
Johannes Weinerb91ac372019-11-30 17:56:02 -0800100 /* Can active pages be deactivated as part of reclaim? */
101#define DEACTIVATE_ANON 1
102#define DEACTIVATE_FILE 2
103 unsigned int may_deactivate:2;
104 unsigned int force_deactivate:1;
105 unsigned int skipped_deactivate:1;
106
Johannes Weiner1276ad62017-02-24 14:56:11 -0800107 /* Writepage batching in laptop mode; RECLAIM_WRITE */
Johannes Weineree814fe2014-08-06 16:06:19 -0700108 unsigned int may_writepage:1;
109
110 /* Can mapped pages be reclaimed? */
111 unsigned int may_unmap:1;
112
113 /* Can pages be swapped as part of reclaim? */
114 unsigned int may_swap:1;
115
Yisheng Xied6622f62017-05-03 14:53:57 -0700116 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700117 * Cgroup memory below memory.low is protected as long as we
118 * don't threaten to OOM. If any cgroup is reclaimed at
119 * reduced force or passed over entirely due to its memory.low
120 * setting (memcg_low_skipped), and nothing is reclaimed as a
121 * result, then go back for one more cycle that reclaims the protected
122 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700123 */
124 unsigned int memcg_low_reclaim:1;
125 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800126
Johannes Weineree814fe2014-08-06 16:06:19 -0700127 unsigned int hibernation_mode:1;
128
129 /* One of the zones is ready for compaction */
130 unsigned int compaction_ready:1;
131
Johannes Weinerb91ac372019-11-30 17:56:02 -0800132 /* There is easily reclaimable cold cache in the current node */
133 unsigned int cache_trim_mode:1;
134
Johannes Weiner53138ce2019-11-30 17:55:56 -0800135 /* The file pages on the current node are dangerously low */
136 unsigned int file_is_tiny:1;
137
Dave Hansen26aa2d12021-09-02 14:59:16 -0700138 /* Always discard instead of demoting to lower tier memory */
139 unsigned int no_demotion:1;
140
Yu Zhaoa8a158a2022-09-18 02:00:06 -0600141#ifdef CONFIG_LRU_GEN
142 /* help kswapd make better choices among multiple memcgs */
143 unsigned int memcgs_need_aging:1;
144 unsigned long last_reclaimed;
145#endif
146
Greg Thelenbb451fd2018-08-17 15:45:19 -0700147 /* Allocation order */
148 s8 order;
149
150 /* Scan (total_size >> priority) pages at once */
151 s8 priority;
152
153 /* The highest zone to isolate pages for reclaim from */
154 s8 reclaim_idx;
155
156 /* This context's GFP mask */
157 gfp_t gfp_mask;
158
Johannes Weineree814fe2014-08-06 16:06:19 -0700159 /* Incremented by the number of inactive pages that were scanned */
160 unsigned long nr_scanned;
161
162 /* Number of pages freed so far during a call to shrink_zones() */
163 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700164
165 struct {
166 unsigned int dirty;
167 unsigned int unqueued_dirty;
168 unsigned int congested;
169 unsigned int writeback;
170 unsigned int immediate;
171 unsigned int file_taken;
172 unsigned int taken;
173 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700174
175 /* for recording the reclaimed slab by now */
176 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700177};
178
Linus Torvalds1da177e2005-04-16 15:20:36 -0700179#ifdef ARCH_HAS_PREFETCHW
180#define prefetchw_prev_lru_page(_page, _base, _field) \
181 do { \
182 if ((_page)->lru.prev != _base) { \
183 struct page *prev; \
184 \
185 prev = lru_to_page(&(_page->lru)); \
186 prefetchw(&prev->_field); \
187 } \
188 } while (0)
189#else
190#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
191#endif
192
193/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700194 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700195 */
196int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700197
Yang Shi0a432dc2019-09-23 15:38:12 -0700198static void set_task_reclaim_state(struct task_struct *task,
199 struct reclaim_state *rs)
200{
201 /* Check for an overwrite */
202 WARN_ON_ONCE(rs && task->reclaim_state);
203
204 /* Check for the nulling of an already-nulled member */
205 WARN_ON_ONCE(!rs && !task->reclaim_state);
206
207 task->reclaim_state = rs;
208}
209
Linus Torvalds1da177e2005-04-16 15:20:36 -0700210static LIST_HEAD(shrinker_list);
211static DECLARE_RWSEM(shrinker_rwsem);
212
Yang Shi0a432dc2019-09-23 15:38:12 -0700213#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700214static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700215
Yang Shi3c6f17e2021-05-04 18:36:33 -0700216/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700217static inline int shrinker_map_size(int nr_items)
218{
219 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
220}
Yang Shi2bfd3632021-05-04 18:36:11 -0700221
Yang Shi3c6f17e2021-05-04 18:36:33 -0700222static inline int shrinker_defer_size(int nr_items)
223{
224 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
225}
226
Yang Shi468ab842021-05-04 18:36:26 -0700227static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
228 int nid)
229{
230 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
231 lockdep_is_held(&shrinker_rwsem));
232}
233
Yang Shie4262c42021-05-04 18:36:23 -0700234static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700235 int map_size, int defer_size,
236 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700237{
Yang Shie4262c42021-05-04 18:36:23 -0700238 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700239 struct mem_cgroup_per_node *pn;
240 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700241 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700242
Yang Shi2bfd3632021-05-04 18:36:11 -0700243 for_each_node(nid) {
244 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700245 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700246 /* Not yet online memcg */
247 if (!old)
248 return 0;
249
250 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
251 if (!new)
252 return -ENOMEM;
253
Yang Shi3c6f17e2021-05-04 18:36:33 -0700254 new->nr_deferred = (atomic_long_t *)(new + 1);
255 new->map = (void *)new->nr_deferred + defer_size;
256
257 /* map: set all old bits, clear all new bits */
258 memset(new->map, (int)0xff, old_map_size);
259 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
260 /* nr_deferred: copy old values, clear all new values */
261 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
262 memset((void *)new->nr_deferred + old_defer_size, 0,
263 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700264
Yang Shie4262c42021-05-04 18:36:23 -0700265 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700266 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700267 }
268
269 return 0;
270}
271
Yang Shie4262c42021-05-04 18:36:23 -0700272void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700273{
274 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700275 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700276 int nid;
277
Yang Shi2bfd3632021-05-04 18:36:11 -0700278 for_each_node(nid) {
279 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700280 info = rcu_dereference_protected(pn->shrinker_info, true);
281 kvfree(info);
282 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700283 }
284}
285
Yang Shie4262c42021-05-04 18:36:23 -0700286int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700287{
Yang Shie4262c42021-05-04 18:36:23 -0700288 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700289 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700290 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700291
Yang Shid27cf2a2021-05-04 18:36:14 -0700292 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700293 map_size = shrinker_map_size(shrinker_nr_max);
294 defer_size = shrinker_defer_size(shrinker_nr_max);
295 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700296 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700297 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
298 if (!info) {
299 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700300 ret = -ENOMEM;
301 break;
302 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700303 info->nr_deferred = (atomic_long_t *)(info + 1);
304 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700305 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700306 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700307 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700308
309 return ret;
310}
311
Yang Shi3c6f17e2021-05-04 18:36:33 -0700312static inline bool need_expand(int nr_max)
313{
314 return round_up(nr_max, BITS_PER_LONG) >
315 round_up(shrinker_nr_max, BITS_PER_LONG);
316}
317
Yang Shie4262c42021-05-04 18:36:23 -0700318static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700319{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700320 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700321 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700322 int map_size, defer_size = 0;
323 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700324 struct mem_cgroup *memcg;
325
Yang Shi3c6f17e2021-05-04 18:36:33 -0700326 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700327 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700328
Yang Shi2bfd3632021-05-04 18:36:11 -0700329 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700330 goto out;
331
332 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700333
Yang Shi3c6f17e2021-05-04 18:36:33 -0700334 map_size = shrinker_map_size(new_nr_max);
335 defer_size = shrinker_defer_size(new_nr_max);
336 old_map_size = shrinker_map_size(shrinker_nr_max);
337 old_defer_size = shrinker_defer_size(shrinker_nr_max);
338
Yang Shi2bfd3632021-05-04 18:36:11 -0700339 memcg = mem_cgroup_iter(NULL, NULL, NULL);
340 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700341 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
342 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700343 if (ret) {
344 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700345 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700346 }
347 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700348out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700349 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700350 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700351
Yang Shi2bfd3632021-05-04 18:36:11 -0700352 return ret;
353}
354
355void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
356{
357 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700358 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700359
360 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700361 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700362 /* Pairs with smp mb in shrink_slab() */
363 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700364 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700365 rcu_read_unlock();
366 }
367}
368
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700369static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700370
371static int prealloc_memcg_shrinker(struct shrinker *shrinker)
372{
373 int id, ret = -ENOMEM;
374
Yang Shi476b30a2021-05-04 18:36:39 -0700375 if (mem_cgroup_disabled())
376 return -ENOSYS;
377
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700378 down_write(&shrinker_rwsem);
379 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700380 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700381 if (id < 0)
382 goto unlock;
383
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700384 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700385 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700386 idr_remove(&shrinker_idr, id);
387 goto unlock;
388 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700389 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700390 shrinker->id = id;
391 ret = 0;
392unlock:
393 up_write(&shrinker_rwsem);
394 return ret;
395}
396
397static void unregister_memcg_shrinker(struct shrinker *shrinker)
398{
399 int id = shrinker->id;
400
401 BUG_ON(id < 0);
402
Yang Shi41ca6682021-05-04 18:36:29 -0700403 lockdep_assert_held(&shrinker_rwsem);
404
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700405 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700406}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700407
Yang Shi86750832021-05-04 18:36:36 -0700408static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
409 struct mem_cgroup *memcg)
410{
411 struct shrinker_info *info;
412
413 info = shrinker_info_protected(memcg, nid);
414 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
415}
416
417static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
418 struct mem_cgroup *memcg)
419{
420 struct shrinker_info *info;
421
422 info = shrinker_info_protected(memcg, nid);
423 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
424}
425
Yang Shia1780152021-05-04 18:36:42 -0700426void reparent_shrinker_deferred(struct mem_cgroup *memcg)
427{
428 int i, nid;
429 long nr;
430 struct mem_cgroup *parent;
431 struct shrinker_info *child_info, *parent_info;
432
433 parent = parent_mem_cgroup(memcg);
434 if (!parent)
435 parent = root_mem_cgroup;
436
437 /* Prevent from concurrent shrinker_info expand */
438 down_read(&shrinker_rwsem);
439 for_each_node(nid) {
440 child_info = shrinker_info_protected(memcg, nid);
441 parent_info = shrinker_info_protected(parent, nid);
442 for (i = 0; i < shrinker_nr_max; i++) {
443 nr = atomic_long_read(&child_info->nr_deferred[i]);
444 atomic_long_add(nr, &parent_info->nr_deferred[i]);
445 }
446 }
447 up_read(&shrinker_rwsem);
448}
449
Johannes Weinerb5ead352019-11-30 17:55:40 -0800450static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800451{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800452 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800453}
Tejun Heo97c93412015-05-22 18:23:36 -0400454
455/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800456 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400457 * @sc: scan_control in question
458 *
459 * The normal page dirty throttling mechanism in balance_dirty_pages() is
460 * completely broken with the legacy memcg and direct stalling in
461 * shrink_page_list() is used for throttling instead, which lacks all the
462 * niceties such as fairness, adaptive pausing, bandwidth proportional
463 * allocation and configurability.
464 *
465 * This function tests whether the vmscan currently in progress can assume
466 * that the normal dirty throttling mechanism is operational.
467 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800468static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400469{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800470 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400471 return true;
472#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800473 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400474 return true;
475#endif
476 return false;
477}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800478#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700479static int prealloc_memcg_shrinker(struct shrinker *shrinker)
480{
Yang Shi476b30a2021-05-04 18:36:39 -0700481 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700482}
483
484static void unregister_memcg_shrinker(struct shrinker *shrinker)
485{
486}
487
Yang Shi86750832021-05-04 18:36:36 -0700488static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
489 struct mem_cgroup *memcg)
490{
491 return 0;
492}
493
494static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
495 struct mem_cgroup *memcg)
496{
497 return 0;
498}
499
Johannes Weinerb5ead352019-11-30 17:55:40 -0800500static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800501{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800502 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800503}
Tejun Heo97c93412015-05-22 18:23:36 -0400504
Johannes Weinerb5ead352019-11-30 17:55:40 -0800505static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400506{
507 return true;
508}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800509#endif
510
Yang Shi86750832021-05-04 18:36:36 -0700511static long xchg_nr_deferred(struct shrinker *shrinker,
512 struct shrink_control *sc)
513{
514 int nid = sc->nid;
515
516 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
517 nid = 0;
518
519 if (sc->memcg &&
520 (shrinker->flags & SHRINKER_MEMCG_AWARE))
521 return xchg_nr_deferred_memcg(nid, shrinker,
522 sc->memcg);
523
524 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
525}
526
527
528static long add_nr_deferred(long nr, struct shrinker *shrinker,
529 struct shrink_control *sc)
530{
531 int nid = sc->nid;
532
533 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
534 nid = 0;
535
536 if (sc->memcg &&
537 (shrinker->flags & SHRINKER_MEMCG_AWARE))
538 return add_nr_deferred_memcg(nr, nid, shrinker,
539 sc->memcg);
540
541 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
542}
543
Dave Hansen26aa2d12021-09-02 14:59:16 -0700544static bool can_demote(int nid, struct scan_control *sc)
545{
Huang Ying20b51af12021-09-02 14:59:33 -0700546 if (!numa_demotion_enabled)
547 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700548 if (sc) {
549 if (sc->no_demotion)
550 return false;
551 /* It is pointless to do demotion in memcg reclaim */
552 if (cgroup_reclaim(sc))
553 return false;
554 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700555 if (next_demotion_node(nid) == NUMA_NO_NODE)
556 return false;
557
Huang Ying20b51af12021-09-02 14:59:33 -0700558 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700559}
560
Keith Buscha2a36482021-09-02 14:59:26 -0700561static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
562 int nid,
563 struct scan_control *sc)
564{
565 if (memcg == NULL) {
566 /*
567 * For non-memcg reclaim, is there
568 * space in any swap device?
569 */
570 if (get_nr_swap_pages() > 0)
571 return true;
572 } else {
573 /* Is the memcg below its swap limit? */
574 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
575 return true;
576 }
577
578 /*
579 * The page can not be swapped.
580 *
581 * Can it be reclaimed from this node via demotion?
582 */
583 return can_demote(nid, sc);
584}
585
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700586/*
587 * This misses isolated pages which are not accounted for to save counters.
588 * As the data only determines if reclaim or compaction continues, it is
589 * not expected that isolated pages will be a dominating factor.
590 */
591unsigned long zone_reclaimable_pages(struct zone *zone)
592{
593 unsigned long nr;
594
595 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
596 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700597 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700598 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
599 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
600
601 return nr;
602}
603
Michal Hockofd538802017-02-22 15:45:58 -0800604/**
605 * lruvec_lru_size - Returns the number of pages on the given LRU list.
606 * @lruvec: lru vector
607 * @lru: lru to use
608 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
609 */
Yu Zhao20913392021-02-24 12:08:44 -0800610static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
611 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800612{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800613 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800614 int zid;
615
Johannes Weinerde3b0152019-11-30 17:55:31 -0800616 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800617 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800618
Michal Hockofd538802017-02-22 15:45:58 -0800619 if (!managed_zone(zone))
620 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800621
Michal Hockofd538802017-02-22 15:45:58 -0800622 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800623 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800624 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800625 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800626 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800627 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800628}
629
Linus Torvalds1da177e2005-04-16 15:20:36 -0700630/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000631 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700632 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900633int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700634{
Yang Shi476b30a2021-05-04 18:36:39 -0700635 unsigned int size;
636 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000637
Yang Shi476b30a2021-05-04 18:36:39 -0700638 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
639 err = prealloc_memcg_shrinker(shrinker);
640 if (err != -ENOSYS)
641 return err;
642
643 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
644 }
645
646 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000647 if (shrinker->flags & SHRINKER_NUMA_AWARE)
648 size *= nr_node_ids;
649
650 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
651 if (!shrinker->nr_deferred)
652 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700653
Tetsuo Handa8e049442018-04-04 19:53:07 +0900654 return 0;
655}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000656
Tetsuo Handa8e049442018-04-04 19:53:07 +0900657void free_prealloced_shrinker(struct shrinker *shrinker)
658{
Yang Shi41ca6682021-05-04 18:36:29 -0700659 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
660 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700661 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700662 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700663 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700664 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700665
Tetsuo Handa8e049442018-04-04 19:53:07 +0900666 kfree(shrinker->nr_deferred);
667 shrinker->nr_deferred = NULL;
668}
669
670void register_shrinker_prepared(struct shrinker *shrinker)
671{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700672 down_write(&shrinker_rwsem);
673 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700674 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700675 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900676}
677
678int register_shrinker(struct shrinker *shrinker)
679{
680 int err = prealloc_shrinker(shrinker);
681
682 if (err)
683 return err;
684 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000685 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700686}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700687EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700688
689/*
690 * Remove one
691 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700692void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700693{
Yang Shi41ca6682021-05-04 18:36:29 -0700694 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900695 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700696
Linus Torvalds1da177e2005-04-16 15:20:36 -0700697 down_write(&shrinker_rwsem);
698 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700699 shrinker->flags &= ~SHRINKER_REGISTERED;
700 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
701 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700702 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700703
Andrew Vaginae393322013-10-16 13:46:46 -0700704 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900705 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700706}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700707EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700708
709#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000710
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800711static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800712 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700713{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000714 unsigned long freed = 0;
715 unsigned long long delta;
716 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700717 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000718 long nr;
719 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000720 long batch_size = shrinker->batch ? shrinker->batch
721 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800722 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000723
rongqianfeng8da6ee32021-05-21 10:30:14 +0800724 trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
725
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700726 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700727 if (freeable == 0 || freeable == SHRINK_EMPTY)
728 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000729
730 /*
731 * copy the current shrinker scan count into a local variable
732 * and zero it so that other concurrent shrinker invocations
733 * don't also do this scanning work.
734 */
Yang Shi86750832021-05-04 18:36:36 -0700735 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000736
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700737 if (shrinker->seeks) {
738 delta = freeable >> priority;
739 delta *= 4;
740 do_div(delta, shrinker->seeks);
741 } else {
742 /*
743 * These objects don't require any IO to create. Trim
744 * them aggressively under memory pressure to keep
745 * them from causing refetches in the IO caches.
746 */
747 delta = freeable / 2;
748 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700749
Yang Shi18bb4732021-05-04 18:36:45 -0700750 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000751 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700752 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000753
754 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800755 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000756
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800757 /*
758 * Normally, we should not scan less than batch_size objects in one
759 * pass to avoid too frequent shrinker calls, but if the slab has less
760 * than batch_size objects in total and we are really tight on memory,
761 * we will try to reclaim all available objects, otherwise we can end
762 * up failing allocations although there are plenty of reclaimable
763 * objects spread over several slabs with usage less than the
764 * batch_size.
765 *
766 * We detect the "tight on memory" situations by looking at the total
767 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700768 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800769 * scanning at high prio and therefore should try to reclaim as much as
770 * possible.
771 */
772 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700773 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000774 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800775 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000776
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800777 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700778 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000779 ret = shrinker->scan_objects(shrinker, shrinkctl);
780 if (ret == SHRINK_STOP)
781 break;
782 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000783
Chris Wilsond460acb2017-09-06 16:19:26 -0700784 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
785 total_scan -= shrinkctl->nr_scanned;
786 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000787
788 cond_resched();
789 }
790
Yang Shi18bb4732021-05-04 18:36:45 -0700791 /*
792 * The deferred work is increased by any new work (delta) that wasn't
793 * done, decreased by old deferred work that was done now.
794 *
795 * And it is capped to two times of the freeable items.
796 */
797 next_deferred = max_t(long, (nr + delta - scanned), 0);
798 next_deferred = min(next_deferred, (2 * freeable));
799
Glauber Costa1d3d4432013-08-28 10:18:04 +1000800 /*
801 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700802 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000803 */
Yang Shi86750832021-05-04 18:36:36 -0700804 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000805
Yang Shi8efb4b52021-05-04 18:36:08 -0700806 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000807 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700808}
809
Yang Shi0a432dc2019-09-23 15:38:12 -0700810#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700811static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
812 struct mem_cgroup *memcg, int priority)
813{
Yang Shie4262c42021-05-04 18:36:23 -0700814 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700815 unsigned long ret, freed = 0;
816 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700817
Yang Shi0a432dc2019-09-23 15:38:12 -0700818 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700819 return 0;
820
821 if (!down_read_trylock(&shrinker_rwsem))
822 return 0;
823
Yang Shi468ab842021-05-04 18:36:26 -0700824 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700825 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700826 goto unlock;
827
Yang Shie4262c42021-05-04 18:36:23 -0700828 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700829 struct shrink_control sc = {
830 .gfp_mask = gfp_mask,
831 .nid = nid,
832 .memcg = memcg,
833 };
834 struct shrinker *shrinker;
835
836 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700837 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700838 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700839 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700840 continue;
841 }
842
Yang Shi0a432dc2019-09-23 15:38:12 -0700843 /* Call non-slab shrinkers even though kmem is disabled */
844 if (!memcg_kmem_enabled() &&
845 !(shrinker->flags & SHRINKER_NONSLAB))
846 continue;
847
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700848 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700849 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700850 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700851 /*
852 * After the shrinker reported that it had no objects to
853 * free, but before we cleared the corresponding bit in
854 * the memcg shrinker map, a new object might have been
855 * added. To make sure, we have the bit set in this
856 * case, we invoke the shrinker one more time and reset
857 * the bit if it reports that it is not empty anymore.
858 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700859 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700860 *
861 * list_lru_add() shrink_slab_memcg()
862 * list_add_tail() clear_bit()
863 * <MB> <MB>
864 * set_bit() do_shrink_slab()
865 */
866 smp_mb__after_atomic();
867 ret = do_shrink_slab(&sc, shrinker, priority);
868 if (ret == SHRINK_EMPTY)
869 ret = 0;
870 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700871 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700872 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700873 freed += ret;
874
875 if (rwsem_is_contended(&shrinker_rwsem)) {
876 freed = freed ? : 1;
877 break;
878 }
879 }
880unlock:
881 up_read(&shrinker_rwsem);
882 return freed;
883}
Yang Shi0a432dc2019-09-23 15:38:12 -0700884#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700885static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
886 struct mem_cgroup *memcg, int priority)
887{
888 return 0;
889}
Yang Shi0a432dc2019-09-23 15:38:12 -0700890#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700891
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800892/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800893 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800894 * @gfp_mask: allocation context
895 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800896 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800897 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700898 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800899 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700900 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800901 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
902 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700903 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700904 * @memcg specifies the memory cgroup to target. Unaware shrinkers
905 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800906 *
Josef Bacik9092c712018-01-31 16:16:26 -0800907 * @priority is sc->priority, we take the number of objects and >> by priority
908 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700909 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800910 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700911 */
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800912unsigned long shrink_slab(gfp_t gfp_mask, int nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800913 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800914 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700915{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700916 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700917 struct shrinker *shrinker;
wudean842c68a2021-04-27 17:40:41 +0800918 bool bypass = false;
919
920 trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
921 if (bypass)
922 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700923
Yang Shifa1e5122019-08-02 21:48:44 -0700924 /*
925 * The root memcg might be allocated even though memcg is disabled
926 * via "cgroup_disable=memory" boot parameter. This could make
927 * mem_cgroup_is_root() return false, then just run memcg slab
928 * shrink, but skip global shrink. This may result in premature
929 * oom.
930 */
931 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700932 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800933
Tetsuo Handae830c632018-04-05 16:23:35 -0700934 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700935 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700936
937 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800938 struct shrink_control sc = {
939 .gfp_mask = gfp_mask,
940 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800941 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800942 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800943
Kirill Tkhai9b996462018-08-17 15:48:21 -0700944 ret = do_shrink_slab(&sc, shrinker, priority);
945 if (ret == SHRINK_EMPTY)
946 ret = 0;
947 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800948 /*
949 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700950 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800951 * by parallel ongoing shrinking.
952 */
953 if (rwsem_is_contended(&shrinker_rwsem)) {
954 freed = freed ? : 1;
955 break;
956 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700957 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800958
Linus Torvalds1da177e2005-04-16 15:20:36 -0700959 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700960out:
961 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000962 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700963}
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800964EXPORT_SYMBOL_GPL(shrink_slab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700965
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800966void drop_slab_node(int nid)
967{
968 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700969 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800970
971 do {
972 struct mem_cgroup *memcg = NULL;
973
Chunxin Zang069c4112020-10-13 16:56:46 -0700974 if (fatal_signal_pending(current))
975 return;
976
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800977 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700978 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800979 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800980 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800981 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700982 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800983}
984
985void drop_slab(void)
986{
987 int nid;
988
989 for_each_online_node(nid)
990 drop_slab_node(nid);
991}
992
Linus Torvalds1da177e2005-04-16 15:20:36 -0700993static inline int is_page_cache_freeable(struct page *page)
994{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700995 /*
996 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400997 * that isolated the page, the page cache and optional buffer
998 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700999 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -07001000 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -04001001 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001002}
1003
Yang Shicb165562019-11-30 17:55:28 -08001004static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001005{
Christoph Lameter930d9152006-01-08 01:00:47 -08001006 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001007 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001008 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001009 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001010 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001011 return 1;
1012 return 0;
1013}
1014
1015/*
1016 * We detected a synchronous write error writing a page out. Probably
1017 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1018 * fsync(), msync() or close().
1019 *
1020 * The tricky part is that after writepage we cannot touch the mapping: nothing
1021 * prevents it from being freed up. But we have a ref on the page and once
1022 * that page is locked, the mapping is pinned.
1023 *
1024 * We're allowed to run sleeping lock_page() here because we know the caller has
1025 * __GFP_FS.
1026 */
1027static void handle_write_error(struct address_space *mapping,
1028 struct page *page, int error)
1029{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001030 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001031 if (page_mapping(page) == mapping)
1032 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001033 unlock_page(page);
1034}
1035
Christoph Lameter04e62a22006-06-23 02:03:38 -07001036/* possible outcome of pageout() */
1037typedef enum {
1038 /* failed to write page out, page is locked */
1039 PAGE_KEEP,
1040 /* move page to the active list, page is locked */
1041 PAGE_ACTIVATE,
1042 /* page has been sent to the disk successfully, page is unlocked */
1043 PAGE_SUCCESS,
1044 /* page is clean and locked */
1045 PAGE_CLEAN,
1046} pageout_t;
1047
Linus Torvalds1da177e2005-04-16 15:20:36 -07001048/*
Andrew Morton1742f192006-03-22 00:08:21 -08001049 * pageout is called by shrink_page_list() for each dirty page.
1050 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001051 */
Yang Shicb165562019-11-30 17:55:28 -08001052static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001053{
1054 /*
1055 * If the page is dirty, only perform writeback if that write
1056 * will be non-blocking. To prevent this allocation from being
1057 * stalled by pagecache activity. But note that there may be
1058 * stalls if we need to run get_block(). We could test
1059 * PagePrivate for that.
1060 *
Al Viro81742022014-04-03 03:17:43 -04001061 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001062 * this page's queue, we can perform writeback even if that
1063 * will block.
1064 *
1065 * If the page is swapcache, write it back even if that would
1066 * block, for some throttling. This happens by accident, because
1067 * swap_backing_dev_info is bust: it doesn't reflect the
1068 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001069 */
1070 if (!is_page_cache_freeable(page))
1071 return PAGE_KEEP;
1072 if (!mapping) {
1073 /*
1074 * Some data journaling orphaned pages can have
1075 * page->mapping == NULL while being dirty with clean buffers.
1076 */
David Howells266cf652009-04-03 16:42:36 +01001077 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001078 if (try_to_free_buffers(page)) {
1079 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001080 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001081 return PAGE_CLEAN;
1082 }
1083 }
1084 return PAGE_KEEP;
1085 }
1086 if (mapping->a_ops->writepage == NULL)
1087 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001088 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001089 return PAGE_KEEP;
1090
1091 if (clear_page_dirty_for_io(page)) {
1092 int res;
1093 struct writeback_control wbc = {
1094 .sync_mode = WB_SYNC_NONE,
1095 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001096 .range_start = 0,
1097 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001098 .for_reclaim = 1,
1099 };
1100
1101 SetPageReclaim(page);
1102 res = mapping->a_ops->writepage(page, &wbc);
1103 if (res < 0)
1104 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001105 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001106 ClearPageReclaim(page);
1107 return PAGE_ACTIVATE;
1108 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001109
Linus Torvalds1da177e2005-04-16 15:20:36 -07001110 if (!PageWriteback(page)) {
1111 /* synchronous write or broken a_ops? */
1112 ClearPageReclaim(page);
1113 }
yalin wang3aa23852016-01-14 15:18:30 -08001114 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001115 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001116 return PAGE_SUCCESS;
1117 }
1118
1119 return PAGE_CLEAN;
1120}
1121
Andrew Mortona649fd92006-10-17 00:09:36 -07001122/*
Nick Piggine2867812008-07-25 19:45:30 -07001123 * Same as remove_mapping, but if the page is removed from the mapping, it
1124 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001125 */
Johannes Weinera5289102014-04-03 14:47:51 -07001126static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001127 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001128{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001129 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001130 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001131
Nick Piggin28e4d962006-09-25 23:31:23 -07001132 BUG_ON(!PageLocked(page));
1133 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001134
Johannes Weiner30472502021-09-02 14:53:18 -07001135 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001136 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001137 * The non racy check for a busy page.
1138 *
1139 * Must be careful with the order of the tests. When someone has
1140 * a ref to the page, it may be possible that they dirty it then
1141 * drop the reference. So if PageDirty is tested before page_count
1142 * here, then the following race may occur:
1143 *
1144 * get_user_pages(&page);
1145 * [user mapping goes away]
1146 * write_to(page);
1147 * !PageDirty(page) [good]
1148 * SetPageDirty(page);
1149 * put_page(page);
1150 * !page_count(page) [good, discard it]
1151 *
1152 * [oops, our write_to data is lost]
1153 *
1154 * Reversing the order of the tests ensures such a situation cannot
1155 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001156 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001157 *
1158 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001159 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001160 */
William Kucharski906d2782019-10-18 20:20:33 -07001161 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001162 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001163 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001164 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001165 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001166 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001167 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001168 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001169
1170 if (PageSwapCache(page)) {
1171 swp_entry_t swap = { .val = page_private(page) };
Yu Zhao37397872022-09-18 02:00:03 -06001172
1173 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001174 if (reclaimed && !mapping_exiting(mapping))
1175 shadow = workingset_eviction(page, target_memcg);
Yu Zhao37397872022-09-18 02:00:03 -06001176 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001177 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001178 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001179 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001180 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001181 void (*freepage)(struct page *);
1182
1183 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001184 /*
1185 * Remember a shadow entry for reclaimed file cache in
1186 * order to detect refaults, thus thrashing, later on.
1187 *
1188 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001189 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001190 * inode reclaim needs to empty out the radix tree or
1191 * the nodes are lost. Don't plant shadows behind its
1192 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001193 *
1194 * We also don't store shadows for DAX mappings because the
1195 * only page cache pages found in these are zero pages
1196 * covering holes, and because we don't want to mix DAX
1197 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001198 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001199 */
Huang Ying9de4f222020-04-06 20:04:41 -07001200 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001201 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001202 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001203 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001204 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001205
1206 if (freepage != NULL)
1207 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001208 }
1209
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001210 return 1;
1211
1212cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001213 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001214 return 0;
1215}
1216
Linus Torvalds1da177e2005-04-16 15:20:36 -07001217/*
Nick Piggine2867812008-07-25 19:45:30 -07001218 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1219 * someone else has a ref on the page, abort and return 0. If it was
1220 * successfully detached, return 1. Assumes the caller has a single ref on
1221 * this page.
1222 */
1223int remove_mapping(struct address_space *mapping, struct page *page)
1224{
Johannes Weinerb9107182019-11-30 17:55:59 -08001225 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001226 /*
1227 * Unfreezing the refcount with 1 rather than 2 effectively
1228 * drops the pagecache ref for us without requiring another
1229 * atomic operation.
1230 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001231 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001232 return 1;
1233 }
1234 return 0;
1235}
1236
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001237/**
1238 * putback_lru_page - put previously isolated page onto appropriate LRU list
1239 * @page: page to be put back to appropriate lru list
1240 *
1241 * Add previously isolated @page to appropriate LRU list.
1242 * Page may still be unevictable for other reasons.
1243 *
1244 * lru_lock must not be held, interrupts must be enabled.
1245 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001246void putback_lru_page(struct page *page)
1247{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001248 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001249 put_page(page); /* drop ref from isolate */
1250}
1251
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001252enum page_references {
1253 PAGEREF_RECLAIM,
1254 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001255 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001256 PAGEREF_ACTIVATE,
1257};
1258
1259static enum page_references page_check_references(struct page *page,
1260 struct scan_control *sc)
1261{
Johannes Weiner645747462010-03-05 13:42:22 -08001262 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001263 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001264
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001265 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1266 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001267 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001268
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001269 /*
1270 * Mlock lost the isolation race with us. Let try_to_unmap()
1271 * move the page to the unevictable list.
1272 */
1273 if (vm_flags & VM_LOCKED)
1274 return PAGEREF_RECLAIM;
1275
Minchan Kimf74aca72022-05-19 14:08:54 -07001276 /* rmap lock contention: rotate */
1277 if (referenced_ptes == -1)
1278 return PAGEREF_KEEP;
1279
Johannes Weiner645747462010-03-05 13:42:22 -08001280 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001281 /*
1282 * All mapped pages start out with page table
1283 * references from the instantiating fault, so we need
1284 * to look twice if a mapped file page is used more
1285 * than once.
1286 *
1287 * Mark it and spare it for another trip around the
1288 * inactive list. Another page table reference will
1289 * lead to its activation.
1290 *
1291 * Note: the mark is set for activated pages as well
1292 * so that recently deactivated but used pages are
1293 * quickly recovered.
1294 */
1295 SetPageReferenced(page);
1296
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001297 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001298 return PAGEREF_ACTIVATE;
1299
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001300 /*
1301 * Activate file-backed executable pages after first usage.
1302 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001303 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001304 return PAGEREF_ACTIVATE;
1305
Johannes Weiner645747462010-03-05 13:42:22 -08001306 return PAGEREF_KEEP;
1307 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001308
1309 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001310 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001311 return PAGEREF_RECLAIM_CLEAN;
1312
1313 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001314}
1315
Mel Gormane2be15f2013-07-03 15:01:57 -07001316/* Check if a page is dirty or under writeback */
1317static void page_check_dirty_writeback(struct page *page,
1318 bool *dirty, bool *writeback)
1319{
Mel Gormanb4597222013-07-03 15:02:05 -07001320 struct address_space *mapping;
1321
Mel Gormane2be15f2013-07-03 15:01:57 -07001322 /*
1323 * Anonymous pages are not handled by flushers and must be written
1324 * from reclaim context. Do not stall reclaim based on them
1325 */
Huang Ying9de4f222020-04-06 20:04:41 -07001326 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001327 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001328 *dirty = false;
1329 *writeback = false;
1330 return;
1331 }
1332
1333 /* By default assume that the page flags are accurate */
1334 *dirty = PageDirty(page);
1335 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001336
1337 /* Verify dirty/writeback state if the filesystem supports it */
1338 if (!page_has_private(page))
1339 return;
1340
1341 mapping = page_mapping(page);
1342 if (mapping && mapping->a_ops->is_dirty_writeback)
1343 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001344}
1345
Dave Hansen26aa2d12021-09-02 14:59:16 -07001346static struct page *alloc_demote_page(struct page *page, unsigned long node)
1347{
1348 struct migration_target_control mtc = {
1349 /*
1350 * Allocate from 'node', or fail quickly and quietly.
1351 * When this happens, 'page' will likely just be discarded
1352 * instead of migrated.
1353 */
1354 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1355 __GFP_THISNODE | __GFP_NOWARN |
1356 __GFP_NOMEMALLOC | GFP_NOWAIT,
1357 .nid = node
1358 };
1359
1360 return alloc_migration_target(page, (unsigned long)&mtc);
1361}
1362
1363/*
1364 * Take pages on @demote_list and attempt to demote them to
1365 * another node. Pages which are not demoted are left on
1366 * @demote_pages.
1367 */
1368static unsigned int demote_page_list(struct list_head *demote_pages,
1369 struct pglist_data *pgdat)
1370{
1371 int target_nid = next_demotion_node(pgdat->node_id);
1372 unsigned int nr_succeeded;
1373 int err;
1374
1375 if (list_empty(demote_pages))
1376 return 0;
1377
1378 if (target_nid == NUMA_NO_NODE)
1379 return 0;
1380
1381 /* Demotion ignores all cpuset and mempolicy settings */
1382 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1383 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1384 &nr_succeeded);
1385
Yang Shi668e4142021-09-02 14:59:19 -07001386 if (current_is_kswapd())
1387 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1388 else
1389 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1390
Dave Hansen26aa2d12021-09-02 14:59:16 -07001391 return nr_succeeded;
1392}
1393
Nick Piggine2867812008-07-25 19:45:30 -07001394/*
Andrew Morton1742f192006-03-22 00:08:21 -08001395 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001396 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001397static unsigned int shrink_page_list(struct list_head *page_list,
1398 struct pglist_data *pgdat,
1399 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001400 struct reclaim_stat *stat,
1401 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001402{
1403 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001404 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001405 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001406 unsigned int nr_reclaimed = 0;
1407 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001408 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001409
Kirill Tkhai060f0052019-03-05 15:48:15 -08001410 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001411 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001412 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001413
Dave Hansen26aa2d12021-09-02 14:59:16 -07001414retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001415 while (!list_empty(page_list)) {
1416 struct address_space *mapping;
1417 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001418 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001419 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001420 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001421
1422 cond_resched();
1423
1424 page = lru_to_page(page_list);
1425 list_del(&page->lru);
1426
Nick Piggin529ae9a2008-08-02 12:01:03 +02001427 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001428 goto keep;
1429
Sasha Levin309381fea2014-01-23 15:52:54 -08001430 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001431
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001432 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001433
1434 /* Account the number of base pages even though THP */
1435 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001436
Hugh Dickins39b5f292012-10-08 16:33:18 -07001437 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001438 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001439
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001440 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001441 goto keep_locked;
1442
Yu Zhao0182f922022-09-18 02:00:04 -06001443 /* page_update_gen() tried to promote this page? */
1444 if (lru_gen_enabled() && !ignore_references &&
1445 page_mapped(page) && PageReferenced(page))
1446 goto keep_locked;
1447
Andy Whitcroftc661b072007-08-22 14:01:26 -07001448 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1449 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1450
Mel Gorman283aba92013-07-03 15:01:51 -07001451 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001452 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001453 * reclaim_congested which affects wait_iff_congested. kswapd
1454 * will stall and start writing pages if the tail of the LRU
1455 * is all dirty unqueued pages.
1456 */
1457 page_check_dirty_writeback(page, &dirty, &writeback);
1458 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001459 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001460
1461 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001462 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001463
Mel Gormand04e8ac2013-07-03 15:02:03 -07001464 /*
1465 * Treat this page as congested if the underlying BDI is or if
1466 * pages are cycling through the LRU so quickly that the
1467 * pages marked for immediate reclaim are making it to the
1468 * end of the LRU a second time.
1469 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001470 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001471 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001472 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001473 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001474 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001475
1476 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001477 * If a page at the tail of the LRU is under writeback, there
1478 * are three cases to consider.
1479 *
1480 * 1) If reclaim is encountering an excessive number of pages
1481 * under writeback and this page is both under writeback and
1482 * PageReclaim then it indicates that pages are being queued
1483 * for IO but are being recycled through the LRU before the
1484 * IO can complete. Waiting on the page itself risks an
1485 * indefinite stall if it is impossible to writeback the
1486 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001487 * note that the LRU is being scanned too quickly and the
1488 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001489 *
Tejun Heo97c93412015-05-22 18:23:36 -04001490 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001491 * not marked for immediate reclaim, or the caller does not
1492 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1493 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001494 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001495 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001496 * Require may_enter_fs because we would wait on fs, which
1497 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001498 * enter reclaim, and deadlock if it waits on a page for
1499 * which it is needed to do the write (loop masks off
1500 * __GFP_IO|__GFP_FS for this reason); but more thought
1501 * would probably show more reasons.
1502 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001503 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001504 * PageReclaim. memcg does not have any dirty pages
1505 * throttling so we could easily OOM just because too many
1506 * pages are in writeback and there is nothing else to
1507 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001508 *
1509 * In cases 1) and 2) we activate the pages to get them out of
1510 * the way while we continue scanning for clean pages on the
1511 * inactive list and refilling from the active list. The
1512 * observation here is that waiting for disk writes is more
1513 * expensive than potentially causing reloads down the line.
1514 * Since they're marked for immediate reclaim, they won't put
1515 * memory pressure on the cache working set any longer than it
1516 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001517 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001518 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001519 /* Case 1 above */
1520 if (current_is_kswapd() &&
1521 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001522 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001523 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001524 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001525
1526 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001527 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001528 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001529 /*
1530 * This is slightly racy - end_page_writeback()
1531 * might have just cleared PageReclaim, then
1532 * setting PageReclaim here end up interpreted
1533 * as PageReadahead - but that does not matter
1534 * enough to care. What we do want is for this
1535 * page to have PageReclaim set next time memcg
1536 * reclaim reaches the tests above, so it will
1537 * then wait_on_page_writeback() to avoid OOM;
1538 * and it's also appropriate in global reclaim.
1539 */
1540 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001541 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001542 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001543
1544 /* Case 3 above */
1545 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001546 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001547 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001548 /* then go back and try same page again */
1549 list_add_tail(&page->lru, page_list);
1550 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001551 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001552 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001553
Minchan Kim8940b342019-09-25 16:49:11 -07001554 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001555 references = page_check_references(page, sc);
1556
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001557 switch (references) {
1558 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001559 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001560 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001561 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001562 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001563 case PAGEREF_RECLAIM:
1564 case PAGEREF_RECLAIM_CLEAN:
1565 ; /* try to reclaim the page below */
1566 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001567
Linus Torvalds1da177e2005-04-16 15:20:36 -07001568 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001569 * Before reclaiming the page, try to relocate
1570 * its contents to another node.
1571 */
1572 if (do_demote_pass &&
1573 (thp_migration_supported() || !PageTransHuge(page))) {
1574 list_add(&page->lru, &demote_pages);
1575 unlock_page(page);
1576 continue;
1577 }
1578
1579 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001580 * Anonymous process memory has backing store?
1581 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001582 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001583 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001584 if (PageAnon(page) && PageSwapBacked(page)) {
1585 if (!PageSwapCache(page)) {
1586 if (!(sc->gfp_mask & __GFP_IO))
1587 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001588 if (page_maybe_dma_pinned(page))
1589 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001590 if (PageTransHuge(page)) {
1591 /* cannot split THP, skip it */
1592 if (!can_split_huge_page(page, NULL))
1593 goto activate_locked;
1594 /*
1595 * Split pages without a PMD map right
1596 * away. Chances are some or all of the
1597 * tail pages can be freed without IO.
1598 */
1599 if (!compound_mapcount(page) &&
1600 split_huge_page_to_list(page,
1601 page_list))
1602 goto activate_locked;
1603 }
1604 if (!add_to_swap(page)) {
1605 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001606 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001607 /* Fallback to swap normal pages */
1608 if (split_huge_page_to_list(page,
1609 page_list))
1610 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001611#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1612 count_vm_event(THP_SWPOUT_FALLBACK);
1613#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001614 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001615 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001616 }
Minchan Kim0f074652017-07-06 15:37:24 -07001617
Kirill Tkhai4b793062020-04-01 21:10:18 -07001618 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001619
1620 /* Adding to swap updated mapping */
1621 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001622 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001623 } else if (unlikely(PageTransHuge(page))) {
1624 /* Split file THP */
1625 if (split_huge_page_to_list(page, page_list))
1626 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001627 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001628
1629 /*
Yang Shi98879b32019-07-11 20:59:30 -07001630 * THP may get split above, need minus tail pages and update
1631 * nr_pages to avoid accounting tail pages twice.
1632 *
1633 * The tail pages that are added into swap cache successfully
1634 * reach here.
1635 */
1636 if ((nr_pages > 1) && !PageTransHuge(page)) {
1637 sc->nr_scanned -= (nr_pages - 1);
1638 nr_pages = 1;
1639 }
1640
1641 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001642 * The page is mapped into the page tables of one or more
1643 * processes. Try to unmap it here.
1644 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001645 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001646 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001647 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001648
1649 if (unlikely(PageTransHuge(page)))
1650 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001651
Yang Shi1fb08ac2021-06-30 18:52:01 -07001652 try_to_unmap(page, flags);
1653 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001654 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001655 if (!was_swapbacked && PageSwapBacked(page))
1656 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001657 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001658 }
1659 }
1660
1661 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001662 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001663 * Only kswapd can writeback filesystem pages
1664 * to avoid risk of stack overflow. But avoid
1665 * injecting inefficient single-page IO into
1666 * flusher writeback as much as possible: only
1667 * write pages when we've encountered many
1668 * dirty pages, and when we've already scanned
1669 * the rest of the LRU for clean pages and see
1670 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001671 */
Huang Ying9de4f222020-04-06 20:04:41 -07001672 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001673 (!current_is_kswapd() || !PageReclaim(page) ||
1674 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001675 /*
1676 * Immediately reclaim when written back.
1677 * Similar in principal to deactivate_page()
1678 * except we already have the page isolated
1679 * and know it's dirty
1680 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001681 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001682 SetPageReclaim(page);
1683
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001684 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001685 }
1686
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001687 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001688 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001689 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001690 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001691 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001692 goto keep_locked;
1693
Mel Gormand950c942015-09-04 15:47:35 -07001694 /*
1695 * Page is dirty. Flush the TLB if a writable entry
1696 * potentially exists to avoid CPU writes after IO
1697 * starts and then write it out here.
1698 */
1699 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001700 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001701 case PAGE_KEEP:
1702 goto keep_locked;
1703 case PAGE_ACTIVATE:
1704 goto activate_locked;
1705 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001706 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001707
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001708 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001709 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001710 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001711 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001712
Linus Torvalds1da177e2005-04-16 15:20:36 -07001713 /*
1714 * A synchronous write - probably a ramdisk. Go
1715 * ahead and try to reclaim the page.
1716 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001717 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001718 goto keep;
1719 if (PageDirty(page) || PageWriteback(page))
1720 goto keep_locked;
1721 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001722 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001723 case PAGE_CLEAN:
1724 ; /* try to free the page below */
1725 }
1726 }
1727
1728 /*
1729 * If the page has buffers, try to free the buffer mappings
1730 * associated with this page. If we succeed we try to free
1731 * the page as well.
1732 *
1733 * We do this even if the page is PageDirty().
1734 * try_to_release_page() does not perform I/O, but it is
1735 * possible for a page to have PageDirty set, but it is actually
1736 * clean (all its buffers are clean). This happens if the
1737 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001738 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001739 * try_to_release_page() will discover that cleanness and will
1740 * drop the buffers and mark the page clean - it can be freed.
1741 *
1742 * Rarely, pages can have buffers and no ->mapping. These are
1743 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001744 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001745 * and if that worked, and the page is no longer mapped into
1746 * process address space (page_count == 1) it can be freed.
1747 * Otherwise, leave the page on the LRU so it is swappable.
1748 */
David Howells266cf652009-04-03 16:42:36 +01001749 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001750 if (!try_to_release_page(page, sc->gfp_mask))
1751 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001752 if (!mapping && page_count(page) == 1) {
1753 unlock_page(page);
1754 if (put_page_testzero(page))
1755 goto free_it;
1756 else {
1757 /*
1758 * rare race with speculative reference.
1759 * the speculative reference will free
1760 * this page shortly, so we may
1761 * increment nr_reclaimed here (and
1762 * leave it off the LRU).
1763 */
1764 nr_reclaimed++;
1765 continue;
1766 }
1767 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001768 }
1769
Shaohua Li802a3a92017-05-03 14:52:32 -07001770 if (PageAnon(page) && !PageSwapBacked(page)) {
1771 /* follow __remove_mapping for reference */
1772 if (!page_ref_freeze(page, 1))
1773 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001774 /*
1775 * The page has only one reference left, which is
1776 * from the isolation. After the caller puts the
1777 * page back on lru and drops the reference, the
1778 * page will be freed anyway. It doesn't matter
1779 * which lru it goes. So we don't bother checking
1780 * PageDirty here.
1781 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001782 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001783 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001784 } else if (!mapping || !__remove_mapping(mapping, page, true,
1785 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001786 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001787
1788 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001789free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001790 /*
1791 * THP may get swapped out in a whole, need account
1792 * all base pages.
1793 */
1794 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001795
1796 /*
1797 * Is there need to periodically free_page_list? It would
1798 * appear not as the counts should be low
1799 */
Yang Shi7ae88532019-09-23 15:38:09 -07001800 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001801 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001802 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001803 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001804 continue;
1805
Yang Shi98879b32019-07-11 20:59:30 -07001806activate_locked_split:
1807 /*
1808 * The tail pages that are failed to add into swap cache
1809 * reach here. Fixup nr_scanned and nr_pages.
1810 */
1811 if (nr_pages > 1) {
1812 sc->nr_scanned -= (nr_pages - 1);
1813 nr_pages = 1;
1814 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001815activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001816 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001817 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1818 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001819 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001820 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001821 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001822 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001823 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001824 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001825 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001826 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001827keep_locked:
1828 unlock_page(page);
1829keep:
1830 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001831 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001832 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001833 /* 'page_list' is always empty here */
1834
1835 /* Migrate pages selected for demotion */
1836 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1837 /* Pages that could not be demoted are still in @demote_pages */
1838 if (!list_empty(&demote_pages)) {
1839 /* Pages which failed to demoted go back on @page_list for retry: */
1840 list_splice_init(&demote_pages, page_list);
1841 do_demote_pass = false;
1842 goto retry;
1843 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001844
Yang Shi98879b32019-07-11 20:59:30 -07001845 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1846
Johannes Weiner747db952014-08-08 14:19:24 -07001847 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001848 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001849 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001850
Linus Torvalds1da177e2005-04-16 15:20:36 -07001851 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001852 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001853
Andrew Morton05ff5132006-03-22 00:08:20 -08001854 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001855}
1856
Maninder Singh730ec8c2020-06-03 16:01:18 -07001857unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001858 struct list_head *page_list)
1859{
1860 struct scan_control sc = {
1861 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001862 .may_unmap = 1,
1863 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001864 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001865 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001866 struct page *page, *next;
1867 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001868 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001869
1870 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001871 if (!PageHuge(page) && page_is_file_lru(page) &&
1872 !PageDirty(page) && !__PageMovable(page) &&
1873 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001874 ClearPageActive(page);
1875 list_move(&page->lru, &clean_pages);
1876 }
1877 }
1878
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001879 /*
1880 * We should be safe here since we are only dealing with file pages and
1881 * we are not kswapd and therefore cannot write dirty file pages. But
1882 * call memalloc_noreclaim_save() anyway, just in case these conditions
1883 * change in the future.
1884 */
1885 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001886 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001887 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001888 memalloc_noreclaim_restore(noreclaim_flag);
1889
Minchan Kim02c6de82012-10-08 16:31:55 -07001890 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001891 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1892 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001893 /*
1894 * Since lazyfree pages are isolated from file LRU from the beginning,
1895 * they will rotate back to anonymous LRU in the end if it failed to
1896 * discard so isolated count will be mismatched.
1897 * Compensate the isolated count for both LRU lists.
1898 */
1899 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1900 stat.nr_lazyfree_fail);
1901 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001902 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001903 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001904}
1905
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001906/*
Mel Gorman7ee36a12016-07-28 15:47:17 -07001907 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001908 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001909 */
1910static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001911 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001912{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001913 int zid;
1914
Mel Gorman7ee36a12016-07-28 15:47:17 -07001915 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1916 if (!nr_zone_taken[zid])
1917 continue;
1918
Wei Yanga892cb62020-06-03 16:01:12 -07001919 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001920 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001921
Mel Gorman7ee36a12016-07-28 15:47:17 -07001922}
1923
Mel Gormanf611fab2021-06-30 18:53:19 -07001924/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001925 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1926 *
1927 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001928 * shrink the lists perform better by taking out a batch of pages
1929 * and working on them outside the LRU lock.
1930 *
1931 * For pagecache intensive workloads, this function is the hottest
1932 * spot in the kernel (apart from copy_*_user functions).
1933 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001934 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001935 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001936 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001937 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001938 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001939 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001940 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001941 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001942 *
1943 * returns how many pages were moved onto *@dst.
1944 */
Andrew Morton69e05942006-03-22 00:08:19 -08001945static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001946 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001947 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001948 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001949{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001950 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001951 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001952 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001953 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07001954 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001955 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07001956 LIST_HEAD(pages_skipped);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001957
Yang Shi98879b32019-07-11 20:59:30 -07001958 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001959 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07001960 while (scan < nr_to_scan && !list_empty(src)) {
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001961 struct list_head *move_to = src;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001962 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001963
Linus Torvalds1da177e2005-04-16 15:20:36 -07001964 page = lru_to_page(src);
1965 prefetchw_prev_lru_page(page, src, flags);
1966
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001967 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001968 total_scan += nr_pages;
1969
Mel Gormanb2e18752016-07-28 15:45:37 -07001970 if (page_zonenum(page) > sc->reclaim_idx) {
Yang Shi98879b32019-07-11 20:59:30 -07001971 nr_skipped[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001972 move_to = &pages_skipped;
1973 goto move;
Mel Gormanb2e18752016-07-28 15:45:37 -07001974 }
1975
Minchan Kim791b48b2017-05-12 15:47:06 -07001976 /*
1977 * Do not count skipped pages because that makes the function
1978 * return with no isolated pages if the LRU mostly contains
1979 * ineligible pages. This causes the VM to not reclaim any
1980 * pages, triggering a premature OOM.
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001981 * Account all tail pages of THP.
Minchan Kim791b48b2017-05-12 15:47:06 -07001982 */
Yang Shi98879b32019-07-11 20:59:30 -07001983 scan += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001984
1985 if (!PageLRU(page))
1986 goto move;
1987 if (!sc->may_unmap && page_mapped(page))
1988 goto move;
1989
Alex Shic2135f72021-02-24 12:08:01 -08001990 /*
1991 * Be careful not to clear PageLRU until after we're
1992 * sure the page is not being freed elsewhere -- the
1993 * page release code relies on it.
1994 */
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001995 if (unlikely(!get_page_unless_zero(page)))
1996 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08001997
1998 if (!TestClearPageLRU(page)) {
1999 /* Another thread is already isolating this page */
2000 put_page(page);
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002001 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002002 }
2003
2004 nr_taken += nr_pages;
2005 nr_zone_taken[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002006 move_to = dst;
2007move:
2008 list_move(&page->lru, move_to);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002009 }
2010
Mel Gormanb2e18752016-07-28 15:45:37 -07002011 /*
2012 * Splice any skipped pages to the start of the LRU list. Note that
2013 * this disrupts the LRU order when reclaiming for lower zones but
2014 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2015 * scanning would soon rescan the same pages to skip and put the
2016 * system at risk of premature OOM.
2017 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002018 if (!list_empty(&pages_skipped)) {
2019 int zid;
2020
Johannes Weiner3db65812017-05-03 14:52:13 -07002021 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002022 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2023 if (!nr_skipped[zid])
2024 continue;
2025
2026 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002027 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002028 }
2029 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002030 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002031 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002032 total_scan, skipped, nr_taken,
2033 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002034 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002035 return nr_taken;
2036}
2037
Nick Piggin62695a82008-10-18 20:26:09 -07002038/**
2039 * isolate_lru_page - tries to isolate a page from its LRU list
2040 * @page: page to isolate from its LRU list
2041 *
2042 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2043 * vmstat statistic corresponding to whatever LRU list the page was on.
2044 *
2045 * Returns 0 if the page was removed from an LRU list.
2046 * Returns -EBUSY if the page was not on an LRU list.
2047 *
2048 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002049 * the active list, it will have PageActive set. If it was found on
2050 * the unevictable list, it will have the PageUnevictable bit set. That flag
2051 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002052 *
2053 * The vmstat statistic corresponding to the list on which the page was
2054 * found will be decremented.
2055 *
2056 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002057 *
Nick Piggin62695a82008-10-18 20:26:09 -07002058 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002059 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002060 * without a stable reference).
2061 * (2) the lru_lock must not be held.
2062 * (3) interrupts must be enabled.
2063 */
2064int isolate_lru_page(struct page *page)
2065{
2066 int ret = -EBUSY;
2067
Sasha Levin309381fea2014-01-23 15:52:54 -08002068 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002069 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002070
Alex Shid25b5bd2020-12-15 12:34:16 -08002071 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002072 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002073
Alex Shid25b5bd2020-12-15 12:34:16 -08002074 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002075 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002076 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002077 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002078 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002079 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002080
Nick Piggin62695a82008-10-18 20:26:09 -07002081 return ret;
2082}
2083
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002084/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002085 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002086 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002087 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2088 * the LRU list will go small and be scanned faster than necessary, leading to
2089 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002090 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002091static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002092 struct scan_control *sc)
2093{
2094 unsigned long inactive, isolated;
2095
2096 if (current_is_kswapd())
2097 return 0;
2098
Johannes Weinerb5ead352019-11-30 17:55:40 -08002099 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002100 return 0;
2101
2102 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002103 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2104 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002105 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002106 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2107 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002108 }
2109
Fengguang Wu3cf23842012-12-18 14:23:31 -08002110 /*
2111 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2112 * won't get blocked by normal direct-reclaimers, forming a circular
2113 * deadlock.
2114 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002115 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002116 inactive >>= 3;
2117
Rik van Riel35cd7812009-09-21 17:01:38 -07002118 return isolated > inactive;
2119}
2120
Kirill Tkhaia222f342019-05-13 17:17:00 -07002121/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002122 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2123 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002124 *
2125 * Returns the number of pages moved to the given lruvec.
2126 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002127static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2128 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002129{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002130 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002131 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002132 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002133
Kirill Tkhaia222f342019-05-13 17:17:00 -07002134 while (!list_empty(list)) {
2135 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002136 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002137 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002138 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002139 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002140 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002141 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002142 continue;
2143 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002144
Alex Shi3d06afa2020-12-15 12:33:37 -08002145 /*
2146 * The SetPageLRU needs to be kept here for list integrity.
2147 * Otherwise:
2148 * #0 move_pages_to_lru #1 release_pages
2149 * if !put_page_testzero
2150 * if (put_page_testzero())
2151 * !PageLRU //skip lru_lock
2152 * SetPageLRU()
2153 * list_add(&page->lru,)
2154 * list_add(&page->lru,)
2155 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002156 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002157
Alex Shi3d06afa2020-12-15 12:33:37 -08002158 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002159 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002160
2161 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002162 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002163 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002164 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002165 } else
2166 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002167
2168 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002169 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002170
Alex Shiafca9152020-12-15 12:34:02 -08002171 /*
2172 * All pages were isolated from the same lruvec (and isolation
2173 * inhibits memcg migration).
2174 */
Muchun Song7467c392021-06-28 19:37:59 -07002175 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002176 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002177 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002178 nr_moved += nr_pages;
2179 if (PageActive(page))
2180 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002181 }
Mel Gorman66635622010-08-09 17:19:30 -07002182
Hugh Dickins3f797682012-01-12 17:20:07 -08002183 /*
2184 * To save our caller's stack, now use input list for pages to free.
2185 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002186 list_splice(&pages_to_free, list);
2187
2188 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002189}
2190
2191/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002192 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002193 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002194 * In that case we should only throttle if the backing device it is
2195 * writing to is congested. In other cases it is safe to throttle.
2196 */
2197static int current_may_throttle(void)
2198{
NeilBrowna37b0712020-06-01 21:48:18 -07002199 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002200 current->backing_dev_info == NULL ||
2201 bdi_write_congested(current->backing_dev_info);
2202}
2203
2204/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002205 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002206 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002207 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002208static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002209shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002210 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002211{
2212 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002213 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002214 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002215 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002216 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002217 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002218 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002219 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002220 bool stalled = false;
Minchan Kim7df45e52022-10-27 08:29:17 -07002221 struct blk_plug plug;
2222 bool do_plug = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002223
Mel Gorman599d0c92016-07-28 15:45:31 -07002224 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002225 if (stalled)
2226 return 0;
2227
2228 /* wait a bit for the reclaimer. */
2229 msleep(100);
2230 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002231
2232 /* We are about to die and free our memory. Return now. */
2233 if (fatal_signal_pending(current))
2234 return SWAP_CLUSTER_MAX;
2235 }
2236
Linus Torvalds1da177e2005-04-16 15:20:36 -07002237 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002238
Alex Shi6168d0d2020-12-15 12:34:29 -08002239 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002240
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002241 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002242 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002243
Mel Gorman599d0c92016-07-28 15:45:31 -07002244 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002245 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002246 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002247 __count_vm_events(item, nr_scanned);
2248 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002249 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2250
Alex Shi6168d0d2020-12-15 12:34:29 -08002251 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002252
Hillf Dantond563c052012-03-21 16:34:02 -07002253 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002254 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002255
Minchan Kim7df45e52022-10-27 08:29:17 -07002256 trace_android_vh_shrink_inactive_list_blk_plug(&do_plug);
2257 if (do_plug)
2258 blk_start_plug(&plug);
Shakeel Butt013339d2020-12-14 19:06:39 -08002259 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002260
Alex Shi6168d0d2020-12-15 12:34:29 -08002261 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002262 move_pages_to_lru(lruvec, &page_list);
2263
2264 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002265 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002266 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002267 __count_vm_events(item, nr_reclaimed);
2268 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002269 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002270 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002271
Minchan Kim7df45e52022-10-27 08:29:17 -07002272 if (do_plug)
2273 blk_finish_plug(&plug);
2274
Alex Shi75cc3c92020-12-15 14:20:50 -08002275 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002276 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002277 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002278
Mel Gorman92df3a72011-10-31 17:07:56 -07002279 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002280 * If dirty pages are scanned that are not queued for IO, it
2281 * implies that flushers are not doing their job. This can
2282 * happen when memory pressure pushes dirty pages to the end of
2283 * the LRU before the dirty limits are breached and the dirty
2284 * data has expired. It can also happen when the proportion of
2285 * dirty pages grows not through writes but through memory
2286 * pressure reclaiming all the clean cache. And in some cases,
2287 * the flushers simply cannot keep up with the allocation
2288 * rate. Nudge the flusher threads in case they are asleep.
2289 */
2290 if (stat.nr_unqueued_dirty == nr_taken)
2291 wakeup_flusher_threads(WB_REASON_VMSCAN);
2292
Andrey Ryabinind108c772018-04-10 16:27:59 -07002293 sc->nr.dirty += stat.nr_dirty;
2294 sc->nr.congested += stat.nr_congested;
2295 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2296 sc->nr.writeback += stat.nr_writeback;
2297 sc->nr.immediate += stat.nr_immediate;
2298 sc->nr.taken += nr_taken;
2299 if (file)
2300 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002301
Mel Gorman599d0c92016-07-28 15:45:31 -07002302 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002303 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002304 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002305}
2306
Hugh Dickins15b44732020-12-15 14:21:31 -08002307/*
2308 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2309 *
2310 * We move them the other way if the page is referenced by one or more
2311 * processes.
2312 *
2313 * If the pages are mostly unmapped, the processing is fast and it is
2314 * appropriate to hold lru_lock across the whole operation. But if
2315 * the pages are mapped, the processing is slow (page_referenced()), so
2316 * we should drop lru_lock around each page. It's impossible to balance
2317 * this, so instead we remove the pages from the LRU while processing them.
2318 * It is safe to rely on PG_active against the non-LRU pages in here because
2319 * nobody will play with that bit on a non-LRU page.
2320 *
2321 * The downside is that we have to touch page->_refcount against each page.
2322 * But we had to alter page->flags anyway.
2323 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002324static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002325 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002326 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002327 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002328{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002329 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002330 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002331 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002332 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002333 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002334 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002335 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002336 unsigned nr_deactivate, nr_activate;
2337 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002338 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002339 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002340 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002341
2342 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002343
Alex Shi6168d0d2020-12-15 12:34:29 -08002344 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002345
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002346 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002347 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002348
Mel Gorman599d0c92016-07-28 15:45:31 -07002349 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002350
Shakeel Butt912c0572020-08-06 23:26:32 -07002351 if (!cgroup_reclaim(sc))
2352 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002353 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002354
Alex Shi6168d0d2020-12-15 12:34:29 -08002355 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002356
Linus Torvalds1da177e2005-04-16 15:20:36 -07002357 while (!list_empty(&l_hold)) {
2358 cond_resched();
2359 page = lru_to_page(&l_hold);
2360 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002361
Hugh Dickins39b5f292012-10-08 16:33:18 -07002362 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002363 putback_lru_page(page);
2364 continue;
2365 }
2366
Mel Gormancc715d92012-03-21 16:34:00 -07002367 if (unlikely(buffer_heads_over_limit)) {
2368 if (page_has_private(page) && trylock_page(page)) {
2369 if (page_has_private(page))
2370 try_to_release_page(page, 0);
2371 unlock_page(page);
2372 }
2373 }
2374
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002375 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2376 if (bypass)
2377 goto skip_page_referenced;
2378
Minchan Kimf74aca72022-05-19 14:08:54 -07002379 /* Referenced or rmap lock contention: rotate */
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002380 if (page_referenced(page, 0, sc->target_mem_cgroup,
Minchan Kimf74aca72022-05-19 14:08:54 -07002381 &vm_flags) != 0) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002382 /*
2383 * Identify referenced, file-backed active pages and
2384 * give them one more trip around the active list. So
2385 * that executable code get better chances to stay in
2386 * memory under moderate memory pressure. Anon pages
2387 * are not likely to be evicted by use-once streaming
2388 * IO, plus JVM can create lots of anon VM_EXEC pages,
2389 * so we ignore them here.
2390 */
Huang Ying9de4f222020-04-06 20:04:41 -07002391 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002392 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002393 list_add(&page->lru, &l_active);
2394 continue;
2395 }
2396 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002397skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002398 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002399 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002400 list_add(&page->lru, &l_inactive);
2401 }
2402
Andrew Mortonb5557492009-01-06 14:40:13 -08002403 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002404 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002405 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002406 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002407
Kirill Tkhaia222f342019-05-13 17:17:00 -07002408 nr_activate = move_pages_to_lru(lruvec, &l_active);
2409 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002410 /* Keep all free pages in l_active list */
2411 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002412
2413 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2414 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2415
Mel Gorman599d0c92016-07-28 15:45:31 -07002416 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002417 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002418
Kirill Tkhaif372d892019-05-13 17:16:57 -07002419 mem_cgroup_uncharge_list(&l_active);
2420 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002421 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2422 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002423}
2424
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002425unsigned long reclaim_pages(struct list_head *page_list)
2426{
Yang Shif661d002020-04-01 21:10:05 -07002427 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002428 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002429 LIST_HEAD(node_page_list);
2430 struct reclaim_stat dummy_stat;
2431 struct page *page;
Minchan Kim7df45e52022-10-27 08:29:17 -07002432 struct blk_plug plug;
2433 bool do_plug = false;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002434 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002435 struct scan_control sc = {
2436 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002437 .may_writepage = 1,
2438 .may_unmap = 1,
2439 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002440 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002441 };
2442
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002443 noreclaim_flag = memalloc_noreclaim_save();
2444
Minchan Kim7df45e52022-10-27 08:29:17 -07002445 trace_android_vh_reclaim_pages_plug(&do_plug);
2446 if (do_plug)
2447 blk_start_plug(&plug);
2448
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002449 while (!list_empty(page_list)) {
2450 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002451 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002452 nid = page_to_nid(page);
2453 INIT_LIST_HEAD(&node_page_list);
2454 }
2455
2456 if (nid == page_to_nid(page)) {
2457 ClearPageActive(page);
2458 list_move(&page->lru, &node_page_list);
2459 continue;
2460 }
2461
2462 nr_reclaimed += shrink_page_list(&node_page_list,
2463 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002464 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002465 while (!list_empty(&node_page_list)) {
2466 page = lru_to_page(&node_page_list);
2467 list_del(&page->lru);
2468 putback_lru_page(page);
2469 }
2470
Yang Shif661d002020-04-01 21:10:05 -07002471 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002472 }
2473
2474 if (!list_empty(&node_page_list)) {
2475 nr_reclaimed += shrink_page_list(&node_page_list,
2476 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002477 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002478 while (!list_empty(&node_page_list)) {
2479 page = lru_to_page(&node_page_list);
2480 list_del(&page->lru);
2481 putback_lru_page(page);
2482 }
2483 }
2484
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002485 memalloc_noreclaim_restore(noreclaim_flag);
2486
Minchan Kim7df45e52022-10-27 08:29:17 -07002487 if (do_plug)
2488 blk_finish_plug(&plug);
2489
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002490 return nr_reclaimed;
2491}
2492
Johannes Weinerb91ac372019-11-30 17:56:02 -08002493static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2494 struct lruvec *lruvec, struct scan_control *sc)
2495{
2496 if (is_active_lru(lru)) {
2497 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2498 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2499 else
2500 sc->skipped_deactivate = 1;
2501 return 0;
2502 }
2503
2504 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2505}
2506
Rik van Riel59dc76b2016-05-20 16:56:31 -07002507/*
2508 * The inactive anon list should be small enough that the VM never has
2509 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002510 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002511 * The inactive file list should be small enough to leave most memory
2512 * to the established workingset on the scan-resistant active list,
2513 * but large enough to avoid thrashing the aggregate readahead window.
2514 *
2515 * Both inactive lists should also be large enough that each inactive
2516 * page has a chance to be referenced again before it is reclaimed.
2517 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002518 * If that fails and refaulting is observed, the inactive list grows.
2519 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002520 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002521 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002522 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2523 *
2524 * total target max
2525 * memory ratio inactive
2526 * -------------------------------------
2527 * 10MB 1 5MB
2528 * 100MB 1 50MB
2529 * 1GB 3 250MB
2530 * 10GB 10 0.9GB
2531 * 100GB 31 3GB
2532 * 1TB 101 10GB
2533 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002534 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002535static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002536{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002537 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002538 unsigned long inactive, active;
2539 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002540 unsigned long gb;
2541
Johannes Weinerb91ac372019-11-30 17:56:02 -08002542 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2543 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002544
Johannes Weinerb91ac372019-11-30 17:56:02 -08002545 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002546 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002547 inactive_ratio = int_sqrt(10 * gb);
2548 else
2549 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002550
Rik van Riel59dc76b2016-05-20 16:56:31 -07002551 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002552}
2553
Johannes Weiner9a265112013-02-22 16:32:17 -08002554enum scan_balance {
2555 SCAN_EQUAL,
2556 SCAN_FRACT,
2557 SCAN_ANON,
2558 SCAN_FILE,
2559};
2560
Yu Zhao6d313442022-09-18 02:00:00 -06002561static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2562{
2563 unsigned long file;
2564 struct lruvec *target_lruvec;
2565
Yu Zhao37397872022-09-18 02:00:03 -06002566 if (lru_gen_enabled())
2567 return;
2568
Yu Zhao6d313442022-09-18 02:00:00 -06002569 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2570
2571 /*
2572 * Flush the memory cgroup stats, so that we read accurate per-memcg
2573 * lruvec stats for heuristics.
2574 */
2575 mem_cgroup_flush_stats();
2576
2577 /*
2578 * Determine the scan balance between anon and file LRUs.
2579 */
2580 spin_lock_irq(&target_lruvec->lru_lock);
2581 sc->anon_cost = target_lruvec->anon_cost;
2582 sc->file_cost = target_lruvec->file_cost;
2583 spin_unlock_irq(&target_lruvec->lru_lock);
2584
2585 /*
2586 * Target desirable inactive:active list ratios for the anon
2587 * and file LRU lists.
2588 */
2589 if (!sc->force_deactivate) {
2590 unsigned long refaults;
2591
2592 refaults = lruvec_page_state(target_lruvec,
2593 WORKINGSET_ACTIVATE_ANON);
2594 if (refaults != target_lruvec->refaults[0] ||
2595 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2596 sc->may_deactivate |= DEACTIVATE_ANON;
2597 else
2598 sc->may_deactivate &= ~DEACTIVATE_ANON;
2599
2600 /*
2601 * When refaults are being observed, it means a new
2602 * workingset is being established. Deactivate to get
2603 * rid of any stale active pages quickly.
2604 */
2605 refaults = lruvec_page_state(target_lruvec,
2606 WORKINGSET_ACTIVATE_FILE);
2607 if (refaults != target_lruvec->refaults[1] ||
2608 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2609 sc->may_deactivate |= DEACTIVATE_FILE;
2610 else
2611 sc->may_deactivate &= ~DEACTIVATE_FILE;
2612 } else
2613 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2614
2615 /*
2616 * If we have plenty of inactive file pages that aren't
2617 * thrashing, try to reclaim those first before touching
2618 * anonymous pages.
2619 */
2620 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2621 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2622 sc->cache_trim_mode = 1;
2623 else
2624 sc->cache_trim_mode = 0;
2625
2626 /*
2627 * Prevent the reclaimer from falling into the cache trap: as
2628 * cache pages start out inactive, every cache fault will tip
2629 * the scan balance towards the file LRU. And as the file LRU
2630 * shrinks, so does the window for rotation from references.
2631 * This means we have a runaway feedback loop where a tiny
2632 * thrashing file LRU becomes infinitely more attractive than
2633 * anon pages. Try to detect this based on file LRU size.
2634 */
2635 if (!cgroup_reclaim(sc)) {
2636 unsigned long total_high_wmark = 0;
2637 unsigned long free, anon;
2638 int z;
2639
2640 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2641 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2642 node_page_state(pgdat, NR_INACTIVE_FILE);
2643
2644 for (z = 0; z < MAX_NR_ZONES; z++) {
2645 struct zone *zone = &pgdat->node_zones[z];
2646
2647 if (!managed_zone(zone))
2648 continue;
2649
2650 total_high_wmark += high_wmark_pages(zone);
2651 }
2652
2653 /*
2654 * Consider anon: if that's low too, this isn't a
2655 * runaway file reclaim problem, but rather just
2656 * extreme pressure. Reclaim as per usual then.
2657 */
2658 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2659
2660 sc->file_is_tiny =
2661 file + free <= total_high_wmark &&
2662 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2663 anon >> sc->priority;
2664 }
2665}
2666
Linus Torvalds1da177e2005-04-16 15:20:36 -07002667/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002668 * Determine how aggressively the anon and file LRU lists should be
2669 * scanned. The relative value of each set of LRU lists is determined
2670 * by looking at the fraction of the pages scanned we did rotate back
2671 * onto the active list instead of evict.
2672 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002673 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2674 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002675 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002676static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2677 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002678{
Keith Buscha2a36482021-09-02 14:59:26 -07002679 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002680 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002681 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002682 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002683 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002684 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002685 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002686 unsigned long ap, fp;
2687 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002688 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002689
2690 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002691 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002692 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002693 goto out;
2694 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002695
Johannes Weiner10316b32013-02-22 16:32:14 -08002696 /*
2697 * Global reclaim will swap to prevent OOM even with no
2698 * swappiness, but memcg users want to use this knob to
2699 * disable swapping for individual groups completely when
2700 * using the memory controller's swap limit feature would be
2701 * too expensive.
2702 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002703 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002704 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002705 goto out;
2706 }
2707
2708 /*
2709 * Do not apply any pressure balancing cleverness when the
2710 * system is close to OOM, scan both anon and file equally
2711 * (unless the swappiness setting disagrees with swapping).
2712 */
Johannes Weiner02695172014-08-06 16:06:17 -07002713 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002714 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002715 goto out;
2716 }
2717
Johannes Weiner11d16c22013-02-22 16:32:15 -08002718 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002719 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002720 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002721 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002722 scan_balance = SCAN_ANON;
2723 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002724 }
2725
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002726 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2727
Johannes Weiner62376252014-05-06 12:50:07 -07002728 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002729 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002730 * anything from the anonymous working right now. But when balancing
2731 * anon and page cache files for reclaim, allow swapping of anon pages
2732 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002733 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002734 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002735 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002736 goto out;
2737 }
2738
Johannes Weiner9a265112013-02-22 16:32:17 -08002739 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002740 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002741 * Calculate the pressure balance between anon and file pages.
2742 *
2743 * The amount of pressure we put on each LRU is inversely
2744 * proportional to the cost of reclaiming each list, as
2745 * determined by the share of pages that are refaulting, times
2746 * the relative IO cost of bringing back a swapped out
2747 * anonymous page vs reloading a filesystem page (swappiness).
2748 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002749 * Although we limit that influence to ensure no list gets
2750 * left behind completely: at least a third of the pressure is
2751 * applied, before swappiness.
2752 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002753 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002754 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002755 total_cost = sc->anon_cost + sc->file_cost;
2756 anon_cost = total_cost + sc->anon_cost;
2757 file_cost = total_cost + sc->file_cost;
2758 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002759
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002760 ap = swappiness * (total_cost + 1);
2761 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002762
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002763 fp = (200 - swappiness) * (total_cost + 1);
2764 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002765
Shaohua Li76a33fc2010-05-24 14:32:36 -07002766 fraction[0] = ap;
2767 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002768 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002769out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002770 for_each_evictable_lru(lru) {
2771 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002772 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002773 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002774 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002775
Chris Down9783aa92019-10-06 17:58:32 -07002776 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002777 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2778 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002779
Johannes Weinerf56ce412021-08-19 19:04:21 -07002780 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002781 /*
2782 * Scale a cgroup's reclaim pressure by proportioning
2783 * its current usage to its memory.low or memory.min
2784 * setting.
2785 *
2786 * This is important, as otherwise scanning aggression
2787 * becomes extremely binary -- from nothing as we
2788 * approach the memory protection threshold, to totally
2789 * nominal as we exceed it. This results in requiring
2790 * setting extremely liberal protection thresholds. It
2791 * also means we simply get no protection at all if we
2792 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002793 *
2794 * If there is any protection in place, we reduce scan
2795 * pressure by how much of the total memory used is
2796 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002797 *
Chris Down9de7ca42019-10-06 17:58:35 -07002798 * There is one special case: in the first reclaim pass,
2799 * we skip over all groups that are within their low
2800 * protection. If that fails to reclaim enough pages to
2801 * satisfy the reclaim goal, we come back and override
2802 * the best-effort low protection. However, we still
2803 * ideally want to honor how well-behaved groups are in
2804 * that case instead of simply punishing them all
2805 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002806 * memory they are using, reducing the scan pressure
2807 * again by how much of the total memory used is under
2808 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002809 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002810 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002811 unsigned long protection;
2812
2813 /* memory.low scaling, make sure we retry before OOM */
2814 if (!sc->memcg_low_reclaim && low > min) {
2815 protection = low;
2816 sc->memcg_low_skipped = 1;
2817 } else {
2818 protection = min;
2819 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002820
2821 /* Avoid TOCTOU with earlier protection check */
2822 cgroup_size = max(cgroup_size, protection);
2823
2824 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002825 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002826
2827 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002828 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002829 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002830 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002831 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002832 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002833 } else {
2834 scan = lruvec_size;
2835 }
2836
2837 scan >>= sc->priority;
2838
Johannes Weiner688035f2017-05-03 14:52:07 -07002839 /*
2840 * If the cgroup's already been deleted, make sure to
2841 * scrape out the remaining cache.
2842 */
2843 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002844 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002845
Johannes Weiner688035f2017-05-03 14:52:07 -07002846 switch (scan_balance) {
2847 case SCAN_EQUAL:
2848 /* Scan lists relative to size */
2849 break;
2850 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002851 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002852 * Scan types proportional to swappiness and
2853 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002854 * Make sure we don't miss the last page on
2855 * the offlined memory cgroups because of a
2856 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002857 */
Gavin Shan76073c62020-02-20 20:04:24 -08002858 scan = mem_cgroup_online(memcg) ?
2859 div64_u64(scan * fraction[file], denominator) :
2860 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002861 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002862 break;
2863 case SCAN_FILE:
2864 case SCAN_ANON:
2865 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002866 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002867 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002868 break;
2869 default:
2870 /* Look ma, no brain */
2871 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002872 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002873
Johannes Weiner688035f2017-05-03 14:52:07 -07002874 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002875 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002876}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002877
Dave Hansen2f368a92021-09-02 14:59:23 -07002878/*
2879 * Anonymous LRU management is a waste if there is
2880 * ultimately no way to reclaim the memory.
2881 */
2882static bool can_age_anon_pages(struct pglist_data *pgdat,
2883 struct scan_control *sc)
2884{
2885 /* Aging the anon LRU is valuable if swap is present: */
2886 if (total_swap_pages > 0)
2887 return true;
2888
2889 /* Also valuable if anon pages can be demoted: */
2890 return can_demote(pgdat->node_id, sc);
2891}
2892
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002893#ifdef CONFIG_LRU_GEN
2894
Yu Zhaobaeb9a02022-09-18 02:00:07 -06002895#ifdef CONFIG_LRU_GEN_ENABLED
2896DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2897#define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2898#else
2899DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2900#define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2901#endif
2902
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002903/******************************************************************************
2904 * shorthand helpers
2905 ******************************************************************************/
2906
Yu Zhao37397872022-09-18 02:00:03 -06002907#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2908
2909#define DEFINE_MAX_SEQ(lruvec) \
2910 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2911
2912#define DEFINE_MIN_SEQ(lruvec) \
2913 unsigned long min_seq[ANON_AND_FILE] = { \
2914 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2915 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2916 }
2917
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002918#define for_each_gen_type_zone(gen, type, zone) \
2919 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2920 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2921 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2922
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002923static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002924{
2925 struct pglist_data *pgdat = NODE_DATA(nid);
2926
2927#ifdef CONFIG_MEMCG
2928 if (memcg) {
2929 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2930
2931 /* for hotadd_new_pgdat() */
2932 if (!lruvec->pgdat)
2933 lruvec->pgdat = pgdat;
2934
2935 return lruvec;
2936 }
2937#endif
2938 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2939
2940 return pgdat ? &pgdat->__lruvec : NULL;
2941}
2942
Yu Zhao37397872022-09-18 02:00:03 -06002943static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2944{
2945 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2946 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2947
Kalesh Singh650081b2023-02-14 14:17:57 -08002948 if (!can_demote(pgdat->node_id, sc))
Yu Zhao37397872022-09-18 02:00:03 -06002949 return 0;
2950
2951 return mem_cgroup_swappiness(memcg);
2952}
2953
2954static int get_nr_gens(struct lruvec *lruvec, int type)
2955{
2956 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2957}
2958
2959static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2960{
Yu Zhao3c6c3592022-12-21 21:18:59 -07002961 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06002962 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2963 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2964 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2965}
2966
2967/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002968 * mm_struct list
2969 ******************************************************************************/
2970
2971static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
2972{
2973 static struct lru_gen_mm_list mm_list = {
2974 .fifo = LIST_HEAD_INIT(mm_list.fifo),
2975 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
2976 };
2977
2978#ifdef CONFIG_MEMCG
2979 if (memcg)
2980 return &memcg->mm_list;
2981#endif
2982 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2983
2984 return &mm_list;
2985}
2986
2987void lru_gen_add_mm(struct mm_struct *mm)
2988{
2989 int nid;
2990 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
2991 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
2992
2993 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
2994#ifdef CONFIG_MEMCG
2995 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
2996 mm->lru_gen.memcg = memcg;
2997#endif
2998 spin_lock(&mm_list->lock);
2999
3000 for_each_node_state(nid, N_MEMORY) {
3001 struct lruvec *lruvec = get_lruvec(memcg, nid);
3002
3003 if (!lruvec)
3004 continue;
3005
3006 /* the first addition since the last iteration */
3007 if (lruvec->mm_state.tail == &mm_list->fifo)
3008 lruvec->mm_state.tail = &mm->lru_gen.list;
3009 }
3010
3011 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3012
3013 spin_unlock(&mm_list->lock);
3014}
3015
3016void lru_gen_del_mm(struct mm_struct *mm)
3017{
3018 int nid;
3019 struct lru_gen_mm_list *mm_list;
3020 struct mem_cgroup *memcg = NULL;
3021
3022 if (list_empty(&mm->lru_gen.list))
3023 return;
3024
3025#ifdef CONFIG_MEMCG
3026 memcg = mm->lru_gen.memcg;
3027#endif
3028 mm_list = get_mm_list(memcg);
3029
3030 spin_lock(&mm_list->lock);
3031
3032 for_each_node(nid) {
3033 struct lruvec *lruvec = get_lruvec(memcg, nid);
3034
3035 if (!lruvec)
3036 continue;
3037
3038 /* where the last iteration ended (exclusive) */
3039 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3040 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3041
3042 /* where the current iteration continues (inclusive) */
3043 if (lruvec->mm_state.head != &mm->lru_gen.list)
3044 continue;
3045
3046 lruvec->mm_state.head = lruvec->mm_state.head->next;
3047 /* the deletion ends the current iteration */
3048 if (lruvec->mm_state.head == &mm_list->fifo)
3049 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3050 }
3051
3052 list_del_init(&mm->lru_gen.list);
3053
3054 spin_unlock(&mm_list->lock);
3055
3056#ifdef CONFIG_MEMCG
3057 mem_cgroup_put(mm->lru_gen.memcg);
3058 mm->lru_gen.memcg = NULL;
3059#endif
3060}
3061
3062#ifdef CONFIG_MEMCG
3063void lru_gen_migrate_mm(struct mm_struct *mm)
3064{
3065 struct mem_cgroup *memcg;
3066 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3067
3068 VM_WARN_ON_ONCE(task->mm != mm);
3069 lockdep_assert_held(&task->alloc_lock);
3070
3071 /* for mm_update_next_owner() */
3072 if (mem_cgroup_disabled())
3073 return;
3074
Yu Zhao578a3a32023-01-15 20:44:05 -07003075 /* migration can happen before addition */
3076 if (!mm->lru_gen.memcg)
3077 return;
3078
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003079 rcu_read_lock();
3080 memcg = mem_cgroup_from_task(task);
3081 rcu_read_unlock();
3082 if (memcg == mm->lru_gen.memcg)
3083 return;
3084
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003085 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3086
3087 lru_gen_del_mm(mm);
3088 lru_gen_add_mm(mm);
3089}
3090#endif
3091
3092/*
3093 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3094 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3095 * bits in a bitmap, k is the number of hash functions and n is the number of
3096 * inserted items.
3097 *
3098 * Page table walkers use one of the two filters to reduce their search space.
3099 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3100 * aging uses the double-buffering technique to flip to the other filter each
3101 * time it produces a new generation. For non-leaf entries that have enough
3102 * leaf entries, the aging carries them over to the next generation in
3103 * walk_pmd_range(); the eviction also report them when walking the rmap
3104 * in lru_gen_look_around().
3105 *
3106 * For future optimizations:
3107 * 1. It's not necessary to keep both filters all the time. The spare one can be
3108 * freed after the RCU grace period and reallocated if needed again.
3109 * 2. And when reallocating, it's worth scaling its size according to the number
3110 * of inserted entries in the other filter, to reduce the memory overhead on
3111 * small systems and false positives on large systems.
3112 * 3. Jenkins' hash function is an alternative to Knuth's.
3113 */
3114#define BLOOM_FILTER_SHIFT 15
3115
3116static inline int filter_gen_from_seq(unsigned long seq)
3117{
3118 return seq % NR_BLOOM_FILTERS;
3119}
3120
3121static void get_item_key(void *item, int *key)
3122{
3123 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3124
3125 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3126
3127 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3128 key[1] = hash >> BLOOM_FILTER_SHIFT;
3129}
3130
3131static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3132{
3133 unsigned long *filter;
3134 int gen = filter_gen_from_seq(seq);
3135
3136 filter = lruvec->mm_state.filters[gen];
3137 if (filter) {
3138 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3139 return;
3140 }
3141
3142 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3143 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3144 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3145}
3146
3147static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3148{
3149 int key[2];
3150 unsigned long *filter;
3151 int gen = filter_gen_from_seq(seq);
3152
3153 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3154 if (!filter)
3155 return;
3156
3157 get_item_key(item, key);
3158
3159 if (!test_bit(key[0], filter))
3160 set_bit(key[0], filter);
3161 if (!test_bit(key[1], filter))
3162 set_bit(key[1], filter);
3163}
3164
3165static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3166{
3167 int key[2];
3168 unsigned long *filter;
3169 int gen = filter_gen_from_seq(seq);
3170
3171 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3172 if (!filter)
3173 return true;
3174
3175 get_item_key(item, key);
3176
3177 return test_bit(key[0], filter) && test_bit(key[1], filter);
3178}
3179
3180static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3181{
3182 int i;
3183 int hist;
3184
3185 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3186
3187 if (walk) {
3188 hist = lru_hist_from_seq(walk->max_seq);
3189
3190 for (i = 0; i < NR_MM_STATS; i++) {
3191 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3192 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3193 walk->mm_stats[i] = 0;
3194 }
3195 }
3196
3197 if (NR_HIST_GENS > 1 && last) {
3198 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3199
3200 for (i = 0; i < NR_MM_STATS; i++)
3201 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3202 }
3203}
3204
3205static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3206{
3207 int type;
3208 unsigned long size = 0;
3209 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3210 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3211
3212 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3213 return true;
3214
3215 clear_bit(key, &mm->lru_gen.bitmap);
3216
3217 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3218 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3219 get_mm_counter(mm, MM_ANONPAGES) +
3220 get_mm_counter(mm, MM_SHMEMPAGES);
3221 }
3222
3223 if (size < MIN_LRU_BATCH)
3224 return true;
3225
3226 return !mmget_not_zero(mm);
3227}
3228
3229static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3230 struct mm_struct **iter)
3231{
3232 bool first = false;
3233 bool last = true;
3234 struct mm_struct *mm = NULL;
3235 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3236 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3237 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3238
3239 /*
3240 * There are four interesting cases for this page table walker:
3241 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3242 * there is nothing left to do.
3243 * 2. It's the first of the current generation, and it needs to reset
3244 * the Bloom filter for the next generation.
3245 * 3. It reaches the end of mm_list, and it needs to increment
3246 * mm_state->seq; the iteration is done.
3247 * 4. It's the last of the current generation, and it needs to reset the
3248 * mm stats counters for the next generation.
3249 */
3250 spin_lock(&mm_list->lock);
3251
3252 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3253 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3254 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3255
3256 if (walk->max_seq <= mm_state->seq) {
3257 if (!*iter)
3258 last = false;
3259 goto done;
3260 }
3261
3262 if (!mm_state->nr_walkers) {
3263 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3264
3265 mm_state->head = mm_list->fifo.next;
3266 first = true;
3267 }
3268
3269 while (!mm && mm_state->head != &mm_list->fifo) {
3270 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3271
3272 mm_state->head = mm_state->head->next;
3273
3274 /* force scan for those added after the last iteration */
3275 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3276 mm_state->tail = mm_state->head;
3277 walk->force_scan = true;
3278 }
3279
3280 if (should_skip_mm(mm, walk))
3281 mm = NULL;
3282 }
3283
3284 if (mm_state->head == &mm_list->fifo)
3285 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3286done:
3287 if (*iter && !mm)
3288 mm_state->nr_walkers--;
3289 if (!*iter && mm)
3290 mm_state->nr_walkers++;
3291
3292 if (mm_state->nr_walkers)
3293 last = false;
3294
3295 if (*iter || last)
3296 reset_mm_stats(lruvec, walk, last);
3297
3298 spin_unlock(&mm_list->lock);
3299
3300 if (mm && first)
3301 reset_bloom_filter(lruvec, walk->max_seq + 1);
3302
3303 if (*iter)
3304 mmput_async(*iter);
3305
3306 *iter = mm;
3307
3308 return last;
3309}
3310
3311static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3312{
3313 bool success = false;
3314 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3315 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3316 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3317
3318 spin_lock(&mm_list->lock);
3319
3320 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3321
3322 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3323 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3324
3325 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3326 reset_mm_stats(lruvec, NULL, true);
3327 success = true;
3328 }
3329
3330 spin_unlock(&mm_list->lock);
3331
3332 return success;
3333}
3334
3335/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003336 * refault feedback loop
3337 ******************************************************************************/
3338
3339/*
3340 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3341 *
3342 * The P term is refaulted/(evicted+protected) from a tier in the generation
3343 * currently being evicted; the I term is the exponential moving average of the
3344 * P term over the generations previously evicted, using the smoothing factor
3345 * 1/2; the D term isn't supported.
3346 *
3347 * The setpoint (SP) is always the first tier of one type; the process variable
3348 * (PV) is either any tier of the other type or any other tier of the same
3349 * type.
3350 *
3351 * The error is the difference between the SP and the PV; the correction is to
3352 * turn off protection when SP>PV or turn on protection when SP<PV.
3353 *
3354 * For future optimizations:
3355 * 1. The D term may discount the other two terms over time so that long-lived
3356 * generations can resist stale information.
3357 */
3358struct ctrl_pos {
3359 unsigned long refaulted;
3360 unsigned long total;
3361 int gain;
3362};
3363
3364static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3365 struct ctrl_pos *pos)
3366{
Yu Zhao3c6c3592022-12-21 21:18:59 -07003367 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003368 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3369
3370 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3371 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3372 pos->total = lrugen->avg_total[type][tier] +
3373 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3374 if (tier)
3375 pos->total += lrugen->protected[hist][type][tier - 1];
3376 pos->gain = gain;
3377}
3378
3379static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3380{
3381 int hist, tier;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003382 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003383 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3384 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3385
3386 lockdep_assert_held(&lruvec->lru_lock);
3387
3388 if (!carryover && !clear)
3389 return;
3390
3391 hist = lru_hist_from_seq(seq);
3392
3393 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3394 if (carryover) {
3395 unsigned long sum;
3396
3397 sum = lrugen->avg_refaulted[type][tier] +
3398 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3399 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3400
3401 sum = lrugen->avg_total[type][tier] +
3402 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3403 if (tier)
3404 sum += lrugen->protected[hist][type][tier - 1];
3405 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3406 }
3407
3408 if (clear) {
3409 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3410 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3411 if (tier)
3412 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3413 }
3414 }
3415}
3416
3417static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3418{
3419 /*
3420 * Return true if the PV has a limited number of refaults or a lower
3421 * refaulted/total than the SP.
3422 */
3423 return pv->refaulted < MIN_LRU_BATCH ||
3424 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3425 (sp->refaulted + 1) * pv->total * pv->gain;
3426}
3427
3428/******************************************************************************
3429 * the aging
3430 ******************************************************************************/
3431
Yu Zhao0182f922022-09-18 02:00:04 -06003432/* promote pages accessed through page tables */
3433static int page_update_gen(struct page *page, int gen)
3434{
3435 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3436
3437 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3438 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3439
3440 do {
3441 /* lru_gen_del_page() has isolated this page? */
3442 if (!(old_flags & LRU_GEN_MASK)) {
3443 /* for shrink_page_list() */
3444 new_flags = old_flags | BIT(PG_referenced);
3445 continue;
3446 }
3447
3448 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3449 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3450 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3451
3452 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3453}
3454
Yu Zhao37397872022-09-18 02:00:03 -06003455/* protect pages accessed multiple times through file descriptors */
3456static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3457{
3458 int type = page_is_file_lru(page);
Yu Zhao3c6c3592022-12-21 21:18:59 -07003459 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003460 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3461 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3462
3463 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3464
3465 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003466 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3467 /* page_update_gen() has promoted this page? */
3468 if (new_gen >= 0 && new_gen != old_gen)
3469 return new_gen;
3470
Yu Zhao37397872022-09-18 02:00:03 -06003471 new_gen = (old_gen + 1) % MAX_NR_GENS;
3472
3473 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3474 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3475 /* for end_page_writeback() */
3476 if (reclaiming)
3477 new_flags |= BIT(PG_reclaim);
3478 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3479
3480 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3481
3482 return new_gen;
3483}
3484
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003485static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3486 int old_gen, int new_gen)
3487{
3488 int type = page_is_file_lru(page);
3489 int zone = page_zonenum(page);
3490 int delta = thp_nr_pages(page);
3491
3492 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3493 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3494
3495 walk->batched++;
3496
3497 walk->nr_pages[old_gen][type][zone] -= delta;
3498 walk->nr_pages[new_gen][type][zone] += delta;
3499}
3500
3501static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3502{
3503 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003504 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003505
3506 walk->batched = 0;
3507
3508 for_each_gen_type_zone(gen, type, zone) {
3509 enum lru_list lru = type * LRU_INACTIVE_FILE;
3510 int delta = walk->nr_pages[gen][type][zone];
3511
3512 if (!delta)
3513 continue;
3514
3515 walk->nr_pages[gen][type][zone] = 0;
3516 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3517 lrugen->nr_pages[gen][type][zone] + delta);
3518
3519 if (lru_gen_is_active(lruvec, gen))
3520 lru += LRU_ACTIVE;
3521 __update_lru_size(lruvec, lru, zone, delta);
3522 }
3523}
3524
3525static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3526{
3527 struct address_space *mapping;
3528 struct vm_area_struct *vma = args->vma;
3529 struct lru_gen_mm_walk *walk = args->private;
3530
3531 if (!vma_is_accessible(vma))
3532 return true;
3533
3534 if (is_vm_hugetlb_page(vma))
3535 return true;
3536
3537 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3538 return true;
3539
3540 if (vma == get_gate_vma(vma->vm_mm))
3541 return true;
3542
3543 if (vma_is_anonymous(vma))
3544 return !walk->can_swap;
3545
3546 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3547 return true;
3548
3549 mapping = vma->vm_file->f_mapping;
3550 if (mapping_unevictable(mapping))
3551 return true;
3552
3553 if (shmem_mapping(mapping))
3554 return !walk->can_swap;
3555
3556 /* to exclude special mappings like dax, etc. */
3557 return !mapping->a_ops->readpage;
3558}
3559
3560/*
3561 * Some userspace memory allocators map many single-page VMAs. Instead of
3562 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3563 * table to reduce zigzags and improve cache performance.
3564 */
3565static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3566 unsigned long *vm_start, unsigned long *vm_end)
3567{
3568 unsigned long start = round_up(*vm_end, size);
3569 unsigned long end = (start | ~mask) + 1;
3570
3571 VM_WARN_ON_ONCE(mask & size);
3572 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3573
3574 while (args->vma) {
3575 if (start >= args->vma->vm_end) {
3576 args->vma = args->vma->vm_next;
3577 continue;
3578 }
3579
3580 if (end && end <= args->vma->vm_start)
3581 return false;
3582
3583 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3584 args->vma = args->vma->vm_next;
3585 continue;
3586 }
3587
3588 *vm_start = max(start, args->vma->vm_start);
3589 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3590
3591 return true;
3592 }
3593
3594 return false;
3595}
3596
Yu Zhao0182f922022-09-18 02:00:04 -06003597static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3598{
3599 unsigned long pfn = pte_pfn(pte);
3600
3601 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3602
3603 if (!pte_present(pte) || is_zero_pfn(pfn))
3604 return -1;
3605
3606 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3607 return -1;
3608
3609 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3610 return -1;
3611
3612 return pfn;
3613}
3614
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003615#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3616static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3617{
3618 unsigned long pfn = pmd_pfn(pmd);
3619
3620 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3621
3622 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3623 return -1;
3624
3625 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3626 return -1;
3627
3628 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3629 return -1;
3630
3631 return pfn;
3632}
3633#endif
3634
Yu Zhao0182f922022-09-18 02:00:04 -06003635static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003636 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003637{
3638 struct page *page;
3639
3640 /* try to avoid unnecessary memory loads */
3641 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3642 return NULL;
3643
3644 page = compound_head(pfn_to_page(pfn));
3645 if (page_to_nid(page) != pgdat->node_id)
3646 return NULL;
3647
3648 if (page_memcg_rcu(page) != memcg)
3649 return NULL;
3650
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003651 /* file VMAs can contain anon pages from COW */
3652 if (!page_is_file_lru(page) && !can_swap)
3653 return NULL;
3654
Yu Zhao0182f922022-09-18 02:00:04 -06003655 return page;
3656}
3657
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003658static bool suitable_to_scan(int total, int young)
3659{
3660 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3661
3662 /* suitable if the average number of young PTEs per cacheline is >=1 */
3663 return young * n >= total;
3664}
3665
3666static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3667 struct mm_walk *args)
3668{
3669 int i;
3670 pte_t *pte;
3671 spinlock_t *ptl;
3672 unsigned long addr;
3673 int total = 0;
3674 int young = 0;
3675 struct lru_gen_mm_walk *walk = args->private;
3676 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3677 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3678 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3679
3680 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3681
3682 ptl = pte_lockptr(args->mm, pmd);
3683 if (!spin_trylock(ptl))
3684 return false;
3685
3686 arch_enter_lazy_mmu_mode();
3687
3688 pte = pte_offset_map(pmd, start & PMD_MASK);
3689restart:
3690 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3691 unsigned long pfn;
3692 struct page *page;
3693
3694 total++;
3695 walk->mm_stats[MM_LEAF_TOTAL]++;
3696
3697 pfn = get_pte_pfn(pte[i], args->vma, addr);
3698 if (pfn == -1)
3699 continue;
3700
3701 if (!pte_young(pte[i])) {
3702 walk->mm_stats[MM_LEAF_OLD]++;
3703 continue;
3704 }
3705
3706 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3707 if (!page)
3708 continue;
3709
3710 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3711 VM_WARN_ON_ONCE(true);
3712
3713 young++;
3714 walk->mm_stats[MM_LEAF_YOUNG]++;
3715
3716 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3717 !(PageAnon(page) && PageSwapBacked(page) &&
3718 !PageSwapCache(page)))
3719 set_page_dirty(page);
3720
3721 old_gen = page_update_gen(page, new_gen);
3722 if (old_gen >= 0 && old_gen != new_gen)
3723 update_batch_size(walk, page, old_gen, new_gen);
3724 }
3725
3726 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3727 goto restart;
3728
3729 pte_unmap(pte);
3730
3731 arch_leave_lazy_mmu_mode();
3732 spin_unlock(ptl);
3733
3734 return suitable_to_scan(total, young);
3735}
3736
3737#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3738static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3739 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3740{
3741 int i;
3742 pmd_t *pmd;
3743 spinlock_t *ptl;
3744 struct lru_gen_mm_walk *walk = args->private;
3745 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3746 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3747 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3748
3749 VM_WARN_ON_ONCE(pud_leaf(*pud));
3750
3751 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3752 if (*start == -1) {
3753 *start = next;
3754 return;
3755 }
3756
3757 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3758 if (i && i <= MIN_LRU_BATCH) {
3759 __set_bit(i - 1, bitmap);
3760 return;
3761 }
3762
3763 pmd = pmd_offset(pud, *start);
3764
3765 ptl = pmd_lockptr(args->mm, pmd);
3766 if (!spin_trylock(ptl))
3767 goto done;
3768
3769 arch_enter_lazy_mmu_mode();
3770
3771 do {
3772 unsigned long pfn;
3773 struct page *page;
3774 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3775
3776 pfn = get_pmd_pfn(pmd[i], vma, addr);
3777 if (pfn == -1)
3778 goto next;
3779
3780 if (!pmd_trans_huge(pmd[i])) {
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003781 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3782 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003783 pmdp_test_and_clear_young(vma, addr, pmd + i);
3784 goto next;
3785 }
3786
3787 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3788 if (!page)
3789 goto next;
3790
3791 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3792 goto next;
3793
3794 walk->mm_stats[MM_LEAF_YOUNG]++;
3795
3796 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3797 !(PageAnon(page) && PageSwapBacked(page) &&
3798 !PageSwapCache(page)))
3799 set_page_dirty(page);
3800
3801 old_gen = page_update_gen(page, new_gen);
3802 if (old_gen >= 0 && old_gen != new_gen)
3803 update_batch_size(walk, page, old_gen, new_gen);
3804next:
3805 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3806 } while (i <= MIN_LRU_BATCH);
3807
3808 arch_leave_lazy_mmu_mode();
3809 spin_unlock(ptl);
3810done:
3811 *start = -1;
3812 bitmap_zero(bitmap, MIN_LRU_BATCH);
3813}
3814#else
3815static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3816 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3817{
3818}
3819#endif
3820
3821static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3822 struct mm_walk *args)
3823{
3824 int i;
3825 pmd_t *pmd;
3826 unsigned long next;
3827 unsigned long addr;
3828 struct vm_area_struct *vma;
3829 unsigned long pos = -1;
3830 struct lru_gen_mm_walk *walk = args->private;
3831 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3832
3833 VM_WARN_ON_ONCE(pud_leaf(*pud));
3834
3835 /*
3836 * Finish an entire PMD in two passes: the first only reaches to PTE
3837 * tables to avoid taking the PMD lock; the second, if necessary, takes
3838 * the PMD lock to clear the accessed bit in PMD entries.
3839 */
3840 pmd = pmd_offset(pud, start & PUD_MASK);
3841restart:
3842 /* walk_pte_range() may call get_next_vma() */
3843 vma = args->vma;
3844 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3845 pmd_t val = pmd_read_atomic(pmd + i);
3846
3847 /* for pmd_read_atomic() */
3848 barrier();
3849
3850 next = pmd_addr_end(addr, end);
3851
3852 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3853 walk->mm_stats[MM_LEAF_TOTAL]++;
3854 continue;
3855 }
3856
3857#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3858 if (pmd_trans_huge(val)) {
3859 unsigned long pfn = pmd_pfn(val);
3860 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3861
3862 walk->mm_stats[MM_LEAF_TOTAL]++;
3863
3864 if (!pmd_young(val)) {
3865 walk->mm_stats[MM_LEAF_OLD]++;
3866 continue;
3867 }
3868
3869 /* try to avoid unnecessary memory loads */
3870 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3871 continue;
3872
3873 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3874 continue;
3875 }
3876#endif
3877 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3878
3879#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003880 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3881 if (!pmd_young(val))
3882 continue;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003883
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003884 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3885 }
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003886#endif
3887 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3888 continue;
3889
3890 walk->mm_stats[MM_NONLEAF_FOUND]++;
3891
3892 if (!walk_pte_range(&val, addr, next, args))
3893 continue;
3894
3895 walk->mm_stats[MM_NONLEAF_ADDED]++;
3896
3897 /* carry over to the next generation */
3898 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3899 }
3900
3901 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3902
3903 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3904 goto restart;
3905}
3906
3907static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3908 struct mm_walk *args)
3909{
3910 int i;
3911 pud_t *pud;
3912 unsigned long addr;
3913 unsigned long next;
3914 struct lru_gen_mm_walk *walk = args->private;
3915
3916 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3917
3918 pud = pud_offset(p4d, start & P4D_MASK);
3919restart:
3920 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3921 pud_t val = READ_ONCE(pud[i]);
3922
3923 next = pud_addr_end(addr, end);
3924
3925 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3926 continue;
3927
3928 walk_pmd_range(&val, addr, next, args);
3929
3930 /* a racy check to curtail the waiting time */
3931 if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
3932 return 1;
3933
3934 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3935 end = (addr | ~PUD_MASK) + 1;
3936 goto done;
3937 }
3938 }
3939
3940 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3941 goto restart;
3942
3943 end = round_up(end, P4D_SIZE);
3944done:
3945 if (!end || !args->vma)
3946 return 1;
3947
3948 walk->next_addr = max(end, args->vma->vm_start);
3949
3950 return -EAGAIN;
3951}
3952
3953static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3954{
3955 static const struct mm_walk_ops mm_walk_ops = {
3956 .test_walk = should_skip_vma,
3957 .p4d_entry = walk_pud_range,
3958 };
3959
3960 int err;
3961 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3962
3963 walk->next_addr = FIRST_USER_ADDRESS;
3964
3965 do {
3966 err = -EBUSY;
3967
3968 /* page_update_gen() requires stable page_memcg() */
3969 if (!mem_cgroup_trylock_pages(memcg))
3970 break;
3971
3972 /* the caller might be holding the lock for write */
3973 if (mmap_read_trylock(mm)) {
3974 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3975
3976 mmap_read_unlock(mm);
3977 }
3978
3979 mem_cgroup_unlock_pages();
3980
3981 if (walk->batched) {
3982 spin_lock_irq(&lruvec->lru_lock);
3983 reset_batch_size(lruvec, walk);
3984 spin_unlock_irq(&lruvec->lru_lock);
3985 }
3986
3987 cond_resched();
3988 } while (err == -EAGAIN);
3989}
3990
3991static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
3992{
3993 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3994
3995 if (pgdat && current_is_kswapd()) {
3996 VM_WARN_ON_ONCE(walk);
3997
3998 walk = &pgdat->mm_walk;
3999 } else if (!pgdat && !walk) {
4000 VM_WARN_ON_ONCE(current_is_kswapd());
4001
4002 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4003 }
4004
4005 current->reclaim_state->mm_walk = walk;
4006
4007 return walk;
4008}
4009
4010static void clear_mm_walk(void)
4011{
4012 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4013
4014 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4015 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4016
4017 current->reclaim_state->mm_walk = NULL;
4018
4019 if (!current_is_kswapd())
4020 kfree(walk);
4021}
4022
Yu Zhao4983c522022-09-18 02:00:09 -06004023static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004024{
Yu Zhao4983c522022-09-18 02:00:09 -06004025 int zone;
4026 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004027 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06004028 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
Yu Zhao37397872022-09-18 02:00:03 -06004029
Yu Zhao4983c522022-09-18 02:00:09 -06004030 if (type == LRU_GEN_ANON && !can_swap)
4031 goto done;
4032
4033 /* prevent cold/hot inversion if force_scan is true */
4034 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004035 struct list_head *head = &lrugen->pages[old_gen][type][zone];
Yu Zhao4983c522022-09-18 02:00:09 -06004036
4037 while (!list_empty(head)) {
4038 struct page *page = lru_to_page(head);
4039
4040 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4041 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4042 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4043 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4044
4045 new_gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004046 list_move_tail(&page->lru, &lrugen->pages[new_gen][type][zone]);
Yu Zhao4983c522022-09-18 02:00:09 -06004047
4048 if (!--remaining)
4049 return false;
4050 }
4051 }
4052done:
Yu Zhao37397872022-09-18 02:00:03 -06004053 reset_ctrl_pos(lruvec, type, true);
4054 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
Yu Zhao4983c522022-09-18 02:00:09 -06004055
4056 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004057}
4058
4059static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4060{
4061 int gen, type, zone;
4062 bool success = false;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004063 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004064 DEFINE_MIN_SEQ(lruvec);
4065
4066 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4067
4068 /* find the oldest populated generation */
4069 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4070 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4071 gen = lru_gen_from_seq(min_seq[type]);
4072
4073 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004074 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhao37397872022-09-18 02:00:03 -06004075 goto next;
4076 }
4077
4078 min_seq[type]++;
4079 }
4080next:
4081 ;
4082 }
4083
Yu Zhao3c6c3592022-12-21 21:18:59 -07004084 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06004085 if (can_swap) {
4086 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4087 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4088 }
4089
4090 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4091 if (min_seq[type] == lrugen->min_seq[type])
4092 continue;
4093
4094 reset_ctrl_pos(lruvec, type, true);
4095 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4096 success = true;
4097 }
4098
4099 return success;
4100}
4101
Yu Zhao4983c522022-09-18 02:00:09 -06004102static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
Yu Zhao37397872022-09-18 02:00:03 -06004103{
4104 int prev, next;
4105 int type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004106 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004107
4108 spin_lock_irq(&lruvec->lru_lock);
4109
4110 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4111
Yu Zhao37397872022-09-18 02:00:03 -06004112 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4113 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4114 continue;
4115
Yu Zhao4983c522022-09-18 02:00:09 -06004116 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
Yu Zhao37397872022-09-18 02:00:03 -06004117
Yu Zhao4983c522022-09-18 02:00:09 -06004118 while (!inc_min_seq(lruvec, type, can_swap)) {
4119 spin_unlock_irq(&lruvec->lru_lock);
4120 cond_resched();
4121 spin_lock_irq(&lruvec->lru_lock);
4122 }
Yu Zhao37397872022-09-18 02:00:03 -06004123 }
4124
4125 /*
4126 * Update the active/inactive LRU sizes for compatibility. Both sides of
4127 * the current max_seq need to be covered, since max_seq+1 can overlap
4128 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4129 * overlap, cold/hot inversion happens.
4130 */
4131 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4132 next = lru_gen_from_seq(lrugen->max_seq + 1);
4133
4134 for (type = 0; type < ANON_AND_FILE; type++) {
4135 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4136 enum lru_list lru = type * LRU_INACTIVE_FILE;
4137 long delta = lrugen->nr_pages[prev][type][zone] -
4138 lrugen->nr_pages[next][type][zone];
4139
4140 if (!delta)
4141 continue;
4142
4143 __update_lru_size(lruvec, lru, zone, delta);
4144 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4145 }
4146 }
4147
4148 for (type = 0; type < ANON_AND_FILE; type++)
4149 reset_ctrl_pos(lruvec, type, false);
4150
Yu Zhao430499c2022-09-18 02:00:08 -06004151 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhao37397872022-09-18 02:00:03 -06004152 /* make sure preceding modifications appear */
4153 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004154
Yu Zhao37397872022-09-18 02:00:03 -06004155 spin_unlock_irq(&lruvec->lru_lock);
4156}
4157
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004158static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
Yu Zhao4983c522022-09-18 02:00:09 -06004159 struct scan_control *sc, bool can_swap, bool force_scan)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004160{
4161 bool success;
4162 struct lru_gen_mm_walk *walk;
4163 struct mm_struct *mm = NULL;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004164 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004165
4166 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4167
4168 /* see the comment in iterate_mm_list() */
4169 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4170 success = false;
4171 goto done;
4172 }
4173
4174 /*
4175 * If the hardware doesn't automatically set the accessed bit, fallback
4176 * to lru_gen_look_around(), which only clears the accessed bit in a
4177 * handful of PTEs. Spreading the work out over a period of time usually
4178 * is less efficient, but it avoids bursty page faults.
4179 */
Yu Zhao4983c522022-09-18 02:00:09 -06004180 if (!force_scan && !(arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004181 success = iterate_mm_list_nowalk(lruvec, max_seq);
4182 goto done;
4183 }
4184
4185 walk = set_mm_walk(NULL);
4186 if (!walk) {
4187 success = iterate_mm_list_nowalk(lruvec, max_seq);
4188 goto done;
4189 }
4190
4191 walk->lruvec = lruvec;
4192 walk->max_seq = max_seq;
4193 walk->can_swap = can_swap;
Yu Zhao4983c522022-09-18 02:00:09 -06004194 walk->force_scan = force_scan;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004195
4196 do {
4197 success = iterate_mm_list(lruvec, walk, &mm);
4198 if (mm)
4199 walk_mm(lruvec, mm, walk);
4200
4201 cond_resched();
4202 } while (mm);
4203done:
4204 if (!success) {
4205 if (sc->priority <= DEF_PRIORITY - 2)
4206 wait_event_killable(lruvec->mm_state.wait,
4207 max_seq < READ_ONCE(lrugen->max_seq));
4208
4209 return max_seq < READ_ONCE(lrugen->max_seq);
4210 }
4211
4212 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4213
Yu Zhao4983c522022-09-18 02:00:09 -06004214 inc_max_seq(lruvec, can_swap, force_scan);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004215 /* either this sees any waiters or they will see updated max_seq */
4216 if (wq_has_sleeper(&lruvec->mm_state.wait))
4217 wake_up_all(&lruvec->mm_state.wait);
4218
4219 return true;
4220}
4221
Yu Zhao37397872022-09-18 02:00:03 -06004222static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
4223 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4224{
4225 int gen, type, zone;
4226 unsigned long old = 0;
4227 unsigned long young = 0;
4228 unsigned long total = 0;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004229 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004230 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4231
4232 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4233 unsigned long seq;
4234
4235 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4236 unsigned long size = 0;
4237
4238 gen = lru_gen_from_seq(seq);
4239
4240 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4241 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4242
4243 total += size;
4244 if (seq == max_seq)
4245 young += size;
4246 else if (seq + MIN_NR_GENS == max_seq)
4247 old += size;
4248 }
4249 }
4250
4251 /* try to scrape all its memory if this memcg was deleted */
4252 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4253
4254 /*
4255 * The aging tries to be lazy to reduce the overhead, while the eviction
4256 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4257 * ideal number of generations is MIN_NR_GENS+1.
4258 */
4259 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
4260 return true;
4261 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4262 return false;
4263
4264 /*
4265 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4266 * of the total number of pages for each generation. A reasonable range
4267 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4268 * aging cares about the upper bound of hot pages, while the eviction
4269 * cares about the lower bound of cold pages.
4270 */
4271 if (young * MIN_NR_GENS > total)
4272 return true;
4273 if (old * (MIN_NR_GENS + 2) < total)
4274 return true;
4275
4276 return false;
4277}
4278
Yu Zhao430499c2022-09-18 02:00:08 -06004279static bool age_lruvec(struct lruvec *lruvec, struct scan_control *sc, unsigned long min_ttl)
Yu Zhao37397872022-09-18 02:00:03 -06004280{
4281 bool need_aging;
4282 unsigned long nr_to_scan;
4283 int swappiness = get_swappiness(lruvec, sc);
4284 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4285 DEFINE_MAX_SEQ(lruvec);
4286 DEFINE_MIN_SEQ(lruvec);
4287
4288 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
4289
4290 mem_cgroup_calculate_protection(NULL, memcg);
4291
4292 if (mem_cgroup_below_min(memcg))
Yu Zhao430499c2022-09-18 02:00:08 -06004293 return false;
Yu Zhao37397872022-09-18 02:00:03 -06004294
4295 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
Yu Zhao430499c2022-09-18 02:00:08 -06004296
4297 if (min_ttl) {
4298 int gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4299 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4300
4301 if (time_is_after_jiffies(birth + min_ttl))
4302 return false;
4303
4304 /* the size is likely too small to be helpful */
4305 if (!nr_to_scan && sc->priority != DEF_PRIORITY)
4306 return false;
4307 }
4308
Yu Zhao37397872022-09-18 02:00:03 -06004309 if (need_aging)
Yu Zhao4983c522022-09-18 02:00:09 -06004310 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
Yu Zhao430499c2022-09-18 02:00:08 -06004311
4312 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004313}
4314
Yu Zhao430499c2022-09-18 02:00:08 -06004315/* to protect the working set of the last N jiffies */
4316static unsigned long lru_gen_min_ttl __read_mostly;
4317
Yu Zhao37397872022-09-18 02:00:03 -06004318static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4319{
4320 struct mem_cgroup *memcg;
Yu Zhao430499c2022-09-18 02:00:08 -06004321 bool success = false;
4322 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhao37397872022-09-18 02:00:03 -06004323
4324 VM_WARN_ON_ONCE(!current_is_kswapd());
4325
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004326 sc->last_reclaimed = sc->nr_reclaimed;
4327
4328 /*
4329 * To reduce the chance of going into the aging path, which can be
4330 * costly, optimistically skip it if the flag below was cleared in the
4331 * eviction path. This improves the overall performance when multiple
4332 * memcgs are available.
4333 */
4334 if (!sc->memcgs_need_aging) {
4335 sc->memcgs_need_aging = true;
4336 return;
4337 }
4338
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004339 set_mm_walk(pgdat);
4340
Yu Zhao37397872022-09-18 02:00:03 -06004341 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4342 do {
4343 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4344
Yu Zhao430499c2022-09-18 02:00:08 -06004345 if (age_lruvec(lruvec, sc, min_ttl))
4346 success = true;
Yu Zhao37397872022-09-18 02:00:03 -06004347
4348 cond_resched();
4349 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004350
4351 clear_mm_walk();
Yu Zhao430499c2022-09-18 02:00:08 -06004352
4353 /* check the order to exclude compaction-induced reclaim */
4354 if (success || !min_ttl || sc->order)
4355 return;
4356
4357 /*
4358 * The main goal is to OOM kill if every generation from all memcgs is
4359 * younger than min_ttl. However, another possibility is all memcgs are
4360 * either below min or empty.
4361 */
4362 if (mutex_trylock(&oom_lock)) {
4363 struct oom_control oc = {
4364 .gfp_mask = sc->gfp_mask,
4365 };
4366
4367 out_of_memory(&oc);
4368
4369 mutex_unlock(&oom_lock);
4370 }
Yu Zhao37397872022-09-18 02:00:03 -06004371}
4372
Yu Zhao0182f922022-09-18 02:00:04 -06004373/*
4374 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004375 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4376 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4377 * the PTE table to the Bloom filter. This forms a feedback loop between the
4378 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004379 */
4380void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4381{
4382 int i;
4383 pte_t *pte;
4384 unsigned long start;
4385 unsigned long end;
4386 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004387 struct lru_gen_mm_walk *walk;
4388 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004389 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4390 struct page *page = pvmw->page;
4391 struct mem_cgroup *memcg = page_memcg(page);
4392 struct pglist_data *pgdat = page_pgdat(page);
4393 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4394 DEFINE_MAX_SEQ(lruvec);
4395 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4396
4397 lockdep_assert_held(pvmw->ptl);
4398 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4399
4400 if (spin_is_contended(pvmw->ptl))
4401 return;
4402
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004403 /* avoid taking the LRU lock under the PTL when possible */
4404 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4405
Yu Zhao0182f922022-09-18 02:00:04 -06004406 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4407 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4408
4409 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4410 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4411 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4412 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4413 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4414 else {
4415 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4416 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4417 }
4418 }
4419
4420 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4421
4422 rcu_read_lock();
4423 arch_enter_lazy_mmu_mode();
4424
4425 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4426 unsigned long pfn;
4427
4428 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4429 if (pfn == -1)
4430 continue;
4431
4432 if (!pte_young(pte[i]))
4433 continue;
4434
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004435 page = get_pfn_page(pfn, memcg, pgdat, !walk || walk->can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004436 if (!page)
4437 continue;
4438
4439 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4440 VM_WARN_ON_ONCE(true);
4441
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004442 young++;
4443
Yu Zhao0182f922022-09-18 02:00:04 -06004444 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4445 !(PageAnon(page) && PageSwapBacked(page) &&
4446 !PageSwapCache(page)))
4447 set_page_dirty(page);
4448
4449 old_gen = page_lru_gen(page);
4450 if (old_gen < 0)
4451 SetPageReferenced(page);
4452 else if (old_gen != new_gen)
4453 __set_bit(i, bitmap);
4454 }
4455
4456 arch_leave_lazy_mmu_mode();
4457 rcu_read_unlock();
4458
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004459 /* feedback from rmap walkers to page table walkers */
4460 if (suitable_to_scan(i, young))
4461 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4462
4463 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004464 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4465 page = pte_page(pte[i]);
4466 activate_page(page);
4467 }
4468 return;
4469 }
4470
4471 /* page_update_gen() requires stable page_memcg() */
4472 if (!mem_cgroup_trylock_pages(memcg))
4473 return;
4474
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004475 if (!walk) {
4476 spin_lock_irq(&lruvec->lru_lock);
4477 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4478 }
Yu Zhao0182f922022-09-18 02:00:04 -06004479
4480 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4481 page = compound_head(pte_page(pte[i]));
4482 if (page_memcg_rcu(page) != memcg)
4483 continue;
4484
4485 old_gen = page_update_gen(page, new_gen);
4486 if (old_gen < 0 || old_gen == new_gen)
4487 continue;
4488
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004489 if (walk)
4490 update_batch_size(walk, page, old_gen, new_gen);
4491 else
4492 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004493 }
4494
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004495 if (!walk)
4496 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004497
4498 mem_cgroup_unlock_pages();
4499}
4500
Yu Zhao37397872022-09-18 02:00:03 -06004501/******************************************************************************
4502 * the eviction
4503 ******************************************************************************/
4504
4505static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4506{
4507 bool success;
4508 int gen = page_lru_gen(page);
4509 int type = page_is_file_lru(page);
4510 int zone = page_zonenum(page);
4511 int delta = thp_nr_pages(page);
4512 int refs = page_lru_refs(page);
4513 int tier = lru_tier_from_refs(refs);
Yu Zhao3c6c3592022-12-21 21:18:59 -07004514 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004515
4516 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4517
4518 /* unevictable */
4519 if (!page_evictable(page)) {
4520 success = lru_gen_del_page(lruvec, page, true);
4521 VM_WARN_ON_ONCE_PAGE(!success, page);
4522 SetPageUnevictable(page);
4523 add_page_to_lru_list(page, lruvec);
4524 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4525 return true;
4526 }
4527
4528 /* dirty lazyfree */
4529 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4530 success = lru_gen_del_page(lruvec, page, true);
4531 VM_WARN_ON_ONCE_PAGE(!success, page);
4532 SetPageSwapBacked(page);
4533 add_page_to_lru_list_tail(page, lruvec);
4534 return true;
4535 }
4536
Yu Zhao0182f922022-09-18 02:00:04 -06004537 /* promoted */
4538 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004539 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao0182f922022-09-18 02:00:04 -06004540 return true;
4541 }
4542
Yu Zhao37397872022-09-18 02:00:03 -06004543 /* protected */
4544 if (tier > tier_idx) {
4545 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4546
4547 gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004548 list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004549
4550 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4551 lrugen->protected[hist][type][tier - 1] + delta);
4552 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4553 return true;
4554 }
4555
4556 /* waiting for writeback */
4557 if (PageLocked(page) || PageWriteback(page) ||
4558 (type == LRU_GEN_FILE && PageDirty(page))) {
4559 gen = page_inc_gen(lruvec, page, true);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004560 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004561 return true;
4562 }
4563
4564 return false;
4565}
4566
4567static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4568{
4569 bool success;
4570
4571 /* unmapping inhibited */
4572 if (!sc->may_unmap && page_mapped(page))
4573 return false;
4574
4575 /* swapping inhibited */
4576 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4577 (PageDirty(page) ||
4578 (PageAnon(page) && !PageSwapCache(page))))
4579 return false;
4580
4581 /* raced with release_pages() */
4582 if (!get_page_unless_zero(page))
4583 return false;
4584
4585 /* raced with another isolation */
4586 if (!TestClearPageLRU(page)) {
4587 put_page(page);
4588 return false;
4589 }
4590
4591 /* see the comment on MAX_NR_TIERS */
4592 if (!PageReferenced(page))
4593 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4594
4595 /* for shrink_page_list() */
4596 ClearPageReclaim(page);
4597 ClearPageReferenced(page);
4598
4599 success = lru_gen_del_page(lruvec, page, true);
4600 VM_WARN_ON_ONCE_PAGE(!success, page);
4601
4602 return true;
4603}
4604
4605static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4606 int type, int tier, struct list_head *list)
4607{
4608 int gen, zone;
4609 enum vm_event_item item;
4610 int sorted = 0;
4611 int scanned = 0;
4612 int isolated = 0;
4613 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004614 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004615 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4616
4617 VM_WARN_ON_ONCE(!list_empty(list));
4618
4619 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4620 return 0;
4621
4622 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4623
4624 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4625 LIST_HEAD(moved);
4626 int skipped = 0;
Yu Zhaodf91dc92022-12-21 21:19:00 -07004627 struct list_head *head = &lrugen->pages[gen][type][zone];
Yu Zhao37397872022-09-18 02:00:03 -06004628
4629 while (!list_empty(head)) {
4630 struct page *page = lru_to_page(head);
4631 int delta = thp_nr_pages(page);
4632
4633 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4634 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4635 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4636 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4637
4638 scanned += delta;
4639
4640 if (sort_page(lruvec, page, tier))
4641 sorted += delta;
4642 else if (isolate_page(lruvec, page, sc)) {
4643 list_add(&page->lru, list);
4644 isolated += delta;
4645 } else {
4646 list_move(&page->lru, &moved);
4647 skipped += delta;
4648 }
4649
4650 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4651 break;
4652 }
4653
4654 if (skipped) {
4655 list_splice(&moved, head);
4656 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4657 }
4658
4659 if (!remaining || isolated >= MIN_LRU_BATCH)
4660 break;
4661 }
4662
4663 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4664 if (!cgroup_reclaim(sc)) {
4665 __count_vm_events(item, isolated);
4666 __count_vm_events(PGREFILL, sorted);
4667 }
4668 __count_memcg_events(memcg, item, isolated);
4669 __count_memcg_events(memcg, PGREFILL, sorted);
4670 __count_vm_events(PGSCAN_ANON + type, isolated);
4671
4672 /*
4673 * There might not be eligible pages due to reclaim_idx, may_unmap and
4674 * may_writepage. Check the remaining to prevent livelock if it's not
4675 * making progress.
4676 */
4677 return isolated || !remaining ? scanned : 0;
4678}
4679
4680static int get_tier_idx(struct lruvec *lruvec, int type)
4681{
4682 int tier;
4683 struct ctrl_pos sp, pv;
4684
4685 /*
4686 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4687 * This value is chosen because any other tier would have at least twice
4688 * as many refaults as the first tier.
4689 */
4690 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4691 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4692 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4693 if (!positive_ctrl_err(&sp, &pv))
4694 break;
4695 }
4696
4697 return tier - 1;
4698}
4699
4700static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4701{
4702 int type, tier;
4703 struct ctrl_pos sp, pv;
4704 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4705
4706 /*
4707 * Compare the first tier of anon with that of file to determine which
4708 * type to scan. Also need to compare other tiers of the selected type
4709 * with the first tier of the other type to determine the last tier (of
4710 * the selected type) to evict.
4711 */
4712 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4713 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4714 type = positive_ctrl_err(&sp, &pv);
4715
4716 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4717 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4718 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4719 if (!positive_ctrl_err(&sp, &pv))
4720 break;
4721 }
4722
4723 *tier_idx = tier - 1;
4724
4725 return type;
4726}
4727
4728static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4729 int *type_scanned, struct list_head *list)
4730{
4731 int i;
4732 int type;
4733 int scanned;
4734 int tier = -1;
4735 DEFINE_MIN_SEQ(lruvec);
4736
4737 /*
4738 * Try to make the obvious choice first. When anon and file are both
4739 * available from the same generation, interpret swappiness 1 as file
4740 * first and 200 as anon first.
4741 */
4742 if (!swappiness)
4743 type = LRU_GEN_FILE;
4744 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4745 type = LRU_GEN_ANON;
4746 else if (swappiness == 1)
4747 type = LRU_GEN_FILE;
4748 else if (swappiness == 200)
4749 type = LRU_GEN_ANON;
4750 else
4751 type = get_type_to_scan(lruvec, swappiness, &tier);
4752
4753 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4754 if (tier < 0)
4755 tier = get_tier_idx(lruvec, type);
4756
4757 scanned = scan_pages(lruvec, sc, type, tier, list);
4758 if (scanned)
4759 break;
4760
4761 type = !type;
4762 tier = -1;
4763 }
4764
4765 *type_scanned = type;
4766
4767 return scanned;
4768}
4769
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004770static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4771 bool *need_swapping)
Yu Zhao37397872022-09-18 02:00:03 -06004772{
4773 int type;
4774 int scanned;
4775 int reclaimed;
4776 LIST_HEAD(list);
4777 struct page *page;
4778 enum vm_event_item item;
4779 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004780 struct lru_gen_mm_walk *walk;
Yu Zhao37397872022-09-18 02:00:03 -06004781 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4782 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4783
4784 spin_lock_irq(&lruvec->lru_lock);
4785
4786 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4787
4788 scanned += try_to_inc_min_seq(lruvec, swappiness);
4789
4790 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4791 scanned = 0;
4792
4793 spin_unlock_irq(&lruvec->lru_lock);
4794
4795 if (list_empty(&list))
4796 return scanned;
4797
4798 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4799
4800 list_for_each_entry(page, &list, lru) {
4801 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4802 if (PageWorkingset(page))
4803 SetPageReferenced(page);
4804
4805 /* don't add rejected pages to the oldest generation */
4806 if (PageReclaim(page) &&
4807 (PageDirty(page) || PageWriteback(page)))
4808 ClearPageActive(page);
4809 else
4810 SetPageActive(page);
4811 }
4812
4813 spin_lock_irq(&lruvec->lru_lock);
4814
4815 move_pages_to_lru(lruvec, &list);
4816
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004817 walk = current->reclaim_state->mm_walk;
4818 if (walk && walk->batched)
4819 reset_batch_size(lruvec, walk);
4820
Yu Zhao37397872022-09-18 02:00:03 -06004821 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4822 if (!cgroup_reclaim(sc))
4823 __count_vm_events(item, reclaimed);
4824 __count_memcg_events(memcg, item, reclaimed);
4825 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4826
4827 spin_unlock_irq(&lruvec->lru_lock);
4828
4829 mem_cgroup_uncharge_list(&list);
4830 free_unref_page_list(&list);
4831
4832 sc->nr_reclaimed += reclaimed;
4833
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004834 if (need_swapping && type == LRU_GEN_ANON)
4835 *need_swapping = true;
4836
Yu Zhao37397872022-09-18 02:00:03 -06004837 return scanned;
4838}
4839
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004840/*
4841 * For future optimizations:
4842 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4843 * reclaim.
4844 */
Yu Zhao37397872022-09-18 02:00:03 -06004845static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004846 bool can_swap, bool *need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004847{
Yu Zhao37397872022-09-18 02:00:03 -06004848 unsigned long nr_to_scan;
4849 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4850 DEFINE_MAX_SEQ(lruvec);
4851 DEFINE_MIN_SEQ(lruvec);
4852
4853 if (mem_cgroup_below_min(memcg) ||
4854 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4855 return 0;
4856
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004857 *need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
4858 if (!*need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004859 return nr_to_scan;
4860
4861 /* skip the aging path at the default priority */
4862 if (sc->priority == DEF_PRIORITY)
4863 goto done;
4864
4865 /* leave the work to lru_gen_age_node() */
4866 if (current_is_kswapd())
4867 return 0;
4868
Yu Zhao4983c522022-09-18 02:00:09 -06004869 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004870 return nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004871done:
4872 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
4873}
4874
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004875static bool should_abort_scan(struct lruvec *lruvec, unsigned long seq,
4876 struct scan_control *sc, bool need_swapping)
4877{
4878 int i;
4879 DEFINE_MAX_SEQ(lruvec);
4880
4881 if (!current_is_kswapd()) {
4882 /* age each memcg at most once to ensure fairness */
4883 if (max_seq - seq > 1)
4884 return true;
4885
4886 /* over-swapping can increase allocation latency */
4887 if (sc->nr_reclaimed >= sc->nr_to_reclaim && need_swapping)
4888 return true;
4889
4890 /* give this thread a chance to exit and free its memory */
4891 if (fatal_signal_pending(current)) {
4892 sc->nr_reclaimed += MIN_LRU_BATCH;
4893 return true;
4894 }
4895
4896 if (cgroup_reclaim(sc))
4897 return false;
4898 } else if (sc->nr_reclaimed - sc->last_reclaimed < sc->nr_to_reclaim)
4899 return false;
4900
4901 /* keep scanning at low priorities to ensure fairness */
4902 if (sc->priority > DEF_PRIORITY - 2)
4903 return false;
4904
4905 /*
4906 * A minimum amount of work was done under global memory pressure. For
4907 * kswapd, it may be overshooting. For direct reclaim, the allocation
4908 * may succeed if all suitable zones are somewhat safe. In either case,
4909 * it's better to stop now, and restart later if necessary.
4910 */
4911 for (i = 0; i <= sc->reclaim_idx; i++) {
4912 unsigned long wmark;
4913 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
4914
4915 if (!managed_zone(zone))
4916 continue;
4917
4918 wmark = current_is_kswapd() ? high_wmark_pages(zone) : low_wmark_pages(zone);
4919 if (wmark > zone_page_state(zone, NR_FREE_PAGES))
4920 return false;
4921 }
4922
4923 sc->nr_reclaimed += MIN_LRU_BATCH;
4924
4925 return true;
4926}
4927
Yu Zhao37397872022-09-18 02:00:03 -06004928static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4929{
4930 struct blk_plug plug;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004931 bool need_aging = false;
4932 bool need_swapping = false;
Yu Zhao37397872022-09-18 02:00:03 -06004933 unsigned long scanned = 0;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004934 unsigned long reclaimed = sc->nr_reclaimed;
4935 DEFINE_MAX_SEQ(lruvec);
Yu Zhao37397872022-09-18 02:00:03 -06004936
4937 lru_add_drain();
4938
4939 blk_start_plug(&plug);
4940
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004941 set_mm_walk(lruvec_pgdat(lruvec));
4942
Yu Zhao37397872022-09-18 02:00:03 -06004943 while (true) {
4944 int delta;
4945 int swappiness;
4946 unsigned long nr_to_scan;
4947
4948 if (sc->may_swap)
4949 swappiness = get_swappiness(lruvec, sc);
4950 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4951 swappiness = 1;
4952 else
4953 swappiness = 0;
4954
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004955 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, &need_aging);
Yu Zhao37397872022-09-18 02:00:03 -06004956 if (!nr_to_scan)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004957 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004958
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004959 delta = evict_pages(lruvec, sc, swappiness, &need_swapping);
Yu Zhao37397872022-09-18 02:00:03 -06004960 if (!delta)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004961 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004962
4963 scanned += delta;
4964 if (scanned >= nr_to_scan)
4965 break;
4966
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004967 if (should_abort_scan(lruvec, max_seq, sc, need_swapping))
4968 break;
4969
Yu Zhao37397872022-09-18 02:00:03 -06004970 cond_resched();
4971 }
4972
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004973 /* see the comment in lru_gen_age_node() */
4974 if (sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH && !need_aging)
4975 sc->memcgs_need_aging = false;
4976done:
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004977 clear_mm_walk();
4978
Yu Zhao37397872022-09-18 02:00:03 -06004979 blk_finish_plug(&plug);
4980}
4981
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004982/******************************************************************************
Yu Zhaobaeb9a02022-09-18 02:00:07 -06004983 * state change
4984 ******************************************************************************/
4985
4986static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
4987{
Yu Zhao3c6c3592022-12-21 21:18:59 -07004988 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06004989
4990 if (lrugen->enabled) {
4991 enum lru_list lru;
4992
4993 for_each_evictable_lru(lru) {
4994 if (!list_empty(&lruvec->lists[lru]))
4995 return false;
4996 }
4997 } else {
4998 int gen, type, zone;
4999
5000 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005001 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005002 return false;
5003 }
5004 }
5005
5006 return true;
5007}
5008
5009static bool fill_evictable(struct lruvec *lruvec)
5010{
5011 enum lru_list lru;
5012 int remaining = MAX_LRU_BATCH;
5013
5014 for_each_evictable_lru(lru) {
5015 int type = is_file_lru(lru);
5016 bool active = is_active_lru(lru);
5017 struct list_head *head = &lruvec->lists[lru];
5018
5019 while (!list_empty(head)) {
5020 bool success;
5021 struct page *page = lru_to_page(head);
5022
5023 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5024 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
5025 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5026 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
5027
5028 del_page_from_lru_list(page, lruvec);
5029 success = lru_gen_add_page(lruvec, page, false);
5030 VM_WARN_ON_ONCE(!success);
5031
5032 if (!--remaining)
5033 return false;
5034 }
5035 }
5036
5037 return true;
5038}
5039
5040static bool drain_evictable(struct lruvec *lruvec)
5041{
5042 int gen, type, zone;
5043 int remaining = MAX_LRU_BATCH;
5044
5045 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005046 struct list_head *head = &lruvec->lrugen.pages[gen][type][zone];
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005047
5048 while (!list_empty(head)) {
5049 bool success;
5050 struct page *page = lru_to_page(head);
5051
5052 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5053 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5054 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5055 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5056
5057 success = lru_gen_del_page(lruvec, page, false);
5058 VM_WARN_ON_ONCE(!success);
5059 add_page_to_lru_list(page, lruvec);
5060
5061 if (!--remaining)
5062 return false;
5063 }
5064 }
5065
5066 return true;
5067}
5068
5069static void lru_gen_change_state(bool enabled)
5070{
5071 static DEFINE_MUTEX(state_mutex);
5072
5073 struct mem_cgroup *memcg;
5074
5075 cgroup_lock();
5076 cpus_read_lock();
5077 get_online_mems();
5078 mutex_lock(&state_mutex);
5079
5080 if (enabled == lru_gen_enabled())
5081 goto unlock;
5082
5083 if (enabled)
5084 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5085 else
5086 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5087
5088 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5089 do {
5090 int nid;
5091
5092 for_each_node(nid) {
5093 struct lruvec *lruvec = get_lruvec(memcg, nid);
5094
5095 if (!lruvec)
5096 continue;
5097
5098 spin_lock_irq(&lruvec->lru_lock);
5099
5100 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5101 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5102
5103 lruvec->lrugen.enabled = enabled;
5104
5105 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5106 spin_unlock_irq(&lruvec->lru_lock);
5107 cond_resched();
5108 spin_lock_irq(&lruvec->lru_lock);
5109 }
5110
5111 spin_unlock_irq(&lruvec->lru_lock);
5112 }
5113
5114 cond_resched();
5115 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5116unlock:
5117 mutex_unlock(&state_mutex);
5118 put_online_mems();
5119 cpus_read_unlock();
5120 cgroup_unlock();
5121}
5122
5123/******************************************************************************
5124 * sysfs interface
5125 ******************************************************************************/
5126
Yu Zhao430499c2022-09-18 02:00:08 -06005127static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5128{
5129 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5130}
5131
Yu Zhao642d9862022-09-18 02:00:10 -06005132/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao430499c2022-09-18 02:00:08 -06005133static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5134 const char *buf, size_t len)
5135{
5136 unsigned int msecs;
5137
5138 if (kstrtouint(buf, 0, &msecs))
5139 return -EINVAL;
5140
5141 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5142
5143 return len;
5144}
5145
5146static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5147 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5148);
5149
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005150static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5151{
5152 unsigned int caps = 0;
5153
5154 if (get_cap(LRU_GEN_CORE))
5155 caps |= BIT(LRU_GEN_CORE);
5156
5157 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5158 caps |= BIT(LRU_GEN_MM_WALK);
5159
5160 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
5161 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5162
5163 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5164}
5165
Yu Zhao642d9862022-09-18 02:00:10 -06005166/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005167static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5168 const char *buf, size_t len)
5169{
5170 int i;
5171 unsigned int caps;
5172
5173 if (tolower(*buf) == 'n')
5174 caps = 0;
5175 else if (tolower(*buf) == 'y')
5176 caps = -1;
5177 else if (kstrtouint(buf, 0, &caps))
5178 return -EINVAL;
5179
5180 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5181 bool enabled = caps & BIT(i);
5182
5183 if (i == LRU_GEN_CORE)
5184 lru_gen_change_state(enabled);
5185 else if (enabled)
5186 static_branch_enable(&lru_gen_caps[i]);
5187 else
5188 static_branch_disable(&lru_gen_caps[i]);
5189 }
5190
5191 return len;
5192}
5193
5194static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5195 enabled, 0644, show_enabled, store_enabled
5196);
5197
5198static struct attribute *lru_gen_attrs[] = {
Yu Zhao430499c2022-09-18 02:00:08 -06005199 &lru_gen_min_ttl_attr.attr,
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005200 &lru_gen_enabled_attr.attr,
5201 NULL
5202};
5203
5204static struct attribute_group lru_gen_attr_group = {
5205 .name = "lru_gen",
5206 .attrs = lru_gen_attrs,
5207};
5208
5209/******************************************************************************
Yu Zhao4983c522022-09-18 02:00:09 -06005210 * debugfs interface
5211 ******************************************************************************/
5212
5213static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5214{
5215 struct mem_cgroup *memcg;
5216 loff_t nr_to_skip = *pos;
5217
5218 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5219 if (!m->private)
5220 return ERR_PTR(-ENOMEM);
5221
5222 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5223 do {
5224 int nid;
5225
5226 for_each_node_state(nid, N_MEMORY) {
5227 if (!nr_to_skip--)
5228 return get_lruvec(memcg, nid);
5229 }
5230 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5231
5232 return NULL;
5233}
5234
5235static void lru_gen_seq_stop(struct seq_file *m, void *v)
5236{
5237 if (!IS_ERR_OR_NULL(v))
5238 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5239
5240 kvfree(m->private);
5241 m->private = NULL;
5242}
5243
5244static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5245{
5246 int nid = lruvec_pgdat(v)->node_id;
5247 struct mem_cgroup *memcg = lruvec_memcg(v);
5248
5249 ++*pos;
5250
5251 nid = next_memory_node(nid);
5252 if (nid == MAX_NUMNODES) {
5253 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5254 if (!memcg)
5255 return NULL;
5256
5257 nid = first_memory_node;
5258 }
5259
5260 return get_lruvec(memcg, nid);
5261}
5262
5263static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5264 unsigned long max_seq, unsigned long *min_seq,
5265 unsigned long seq)
5266{
5267 int i;
5268 int type, tier;
5269 int hist = lru_hist_from_seq(seq);
Yu Zhao3c6c3592022-12-21 21:18:59 -07005270 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005271
5272 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5273 seq_printf(m, " %10d", tier);
5274 for (type = 0; type < ANON_AND_FILE; type++) {
5275 const char *s = " ";
5276 unsigned long n[3] = {};
5277
5278 if (seq == max_seq) {
5279 s = "RT ";
5280 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5281 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5282 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5283 s = "rep";
5284 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5285 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5286 if (tier)
5287 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5288 }
5289
5290 for (i = 0; i < 3; i++)
5291 seq_printf(m, " %10lu%c", n[i], s[i]);
5292 }
5293 seq_putc(m, '\n');
5294 }
5295
5296 seq_puts(m, " ");
5297 for (i = 0; i < NR_MM_STATS; i++) {
5298 const char *s = " ";
5299 unsigned long n = 0;
5300
5301 if (seq == max_seq && NR_HIST_GENS == 1) {
5302 s = "LOYNFA";
5303 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5304 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5305 s = "loynfa";
5306 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5307 }
5308
5309 seq_printf(m, " %10lu%c", n, s[i]);
5310 }
5311 seq_putc(m, '\n');
5312}
5313
Yu Zhao642d9862022-09-18 02:00:10 -06005314/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005315static int lru_gen_seq_show(struct seq_file *m, void *v)
5316{
5317 unsigned long seq;
5318 bool full = !debugfs_real_fops(m->file)->write;
5319 struct lruvec *lruvec = v;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005320 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005321 int nid = lruvec_pgdat(lruvec)->node_id;
5322 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5323 DEFINE_MAX_SEQ(lruvec);
5324 DEFINE_MIN_SEQ(lruvec);
5325
5326 if (nid == first_memory_node) {
5327 const char *path = memcg ? m->private : "";
5328
5329#ifdef CONFIG_MEMCG
5330 if (memcg)
5331 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5332#endif
5333 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5334 }
5335
5336 seq_printf(m, " node %5d\n", nid);
5337
5338 if (!full)
5339 seq = min_seq[LRU_GEN_ANON];
5340 else if (max_seq >= MAX_NR_GENS)
5341 seq = max_seq - MAX_NR_GENS + 1;
5342 else
5343 seq = 0;
5344
5345 for (; seq <= max_seq; seq++) {
5346 int type, zone;
5347 int gen = lru_gen_from_seq(seq);
5348 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5349
5350 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5351
5352 for (type = 0; type < ANON_AND_FILE; type++) {
5353 unsigned long size = 0;
5354 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5355
5356 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5357 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5358
5359 seq_printf(m, " %10lu%c", size, mark);
5360 }
5361
5362 seq_putc(m, '\n');
5363
5364 if (full)
5365 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5366 }
5367
5368 return 0;
5369}
5370
5371static const struct seq_operations lru_gen_seq_ops = {
5372 .start = lru_gen_seq_start,
5373 .stop = lru_gen_seq_stop,
5374 .next = lru_gen_seq_next,
5375 .show = lru_gen_seq_show,
5376};
5377
5378static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5379 bool can_swap, bool force_scan)
5380{
5381 DEFINE_MAX_SEQ(lruvec);
5382 DEFINE_MIN_SEQ(lruvec);
5383
5384 if (seq < max_seq)
5385 return 0;
5386
5387 if (seq > max_seq)
5388 return -EINVAL;
5389
5390 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5391 return -ERANGE;
5392
5393 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5394
5395 return 0;
5396}
5397
5398static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5399 int swappiness, unsigned long nr_to_reclaim)
5400{
5401 DEFINE_MAX_SEQ(lruvec);
5402
5403 if (seq + MIN_NR_GENS > max_seq)
5404 return -EINVAL;
5405
5406 sc->nr_reclaimed = 0;
5407
5408 while (!signal_pending(current)) {
5409 DEFINE_MIN_SEQ(lruvec);
5410
5411 if (seq < min_seq[!swappiness])
5412 return 0;
5413
5414 if (sc->nr_reclaimed >= nr_to_reclaim)
5415 return 0;
5416
5417 if (!evict_pages(lruvec, sc, swappiness, NULL))
5418 return 0;
5419
5420 cond_resched();
5421 }
5422
5423 return -EINTR;
5424}
5425
5426static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5427 struct scan_control *sc, int swappiness, unsigned long opt)
5428{
5429 struct lruvec *lruvec;
5430 int err = -EINVAL;
5431 struct mem_cgroup *memcg = NULL;
5432
5433 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5434 return -EINVAL;
5435
5436 if (!mem_cgroup_disabled()) {
5437 rcu_read_lock();
5438 memcg = mem_cgroup_from_id(memcg_id);
5439#ifdef CONFIG_MEMCG
5440 if (memcg && !css_tryget(&memcg->css))
5441 memcg = NULL;
5442#endif
5443 rcu_read_unlock();
5444
5445 if (!memcg)
5446 return -EINVAL;
5447 }
5448
5449 if (memcg_id != mem_cgroup_id(memcg))
5450 goto done;
5451
5452 lruvec = get_lruvec(memcg, nid);
5453
5454 if (swappiness < 0)
5455 swappiness = get_swappiness(lruvec, sc);
5456 else if (swappiness > 200)
5457 goto done;
5458
5459 switch (cmd) {
5460 case '+':
5461 err = run_aging(lruvec, seq, sc, swappiness, opt);
5462 break;
5463 case '-':
5464 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5465 break;
5466 }
5467done:
5468 mem_cgroup_put(memcg);
5469
5470 return err;
5471}
5472
Yu Zhao642d9862022-09-18 02:00:10 -06005473/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005474static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5475 size_t len, loff_t *pos)
5476{
5477 void *buf;
5478 char *cur, *next;
5479 unsigned int flags;
5480 struct blk_plug plug;
5481 int err = -EINVAL;
5482 struct scan_control sc = {
5483 .may_writepage = true,
5484 .may_unmap = true,
5485 .may_swap = true,
5486 .reclaim_idx = MAX_NR_ZONES - 1,
5487 .gfp_mask = GFP_KERNEL,
5488 };
5489
5490 buf = kvmalloc(len + 1, GFP_KERNEL);
5491 if (!buf)
5492 return -ENOMEM;
5493
5494 if (copy_from_user(buf, src, len)) {
5495 kvfree(buf);
5496 return -EFAULT;
5497 }
5498
5499 set_task_reclaim_state(current, &sc.reclaim_state);
5500 flags = memalloc_noreclaim_save();
5501 blk_start_plug(&plug);
5502 if (!set_mm_walk(NULL)) {
5503 err = -ENOMEM;
5504 goto done;
5505 }
5506
5507 next = buf;
5508 next[len] = '\0';
5509
5510 while ((cur = strsep(&next, ",;\n"))) {
5511 int n;
5512 int end;
5513 char cmd;
5514 unsigned int memcg_id;
5515 unsigned int nid;
5516 unsigned long seq;
5517 unsigned int swappiness = -1;
5518 unsigned long opt = -1;
5519
5520 cur = skip_spaces(cur);
5521 if (!*cur)
5522 continue;
5523
5524 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5525 &seq, &end, &swappiness, &end, &opt, &end);
5526 if (n < 4 || cur[end]) {
5527 err = -EINVAL;
5528 break;
5529 }
5530
5531 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5532 if (err)
5533 break;
5534 }
5535done:
5536 clear_mm_walk();
5537 blk_finish_plug(&plug);
5538 memalloc_noreclaim_restore(flags);
5539 set_task_reclaim_state(current, NULL);
5540
5541 kvfree(buf);
5542
5543 return err ? : len;
5544}
5545
5546static int lru_gen_seq_open(struct inode *inode, struct file *file)
5547{
5548 return seq_open(file, &lru_gen_seq_ops);
5549}
5550
5551static const struct file_operations lru_gen_rw_fops = {
5552 .open = lru_gen_seq_open,
5553 .read = seq_read,
5554 .write = lru_gen_seq_write,
5555 .llseek = seq_lseek,
5556 .release = seq_release,
5557};
5558
5559static const struct file_operations lru_gen_ro_fops = {
5560 .open = lru_gen_seq_open,
5561 .read = seq_read,
5562 .llseek = seq_lseek,
5563 .release = seq_release,
5564};
5565
5566/******************************************************************************
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005567 * initialization
5568 ******************************************************************************/
5569
5570void lru_gen_init_lruvec(struct lruvec *lruvec)
5571{
Yu Zhao430499c2022-09-18 02:00:08 -06005572 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005573 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005574 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005575
5576 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005577 lrugen->enabled = lru_gen_enabled();
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005578
Yu Zhao430499c2022-09-18 02:00:08 -06005579 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5580 lrugen->timestamps[i] = jiffies;
5581
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005582 for_each_gen_type_zone(gen, type, zone)
Yu Zhaodf91dc92022-12-21 21:19:00 -07005583 INIT_LIST_HEAD(&lrugen->pages[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005584
5585 lruvec->mm_state.seq = MIN_NR_GENS;
5586 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005587}
5588
5589#ifdef CONFIG_MEMCG
5590void lru_gen_init_memcg(struct mem_cgroup *memcg)
5591{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005592 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5593 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005594}
5595
5596void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5597{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005598 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005599 int nid;
5600
5601 for_each_node(nid) {
5602 struct lruvec *lruvec = get_lruvec(memcg, nid);
5603
5604 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5605 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005606
5607 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5608 bitmap_free(lruvec->mm_state.filters[i]);
5609 lruvec->mm_state.filters[i] = NULL;
5610 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005611 }
5612}
5613#endif
5614
5615static int __init init_lru_gen(void)
5616{
5617 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5618 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5619
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005620 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5621 pr_err("lru_gen: failed to create sysfs group\n");
5622
Yu Zhao4983c522022-09-18 02:00:09 -06005623 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5624 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5625
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005626 return 0;
5627};
5628late_initcall(init_lru_gen);
5629
Yu Zhao37397872022-09-18 02:00:03 -06005630#else /* !CONFIG_LRU_GEN */
5631
5632static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5633{
5634}
5635
5636static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5637{
5638}
5639
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005640#endif /* CONFIG_LRU_GEN */
5641
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005642static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005643{
5644 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005645 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005646 unsigned long nr_to_scan;
5647 enum lru_list lru;
5648 unsigned long nr_reclaimed = 0;
5649 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005650 bool proportional_reclaim;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005651 struct blk_plug plug;
Minchan Kima8962f62022-11-02 09:04:41 -07005652 bool do_plug = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005653
Yu Zhao37397872022-09-18 02:00:03 -06005654 if (lru_gen_enabled()) {
5655 lru_gen_shrink_lruvec(lruvec, sc);
5656 return;
5657 }
5658
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005659 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005660
Mel Gormane82e0562013-07-03 15:01:44 -07005661 /* Record the original scan target for proportional adjustments later */
5662 memcpy(targets, nr, sizeof(nr));
5663
Mel Gorman1a501902014-06-04 16:10:49 -07005664 /*
5665 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5666 * event that can occur when there is little memory pressure e.g.
5667 * multiple streaming readers/writers. Hence, we do not abort scanning
5668 * when the requested number of pages are reclaimed when scanning at
5669 * DEF_PRIORITY on the assumption that the fact we are direct
5670 * reclaiming implies that kswapd is not keeping up and it is best to
5671 * do a batch of work at once. For memcg reclaim one check is made to
5672 * abort proportional reclaim if either the file or anon lru has already
5673 * dropped to zero at the first pass.
5674 */
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005675 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5676 sc->priority == DEF_PRIORITY);
Mel Gorman1a501902014-06-04 16:10:49 -07005677
Minchan Kima8962f62022-11-02 09:04:41 -07005678 trace_android_vh_shrink_lruvec_blk_plug(&do_plug);
5679 if (do_plug)
5680 blk_start_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005681 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5682 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005683 unsigned long nr_anon, nr_file, percentage;
5684 unsigned long nr_scanned;
5685
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005686 for_each_evictable_lru(lru) {
5687 if (nr[lru]) {
5688 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5689 nr[lru] -= nr_to_scan;
5690
5691 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005692 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005693 }
5694 }
Mel Gormane82e0562013-07-03 15:01:44 -07005695
Michal Hockobd041732016-12-02 17:26:48 -08005696 cond_resched();
5697
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005698 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
Mel Gormane82e0562013-07-03 15:01:44 -07005699 continue;
5700
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005701 /*
Mel Gormane82e0562013-07-03 15:01:44 -07005702 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07005703 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07005704 * proportionally what was requested by get_scan_count(). We
5705 * stop reclaiming one LRU and reduce the amount scanning
5706 * proportional to the original scan target.
5707 */
5708 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5709 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5710
Mel Gorman1a501902014-06-04 16:10:49 -07005711 /*
5712 * It's just vindictive to attack the larger once the smaller
5713 * has gone to zero. And given the way we stop scanning the
5714 * smaller below, this makes sure that we only make one nudge
5715 * towards proportionality once we've got nr_to_reclaim.
5716 */
5717 if (!nr_file || !nr_anon)
5718 break;
5719
Mel Gormane82e0562013-07-03 15:01:44 -07005720 if (nr_file > nr_anon) {
5721 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5722 targets[LRU_ACTIVE_ANON] + 1;
5723 lru = LRU_BASE;
5724 percentage = nr_anon * 100 / scan_target;
5725 } else {
5726 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5727 targets[LRU_ACTIVE_FILE] + 1;
5728 lru = LRU_FILE;
5729 percentage = nr_file * 100 / scan_target;
5730 }
5731
5732 /* Stop scanning the smaller of the LRU */
5733 nr[lru] = 0;
5734 nr[lru + LRU_ACTIVE] = 0;
5735
5736 /*
5737 * Recalculate the other LRU scan count based on its original
5738 * scan target and the percentage scanning already complete
5739 */
5740 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5741 nr_scanned = targets[lru] - nr[lru];
5742 nr[lru] = targets[lru] * (100 - percentage) / 100;
5743 nr[lru] -= min(nr[lru], nr_scanned);
5744
5745 lru += LRU_ACTIVE;
5746 nr_scanned = targets[lru] - nr[lru];
5747 nr[lru] = targets[lru] * (100 - percentage) / 100;
5748 nr[lru] -= min(nr[lru], nr_scanned);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005749 }
Minchan Kima8962f62022-11-02 09:04:41 -07005750 if (do_plug)
5751 blk_finish_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005752 sc->nr_reclaimed += nr_reclaimed;
5753
5754 /*
5755 * Even if we did not try to evict anon pages at all, we want to
5756 * rebalance the anon lru active/inactive ratio.
5757 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005758 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5759 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005760 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5761 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005762}
5763
Mel Gorman23b9da52012-05-29 15:06:20 -07005764/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005765static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005766{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005767 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005768 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005769 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005770 return true;
5771
5772 return false;
5773}
5774
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005775/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005776 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5777 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5778 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005779 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005780 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005781 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005782static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005783 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005784 struct scan_control *sc)
5785{
5786 unsigned long pages_for_compaction;
5787 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005788 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005789
5790 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005791 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005792 return false;
5793
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005794 /*
5795 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5796 * number of pages that were scanned. This will return to the caller
5797 * with the risk reclaim/compaction and the resulting allocation attempt
5798 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5799 * allocations through requiring that the full LRU list has been scanned
5800 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5801 * scan, but that approximation was wrong, and there were corner cases
5802 * where always a non-zero amount of pages were scanned.
5803 */
5804 if (!nr_reclaimed)
5805 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005806
Mel Gorman3e7d3442011-01-13 15:45:56 -08005807 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005808 for (z = 0; z <= sc->reclaim_idx; z++) {
5809 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005810 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005811 continue;
5812
5813 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005814 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005815 case COMPACT_CONTINUE:
5816 return false;
5817 default:
5818 /* check next zone */
5819 ;
5820 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005821 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005822
5823 /*
5824 * If we have not reclaimed enough pages for compaction and the
5825 * inactive lists are large enough, continue reclaiming
5826 */
5827 pages_for_compaction = compact_gap(sc->order);
5828 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005829 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005830 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5831
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005832 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005833}
5834
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005835static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005836{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005837 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005838 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005839
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005840 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005841 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005842 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005843 unsigned long reclaimed;
5844 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005845 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08005846
Xunlei Pange3336ca2020-09-04 16:35:27 -07005847 /*
5848 * This loop can become CPU-bound when target memcgs
5849 * aren't eligible for reclaim - either because they
5850 * don't have any reclaimable pages, or because their
5851 * memory is explicitly protected. Avoid soft lockups.
5852 */
5853 cond_resched();
5854
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005855 trace_android_vh_shrink_node_memcgs(memcg, &skip);
5856 if (skip)
5857 continue;
5858
Chris Down45c7f7e2020-08-06 23:22:05 -07005859 mem_cgroup_calculate_protection(target_memcg, memcg);
5860
5861 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005862 /*
5863 * Hard protection.
5864 * If there is no reclaimable memory, OOM.
5865 */
5866 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005867 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005868 /*
5869 * Soft protection.
5870 * Respect the protection only as long as
5871 * there is an unprotected supply
5872 * of reclaimable memory from other cgroups.
5873 */
5874 if (!sc->memcg_low_reclaim) {
5875 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005876 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005877 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005878 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005879 }
5880
Johannes Weinerd2af3392019-11-30 17:55:43 -08005881 reclaimed = sc->nr_reclaimed;
5882 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005883
5884 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005885
Johannes Weinerd2af3392019-11-30 17:55:43 -08005886 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5887 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005888
Johannes Weinerd2af3392019-11-30 17:55:43 -08005889 /* Record the group's reclaim efficiency */
5890 vmpressure(sc->gfp_mask, memcg, false,
5891 sc->nr_scanned - scanned,
5892 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005893
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005894 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5895}
5896
Liu Song6c9e09072020-01-30 22:14:08 -08005897static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005898{
5899 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005900 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005901 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005902 bool reclaimable = false;
5903
Johannes Weiner1b051172019-11-30 17:55:52 -08005904 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5905
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005906again:
5907 memset(&sc->nr, 0, sizeof(sc->nr));
5908
5909 nr_reclaimed = sc->nr_reclaimed;
5910 nr_scanned = sc->nr_scanned;
5911
Yu Zhao6d313442022-09-18 02:00:00 -06005912 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005913
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005914 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005915
Johannes Weinerd2af3392019-11-30 17:55:43 -08005916 if (reclaim_state) {
5917 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5918 reclaim_state->reclaimed_slab = 0;
5919 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005920
Johannes Weinerd2af3392019-11-30 17:55:43 -08005921 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005922 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005923 sc->nr_scanned - nr_scanned,
5924 sc->nr_reclaimed - nr_reclaimed);
5925
5926 if (sc->nr_reclaimed - nr_reclaimed)
5927 reclaimable = true;
5928
5929 if (current_is_kswapd()) {
5930 /*
5931 * If reclaim is isolating dirty pages under writeback,
5932 * it implies that the long-lived page allocation rate
5933 * is exceeding the page laundering rate. Either the
5934 * global limits are not being effective at throttling
5935 * processes due to the page distribution throughout
5936 * zones or there is heavy usage of a slow backing
5937 * device. The only option is to throttle from reclaim
5938 * context which is not ideal as there is no guarantee
5939 * the dirtying process is throttled in the same way
5940 * balance_dirty_pages() manages.
5941 *
5942 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5943 * count the number of pages under pages flagged for
5944 * immediate reclaim and stall if any are encountered
5945 * in the nr_immediate check below.
5946 */
5947 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5948 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005949
Johannes Weinerd2af3392019-11-30 17:55:43 -08005950 /* Allow kswapd to start writing pages during reclaim.*/
5951 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5952 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005953
5954 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005955 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005956 * reclaim and under writeback (nr_immediate), it
5957 * implies that pages are cycling through the LRU
5958 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005959 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005960 if (sc->nr.immediate)
5961 congestion_wait(BLK_RW_ASYNC, HZ/10);
5962 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005963
Johannes Weinerd2af3392019-11-30 17:55:43 -08005964 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005965 * Tag a node/memcg as congested if all the dirty pages
5966 * scanned were backed by a congested BDI and
5967 * wait_iff_congested will stall.
5968 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005969 * Legacy memcg will stall in page writeback so avoid forcibly
5970 * stalling in wait_iff_congested().
5971 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005972 if ((current_is_kswapd() ||
5973 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005974 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005975 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005976
5977 /*
5978 * Stall direct reclaim for IO completions if underlying BDIs
5979 * and node is congested. Allow kswapd to continue until it
5980 * starts encountering unqueued dirty pages or cycling through
5981 * the LRU too quickly.
5982 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005983 if (!current_is_kswapd() && current_may_throttle() &&
5984 !sc->hibernation_mode &&
5985 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005986 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5987
5988 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5989 sc))
5990 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005991
Johannes Weinerc73322d2017-05-03 14:51:51 -07005992 /*
5993 * Kswapd gives up on balancing particular nodes after too
5994 * many failures to reclaim anything from them and goes to
5995 * sleep. On reclaim progress, reset the failure counter. A
5996 * successful direct reclaim run will revive a dormant kswapd.
5997 */
5998 if (reclaimable)
5999 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006000}
6001
Vlastimil Babka53853e22014-10-09 15:27:02 -07006002/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006003 * Returns true if compaction should go ahead for a costly-order request, or
6004 * the allocation would already succeed without compaction. Return false if we
6005 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07006006 */
Mel Gorman4f588332016-07-28 15:46:38 -07006007static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006008{
Mel Gorman31483b62016-07-28 15:45:46 -07006009 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006010 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006011
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006012 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6013 if (suitable == COMPACT_SUCCESS)
6014 /* Allocation should succeed already. Don't reclaim. */
6015 return true;
6016 if (suitable == COMPACT_SKIPPED)
6017 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006018 return false;
6019
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006020 /*
6021 * Compaction is already possible, but it takes time to run and there
6022 * are potentially other callers using the pages just freed. So proceed
6023 * with reclaim to make a buffer of free pages available to give
6024 * compaction a reasonable chance of completing and allocating the page.
6025 * Note that we won't actually reclaim the whole buffer in one attempt
6026 * as the target watermark in should_continue_reclaim() is lower. But if
6027 * we are already above the high+gap watermark, don't reclaim at all.
6028 */
6029 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6030
6031 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006032}
6033
Linus Torvalds1da177e2005-04-16 15:20:36 -07006034/*
6035 * This is the direct reclaim path, for page-allocating processes. We only
6036 * try to reclaim pages from zones which will satisfy the caller's allocation
6037 * request.
6038 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07006039 * If a zone is deemed to be full of pinned pages then just give it a light
6040 * scan then give up on it.
6041 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07006042static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006043{
Mel Gormandd1a2392008-04-28 02:12:17 -07006044 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07006045 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07006046 unsigned long nr_soft_reclaimed;
6047 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07006048 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07006049 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006050
Mel Gormancc715d92012-03-21 16:34:00 -07006051 /*
6052 * If the number of buffer_heads in the machine exceeds the maximum
6053 * allowed level, force direct reclaim to scan the highmem zone as
6054 * highmem pages could be pinning lowmem pages storing buffer_heads
6055 */
Weijie Yang619d0d762014-04-07 15:36:59 -07006056 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07006057 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07006058 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07006059 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07006060 }
Mel Gormancc715d92012-03-21 16:34:00 -07006061
Mel Gormand4debc62010-08-09 17:19:29 -07006062 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07006063 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07006064 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006065 * Take care memory controller reclaiming has small influence
6066 * to global LRU.
6067 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08006068 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04006069 if (!cpuset_zone_allowed(zone,
6070 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006071 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006072
Johannes Weiner0b064962014-08-06 16:06:12 -07006073 /*
6074 * If we already have plenty of memory free for
6075 * compaction in this zone, don't free any more.
6076 * Even though compaction is invoked for any
6077 * non-zero order, only frequent costly order
6078 * reclamation is disruptive enough to become a
6079 * noticeable problem, like transparent huge
6080 * page allocations.
6081 */
6082 if (IS_ENABLED(CONFIG_COMPACTION) &&
6083 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07006084 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07006085 sc->compaction_ready = true;
6086 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07006087 }
Johannes Weiner0b064962014-08-06 16:06:12 -07006088
Andrew Morton0608f432013-09-24 15:27:41 -07006089 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07006090 * Shrink each node in the zonelist once. If the
6091 * zonelist is ordered by zone (not the default) then a
6092 * node may be shrunk multiple times but in that case
6093 * the user prefers lower zones being preserved.
6094 */
6095 if (zone->zone_pgdat == last_pgdat)
6096 continue;
6097
6098 /*
Andrew Morton0608f432013-09-24 15:27:41 -07006099 * This steals pages from memory cgroups over softlimit
6100 * and returns the number of reclaimed pages and
6101 * scanned pages. This works for global memory pressure
6102 * and balancing, not for a memcg's limit.
6103 */
6104 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006105 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006106 sc->order, sc->gfp_mask,
6107 &nr_soft_scanned);
6108 sc->nr_reclaimed += nr_soft_reclaimed;
6109 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006110 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006111 }
Nick Piggin408d8542006-09-25 23:31:27 -07006112
Mel Gorman79dafcd2016-07-28 15:45:53 -07006113 /* See comment about same check for global reclaim above */
6114 if (zone->zone_pgdat == last_pgdat)
6115 continue;
6116 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006117 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006118 }
Mel Gormane0c23272011-10-31 17:09:33 -07006119
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006120 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006121 * Restore to original mask to avoid the impact on the caller if we
6122 * promoted it to __GFP_HIGHMEM.
6123 */
6124 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006125}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006126
Johannes Weinerb9107182019-11-30 17:55:59 -08006127static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006128{
Johannes Weinerb9107182019-11-30 17:55:59 -08006129 struct lruvec *target_lruvec;
6130 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006131
Yu Zhao37397872022-09-18 02:00:03 -06006132 if (lru_gen_enabled())
6133 return;
6134
Johannes Weinerb9107182019-11-30 17:55:59 -08006135 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006136 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6137 target_lruvec->refaults[0] = refaults;
6138 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6139 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006140}
6141
Linus Torvalds1da177e2005-04-16 15:20:36 -07006142/*
6143 * This is the main entry point to direct page reclaim.
6144 *
6145 * If a full scan of the inactive list fails to free enough memory then we
6146 * are "out of memory" and something needs to be killed.
6147 *
6148 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6149 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006150 * caller can't do much about. We kick the writeback threads and take explicit
6151 * naps in the hope that some of these pages can be written. But if the
6152 * allocating task holds filesystem locks which prevent writeout this might not
6153 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006154 *
6155 * returns: 0, if no pages reclaimed
6156 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006157 */
Mel Gormandac1d272008-04-28 02:12:12 -07006158static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006159 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006160{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006161 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006162 pg_data_t *last_pgdat;
6163 struct zoneref *z;
6164 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006165retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006166 delayacct_freepages_start();
6167
Johannes Weinerb5ead352019-11-30 17:55:40 -08006168 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006169 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006170
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006171 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006172 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6173 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006174 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006175 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006176
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006177 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006178 break;
6179
6180 if (sc->compaction_ready)
6181 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006182
6183 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006184 * If we're getting trouble reclaiming, start doing
6185 * writepage even in laptop mode.
6186 */
6187 if (sc->priority < DEF_PRIORITY - 2)
6188 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006189 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006190
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006191 last_pgdat = NULL;
6192 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6193 sc->nodemask) {
6194 if (zone->zone_pgdat == last_pgdat)
6195 continue;
6196 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006197
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006198 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006199
6200 if (cgroup_reclaim(sc)) {
6201 struct lruvec *lruvec;
6202
6203 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6204 zone->zone_pgdat);
6205 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6206 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006207 }
6208
Keika Kobayashi873b4772008-07-25 01:48:52 -07006209 delayacct_freepages_end();
6210
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006211 if (sc->nr_reclaimed)
6212 return sc->nr_reclaimed;
6213
Mel Gorman0cee34f2012-01-12 17:19:49 -08006214 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006215 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006216 return 1;
6217
Johannes Weinerb91ac372019-11-30 17:56:02 -08006218 /*
6219 * We make inactive:active ratio decisions based on the node's
6220 * composition of memory, but a restrictive reclaim_idx or a
6221 * memory.low cgroup setting can exempt large amounts of
6222 * memory from reclaim. Neither of which are very common, so
6223 * instead of doing costly eligibility calculations of the
6224 * entire cgroup subtree up front, we assume the estimates are
6225 * good, and retry with forcible deactivation if that fails.
6226 */
6227 if (sc->skipped_deactivate) {
6228 sc->priority = initial_priority;
6229 sc->force_deactivate = 1;
6230 sc->skipped_deactivate = 0;
6231 goto retry;
6232 }
6233
Johannes Weiner241994ed2015-02-11 15:26:06 -08006234 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006235 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006236 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006237 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006238 sc->memcg_low_reclaim = 1;
6239 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006240 goto retry;
6241 }
6242
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006243 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006244}
6245
Johannes Weinerc73322d2017-05-03 14:51:51 -07006246static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006247{
6248 struct zone *zone;
6249 unsigned long pfmemalloc_reserve = 0;
6250 unsigned long free_pages = 0;
6251 int i;
6252 bool wmark_ok;
6253
Johannes Weinerc73322d2017-05-03 14:51:51 -07006254 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6255 return true;
6256
Mel Gorman55150612012-07-31 16:44:35 -07006257 for (i = 0; i <= ZONE_NORMAL; i++) {
6258 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006259 if (!managed_zone(zone))
6260 continue;
6261
6262 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006263 continue;
6264
Mel Gorman55150612012-07-31 16:44:35 -07006265 pfmemalloc_reserve += min_wmark_pages(zone);
6266 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6267 }
6268
Mel Gorman675becc2014-06-04 16:07:35 -07006269 /* If there are no reserves (unexpected config) then do not throttle */
6270 if (!pfmemalloc_reserve)
6271 return true;
6272
Mel Gorman55150612012-07-31 16:44:35 -07006273 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6274
6275 /* kswapd must be awake if processes are being throttled */
6276 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006277 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6278 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006279
Mel Gorman55150612012-07-31 16:44:35 -07006280 wake_up_interruptible(&pgdat->kswapd_wait);
6281 }
6282
6283 return wmark_ok;
6284}
6285
6286/*
6287 * Throttle direct reclaimers if backing storage is backed by the network
6288 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6289 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006290 * when the low watermark is reached.
6291 *
6292 * Returns true if a fatal signal was delivered during throttling. If this
6293 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006294 */
Mel Gorman50694c22012-11-26 16:29:48 -08006295static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006296 nodemask_t *nodemask)
6297{
Mel Gorman675becc2014-06-04 16:07:35 -07006298 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006299 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006300 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006301
6302 /*
6303 * Kernel threads should not be throttled as they may be indirectly
6304 * responsible for cleaning pages necessary for reclaim to make forward
6305 * progress. kjournald for example may enter direct reclaim while
6306 * committing a transaction where throttling it could forcing other
6307 * processes to block on log_wait_commit().
6308 */
6309 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006310 goto out;
6311
6312 /*
6313 * If a fatal signal is pending, this process should not throttle.
6314 * It should return quickly so it can exit and free its memory
6315 */
6316 if (fatal_signal_pending(current))
6317 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006318
Mel Gorman675becc2014-06-04 16:07:35 -07006319 /*
6320 * Check if the pfmemalloc reserves are ok by finding the first node
6321 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6322 * GFP_KERNEL will be required for allocating network buffers when
6323 * swapping over the network so ZONE_HIGHMEM is unusable.
6324 *
6325 * Throttling is based on the first usable node and throttled processes
6326 * wait on a queue until kswapd makes progress and wakes them. There
6327 * is an affinity then between processes waking up and where reclaim
6328 * progress has been made assuming the process wakes on the same node.
6329 * More importantly, processes running on remote nodes will not compete
6330 * for remote pfmemalloc reserves and processes on different nodes
6331 * should make reasonable progress.
6332 */
6333 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006334 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006335 if (zone_idx(zone) > ZONE_NORMAL)
6336 continue;
6337
6338 /* Throttle based on the first usable node */
6339 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006340 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006341 goto out;
6342 break;
6343 }
6344
6345 /* If no zone was usable by the allocation flags then do not throttle */
6346 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006347 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006348
Mel Gorman68243e72012-07-31 16:44:39 -07006349 /* Account for the throttling */
6350 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6351
Mel Gorman55150612012-07-31 16:44:35 -07006352 /*
6353 * If the caller cannot enter the filesystem, it's possible that it
6354 * is due to the caller holding an FS lock or performing a journal
6355 * transaction in the case of a filesystem like ext[3|4]. In this case,
6356 * it is not safe to block on pfmemalloc_wait as kswapd could be
6357 * blocked waiting on the same lock. Instead, throttle for up to a
6358 * second before continuing.
6359 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006360 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006361 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006362 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006363 else
6364 /* Throttle until kswapd wakes the process */
6365 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6366 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006367
Mel Gorman50694c22012-11-26 16:29:48 -08006368 if (fatal_signal_pending(current))
6369 return true;
6370
6371out:
6372 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006373}
6374
Mel Gormandac1d272008-04-28 02:12:12 -07006375unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006376 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006377{
Mel Gorman33906bc2010-08-09 17:19:16 -07006378 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006379 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006380 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006381 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006382 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006383 .order = order,
6384 .nodemask = nodemask,
6385 .priority = DEF_PRIORITY,
6386 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006387 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006388 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006389 };
6390
Mel Gorman55150612012-07-31 16:44:35 -07006391 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006392 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6393 * Confirm they are large enough for max values.
6394 */
6395 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6396 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6397 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6398
6399 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006400 * Do not enter reclaim if fatal signal was delivered while throttled.
6401 * 1 is returned so that the page allocator does not OOM kill at this
6402 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006403 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006404 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006405 return 1;
6406
Andrew Morton1732d2b012019-07-16 16:26:15 -07006407 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006408 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006409
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006410 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006411
6412 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006413 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006414
6415 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006416}
6417
Andrew Mortonc255a452012-07-31 16:43:02 -07006418#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006419
Michal Hockod2e5fb92019-08-30 16:04:50 -07006420/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006421unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006422 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006423 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006424 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006425{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006426 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006427 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006428 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006429 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006430 .may_writepage = !laptop_mode,
6431 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006432 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006433 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006434 };
Ying Han0ae5e892011-05-26 16:25:25 -07006435
Michal Hockod2e5fb92019-08-30 16:04:50 -07006436 WARN_ON_ONCE(!current->reclaim_state);
6437
Balbir Singh4e416952009-09-23 15:56:39 -07006438 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6439 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006440
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006441 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006442 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006443
Balbir Singh4e416952009-09-23 15:56:39 -07006444 /*
6445 * NOTE: Although we can get the priority field, using it
6446 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006447 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006448 * will pick up pages from other mem cgroup's as well. We hack
6449 * the priority and make it zero.
6450 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006451 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006452
6453 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6454
Ying Han0ae5e892011-05-26 16:25:25 -07006455 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006456
Balbir Singh4e416952009-09-23 15:56:39 -07006457 return sc.nr_reclaimed;
6458}
6459
Johannes Weiner72835c82012-01-12 17:18:32 -08006460unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006461 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006462 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006463 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08006464{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006465 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006466 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006467 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006468 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006469 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006470 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006471 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006472 .target_mem_cgroup = memcg,
6473 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006474 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006475 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006476 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07006477 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006478 /*
6479 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6480 * equal pressure on all the nodes. This is based on the assumption that
6481 * the reclaim does not bail out early.
6482 */
6483 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006484
Andrew Morton1732d2b012019-07-16 16:26:15 -07006485 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006486 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006487 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006488
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006489 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006490
Vlastimil Babka499118e2017-05-08 15:59:50 -07006491 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006492 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006493 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006494
6495 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006496}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006497EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006498#endif
6499
Yu Zhao37397872022-09-18 02:00:03 -06006500static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006501{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006502 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006503 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006504
Yu Zhao37397872022-09-18 02:00:03 -06006505 if (lru_gen_enabled()) {
6506 lru_gen_age_node(pgdat, sc);
6507 return;
6508 }
6509
Dave Hansen2f368a92021-09-02 14:59:23 -07006510 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006511 return;
6512
Johannes Weinerb91ac372019-11-30 17:56:02 -08006513 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6514 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6515 return;
6516
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006517 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6518 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006519 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6520 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6521 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006522 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6523 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006524}
6525
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006526static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006527{
6528 int i;
6529 struct zone *zone;
6530
6531 /*
6532 * Check for watermark boosts top-down as the higher zones
6533 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006534 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006535 * start prematurely when there is no boosting and a lower
6536 * zone is balanced.
6537 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006538 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006539 zone = pgdat->node_zones + i;
6540 if (!managed_zone(zone))
6541 continue;
6542
6543 if (zone->watermark_boost)
6544 return true;
6545 }
6546
6547 return false;
6548}
6549
Mel Gormane716f2e2017-05-03 14:53:45 -07006550/*
6551 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006552 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006553 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006554static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006555{
Mel Gormane716f2e2017-05-03 14:53:45 -07006556 int i;
6557 unsigned long mark = -1;
6558 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006559
Mel Gorman1c308442018-12-28 00:35:52 -08006560 /*
6561 * Check watermarks bottom-up as lower zones are more likely to
6562 * meet watermarks.
6563 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006564 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006565 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006566
Mel Gormane716f2e2017-05-03 14:53:45 -07006567 if (!managed_zone(zone))
6568 continue;
6569
6570 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006571 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006572 return true;
6573 }
6574
6575 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006576 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006577 * need balancing by definition. This can happen if a zone-restricted
6578 * allocation tries to wake a remote kswapd.
6579 */
6580 if (mark == -1)
6581 return true;
6582
6583 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006584}
6585
Mel Gorman631b6e02017-05-03 14:53:41 -07006586/* Clear pgdat state for congested, dirty or under writeback. */
6587static void clear_pgdat_congested(pg_data_t *pgdat)
6588{
Johannes Weiner1b051172019-11-30 17:55:52 -08006589 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6590
6591 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006592 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6593 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6594}
6595
Mel Gorman1741c872011-01-13 15:46:21 -08006596/*
Mel Gorman55150612012-07-31 16:44:35 -07006597 * Prepare kswapd for sleeping. This verifies that there are no processes
6598 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6599 *
6600 * Returns true if kswapd is ready to sleep
6601 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006602static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6603 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006604{
Mel Gorman55150612012-07-31 16:44:35 -07006605 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006606 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006607 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006608 * race between when kswapd checks the watermarks and a process gets
6609 * throttled. There is also a potential race if processes get
6610 * throttled, kswapd wakes, a large process exits thereby balancing the
6611 * zones, which causes kswapd to exit balance_pgdat() before reaching
6612 * the wake up checks. If kswapd is going to sleep, no process should
6613 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6614 * the wake up is premature, processes will wake kswapd and get
6615 * throttled again. The difference from wake ups in balance_pgdat() is
6616 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006617 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006618 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6619 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006620
Johannes Weinerc73322d2017-05-03 14:51:51 -07006621 /* Hopeless node, leave it to direct reclaim */
6622 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6623 return true;
6624
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006625 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006626 clear_pgdat_congested(pgdat);
6627 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006628 }
6629
Shantanu Goel333b0a42017-05-03 14:53:38 -07006630 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006631}
6632
Linus Torvalds1da177e2005-04-16 15:20:36 -07006633/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006634 * kswapd shrinks a node of pages that are at or below the highest usable
6635 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006636 *
6637 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006638 * reclaim or if the lack of progress was due to pages under writeback.
6639 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006640 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006641static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006642 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006643{
Mel Gorman1d82de62016-07-28 15:45:43 -07006644 struct zone *zone;
6645 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006646
Mel Gorman1d82de62016-07-28 15:45:43 -07006647 /* Reclaim a number of pages proportional to the number of zones */
6648 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006649 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006650 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006651 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006652 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006653
Mel Gorman1d82de62016-07-28 15:45:43 -07006654 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006655 }
6656
Mel Gorman1d82de62016-07-28 15:45:43 -07006657 /*
6658 * Historically care was taken to put equal pressure on all zones but
6659 * now pressure is applied based on node LRU order.
6660 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006661 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006662
6663 /*
6664 * Fragmentation may mean that the system cannot be rebalanced for
6665 * high-order allocations. If twice the allocation size has been
6666 * reclaimed then recheck watermarks only at order-0 to prevent
6667 * excessive reclaim. Assume that a process requested a high-order
6668 * can direct reclaim/compact.
6669 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006670 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006671 sc->order = 0;
6672
Mel Gormanb8e83b92013-07-03 15:01:45 -07006673 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006674}
6675
Mel Gormanc49c2c42021-06-28 19:42:21 -07006676/* Page allocator PCP high watermark is lowered if reclaim is active. */
6677static inline void
6678update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6679{
6680 int i;
6681 struct zone *zone;
6682
6683 for (i = 0; i <= highest_zoneidx; i++) {
6684 zone = pgdat->node_zones + i;
6685
6686 if (!managed_zone(zone))
6687 continue;
6688
6689 if (active)
6690 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6691 else
6692 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6693 }
6694}
6695
6696static inline void
6697set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6698{
6699 update_reclaim_active(pgdat, highest_zoneidx, true);
6700}
6701
6702static inline void
6703clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6704{
6705 update_reclaim_active(pgdat, highest_zoneidx, false);
6706}
6707
Mel Gorman75485362013-07-03 15:01:42 -07006708/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006709 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6710 * that are eligible for use by the caller until at least one zone is
6711 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006712 *
Mel Gorman1d82de62016-07-28 15:45:43 -07006713 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006714 *
6715 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07006716 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08006717 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07006718 * or lower is eligible for reclaim until at least one usable zone is
6719 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006720 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006721static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006722{
Linus Torvalds1da177e2005-04-16 15:20:36 -07006723 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07006724 unsigned long nr_soft_reclaimed;
6725 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07006726 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08006727 unsigned long nr_boost_reclaim;
6728 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6729 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07006730 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08006731 struct scan_control sc = {
6732 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07006733 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006734 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08006735 };
Omar Sandoval93781322018-06-07 17:07:02 -07006736
Andrew Morton1732d2b012019-07-16 16:26:15 -07006737 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07006738 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006739 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006740
Christoph Lameterf8891e52006-06-30 01:55:45 -07006741 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006742
Mel Gorman1c308442018-12-28 00:35:52 -08006743 /*
6744 * Account for the reclaim boost. Note that the zone boost is left in
6745 * place so that parallel allocations that are near the watermark will
6746 * stall or direct reclaim until kswapd is finished.
6747 */
6748 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006749 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006750 zone = pgdat->node_zones + i;
6751 if (!managed_zone(zone))
6752 continue;
6753
6754 nr_boost_reclaim += zone->watermark_boost;
6755 zone_boosts[i] = zone->watermark_boost;
6756 }
6757 boosted = nr_boost_reclaim;
6758
6759restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006760 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006761 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006762 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006763 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006764 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006765 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006766 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006767
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006768 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006769
Mel Gorman86c79f62016-07-28 15:45:59 -07006770 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006771 * If the number of buffer_heads exceeds the maximum allowed
6772 * then consider reclaiming from all zones. This has a dual
6773 * purpose -- on 64-bit systems it is expected that
6774 * buffer_heads are stripped during active rotation. On 32-bit
6775 * systems, highmem pages can pin lowmem memory and shrinking
6776 * buffers can relieve lowmem pressure. Reclaim may still not
6777 * go ahead if all eligible zones for the original allocation
6778 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006779 */
6780 if (buffer_heads_over_limit) {
6781 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6782 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006783 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006784 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006785
Mel Gorman970a39a2016-07-28 15:46:35 -07006786 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006787 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006788 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006789 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006790
Mel Gorman86c79f62016-07-28 15:45:59 -07006791 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006792 * If the pgdat is imbalanced then ignore boosting and preserve
6793 * the watermarks for a later time and restart. Note that the
6794 * zone watermarks will be still reset at the end of balancing
6795 * on the grounds that the normal reclaim should be enough to
6796 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006797 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006798 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006799 if (!balanced && nr_boost_reclaim) {
6800 nr_boost_reclaim = 0;
6801 goto restart;
6802 }
6803
6804 /*
6805 * If boosting is not active then only reclaim if there are no
6806 * eligible zones. Note that sc.reclaim_idx is not used as
6807 * buffer_heads_over_limit may have adjusted it.
6808 */
6809 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006810 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006811
Mel Gorman1c308442018-12-28 00:35:52 -08006812 /* Limit the priority of boosting to avoid reclaim writeback */
6813 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6814 raise_priority = false;
6815
6816 /*
6817 * Do not writeback or swap pages for boosted reclaim. The
6818 * intent is to relieve pressure not issue sub-optimal IO
6819 * from reclaim context. If no pages are reclaimed, the
6820 * reclaim will be aborted.
6821 */
6822 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6823 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006824
Linus Torvalds1da177e2005-04-16 15:20:36 -07006825 /*
Yu Zhao37397872022-09-18 02:00:03 -06006826 * Do some background aging, to give pages a chance to be
6827 * referenced before reclaiming. All pages are rotated
6828 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07006829 */
Yu Zhao37397872022-09-18 02:00:03 -06006830 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006831
6832 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006833 * If we're getting trouble reclaiming, start doing writepage
6834 * even in laptop mode.
6835 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006836 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006837 sc.may_writepage = 1;
6838
Mel Gorman1d82de62016-07-28 15:45:43 -07006839 /* Call soft limit reclaim before calling shrink_node. */
6840 sc.nr_scanned = 0;
6841 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006842 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006843 sc.gfp_mask, &nr_soft_scanned);
6844 sc.nr_reclaimed += nr_soft_reclaimed;
6845
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006846 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006847 * There should be no need to raise the scanning priority if
6848 * enough pages are already being scanned that that high
6849 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006850 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006851 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006852 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006853
6854 /*
6855 * If the low watermark is met there is no need for processes
6856 * to be throttled on pfmemalloc_wait as they should not be
6857 * able to safely make forward progress. Wake them
6858 */
6859 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006860 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006861 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006862
Mel Gormanb8e83b92013-07-03 15:01:45 -07006863 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006864 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006865 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006866 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006867 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006868 break;
6869
6870 /*
6871 * Raise priority if scanning rate is too low or there was no
6872 * progress in reclaiming pages
6873 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006874 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006875 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6876
6877 /*
6878 * If reclaim made no progress for a boost, stop reclaim as
6879 * IO cannot be queued and it could be an infinite loop in
6880 * extreme circumstances.
6881 */
6882 if (nr_boost_reclaim && !nr_reclaimed)
6883 break;
6884
Johannes Weinerc73322d2017-05-03 14:51:51 -07006885 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006886 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006887 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006888
Johannes Weinerc73322d2017-05-03 14:51:51 -07006889 if (!sc.nr_reclaimed)
6890 pgdat->kswapd_failures++;
6891
Mel Gormanb8e83b92013-07-03 15:01:45 -07006892out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006893 clear_reclaim_active(pgdat, highest_zoneidx);
6894
Mel Gorman1c308442018-12-28 00:35:52 -08006895 /* If reclaim was boosted, account for the reclaim done in this pass */
6896 if (boosted) {
6897 unsigned long flags;
6898
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006899 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006900 if (!zone_boosts[i])
6901 continue;
6902
6903 /* Increments are under the zone lock */
6904 zone = pgdat->node_zones + i;
6905 spin_lock_irqsave(&zone->lock, flags);
6906 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6907 spin_unlock_irqrestore(&zone->lock, flags);
6908 }
6909
6910 /*
6911 * As there is now likely space, wakeup kcompact to defragment
6912 * pageblocks.
6913 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006914 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006915 }
6916
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006917 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006918 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006919 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006920 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006921
Mel Gorman0abdee22011-01-13 15:46:22 -08006922 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006923 * Return the order kswapd stopped reclaiming at as
6924 * prepare_kswapd_sleep() takes it into account. If another caller
6925 * entered the allocator slow path while kswapd was awake, order will
6926 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006927 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006928 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006929}
6930
Mel Gormane716f2e2017-05-03 14:53:45 -07006931/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006932 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6933 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6934 * not a valid index then either kswapd runs for first time or kswapd couldn't
6935 * sleep after previous reclaim attempt (node is still unbalanced). In that
6936 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006937 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006938static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6939 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006940{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006941 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006942
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006943 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006944}
6945
Mel Gorman38087d92016-07-28 15:45:49 -07006946static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006947 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006948{
6949 long remaining = 0;
6950 DEFINE_WAIT(wait);
6951
6952 if (freezing(current) || kthread_should_stop())
6953 return;
6954
6955 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6956
Shantanu Goel333b0a42017-05-03 14:53:38 -07006957 /*
6958 * Try to sleep for a short interval. Note that kcompactd will only be
6959 * woken if it is possible to sleep for a short interval. This is
6960 * deliberate on the assumption that if reclaim cannot keep an
6961 * eligible zone balanced that it's also unlikely that compaction will
6962 * succeed.
6963 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006964 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006965 /*
6966 * Compaction records what page blocks it recently failed to
6967 * isolate pages from and skips them in the future scanning.
6968 * When kswapd is going to sleep, it is reasonable to assume
6969 * that pages and compaction may succeed so reset the cache.
6970 */
6971 reset_isolation_suitable(pgdat);
6972
6973 /*
6974 * We have freed the memory, now we should compact it to make
6975 * allocation of the requested order possible.
6976 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006977 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006978
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006979 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006980
6981 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006982 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006983 * order. The values will either be from a wakeup request or
6984 * the previous request that slept prematurely.
6985 */
6986 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006987 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6988 kswapd_highest_zoneidx(pgdat,
6989 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006990
6991 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6992 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006993 }
6994
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006995 finish_wait(&pgdat->kswapd_wait, &wait);
6996 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6997 }
6998
6999 /*
7000 * After a short sleep, check if it was a premature sleep. If not, then
7001 * go fully to sleep until explicitly woken up.
7002 */
Mel Gormand9f21d42016-07-28 15:46:41 -07007003 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007004 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007005 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7006
7007 /*
7008 * vmstat counters are not perfectly accurate and the estimated
7009 * value for counters such as NR_FREE_PAGES can deviate from the
7010 * true value by nr_online_cpus * threshold. To avoid the zone
7011 * watermarks being breached while under pressure, we reduce the
7012 * per-cpu vmstat threshold while kswapd is awake and restore
7013 * them before going back to sleep.
7014 */
7015 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07007016
7017 if (!kthread_should_stop())
7018 schedule();
7019
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007020 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7021 } else {
7022 if (remaining)
7023 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7024 else
7025 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7026 }
7027 finish_wait(&pgdat->kswapd_wait, &wait);
7028}
7029
Linus Torvalds1da177e2005-04-16 15:20:36 -07007030/*
7031 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07007032 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007033 *
7034 * This basically trickles out pages so that we have _some_
7035 * free memory available even if there is no other activity
7036 * that frees anything up. This is needed for things like routing
7037 * etc, where we otherwise might have all activity going on in
7038 * asynchronous contexts that cannot page things out.
7039 *
7040 * If there are applications that are active memory-allocators
7041 * (most normal use), this basically shouldn't matter.
7042 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307043int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007044{
Mel Gormane716f2e2017-05-03 14:53:45 -07007045 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007046 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07007047 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007048 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10307049 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007050
Rusty Russell174596a2009-01-01 10:12:29 +10307051 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07007052 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007053
7054 /*
7055 * Tell the memory management that we're a "memory allocator",
7056 * and that if we need more memory we should get access to it
7057 * regardless (see "__alloc_pages()"). "kswapd" should
7058 * never get caught in the normal page freeing logic.
7059 *
7060 * (Kswapd normally doesn't need memory anyway, but sometimes
7061 * you need a small amount of memory in order to be able to
7062 * page out something else, and this flag essentially protects
7063 * us from recursively trying to free more memory as we're
7064 * trying to free the first piece of memory in the first place).
7065 */
Christoph Lameter930d9152006-01-08 01:00:47 -08007066 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07007067 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07007068
Qian Cai5644e1fb2020-04-01 21:10:12 -07007069 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007070 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007071 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08007072 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07007073
Qian Cai5644e1fb2020-04-01 21:10:12 -07007074 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007075 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7076 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07007077
Mel Gorman38087d92016-07-28 15:45:49 -07007078kswapd_try_sleep:
7079 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007080 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07007081
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007082 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08007083 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007084 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7085 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007086 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007087 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007088
David Rientjes8fe23e02009-12-14 17:58:33 -08007089 ret = try_to_freeze();
7090 if (kthread_should_stop())
7091 break;
7092
7093 /*
7094 * We can speed up thawing tasks if we don't call balance_pgdat
7095 * after returning from the refrigerator
7096 */
Mel Gorman38087d92016-07-28 15:45:49 -07007097 if (ret)
7098 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07007099
Mel Gorman38087d92016-07-28 15:45:49 -07007100 /*
7101 * Reclaim begins at the requested order but if a high-order
7102 * reclaim fails then kswapd falls back to reclaiming for
7103 * order-0. If that happens, kswapd will consider sleeping
7104 * for the order it finished reclaiming at (reclaim_order)
7105 * but kcompactd is woken to compact for the original
7106 * request (alloc_order).
7107 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007108 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007109 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007110 reclaim_order = balance_pgdat(pgdat, alloc_order,
7111 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007112 if (reclaim_order < alloc_order)
7113 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007114 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007115
Johannes Weiner71abdc12014-06-06 14:35:35 -07007116 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007117
Linus Torvalds1da177e2005-04-16 15:20:36 -07007118 return 0;
7119}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307120EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007121
7122/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007123 * A zone is low on free memory or too fragmented for high-order memory. If
7124 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7125 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7126 * has failed or is not needed, still wake up kcompactd if only compaction is
7127 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007128 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007129void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007130 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007131{
7132 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007133 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007134
Mel Gorman6aa303d2016-09-01 16:14:55 -07007135 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007136 return;
7137
David Rientjes5ecd9d42018-04-05 16:25:16 -07007138 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007139 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007140
Qian Cai5644e1fb2020-04-01 21:10:12 -07007141 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007142 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007143
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007144 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7145 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007146
7147 if (READ_ONCE(pgdat->kswapd_order) < order)
7148 WRITE_ONCE(pgdat->kswapd_order, order);
7149
Con Kolivas8d0986e2005-09-13 01:25:07 -07007150 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007151 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007152
David Rientjes5ecd9d42018-04-05 16:25:16 -07007153 /* Hopeless node, leave it to direct reclaim if possible */
7154 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007155 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7156 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007157 /*
7158 * There may be plenty of free memory available, but it's too
7159 * fragmented for high-order allocations. Wake up kcompactd
7160 * and rely on compaction_suitable() to determine if it's
7161 * needed. If it fails, it will defer subsequent attempts to
7162 * ratelimit its work.
7163 */
7164 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007165 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007166 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007167 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007168
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007169 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007170 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007171 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007172}
7173
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007174#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007175/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007176 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007177 * freed pages.
7178 *
7179 * Rather than trying to age LRUs the aim is to preserve the overall
7180 * LRU order by reclaiming preferentially
7181 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007182 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007183unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007184{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007185 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007186 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007187 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007188 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007189 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007190 .may_writepage = 1,
7191 .may_unmap = 1,
7192 .may_swap = 1,
7193 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007194 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007195 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007196 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007197 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007198
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007199 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007200 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007201 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007202
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007203 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007204
Andrew Morton1732d2b012019-07-16 16:26:15 -07007205 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007206 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007207 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007208
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007209 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007210}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007211#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007212
Yasunori Goto3218ae12006-06-27 02:53:33 -07007213/*
7214 * This kswapd start function will be called by init and node-hot-add.
7215 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7216 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007217void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007218{
7219 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307220 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007221
7222 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007223 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007224
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307225 trace_android_vh_kswapd_per_node(nid, &skip, true);
7226 if (skip)
7227 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007228 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7229 if (IS_ERR(pgdat->kswapd)) {
7230 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007231 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007232 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007233 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007234 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007235}
7236
David Rientjes8fe23e02009-12-14 17:58:33 -08007237/*
Jiang Liud8adde12012-07-11 14:01:52 -07007238 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007239 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007240 */
7241void kswapd_stop(int nid)
7242{
7243 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307244 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007245
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307246 trace_android_vh_kswapd_per_node(nid, &skip, false);
7247 if (skip)
7248 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007249 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007250 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007251 NODE_DATA(nid)->kswapd = NULL;
7252 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007253}
7254
Linus Torvalds1da177e2005-04-16 15:20:36 -07007255static int __init kswapd_init(void)
7256{
Wei Yang6b700b52020-04-01 21:10:09 -07007257 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007258
Linus Torvalds1da177e2005-04-16 15:20:36 -07007259 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007260 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007261 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007262 return 0;
7263}
7264
7265module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007266
7267#ifdef CONFIG_NUMA
7268/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007269 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007270 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007271 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007272 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007273 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007274int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007275
Dave Hansen51998362021-02-24 12:09:15 -08007276/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007277 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007278 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7279 * a zone.
7280 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007281#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007282
Christoph Lameter9eeff232006-01-18 17:42:31 -08007283/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007284 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007285 * occur.
7286 */
7287int sysctl_min_unmapped_ratio = 1;
7288
7289/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007290 * If the number of slab pages in a zone grows beyond this percentage then
7291 * slab reclaim needs to occur.
7292 */
7293int sysctl_min_slab_ratio = 5;
7294
Mel Gorman11fb9982016-07-28 15:46:20 -07007295static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007296{
Mel Gorman11fb9982016-07-28 15:46:20 -07007297 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7298 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7299 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007300
7301 /*
7302 * It's possible for there to be more file mapped pages than
7303 * accounted for by the pages on the file LRU lists because
7304 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7305 */
7306 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7307}
7308
7309/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007310static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007311{
Alexandru Moised031a152015-11-05 18:48:08 -08007312 unsigned long nr_pagecache_reclaimable;
7313 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007314
7315 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007316 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007317 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007318 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007319 * a better estimate
7320 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007321 if (node_reclaim_mode & RECLAIM_UNMAP)
7322 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007323 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007324 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007325
7326 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007327 if (!(node_reclaim_mode & RECLAIM_WRITE))
7328 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007329
7330 /* Watch for any possible underflows due to delta */
7331 if (unlikely(delta > nr_pagecache_reclaimable))
7332 delta = nr_pagecache_reclaimable;
7333
7334 return nr_pagecache_reclaimable - delta;
7335}
7336
Christoph Lameter0ff38492006-09-25 23:31:52 -07007337/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007338 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007339 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007340static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007341{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007342 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007343 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007344 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007345 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007346 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007347 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007348 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007349 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007350 .priority = NODE_RECLAIM_PRIORITY,
7351 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7352 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007353 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007354 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007355 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007356 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007357
Yafang Shao132bb8c2019-05-13 17:17:53 -07007358 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7359 sc.gfp_mask);
7360
Christoph Lameter9eeff232006-01-18 17:42:31 -08007361 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007362 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007363 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007364 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007365 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007366 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007367 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007368 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007369 noreclaim_flag = memalloc_noreclaim_save();
7370 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007371 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007372
Mel Gormana5f5f912016-07-28 15:46:32 -07007373 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007374 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007375 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007376 * priorities until we have enough memory freed.
7377 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007378 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007379 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007380 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007381 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007382
Andrew Morton1732d2b012019-07-16 16:26:15 -07007383 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007384 current->flags &= ~PF_SWAPWRITE;
7385 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007386 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007387 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007388
7389 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7390
Rik van Riela79311c2009-01-06 14:40:01 -08007391 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007392}
Andrew Morton179e9632006-03-22 00:08:18 -08007393
Mel Gormana5f5f912016-07-28 15:46:32 -07007394int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007395{
David Rientjesd773ed62007-10-16 23:26:01 -07007396 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007397
7398 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007399 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007400 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007401 *
Christoph Lameter96146342006-07-03 00:24:13 -07007402 * A small portion of unmapped file backed pages is needed for
7403 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007404 * thrown out if the node is overallocated. So we do not reclaim
7405 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007406 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007407 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007408 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007409 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7410 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007411 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007412
7413 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007414 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007415 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007416 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007417 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007418
7419 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007420 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007421 * have associated processors. This will favor the local processor
7422 * over remote processors and spread off node memory allocations
7423 * as wide as possible.
7424 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007425 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7426 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007427
Mel Gormana5f5f912016-07-28 15:46:32 -07007428 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7429 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007430
Mel Gormana5f5f912016-07-28 15:46:32 -07007431 ret = __node_reclaim(pgdat, gfp_mask, order);
7432 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007433
Mel Gorman24cf725182009-06-16 15:33:23 -07007434 if (!ret)
7435 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7436
David Rientjesd773ed62007-10-16 23:26:01 -07007437 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007438}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007439#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007440
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007441/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007442 * check_move_unevictable_pages - check pages for evictability and move to
7443 * appropriate zone lru list
7444 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007445 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007446 * Checks pages for evictability, if an evictable page is in the unevictable
7447 * lru list, moves it to the appropriate evictable lru list. This function
7448 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007449 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007450void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007451{
Alex Shi6168d0d2020-12-15 12:34:29 -08007452 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007453 int pgscanned = 0;
7454 int pgrescued = 0;
7455 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007456
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007457 for (i = 0; i < pvec->nr; i++) {
7458 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007459 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007460
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007461 if (PageTransTail(page))
7462 continue;
7463
7464 nr_pages = thp_nr_pages(page);
7465 pgscanned += nr_pages;
7466
Alex Shid25b5bd2020-12-15 12:34:16 -08007467 /* block memcg migration during page moving between lru */
7468 if (!TestClearPageLRU(page))
7469 continue;
7470
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007471 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007472 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007473 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007474 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007475 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007476 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007477 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007478 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007479 }
Hugh Dickins24513262012-01-20 14:34:21 -08007480
Alex Shi6168d0d2020-12-15 12:34:29 -08007481 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007482 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7483 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007484 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007485 } else if (pgscanned) {
7486 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007487 }
Hugh Dickins850465792012-01-20 14:34:19 -08007488}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007489EXPORT_SYMBOL_GPL(check_move_unevictable_pages);