blob: 95cc65d3f6b92e68d98fbd2f4cc28159681efc4c [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{
2961 /* see the comment on lru_gen_struct */
2962 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
3075 rcu_read_lock();
3076 memcg = mem_cgroup_from_task(task);
3077 rcu_read_unlock();
3078 if (memcg == mm->lru_gen.memcg)
3079 return;
3080
3081 VM_WARN_ON_ONCE(!mm->lru_gen.memcg);
3082 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3083
3084 lru_gen_del_mm(mm);
3085 lru_gen_add_mm(mm);
3086}
3087#endif
3088
3089/*
3090 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3091 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3092 * bits in a bitmap, k is the number of hash functions and n is the number of
3093 * inserted items.
3094 *
3095 * Page table walkers use one of the two filters to reduce their search space.
3096 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3097 * aging uses the double-buffering technique to flip to the other filter each
3098 * time it produces a new generation. For non-leaf entries that have enough
3099 * leaf entries, the aging carries them over to the next generation in
3100 * walk_pmd_range(); the eviction also report them when walking the rmap
3101 * in lru_gen_look_around().
3102 *
3103 * For future optimizations:
3104 * 1. It's not necessary to keep both filters all the time. The spare one can be
3105 * freed after the RCU grace period and reallocated if needed again.
3106 * 2. And when reallocating, it's worth scaling its size according to the number
3107 * of inserted entries in the other filter, to reduce the memory overhead on
3108 * small systems and false positives on large systems.
3109 * 3. Jenkins' hash function is an alternative to Knuth's.
3110 */
3111#define BLOOM_FILTER_SHIFT 15
3112
3113static inline int filter_gen_from_seq(unsigned long seq)
3114{
3115 return seq % NR_BLOOM_FILTERS;
3116}
3117
3118static void get_item_key(void *item, int *key)
3119{
3120 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3121
3122 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3123
3124 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3125 key[1] = hash >> BLOOM_FILTER_SHIFT;
3126}
3127
3128static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3129{
3130 unsigned long *filter;
3131 int gen = filter_gen_from_seq(seq);
3132
3133 filter = lruvec->mm_state.filters[gen];
3134 if (filter) {
3135 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3136 return;
3137 }
3138
3139 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3140 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3141 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3142}
3143
3144static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3145{
3146 int key[2];
3147 unsigned long *filter;
3148 int gen = filter_gen_from_seq(seq);
3149
3150 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3151 if (!filter)
3152 return;
3153
3154 get_item_key(item, key);
3155
3156 if (!test_bit(key[0], filter))
3157 set_bit(key[0], filter);
3158 if (!test_bit(key[1], filter))
3159 set_bit(key[1], filter);
3160}
3161
3162static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3163{
3164 int key[2];
3165 unsigned long *filter;
3166 int gen = filter_gen_from_seq(seq);
3167
3168 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3169 if (!filter)
3170 return true;
3171
3172 get_item_key(item, key);
3173
3174 return test_bit(key[0], filter) && test_bit(key[1], filter);
3175}
3176
3177static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3178{
3179 int i;
3180 int hist;
3181
3182 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3183
3184 if (walk) {
3185 hist = lru_hist_from_seq(walk->max_seq);
3186
3187 for (i = 0; i < NR_MM_STATS; i++) {
3188 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3189 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3190 walk->mm_stats[i] = 0;
3191 }
3192 }
3193
3194 if (NR_HIST_GENS > 1 && last) {
3195 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3196
3197 for (i = 0; i < NR_MM_STATS; i++)
3198 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3199 }
3200}
3201
3202static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3203{
3204 int type;
3205 unsigned long size = 0;
3206 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3207 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3208
3209 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3210 return true;
3211
3212 clear_bit(key, &mm->lru_gen.bitmap);
3213
3214 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3215 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3216 get_mm_counter(mm, MM_ANONPAGES) +
3217 get_mm_counter(mm, MM_SHMEMPAGES);
3218 }
3219
3220 if (size < MIN_LRU_BATCH)
3221 return true;
3222
3223 return !mmget_not_zero(mm);
3224}
3225
3226static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3227 struct mm_struct **iter)
3228{
3229 bool first = false;
3230 bool last = true;
3231 struct mm_struct *mm = NULL;
3232 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3233 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3234 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3235
3236 /*
3237 * There are four interesting cases for this page table walker:
3238 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3239 * there is nothing left to do.
3240 * 2. It's the first of the current generation, and it needs to reset
3241 * the Bloom filter for the next generation.
3242 * 3. It reaches the end of mm_list, and it needs to increment
3243 * mm_state->seq; the iteration is done.
3244 * 4. It's the last of the current generation, and it needs to reset the
3245 * mm stats counters for the next generation.
3246 */
3247 spin_lock(&mm_list->lock);
3248
3249 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3250 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3251 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3252
3253 if (walk->max_seq <= mm_state->seq) {
3254 if (!*iter)
3255 last = false;
3256 goto done;
3257 }
3258
3259 if (!mm_state->nr_walkers) {
3260 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3261
3262 mm_state->head = mm_list->fifo.next;
3263 first = true;
3264 }
3265
3266 while (!mm && mm_state->head != &mm_list->fifo) {
3267 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3268
3269 mm_state->head = mm_state->head->next;
3270
3271 /* force scan for those added after the last iteration */
3272 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3273 mm_state->tail = mm_state->head;
3274 walk->force_scan = true;
3275 }
3276
3277 if (should_skip_mm(mm, walk))
3278 mm = NULL;
3279 }
3280
3281 if (mm_state->head == &mm_list->fifo)
3282 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3283done:
3284 if (*iter && !mm)
3285 mm_state->nr_walkers--;
3286 if (!*iter && mm)
3287 mm_state->nr_walkers++;
3288
3289 if (mm_state->nr_walkers)
3290 last = false;
3291
3292 if (*iter || last)
3293 reset_mm_stats(lruvec, walk, last);
3294
3295 spin_unlock(&mm_list->lock);
3296
3297 if (mm && first)
3298 reset_bloom_filter(lruvec, walk->max_seq + 1);
3299
3300 if (*iter)
3301 mmput_async(*iter);
3302
3303 *iter = mm;
3304
3305 return last;
3306}
3307
3308static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3309{
3310 bool success = false;
3311 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3312 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3313 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3314
3315 spin_lock(&mm_list->lock);
3316
3317 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3318
3319 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3320 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3321
3322 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3323 reset_mm_stats(lruvec, NULL, true);
3324 success = true;
3325 }
3326
3327 spin_unlock(&mm_list->lock);
3328
3329 return success;
3330}
3331
3332/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003333 * refault feedback loop
3334 ******************************************************************************/
3335
3336/*
3337 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3338 *
3339 * The P term is refaulted/(evicted+protected) from a tier in the generation
3340 * currently being evicted; the I term is the exponential moving average of the
3341 * P term over the generations previously evicted, using the smoothing factor
3342 * 1/2; the D term isn't supported.
3343 *
3344 * The setpoint (SP) is always the first tier of one type; the process variable
3345 * (PV) is either any tier of the other type or any other tier of the same
3346 * type.
3347 *
3348 * The error is the difference between the SP and the PV; the correction is to
3349 * turn off protection when SP>PV or turn on protection when SP<PV.
3350 *
3351 * For future optimizations:
3352 * 1. The D term may discount the other two terms over time so that long-lived
3353 * generations can resist stale information.
3354 */
3355struct ctrl_pos {
3356 unsigned long refaulted;
3357 unsigned long total;
3358 int gain;
3359};
3360
3361static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3362 struct ctrl_pos *pos)
3363{
3364 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3365 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3366
3367 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3368 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3369 pos->total = lrugen->avg_total[type][tier] +
3370 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3371 if (tier)
3372 pos->total += lrugen->protected[hist][type][tier - 1];
3373 pos->gain = gain;
3374}
3375
3376static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3377{
3378 int hist, tier;
3379 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3380 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3381 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3382
3383 lockdep_assert_held(&lruvec->lru_lock);
3384
3385 if (!carryover && !clear)
3386 return;
3387
3388 hist = lru_hist_from_seq(seq);
3389
3390 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3391 if (carryover) {
3392 unsigned long sum;
3393
3394 sum = lrugen->avg_refaulted[type][tier] +
3395 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3396 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3397
3398 sum = lrugen->avg_total[type][tier] +
3399 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3400 if (tier)
3401 sum += lrugen->protected[hist][type][tier - 1];
3402 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3403 }
3404
3405 if (clear) {
3406 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3407 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3408 if (tier)
3409 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3410 }
3411 }
3412}
3413
3414static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3415{
3416 /*
3417 * Return true if the PV has a limited number of refaults or a lower
3418 * refaulted/total than the SP.
3419 */
3420 return pv->refaulted < MIN_LRU_BATCH ||
3421 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3422 (sp->refaulted + 1) * pv->total * pv->gain;
3423}
3424
3425/******************************************************************************
3426 * the aging
3427 ******************************************************************************/
3428
Yu Zhao0182f922022-09-18 02:00:04 -06003429/* promote pages accessed through page tables */
3430static int page_update_gen(struct page *page, int gen)
3431{
3432 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3433
3434 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3435 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3436
3437 do {
3438 /* lru_gen_del_page() has isolated this page? */
3439 if (!(old_flags & LRU_GEN_MASK)) {
3440 /* for shrink_page_list() */
3441 new_flags = old_flags | BIT(PG_referenced);
3442 continue;
3443 }
3444
3445 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3446 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3447 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3448
3449 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3450}
3451
Yu Zhao37397872022-09-18 02:00:03 -06003452/* protect pages accessed multiple times through file descriptors */
3453static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3454{
3455 int type = page_is_file_lru(page);
3456 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3457 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3458 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3459
3460 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3461
3462 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003463 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3464 /* page_update_gen() has promoted this page? */
3465 if (new_gen >= 0 && new_gen != old_gen)
3466 return new_gen;
3467
Yu Zhao37397872022-09-18 02:00:03 -06003468 new_gen = (old_gen + 1) % MAX_NR_GENS;
3469
3470 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3471 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3472 /* for end_page_writeback() */
3473 if (reclaiming)
3474 new_flags |= BIT(PG_reclaim);
3475 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3476
3477 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3478
3479 return new_gen;
3480}
3481
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003482static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3483 int old_gen, int new_gen)
3484{
3485 int type = page_is_file_lru(page);
3486 int zone = page_zonenum(page);
3487 int delta = thp_nr_pages(page);
3488
3489 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3490 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3491
3492 walk->batched++;
3493
3494 walk->nr_pages[old_gen][type][zone] -= delta;
3495 walk->nr_pages[new_gen][type][zone] += delta;
3496}
3497
3498static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3499{
3500 int gen, type, zone;
3501 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3502
3503 walk->batched = 0;
3504
3505 for_each_gen_type_zone(gen, type, zone) {
3506 enum lru_list lru = type * LRU_INACTIVE_FILE;
3507 int delta = walk->nr_pages[gen][type][zone];
3508
3509 if (!delta)
3510 continue;
3511
3512 walk->nr_pages[gen][type][zone] = 0;
3513 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3514 lrugen->nr_pages[gen][type][zone] + delta);
3515
3516 if (lru_gen_is_active(lruvec, gen))
3517 lru += LRU_ACTIVE;
3518 __update_lru_size(lruvec, lru, zone, delta);
3519 }
3520}
3521
3522static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3523{
3524 struct address_space *mapping;
3525 struct vm_area_struct *vma = args->vma;
3526 struct lru_gen_mm_walk *walk = args->private;
3527
3528 if (!vma_is_accessible(vma))
3529 return true;
3530
3531 if (is_vm_hugetlb_page(vma))
3532 return true;
3533
3534 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3535 return true;
3536
3537 if (vma == get_gate_vma(vma->vm_mm))
3538 return true;
3539
3540 if (vma_is_anonymous(vma))
3541 return !walk->can_swap;
3542
3543 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3544 return true;
3545
3546 mapping = vma->vm_file->f_mapping;
3547 if (mapping_unevictable(mapping))
3548 return true;
3549
3550 if (shmem_mapping(mapping))
3551 return !walk->can_swap;
3552
3553 /* to exclude special mappings like dax, etc. */
3554 return !mapping->a_ops->readpage;
3555}
3556
3557/*
3558 * Some userspace memory allocators map many single-page VMAs. Instead of
3559 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3560 * table to reduce zigzags and improve cache performance.
3561 */
3562static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3563 unsigned long *vm_start, unsigned long *vm_end)
3564{
3565 unsigned long start = round_up(*vm_end, size);
3566 unsigned long end = (start | ~mask) + 1;
3567
3568 VM_WARN_ON_ONCE(mask & size);
3569 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3570
3571 while (args->vma) {
3572 if (start >= args->vma->vm_end) {
3573 args->vma = args->vma->vm_next;
3574 continue;
3575 }
3576
3577 if (end && end <= args->vma->vm_start)
3578 return false;
3579
3580 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3581 args->vma = args->vma->vm_next;
3582 continue;
3583 }
3584
3585 *vm_start = max(start, args->vma->vm_start);
3586 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3587
3588 return true;
3589 }
3590
3591 return false;
3592}
3593
Yu Zhao0182f922022-09-18 02:00:04 -06003594static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3595{
3596 unsigned long pfn = pte_pfn(pte);
3597
3598 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3599
3600 if (!pte_present(pte) || is_zero_pfn(pfn))
3601 return -1;
3602
3603 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3604 return -1;
3605
3606 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3607 return -1;
3608
3609 return pfn;
3610}
3611
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003612#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3613static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3614{
3615 unsigned long pfn = pmd_pfn(pmd);
3616
3617 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3618
3619 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3620 return -1;
3621
3622 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3623 return -1;
3624
3625 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3626 return -1;
3627
3628 return pfn;
3629}
3630#endif
3631
Yu Zhao0182f922022-09-18 02:00:04 -06003632static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003633 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003634{
3635 struct page *page;
3636
3637 /* try to avoid unnecessary memory loads */
3638 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3639 return NULL;
3640
3641 page = compound_head(pfn_to_page(pfn));
3642 if (page_to_nid(page) != pgdat->node_id)
3643 return NULL;
3644
3645 if (page_memcg_rcu(page) != memcg)
3646 return NULL;
3647
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003648 /* file VMAs can contain anon pages from COW */
3649 if (!page_is_file_lru(page) && !can_swap)
3650 return NULL;
3651
Yu Zhao0182f922022-09-18 02:00:04 -06003652 return page;
3653}
3654
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003655static bool suitable_to_scan(int total, int young)
3656{
3657 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3658
3659 /* suitable if the average number of young PTEs per cacheline is >=1 */
3660 return young * n >= total;
3661}
3662
3663static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3664 struct mm_walk *args)
3665{
3666 int i;
3667 pte_t *pte;
3668 spinlock_t *ptl;
3669 unsigned long addr;
3670 int total = 0;
3671 int young = 0;
3672 struct lru_gen_mm_walk *walk = args->private;
3673 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3674 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3675 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3676
3677 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3678
3679 ptl = pte_lockptr(args->mm, pmd);
3680 if (!spin_trylock(ptl))
3681 return false;
3682
3683 arch_enter_lazy_mmu_mode();
3684
3685 pte = pte_offset_map(pmd, start & PMD_MASK);
3686restart:
3687 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3688 unsigned long pfn;
3689 struct page *page;
3690
3691 total++;
3692 walk->mm_stats[MM_LEAF_TOTAL]++;
3693
3694 pfn = get_pte_pfn(pte[i], args->vma, addr);
3695 if (pfn == -1)
3696 continue;
3697
3698 if (!pte_young(pte[i])) {
3699 walk->mm_stats[MM_LEAF_OLD]++;
3700 continue;
3701 }
3702
3703 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3704 if (!page)
3705 continue;
3706
3707 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3708 VM_WARN_ON_ONCE(true);
3709
3710 young++;
3711 walk->mm_stats[MM_LEAF_YOUNG]++;
3712
3713 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3714 !(PageAnon(page) && PageSwapBacked(page) &&
3715 !PageSwapCache(page)))
3716 set_page_dirty(page);
3717
3718 old_gen = page_update_gen(page, new_gen);
3719 if (old_gen >= 0 && old_gen != new_gen)
3720 update_batch_size(walk, page, old_gen, new_gen);
3721 }
3722
3723 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3724 goto restart;
3725
3726 pte_unmap(pte);
3727
3728 arch_leave_lazy_mmu_mode();
3729 spin_unlock(ptl);
3730
3731 return suitable_to_scan(total, young);
3732}
3733
3734#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3735static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3736 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3737{
3738 int i;
3739 pmd_t *pmd;
3740 spinlock_t *ptl;
3741 struct lru_gen_mm_walk *walk = args->private;
3742 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3743 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3744 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3745
3746 VM_WARN_ON_ONCE(pud_leaf(*pud));
3747
3748 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3749 if (*start == -1) {
3750 *start = next;
3751 return;
3752 }
3753
3754 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3755 if (i && i <= MIN_LRU_BATCH) {
3756 __set_bit(i - 1, bitmap);
3757 return;
3758 }
3759
3760 pmd = pmd_offset(pud, *start);
3761
3762 ptl = pmd_lockptr(args->mm, pmd);
3763 if (!spin_trylock(ptl))
3764 goto done;
3765
3766 arch_enter_lazy_mmu_mode();
3767
3768 do {
3769 unsigned long pfn;
3770 struct page *page;
3771 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3772
3773 pfn = get_pmd_pfn(pmd[i], vma, addr);
3774 if (pfn == -1)
3775 goto next;
3776
3777 if (!pmd_trans_huge(pmd[i])) {
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003778 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3779 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003780 pmdp_test_and_clear_young(vma, addr, pmd + i);
3781 goto next;
3782 }
3783
3784 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3785 if (!page)
3786 goto next;
3787
3788 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3789 goto next;
3790
3791 walk->mm_stats[MM_LEAF_YOUNG]++;
3792
3793 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3794 !(PageAnon(page) && PageSwapBacked(page) &&
3795 !PageSwapCache(page)))
3796 set_page_dirty(page);
3797
3798 old_gen = page_update_gen(page, new_gen);
3799 if (old_gen >= 0 && old_gen != new_gen)
3800 update_batch_size(walk, page, old_gen, new_gen);
3801next:
3802 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3803 } while (i <= MIN_LRU_BATCH);
3804
3805 arch_leave_lazy_mmu_mode();
3806 spin_unlock(ptl);
3807done:
3808 *start = -1;
3809 bitmap_zero(bitmap, MIN_LRU_BATCH);
3810}
3811#else
3812static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3813 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3814{
3815}
3816#endif
3817
3818static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3819 struct mm_walk *args)
3820{
3821 int i;
3822 pmd_t *pmd;
3823 unsigned long next;
3824 unsigned long addr;
3825 struct vm_area_struct *vma;
3826 unsigned long pos = -1;
3827 struct lru_gen_mm_walk *walk = args->private;
3828 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3829
3830 VM_WARN_ON_ONCE(pud_leaf(*pud));
3831
3832 /*
3833 * Finish an entire PMD in two passes: the first only reaches to PTE
3834 * tables to avoid taking the PMD lock; the second, if necessary, takes
3835 * the PMD lock to clear the accessed bit in PMD entries.
3836 */
3837 pmd = pmd_offset(pud, start & PUD_MASK);
3838restart:
3839 /* walk_pte_range() may call get_next_vma() */
3840 vma = args->vma;
3841 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3842 pmd_t val = pmd_read_atomic(pmd + i);
3843
3844 /* for pmd_read_atomic() */
3845 barrier();
3846
3847 next = pmd_addr_end(addr, end);
3848
3849 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3850 walk->mm_stats[MM_LEAF_TOTAL]++;
3851 continue;
3852 }
3853
3854#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3855 if (pmd_trans_huge(val)) {
3856 unsigned long pfn = pmd_pfn(val);
3857 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3858
3859 walk->mm_stats[MM_LEAF_TOTAL]++;
3860
3861 if (!pmd_young(val)) {
3862 walk->mm_stats[MM_LEAF_OLD]++;
3863 continue;
3864 }
3865
3866 /* try to avoid unnecessary memory loads */
3867 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3868 continue;
3869
3870 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3871 continue;
3872 }
3873#endif
3874 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3875
3876#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003877 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3878 if (!pmd_young(val))
3879 continue;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003880
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003881 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3882 }
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003883#endif
3884 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3885 continue;
3886
3887 walk->mm_stats[MM_NONLEAF_FOUND]++;
3888
3889 if (!walk_pte_range(&val, addr, next, args))
3890 continue;
3891
3892 walk->mm_stats[MM_NONLEAF_ADDED]++;
3893
3894 /* carry over to the next generation */
3895 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3896 }
3897
3898 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3899
3900 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3901 goto restart;
3902}
3903
3904static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3905 struct mm_walk *args)
3906{
3907 int i;
3908 pud_t *pud;
3909 unsigned long addr;
3910 unsigned long next;
3911 struct lru_gen_mm_walk *walk = args->private;
3912
3913 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3914
3915 pud = pud_offset(p4d, start & P4D_MASK);
3916restart:
3917 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3918 pud_t val = READ_ONCE(pud[i]);
3919
3920 next = pud_addr_end(addr, end);
3921
3922 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3923 continue;
3924
3925 walk_pmd_range(&val, addr, next, args);
3926
3927 /* a racy check to curtail the waiting time */
3928 if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
3929 return 1;
3930
3931 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3932 end = (addr | ~PUD_MASK) + 1;
3933 goto done;
3934 }
3935 }
3936
3937 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3938 goto restart;
3939
3940 end = round_up(end, P4D_SIZE);
3941done:
3942 if (!end || !args->vma)
3943 return 1;
3944
3945 walk->next_addr = max(end, args->vma->vm_start);
3946
3947 return -EAGAIN;
3948}
3949
3950static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3951{
3952 static const struct mm_walk_ops mm_walk_ops = {
3953 .test_walk = should_skip_vma,
3954 .p4d_entry = walk_pud_range,
3955 };
3956
3957 int err;
3958 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3959
3960 walk->next_addr = FIRST_USER_ADDRESS;
3961
3962 do {
3963 err = -EBUSY;
3964
3965 /* page_update_gen() requires stable page_memcg() */
3966 if (!mem_cgroup_trylock_pages(memcg))
3967 break;
3968
3969 /* the caller might be holding the lock for write */
3970 if (mmap_read_trylock(mm)) {
3971 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3972
3973 mmap_read_unlock(mm);
3974 }
3975
3976 mem_cgroup_unlock_pages();
3977
3978 if (walk->batched) {
3979 spin_lock_irq(&lruvec->lru_lock);
3980 reset_batch_size(lruvec, walk);
3981 spin_unlock_irq(&lruvec->lru_lock);
3982 }
3983
3984 cond_resched();
3985 } while (err == -EAGAIN);
3986}
3987
3988static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
3989{
3990 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3991
3992 if (pgdat && current_is_kswapd()) {
3993 VM_WARN_ON_ONCE(walk);
3994
3995 walk = &pgdat->mm_walk;
3996 } else if (!pgdat && !walk) {
3997 VM_WARN_ON_ONCE(current_is_kswapd());
3998
3999 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4000 }
4001
4002 current->reclaim_state->mm_walk = walk;
4003
4004 return walk;
4005}
4006
4007static void clear_mm_walk(void)
4008{
4009 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4010
4011 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4012 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4013
4014 current->reclaim_state->mm_walk = NULL;
4015
4016 if (!current_is_kswapd())
4017 kfree(walk);
4018}
4019
Yu Zhao4983c522022-09-18 02:00:09 -06004020static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004021{
Yu Zhao4983c522022-09-18 02:00:09 -06004022 int zone;
4023 int remaining = MAX_LRU_BATCH;
Yu Zhao37397872022-09-18 02:00:03 -06004024 struct lru_gen_struct *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06004025 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
Yu Zhao37397872022-09-18 02:00:03 -06004026
Yu Zhao4983c522022-09-18 02:00:09 -06004027 if (type == LRU_GEN_ANON && !can_swap)
4028 goto done;
4029
4030 /* prevent cold/hot inversion if force_scan is true */
4031 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4032 struct list_head *head = &lrugen->lists[old_gen][type][zone];
4033
4034 while (!list_empty(head)) {
4035 struct page *page = lru_to_page(head);
4036
4037 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4038 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4039 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4040 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4041
4042 new_gen = page_inc_gen(lruvec, page, false);
4043 list_move_tail(&page->lru, &lrugen->lists[new_gen][type][zone]);
4044
4045 if (!--remaining)
4046 return false;
4047 }
4048 }
4049done:
Yu Zhao37397872022-09-18 02:00:03 -06004050 reset_ctrl_pos(lruvec, type, true);
4051 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
Yu Zhao4983c522022-09-18 02:00:09 -06004052
4053 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004054}
4055
4056static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4057{
4058 int gen, type, zone;
4059 bool success = false;
4060 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4061 DEFINE_MIN_SEQ(lruvec);
4062
4063 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4064
4065 /* find the oldest populated generation */
4066 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4067 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4068 gen = lru_gen_from_seq(min_seq[type]);
4069
4070 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4071 if (!list_empty(&lrugen->lists[gen][type][zone]))
4072 goto next;
4073 }
4074
4075 min_seq[type]++;
4076 }
4077next:
4078 ;
4079 }
4080
4081 /* see the comment on lru_gen_struct */
4082 if (can_swap) {
4083 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4084 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4085 }
4086
4087 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4088 if (min_seq[type] == lrugen->min_seq[type])
4089 continue;
4090
4091 reset_ctrl_pos(lruvec, type, true);
4092 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4093 success = true;
4094 }
4095
4096 return success;
4097}
4098
Yu Zhao4983c522022-09-18 02:00:09 -06004099static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
Yu Zhao37397872022-09-18 02:00:03 -06004100{
4101 int prev, next;
4102 int type, zone;
4103 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4104
4105 spin_lock_irq(&lruvec->lru_lock);
4106
4107 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4108
Yu Zhao37397872022-09-18 02:00:03 -06004109 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4110 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4111 continue;
4112
Yu Zhao4983c522022-09-18 02:00:09 -06004113 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
Yu Zhao37397872022-09-18 02:00:03 -06004114
Yu Zhao4983c522022-09-18 02:00:09 -06004115 while (!inc_min_seq(lruvec, type, can_swap)) {
4116 spin_unlock_irq(&lruvec->lru_lock);
4117 cond_resched();
4118 spin_lock_irq(&lruvec->lru_lock);
4119 }
Yu Zhao37397872022-09-18 02:00:03 -06004120 }
4121
4122 /*
4123 * Update the active/inactive LRU sizes for compatibility. Both sides of
4124 * the current max_seq need to be covered, since max_seq+1 can overlap
4125 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4126 * overlap, cold/hot inversion happens.
4127 */
4128 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4129 next = lru_gen_from_seq(lrugen->max_seq + 1);
4130
4131 for (type = 0; type < ANON_AND_FILE; type++) {
4132 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4133 enum lru_list lru = type * LRU_INACTIVE_FILE;
4134 long delta = lrugen->nr_pages[prev][type][zone] -
4135 lrugen->nr_pages[next][type][zone];
4136
4137 if (!delta)
4138 continue;
4139
4140 __update_lru_size(lruvec, lru, zone, delta);
4141 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4142 }
4143 }
4144
4145 for (type = 0; type < ANON_AND_FILE; type++)
4146 reset_ctrl_pos(lruvec, type, false);
4147
Yu Zhao430499c2022-09-18 02:00:08 -06004148 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhao37397872022-09-18 02:00:03 -06004149 /* make sure preceding modifications appear */
4150 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004151
Yu Zhao37397872022-09-18 02:00:03 -06004152 spin_unlock_irq(&lruvec->lru_lock);
4153}
4154
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004155static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
Yu Zhao4983c522022-09-18 02:00:09 -06004156 struct scan_control *sc, bool can_swap, bool force_scan)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004157{
4158 bool success;
4159 struct lru_gen_mm_walk *walk;
4160 struct mm_struct *mm = NULL;
4161 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4162
4163 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4164
4165 /* see the comment in iterate_mm_list() */
4166 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4167 success = false;
4168 goto done;
4169 }
4170
4171 /*
4172 * If the hardware doesn't automatically set the accessed bit, fallback
4173 * to lru_gen_look_around(), which only clears the accessed bit in a
4174 * handful of PTEs. Spreading the work out over a period of time usually
4175 * is less efficient, but it avoids bursty page faults.
4176 */
Yu Zhao4983c522022-09-18 02:00:09 -06004177 if (!force_scan && !(arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004178 success = iterate_mm_list_nowalk(lruvec, max_seq);
4179 goto done;
4180 }
4181
4182 walk = set_mm_walk(NULL);
4183 if (!walk) {
4184 success = iterate_mm_list_nowalk(lruvec, max_seq);
4185 goto done;
4186 }
4187
4188 walk->lruvec = lruvec;
4189 walk->max_seq = max_seq;
4190 walk->can_swap = can_swap;
Yu Zhao4983c522022-09-18 02:00:09 -06004191 walk->force_scan = force_scan;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004192
4193 do {
4194 success = iterate_mm_list(lruvec, walk, &mm);
4195 if (mm)
4196 walk_mm(lruvec, mm, walk);
4197
4198 cond_resched();
4199 } while (mm);
4200done:
4201 if (!success) {
4202 if (sc->priority <= DEF_PRIORITY - 2)
4203 wait_event_killable(lruvec->mm_state.wait,
4204 max_seq < READ_ONCE(lrugen->max_seq));
4205
4206 return max_seq < READ_ONCE(lrugen->max_seq);
4207 }
4208
4209 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4210
Yu Zhao4983c522022-09-18 02:00:09 -06004211 inc_max_seq(lruvec, can_swap, force_scan);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004212 /* either this sees any waiters or they will see updated max_seq */
4213 if (wq_has_sleeper(&lruvec->mm_state.wait))
4214 wake_up_all(&lruvec->mm_state.wait);
4215
4216 return true;
4217}
4218
Yu Zhao37397872022-09-18 02:00:03 -06004219static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
4220 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4221{
4222 int gen, type, zone;
4223 unsigned long old = 0;
4224 unsigned long young = 0;
4225 unsigned long total = 0;
4226 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4227 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4228
4229 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4230 unsigned long seq;
4231
4232 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4233 unsigned long size = 0;
4234
4235 gen = lru_gen_from_seq(seq);
4236
4237 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4238 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4239
4240 total += size;
4241 if (seq == max_seq)
4242 young += size;
4243 else if (seq + MIN_NR_GENS == max_seq)
4244 old += size;
4245 }
4246 }
4247
4248 /* try to scrape all its memory if this memcg was deleted */
4249 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4250
4251 /*
4252 * The aging tries to be lazy to reduce the overhead, while the eviction
4253 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4254 * ideal number of generations is MIN_NR_GENS+1.
4255 */
4256 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
4257 return true;
4258 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4259 return false;
4260
4261 /*
4262 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4263 * of the total number of pages for each generation. A reasonable range
4264 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4265 * aging cares about the upper bound of hot pages, while the eviction
4266 * cares about the lower bound of cold pages.
4267 */
4268 if (young * MIN_NR_GENS > total)
4269 return true;
4270 if (old * (MIN_NR_GENS + 2) < total)
4271 return true;
4272
4273 return false;
4274}
4275
Yu Zhao430499c2022-09-18 02:00:08 -06004276static bool age_lruvec(struct lruvec *lruvec, struct scan_control *sc, unsigned long min_ttl)
Yu Zhao37397872022-09-18 02:00:03 -06004277{
4278 bool need_aging;
4279 unsigned long nr_to_scan;
4280 int swappiness = get_swappiness(lruvec, sc);
4281 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4282 DEFINE_MAX_SEQ(lruvec);
4283 DEFINE_MIN_SEQ(lruvec);
4284
4285 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
4286
4287 mem_cgroup_calculate_protection(NULL, memcg);
4288
4289 if (mem_cgroup_below_min(memcg))
Yu Zhao430499c2022-09-18 02:00:08 -06004290 return false;
Yu Zhao37397872022-09-18 02:00:03 -06004291
4292 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
Yu Zhao430499c2022-09-18 02:00:08 -06004293
4294 if (min_ttl) {
4295 int gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4296 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4297
4298 if (time_is_after_jiffies(birth + min_ttl))
4299 return false;
4300
4301 /* the size is likely too small to be helpful */
4302 if (!nr_to_scan && sc->priority != DEF_PRIORITY)
4303 return false;
4304 }
4305
Yu Zhao37397872022-09-18 02:00:03 -06004306 if (need_aging)
Yu Zhao4983c522022-09-18 02:00:09 -06004307 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
Yu Zhao430499c2022-09-18 02:00:08 -06004308
4309 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004310}
4311
Yu Zhao430499c2022-09-18 02:00:08 -06004312/* to protect the working set of the last N jiffies */
4313static unsigned long lru_gen_min_ttl __read_mostly;
4314
Yu Zhao37397872022-09-18 02:00:03 -06004315static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4316{
4317 struct mem_cgroup *memcg;
Yu Zhao430499c2022-09-18 02:00:08 -06004318 bool success = false;
4319 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhao37397872022-09-18 02:00:03 -06004320
4321 VM_WARN_ON_ONCE(!current_is_kswapd());
4322
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004323 sc->last_reclaimed = sc->nr_reclaimed;
4324
4325 /*
4326 * To reduce the chance of going into the aging path, which can be
4327 * costly, optimistically skip it if the flag below was cleared in the
4328 * eviction path. This improves the overall performance when multiple
4329 * memcgs are available.
4330 */
4331 if (!sc->memcgs_need_aging) {
4332 sc->memcgs_need_aging = true;
4333 return;
4334 }
4335
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004336 set_mm_walk(pgdat);
4337
Yu Zhao37397872022-09-18 02:00:03 -06004338 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4339 do {
4340 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4341
Yu Zhao430499c2022-09-18 02:00:08 -06004342 if (age_lruvec(lruvec, sc, min_ttl))
4343 success = true;
Yu Zhao37397872022-09-18 02:00:03 -06004344
4345 cond_resched();
4346 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004347
4348 clear_mm_walk();
Yu Zhao430499c2022-09-18 02:00:08 -06004349
4350 /* check the order to exclude compaction-induced reclaim */
4351 if (success || !min_ttl || sc->order)
4352 return;
4353
4354 /*
4355 * The main goal is to OOM kill if every generation from all memcgs is
4356 * younger than min_ttl. However, another possibility is all memcgs are
4357 * either below min or empty.
4358 */
4359 if (mutex_trylock(&oom_lock)) {
4360 struct oom_control oc = {
4361 .gfp_mask = sc->gfp_mask,
4362 };
4363
4364 out_of_memory(&oc);
4365
4366 mutex_unlock(&oom_lock);
4367 }
Yu Zhao37397872022-09-18 02:00:03 -06004368}
4369
Yu Zhao0182f922022-09-18 02:00:04 -06004370/*
4371 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004372 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4373 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4374 * the PTE table to the Bloom filter. This forms a feedback loop between the
4375 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004376 */
4377void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4378{
4379 int i;
4380 pte_t *pte;
4381 unsigned long start;
4382 unsigned long end;
4383 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004384 struct lru_gen_mm_walk *walk;
4385 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004386 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4387 struct page *page = pvmw->page;
4388 struct mem_cgroup *memcg = page_memcg(page);
4389 struct pglist_data *pgdat = page_pgdat(page);
4390 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4391 DEFINE_MAX_SEQ(lruvec);
4392 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4393
4394 lockdep_assert_held(pvmw->ptl);
4395 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4396
4397 if (spin_is_contended(pvmw->ptl))
4398 return;
4399
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004400 /* avoid taking the LRU lock under the PTL when possible */
4401 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4402
Yu Zhao0182f922022-09-18 02:00:04 -06004403 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4404 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4405
4406 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4407 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4408 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4409 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4410 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4411 else {
4412 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4413 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4414 }
4415 }
4416
4417 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4418
4419 rcu_read_lock();
4420 arch_enter_lazy_mmu_mode();
4421
4422 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4423 unsigned long pfn;
4424
4425 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4426 if (pfn == -1)
4427 continue;
4428
4429 if (!pte_young(pte[i]))
4430 continue;
4431
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004432 page = get_pfn_page(pfn, memcg, pgdat, !walk || walk->can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004433 if (!page)
4434 continue;
4435
4436 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4437 VM_WARN_ON_ONCE(true);
4438
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004439 young++;
4440
Yu Zhao0182f922022-09-18 02:00:04 -06004441 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4442 !(PageAnon(page) && PageSwapBacked(page) &&
4443 !PageSwapCache(page)))
4444 set_page_dirty(page);
4445
4446 old_gen = page_lru_gen(page);
4447 if (old_gen < 0)
4448 SetPageReferenced(page);
4449 else if (old_gen != new_gen)
4450 __set_bit(i, bitmap);
4451 }
4452
4453 arch_leave_lazy_mmu_mode();
4454 rcu_read_unlock();
4455
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004456 /* feedback from rmap walkers to page table walkers */
4457 if (suitable_to_scan(i, young))
4458 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4459
4460 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004461 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4462 page = pte_page(pte[i]);
4463 activate_page(page);
4464 }
4465 return;
4466 }
4467
4468 /* page_update_gen() requires stable page_memcg() */
4469 if (!mem_cgroup_trylock_pages(memcg))
4470 return;
4471
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004472 if (!walk) {
4473 spin_lock_irq(&lruvec->lru_lock);
4474 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4475 }
Yu Zhao0182f922022-09-18 02:00:04 -06004476
4477 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4478 page = compound_head(pte_page(pte[i]));
4479 if (page_memcg_rcu(page) != memcg)
4480 continue;
4481
4482 old_gen = page_update_gen(page, new_gen);
4483 if (old_gen < 0 || old_gen == new_gen)
4484 continue;
4485
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004486 if (walk)
4487 update_batch_size(walk, page, old_gen, new_gen);
4488 else
4489 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004490 }
4491
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004492 if (!walk)
4493 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004494
4495 mem_cgroup_unlock_pages();
4496}
4497
Yu Zhao37397872022-09-18 02:00:03 -06004498/******************************************************************************
4499 * the eviction
4500 ******************************************************************************/
4501
4502static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4503{
4504 bool success;
4505 int gen = page_lru_gen(page);
4506 int type = page_is_file_lru(page);
4507 int zone = page_zonenum(page);
4508 int delta = thp_nr_pages(page);
4509 int refs = page_lru_refs(page);
4510 int tier = lru_tier_from_refs(refs);
4511 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4512
4513 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4514
4515 /* unevictable */
4516 if (!page_evictable(page)) {
4517 success = lru_gen_del_page(lruvec, page, true);
4518 VM_WARN_ON_ONCE_PAGE(!success, page);
4519 SetPageUnevictable(page);
4520 add_page_to_lru_list(page, lruvec);
4521 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4522 return true;
4523 }
4524
4525 /* dirty lazyfree */
4526 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4527 success = lru_gen_del_page(lruvec, page, true);
4528 VM_WARN_ON_ONCE_PAGE(!success, page);
4529 SetPageSwapBacked(page);
4530 add_page_to_lru_list_tail(page, lruvec);
4531 return true;
4532 }
4533
Yu Zhao0182f922022-09-18 02:00:04 -06004534 /* promoted */
4535 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4536 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4537 return true;
4538 }
4539
Yu Zhao37397872022-09-18 02:00:03 -06004540 /* protected */
4541 if (tier > tier_idx) {
4542 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4543
4544 gen = page_inc_gen(lruvec, page, false);
4545 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4546
4547 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4548 lrugen->protected[hist][type][tier - 1] + delta);
4549 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4550 return true;
4551 }
4552
4553 /* waiting for writeback */
4554 if (PageLocked(page) || PageWriteback(page) ||
4555 (type == LRU_GEN_FILE && PageDirty(page))) {
4556 gen = page_inc_gen(lruvec, page, true);
4557 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4558 return true;
4559 }
4560
4561 return false;
4562}
4563
4564static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4565{
4566 bool success;
4567
4568 /* unmapping inhibited */
4569 if (!sc->may_unmap && page_mapped(page))
4570 return false;
4571
4572 /* swapping inhibited */
4573 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4574 (PageDirty(page) ||
4575 (PageAnon(page) && !PageSwapCache(page))))
4576 return false;
4577
4578 /* raced with release_pages() */
4579 if (!get_page_unless_zero(page))
4580 return false;
4581
4582 /* raced with another isolation */
4583 if (!TestClearPageLRU(page)) {
4584 put_page(page);
4585 return false;
4586 }
4587
4588 /* see the comment on MAX_NR_TIERS */
4589 if (!PageReferenced(page))
4590 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4591
4592 /* for shrink_page_list() */
4593 ClearPageReclaim(page);
4594 ClearPageReferenced(page);
4595
4596 success = lru_gen_del_page(lruvec, page, true);
4597 VM_WARN_ON_ONCE_PAGE(!success, page);
4598
4599 return true;
4600}
4601
4602static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4603 int type, int tier, struct list_head *list)
4604{
4605 int gen, zone;
4606 enum vm_event_item item;
4607 int sorted = 0;
4608 int scanned = 0;
4609 int isolated = 0;
4610 int remaining = MAX_LRU_BATCH;
4611 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4612 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4613
4614 VM_WARN_ON_ONCE(!list_empty(list));
4615
4616 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4617 return 0;
4618
4619 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4620
4621 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4622 LIST_HEAD(moved);
4623 int skipped = 0;
4624 struct list_head *head = &lrugen->lists[gen][type][zone];
4625
4626 while (!list_empty(head)) {
4627 struct page *page = lru_to_page(head);
4628 int delta = thp_nr_pages(page);
4629
4630 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4631 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4632 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4633 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4634
4635 scanned += delta;
4636
4637 if (sort_page(lruvec, page, tier))
4638 sorted += delta;
4639 else if (isolate_page(lruvec, page, sc)) {
4640 list_add(&page->lru, list);
4641 isolated += delta;
4642 } else {
4643 list_move(&page->lru, &moved);
4644 skipped += delta;
4645 }
4646
4647 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4648 break;
4649 }
4650
4651 if (skipped) {
4652 list_splice(&moved, head);
4653 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4654 }
4655
4656 if (!remaining || isolated >= MIN_LRU_BATCH)
4657 break;
4658 }
4659
4660 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4661 if (!cgroup_reclaim(sc)) {
4662 __count_vm_events(item, isolated);
4663 __count_vm_events(PGREFILL, sorted);
4664 }
4665 __count_memcg_events(memcg, item, isolated);
4666 __count_memcg_events(memcg, PGREFILL, sorted);
4667 __count_vm_events(PGSCAN_ANON + type, isolated);
4668
4669 /*
4670 * There might not be eligible pages due to reclaim_idx, may_unmap and
4671 * may_writepage. Check the remaining to prevent livelock if it's not
4672 * making progress.
4673 */
4674 return isolated || !remaining ? scanned : 0;
4675}
4676
4677static int get_tier_idx(struct lruvec *lruvec, int type)
4678{
4679 int tier;
4680 struct ctrl_pos sp, pv;
4681
4682 /*
4683 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4684 * This value is chosen because any other tier would have at least twice
4685 * as many refaults as the first tier.
4686 */
4687 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4688 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4689 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4690 if (!positive_ctrl_err(&sp, &pv))
4691 break;
4692 }
4693
4694 return tier - 1;
4695}
4696
4697static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4698{
4699 int type, tier;
4700 struct ctrl_pos sp, pv;
4701 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4702
4703 /*
4704 * Compare the first tier of anon with that of file to determine which
4705 * type to scan. Also need to compare other tiers of the selected type
4706 * with the first tier of the other type to determine the last tier (of
4707 * the selected type) to evict.
4708 */
4709 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4710 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4711 type = positive_ctrl_err(&sp, &pv);
4712
4713 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4714 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4715 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4716 if (!positive_ctrl_err(&sp, &pv))
4717 break;
4718 }
4719
4720 *tier_idx = tier - 1;
4721
4722 return type;
4723}
4724
4725static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4726 int *type_scanned, struct list_head *list)
4727{
4728 int i;
4729 int type;
4730 int scanned;
4731 int tier = -1;
4732 DEFINE_MIN_SEQ(lruvec);
4733
4734 /*
4735 * Try to make the obvious choice first. When anon and file are both
4736 * available from the same generation, interpret swappiness 1 as file
4737 * first and 200 as anon first.
4738 */
4739 if (!swappiness)
4740 type = LRU_GEN_FILE;
4741 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4742 type = LRU_GEN_ANON;
4743 else if (swappiness == 1)
4744 type = LRU_GEN_FILE;
4745 else if (swappiness == 200)
4746 type = LRU_GEN_ANON;
4747 else
4748 type = get_type_to_scan(lruvec, swappiness, &tier);
4749
4750 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4751 if (tier < 0)
4752 tier = get_tier_idx(lruvec, type);
4753
4754 scanned = scan_pages(lruvec, sc, type, tier, list);
4755 if (scanned)
4756 break;
4757
4758 type = !type;
4759 tier = -1;
4760 }
4761
4762 *type_scanned = type;
4763
4764 return scanned;
4765}
4766
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004767static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4768 bool *need_swapping)
Yu Zhao37397872022-09-18 02:00:03 -06004769{
4770 int type;
4771 int scanned;
4772 int reclaimed;
4773 LIST_HEAD(list);
4774 struct page *page;
4775 enum vm_event_item item;
4776 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004777 struct lru_gen_mm_walk *walk;
Yu Zhao37397872022-09-18 02:00:03 -06004778 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4779 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4780
4781 spin_lock_irq(&lruvec->lru_lock);
4782
4783 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4784
4785 scanned += try_to_inc_min_seq(lruvec, swappiness);
4786
4787 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4788 scanned = 0;
4789
4790 spin_unlock_irq(&lruvec->lru_lock);
4791
4792 if (list_empty(&list))
4793 return scanned;
4794
4795 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4796
4797 list_for_each_entry(page, &list, lru) {
4798 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4799 if (PageWorkingset(page))
4800 SetPageReferenced(page);
4801
4802 /* don't add rejected pages to the oldest generation */
4803 if (PageReclaim(page) &&
4804 (PageDirty(page) || PageWriteback(page)))
4805 ClearPageActive(page);
4806 else
4807 SetPageActive(page);
4808 }
4809
4810 spin_lock_irq(&lruvec->lru_lock);
4811
4812 move_pages_to_lru(lruvec, &list);
4813
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004814 walk = current->reclaim_state->mm_walk;
4815 if (walk && walk->batched)
4816 reset_batch_size(lruvec, walk);
4817
Yu Zhao37397872022-09-18 02:00:03 -06004818 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4819 if (!cgroup_reclaim(sc))
4820 __count_vm_events(item, reclaimed);
4821 __count_memcg_events(memcg, item, reclaimed);
4822 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4823
4824 spin_unlock_irq(&lruvec->lru_lock);
4825
4826 mem_cgroup_uncharge_list(&list);
4827 free_unref_page_list(&list);
4828
4829 sc->nr_reclaimed += reclaimed;
4830
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004831 if (need_swapping && type == LRU_GEN_ANON)
4832 *need_swapping = true;
4833
Yu Zhao37397872022-09-18 02:00:03 -06004834 return scanned;
4835}
4836
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004837/*
4838 * For future optimizations:
4839 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4840 * reclaim.
4841 */
Yu Zhao37397872022-09-18 02:00:03 -06004842static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004843 bool can_swap, bool *need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004844{
Yu Zhao37397872022-09-18 02:00:03 -06004845 unsigned long nr_to_scan;
4846 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4847 DEFINE_MAX_SEQ(lruvec);
4848 DEFINE_MIN_SEQ(lruvec);
4849
4850 if (mem_cgroup_below_min(memcg) ||
4851 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4852 return 0;
4853
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004854 *need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
4855 if (!*need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004856 return nr_to_scan;
4857
4858 /* skip the aging path at the default priority */
4859 if (sc->priority == DEF_PRIORITY)
4860 goto done;
4861
4862 /* leave the work to lru_gen_age_node() */
4863 if (current_is_kswapd())
4864 return 0;
4865
Yu Zhao4983c522022-09-18 02:00:09 -06004866 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004867 return nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004868done:
4869 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
4870}
4871
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004872static bool should_abort_scan(struct lruvec *lruvec, unsigned long seq,
4873 struct scan_control *sc, bool need_swapping)
4874{
4875 int i;
4876 DEFINE_MAX_SEQ(lruvec);
4877
4878 if (!current_is_kswapd()) {
4879 /* age each memcg at most once to ensure fairness */
4880 if (max_seq - seq > 1)
4881 return true;
4882
4883 /* over-swapping can increase allocation latency */
4884 if (sc->nr_reclaimed >= sc->nr_to_reclaim && need_swapping)
4885 return true;
4886
4887 /* give this thread a chance to exit and free its memory */
4888 if (fatal_signal_pending(current)) {
4889 sc->nr_reclaimed += MIN_LRU_BATCH;
4890 return true;
4891 }
4892
4893 if (cgroup_reclaim(sc))
4894 return false;
4895 } else if (sc->nr_reclaimed - sc->last_reclaimed < sc->nr_to_reclaim)
4896 return false;
4897
4898 /* keep scanning at low priorities to ensure fairness */
4899 if (sc->priority > DEF_PRIORITY - 2)
4900 return false;
4901
4902 /*
4903 * A minimum amount of work was done under global memory pressure. For
4904 * kswapd, it may be overshooting. For direct reclaim, the allocation
4905 * may succeed if all suitable zones are somewhat safe. In either case,
4906 * it's better to stop now, and restart later if necessary.
4907 */
4908 for (i = 0; i <= sc->reclaim_idx; i++) {
4909 unsigned long wmark;
4910 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
4911
4912 if (!managed_zone(zone))
4913 continue;
4914
4915 wmark = current_is_kswapd() ? high_wmark_pages(zone) : low_wmark_pages(zone);
4916 if (wmark > zone_page_state(zone, NR_FREE_PAGES))
4917 return false;
4918 }
4919
4920 sc->nr_reclaimed += MIN_LRU_BATCH;
4921
4922 return true;
4923}
4924
Yu Zhao37397872022-09-18 02:00:03 -06004925static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4926{
4927 struct blk_plug plug;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004928 bool need_aging = false;
4929 bool need_swapping = false;
Yu Zhao37397872022-09-18 02:00:03 -06004930 unsigned long scanned = 0;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004931 unsigned long reclaimed = sc->nr_reclaimed;
4932 DEFINE_MAX_SEQ(lruvec);
Yu Zhao37397872022-09-18 02:00:03 -06004933
4934 lru_add_drain();
4935
4936 blk_start_plug(&plug);
4937
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004938 set_mm_walk(lruvec_pgdat(lruvec));
4939
Yu Zhao37397872022-09-18 02:00:03 -06004940 while (true) {
4941 int delta;
4942 int swappiness;
4943 unsigned long nr_to_scan;
4944
4945 if (sc->may_swap)
4946 swappiness = get_swappiness(lruvec, sc);
4947 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4948 swappiness = 1;
4949 else
4950 swappiness = 0;
4951
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004952 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, &need_aging);
Yu Zhao37397872022-09-18 02:00:03 -06004953 if (!nr_to_scan)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004954 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004955
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004956 delta = evict_pages(lruvec, sc, swappiness, &need_swapping);
Yu Zhao37397872022-09-18 02:00:03 -06004957 if (!delta)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004958 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004959
4960 scanned += delta;
4961 if (scanned >= nr_to_scan)
4962 break;
4963
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004964 if (should_abort_scan(lruvec, max_seq, sc, need_swapping))
4965 break;
4966
Yu Zhao37397872022-09-18 02:00:03 -06004967 cond_resched();
4968 }
4969
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004970 /* see the comment in lru_gen_age_node() */
4971 if (sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH && !need_aging)
4972 sc->memcgs_need_aging = false;
4973done:
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004974 clear_mm_walk();
4975
Yu Zhao37397872022-09-18 02:00:03 -06004976 blk_finish_plug(&plug);
4977}
4978
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004979/******************************************************************************
Yu Zhaobaeb9a02022-09-18 02:00:07 -06004980 * state change
4981 ******************************************************************************/
4982
4983static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
4984{
4985 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4986
4987 if (lrugen->enabled) {
4988 enum lru_list lru;
4989
4990 for_each_evictable_lru(lru) {
4991 if (!list_empty(&lruvec->lists[lru]))
4992 return false;
4993 }
4994 } else {
4995 int gen, type, zone;
4996
4997 for_each_gen_type_zone(gen, type, zone) {
4998 if (!list_empty(&lrugen->lists[gen][type][zone]))
4999 return false;
5000 }
5001 }
5002
5003 return true;
5004}
5005
5006static bool fill_evictable(struct lruvec *lruvec)
5007{
5008 enum lru_list lru;
5009 int remaining = MAX_LRU_BATCH;
5010
5011 for_each_evictable_lru(lru) {
5012 int type = is_file_lru(lru);
5013 bool active = is_active_lru(lru);
5014 struct list_head *head = &lruvec->lists[lru];
5015
5016 while (!list_empty(head)) {
5017 bool success;
5018 struct page *page = lru_to_page(head);
5019
5020 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5021 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
5022 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5023 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
5024
5025 del_page_from_lru_list(page, lruvec);
5026 success = lru_gen_add_page(lruvec, page, false);
5027 VM_WARN_ON_ONCE(!success);
5028
5029 if (!--remaining)
5030 return false;
5031 }
5032 }
5033
5034 return true;
5035}
5036
5037static bool drain_evictable(struct lruvec *lruvec)
5038{
5039 int gen, type, zone;
5040 int remaining = MAX_LRU_BATCH;
5041
5042 for_each_gen_type_zone(gen, type, zone) {
5043 struct list_head *head = &lruvec->lrugen.lists[gen][type][zone];
5044
5045 while (!list_empty(head)) {
5046 bool success;
5047 struct page *page = lru_to_page(head);
5048
5049 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5050 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5051 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5052 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5053
5054 success = lru_gen_del_page(lruvec, page, false);
5055 VM_WARN_ON_ONCE(!success);
5056 add_page_to_lru_list(page, lruvec);
5057
5058 if (!--remaining)
5059 return false;
5060 }
5061 }
5062
5063 return true;
5064}
5065
5066static void lru_gen_change_state(bool enabled)
5067{
5068 static DEFINE_MUTEX(state_mutex);
5069
5070 struct mem_cgroup *memcg;
5071
5072 cgroup_lock();
5073 cpus_read_lock();
5074 get_online_mems();
5075 mutex_lock(&state_mutex);
5076
5077 if (enabled == lru_gen_enabled())
5078 goto unlock;
5079
5080 if (enabled)
5081 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5082 else
5083 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5084
5085 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5086 do {
5087 int nid;
5088
5089 for_each_node(nid) {
5090 struct lruvec *lruvec = get_lruvec(memcg, nid);
5091
5092 if (!lruvec)
5093 continue;
5094
5095 spin_lock_irq(&lruvec->lru_lock);
5096
5097 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5098 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5099
5100 lruvec->lrugen.enabled = enabled;
5101
5102 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5103 spin_unlock_irq(&lruvec->lru_lock);
5104 cond_resched();
5105 spin_lock_irq(&lruvec->lru_lock);
5106 }
5107
5108 spin_unlock_irq(&lruvec->lru_lock);
5109 }
5110
5111 cond_resched();
5112 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5113unlock:
5114 mutex_unlock(&state_mutex);
5115 put_online_mems();
5116 cpus_read_unlock();
5117 cgroup_unlock();
5118}
5119
5120/******************************************************************************
5121 * sysfs interface
5122 ******************************************************************************/
5123
Yu Zhao430499c2022-09-18 02:00:08 -06005124static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5125{
5126 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5127}
5128
Yu Zhao642d9862022-09-18 02:00:10 -06005129/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao430499c2022-09-18 02:00:08 -06005130static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5131 const char *buf, size_t len)
5132{
5133 unsigned int msecs;
5134
5135 if (kstrtouint(buf, 0, &msecs))
5136 return -EINVAL;
5137
5138 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5139
5140 return len;
5141}
5142
5143static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5144 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5145);
5146
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005147static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5148{
5149 unsigned int caps = 0;
5150
5151 if (get_cap(LRU_GEN_CORE))
5152 caps |= BIT(LRU_GEN_CORE);
5153
5154 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5155 caps |= BIT(LRU_GEN_MM_WALK);
5156
5157 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
5158 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5159
5160 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5161}
5162
Yu Zhao642d9862022-09-18 02:00:10 -06005163/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005164static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5165 const char *buf, size_t len)
5166{
5167 int i;
5168 unsigned int caps;
5169
5170 if (tolower(*buf) == 'n')
5171 caps = 0;
5172 else if (tolower(*buf) == 'y')
5173 caps = -1;
5174 else if (kstrtouint(buf, 0, &caps))
5175 return -EINVAL;
5176
5177 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5178 bool enabled = caps & BIT(i);
5179
5180 if (i == LRU_GEN_CORE)
5181 lru_gen_change_state(enabled);
5182 else if (enabled)
5183 static_branch_enable(&lru_gen_caps[i]);
5184 else
5185 static_branch_disable(&lru_gen_caps[i]);
5186 }
5187
5188 return len;
5189}
5190
5191static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5192 enabled, 0644, show_enabled, store_enabled
5193);
5194
5195static struct attribute *lru_gen_attrs[] = {
Yu Zhao430499c2022-09-18 02:00:08 -06005196 &lru_gen_min_ttl_attr.attr,
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005197 &lru_gen_enabled_attr.attr,
5198 NULL
5199};
5200
5201static struct attribute_group lru_gen_attr_group = {
5202 .name = "lru_gen",
5203 .attrs = lru_gen_attrs,
5204};
5205
5206/******************************************************************************
Yu Zhao4983c522022-09-18 02:00:09 -06005207 * debugfs interface
5208 ******************************************************************************/
5209
5210static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5211{
5212 struct mem_cgroup *memcg;
5213 loff_t nr_to_skip = *pos;
5214
5215 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5216 if (!m->private)
5217 return ERR_PTR(-ENOMEM);
5218
5219 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5220 do {
5221 int nid;
5222
5223 for_each_node_state(nid, N_MEMORY) {
5224 if (!nr_to_skip--)
5225 return get_lruvec(memcg, nid);
5226 }
5227 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5228
5229 return NULL;
5230}
5231
5232static void lru_gen_seq_stop(struct seq_file *m, void *v)
5233{
5234 if (!IS_ERR_OR_NULL(v))
5235 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5236
5237 kvfree(m->private);
5238 m->private = NULL;
5239}
5240
5241static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5242{
5243 int nid = lruvec_pgdat(v)->node_id;
5244 struct mem_cgroup *memcg = lruvec_memcg(v);
5245
5246 ++*pos;
5247
5248 nid = next_memory_node(nid);
5249 if (nid == MAX_NUMNODES) {
5250 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5251 if (!memcg)
5252 return NULL;
5253
5254 nid = first_memory_node;
5255 }
5256
5257 return get_lruvec(memcg, nid);
5258}
5259
5260static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5261 unsigned long max_seq, unsigned long *min_seq,
5262 unsigned long seq)
5263{
5264 int i;
5265 int type, tier;
5266 int hist = lru_hist_from_seq(seq);
5267 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5268
5269 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5270 seq_printf(m, " %10d", tier);
5271 for (type = 0; type < ANON_AND_FILE; type++) {
5272 const char *s = " ";
5273 unsigned long n[3] = {};
5274
5275 if (seq == max_seq) {
5276 s = "RT ";
5277 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5278 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5279 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5280 s = "rep";
5281 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5282 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5283 if (tier)
5284 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5285 }
5286
5287 for (i = 0; i < 3; i++)
5288 seq_printf(m, " %10lu%c", n[i], s[i]);
5289 }
5290 seq_putc(m, '\n');
5291 }
5292
5293 seq_puts(m, " ");
5294 for (i = 0; i < NR_MM_STATS; i++) {
5295 const char *s = " ";
5296 unsigned long n = 0;
5297
5298 if (seq == max_seq && NR_HIST_GENS == 1) {
5299 s = "LOYNFA";
5300 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5301 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5302 s = "loynfa";
5303 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5304 }
5305
5306 seq_printf(m, " %10lu%c", n, s[i]);
5307 }
5308 seq_putc(m, '\n');
5309}
5310
Yu Zhao642d9862022-09-18 02:00:10 -06005311/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005312static int lru_gen_seq_show(struct seq_file *m, void *v)
5313{
5314 unsigned long seq;
5315 bool full = !debugfs_real_fops(m->file)->write;
5316 struct lruvec *lruvec = v;
5317 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5318 int nid = lruvec_pgdat(lruvec)->node_id;
5319 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5320 DEFINE_MAX_SEQ(lruvec);
5321 DEFINE_MIN_SEQ(lruvec);
5322
5323 if (nid == first_memory_node) {
5324 const char *path = memcg ? m->private : "";
5325
5326#ifdef CONFIG_MEMCG
5327 if (memcg)
5328 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5329#endif
5330 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5331 }
5332
5333 seq_printf(m, " node %5d\n", nid);
5334
5335 if (!full)
5336 seq = min_seq[LRU_GEN_ANON];
5337 else if (max_seq >= MAX_NR_GENS)
5338 seq = max_seq - MAX_NR_GENS + 1;
5339 else
5340 seq = 0;
5341
5342 for (; seq <= max_seq; seq++) {
5343 int type, zone;
5344 int gen = lru_gen_from_seq(seq);
5345 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5346
5347 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5348
5349 for (type = 0; type < ANON_AND_FILE; type++) {
5350 unsigned long size = 0;
5351 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5352
5353 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5354 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5355
5356 seq_printf(m, " %10lu%c", size, mark);
5357 }
5358
5359 seq_putc(m, '\n');
5360
5361 if (full)
5362 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5363 }
5364
5365 return 0;
5366}
5367
5368static const struct seq_operations lru_gen_seq_ops = {
5369 .start = lru_gen_seq_start,
5370 .stop = lru_gen_seq_stop,
5371 .next = lru_gen_seq_next,
5372 .show = lru_gen_seq_show,
5373};
5374
5375static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5376 bool can_swap, bool force_scan)
5377{
5378 DEFINE_MAX_SEQ(lruvec);
5379 DEFINE_MIN_SEQ(lruvec);
5380
5381 if (seq < max_seq)
5382 return 0;
5383
5384 if (seq > max_seq)
5385 return -EINVAL;
5386
5387 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5388 return -ERANGE;
5389
5390 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5391
5392 return 0;
5393}
5394
5395static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5396 int swappiness, unsigned long nr_to_reclaim)
5397{
5398 DEFINE_MAX_SEQ(lruvec);
5399
5400 if (seq + MIN_NR_GENS > max_seq)
5401 return -EINVAL;
5402
5403 sc->nr_reclaimed = 0;
5404
5405 while (!signal_pending(current)) {
5406 DEFINE_MIN_SEQ(lruvec);
5407
5408 if (seq < min_seq[!swappiness])
5409 return 0;
5410
5411 if (sc->nr_reclaimed >= nr_to_reclaim)
5412 return 0;
5413
5414 if (!evict_pages(lruvec, sc, swappiness, NULL))
5415 return 0;
5416
5417 cond_resched();
5418 }
5419
5420 return -EINTR;
5421}
5422
5423static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5424 struct scan_control *sc, int swappiness, unsigned long opt)
5425{
5426 struct lruvec *lruvec;
5427 int err = -EINVAL;
5428 struct mem_cgroup *memcg = NULL;
5429
5430 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5431 return -EINVAL;
5432
5433 if (!mem_cgroup_disabled()) {
5434 rcu_read_lock();
5435 memcg = mem_cgroup_from_id(memcg_id);
5436#ifdef CONFIG_MEMCG
5437 if (memcg && !css_tryget(&memcg->css))
5438 memcg = NULL;
5439#endif
5440 rcu_read_unlock();
5441
5442 if (!memcg)
5443 return -EINVAL;
5444 }
5445
5446 if (memcg_id != mem_cgroup_id(memcg))
5447 goto done;
5448
5449 lruvec = get_lruvec(memcg, nid);
5450
5451 if (swappiness < 0)
5452 swappiness = get_swappiness(lruvec, sc);
5453 else if (swappiness > 200)
5454 goto done;
5455
5456 switch (cmd) {
5457 case '+':
5458 err = run_aging(lruvec, seq, sc, swappiness, opt);
5459 break;
5460 case '-':
5461 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5462 break;
5463 }
5464done:
5465 mem_cgroup_put(memcg);
5466
5467 return err;
5468}
5469
Yu Zhao642d9862022-09-18 02:00:10 -06005470/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005471static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5472 size_t len, loff_t *pos)
5473{
5474 void *buf;
5475 char *cur, *next;
5476 unsigned int flags;
5477 struct blk_plug plug;
5478 int err = -EINVAL;
5479 struct scan_control sc = {
5480 .may_writepage = true,
5481 .may_unmap = true,
5482 .may_swap = true,
5483 .reclaim_idx = MAX_NR_ZONES - 1,
5484 .gfp_mask = GFP_KERNEL,
5485 };
5486
5487 buf = kvmalloc(len + 1, GFP_KERNEL);
5488 if (!buf)
5489 return -ENOMEM;
5490
5491 if (copy_from_user(buf, src, len)) {
5492 kvfree(buf);
5493 return -EFAULT;
5494 }
5495
5496 set_task_reclaim_state(current, &sc.reclaim_state);
5497 flags = memalloc_noreclaim_save();
5498 blk_start_plug(&plug);
5499 if (!set_mm_walk(NULL)) {
5500 err = -ENOMEM;
5501 goto done;
5502 }
5503
5504 next = buf;
5505 next[len] = '\0';
5506
5507 while ((cur = strsep(&next, ",;\n"))) {
5508 int n;
5509 int end;
5510 char cmd;
5511 unsigned int memcg_id;
5512 unsigned int nid;
5513 unsigned long seq;
5514 unsigned int swappiness = -1;
5515 unsigned long opt = -1;
5516
5517 cur = skip_spaces(cur);
5518 if (!*cur)
5519 continue;
5520
5521 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5522 &seq, &end, &swappiness, &end, &opt, &end);
5523 if (n < 4 || cur[end]) {
5524 err = -EINVAL;
5525 break;
5526 }
5527
5528 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5529 if (err)
5530 break;
5531 }
5532done:
5533 clear_mm_walk();
5534 blk_finish_plug(&plug);
5535 memalloc_noreclaim_restore(flags);
5536 set_task_reclaim_state(current, NULL);
5537
5538 kvfree(buf);
5539
5540 return err ? : len;
5541}
5542
5543static int lru_gen_seq_open(struct inode *inode, struct file *file)
5544{
5545 return seq_open(file, &lru_gen_seq_ops);
5546}
5547
5548static const struct file_operations lru_gen_rw_fops = {
5549 .open = lru_gen_seq_open,
5550 .read = seq_read,
5551 .write = lru_gen_seq_write,
5552 .llseek = seq_lseek,
5553 .release = seq_release,
5554};
5555
5556static const struct file_operations lru_gen_ro_fops = {
5557 .open = lru_gen_seq_open,
5558 .read = seq_read,
5559 .llseek = seq_lseek,
5560 .release = seq_release,
5561};
5562
5563/******************************************************************************
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005564 * initialization
5565 ******************************************************************************/
5566
5567void lru_gen_init_lruvec(struct lruvec *lruvec)
5568{
Yu Zhao430499c2022-09-18 02:00:08 -06005569 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005570 int gen, type, zone;
5571 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5572
5573 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005574 lrugen->enabled = lru_gen_enabled();
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005575
Yu Zhao430499c2022-09-18 02:00:08 -06005576 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5577 lrugen->timestamps[i] = jiffies;
5578
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005579 for_each_gen_type_zone(gen, type, zone)
5580 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005581
5582 lruvec->mm_state.seq = MIN_NR_GENS;
5583 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005584}
5585
5586#ifdef CONFIG_MEMCG
5587void lru_gen_init_memcg(struct mem_cgroup *memcg)
5588{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005589 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5590 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005591}
5592
5593void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5594{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005595 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005596 int nid;
5597
5598 for_each_node(nid) {
5599 struct lruvec *lruvec = get_lruvec(memcg, nid);
5600
5601 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5602 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005603
5604 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5605 bitmap_free(lruvec->mm_state.filters[i]);
5606 lruvec->mm_state.filters[i] = NULL;
5607 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005608 }
5609}
5610#endif
5611
5612static int __init init_lru_gen(void)
5613{
5614 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5615 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5616
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005617 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5618 pr_err("lru_gen: failed to create sysfs group\n");
5619
Yu Zhao4983c522022-09-18 02:00:09 -06005620 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5621 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5622
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005623 return 0;
5624};
5625late_initcall(init_lru_gen);
5626
Yu Zhao37397872022-09-18 02:00:03 -06005627#else /* !CONFIG_LRU_GEN */
5628
5629static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5630{
5631}
5632
5633static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5634{
5635}
5636
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005637#endif /* CONFIG_LRU_GEN */
5638
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005639static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005640{
5641 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005642 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005643 unsigned long nr_to_scan;
5644 enum lru_list lru;
5645 unsigned long nr_reclaimed = 0;
5646 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005647 bool proportional_reclaim;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005648 struct blk_plug plug;
Minchan Kima8962f62022-11-02 09:04:41 -07005649 bool do_plug = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005650
Yu Zhao37397872022-09-18 02:00:03 -06005651 if (lru_gen_enabled()) {
5652 lru_gen_shrink_lruvec(lruvec, sc);
5653 return;
5654 }
5655
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005656 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005657
Mel Gormane82e0562013-07-03 15:01:44 -07005658 /* Record the original scan target for proportional adjustments later */
5659 memcpy(targets, nr, sizeof(nr));
5660
Mel Gorman1a501902014-06-04 16:10:49 -07005661 /*
5662 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5663 * event that can occur when there is little memory pressure e.g.
5664 * multiple streaming readers/writers. Hence, we do not abort scanning
5665 * when the requested number of pages are reclaimed when scanning at
5666 * DEF_PRIORITY on the assumption that the fact we are direct
5667 * reclaiming implies that kswapd is not keeping up and it is best to
5668 * do a batch of work at once. For memcg reclaim one check is made to
5669 * abort proportional reclaim if either the file or anon lru has already
5670 * dropped to zero at the first pass.
5671 */
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005672 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5673 sc->priority == DEF_PRIORITY);
Mel Gorman1a501902014-06-04 16:10:49 -07005674
Minchan Kima8962f62022-11-02 09:04:41 -07005675 trace_android_vh_shrink_lruvec_blk_plug(&do_plug);
5676 if (do_plug)
5677 blk_start_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005678 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5679 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005680 unsigned long nr_anon, nr_file, percentage;
5681 unsigned long nr_scanned;
5682
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005683 for_each_evictable_lru(lru) {
5684 if (nr[lru]) {
5685 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5686 nr[lru] -= nr_to_scan;
5687
5688 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005689 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005690 }
5691 }
Mel Gormane82e0562013-07-03 15:01:44 -07005692
Michal Hockobd041732016-12-02 17:26:48 -08005693 cond_resched();
5694
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005695 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
Mel Gormane82e0562013-07-03 15:01:44 -07005696 continue;
5697
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005698 /*
Mel Gormane82e0562013-07-03 15:01:44 -07005699 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07005700 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07005701 * proportionally what was requested by get_scan_count(). We
5702 * stop reclaiming one LRU and reduce the amount scanning
5703 * proportional to the original scan target.
5704 */
5705 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5706 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5707
Mel Gorman1a501902014-06-04 16:10:49 -07005708 /*
5709 * It's just vindictive to attack the larger once the smaller
5710 * has gone to zero. And given the way we stop scanning the
5711 * smaller below, this makes sure that we only make one nudge
5712 * towards proportionality once we've got nr_to_reclaim.
5713 */
5714 if (!nr_file || !nr_anon)
5715 break;
5716
Mel Gormane82e0562013-07-03 15:01:44 -07005717 if (nr_file > nr_anon) {
5718 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5719 targets[LRU_ACTIVE_ANON] + 1;
5720 lru = LRU_BASE;
5721 percentage = nr_anon * 100 / scan_target;
5722 } else {
5723 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5724 targets[LRU_ACTIVE_FILE] + 1;
5725 lru = LRU_FILE;
5726 percentage = nr_file * 100 / scan_target;
5727 }
5728
5729 /* Stop scanning the smaller of the LRU */
5730 nr[lru] = 0;
5731 nr[lru + LRU_ACTIVE] = 0;
5732
5733 /*
5734 * Recalculate the other LRU scan count based on its original
5735 * scan target and the percentage scanning already complete
5736 */
5737 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5738 nr_scanned = targets[lru] - nr[lru];
5739 nr[lru] = targets[lru] * (100 - percentage) / 100;
5740 nr[lru] -= min(nr[lru], nr_scanned);
5741
5742 lru += LRU_ACTIVE;
5743 nr_scanned = targets[lru] - nr[lru];
5744 nr[lru] = targets[lru] * (100 - percentage) / 100;
5745 nr[lru] -= min(nr[lru], nr_scanned);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005746 }
Minchan Kima8962f62022-11-02 09:04:41 -07005747 if (do_plug)
5748 blk_finish_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005749 sc->nr_reclaimed += nr_reclaimed;
5750
5751 /*
5752 * Even if we did not try to evict anon pages at all, we want to
5753 * rebalance the anon lru active/inactive ratio.
5754 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005755 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5756 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005757 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5758 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005759}
5760
Mel Gorman23b9da52012-05-29 15:06:20 -07005761/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005762static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005763{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005764 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005765 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005766 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005767 return true;
5768
5769 return false;
5770}
5771
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005772/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005773 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5774 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5775 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005776 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005777 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005778 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005779static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005780 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005781 struct scan_control *sc)
5782{
5783 unsigned long pages_for_compaction;
5784 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005785 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005786
5787 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005788 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005789 return false;
5790
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005791 /*
5792 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5793 * number of pages that were scanned. This will return to the caller
5794 * with the risk reclaim/compaction and the resulting allocation attempt
5795 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5796 * allocations through requiring that the full LRU list has been scanned
5797 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5798 * scan, but that approximation was wrong, and there were corner cases
5799 * where always a non-zero amount of pages were scanned.
5800 */
5801 if (!nr_reclaimed)
5802 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005803
Mel Gorman3e7d3442011-01-13 15:45:56 -08005804 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005805 for (z = 0; z <= sc->reclaim_idx; z++) {
5806 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005807 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005808 continue;
5809
5810 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005811 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005812 case COMPACT_CONTINUE:
5813 return false;
5814 default:
5815 /* check next zone */
5816 ;
5817 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005818 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005819
5820 /*
5821 * If we have not reclaimed enough pages for compaction and the
5822 * inactive lists are large enough, continue reclaiming
5823 */
5824 pages_for_compaction = compact_gap(sc->order);
5825 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005826 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005827 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5828
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005829 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005830}
5831
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005832static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005833{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005834 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005835 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005836
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005837 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005838 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005839 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005840 unsigned long reclaimed;
5841 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005842 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08005843
Xunlei Pange3336ca2020-09-04 16:35:27 -07005844 /*
5845 * This loop can become CPU-bound when target memcgs
5846 * aren't eligible for reclaim - either because they
5847 * don't have any reclaimable pages, or because their
5848 * memory is explicitly protected. Avoid soft lockups.
5849 */
5850 cond_resched();
5851
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005852 trace_android_vh_shrink_node_memcgs(memcg, &skip);
5853 if (skip)
5854 continue;
5855
Chris Down45c7f7e2020-08-06 23:22:05 -07005856 mem_cgroup_calculate_protection(target_memcg, memcg);
5857
5858 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005859 /*
5860 * Hard protection.
5861 * If there is no reclaimable memory, OOM.
5862 */
5863 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005864 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005865 /*
5866 * Soft protection.
5867 * Respect the protection only as long as
5868 * there is an unprotected supply
5869 * of reclaimable memory from other cgroups.
5870 */
5871 if (!sc->memcg_low_reclaim) {
5872 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005873 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005874 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005875 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005876 }
5877
Johannes Weinerd2af3392019-11-30 17:55:43 -08005878 reclaimed = sc->nr_reclaimed;
5879 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005880
5881 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005882
Johannes Weinerd2af3392019-11-30 17:55:43 -08005883 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5884 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005885
Johannes Weinerd2af3392019-11-30 17:55:43 -08005886 /* Record the group's reclaim efficiency */
5887 vmpressure(sc->gfp_mask, memcg, false,
5888 sc->nr_scanned - scanned,
5889 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005890
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005891 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5892}
5893
Liu Song6c9e09072020-01-30 22:14:08 -08005894static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005895{
5896 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005897 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005898 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005899 bool reclaimable = false;
5900
Johannes Weiner1b051172019-11-30 17:55:52 -08005901 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5902
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005903again:
5904 memset(&sc->nr, 0, sizeof(sc->nr));
5905
5906 nr_reclaimed = sc->nr_reclaimed;
5907 nr_scanned = sc->nr_scanned;
5908
Yu Zhao6d313442022-09-18 02:00:00 -06005909 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005910
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005911 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005912
Johannes Weinerd2af3392019-11-30 17:55:43 -08005913 if (reclaim_state) {
5914 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5915 reclaim_state->reclaimed_slab = 0;
5916 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005917
Johannes Weinerd2af3392019-11-30 17:55:43 -08005918 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005919 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005920 sc->nr_scanned - nr_scanned,
5921 sc->nr_reclaimed - nr_reclaimed);
5922
5923 if (sc->nr_reclaimed - nr_reclaimed)
5924 reclaimable = true;
5925
5926 if (current_is_kswapd()) {
5927 /*
5928 * If reclaim is isolating dirty pages under writeback,
5929 * it implies that the long-lived page allocation rate
5930 * is exceeding the page laundering rate. Either the
5931 * global limits are not being effective at throttling
5932 * processes due to the page distribution throughout
5933 * zones or there is heavy usage of a slow backing
5934 * device. The only option is to throttle from reclaim
5935 * context which is not ideal as there is no guarantee
5936 * the dirtying process is throttled in the same way
5937 * balance_dirty_pages() manages.
5938 *
5939 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5940 * count the number of pages under pages flagged for
5941 * immediate reclaim and stall if any are encountered
5942 * in the nr_immediate check below.
5943 */
5944 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5945 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005946
Johannes Weinerd2af3392019-11-30 17:55:43 -08005947 /* Allow kswapd to start writing pages during reclaim.*/
5948 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5949 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005950
5951 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005952 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005953 * reclaim and under writeback (nr_immediate), it
5954 * implies that pages are cycling through the LRU
5955 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005956 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005957 if (sc->nr.immediate)
5958 congestion_wait(BLK_RW_ASYNC, HZ/10);
5959 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005960
Johannes Weinerd2af3392019-11-30 17:55:43 -08005961 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005962 * Tag a node/memcg as congested if all the dirty pages
5963 * scanned were backed by a congested BDI and
5964 * wait_iff_congested will stall.
5965 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005966 * Legacy memcg will stall in page writeback so avoid forcibly
5967 * stalling in wait_iff_congested().
5968 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005969 if ((current_is_kswapd() ||
5970 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005971 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005972 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005973
5974 /*
5975 * Stall direct reclaim for IO completions if underlying BDIs
5976 * and node is congested. Allow kswapd to continue until it
5977 * starts encountering unqueued dirty pages or cycling through
5978 * the LRU too quickly.
5979 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005980 if (!current_is_kswapd() && current_may_throttle() &&
5981 !sc->hibernation_mode &&
5982 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005983 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5984
5985 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5986 sc))
5987 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005988
Johannes Weinerc73322d2017-05-03 14:51:51 -07005989 /*
5990 * Kswapd gives up on balancing particular nodes after too
5991 * many failures to reclaim anything from them and goes to
5992 * sleep. On reclaim progress, reset the failure counter. A
5993 * successful direct reclaim run will revive a dormant kswapd.
5994 */
5995 if (reclaimable)
5996 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005997}
5998
Vlastimil Babka53853e22014-10-09 15:27:02 -07005999/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006000 * Returns true if compaction should go ahead for a costly-order request, or
6001 * the allocation would already succeed without compaction. Return false if we
6002 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07006003 */
Mel Gorman4f588332016-07-28 15:46:38 -07006004static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006005{
Mel Gorman31483b62016-07-28 15:45:46 -07006006 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006007 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006008
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006009 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6010 if (suitable == COMPACT_SUCCESS)
6011 /* Allocation should succeed already. Don't reclaim. */
6012 return true;
6013 if (suitable == COMPACT_SKIPPED)
6014 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006015 return false;
6016
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006017 /*
6018 * Compaction is already possible, but it takes time to run and there
6019 * are potentially other callers using the pages just freed. So proceed
6020 * with reclaim to make a buffer of free pages available to give
6021 * compaction a reasonable chance of completing and allocating the page.
6022 * Note that we won't actually reclaim the whole buffer in one attempt
6023 * as the target watermark in should_continue_reclaim() is lower. But if
6024 * we are already above the high+gap watermark, don't reclaim at all.
6025 */
6026 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6027
6028 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006029}
6030
Linus Torvalds1da177e2005-04-16 15:20:36 -07006031/*
6032 * This is the direct reclaim path, for page-allocating processes. We only
6033 * try to reclaim pages from zones which will satisfy the caller's allocation
6034 * request.
6035 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07006036 * If a zone is deemed to be full of pinned pages then just give it a light
6037 * scan then give up on it.
6038 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07006039static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006040{
Mel Gormandd1a2392008-04-28 02:12:17 -07006041 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07006042 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07006043 unsigned long nr_soft_reclaimed;
6044 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07006045 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07006046 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006047
Mel Gormancc715d92012-03-21 16:34:00 -07006048 /*
6049 * If the number of buffer_heads in the machine exceeds the maximum
6050 * allowed level, force direct reclaim to scan the highmem zone as
6051 * highmem pages could be pinning lowmem pages storing buffer_heads
6052 */
Weijie Yang619d0d762014-04-07 15:36:59 -07006053 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07006054 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07006055 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07006056 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07006057 }
Mel Gormancc715d92012-03-21 16:34:00 -07006058
Mel Gormand4debc62010-08-09 17:19:29 -07006059 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07006060 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07006061 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006062 * Take care memory controller reclaiming has small influence
6063 * to global LRU.
6064 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08006065 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04006066 if (!cpuset_zone_allowed(zone,
6067 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006068 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006069
Johannes Weiner0b064962014-08-06 16:06:12 -07006070 /*
6071 * If we already have plenty of memory free for
6072 * compaction in this zone, don't free any more.
6073 * Even though compaction is invoked for any
6074 * non-zero order, only frequent costly order
6075 * reclamation is disruptive enough to become a
6076 * noticeable problem, like transparent huge
6077 * page allocations.
6078 */
6079 if (IS_ENABLED(CONFIG_COMPACTION) &&
6080 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07006081 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07006082 sc->compaction_ready = true;
6083 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07006084 }
Johannes Weiner0b064962014-08-06 16:06:12 -07006085
Andrew Morton0608f432013-09-24 15:27:41 -07006086 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07006087 * Shrink each node in the zonelist once. If the
6088 * zonelist is ordered by zone (not the default) then a
6089 * node may be shrunk multiple times but in that case
6090 * the user prefers lower zones being preserved.
6091 */
6092 if (zone->zone_pgdat == last_pgdat)
6093 continue;
6094
6095 /*
Andrew Morton0608f432013-09-24 15:27:41 -07006096 * This steals pages from memory cgroups over softlimit
6097 * and returns the number of reclaimed pages and
6098 * scanned pages. This works for global memory pressure
6099 * and balancing, not for a memcg's limit.
6100 */
6101 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006102 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006103 sc->order, sc->gfp_mask,
6104 &nr_soft_scanned);
6105 sc->nr_reclaimed += nr_soft_reclaimed;
6106 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006107 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006108 }
Nick Piggin408d8542006-09-25 23:31:27 -07006109
Mel Gorman79dafcd2016-07-28 15:45:53 -07006110 /* See comment about same check for global reclaim above */
6111 if (zone->zone_pgdat == last_pgdat)
6112 continue;
6113 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006114 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006115 }
Mel Gormane0c23272011-10-31 17:09:33 -07006116
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006117 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006118 * Restore to original mask to avoid the impact on the caller if we
6119 * promoted it to __GFP_HIGHMEM.
6120 */
6121 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006122}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006123
Johannes Weinerb9107182019-11-30 17:55:59 -08006124static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006125{
Johannes Weinerb9107182019-11-30 17:55:59 -08006126 struct lruvec *target_lruvec;
6127 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006128
Yu Zhao37397872022-09-18 02:00:03 -06006129 if (lru_gen_enabled())
6130 return;
6131
Johannes Weinerb9107182019-11-30 17:55:59 -08006132 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006133 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6134 target_lruvec->refaults[0] = refaults;
6135 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6136 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006137}
6138
Linus Torvalds1da177e2005-04-16 15:20:36 -07006139/*
6140 * This is the main entry point to direct page reclaim.
6141 *
6142 * If a full scan of the inactive list fails to free enough memory then we
6143 * are "out of memory" and something needs to be killed.
6144 *
6145 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6146 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006147 * caller can't do much about. We kick the writeback threads and take explicit
6148 * naps in the hope that some of these pages can be written. But if the
6149 * allocating task holds filesystem locks which prevent writeout this might not
6150 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006151 *
6152 * returns: 0, if no pages reclaimed
6153 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006154 */
Mel Gormandac1d272008-04-28 02:12:12 -07006155static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006156 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006157{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006158 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006159 pg_data_t *last_pgdat;
6160 struct zoneref *z;
6161 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006162retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006163 delayacct_freepages_start();
6164
Johannes Weinerb5ead352019-11-30 17:55:40 -08006165 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006166 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006167
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006168 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006169 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6170 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006171 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006172 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006173
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006174 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006175 break;
6176
6177 if (sc->compaction_ready)
6178 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006179
6180 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006181 * If we're getting trouble reclaiming, start doing
6182 * writepage even in laptop mode.
6183 */
6184 if (sc->priority < DEF_PRIORITY - 2)
6185 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006186 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006187
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006188 last_pgdat = NULL;
6189 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6190 sc->nodemask) {
6191 if (zone->zone_pgdat == last_pgdat)
6192 continue;
6193 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006194
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006195 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006196
6197 if (cgroup_reclaim(sc)) {
6198 struct lruvec *lruvec;
6199
6200 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6201 zone->zone_pgdat);
6202 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6203 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006204 }
6205
Keika Kobayashi873b4772008-07-25 01:48:52 -07006206 delayacct_freepages_end();
6207
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006208 if (sc->nr_reclaimed)
6209 return sc->nr_reclaimed;
6210
Mel Gorman0cee34f2012-01-12 17:19:49 -08006211 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006212 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006213 return 1;
6214
Johannes Weinerb91ac372019-11-30 17:56:02 -08006215 /*
6216 * We make inactive:active ratio decisions based on the node's
6217 * composition of memory, but a restrictive reclaim_idx or a
6218 * memory.low cgroup setting can exempt large amounts of
6219 * memory from reclaim. Neither of which are very common, so
6220 * instead of doing costly eligibility calculations of the
6221 * entire cgroup subtree up front, we assume the estimates are
6222 * good, and retry with forcible deactivation if that fails.
6223 */
6224 if (sc->skipped_deactivate) {
6225 sc->priority = initial_priority;
6226 sc->force_deactivate = 1;
6227 sc->skipped_deactivate = 0;
6228 goto retry;
6229 }
6230
Johannes Weiner241994ed2015-02-11 15:26:06 -08006231 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006232 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006233 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006234 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006235 sc->memcg_low_reclaim = 1;
6236 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006237 goto retry;
6238 }
6239
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006240 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006241}
6242
Johannes Weinerc73322d2017-05-03 14:51:51 -07006243static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006244{
6245 struct zone *zone;
6246 unsigned long pfmemalloc_reserve = 0;
6247 unsigned long free_pages = 0;
6248 int i;
6249 bool wmark_ok;
6250
Johannes Weinerc73322d2017-05-03 14:51:51 -07006251 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6252 return true;
6253
Mel Gorman55150612012-07-31 16:44:35 -07006254 for (i = 0; i <= ZONE_NORMAL; i++) {
6255 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006256 if (!managed_zone(zone))
6257 continue;
6258
6259 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006260 continue;
6261
Mel Gorman55150612012-07-31 16:44:35 -07006262 pfmemalloc_reserve += min_wmark_pages(zone);
6263 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6264 }
6265
Mel Gorman675becc2014-06-04 16:07:35 -07006266 /* If there are no reserves (unexpected config) then do not throttle */
6267 if (!pfmemalloc_reserve)
6268 return true;
6269
Mel Gorman55150612012-07-31 16:44:35 -07006270 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6271
6272 /* kswapd must be awake if processes are being throttled */
6273 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006274 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6275 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006276
Mel Gorman55150612012-07-31 16:44:35 -07006277 wake_up_interruptible(&pgdat->kswapd_wait);
6278 }
6279
6280 return wmark_ok;
6281}
6282
6283/*
6284 * Throttle direct reclaimers if backing storage is backed by the network
6285 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6286 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006287 * when the low watermark is reached.
6288 *
6289 * Returns true if a fatal signal was delivered during throttling. If this
6290 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006291 */
Mel Gorman50694c22012-11-26 16:29:48 -08006292static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006293 nodemask_t *nodemask)
6294{
Mel Gorman675becc2014-06-04 16:07:35 -07006295 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006296 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006297 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006298
6299 /*
6300 * Kernel threads should not be throttled as they may be indirectly
6301 * responsible for cleaning pages necessary for reclaim to make forward
6302 * progress. kjournald for example may enter direct reclaim while
6303 * committing a transaction where throttling it could forcing other
6304 * processes to block on log_wait_commit().
6305 */
6306 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006307 goto out;
6308
6309 /*
6310 * If a fatal signal is pending, this process should not throttle.
6311 * It should return quickly so it can exit and free its memory
6312 */
6313 if (fatal_signal_pending(current))
6314 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006315
Mel Gorman675becc2014-06-04 16:07:35 -07006316 /*
6317 * Check if the pfmemalloc reserves are ok by finding the first node
6318 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6319 * GFP_KERNEL will be required for allocating network buffers when
6320 * swapping over the network so ZONE_HIGHMEM is unusable.
6321 *
6322 * Throttling is based on the first usable node and throttled processes
6323 * wait on a queue until kswapd makes progress and wakes them. There
6324 * is an affinity then between processes waking up and where reclaim
6325 * progress has been made assuming the process wakes on the same node.
6326 * More importantly, processes running on remote nodes will not compete
6327 * for remote pfmemalloc reserves and processes on different nodes
6328 * should make reasonable progress.
6329 */
6330 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006331 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006332 if (zone_idx(zone) > ZONE_NORMAL)
6333 continue;
6334
6335 /* Throttle based on the first usable node */
6336 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006337 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006338 goto out;
6339 break;
6340 }
6341
6342 /* If no zone was usable by the allocation flags then do not throttle */
6343 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006344 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006345
Mel Gorman68243e72012-07-31 16:44:39 -07006346 /* Account for the throttling */
6347 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6348
Mel Gorman55150612012-07-31 16:44:35 -07006349 /*
6350 * If the caller cannot enter the filesystem, it's possible that it
6351 * is due to the caller holding an FS lock or performing a journal
6352 * transaction in the case of a filesystem like ext[3|4]. In this case,
6353 * it is not safe to block on pfmemalloc_wait as kswapd could be
6354 * blocked waiting on the same lock. Instead, throttle for up to a
6355 * second before continuing.
6356 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006357 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006358 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006359 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006360 else
6361 /* Throttle until kswapd wakes the process */
6362 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6363 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006364
Mel Gorman50694c22012-11-26 16:29:48 -08006365 if (fatal_signal_pending(current))
6366 return true;
6367
6368out:
6369 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006370}
6371
Mel Gormandac1d272008-04-28 02:12:12 -07006372unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006373 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006374{
Mel Gorman33906bc2010-08-09 17:19:16 -07006375 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006376 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006377 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006378 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006379 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006380 .order = order,
6381 .nodemask = nodemask,
6382 .priority = DEF_PRIORITY,
6383 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006384 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006385 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006386 };
6387
Mel Gorman55150612012-07-31 16:44:35 -07006388 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006389 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6390 * Confirm they are large enough for max values.
6391 */
6392 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6393 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6394 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6395
6396 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006397 * Do not enter reclaim if fatal signal was delivered while throttled.
6398 * 1 is returned so that the page allocator does not OOM kill at this
6399 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006400 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006401 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006402 return 1;
6403
Andrew Morton1732d2b012019-07-16 16:26:15 -07006404 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006405 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006406
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006407 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006408
6409 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006410 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006411
6412 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006413}
6414
Andrew Mortonc255a452012-07-31 16:43:02 -07006415#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006416
Michal Hockod2e5fb92019-08-30 16:04:50 -07006417/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006418unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006419 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006420 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006421 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006422{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006423 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006424 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006425 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006426 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006427 .may_writepage = !laptop_mode,
6428 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006429 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006430 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006431 };
Ying Han0ae5e892011-05-26 16:25:25 -07006432
Michal Hockod2e5fb92019-08-30 16:04:50 -07006433 WARN_ON_ONCE(!current->reclaim_state);
6434
Balbir Singh4e416952009-09-23 15:56:39 -07006435 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6436 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006437
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006438 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006439 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006440
Balbir Singh4e416952009-09-23 15:56:39 -07006441 /*
6442 * NOTE: Although we can get the priority field, using it
6443 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006444 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006445 * will pick up pages from other mem cgroup's as well. We hack
6446 * the priority and make it zero.
6447 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006448 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006449
6450 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6451
Ying Han0ae5e892011-05-26 16:25:25 -07006452 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006453
Balbir Singh4e416952009-09-23 15:56:39 -07006454 return sc.nr_reclaimed;
6455}
6456
Johannes Weiner72835c82012-01-12 17:18:32 -08006457unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006458 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006459 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006460 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08006461{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006462 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006463 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006464 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006465 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006466 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006467 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006468 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006469 .target_mem_cgroup = memcg,
6470 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006471 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006472 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006473 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07006474 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006475 /*
6476 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6477 * equal pressure on all the nodes. This is based on the assumption that
6478 * the reclaim does not bail out early.
6479 */
6480 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006481
Andrew Morton1732d2b012019-07-16 16:26:15 -07006482 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006483 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006484 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006485
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006486 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006487
Vlastimil Babka499118e2017-05-08 15:59:50 -07006488 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006489 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006490 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006491
6492 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006493}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006494EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006495#endif
6496
Yu Zhao37397872022-09-18 02:00:03 -06006497static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006498{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006499 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006500 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006501
Yu Zhao37397872022-09-18 02:00:03 -06006502 if (lru_gen_enabled()) {
6503 lru_gen_age_node(pgdat, sc);
6504 return;
6505 }
6506
Dave Hansen2f368a92021-09-02 14:59:23 -07006507 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006508 return;
6509
Johannes Weinerb91ac372019-11-30 17:56:02 -08006510 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6511 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6512 return;
6513
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006514 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6515 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006516 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6517 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6518 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006519 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6520 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006521}
6522
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006523static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006524{
6525 int i;
6526 struct zone *zone;
6527
6528 /*
6529 * Check for watermark boosts top-down as the higher zones
6530 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006531 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006532 * start prematurely when there is no boosting and a lower
6533 * zone is balanced.
6534 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006535 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006536 zone = pgdat->node_zones + i;
6537 if (!managed_zone(zone))
6538 continue;
6539
6540 if (zone->watermark_boost)
6541 return true;
6542 }
6543
6544 return false;
6545}
6546
Mel Gormane716f2e2017-05-03 14:53:45 -07006547/*
6548 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006549 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006550 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006551static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006552{
Mel Gormane716f2e2017-05-03 14:53:45 -07006553 int i;
6554 unsigned long mark = -1;
6555 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006556
Mel Gorman1c308442018-12-28 00:35:52 -08006557 /*
6558 * Check watermarks bottom-up as lower zones are more likely to
6559 * meet watermarks.
6560 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006561 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006562 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006563
Mel Gormane716f2e2017-05-03 14:53:45 -07006564 if (!managed_zone(zone))
6565 continue;
6566
6567 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006568 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006569 return true;
6570 }
6571
6572 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006573 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006574 * need balancing by definition. This can happen if a zone-restricted
6575 * allocation tries to wake a remote kswapd.
6576 */
6577 if (mark == -1)
6578 return true;
6579
6580 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006581}
6582
Mel Gorman631b6e02017-05-03 14:53:41 -07006583/* Clear pgdat state for congested, dirty or under writeback. */
6584static void clear_pgdat_congested(pg_data_t *pgdat)
6585{
Johannes Weiner1b051172019-11-30 17:55:52 -08006586 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6587
6588 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006589 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6590 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6591}
6592
Mel Gorman1741c872011-01-13 15:46:21 -08006593/*
Mel Gorman55150612012-07-31 16:44:35 -07006594 * Prepare kswapd for sleeping. This verifies that there are no processes
6595 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6596 *
6597 * Returns true if kswapd is ready to sleep
6598 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006599static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6600 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006601{
Mel Gorman55150612012-07-31 16:44:35 -07006602 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006603 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006604 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006605 * race between when kswapd checks the watermarks and a process gets
6606 * throttled. There is also a potential race if processes get
6607 * throttled, kswapd wakes, a large process exits thereby balancing the
6608 * zones, which causes kswapd to exit balance_pgdat() before reaching
6609 * the wake up checks. If kswapd is going to sleep, no process should
6610 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6611 * the wake up is premature, processes will wake kswapd and get
6612 * throttled again. The difference from wake ups in balance_pgdat() is
6613 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006614 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006615 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6616 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006617
Johannes Weinerc73322d2017-05-03 14:51:51 -07006618 /* Hopeless node, leave it to direct reclaim */
6619 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6620 return true;
6621
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006622 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006623 clear_pgdat_congested(pgdat);
6624 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006625 }
6626
Shantanu Goel333b0a42017-05-03 14:53:38 -07006627 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006628}
6629
Linus Torvalds1da177e2005-04-16 15:20:36 -07006630/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006631 * kswapd shrinks a node of pages that are at or below the highest usable
6632 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006633 *
6634 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006635 * reclaim or if the lack of progress was due to pages under writeback.
6636 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006637 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006638static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006639 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006640{
Mel Gorman1d82de62016-07-28 15:45:43 -07006641 struct zone *zone;
6642 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006643
Mel Gorman1d82de62016-07-28 15:45:43 -07006644 /* Reclaim a number of pages proportional to the number of zones */
6645 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006646 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006647 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006648 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006649 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006650
Mel Gorman1d82de62016-07-28 15:45:43 -07006651 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006652 }
6653
Mel Gorman1d82de62016-07-28 15:45:43 -07006654 /*
6655 * Historically care was taken to put equal pressure on all zones but
6656 * now pressure is applied based on node LRU order.
6657 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006658 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006659
6660 /*
6661 * Fragmentation may mean that the system cannot be rebalanced for
6662 * high-order allocations. If twice the allocation size has been
6663 * reclaimed then recheck watermarks only at order-0 to prevent
6664 * excessive reclaim. Assume that a process requested a high-order
6665 * can direct reclaim/compact.
6666 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006667 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006668 sc->order = 0;
6669
Mel Gormanb8e83b92013-07-03 15:01:45 -07006670 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006671}
6672
Mel Gormanc49c2c42021-06-28 19:42:21 -07006673/* Page allocator PCP high watermark is lowered if reclaim is active. */
6674static inline void
6675update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6676{
6677 int i;
6678 struct zone *zone;
6679
6680 for (i = 0; i <= highest_zoneidx; i++) {
6681 zone = pgdat->node_zones + i;
6682
6683 if (!managed_zone(zone))
6684 continue;
6685
6686 if (active)
6687 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6688 else
6689 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6690 }
6691}
6692
6693static inline void
6694set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6695{
6696 update_reclaim_active(pgdat, highest_zoneidx, true);
6697}
6698
6699static inline void
6700clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6701{
6702 update_reclaim_active(pgdat, highest_zoneidx, false);
6703}
6704
Mel Gorman75485362013-07-03 15:01:42 -07006705/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006706 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6707 * that are eligible for use by the caller until at least one zone is
6708 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006709 *
Mel Gorman1d82de62016-07-28 15:45:43 -07006710 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006711 *
6712 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07006713 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08006714 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07006715 * or lower is eligible for reclaim until at least one usable zone is
6716 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006717 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006718static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006719{
Linus Torvalds1da177e2005-04-16 15:20:36 -07006720 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07006721 unsigned long nr_soft_reclaimed;
6722 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07006723 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08006724 unsigned long nr_boost_reclaim;
6725 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6726 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07006727 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08006728 struct scan_control sc = {
6729 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07006730 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006731 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08006732 };
Omar Sandoval93781322018-06-07 17:07:02 -07006733
Andrew Morton1732d2b012019-07-16 16:26:15 -07006734 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07006735 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006736 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006737
Christoph Lameterf8891e52006-06-30 01:55:45 -07006738 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006739
Mel Gorman1c308442018-12-28 00:35:52 -08006740 /*
6741 * Account for the reclaim boost. Note that the zone boost is left in
6742 * place so that parallel allocations that are near the watermark will
6743 * stall or direct reclaim until kswapd is finished.
6744 */
6745 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006746 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006747 zone = pgdat->node_zones + i;
6748 if (!managed_zone(zone))
6749 continue;
6750
6751 nr_boost_reclaim += zone->watermark_boost;
6752 zone_boosts[i] = zone->watermark_boost;
6753 }
6754 boosted = nr_boost_reclaim;
6755
6756restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006757 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006758 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006759 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006760 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006761 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006762 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006763 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006764
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006765 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006766
Mel Gorman86c79f62016-07-28 15:45:59 -07006767 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006768 * If the number of buffer_heads exceeds the maximum allowed
6769 * then consider reclaiming from all zones. This has a dual
6770 * purpose -- on 64-bit systems it is expected that
6771 * buffer_heads are stripped during active rotation. On 32-bit
6772 * systems, highmem pages can pin lowmem memory and shrinking
6773 * buffers can relieve lowmem pressure. Reclaim may still not
6774 * go ahead if all eligible zones for the original allocation
6775 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006776 */
6777 if (buffer_heads_over_limit) {
6778 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6779 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006780 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006781 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006782
Mel Gorman970a39a2016-07-28 15:46:35 -07006783 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006784 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006785 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006786 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006787
Mel Gorman86c79f62016-07-28 15:45:59 -07006788 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006789 * If the pgdat is imbalanced then ignore boosting and preserve
6790 * the watermarks for a later time and restart. Note that the
6791 * zone watermarks will be still reset at the end of balancing
6792 * on the grounds that the normal reclaim should be enough to
6793 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006794 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006795 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006796 if (!balanced && nr_boost_reclaim) {
6797 nr_boost_reclaim = 0;
6798 goto restart;
6799 }
6800
6801 /*
6802 * If boosting is not active then only reclaim if there are no
6803 * eligible zones. Note that sc.reclaim_idx is not used as
6804 * buffer_heads_over_limit may have adjusted it.
6805 */
6806 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006807 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006808
Mel Gorman1c308442018-12-28 00:35:52 -08006809 /* Limit the priority of boosting to avoid reclaim writeback */
6810 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6811 raise_priority = false;
6812
6813 /*
6814 * Do not writeback or swap pages for boosted reclaim. The
6815 * intent is to relieve pressure not issue sub-optimal IO
6816 * from reclaim context. If no pages are reclaimed, the
6817 * reclaim will be aborted.
6818 */
6819 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6820 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006821
Linus Torvalds1da177e2005-04-16 15:20:36 -07006822 /*
Yu Zhao37397872022-09-18 02:00:03 -06006823 * Do some background aging, to give pages a chance to be
6824 * referenced before reclaiming. All pages are rotated
6825 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07006826 */
Yu Zhao37397872022-09-18 02:00:03 -06006827 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006828
6829 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006830 * If we're getting trouble reclaiming, start doing writepage
6831 * even in laptop mode.
6832 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006833 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006834 sc.may_writepage = 1;
6835
Mel Gorman1d82de62016-07-28 15:45:43 -07006836 /* Call soft limit reclaim before calling shrink_node. */
6837 sc.nr_scanned = 0;
6838 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006839 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006840 sc.gfp_mask, &nr_soft_scanned);
6841 sc.nr_reclaimed += nr_soft_reclaimed;
6842
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006843 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006844 * There should be no need to raise the scanning priority if
6845 * enough pages are already being scanned that that high
6846 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006847 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006848 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006849 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006850
6851 /*
6852 * If the low watermark is met there is no need for processes
6853 * to be throttled on pfmemalloc_wait as they should not be
6854 * able to safely make forward progress. Wake them
6855 */
6856 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006857 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006858 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006859
Mel Gormanb8e83b92013-07-03 15:01:45 -07006860 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006861 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006862 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006863 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006864 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006865 break;
6866
6867 /*
6868 * Raise priority if scanning rate is too low or there was no
6869 * progress in reclaiming pages
6870 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006871 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006872 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6873
6874 /*
6875 * If reclaim made no progress for a boost, stop reclaim as
6876 * IO cannot be queued and it could be an infinite loop in
6877 * extreme circumstances.
6878 */
6879 if (nr_boost_reclaim && !nr_reclaimed)
6880 break;
6881
Johannes Weinerc73322d2017-05-03 14:51:51 -07006882 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006883 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006884 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006885
Johannes Weinerc73322d2017-05-03 14:51:51 -07006886 if (!sc.nr_reclaimed)
6887 pgdat->kswapd_failures++;
6888
Mel Gormanb8e83b92013-07-03 15:01:45 -07006889out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006890 clear_reclaim_active(pgdat, highest_zoneidx);
6891
Mel Gorman1c308442018-12-28 00:35:52 -08006892 /* If reclaim was boosted, account for the reclaim done in this pass */
6893 if (boosted) {
6894 unsigned long flags;
6895
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006896 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006897 if (!zone_boosts[i])
6898 continue;
6899
6900 /* Increments are under the zone lock */
6901 zone = pgdat->node_zones + i;
6902 spin_lock_irqsave(&zone->lock, flags);
6903 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6904 spin_unlock_irqrestore(&zone->lock, flags);
6905 }
6906
6907 /*
6908 * As there is now likely space, wakeup kcompact to defragment
6909 * pageblocks.
6910 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006911 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006912 }
6913
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006914 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006915 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006916 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006917 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006918
Mel Gorman0abdee22011-01-13 15:46:22 -08006919 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006920 * Return the order kswapd stopped reclaiming at as
6921 * prepare_kswapd_sleep() takes it into account. If another caller
6922 * entered the allocator slow path while kswapd was awake, order will
6923 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006924 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006925 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006926}
6927
Mel Gormane716f2e2017-05-03 14:53:45 -07006928/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006929 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6930 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6931 * not a valid index then either kswapd runs for first time or kswapd couldn't
6932 * sleep after previous reclaim attempt (node is still unbalanced). In that
6933 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006934 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006935static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6936 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006937{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006938 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006939
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006940 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006941}
6942
Mel Gorman38087d92016-07-28 15:45:49 -07006943static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006944 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006945{
6946 long remaining = 0;
6947 DEFINE_WAIT(wait);
6948
6949 if (freezing(current) || kthread_should_stop())
6950 return;
6951
6952 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6953
Shantanu Goel333b0a42017-05-03 14:53:38 -07006954 /*
6955 * Try to sleep for a short interval. Note that kcompactd will only be
6956 * woken if it is possible to sleep for a short interval. This is
6957 * deliberate on the assumption that if reclaim cannot keep an
6958 * eligible zone balanced that it's also unlikely that compaction will
6959 * succeed.
6960 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006961 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006962 /*
6963 * Compaction records what page blocks it recently failed to
6964 * isolate pages from and skips them in the future scanning.
6965 * When kswapd is going to sleep, it is reasonable to assume
6966 * that pages and compaction may succeed so reset the cache.
6967 */
6968 reset_isolation_suitable(pgdat);
6969
6970 /*
6971 * We have freed the memory, now we should compact it to make
6972 * allocation of the requested order possible.
6973 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006974 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006975
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006976 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006977
6978 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006979 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006980 * order. The values will either be from a wakeup request or
6981 * the previous request that slept prematurely.
6982 */
6983 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006984 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6985 kswapd_highest_zoneidx(pgdat,
6986 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006987
6988 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6989 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006990 }
6991
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006992 finish_wait(&pgdat->kswapd_wait, &wait);
6993 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6994 }
6995
6996 /*
6997 * After a short sleep, check if it was a premature sleep. If not, then
6998 * go fully to sleep until explicitly woken up.
6999 */
Mel Gormand9f21d42016-07-28 15:46:41 -07007000 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007001 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007002 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7003
7004 /*
7005 * vmstat counters are not perfectly accurate and the estimated
7006 * value for counters such as NR_FREE_PAGES can deviate from the
7007 * true value by nr_online_cpus * threshold. To avoid the zone
7008 * watermarks being breached while under pressure, we reduce the
7009 * per-cpu vmstat threshold while kswapd is awake and restore
7010 * them before going back to sleep.
7011 */
7012 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07007013
7014 if (!kthread_should_stop())
7015 schedule();
7016
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007017 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7018 } else {
7019 if (remaining)
7020 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7021 else
7022 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7023 }
7024 finish_wait(&pgdat->kswapd_wait, &wait);
7025}
7026
Linus Torvalds1da177e2005-04-16 15:20:36 -07007027/*
7028 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07007029 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007030 *
7031 * This basically trickles out pages so that we have _some_
7032 * free memory available even if there is no other activity
7033 * that frees anything up. This is needed for things like routing
7034 * etc, where we otherwise might have all activity going on in
7035 * asynchronous contexts that cannot page things out.
7036 *
7037 * If there are applications that are active memory-allocators
7038 * (most normal use), this basically shouldn't matter.
7039 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307040int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007041{
Mel Gormane716f2e2017-05-03 14:53:45 -07007042 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007043 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07007044 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007045 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10307046 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007047
Rusty Russell174596a2009-01-01 10:12:29 +10307048 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07007049 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007050
7051 /*
7052 * Tell the memory management that we're a "memory allocator",
7053 * and that if we need more memory we should get access to it
7054 * regardless (see "__alloc_pages()"). "kswapd" should
7055 * never get caught in the normal page freeing logic.
7056 *
7057 * (Kswapd normally doesn't need memory anyway, but sometimes
7058 * you need a small amount of memory in order to be able to
7059 * page out something else, and this flag essentially protects
7060 * us from recursively trying to free more memory as we're
7061 * trying to free the first piece of memory in the first place).
7062 */
Christoph Lameter930d9152006-01-08 01:00:47 -08007063 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07007064 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07007065
Qian Cai5644e1fb2020-04-01 21:10:12 -07007066 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007067 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007068 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08007069 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07007070
Qian Cai5644e1fb2020-04-01 21:10:12 -07007071 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007072 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7073 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07007074
Mel Gorman38087d92016-07-28 15:45:49 -07007075kswapd_try_sleep:
7076 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007077 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07007078
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007079 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08007080 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007081 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7082 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007083 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007084 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007085
David Rientjes8fe23e02009-12-14 17:58:33 -08007086 ret = try_to_freeze();
7087 if (kthread_should_stop())
7088 break;
7089
7090 /*
7091 * We can speed up thawing tasks if we don't call balance_pgdat
7092 * after returning from the refrigerator
7093 */
Mel Gorman38087d92016-07-28 15:45:49 -07007094 if (ret)
7095 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07007096
Mel Gorman38087d92016-07-28 15:45:49 -07007097 /*
7098 * Reclaim begins at the requested order but if a high-order
7099 * reclaim fails then kswapd falls back to reclaiming for
7100 * order-0. If that happens, kswapd will consider sleeping
7101 * for the order it finished reclaiming at (reclaim_order)
7102 * but kcompactd is woken to compact for the original
7103 * request (alloc_order).
7104 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007105 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007106 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007107 reclaim_order = balance_pgdat(pgdat, alloc_order,
7108 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007109 if (reclaim_order < alloc_order)
7110 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007111 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007112
Johannes Weiner71abdc12014-06-06 14:35:35 -07007113 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007114
Linus Torvalds1da177e2005-04-16 15:20:36 -07007115 return 0;
7116}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307117EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007118
7119/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007120 * A zone is low on free memory or too fragmented for high-order memory. If
7121 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7122 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7123 * has failed or is not needed, still wake up kcompactd if only compaction is
7124 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007125 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007126void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007127 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007128{
7129 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007130 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007131
Mel Gorman6aa303d2016-09-01 16:14:55 -07007132 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007133 return;
7134
David Rientjes5ecd9d42018-04-05 16:25:16 -07007135 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007136 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007137
Qian Cai5644e1fb2020-04-01 21:10:12 -07007138 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007139 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007140
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007141 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7142 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007143
7144 if (READ_ONCE(pgdat->kswapd_order) < order)
7145 WRITE_ONCE(pgdat->kswapd_order, order);
7146
Con Kolivas8d0986e2005-09-13 01:25:07 -07007147 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007148 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007149
David Rientjes5ecd9d42018-04-05 16:25:16 -07007150 /* Hopeless node, leave it to direct reclaim if possible */
7151 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007152 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7153 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007154 /*
7155 * There may be plenty of free memory available, but it's too
7156 * fragmented for high-order allocations. Wake up kcompactd
7157 * and rely on compaction_suitable() to determine if it's
7158 * needed. If it fails, it will defer subsequent attempts to
7159 * ratelimit its work.
7160 */
7161 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007162 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007163 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007164 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007165
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007166 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007167 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007168 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007169}
7170
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007171#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007172/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007173 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007174 * freed pages.
7175 *
7176 * Rather than trying to age LRUs the aim is to preserve the overall
7177 * LRU order by reclaiming preferentially
7178 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007179 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007180unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007181{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007182 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007183 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007184 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007185 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007186 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007187 .may_writepage = 1,
7188 .may_unmap = 1,
7189 .may_swap = 1,
7190 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007191 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007192 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007193 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007194 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007195
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007196 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007197 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007198 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007199
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007200 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007201
Andrew Morton1732d2b012019-07-16 16:26:15 -07007202 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007203 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007204 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007205
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007206 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007207}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007208#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007209
Yasunori Goto3218ae12006-06-27 02:53:33 -07007210/*
7211 * This kswapd start function will be called by init and node-hot-add.
7212 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7213 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007214void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007215{
7216 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307217 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007218
7219 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007220 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007221
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307222 trace_android_vh_kswapd_per_node(nid, &skip, true);
7223 if (skip)
7224 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007225 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7226 if (IS_ERR(pgdat->kswapd)) {
7227 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007228 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007229 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007230 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007231 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007232}
7233
David Rientjes8fe23e02009-12-14 17:58:33 -08007234/*
Jiang Liud8adde12012-07-11 14:01:52 -07007235 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007236 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007237 */
7238void kswapd_stop(int nid)
7239{
7240 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307241 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007242
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307243 trace_android_vh_kswapd_per_node(nid, &skip, false);
7244 if (skip)
7245 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007246 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007247 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007248 NODE_DATA(nid)->kswapd = NULL;
7249 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007250}
7251
Linus Torvalds1da177e2005-04-16 15:20:36 -07007252static int __init kswapd_init(void)
7253{
Wei Yang6b700b52020-04-01 21:10:09 -07007254 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007255
Linus Torvalds1da177e2005-04-16 15:20:36 -07007256 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007257 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007258 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007259 return 0;
7260}
7261
7262module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007263
7264#ifdef CONFIG_NUMA
7265/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007266 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007267 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007268 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007269 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007270 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007271int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007272
Dave Hansen51998362021-02-24 12:09:15 -08007273/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007274 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007275 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7276 * a zone.
7277 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007278#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007279
Christoph Lameter9eeff232006-01-18 17:42:31 -08007280/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007281 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007282 * occur.
7283 */
7284int sysctl_min_unmapped_ratio = 1;
7285
7286/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007287 * If the number of slab pages in a zone grows beyond this percentage then
7288 * slab reclaim needs to occur.
7289 */
7290int sysctl_min_slab_ratio = 5;
7291
Mel Gorman11fb9982016-07-28 15:46:20 -07007292static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007293{
Mel Gorman11fb9982016-07-28 15:46:20 -07007294 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7295 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7296 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007297
7298 /*
7299 * It's possible for there to be more file mapped pages than
7300 * accounted for by the pages on the file LRU lists because
7301 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7302 */
7303 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7304}
7305
7306/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007307static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007308{
Alexandru Moised031a152015-11-05 18:48:08 -08007309 unsigned long nr_pagecache_reclaimable;
7310 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007311
7312 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007313 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007314 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007315 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007316 * a better estimate
7317 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007318 if (node_reclaim_mode & RECLAIM_UNMAP)
7319 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007320 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007321 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007322
7323 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007324 if (!(node_reclaim_mode & RECLAIM_WRITE))
7325 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007326
7327 /* Watch for any possible underflows due to delta */
7328 if (unlikely(delta > nr_pagecache_reclaimable))
7329 delta = nr_pagecache_reclaimable;
7330
7331 return nr_pagecache_reclaimable - delta;
7332}
7333
Christoph Lameter0ff38492006-09-25 23:31:52 -07007334/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007335 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007336 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007337static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007338{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007339 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007340 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007341 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007342 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007343 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007344 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007345 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007346 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007347 .priority = NODE_RECLAIM_PRIORITY,
7348 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7349 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007350 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007351 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007352 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007353 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007354
Yafang Shao132bb8c2019-05-13 17:17:53 -07007355 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7356 sc.gfp_mask);
7357
Christoph Lameter9eeff232006-01-18 17:42:31 -08007358 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007359 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007360 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007361 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007362 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007363 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007364 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007365 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007366 noreclaim_flag = memalloc_noreclaim_save();
7367 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007368 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007369
Mel Gormana5f5f912016-07-28 15:46:32 -07007370 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007371 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007372 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007373 * priorities until we have enough memory freed.
7374 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007375 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007376 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007377 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007378 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007379
Andrew Morton1732d2b012019-07-16 16:26:15 -07007380 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007381 current->flags &= ~PF_SWAPWRITE;
7382 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007383 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007384 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007385
7386 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7387
Rik van Riela79311c2009-01-06 14:40:01 -08007388 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007389}
Andrew Morton179e9632006-03-22 00:08:18 -08007390
Mel Gormana5f5f912016-07-28 15:46:32 -07007391int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007392{
David Rientjesd773ed62007-10-16 23:26:01 -07007393 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007394
7395 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007396 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007397 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007398 *
Christoph Lameter96146342006-07-03 00:24:13 -07007399 * A small portion of unmapped file backed pages is needed for
7400 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007401 * thrown out if the node is overallocated. So we do not reclaim
7402 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007403 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007404 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007405 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007406 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7407 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007408 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007409
7410 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007411 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007412 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007413 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007414 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007415
7416 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007417 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007418 * have associated processors. This will favor the local processor
7419 * over remote processors and spread off node memory allocations
7420 * as wide as possible.
7421 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007422 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7423 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007424
Mel Gormana5f5f912016-07-28 15:46:32 -07007425 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7426 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007427
Mel Gormana5f5f912016-07-28 15:46:32 -07007428 ret = __node_reclaim(pgdat, gfp_mask, order);
7429 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007430
Mel Gorman24cf725182009-06-16 15:33:23 -07007431 if (!ret)
7432 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7433
David Rientjesd773ed62007-10-16 23:26:01 -07007434 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007435}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007436#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007437
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007438/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007439 * check_move_unevictable_pages - check pages for evictability and move to
7440 * appropriate zone lru list
7441 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007442 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007443 * Checks pages for evictability, if an evictable page is in the unevictable
7444 * lru list, moves it to the appropriate evictable lru list. This function
7445 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007446 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007447void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007448{
Alex Shi6168d0d2020-12-15 12:34:29 -08007449 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007450 int pgscanned = 0;
7451 int pgrescued = 0;
7452 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007453
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007454 for (i = 0; i < pvec->nr; i++) {
7455 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007456 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007457
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007458 if (PageTransTail(page))
7459 continue;
7460
7461 nr_pages = thp_nr_pages(page);
7462 pgscanned += nr_pages;
7463
Alex Shid25b5bd2020-12-15 12:34:16 -08007464 /* block memcg migration during page moving between lru */
7465 if (!TestClearPageLRU(page))
7466 continue;
7467
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007468 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007469 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007470 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007471 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007472 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007473 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007474 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007475 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007476 }
Hugh Dickins24513262012-01-20 14:34:21 -08007477
Alex Shi6168d0d2020-12-15 12:34:29 -08007478 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007479 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7480 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007481 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007482 } else if (pgscanned) {
7483 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007484 }
Hugh Dickins850465792012-01-20 14:34:19 -08007485}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007486EXPORT_SYMBOL_GPL(check_move_unevictable_pages);