blob: d781461399908ccffa777e570a84df5d476f15d7 [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
2948 if (!can_demote(pgdat->node_id, sc) &&
2949 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2950 return 0;
2951
2952 return mem_cgroup_swappiness(memcg);
2953}
2954
2955static int get_nr_gens(struct lruvec *lruvec, int type)
2956{
2957 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2958}
2959
2960static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2961{
2962 /* see the comment on lru_gen_struct */
2963 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2964 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2965 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2966}
2967
2968/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002969 * mm_struct list
2970 ******************************************************************************/
2971
2972static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
2973{
2974 static struct lru_gen_mm_list mm_list = {
2975 .fifo = LIST_HEAD_INIT(mm_list.fifo),
2976 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
2977 };
2978
2979#ifdef CONFIG_MEMCG
2980 if (memcg)
2981 return &memcg->mm_list;
2982#endif
2983 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2984
2985 return &mm_list;
2986}
2987
2988void lru_gen_add_mm(struct mm_struct *mm)
2989{
2990 int nid;
2991 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
2992 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
2993
2994 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
2995#ifdef CONFIG_MEMCG
2996 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
2997 mm->lru_gen.memcg = memcg;
2998#endif
2999 spin_lock(&mm_list->lock);
3000
3001 for_each_node_state(nid, N_MEMORY) {
3002 struct lruvec *lruvec = get_lruvec(memcg, nid);
3003
3004 if (!lruvec)
3005 continue;
3006
3007 /* the first addition since the last iteration */
3008 if (lruvec->mm_state.tail == &mm_list->fifo)
3009 lruvec->mm_state.tail = &mm->lru_gen.list;
3010 }
3011
3012 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3013
3014 spin_unlock(&mm_list->lock);
3015}
3016
3017void lru_gen_del_mm(struct mm_struct *mm)
3018{
3019 int nid;
3020 struct lru_gen_mm_list *mm_list;
3021 struct mem_cgroup *memcg = NULL;
3022
3023 if (list_empty(&mm->lru_gen.list))
3024 return;
3025
3026#ifdef CONFIG_MEMCG
3027 memcg = mm->lru_gen.memcg;
3028#endif
3029 mm_list = get_mm_list(memcg);
3030
3031 spin_lock(&mm_list->lock);
3032
3033 for_each_node(nid) {
3034 struct lruvec *lruvec = get_lruvec(memcg, nid);
3035
3036 if (!lruvec)
3037 continue;
3038
3039 /* where the last iteration ended (exclusive) */
3040 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3041 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3042
3043 /* where the current iteration continues (inclusive) */
3044 if (lruvec->mm_state.head != &mm->lru_gen.list)
3045 continue;
3046
3047 lruvec->mm_state.head = lruvec->mm_state.head->next;
3048 /* the deletion ends the current iteration */
3049 if (lruvec->mm_state.head == &mm_list->fifo)
3050 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3051 }
3052
3053 list_del_init(&mm->lru_gen.list);
3054
3055 spin_unlock(&mm_list->lock);
3056
3057#ifdef CONFIG_MEMCG
3058 mem_cgroup_put(mm->lru_gen.memcg);
3059 mm->lru_gen.memcg = NULL;
3060#endif
3061}
3062
3063#ifdef CONFIG_MEMCG
3064void lru_gen_migrate_mm(struct mm_struct *mm)
3065{
3066 struct mem_cgroup *memcg;
3067 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3068
3069 VM_WARN_ON_ONCE(task->mm != mm);
3070 lockdep_assert_held(&task->alloc_lock);
3071
3072 /* for mm_update_next_owner() */
3073 if (mem_cgroup_disabled())
3074 return;
3075
3076 rcu_read_lock();
3077 memcg = mem_cgroup_from_task(task);
3078 rcu_read_unlock();
3079 if (memcg == mm->lru_gen.memcg)
3080 return;
3081
3082 VM_WARN_ON_ONCE(!mm->lru_gen.memcg);
3083 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3084
3085 lru_gen_del_mm(mm);
3086 lru_gen_add_mm(mm);
3087}
3088#endif
3089
3090/*
3091 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3092 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3093 * bits in a bitmap, k is the number of hash functions and n is the number of
3094 * inserted items.
3095 *
3096 * Page table walkers use one of the two filters to reduce their search space.
3097 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3098 * aging uses the double-buffering technique to flip to the other filter each
3099 * time it produces a new generation. For non-leaf entries that have enough
3100 * leaf entries, the aging carries them over to the next generation in
3101 * walk_pmd_range(); the eviction also report them when walking the rmap
3102 * in lru_gen_look_around().
3103 *
3104 * For future optimizations:
3105 * 1. It's not necessary to keep both filters all the time. The spare one can be
3106 * freed after the RCU grace period and reallocated if needed again.
3107 * 2. And when reallocating, it's worth scaling its size according to the number
3108 * of inserted entries in the other filter, to reduce the memory overhead on
3109 * small systems and false positives on large systems.
3110 * 3. Jenkins' hash function is an alternative to Knuth's.
3111 */
3112#define BLOOM_FILTER_SHIFT 15
3113
3114static inline int filter_gen_from_seq(unsigned long seq)
3115{
3116 return seq % NR_BLOOM_FILTERS;
3117}
3118
3119static void get_item_key(void *item, int *key)
3120{
3121 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3122
3123 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3124
3125 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3126 key[1] = hash >> BLOOM_FILTER_SHIFT;
3127}
3128
3129static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3130{
3131 unsigned long *filter;
3132 int gen = filter_gen_from_seq(seq);
3133
3134 filter = lruvec->mm_state.filters[gen];
3135 if (filter) {
3136 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3137 return;
3138 }
3139
3140 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3141 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3142 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3143}
3144
3145static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3146{
3147 int key[2];
3148 unsigned long *filter;
3149 int gen = filter_gen_from_seq(seq);
3150
3151 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3152 if (!filter)
3153 return;
3154
3155 get_item_key(item, key);
3156
3157 if (!test_bit(key[0], filter))
3158 set_bit(key[0], filter);
3159 if (!test_bit(key[1], filter))
3160 set_bit(key[1], filter);
3161}
3162
3163static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3164{
3165 int key[2];
3166 unsigned long *filter;
3167 int gen = filter_gen_from_seq(seq);
3168
3169 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3170 if (!filter)
3171 return true;
3172
3173 get_item_key(item, key);
3174
3175 return test_bit(key[0], filter) && test_bit(key[1], filter);
3176}
3177
3178static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3179{
3180 int i;
3181 int hist;
3182
3183 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3184
3185 if (walk) {
3186 hist = lru_hist_from_seq(walk->max_seq);
3187
3188 for (i = 0; i < NR_MM_STATS; i++) {
3189 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3190 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3191 walk->mm_stats[i] = 0;
3192 }
3193 }
3194
3195 if (NR_HIST_GENS > 1 && last) {
3196 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3197
3198 for (i = 0; i < NR_MM_STATS; i++)
3199 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3200 }
3201}
3202
3203static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3204{
3205 int type;
3206 unsigned long size = 0;
3207 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3208 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3209
3210 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3211 return true;
3212
3213 clear_bit(key, &mm->lru_gen.bitmap);
3214
3215 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3216 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3217 get_mm_counter(mm, MM_ANONPAGES) +
3218 get_mm_counter(mm, MM_SHMEMPAGES);
3219 }
3220
3221 if (size < MIN_LRU_BATCH)
3222 return true;
3223
3224 return !mmget_not_zero(mm);
3225}
3226
3227static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3228 struct mm_struct **iter)
3229{
3230 bool first = false;
3231 bool last = true;
3232 struct mm_struct *mm = NULL;
3233 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3234 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3235 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3236
3237 /*
3238 * There are four interesting cases for this page table walker:
3239 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3240 * there is nothing left to do.
3241 * 2. It's the first of the current generation, and it needs to reset
3242 * the Bloom filter for the next generation.
3243 * 3. It reaches the end of mm_list, and it needs to increment
3244 * mm_state->seq; the iteration is done.
3245 * 4. It's the last of the current generation, and it needs to reset the
3246 * mm stats counters for the next generation.
3247 */
3248 spin_lock(&mm_list->lock);
3249
3250 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3251 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3252 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3253
3254 if (walk->max_seq <= mm_state->seq) {
3255 if (!*iter)
3256 last = false;
3257 goto done;
3258 }
3259
3260 if (!mm_state->nr_walkers) {
3261 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3262
3263 mm_state->head = mm_list->fifo.next;
3264 first = true;
3265 }
3266
3267 while (!mm && mm_state->head != &mm_list->fifo) {
3268 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3269
3270 mm_state->head = mm_state->head->next;
3271
3272 /* force scan for those added after the last iteration */
3273 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3274 mm_state->tail = mm_state->head;
3275 walk->force_scan = true;
3276 }
3277
3278 if (should_skip_mm(mm, walk))
3279 mm = NULL;
3280 }
3281
3282 if (mm_state->head == &mm_list->fifo)
3283 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3284done:
3285 if (*iter && !mm)
3286 mm_state->nr_walkers--;
3287 if (!*iter && mm)
3288 mm_state->nr_walkers++;
3289
3290 if (mm_state->nr_walkers)
3291 last = false;
3292
3293 if (*iter || last)
3294 reset_mm_stats(lruvec, walk, last);
3295
3296 spin_unlock(&mm_list->lock);
3297
3298 if (mm && first)
3299 reset_bloom_filter(lruvec, walk->max_seq + 1);
3300
3301 if (*iter)
3302 mmput_async(*iter);
3303
3304 *iter = mm;
3305
3306 return last;
3307}
3308
3309static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3310{
3311 bool success = false;
3312 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3313 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3314 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3315
3316 spin_lock(&mm_list->lock);
3317
3318 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3319
3320 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3321 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3322
3323 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3324 reset_mm_stats(lruvec, NULL, true);
3325 success = true;
3326 }
3327
3328 spin_unlock(&mm_list->lock);
3329
3330 return success;
3331}
3332
3333/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003334 * refault feedback loop
3335 ******************************************************************************/
3336
3337/*
3338 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3339 *
3340 * The P term is refaulted/(evicted+protected) from a tier in the generation
3341 * currently being evicted; the I term is the exponential moving average of the
3342 * P term over the generations previously evicted, using the smoothing factor
3343 * 1/2; the D term isn't supported.
3344 *
3345 * The setpoint (SP) is always the first tier of one type; the process variable
3346 * (PV) is either any tier of the other type or any other tier of the same
3347 * type.
3348 *
3349 * The error is the difference between the SP and the PV; the correction is to
3350 * turn off protection when SP>PV or turn on protection when SP<PV.
3351 *
3352 * For future optimizations:
3353 * 1. The D term may discount the other two terms over time so that long-lived
3354 * generations can resist stale information.
3355 */
3356struct ctrl_pos {
3357 unsigned long refaulted;
3358 unsigned long total;
3359 int gain;
3360};
3361
3362static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3363 struct ctrl_pos *pos)
3364{
3365 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3366 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3367
3368 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3369 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3370 pos->total = lrugen->avg_total[type][tier] +
3371 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3372 if (tier)
3373 pos->total += lrugen->protected[hist][type][tier - 1];
3374 pos->gain = gain;
3375}
3376
3377static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3378{
3379 int hist, tier;
3380 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3381 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3382 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3383
3384 lockdep_assert_held(&lruvec->lru_lock);
3385
3386 if (!carryover && !clear)
3387 return;
3388
3389 hist = lru_hist_from_seq(seq);
3390
3391 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3392 if (carryover) {
3393 unsigned long sum;
3394
3395 sum = lrugen->avg_refaulted[type][tier] +
3396 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3397 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3398
3399 sum = lrugen->avg_total[type][tier] +
3400 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3401 if (tier)
3402 sum += lrugen->protected[hist][type][tier - 1];
3403 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3404 }
3405
3406 if (clear) {
3407 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3408 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3409 if (tier)
3410 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3411 }
3412 }
3413}
3414
3415static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3416{
3417 /*
3418 * Return true if the PV has a limited number of refaults or a lower
3419 * refaulted/total than the SP.
3420 */
3421 return pv->refaulted < MIN_LRU_BATCH ||
3422 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3423 (sp->refaulted + 1) * pv->total * pv->gain;
3424}
3425
3426/******************************************************************************
3427 * the aging
3428 ******************************************************************************/
3429
Yu Zhao0182f922022-09-18 02:00:04 -06003430/* promote pages accessed through page tables */
3431static int page_update_gen(struct page *page, int gen)
3432{
3433 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3434
3435 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3436 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3437
3438 do {
3439 /* lru_gen_del_page() has isolated this page? */
3440 if (!(old_flags & LRU_GEN_MASK)) {
3441 /* for shrink_page_list() */
3442 new_flags = old_flags | BIT(PG_referenced);
3443 continue;
3444 }
3445
3446 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3447 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3448 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3449
3450 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3451}
3452
Yu Zhao37397872022-09-18 02:00:03 -06003453/* protect pages accessed multiple times through file descriptors */
3454static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3455{
3456 int type = page_is_file_lru(page);
3457 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3458 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3459 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3460
3461 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3462
3463 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003464 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3465 /* page_update_gen() has promoted this page? */
3466 if (new_gen >= 0 && new_gen != old_gen)
3467 return new_gen;
3468
Yu Zhao37397872022-09-18 02:00:03 -06003469 new_gen = (old_gen + 1) % MAX_NR_GENS;
3470
3471 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3472 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3473 /* for end_page_writeback() */
3474 if (reclaiming)
3475 new_flags |= BIT(PG_reclaim);
3476 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3477
3478 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3479
3480 return new_gen;
3481}
3482
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003483static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3484 int old_gen, int new_gen)
3485{
3486 int type = page_is_file_lru(page);
3487 int zone = page_zonenum(page);
3488 int delta = thp_nr_pages(page);
3489
3490 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3491 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3492
3493 walk->batched++;
3494
3495 walk->nr_pages[old_gen][type][zone] -= delta;
3496 walk->nr_pages[new_gen][type][zone] += delta;
3497}
3498
3499static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3500{
3501 int gen, type, zone;
3502 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3503
3504 walk->batched = 0;
3505
3506 for_each_gen_type_zone(gen, type, zone) {
3507 enum lru_list lru = type * LRU_INACTIVE_FILE;
3508 int delta = walk->nr_pages[gen][type][zone];
3509
3510 if (!delta)
3511 continue;
3512
3513 walk->nr_pages[gen][type][zone] = 0;
3514 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3515 lrugen->nr_pages[gen][type][zone] + delta);
3516
3517 if (lru_gen_is_active(lruvec, gen))
3518 lru += LRU_ACTIVE;
3519 __update_lru_size(lruvec, lru, zone, delta);
3520 }
3521}
3522
3523static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3524{
3525 struct address_space *mapping;
3526 struct vm_area_struct *vma = args->vma;
3527 struct lru_gen_mm_walk *walk = args->private;
3528
3529 if (!vma_is_accessible(vma))
3530 return true;
3531
3532 if (is_vm_hugetlb_page(vma))
3533 return true;
3534
3535 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3536 return true;
3537
3538 if (vma == get_gate_vma(vma->vm_mm))
3539 return true;
3540
3541 if (vma_is_anonymous(vma))
3542 return !walk->can_swap;
3543
3544 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3545 return true;
3546
3547 mapping = vma->vm_file->f_mapping;
3548 if (mapping_unevictable(mapping))
3549 return true;
3550
3551 if (shmem_mapping(mapping))
3552 return !walk->can_swap;
3553
3554 /* to exclude special mappings like dax, etc. */
3555 return !mapping->a_ops->readpage;
3556}
3557
3558/*
3559 * Some userspace memory allocators map many single-page VMAs. Instead of
3560 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3561 * table to reduce zigzags and improve cache performance.
3562 */
3563static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3564 unsigned long *vm_start, unsigned long *vm_end)
3565{
3566 unsigned long start = round_up(*vm_end, size);
3567 unsigned long end = (start | ~mask) + 1;
3568
3569 VM_WARN_ON_ONCE(mask & size);
3570 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3571
3572 while (args->vma) {
3573 if (start >= args->vma->vm_end) {
3574 args->vma = args->vma->vm_next;
3575 continue;
3576 }
3577
3578 if (end && end <= args->vma->vm_start)
3579 return false;
3580
3581 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3582 args->vma = args->vma->vm_next;
3583 continue;
3584 }
3585
3586 *vm_start = max(start, args->vma->vm_start);
3587 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3588
3589 return true;
3590 }
3591
3592 return false;
3593}
3594
Yu Zhao0182f922022-09-18 02:00:04 -06003595static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3596{
3597 unsigned long pfn = pte_pfn(pte);
3598
3599 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3600
3601 if (!pte_present(pte) || is_zero_pfn(pfn))
3602 return -1;
3603
3604 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3605 return -1;
3606
3607 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3608 return -1;
3609
3610 return pfn;
3611}
3612
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003613#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3614static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3615{
3616 unsigned long pfn = pmd_pfn(pmd);
3617
3618 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3619
3620 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3621 return -1;
3622
3623 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3624 return -1;
3625
3626 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3627 return -1;
3628
3629 return pfn;
3630}
3631#endif
3632
Yu Zhao0182f922022-09-18 02:00:04 -06003633static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003634 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003635{
3636 struct page *page;
3637
3638 /* try to avoid unnecessary memory loads */
3639 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3640 return NULL;
3641
3642 page = compound_head(pfn_to_page(pfn));
3643 if (page_to_nid(page) != pgdat->node_id)
3644 return NULL;
3645
3646 if (page_memcg_rcu(page) != memcg)
3647 return NULL;
3648
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003649 /* file VMAs can contain anon pages from COW */
3650 if (!page_is_file_lru(page) && !can_swap)
3651 return NULL;
3652
Yu Zhao0182f922022-09-18 02:00:04 -06003653 return page;
3654}
3655
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003656static bool suitable_to_scan(int total, int young)
3657{
3658 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3659
3660 /* suitable if the average number of young PTEs per cacheline is >=1 */
3661 return young * n >= total;
3662}
3663
3664static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3665 struct mm_walk *args)
3666{
3667 int i;
3668 pte_t *pte;
3669 spinlock_t *ptl;
3670 unsigned long addr;
3671 int total = 0;
3672 int young = 0;
3673 struct lru_gen_mm_walk *walk = args->private;
3674 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3675 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3676 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3677
3678 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3679
3680 ptl = pte_lockptr(args->mm, pmd);
3681 if (!spin_trylock(ptl))
3682 return false;
3683
3684 arch_enter_lazy_mmu_mode();
3685
3686 pte = pte_offset_map(pmd, start & PMD_MASK);
3687restart:
3688 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3689 unsigned long pfn;
3690 struct page *page;
3691
3692 total++;
3693 walk->mm_stats[MM_LEAF_TOTAL]++;
3694
3695 pfn = get_pte_pfn(pte[i], args->vma, addr);
3696 if (pfn == -1)
3697 continue;
3698
3699 if (!pte_young(pte[i])) {
3700 walk->mm_stats[MM_LEAF_OLD]++;
3701 continue;
3702 }
3703
3704 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3705 if (!page)
3706 continue;
3707
3708 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3709 VM_WARN_ON_ONCE(true);
3710
3711 young++;
3712 walk->mm_stats[MM_LEAF_YOUNG]++;
3713
3714 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3715 !(PageAnon(page) && PageSwapBacked(page) &&
3716 !PageSwapCache(page)))
3717 set_page_dirty(page);
3718
3719 old_gen = page_update_gen(page, new_gen);
3720 if (old_gen >= 0 && old_gen != new_gen)
3721 update_batch_size(walk, page, old_gen, new_gen);
3722 }
3723
3724 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3725 goto restart;
3726
3727 pte_unmap(pte);
3728
3729 arch_leave_lazy_mmu_mode();
3730 spin_unlock(ptl);
3731
3732 return suitable_to_scan(total, young);
3733}
3734
3735#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3736static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3737 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3738{
3739 int i;
3740 pmd_t *pmd;
3741 spinlock_t *ptl;
3742 struct lru_gen_mm_walk *walk = args->private;
3743 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3744 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3745 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3746
3747 VM_WARN_ON_ONCE(pud_leaf(*pud));
3748
3749 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3750 if (*start == -1) {
3751 *start = next;
3752 return;
3753 }
3754
3755 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3756 if (i && i <= MIN_LRU_BATCH) {
3757 __set_bit(i - 1, bitmap);
3758 return;
3759 }
3760
3761 pmd = pmd_offset(pud, *start);
3762
3763 ptl = pmd_lockptr(args->mm, pmd);
3764 if (!spin_trylock(ptl))
3765 goto done;
3766
3767 arch_enter_lazy_mmu_mode();
3768
3769 do {
3770 unsigned long pfn;
3771 struct page *page;
3772 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3773
3774 pfn = get_pmd_pfn(pmd[i], vma, addr);
3775 if (pfn == -1)
3776 goto next;
3777
3778 if (!pmd_trans_huge(pmd[i])) {
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003779 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3780 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003781 pmdp_test_and_clear_young(vma, addr, pmd + i);
3782 goto next;
3783 }
3784
3785 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3786 if (!page)
3787 goto next;
3788
3789 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3790 goto next;
3791
3792 walk->mm_stats[MM_LEAF_YOUNG]++;
3793
3794 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3795 !(PageAnon(page) && PageSwapBacked(page) &&
3796 !PageSwapCache(page)))
3797 set_page_dirty(page);
3798
3799 old_gen = page_update_gen(page, new_gen);
3800 if (old_gen >= 0 && old_gen != new_gen)
3801 update_batch_size(walk, page, old_gen, new_gen);
3802next:
3803 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3804 } while (i <= MIN_LRU_BATCH);
3805
3806 arch_leave_lazy_mmu_mode();
3807 spin_unlock(ptl);
3808done:
3809 *start = -1;
3810 bitmap_zero(bitmap, MIN_LRU_BATCH);
3811}
3812#else
3813static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3814 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3815{
3816}
3817#endif
3818
3819static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3820 struct mm_walk *args)
3821{
3822 int i;
3823 pmd_t *pmd;
3824 unsigned long next;
3825 unsigned long addr;
3826 struct vm_area_struct *vma;
3827 unsigned long pos = -1;
3828 struct lru_gen_mm_walk *walk = args->private;
3829 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3830
3831 VM_WARN_ON_ONCE(pud_leaf(*pud));
3832
3833 /*
3834 * Finish an entire PMD in two passes: the first only reaches to PTE
3835 * tables to avoid taking the PMD lock; the second, if necessary, takes
3836 * the PMD lock to clear the accessed bit in PMD entries.
3837 */
3838 pmd = pmd_offset(pud, start & PUD_MASK);
3839restart:
3840 /* walk_pte_range() may call get_next_vma() */
3841 vma = args->vma;
3842 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3843 pmd_t val = pmd_read_atomic(pmd + i);
3844
3845 /* for pmd_read_atomic() */
3846 barrier();
3847
3848 next = pmd_addr_end(addr, end);
3849
3850 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3851 walk->mm_stats[MM_LEAF_TOTAL]++;
3852 continue;
3853 }
3854
3855#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3856 if (pmd_trans_huge(val)) {
3857 unsigned long pfn = pmd_pfn(val);
3858 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3859
3860 walk->mm_stats[MM_LEAF_TOTAL]++;
3861
3862 if (!pmd_young(val)) {
3863 walk->mm_stats[MM_LEAF_OLD]++;
3864 continue;
3865 }
3866
3867 /* try to avoid unnecessary memory loads */
3868 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3869 continue;
3870
3871 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3872 continue;
3873 }
3874#endif
3875 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3876
3877#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003878 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3879 if (!pmd_young(val))
3880 continue;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003881
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003882 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3883 }
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003884#endif
3885 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3886 continue;
3887
3888 walk->mm_stats[MM_NONLEAF_FOUND]++;
3889
3890 if (!walk_pte_range(&val, addr, next, args))
3891 continue;
3892
3893 walk->mm_stats[MM_NONLEAF_ADDED]++;
3894
3895 /* carry over to the next generation */
3896 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3897 }
3898
3899 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3900
3901 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3902 goto restart;
3903}
3904
3905static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3906 struct mm_walk *args)
3907{
3908 int i;
3909 pud_t *pud;
3910 unsigned long addr;
3911 unsigned long next;
3912 struct lru_gen_mm_walk *walk = args->private;
3913
3914 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3915
3916 pud = pud_offset(p4d, start & P4D_MASK);
3917restart:
3918 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3919 pud_t val = READ_ONCE(pud[i]);
3920
3921 next = pud_addr_end(addr, end);
3922
3923 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3924 continue;
3925
3926 walk_pmd_range(&val, addr, next, args);
3927
3928 /* a racy check to curtail the waiting time */
3929 if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
3930 return 1;
3931
3932 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3933 end = (addr | ~PUD_MASK) + 1;
3934 goto done;
3935 }
3936 }
3937
3938 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3939 goto restart;
3940
3941 end = round_up(end, P4D_SIZE);
3942done:
3943 if (!end || !args->vma)
3944 return 1;
3945
3946 walk->next_addr = max(end, args->vma->vm_start);
3947
3948 return -EAGAIN;
3949}
3950
3951static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3952{
3953 static const struct mm_walk_ops mm_walk_ops = {
3954 .test_walk = should_skip_vma,
3955 .p4d_entry = walk_pud_range,
3956 };
3957
3958 int err;
3959 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3960
3961 walk->next_addr = FIRST_USER_ADDRESS;
3962
3963 do {
3964 err = -EBUSY;
3965
3966 /* page_update_gen() requires stable page_memcg() */
3967 if (!mem_cgroup_trylock_pages(memcg))
3968 break;
3969
3970 /* the caller might be holding the lock for write */
3971 if (mmap_read_trylock(mm)) {
3972 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3973
3974 mmap_read_unlock(mm);
3975 }
3976
3977 mem_cgroup_unlock_pages();
3978
3979 if (walk->batched) {
3980 spin_lock_irq(&lruvec->lru_lock);
3981 reset_batch_size(lruvec, walk);
3982 spin_unlock_irq(&lruvec->lru_lock);
3983 }
3984
3985 cond_resched();
3986 } while (err == -EAGAIN);
3987}
3988
3989static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
3990{
3991 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3992
3993 if (pgdat && current_is_kswapd()) {
3994 VM_WARN_ON_ONCE(walk);
3995
3996 walk = &pgdat->mm_walk;
3997 } else if (!pgdat && !walk) {
3998 VM_WARN_ON_ONCE(current_is_kswapd());
3999
4000 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4001 }
4002
4003 current->reclaim_state->mm_walk = walk;
4004
4005 return walk;
4006}
4007
4008static void clear_mm_walk(void)
4009{
4010 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4011
4012 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4013 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4014
4015 current->reclaim_state->mm_walk = NULL;
4016
4017 if (!current_is_kswapd())
4018 kfree(walk);
4019}
4020
Yu Zhao4983c522022-09-18 02:00:09 -06004021static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004022{
Yu Zhao4983c522022-09-18 02:00:09 -06004023 int zone;
4024 int remaining = MAX_LRU_BATCH;
Yu Zhao37397872022-09-18 02:00:03 -06004025 struct lru_gen_struct *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06004026 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
Yu Zhao37397872022-09-18 02:00:03 -06004027
Yu Zhao4983c522022-09-18 02:00:09 -06004028 if (type == LRU_GEN_ANON && !can_swap)
4029 goto done;
4030
4031 /* prevent cold/hot inversion if force_scan is true */
4032 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4033 struct list_head *head = &lrugen->lists[old_gen][type][zone];
4034
4035 while (!list_empty(head)) {
4036 struct page *page = lru_to_page(head);
4037
4038 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4039 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4040 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4041 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4042
4043 new_gen = page_inc_gen(lruvec, page, false);
4044 list_move_tail(&page->lru, &lrugen->lists[new_gen][type][zone]);
4045
4046 if (!--remaining)
4047 return false;
4048 }
4049 }
4050done:
Yu Zhao37397872022-09-18 02:00:03 -06004051 reset_ctrl_pos(lruvec, type, true);
4052 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
Yu Zhao4983c522022-09-18 02:00:09 -06004053
4054 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004055}
4056
4057static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4058{
4059 int gen, type, zone;
4060 bool success = false;
4061 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4062 DEFINE_MIN_SEQ(lruvec);
4063
4064 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4065
4066 /* find the oldest populated generation */
4067 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4068 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4069 gen = lru_gen_from_seq(min_seq[type]);
4070
4071 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4072 if (!list_empty(&lrugen->lists[gen][type][zone]))
4073 goto next;
4074 }
4075
4076 min_seq[type]++;
4077 }
4078next:
4079 ;
4080 }
4081
4082 /* see the comment on lru_gen_struct */
4083 if (can_swap) {
4084 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4085 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4086 }
4087
4088 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4089 if (min_seq[type] == lrugen->min_seq[type])
4090 continue;
4091
4092 reset_ctrl_pos(lruvec, type, true);
4093 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4094 success = true;
4095 }
4096
4097 return success;
4098}
4099
Yu Zhao4983c522022-09-18 02:00:09 -06004100static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
Yu Zhao37397872022-09-18 02:00:03 -06004101{
4102 int prev, next;
4103 int type, zone;
4104 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4105
4106 spin_lock_irq(&lruvec->lru_lock);
4107
4108 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4109
Yu Zhao37397872022-09-18 02:00:03 -06004110 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4111 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4112 continue;
4113
Yu Zhao4983c522022-09-18 02:00:09 -06004114 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
Yu Zhao37397872022-09-18 02:00:03 -06004115
Yu Zhao4983c522022-09-18 02:00:09 -06004116 while (!inc_min_seq(lruvec, type, can_swap)) {
4117 spin_unlock_irq(&lruvec->lru_lock);
4118 cond_resched();
4119 spin_lock_irq(&lruvec->lru_lock);
4120 }
Yu Zhao37397872022-09-18 02:00:03 -06004121 }
4122
4123 /*
4124 * Update the active/inactive LRU sizes for compatibility. Both sides of
4125 * the current max_seq need to be covered, since max_seq+1 can overlap
4126 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4127 * overlap, cold/hot inversion happens.
4128 */
4129 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4130 next = lru_gen_from_seq(lrugen->max_seq + 1);
4131
4132 for (type = 0; type < ANON_AND_FILE; type++) {
4133 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4134 enum lru_list lru = type * LRU_INACTIVE_FILE;
4135 long delta = lrugen->nr_pages[prev][type][zone] -
4136 lrugen->nr_pages[next][type][zone];
4137
4138 if (!delta)
4139 continue;
4140
4141 __update_lru_size(lruvec, lru, zone, delta);
4142 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4143 }
4144 }
4145
4146 for (type = 0; type < ANON_AND_FILE; type++)
4147 reset_ctrl_pos(lruvec, type, false);
4148
Yu Zhao430499c2022-09-18 02:00:08 -06004149 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhao37397872022-09-18 02:00:03 -06004150 /* make sure preceding modifications appear */
4151 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004152
Yu Zhao37397872022-09-18 02:00:03 -06004153 spin_unlock_irq(&lruvec->lru_lock);
4154}
4155
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004156static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
Yu Zhao4983c522022-09-18 02:00:09 -06004157 struct scan_control *sc, bool can_swap, bool force_scan)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004158{
4159 bool success;
4160 struct lru_gen_mm_walk *walk;
4161 struct mm_struct *mm = NULL;
4162 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4163
4164 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4165
4166 /* see the comment in iterate_mm_list() */
4167 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4168 success = false;
4169 goto done;
4170 }
4171
4172 /*
4173 * If the hardware doesn't automatically set the accessed bit, fallback
4174 * to lru_gen_look_around(), which only clears the accessed bit in a
4175 * handful of PTEs. Spreading the work out over a period of time usually
4176 * is less efficient, but it avoids bursty page faults.
4177 */
Yu Zhao4983c522022-09-18 02:00:09 -06004178 if (!force_scan && !(arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004179 success = iterate_mm_list_nowalk(lruvec, max_seq);
4180 goto done;
4181 }
4182
4183 walk = set_mm_walk(NULL);
4184 if (!walk) {
4185 success = iterate_mm_list_nowalk(lruvec, max_seq);
4186 goto done;
4187 }
4188
4189 walk->lruvec = lruvec;
4190 walk->max_seq = max_seq;
4191 walk->can_swap = can_swap;
Yu Zhao4983c522022-09-18 02:00:09 -06004192 walk->force_scan = force_scan;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004193
4194 do {
4195 success = iterate_mm_list(lruvec, walk, &mm);
4196 if (mm)
4197 walk_mm(lruvec, mm, walk);
4198
4199 cond_resched();
4200 } while (mm);
4201done:
4202 if (!success) {
4203 if (sc->priority <= DEF_PRIORITY - 2)
4204 wait_event_killable(lruvec->mm_state.wait,
4205 max_seq < READ_ONCE(lrugen->max_seq));
4206
4207 return max_seq < READ_ONCE(lrugen->max_seq);
4208 }
4209
4210 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4211
Yu Zhao4983c522022-09-18 02:00:09 -06004212 inc_max_seq(lruvec, can_swap, force_scan);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004213 /* either this sees any waiters or they will see updated max_seq */
4214 if (wq_has_sleeper(&lruvec->mm_state.wait))
4215 wake_up_all(&lruvec->mm_state.wait);
4216
4217 return true;
4218}
4219
Yu Zhao37397872022-09-18 02:00:03 -06004220static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
4221 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4222{
4223 int gen, type, zone;
4224 unsigned long old = 0;
4225 unsigned long young = 0;
4226 unsigned long total = 0;
4227 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4228 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4229
4230 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4231 unsigned long seq;
4232
4233 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4234 unsigned long size = 0;
4235
4236 gen = lru_gen_from_seq(seq);
4237
4238 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4239 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4240
4241 total += size;
4242 if (seq == max_seq)
4243 young += size;
4244 else if (seq + MIN_NR_GENS == max_seq)
4245 old += size;
4246 }
4247 }
4248
4249 /* try to scrape all its memory if this memcg was deleted */
4250 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4251
4252 /*
4253 * The aging tries to be lazy to reduce the overhead, while the eviction
4254 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4255 * ideal number of generations is MIN_NR_GENS+1.
4256 */
4257 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
4258 return true;
4259 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4260 return false;
4261
4262 /*
4263 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4264 * of the total number of pages for each generation. A reasonable range
4265 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4266 * aging cares about the upper bound of hot pages, while the eviction
4267 * cares about the lower bound of cold pages.
4268 */
4269 if (young * MIN_NR_GENS > total)
4270 return true;
4271 if (old * (MIN_NR_GENS + 2) < total)
4272 return true;
4273
4274 return false;
4275}
4276
Yu Zhao430499c2022-09-18 02:00:08 -06004277static bool age_lruvec(struct lruvec *lruvec, struct scan_control *sc, unsigned long min_ttl)
Yu Zhao37397872022-09-18 02:00:03 -06004278{
4279 bool need_aging;
4280 unsigned long nr_to_scan;
4281 int swappiness = get_swappiness(lruvec, sc);
4282 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4283 DEFINE_MAX_SEQ(lruvec);
4284 DEFINE_MIN_SEQ(lruvec);
4285
4286 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
4287
4288 mem_cgroup_calculate_protection(NULL, memcg);
4289
4290 if (mem_cgroup_below_min(memcg))
Yu Zhao430499c2022-09-18 02:00:08 -06004291 return false;
Yu Zhao37397872022-09-18 02:00:03 -06004292
4293 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
Yu Zhao430499c2022-09-18 02:00:08 -06004294
4295 if (min_ttl) {
4296 int gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4297 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4298
4299 if (time_is_after_jiffies(birth + min_ttl))
4300 return false;
4301
4302 /* the size is likely too small to be helpful */
4303 if (!nr_to_scan && sc->priority != DEF_PRIORITY)
4304 return false;
4305 }
4306
Yu Zhao37397872022-09-18 02:00:03 -06004307 if (need_aging)
Yu Zhao4983c522022-09-18 02:00:09 -06004308 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
Yu Zhao430499c2022-09-18 02:00:08 -06004309
4310 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004311}
4312
Yu Zhao430499c2022-09-18 02:00:08 -06004313/* to protect the working set of the last N jiffies */
4314static unsigned long lru_gen_min_ttl __read_mostly;
4315
Yu Zhao37397872022-09-18 02:00:03 -06004316static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4317{
4318 struct mem_cgroup *memcg;
Yu Zhao430499c2022-09-18 02:00:08 -06004319 bool success = false;
4320 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhao37397872022-09-18 02:00:03 -06004321
4322 VM_WARN_ON_ONCE(!current_is_kswapd());
4323
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004324 sc->last_reclaimed = sc->nr_reclaimed;
4325
4326 /*
4327 * To reduce the chance of going into the aging path, which can be
4328 * costly, optimistically skip it if the flag below was cleared in the
4329 * eviction path. This improves the overall performance when multiple
4330 * memcgs are available.
4331 */
4332 if (!sc->memcgs_need_aging) {
4333 sc->memcgs_need_aging = true;
4334 return;
4335 }
4336
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004337 set_mm_walk(pgdat);
4338
Yu Zhao37397872022-09-18 02:00:03 -06004339 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4340 do {
4341 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4342
Yu Zhao430499c2022-09-18 02:00:08 -06004343 if (age_lruvec(lruvec, sc, min_ttl))
4344 success = true;
Yu Zhao37397872022-09-18 02:00:03 -06004345
4346 cond_resched();
4347 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004348
4349 clear_mm_walk();
Yu Zhao430499c2022-09-18 02:00:08 -06004350
4351 /* check the order to exclude compaction-induced reclaim */
4352 if (success || !min_ttl || sc->order)
4353 return;
4354
4355 /*
4356 * The main goal is to OOM kill if every generation from all memcgs is
4357 * younger than min_ttl. However, another possibility is all memcgs are
4358 * either below min or empty.
4359 */
4360 if (mutex_trylock(&oom_lock)) {
4361 struct oom_control oc = {
4362 .gfp_mask = sc->gfp_mask,
4363 };
4364
4365 out_of_memory(&oc);
4366
4367 mutex_unlock(&oom_lock);
4368 }
Yu Zhao37397872022-09-18 02:00:03 -06004369}
4370
Yu Zhao0182f922022-09-18 02:00:04 -06004371/*
4372 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004373 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4374 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4375 * the PTE table to the Bloom filter. This forms a feedback loop between the
4376 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004377 */
4378void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4379{
4380 int i;
4381 pte_t *pte;
4382 unsigned long start;
4383 unsigned long end;
4384 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004385 struct lru_gen_mm_walk *walk;
4386 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004387 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4388 struct page *page = pvmw->page;
4389 struct mem_cgroup *memcg = page_memcg(page);
4390 struct pglist_data *pgdat = page_pgdat(page);
4391 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4392 DEFINE_MAX_SEQ(lruvec);
4393 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4394
4395 lockdep_assert_held(pvmw->ptl);
4396 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4397
4398 if (spin_is_contended(pvmw->ptl))
4399 return;
4400
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004401 /* avoid taking the LRU lock under the PTL when possible */
4402 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4403
Yu Zhao0182f922022-09-18 02:00:04 -06004404 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4405 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4406
4407 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4408 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4409 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4410 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4411 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4412 else {
4413 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4414 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4415 }
4416 }
4417
4418 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4419
4420 rcu_read_lock();
4421 arch_enter_lazy_mmu_mode();
4422
4423 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4424 unsigned long pfn;
4425
4426 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4427 if (pfn == -1)
4428 continue;
4429
4430 if (!pte_young(pte[i]))
4431 continue;
4432
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004433 page = get_pfn_page(pfn, memcg, pgdat, !walk || walk->can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004434 if (!page)
4435 continue;
4436
4437 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4438 VM_WARN_ON_ONCE(true);
4439
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004440 young++;
4441
Yu Zhao0182f922022-09-18 02:00:04 -06004442 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4443 !(PageAnon(page) && PageSwapBacked(page) &&
4444 !PageSwapCache(page)))
4445 set_page_dirty(page);
4446
4447 old_gen = page_lru_gen(page);
4448 if (old_gen < 0)
4449 SetPageReferenced(page);
4450 else if (old_gen != new_gen)
4451 __set_bit(i, bitmap);
4452 }
4453
4454 arch_leave_lazy_mmu_mode();
4455 rcu_read_unlock();
4456
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004457 /* feedback from rmap walkers to page table walkers */
4458 if (suitable_to_scan(i, young))
4459 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4460
4461 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004462 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4463 page = pte_page(pte[i]);
4464 activate_page(page);
4465 }
4466 return;
4467 }
4468
4469 /* page_update_gen() requires stable page_memcg() */
4470 if (!mem_cgroup_trylock_pages(memcg))
4471 return;
4472
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004473 if (!walk) {
4474 spin_lock_irq(&lruvec->lru_lock);
4475 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4476 }
Yu Zhao0182f922022-09-18 02:00:04 -06004477
4478 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4479 page = compound_head(pte_page(pte[i]));
4480 if (page_memcg_rcu(page) != memcg)
4481 continue;
4482
4483 old_gen = page_update_gen(page, new_gen);
4484 if (old_gen < 0 || old_gen == new_gen)
4485 continue;
4486
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004487 if (walk)
4488 update_batch_size(walk, page, old_gen, new_gen);
4489 else
4490 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004491 }
4492
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004493 if (!walk)
4494 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004495
4496 mem_cgroup_unlock_pages();
4497}
4498
Yu Zhao37397872022-09-18 02:00:03 -06004499/******************************************************************************
4500 * the eviction
4501 ******************************************************************************/
4502
4503static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4504{
4505 bool success;
4506 int gen = page_lru_gen(page);
4507 int type = page_is_file_lru(page);
4508 int zone = page_zonenum(page);
4509 int delta = thp_nr_pages(page);
4510 int refs = page_lru_refs(page);
4511 int tier = lru_tier_from_refs(refs);
4512 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4513
4514 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4515
4516 /* unevictable */
4517 if (!page_evictable(page)) {
4518 success = lru_gen_del_page(lruvec, page, true);
4519 VM_WARN_ON_ONCE_PAGE(!success, page);
4520 SetPageUnevictable(page);
4521 add_page_to_lru_list(page, lruvec);
4522 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4523 return true;
4524 }
4525
4526 /* dirty lazyfree */
4527 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4528 success = lru_gen_del_page(lruvec, page, true);
4529 VM_WARN_ON_ONCE_PAGE(!success, page);
4530 SetPageSwapBacked(page);
4531 add_page_to_lru_list_tail(page, lruvec);
4532 return true;
4533 }
4534
Yu Zhao0182f922022-09-18 02:00:04 -06004535 /* promoted */
4536 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4537 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4538 return true;
4539 }
4540
Yu Zhao37397872022-09-18 02:00:03 -06004541 /* protected */
4542 if (tier > tier_idx) {
4543 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4544
4545 gen = page_inc_gen(lruvec, page, false);
4546 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4547
4548 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4549 lrugen->protected[hist][type][tier - 1] + delta);
4550 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4551 return true;
4552 }
4553
4554 /* waiting for writeback */
4555 if (PageLocked(page) || PageWriteback(page) ||
4556 (type == LRU_GEN_FILE && PageDirty(page))) {
4557 gen = page_inc_gen(lruvec, page, true);
4558 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4559 return true;
4560 }
4561
4562 return false;
4563}
4564
4565static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4566{
4567 bool success;
4568
4569 /* unmapping inhibited */
4570 if (!sc->may_unmap && page_mapped(page))
4571 return false;
4572
4573 /* swapping inhibited */
4574 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4575 (PageDirty(page) ||
4576 (PageAnon(page) && !PageSwapCache(page))))
4577 return false;
4578
4579 /* raced with release_pages() */
4580 if (!get_page_unless_zero(page))
4581 return false;
4582
4583 /* raced with another isolation */
4584 if (!TestClearPageLRU(page)) {
4585 put_page(page);
4586 return false;
4587 }
4588
4589 /* see the comment on MAX_NR_TIERS */
4590 if (!PageReferenced(page))
4591 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4592
4593 /* for shrink_page_list() */
4594 ClearPageReclaim(page);
4595 ClearPageReferenced(page);
4596
4597 success = lru_gen_del_page(lruvec, page, true);
4598 VM_WARN_ON_ONCE_PAGE(!success, page);
4599
4600 return true;
4601}
4602
4603static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4604 int type, int tier, struct list_head *list)
4605{
4606 int gen, zone;
4607 enum vm_event_item item;
4608 int sorted = 0;
4609 int scanned = 0;
4610 int isolated = 0;
4611 int remaining = MAX_LRU_BATCH;
4612 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4613 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4614
4615 VM_WARN_ON_ONCE(!list_empty(list));
4616
4617 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4618 return 0;
4619
4620 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4621
4622 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4623 LIST_HEAD(moved);
4624 int skipped = 0;
4625 struct list_head *head = &lrugen->lists[gen][type][zone];
4626
4627 while (!list_empty(head)) {
4628 struct page *page = lru_to_page(head);
4629 int delta = thp_nr_pages(page);
4630
4631 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4632 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4633 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4634 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4635
4636 scanned += delta;
4637
4638 if (sort_page(lruvec, page, tier))
4639 sorted += delta;
4640 else if (isolate_page(lruvec, page, sc)) {
4641 list_add(&page->lru, list);
4642 isolated += delta;
4643 } else {
4644 list_move(&page->lru, &moved);
4645 skipped += delta;
4646 }
4647
4648 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4649 break;
4650 }
4651
4652 if (skipped) {
4653 list_splice(&moved, head);
4654 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4655 }
4656
4657 if (!remaining || isolated >= MIN_LRU_BATCH)
4658 break;
4659 }
4660
4661 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4662 if (!cgroup_reclaim(sc)) {
4663 __count_vm_events(item, isolated);
4664 __count_vm_events(PGREFILL, sorted);
4665 }
4666 __count_memcg_events(memcg, item, isolated);
4667 __count_memcg_events(memcg, PGREFILL, sorted);
4668 __count_vm_events(PGSCAN_ANON + type, isolated);
4669
4670 /*
4671 * There might not be eligible pages due to reclaim_idx, may_unmap and
4672 * may_writepage. Check the remaining to prevent livelock if it's not
4673 * making progress.
4674 */
4675 return isolated || !remaining ? scanned : 0;
4676}
4677
4678static int get_tier_idx(struct lruvec *lruvec, int type)
4679{
4680 int tier;
4681 struct ctrl_pos sp, pv;
4682
4683 /*
4684 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4685 * This value is chosen because any other tier would have at least twice
4686 * as many refaults as the first tier.
4687 */
4688 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4689 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4690 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4691 if (!positive_ctrl_err(&sp, &pv))
4692 break;
4693 }
4694
4695 return tier - 1;
4696}
4697
4698static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4699{
4700 int type, tier;
4701 struct ctrl_pos sp, pv;
4702 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4703
4704 /*
4705 * Compare the first tier of anon with that of file to determine which
4706 * type to scan. Also need to compare other tiers of the selected type
4707 * with the first tier of the other type to determine the last tier (of
4708 * the selected type) to evict.
4709 */
4710 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4711 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4712 type = positive_ctrl_err(&sp, &pv);
4713
4714 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4715 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4716 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4717 if (!positive_ctrl_err(&sp, &pv))
4718 break;
4719 }
4720
4721 *tier_idx = tier - 1;
4722
4723 return type;
4724}
4725
4726static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4727 int *type_scanned, struct list_head *list)
4728{
4729 int i;
4730 int type;
4731 int scanned;
4732 int tier = -1;
4733 DEFINE_MIN_SEQ(lruvec);
4734
4735 /*
4736 * Try to make the obvious choice first. When anon and file are both
4737 * available from the same generation, interpret swappiness 1 as file
4738 * first and 200 as anon first.
4739 */
4740 if (!swappiness)
4741 type = LRU_GEN_FILE;
4742 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4743 type = LRU_GEN_ANON;
4744 else if (swappiness == 1)
4745 type = LRU_GEN_FILE;
4746 else if (swappiness == 200)
4747 type = LRU_GEN_ANON;
4748 else
4749 type = get_type_to_scan(lruvec, swappiness, &tier);
4750
4751 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4752 if (tier < 0)
4753 tier = get_tier_idx(lruvec, type);
4754
4755 scanned = scan_pages(lruvec, sc, type, tier, list);
4756 if (scanned)
4757 break;
4758
4759 type = !type;
4760 tier = -1;
4761 }
4762
4763 *type_scanned = type;
4764
4765 return scanned;
4766}
4767
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004768static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4769 bool *need_swapping)
Yu Zhao37397872022-09-18 02:00:03 -06004770{
4771 int type;
4772 int scanned;
4773 int reclaimed;
4774 LIST_HEAD(list);
4775 struct page *page;
4776 enum vm_event_item item;
4777 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004778 struct lru_gen_mm_walk *walk;
Yu Zhao37397872022-09-18 02:00:03 -06004779 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4780 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4781
4782 spin_lock_irq(&lruvec->lru_lock);
4783
4784 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4785
4786 scanned += try_to_inc_min_seq(lruvec, swappiness);
4787
4788 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4789 scanned = 0;
4790
4791 spin_unlock_irq(&lruvec->lru_lock);
4792
4793 if (list_empty(&list))
4794 return scanned;
4795
4796 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4797
4798 list_for_each_entry(page, &list, lru) {
4799 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4800 if (PageWorkingset(page))
4801 SetPageReferenced(page);
4802
4803 /* don't add rejected pages to the oldest generation */
4804 if (PageReclaim(page) &&
4805 (PageDirty(page) || PageWriteback(page)))
4806 ClearPageActive(page);
4807 else
4808 SetPageActive(page);
4809 }
4810
4811 spin_lock_irq(&lruvec->lru_lock);
4812
4813 move_pages_to_lru(lruvec, &list);
4814
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004815 walk = current->reclaim_state->mm_walk;
4816 if (walk && walk->batched)
4817 reset_batch_size(lruvec, walk);
4818
Yu Zhao37397872022-09-18 02:00:03 -06004819 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4820 if (!cgroup_reclaim(sc))
4821 __count_vm_events(item, reclaimed);
4822 __count_memcg_events(memcg, item, reclaimed);
4823 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4824
4825 spin_unlock_irq(&lruvec->lru_lock);
4826
4827 mem_cgroup_uncharge_list(&list);
4828 free_unref_page_list(&list);
4829
4830 sc->nr_reclaimed += reclaimed;
4831
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004832 if (need_swapping && type == LRU_GEN_ANON)
4833 *need_swapping = true;
4834
Yu Zhao37397872022-09-18 02:00:03 -06004835 return scanned;
4836}
4837
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004838/*
4839 * For future optimizations:
4840 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4841 * reclaim.
4842 */
Yu Zhao37397872022-09-18 02:00:03 -06004843static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004844 bool can_swap, bool *need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004845{
Yu Zhao37397872022-09-18 02:00:03 -06004846 unsigned long nr_to_scan;
4847 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4848 DEFINE_MAX_SEQ(lruvec);
4849 DEFINE_MIN_SEQ(lruvec);
4850
4851 if (mem_cgroup_below_min(memcg) ||
4852 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4853 return 0;
4854
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004855 *need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
4856 if (!*need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004857 return nr_to_scan;
4858
4859 /* skip the aging path at the default priority */
4860 if (sc->priority == DEF_PRIORITY)
4861 goto done;
4862
4863 /* leave the work to lru_gen_age_node() */
4864 if (current_is_kswapd())
4865 return 0;
4866
Yu Zhao4983c522022-09-18 02:00:09 -06004867 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004868 return nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004869done:
4870 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
4871}
4872
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004873static bool should_abort_scan(struct lruvec *lruvec, unsigned long seq,
4874 struct scan_control *sc, bool need_swapping)
4875{
4876 int i;
4877 DEFINE_MAX_SEQ(lruvec);
4878
4879 if (!current_is_kswapd()) {
4880 /* age each memcg at most once to ensure fairness */
4881 if (max_seq - seq > 1)
4882 return true;
4883
4884 /* over-swapping can increase allocation latency */
4885 if (sc->nr_reclaimed >= sc->nr_to_reclaim && need_swapping)
4886 return true;
4887
4888 /* give this thread a chance to exit and free its memory */
4889 if (fatal_signal_pending(current)) {
4890 sc->nr_reclaimed += MIN_LRU_BATCH;
4891 return true;
4892 }
4893
4894 if (cgroup_reclaim(sc))
4895 return false;
4896 } else if (sc->nr_reclaimed - sc->last_reclaimed < sc->nr_to_reclaim)
4897 return false;
4898
4899 /* keep scanning at low priorities to ensure fairness */
4900 if (sc->priority > DEF_PRIORITY - 2)
4901 return false;
4902
4903 /*
4904 * A minimum amount of work was done under global memory pressure. For
4905 * kswapd, it may be overshooting. For direct reclaim, the allocation
4906 * may succeed if all suitable zones are somewhat safe. In either case,
4907 * it's better to stop now, and restart later if necessary.
4908 */
4909 for (i = 0; i <= sc->reclaim_idx; i++) {
4910 unsigned long wmark;
4911 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
4912
4913 if (!managed_zone(zone))
4914 continue;
4915
4916 wmark = current_is_kswapd() ? high_wmark_pages(zone) : low_wmark_pages(zone);
4917 if (wmark > zone_page_state(zone, NR_FREE_PAGES))
4918 return false;
4919 }
4920
4921 sc->nr_reclaimed += MIN_LRU_BATCH;
4922
4923 return true;
4924}
4925
Yu Zhao37397872022-09-18 02:00:03 -06004926static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4927{
4928 struct blk_plug plug;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004929 bool need_aging = false;
4930 bool need_swapping = false;
Yu Zhao37397872022-09-18 02:00:03 -06004931 unsigned long scanned = 0;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004932 unsigned long reclaimed = sc->nr_reclaimed;
4933 DEFINE_MAX_SEQ(lruvec);
Yu Zhao37397872022-09-18 02:00:03 -06004934
4935 lru_add_drain();
4936
4937 blk_start_plug(&plug);
4938
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004939 set_mm_walk(lruvec_pgdat(lruvec));
4940
Yu Zhao37397872022-09-18 02:00:03 -06004941 while (true) {
4942 int delta;
4943 int swappiness;
4944 unsigned long nr_to_scan;
4945
4946 if (sc->may_swap)
4947 swappiness = get_swappiness(lruvec, sc);
4948 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4949 swappiness = 1;
4950 else
4951 swappiness = 0;
4952
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004953 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, &need_aging);
Yu Zhao37397872022-09-18 02:00:03 -06004954 if (!nr_to_scan)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004955 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004956
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004957 delta = evict_pages(lruvec, sc, swappiness, &need_swapping);
Yu Zhao37397872022-09-18 02:00:03 -06004958 if (!delta)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004959 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004960
4961 scanned += delta;
4962 if (scanned >= nr_to_scan)
4963 break;
4964
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004965 if (should_abort_scan(lruvec, max_seq, sc, need_swapping))
4966 break;
4967
Yu Zhao37397872022-09-18 02:00:03 -06004968 cond_resched();
4969 }
4970
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004971 /* see the comment in lru_gen_age_node() */
4972 if (sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH && !need_aging)
4973 sc->memcgs_need_aging = false;
4974done:
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004975 clear_mm_walk();
4976
Yu Zhao37397872022-09-18 02:00:03 -06004977 blk_finish_plug(&plug);
4978}
4979
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004980/******************************************************************************
Yu Zhaobaeb9a02022-09-18 02:00:07 -06004981 * state change
4982 ******************************************************************************/
4983
4984static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
4985{
4986 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4987
4988 if (lrugen->enabled) {
4989 enum lru_list lru;
4990
4991 for_each_evictable_lru(lru) {
4992 if (!list_empty(&lruvec->lists[lru]))
4993 return false;
4994 }
4995 } else {
4996 int gen, type, zone;
4997
4998 for_each_gen_type_zone(gen, type, zone) {
4999 if (!list_empty(&lrugen->lists[gen][type][zone]))
5000 return false;
5001 }
5002 }
5003
5004 return true;
5005}
5006
5007static bool fill_evictable(struct lruvec *lruvec)
5008{
5009 enum lru_list lru;
5010 int remaining = MAX_LRU_BATCH;
5011
5012 for_each_evictable_lru(lru) {
5013 int type = is_file_lru(lru);
5014 bool active = is_active_lru(lru);
5015 struct list_head *head = &lruvec->lists[lru];
5016
5017 while (!list_empty(head)) {
5018 bool success;
5019 struct page *page = lru_to_page(head);
5020
5021 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5022 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
5023 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5024 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
5025
5026 del_page_from_lru_list(page, lruvec);
5027 success = lru_gen_add_page(lruvec, page, false);
5028 VM_WARN_ON_ONCE(!success);
5029
5030 if (!--remaining)
5031 return false;
5032 }
5033 }
5034
5035 return true;
5036}
5037
5038static bool drain_evictable(struct lruvec *lruvec)
5039{
5040 int gen, type, zone;
5041 int remaining = MAX_LRU_BATCH;
5042
5043 for_each_gen_type_zone(gen, type, zone) {
5044 struct list_head *head = &lruvec->lrugen.lists[gen][type][zone];
5045
5046 while (!list_empty(head)) {
5047 bool success;
5048 struct page *page = lru_to_page(head);
5049
5050 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5051 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5052 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5053 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5054
5055 success = lru_gen_del_page(lruvec, page, false);
5056 VM_WARN_ON_ONCE(!success);
5057 add_page_to_lru_list(page, lruvec);
5058
5059 if (!--remaining)
5060 return false;
5061 }
5062 }
5063
5064 return true;
5065}
5066
5067static void lru_gen_change_state(bool enabled)
5068{
5069 static DEFINE_MUTEX(state_mutex);
5070
5071 struct mem_cgroup *memcg;
5072
5073 cgroup_lock();
5074 cpus_read_lock();
5075 get_online_mems();
5076 mutex_lock(&state_mutex);
5077
5078 if (enabled == lru_gen_enabled())
5079 goto unlock;
5080
5081 if (enabled)
5082 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5083 else
5084 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5085
5086 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5087 do {
5088 int nid;
5089
5090 for_each_node(nid) {
5091 struct lruvec *lruvec = get_lruvec(memcg, nid);
5092
5093 if (!lruvec)
5094 continue;
5095
5096 spin_lock_irq(&lruvec->lru_lock);
5097
5098 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5099 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5100
5101 lruvec->lrugen.enabled = enabled;
5102
5103 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5104 spin_unlock_irq(&lruvec->lru_lock);
5105 cond_resched();
5106 spin_lock_irq(&lruvec->lru_lock);
5107 }
5108
5109 spin_unlock_irq(&lruvec->lru_lock);
5110 }
5111
5112 cond_resched();
5113 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5114unlock:
5115 mutex_unlock(&state_mutex);
5116 put_online_mems();
5117 cpus_read_unlock();
5118 cgroup_unlock();
5119}
5120
5121/******************************************************************************
5122 * sysfs interface
5123 ******************************************************************************/
5124
Yu Zhao430499c2022-09-18 02:00:08 -06005125static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5126{
5127 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5128}
5129
Yu Zhao642d9862022-09-18 02:00:10 -06005130/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao430499c2022-09-18 02:00:08 -06005131static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5132 const char *buf, size_t len)
5133{
5134 unsigned int msecs;
5135
5136 if (kstrtouint(buf, 0, &msecs))
5137 return -EINVAL;
5138
5139 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5140
5141 return len;
5142}
5143
5144static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5145 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5146);
5147
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005148static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5149{
5150 unsigned int caps = 0;
5151
5152 if (get_cap(LRU_GEN_CORE))
5153 caps |= BIT(LRU_GEN_CORE);
5154
5155 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5156 caps |= BIT(LRU_GEN_MM_WALK);
5157
5158 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
5159 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5160
5161 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5162}
5163
Yu Zhao642d9862022-09-18 02:00:10 -06005164/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005165static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5166 const char *buf, size_t len)
5167{
5168 int i;
5169 unsigned int caps;
5170
5171 if (tolower(*buf) == 'n')
5172 caps = 0;
5173 else if (tolower(*buf) == 'y')
5174 caps = -1;
5175 else if (kstrtouint(buf, 0, &caps))
5176 return -EINVAL;
5177
5178 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5179 bool enabled = caps & BIT(i);
5180
5181 if (i == LRU_GEN_CORE)
5182 lru_gen_change_state(enabled);
5183 else if (enabled)
5184 static_branch_enable(&lru_gen_caps[i]);
5185 else
5186 static_branch_disable(&lru_gen_caps[i]);
5187 }
5188
5189 return len;
5190}
5191
5192static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5193 enabled, 0644, show_enabled, store_enabled
5194);
5195
5196static struct attribute *lru_gen_attrs[] = {
Yu Zhao430499c2022-09-18 02:00:08 -06005197 &lru_gen_min_ttl_attr.attr,
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005198 &lru_gen_enabled_attr.attr,
5199 NULL
5200};
5201
5202static struct attribute_group lru_gen_attr_group = {
5203 .name = "lru_gen",
5204 .attrs = lru_gen_attrs,
5205};
5206
5207/******************************************************************************
Yu Zhao4983c522022-09-18 02:00:09 -06005208 * debugfs interface
5209 ******************************************************************************/
5210
5211static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5212{
5213 struct mem_cgroup *memcg;
5214 loff_t nr_to_skip = *pos;
5215
5216 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5217 if (!m->private)
5218 return ERR_PTR(-ENOMEM);
5219
5220 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5221 do {
5222 int nid;
5223
5224 for_each_node_state(nid, N_MEMORY) {
5225 if (!nr_to_skip--)
5226 return get_lruvec(memcg, nid);
5227 }
5228 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5229
5230 return NULL;
5231}
5232
5233static void lru_gen_seq_stop(struct seq_file *m, void *v)
5234{
5235 if (!IS_ERR_OR_NULL(v))
5236 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5237
5238 kvfree(m->private);
5239 m->private = NULL;
5240}
5241
5242static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5243{
5244 int nid = lruvec_pgdat(v)->node_id;
5245 struct mem_cgroup *memcg = lruvec_memcg(v);
5246
5247 ++*pos;
5248
5249 nid = next_memory_node(nid);
5250 if (nid == MAX_NUMNODES) {
5251 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5252 if (!memcg)
5253 return NULL;
5254
5255 nid = first_memory_node;
5256 }
5257
5258 return get_lruvec(memcg, nid);
5259}
5260
5261static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5262 unsigned long max_seq, unsigned long *min_seq,
5263 unsigned long seq)
5264{
5265 int i;
5266 int type, tier;
5267 int hist = lru_hist_from_seq(seq);
5268 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5269
5270 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5271 seq_printf(m, " %10d", tier);
5272 for (type = 0; type < ANON_AND_FILE; type++) {
5273 const char *s = " ";
5274 unsigned long n[3] = {};
5275
5276 if (seq == max_seq) {
5277 s = "RT ";
5278 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5279 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5280 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5281 s = "rep";
5282 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5283 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5284 if (tier)
5285 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5286 }
5287
5288 for (i = 0; i < 3; i++)
5289 seq_printf(m, " %10lu%c", n[i], s[i]);
5290 }
5291 seq_putc(m, '\n');
5292 }
5293
5294 seq_puts(m, " ");
5295 for (i = 0; i < NR_MM_STATS; i++) {
5296 const char *s = " ";
5297 unsigned long n = 0;
5298
5299 if (seq == max_seq && NR_HIST_GENS == 1) {
5300 s = "LOYNFA";
5301 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5302 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5303 s = "loynfa";
5304 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5305 }
5306
5307 seq_printf(m, " %10lu%c", n, s[i]);
5308 }
5309 seq_putc(m, '\n');
5310}
5311
Yu Zhao642d9862022-09-18 02:00:10 -06005312/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005313static int lru_gen_seq_show(struct seq_file *m, void *v)
5314{
5315 unsigned long seq;
5316 bool full = !debugfs_real_fops(m->file)->write;
5317 struct lruvec *lruvec = v;
5318 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5319 int nid = lruvec_pgdat(lruvec)->node_id;
5320 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5321 DEFINE_MAX_SEQ(lruvec);
5322 DEFINE_MIN_SEQ(lruvec);
5323
5324 if (nid == first_memory_node) {
5325 const char *path = memcg ? m->private : "";
5326
5327#ifdef CONFIG_MEMCG
5328 if (memcg)
5329 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5330#endif
5331 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5332 }
5333
5334 seq_printf(m, " node %5d\n", nid);
5335
5336 if (!full)
5337 seq = min_seq[LRU_GEN_ANON];
5338 else if (max_seq >= MAX_NR_GENS)
5339 seq = max_seq - MAX_NR_GENS + 1;
5340 else
5341 seq = 0;
5342
5343 for (; seq <= max_seq; seq++) {
5344 int type, zone;
5345 int gen = lru_gen_from_seq(seq);
5346 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5347
5348 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5349
5350 for (type = 0; type < ANON_AND_FILE; type++) {
5351 unsigned long size = 0;
5352 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5353
5354 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5355 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5356
5357 seq_printf(m, " %10lu%c", size, mark);
5358 }
5359
5360 seq_putc(m, '\n');
5361
5362 if (full)
5363 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5364 }
5365
5366 return 0;
5367}
5368
5369static const struct seq_operations lru_gen_seq_ops = {
5370 .start = lru_gen_seq_start,
5371 .stop = lru_gen_seq_stop,
5372 .next = lru_gen_seq_next,
5373 .show = lru_gen_seq_show,
5374};
5375
5376static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5377 bool can_swap, bool force_scan)
5378{
5379 DEFINE_MAX_SEQ(lruvec);
5380 DEFINE_MIN_SEQ(lruvec);
5381
5382 if (seq < max_seq)
5383 return 0;
5384
5385 if (seq > max_seq)
5386 return -EINVAL;
5387
5388 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5389 return -ERANGE;
5390
5391 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5392
5393 return 0;
5394}
5395
5396static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5397 int swappiness, unsigned long nr_to_reclaim)
5398{
5399 DEFINE_MAX_SEQ(lruvec);
5400
5401 if (seq + MIN_NR_GENS > max_seq)
5402 return -EINVAL;
5403
5404 sc->nr_reclaimed = 0;
5405
5406 while (!signal_pending(current)) {
5407 DEFINE_MIN_SEQ(lruvec);
5408
5409 if (seq < min_seq[!swappiness])
5410 return 0;
5411
5412 if (sc->nr_reclaimed >= nr_to_reclaim)
5413 return 0;
5414
5415 if (!evict_pages(lruvec, sc, swappiness, NULL))
5416 return 0;
5417
5418 cond_resched();
5419 }
5420
5421 return -EINTR;
5422}
5423
5424static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5425 struct scan_control *sc, int swappiness, unsigned long opt)
5426{
5427 struct lruvec *lruvec;
5428 int err = -EINVAL;
5429 struct mem_cgroup *memcg = NULL;
5430
5431 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5432 return -EINVAL;
5433
5434 if (!mem_cgroup_disabled()) {
5435 rcu_read_lock();
5436 memcg = mem_cgroup_from_id(memcg_id);
5437#ifdef CONFIG_MEMCG
5438 if (memcg && !css_tryget(&memcg->css))
5439 memcg = NULL;
5440#endif
5441 rcu_read_unlock();
5442
5443 if (!memcg)
5444 return -EINVAL;
5445 }
5446
5447 if (memcg_id != mem_cgroup_id(memcg))
5448 goto done;
5449
5450 lruvec = get_lruvec(memcg, nid);
5451
5452 if (swappiness < 0)
5453 swappiness = get_swappiness(lruvec, sc);
5454 else if (swappiness > 200)
5455 goto done;
5456
5457 switch (cmd) {
5458 case '+':
5459 err = run_aging(lruvec, seq, sc, swappiness, opt);
5460 break;
5461 case '-':
5462 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5463 break;
5464 }
5465done:
5466 mem_cgroup_put(memcg);
5467
5468 return err;
5469}
5470
Yu Zhao642d9862022-09-18 02:00:10 -06005471/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005472static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5473 size_t len, loff_t *pos)
5474{
5475 void *buf;
5476 char *cur, *next;
5477 unsigned int flags;
5478 struct blk_plug plug;
5479 int err = -EINVAL;
5480 struct scan_control sc = {
5481 .may_writepage = true,
5482 .may_unmap = true,
5483 .may_swap = true,
5484 .reclaim_idx = MAX_NR_ZONES - 1,
5485 .gfp_mask = GFP_KERNEL,
5486 };
5487
5488 buf = kvmalloc(len + 1, GFP_KERNEL);
5489 if (!buf)
5490 return -ENOMEM;
5491
5492 if (copy_from_user(buf, src, len)) {
5493 kvfree(buf);
5494 return -EFAULT;
5495 }
5496
5497 set_task_reclaim_state(current, &sc.reclaim_state);
5498 flags = memalloc_noreclaim_save();
5499 blk_start_plug(&plug);
5500 if (!set_mm_walk(NULL)) {
5501 err = -ENOMEM;
5502 goto done;
5503 }
5504
5505 next = buf;
5506 next[len] = '\0';
5507
5508 while ((cur = strsep(&next, ",;\n"))) {
5509 int n;
5510 int end;
5511 char cmd;
5512 unsigned int memcg_id;
5513 unsigned int nid;
5514 unsigned long seq;
5515 unsigned int swappiness = -1;
5516 unsigned long opt = -1;
5517
5518 cur = skip_spaces(cur);
5519 if (!*cur)
5520 continue;
5521
5522 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5523 &seq, &end, &swappiness, &end, &opt, &end);
5524 if (n < 4 || cur[end]) {
5525 err = -EINVAL;
5526 break;
5527 }
5528
5529 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5530 if (err)
5531 break;
5532 }
5533done:
5534 clear_mm_walk();
5535 blk_finish_plug(&plug);
5536 memalloc_noreclaim_restore(flags);
5537 set_task_reclaim_state(current, NULL);
5538
5539 kvfree(buf);
5540
5541 return err ? : len;
5542}
5543
5544static int lru_gen_seq_open(struct inode *inode, struct file *file)
5545{
5546 return seq_open(file, &lru_gen_seq_ops);
5547}
5548
5549static const struct file_operations lru_gen_rw_fops = {
5550 .open = lru_gen_seq_open,
5551 .read = seq_read,
5552 .write = lru_gen_seq_write,
5553 .llseek = seq_lseek,
5554 .release = seq_release,
5555};
5556
5557static const struct file_operations lru_gen_ro_fops = {
5558 .open = lru_gen_seq_open,
5559 .read = seq_read,
5560 .llseek = seq_lseek,
5561 .release = seq_release,
5562};
5563
5564/******************************************************************************
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005565 * initialization
5566 ******************************************************************************/
5567
5568void lru_gen_init_lruvec(struct lruvec *lruvec)
5569{
Yu Zhao430499c2022-09-18 02:00:08 -06005570 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005571 int gen, type, zone;
5572 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5573
5574 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005575 lrugen->enabled = lru_gen_enabled();
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005576
Yu Zhao430499c2022-09-18 02:00:08 -06005577 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5578 lrugen->timestamps[i] = jiffies;
5579
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005580 for_each_gen_type_zone(gen, type, zone)
5581 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005582
5583 lruvec->mm_state.seq = MIN_NR_GENS;
5584 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005585}
5586
5587#ifdef CONFIG_MEMCG
5588void lru_gen_init_memcg(struct mem_cgroup *memcg)
5589{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005590 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5591 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005592}
5593
5594void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5595{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005596 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005597 int nid;
5598
5599 for_each_node(nid) {
5600 struct lruvec *lruvec = get_lruvec(memcg, nid);
5601
5602 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5603 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005604
5605 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5606 bitmap_free(lruvec->mm_state.filters[i]);
5607 lruvec->mm_state.filters[i] = NULL;
5608 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005609 }
5610}
5611#endif
5612
5613static int __init init_lru_gen(void)
5614{
5615 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5616 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5617
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005618 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5619 pr_err("lru_gen: failed to create sysfs group\n");
5620
Yu Zhao4983c522022-09-18 02:00:09 -06005621 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5622 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5623
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005624 return 0;
5625};
5626late_initcall(init_lru_gen);
5627
Yu Zhao37397872022-09-18 02:00:03 -06005628#else /* !CONFIG_LRU_GEN */
5629
5630static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5631{
5632}
5633
5634static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5635{
5636}
5637
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005638#endif /* CONFIG_LRU_GEN */
5639
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005640static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005641{
5642 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005643 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005644 unsigned long nr_to_scan;
5645 enum lru_list lru;
5646 unsigned long nr_reclaimed = 0;
5647 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005648 bool proportional_reclaim;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005649 struct blk_plug plug;
5650
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
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005675 blk_start_plug(&plug);
5676 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5677 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005678 unsigned long nr_anon, nr_file, percentage;
5679 unsigned long nr_scanned;
5680
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005681 for_each_evictable_lru(lru) {
5682 if (nr[lru]) {
5683 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5684 nr[lru] -= nr_to_scan;
5685
5686 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005687 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005688 }
5689 }
Mel Gormane82e0562013-07-03 15:01:44 -07005690
Michal Hockobd041732016-12-02 17:26:48 -08005691 cond_resched();
5692
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005693 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
Mel Gormane82e0562013-07-03 15:01:44 -07005694 continue;
5695
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005696 /*
Mel Gormane82e0562013-07-03 15:01:44 -07005697 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07005698 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07005699 * proportionally what was requested by get_scan_count(). We
5700 * stop reclaiming one LRU and reduce the amount scanning
5701 * proportional to the original scan target.
5702 */
5703 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5704 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5705
Mel Gorman1a501902014-06-04 16:10:49 -07005706 /*
5707 * It's just vindictive to attack the larger once the smaller
5708 * has gone to zero. And given the way we stop scanning the
5709 * smaller below, this makes sure that we only make one nudge
5710 * towards proportionality once we've got nr_to_reclaim.
5711 */
5712 if (!nr_file || !nr_anon)
5713 break;
5714
Mel Gormane82e0562013-07-03 15:01:44 -07005715 if (nr_file > nr_anon) {
5716 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5717 targets[LRU_ACTIVE_ANON] + 1;
5718 lru = LRU_BASE;
5719 percentage = nr_anon * 100 / scan_target;
5720 } else {
5721 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5722 targets[LRU_ACTIVE_FILE] + 1;
5723 lru = LRU_FILE;
5724 percentage = nr_file * 100 / scan_target;
5725 }
5726
5727 /* Stop scanning the smaller of the LRU */
5728 nr[lru] = 0;
5729 nr[lru + LRU_ACTIVE] = 0;
5730
5731 /*
5732 * Recalculate the other LRU scan count based on its original
5733 * scan target and the percentage scanning already complete
5734 */
5735 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5736 nr_scanned = targets[lru] - nr[lru];
5737 nr[lru] = targets[lru] * (100 - percentage) / 100;
5738 nr[lru] -= min(nr[lru], nr_scanned);
5739
5740 lru += LRU_ACTIVE;
5741 nr_scanned = targets[lru] - nr[lru];
5742 nr[lru] = targets[lru] * (100 - percentage) / 100;
5743 nr[lru] -= min(nr[lru], nr_scanned);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005744 }
5745 blk_finish_plug(&plug);
5746 sc->nr_reclaimed += nr_reclaimed;
5747
5748 /*
5749 * Even if we did not try to evict anon pages at all, we want to
5750 * rebalance the anon lru active/inactive ratio.
5751 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005752 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5753 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005754 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5755 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005756}
5757
Mel Gorman23b9da52012-05-29 15:06:20 -07005758/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005759static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005760{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005761 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005762 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005763 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005764 return true;
5765
5766 return false;
5767}
5768
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005769/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005770 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5771 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5772 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005773 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005774 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005775 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005776static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005777 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005778 struct scan_control *sc)
5779{
5780 unsigned long pages_for_compaction;
5781 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005782 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005783
5784 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005785 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005786 return false;
5787
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005788 /*
5789 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5790 * number of pages that were scanned. This will return to the caller
5791 * with the risk reclaim/compaction and the resulting allocation attempt
5792 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5793 * allocations through requiring that the full LRU list has been scanned
5794 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5795 * scan, but that approximation was wrong, and there were corner cases
5796 * where always a non-zero amount of pages were scanned.
5797 */
5798 if (!nr_reclaimed)
5799 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005800
Mel Gorman3e7d3442011-01-13 15:45:56 -08005801 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005802 for (z = 0; z <= sc->reclaim_idx; z++) {
5803 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005804 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005805 continue;
5806
5807 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005808 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005809 case COMPACT_CONTINUE:
5810 return false;
5811 default:
5812 /* check next zone */
5813 ;
5814 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005815 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005816
5817 /*
5818 * If we have not reclaimed enough pages for compaction and the
5819 * inactive lists are large enough, continue reclaiming
5820 */
5821 pages_for_compaction = compact_gap(sc->order);
5822 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005823 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005824 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5825
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005826 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005827}
5828
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005829static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005830{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005831 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005832 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005833
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005834 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005835 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005836 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005837 unsigned long reclaimed;
5838 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005839 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08005840
Xunlei Pange3336ca2020-09-04 16:35:27 -07005841 /*
5842 * This loop can become CPU-bound when target memcgs
5843 * aren't eligible for reclaim - either because they
5844 * don't have any reclaimable pages, or because their
5845 * memory is explicitly protected. Avoid soft lockups.
5846 */
5847 cond_resched();
5848
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005849 trace_android_vh_shrink_node_memcgs(memcg, &skip);
5850 if (skip)
5851 continue;
5852
Chris Down45c7f7e2020-08-06 23:22:05 -07005853 mem_cgroup_calculate_protection(target_memcg, memcg);
5854
5855 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005856 /*
5857 * Hard protection.
5858 * If there is no reclaimable memory, OOM.
5859 */
5860 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005861 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005862 /*
5863 * Soft protection.
5864 * Respect the protection only as long as
5865 * there is an unprotected supply
5866 * of reclaimable memory from other cgroups.
5867 */
5868 if (!sc->memcg_low_reclaim) {
5869 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005870 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005871 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005872 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005873 }
5874
Johannes Weinerd2af3392019-11-30 17:55:43 -08005875 reclaimed = sc->nr_reclaimed;
5876 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005877
5878 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005879
Johannes Weinerd2af3392019-11-30 17:55:43 -08005880 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5881 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005882
Johannes Weinerd2af3392019-11-30 17:55:43 -08005883 /* Record the group's reclaim efficiency */
5884 vmpressure(sc->gfp_mask, memcg, false,
5885 sc->nr_scanned - scanned,
5886 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005887
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005888 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5889}
5890
Liu Song6c9e09072020-01-30 22:14:08 -08005891static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005892{
5893 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005894 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005895 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005896 bool reclaimable = false;
5897
Johannes Weiner1b051172019-11-30 17:55:52 -08005898 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5899
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005900again:
5901 memset(&sc->nr, 0, sizeof(sc->nr));
5902
5903 nr_reclaimed = sc->nr_reclaimed;
5904 nr_scanned = sc->nr_scanned;
5905
Yu Zhao6d313442022-09-18 02:00:00 -06005906 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005907
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005908 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005909
Johannes Weinerd2af3392019-11-30 17:55:43 -08005910 if (reclaim_state) {
5911 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5912 reclaim_state->reclaimed_slab = 0;
5913 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005914
Johannes Weinerd2af3392019-11-30 17:55:43 -08005915 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005916 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005917 sc->nr_scanned - nr_scanned,
5918 sc->nr_reclaimed - nr_reclaimed);
5919
5920 if (sc->nr_reclaimed - nr_reclaimed)
5921 reclaimable = true;
5922
5923 if (current_is_kswapd()) {
5924 /*
5925 * If reclaim is isolating dirty pages under writeback,
5926 * it implies that the long-lived page allocation rate
5927 * is exceeding the page laundering rate. Either the
5928 * global limits are not being effective at throttling
5929 * processes due to the page distribution throughout
5930 * zones or there is heavy usage of a slow backing
5931 * device. The only option is to throttle from reclaim
5932 * context which is not ideal as there is no guarantee
5933 * the dirtying process is throttled in the same way
5934 * balance_dirty_pages() manages.
5935 *
5936 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5937 * count the number of pages under pages flagged for
5938 * immediate reclaim and stall if any are encountered
5939 * in the nr_immediate check below.
5940 */
5941 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5942 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005943
Johannes Weinerd2af3392019-11-30 17:55:43 -08005944 /* Allow kswapd to start writing pages during reclaim.*/
5945 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5946 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005947
5948 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005949 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005950 * reclaim and under writeback (nr_immediate), it
5951 * implies that pages are cycling through the LRU
5952 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005953 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005954 if (sc->nr.immediate)
5955 congestion_wait(BLK_RW_ASYNC, HZ/10);
5956 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005957
Johannes Weinerd2af3392019-11-30 17:55:43 -08005958 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005959 * Tag a node/memcg as congested if all the dirty pages
5960 * scanned were backed by a congested BDI and
5961 * wait_iff_congested will stall.
5962 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005963 * Legacy memcg will stall in page writeback so avoid forcibly
5964 * stalling in wait_iff_congested().
5965 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005966 if ((current_is_kswapd() ||
5967 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005968 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005969 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005970
5971 /*
5972 * Stall direct reclaim for IO completions if underlying BDIs
5973 * and node is congested. Allow kswapd to continue until it
5974 * starts encountering unqueued dirty pages or cycling through
5975 * the LRU too quickly.
5976 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005977 if (!current_is_kswapd() && current_may_throttle() &&
5978 !sc->hibernation_mode &&
5979 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005980 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5981
5982 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5983 sc))
5984 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005985
Johannes Weinerc73322d2017-05-03 14:51:51 -07005986 /*
5987 * Kswapd gives up on balancing particular nodes after too
5988 * many failures to reclaim anything from them and goes to
5989 * sleep. On reclaim progress, reset the failure counter. A
5990 * successful direct reclaim run will revive a dormant kswapd.
5991 */
5992 if (reclaimable)
5993 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005994}
5995
Vlastimil Babka53853e22014-10-09 15:27:02 -07005996/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005997 * Returns true if compaction should go ahead for a costly-order request, or
5998 * the allocation would already succeed without compaction. Return false if we
5999 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07006000 */
Mel Gorman4f588332016-07-28 15:46:38 -07006001static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006002{
Mel Gorman31483b62016-07-28 15:45:46 -07006003 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006004 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006005
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006006 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6007 if (suitable == COMPACT_SUCCESS)
6008 /* Allocation should succeed already. Don't reclaim. */
6009 return true;
6010 if (suitable == COMPACT_SKIPPED)
6011 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006012 return false;
6013
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006014 /*
6015 * Compaction is already possible, but it takes time to run and there
6016 * are potentially other callers using the pages just freed. So proceed
6017 * with reclaim to make a buffer of free pages available to give
6018 * compaction a reasonable chance of completing and allocating the page.
6019 * Note that we won't actually reclaim the whole buffer in one attempt
6020 * as the target watermark in should_continue_reclaim() is lower. But if
6021 * we are already above the high+gap watermark, don't reclaim at all.
6022 */
6023 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6024
6025 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006026}
6027
Linus Torvalds1da177e2005-04-16 15:20:36 -07006028/*
6029 * This is the direct reclaim path, for page-allocating processes. We only
6030 * try to reclaim pages from zones which will satisfy the caller's allocation
6031 * request.
6032 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07006033 * If a zone is deemed to be full of pinned pages then just give it a light
6034 * scan then give up on it.
6035 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07006036static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006037{
Mel Gormandd1a2392008-04-28 02:12:17 -07006038 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07006039 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07006040 unsigned long nr_soft_reclaimed;
6041 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07006042 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07006043 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006044
Mel Gormancc715d92012-03-21 16:34:00 -07006045 /*
6046 * If the number of buffer_heads in the machine exceeds the maximum
6047 * allowed level, force direct reclaim to scan the highmem zone as
6048 * highmem pages could be pinning lowmem pages storing buffer_heads
6049 */
Weijie Yang619d0d762014-04-07 15:36:59 -07006050 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07006051 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07006052 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07006053 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07006054 }
Mel Gormancc715d92012-03-21 16:34:00 -07006055
Mel Gormand4debc62010-08-09 17:19:29 -07006056 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07006057 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07006058 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006059 * Take care memory controller reclaiming has small influence
6060 * to global LRU.
6061 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08006062 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04006063 if (!cpuset_zone_allowed(zone,
6064 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006065 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006066
Johannes Weiner0b064962014-08-06 16:06:12 -07006067 /*
6068 * If we already have plenty of memory free for
6069 * compaction in this zone, don't free any more.
6070 * Even though compaction is invoked for any
6071 * non-zero order, only frequent costly order
6072 * reclamation is disruptive enough to become a
6073 * noticeable problem, like transparent huge
6074 * page allocations.
6075 */
6076 if (IS_ENABLED(CONFIG_COMPACTION) &&
6077 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07006078 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07006079 sc->compaction_ready = true;
6080 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07006081 }
Johannes Weiner0b064962014-08-06 16:06:12 -07006082
Andrew Morton0608f432013-09-24 15:27:41 -07006083 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07006084 * Shrink each node in the zonelist once. If the
6085 * zonelist is ordered by zone (not the default) then a
6086 * node may be shrunk multiple times but in that case
6087 * the user prefers lower zones being preserved.
6088 */
6089 if (zone->zone_pgdat == last_pgdat)
6090 continue;
6091
6092 /*
Andrew Morton0608f432013-09-24 15:27:41 -07006093 * This steals pages from memory cgroups over softlimit
6094 * and returns the number of reclaimed pages and
6095 * scanned pages. This works for global memory pressure
6096 * and balancing, not for a memcg's limit.
6097 */
6098 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006099 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006100 sc->order, sc->gfp_mask,
6101 &nr_soft_scanned);
6102 sc->nr_reclaimed += nr_soft_reclaimed;
6103 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006104 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006105 }
Nick Piggin408d8542006-09-25 23:31:27 -07006106
Mel Gorman79dafcd2016-07-28 15:45:53 -07006107 /* See comment about same check for global reclaim above */
6108 if (zone->zone_pgdat == last_pgdat)
6109 continue;
6110 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006111 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006112 }
Mel Gormane0c23272011-10-31 17:09:33 -07006113
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006114 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006115 * Restore to original mask to avoid the impact on the caller if we
6116 * promoted it to __GFP_HIGHMEM.
6117 */
6118 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006119}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006120
Johannes Weinerb9107182019-11-30 17:55:59 -08006121static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006122{
Johannes Weinerb9107182019-11-30 17:55:59 -08006123 struct lruvec *target_lruvec;
6124 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006125
Yu Zhao37397872022-09-18 02:00:03 -06006126 if (lru_gen_enabled())
6127 return;
6128
Johannes Weinerb9107182019-11-30 17:55:59 -08006129 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006130 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6131 target_lruvec->refaults[0] = refaults;
6132 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6133 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006134}
6135
Linus Torvalds1da177e2005-04-16 15:20:36 -07006136/*
6137 * This is the main entry point to direct page reclaim.
6138 *
6139 * If a full scan of the inactive list fails to free enough memory then we
6140 * are "out of memory" and something needs to be killed.
6141 *
6142 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6143 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006144 * caller can't do much about. We kick the writeback threads and take explicit
6145 * naps in the hope that some of these pages can be written. But if the
6146 * allocating task holds filesystem locks which prevent writeout this might not
6147 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006148 *
6149 * returns: 0, if no pages reclaimed
6150 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006151 */
Mel Gormandac1d272008-04-28 02:12:12 -07006152static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006153 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006154{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006155 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006156 pg_data_t *last_pgdat;
6157 struct zoneref *z;
6158 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006159retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006160 delayacct_freepages_start();
6161
Johannes Weinerb5ead352019-11-30 17:55:40 -08006162 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006163 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006164
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006165 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006166 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6167 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006168 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006169 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006170
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006171 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006172 break;
6173
6174 if (sc->compaction_ready)
6175 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006176
6177 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006178 * If we're getting trouble reclaiming, start doing
6179 * writepage even in laptop mode.
6180 */
6181 if (sc->priority < DEF_PRIORITY - 2)
6182 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006183 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006184
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006185 last_pgdat = NULL;
6186 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6187 sc->nodemask) {
6188 if (zone->zone_pgdat == last_pgdat)
6189 continue;
6190 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006191
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006192 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006193
6194 if (cgroup_reclaim(sc)) {
6195 struct lruvec *lruvec;
6196
6197 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6198 zone->zone_pgdat);
6199 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6200 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006201 }
6202
Keika Kobayashi873b4772008-07-25 01:48:52 -07006203 delayacct_freepages_end();
6204
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006205 if (sc->nr_reclaimed)
6206 return sc->nr_reclaimed;
6207
Mel Gorman0cee34f2012-01-12 17:19:49 -08006208 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006209 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006210 return 1;
6211
Johannes Weinerb91ac372019-11-30 17:56:02 -08006212 /*
6213 * We make inactive:active ratio decisions based on the node's
6214 * composition of memory, but a restrictive reclaim_idx or a
6215 * memory.low cgroup setting can exempt large amounts of
6216 * memory from reclaim. Neither of which are very common, so
6217 * instead of doing costly eligibility calculations of the
6218 * entire cgroup subtree up front, we assume the estimates are
6219 * good, and retry with forcible deactivation if that fails.
6220 */
6221 if (sc->skipped_deactivate) {
6222 sc->priority = initial_priority;
6223 sc->force_deactivate = 1;
6224 sc->skipped_deactivate = 0;
6225 goto retry;
6226 }
6227
Johannes Weiner241994ed2015-02-11 15:26:06 -08006228 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006229 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006230 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006231 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006232 sc->memcg_low_reclaim = 1;
6233 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006234 goto retry;
6235 }
6236
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006237 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006238}
6239
Johannes Weinerc73322d2017-05-03 14:51:51 -07006240static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006241{
6242 struct zone *zone;
6243 unsigned long pfmemalloc_reserve = 0;
6244 unsigned long free_pages = 0;
6245 int i;
6246 bool wmark_ok;
6247
Johannes Weinerc73322d2017-05-03 14:51:51 -07006248 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6249 return true;
6250
Mel Gorman55150612012-07-31 16:44:35 -07006251 for (i = 0; i <= ZONE_NORMAL; i++) {
6252 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006253 if (!managed_zone(zone))
6254 continue;
6255
6256 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006257 continue;
6258
Mel Gorman55150612012-07-31 16:44:35 -07006259 pfmemalloc_reserve += min_wmark_pages(zone);
6260 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6261 }
6262
Mel Gorman675becc2014-06-04 16:07:35 -07006263 /* If there are no reserves (unexpected config) then do not throttle */
6264 if (!pfmemalloc_reserve)
6265 return true;
6266
Mel Gorman55150612012-07-31 16:44:35 -07006267 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6268
6269 /* kswapd must be awake if processes are being throttled */
6270 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006271 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6272 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006273
Mel Gorman55150612012-07-31 16:44:35 -07006274 wake_up_interruptible(&pgdat->kswapd_wait);
6275 }
6276
6277 return wmark_ok;
6278}
6279
6280/*
6281 * Throttle direct reclaimers if backing storage is backed by the network
6282 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6283 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006284 * when the low watermark is reached.
6285 *
6286 * Returns true if a fatal signal was delivered during throttling. If this
6287 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006288 */
Mel Gorman50694c22012-11-26 16:29:48 -08006289static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006290 nodemask_t *nodemask)
6291{
Mel Gorman675becc2014-06-04 16:07:35 -07006292 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006293 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006294 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006295
6296 /*
6297 * Kernel threads should not be throttled as they may be indirectly
6298 * responsible for cleaning pages necessary for reclaim to make forward
6299 * progress. kjournald for example may enter direct reclaim while
6300 * committing a transaction where throttling it could forcing other
6301 * processes to block on log_wait_commit().
6302 */
6303 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006304 goto out;
6305
6306 /*
6307 * If a fatal signal is pending, this process should not throttle.
6308 * It should return quickly so it can exit and free its memory
6309 */
6310 if (fatal_signal_pending(current))
6311 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006312
Mel Gorman675becc2014-06-04 16:07:35 -07006313 /*
6314 * Check if the pfmemalloc reserves are ok by finding the first node
6315 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6316 * GFP_KERNEL will be required for allocating network buffers when
6317 * swapping over the network so ZONE_HIGHMEM is unusable.
6318 *
6319 * Throttling is based on the first usable node and throttled processes
6320 * wait on a queue until kswapd makes progress and wakes them. There
6321 * is an affinity then between processes waking up and where reclaim
6322 * progress has been made assuming the process wakes on the same node.
6323 * More importantly, processes running on remote nodes will not compete
6324 * for remote pfmemalloc reserves and processes on different nodes
6325 * should make reasonable progress.
6326 */
6327 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006328 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006329 if (zone_idx(zone) > ZONE_NORMAL)
6330 continue;
6331
6332 /* Throttle based on the first usable node */
6333 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006334 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006335 goto out;
6336 break;
6337 }
6338
6339 /* If no zone was usable by the allocation flags then do not throttle */
6340 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006341 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006342
Mel Gorman68243e72012-07-31 16:44:39 -07006343 /* Account for the throttling */
6344 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6345
Mel Gorman55150612012-07-31 16:44:35 -07006346 /*
6347 * If the caller cannot enter the filesystem, it's possible that it
6348 * is due to the caller holding an FS lock or performing a journal
6349 * transaction in the case of a filesystem like ext[3|4]. In this case,
6350 * it is not safe to block on pfmemalloc_wait as kswapd could be
6351 * blocked waiting on the same lock. Instead, throttle for up to a
6352 * second before continuing.
6353 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006354 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006355 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006356 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006357 else
6358 /* Throttle until kswapd wakes the process */
6359 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6360 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006361
Mel Gorman50694c22012-11-26 16:29:48 -08006362 if (fatal_signal_pending(current))
6363 return true;
6364
6365out:
6366 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006367}
6368
Mel Gormandac1d272008-04-28 02:12:12 -07006369unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006370 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006371{
Mel Gorman33906bc2010-08-09 17:19:16 -07006372 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006373 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006374 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006375 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006376 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006377 .order = order,
6378 .nodemask = nodemask,
6379 .priority = DEF_PRIORITY,
6380 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006381 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006382 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006383 };
6384
Mel Gorman55150612012-07-31 16:44:35 -07006385 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006386 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6387 * Confirm they are large enough for max values.
6388 */
6389 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6390 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6391 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6392
6393 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006394 * Do not enter reclaim if fatal signal was delivered while throttled.
6395 * 1 is returned so that the page allocator does not OOM kill at this
6396 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006397 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006398 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006399 return 1;
6400
Andrew Morton1732d2b012019-07-16 16:26:15 -07006401 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006402 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006403
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006404 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006405
6406 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006407 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006408
6409 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006410}
6411
Andrew Mortonc255a452012-07-31 16:43:02 -07006412#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006413
Michal Hockod2e5fb92019-08-30 16:04:50 -07006414/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006415unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006416 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006417 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006418 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006419{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006420 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006421 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006422 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006423 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006424 .may_writepage = !laptop_mode,
6425 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006426 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006427 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006428 };
Ying Han0ae5e892011-05-26 16:25:25 -07006429
Michal Hockod2e5fb92019-08-30 16:04:50 -07006430 WARN_ON_ONCE(!current->reclaim_state);
6431
Balbir Singh4e416952009-09-23 15:56:39 -07006432 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6433 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006434
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006435 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006436 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006437
Balbir Singh4e416952009-09-23 15:56:39 -07006438 /*
6439 * NOTE: Although we can get the priority field, using it
6440 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006441 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006442 * will pick up pages from other mem cgroup's as well. We hack
6443 * the priority and make it zero.
6444 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006445 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006446
6447 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6448
Ying Han0ae5e892011-05-26 16:25:25 -07006449 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006450
Balbir Singh4e416952009-09-23 15:56:39 -07006451 return sc.nr_reclaimed;
6452}
6453
Johannes Weiner72835c82012-01-12 17:18:32 -08006454unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006455 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006456 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006457 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08006458{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006459 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006460 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006461 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006462 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006463 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006464 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006465 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006466 .target_mem_cgroup = memcg,
6467 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006468 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006469 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006470 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07006471 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006472 /*
6473 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6474 * equal pressure on all the nodes. This is based on the assumption that
6475 * the reclaim does not bail out early.
6476 */
6477 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006478
Andrew Morton1732d2b012019-07-16 16:26:15 -07006479 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006480 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006481 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006482
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006483 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006484
Vlastimil Babka499118e2017-05-08 15:59:50 -07006485 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006486 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006487 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006488
6489 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006490}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006491EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006492#endif
6493
Yu Zhao37397872022-09-18 02:00:03 -06006494static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006495{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006496 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006497 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006498
Yu Zhao37397872022-09-18 02:00:03 -06006499 if (lru_gen_enabled()) {
6500 lru_gen_age_node(pgdat, sc);
6501 return;
6502 }
6503
Dave Hansen2f368a92021-09-02 14:59:23 -07006504 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006505 return;
6506
Johannes Weinerb91ac372019-11-30 17:56:02 -08006507 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6508 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6509 return;
6510
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006511 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6512 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006513 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6514 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6515 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006516 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6517 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006518}
6519
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006520static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006521{
6522 int i;
6523 struct zone *zone;
6524
6525 /*
6526 * Check for watermark boosts top-down as the higher zones
6527 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006528 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006529 * start prematurely when there is no boosting and a lower
6530 * zone is balanced.
6531 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006532 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006533 zone = pgdat->node_zones + i;
6534 if (!managed_zone(zone))
6535 continue;
6536
6537 if (zone->watermark_boost)
6538 return true;
6539 }
6540
6541 return false;
6542}
6543
Mel Gormane716f2e2017-05-03 14:53:45 -07006544/*
6545 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006546 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006547 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006548static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006549{
Mel Gormane716f2e2017-05-03 14:53:45 -07006550 int i;
6551 unsigned long mark = -1;
6552 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006553
Mel Gorman1c308442018-12-28 00:35:52 -08006554 /*
6555 * Check watermarks bottom-up as lower zones are more likely to
6556 * meet watermarks.
6557 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006558 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006559 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006560
Mel Gormane716f2e2017-05-03 14:53:45 -07006561 if (!managed_zone(zone))
6562 continue;
6563
6564 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006565 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006566 return true;
6567 }
6568
6569 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006570 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006571 * need balancing by definition. This can happen if a zone-restricted
6572 * allocation tries to wake a remote kswapd.
6573 */
6574 if (mark == -1)
6575 return true;
6576
6577 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006578}
6579
Mel Gorman631b6e02017-05-03 14:53:41 -07006580/* Clear pgdat state for congested, dirty or under writeback. */
6581static void clear_pgdat_congested(pg_data_t *pgdat)
6582{
Johannes Weiner1b051172019-11-30 17:55:52 -08006583 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6584
6585 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006586 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6587 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6588}
6589
Mel Gorman1741c872011-01-13 15:46:21 -08006590/*
Mel Gorman55150612012-07-31 16:44:35 -07006591 * Prepare kswapd for sleeping. This verifies that there are no processes
6592 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6593 *
6594 * Returns true if kswapd is ready to sleep
6595 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006596static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6597 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006598{
Mel Gorman55150612012-07-31 16:44:35 -07006599 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006600 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006601 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006602 * race between when kswapd checks the watermarks and a process gets
6603 * throttled. There is also a potential race if processes get
6604 * throttled, kswapd wakes, a large process exits thereby balancing the
6605 * zones, which causes kswapd to exit balance_pgdat() before reaching
6606 * the wake up checks. If kswapd is going to sleep, no process should
6607 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6608 * the wake up is premature, processes will wake kswapd and get
6609 * throttled again. The difference from wake ups in balance_pgdat() is
6610 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006611 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006612 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6613 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006614
Johannes Weinerc73322d2017-05-03 14:51:51 -07006615 /* Hopeless node, leave it to direct reclaim */
6616 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6617 return true;
6618
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006619 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006620 clear_pgdat_congested(pgdat);
6621 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006622 }
6623
Shantanu Goel333b0a42017-05-03 14:53:38 -07006624 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006625}
6626
Linus Torvalds1da177e2005-04-16 15:20:36 -07006627/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006628 * kswapd shrinks a node of pages that are at or below the highest usable
6629 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006630 *
6631 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006632 * reclaim or if the lack of progress was due to pages under writeback.
6633 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006634 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006635static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006636 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006637{
Mel Gorman1d82de62016-07-28 15:45:43 -07006638 struct zone *zone;
6639 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006640
Mel Gorman1d82de62016-07-28 15:45:43 -07006641 /* Reclaim a number of pages proportional to the number of zones */
6642 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006643 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006644 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006645 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006646 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006647
Mel Gorman1d82de62016-07-28 15:45:43 -07006648 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006649 }
6650
Mel Gorman1d82de62016-07-28 15:45:43 -07006651 /*
6652 * Historically care was taken to put equal pressure on all zones but
6653 * now pressure is applied based on node LRU order.
6654 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006655 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006656
6657 /*
6658 * Fragmentation may mean that the system cannot be rebalanced for
6659 * high-order allocations. If twice the allocation size has been
6660 * reclaimed then recheck watermarks only at order-0 to prevent
6661 * excessive reclaim. Assume that a process requested a high-order
6662 * can direct reclaim/compact.
6663 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006664 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006665 sc->order = 0;
6666
Mel Gormanb8e83b92013-07-03 15:01:45 -07006667 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006668}
6669
Mel Gormanc49c2c42021-06-28 19:42:21 -07006670/* Page allocator PCP high watermark is lowered if reclaim is active. */
6671static inline void
6672update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6673{
6674 int i;
6675 struct zone *zone;
6676
6677 for (i = 0; i <= highest_zoneidx; i++) {
6678 zone = pgdat->node_zones + i;
6679
6680 if (!managed_zone(zone))
6681 continue;
6682
6683 if (active)
6684 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6685 else
6686 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6687 }
6688}
6689
6690static inline void
6691set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6692{
6693 update_reclaim_active(pgdat, highest_zoneidx, true);
6694}
6695
6696static inline void
6697clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6698{
6699 update_reclaim_active(pgdat, highest_zoneidx, false);
6700}
6701
Mel Gorman75485362013-07-03 15:01:42 -07006702/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006703 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6704 * that are eligible for use by the caller until at least one zone is
6705 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006706 *
Mel Gorman1d82de62016-07-28 15:45:43 -07006707 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006708 *
6709 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07006710 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08006711 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07006712 * or lower is eligible for reclaim until at least one usable zone is
6713 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006714 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006715static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006716{
Linus Torvalds1da177e2005-04-16 15:20:36 -07006717 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07006718 unsigned long nr_soft_reclaimed;
6719 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07006720 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08006721 unsigned long nr_boost_reclaim;
6722 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6723 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07006724 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08006725 struct scan_control sc = {
6726 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07006727 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006728 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08006729 };
Omar Sandoval93781322018-06-07 17:07:02 -07006730
Andrew Morton1732d2b012019-07-16 16:26:15 -07006731 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07006732 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006733 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006734
Christoph Lameterf8891e52006-06-30 01:55:45 -07006735 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006736
Mel Gorman1c308442018-12-28 00:35:52 -08006737 /*
6738 * Account for the reclaim boost. Note that the zone boost is left in
6739 * place so that parallel allocations that are near the watermark will
6740 * stall or direct reclaim until kswapd is finished.
6741 */
6742 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006743 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006744 zone = pgdat->node_zones + i;
6745 if (!managed_zone(zone))
6746 continue;
6747
6748 nr_boost_reclaim += zone->watermark_boost;
6749 zone_boosts[i] = zone->watermark_boost;
6750 }
6751 boosted = nr_boost_reclaim;
6752
6753restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006754 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006755 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006756 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006757 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006758 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006759 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006760 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006761
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006762 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006763
Mel Gorman86c79f62016-07-28 15:45:59 -07006764 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006765 * If the number of buffer_heads exceeds the maximum allowed
6766 * then consider reclaiming from all zones. This has a dual
6767 * purpose -- on 64-bit systems it is expected that
6768 * buffer_heads are stripped during active rotation. On 32-bit
6769 * systems, highmem pages can pin lowmem memory and shrinking
6770 * buffers can relieve lowmem pressure. Reclaim may still not
6771 * go ahead if all eligible zones for the original allocation
6772 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006773 */
6774 if (buffer_heads_over_limit) {
6775 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6776 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006777 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006778 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006779
Mel Gorman970a39a2016-07-28 15:46:35 -07006780 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006781 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006782 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006783 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006784
Mel Gorman86c79f62016-07-28 15:45:59 -07006785 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006786 * If the pgdat is imbalanced then ignore boosting and preserve
6787 * the watermarks for a later time and restart. Note that the
6788 * zone watermarks will be still reset at the end of balancing
6789 * on the grounds that the normal reclaim should be enough to
6790 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006791 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006792 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006793 if (!balanced && nr_boost_reclaim) {
6794 nr_boost_reclaim = 0;
6795 goto restart;
6796 }
6797
6798 /*
6799 * If boosting is not active then only reclaim if there are no
6800 * eligible zones. Note that sc.reclaim_idx is not used as
6801 * buffer_heads_over_limit may have adjusted it.
6802 */
6803 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006804 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006805
Mel Gorman1c308442018-12-28 00:35:52 -08006806 /* Limit the priority of boosting to avoid reclaim writeback */
6807 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6808 raise_priority = false;
6809
6810 /*
6811 * Do not writeback or swap pages for boosted reclaim. The
6812 * intent is to relieve pressure not issue sub-optimal IO
6813 * from reclaim context. If no pages are reclaimed, the
6814 * reclaim will be aborted.
6815 */
6816 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6817 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006818
Linus Torvalds1da177e2005-04-16 15:20:36 -07006819 /*
Yu Zhao37397872022-09-18 02:00:03 -06006820 * Do some background aging, to give pages a chance to be
6821 * referenced before reclaiming. All pages are rotated
6822 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07006823 */
Yu Zhao37397872022-09-18 02:00:03 -06006824 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006825
6826 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006827 * If we're getting trouble reclaiming, start doing writepage
6828 * even in laptop mode.
6829 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006830 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006831 sc.may_writepage = 1;
6832
Mel Gorman1d82de62016-07-28 15:45:43 -07006833 /* Call soft limit reclaim before calling shrink_node. */
6834 sc.nr_scanned = 0;
6835 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006836 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006837 sc.gfp_mask, &nr_soft_scanned);
6838 sc.nr_reclaimed += nr_soft_reclaimed;
6839
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006840 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006841 * There should be no need to raise the scanning priority if
6842 * enough pages are already being scanned that that high
6843 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006844 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006845 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006846 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006847
6848 /*
6849 * If the low watermark is met there is no need for processes
6850 * to be throttled on pfmemalloc_wait as they should not be
6851 * able to safely make forward progress. Wake them
6852 */
6853 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006854 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006855 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006856
Mel Gormanb8e83b92013-07-03 15:01:45 -07006857 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006858 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006859 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006860 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006861 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006862 break;
6863
6864 /*
6865 * Raise priority if scanning rate is too low or there was no
6866 * progress in reclaiming pages
6867 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006868 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006869 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6870
6871 /*
6872 * If reclaim made no progress for a boost, stop reclaim as
6873 * IO cannot be queued and it could be an infinite loop in
6874 * extreme circumstances.
6875 */
6876 if (nr_boost_reclaim && !nr_reclaimed)
6877 break;
6878
Johannes Weinerc73322d2017-05-03 14:51:51 -07006879 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006880 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006881 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006882
Johannes Weinerc73322d2017-05-03 14:51:51 -07006883 if (!sc.nr_reclaimed)
6884 pgdat->kswapd_failures++;
6885
Mel Gormanb8e83b92013-07-03 15:01:45 -07006886out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006887 clear_reclaim_active(pgdat, highest_zoneidx);
6888
Mel Gorman1c308442018-12-28 00:35:52 -08006889 /* If reclaim was boosted, account for the reclaim done in this pass */
6890 if (boosted) {
6891 unsigned long flags;
6892
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006893 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006894 if (!zone_boosts[i])
6895 continue;
6896
6897 /* Increments are under the zone lock */
6898 zone = pgdat->node_zones + i;
6899 spin_lock_irqsave(&zone->lock, flags);
6900 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6901 spin_unlock_irqrestore(&zone->lock, flags);
6902 }
6903
6904 /*
6905 * As there is now likely space, wakeup kcompact to defragment
6906 * pageblocks.
6907 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006908 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006909 }
6910
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006911 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006912 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006913 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006914 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006915
Mel Gorman0abdee22011-01-13 15:46:22 -08006916 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006917 * Return the order kswapd stopped reclaiming at as
6918 * prepare_kswapd_sleep() takes it into account. If another caller
6919 * entered the allocator slow path while kswapd was awake, order will
6920 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006921 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006922 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006923}
6924
Mel Gormane716f2e2017-05-03 14:53:45 -07006925/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006926 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6927 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6928 * not a valid index then either kswapd runs for first time or kswapd couldn't
6929 * sleep after previous reclaim attempt (node is still unbalanced). In that
6930 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006931 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006932static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6933 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006934{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006935 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006936
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006937 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006938}
6939
Mel Gorman38087d92016-07-28 15:45:49 -07006940static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006941 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006942{
6943 long remaining = 0;
6944 DEFINE_WAIT(wait);
6945
6946 if (freezing(current) || kthread_should_stop())
6947 return;
6948
6949 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6950
Shantanu Goel333b0a42017-05-03 14:53:38 -07006951 /*
6952 * Try to sleep for a short interval. Note that kcompactd will only be
6953 * woken if it is possible to sleep for a short interval. This is
6954 * deliberate on the assumption that if reclaim cannot keep an
6955 * eligible zone balanced that it's also unlikely that compaction will
6956 * succeed.
6957 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006958 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006959 /*
6960 * Compaction records what page blocks it recently failed to
6961 * isolate pages from and skips them in the future scanning.
6962 * When kswapd is going to sleep, it is reasonable to assume
6963 * that pages and compaction may succeed so reset the cache.
6964 */
6965 reset_isolation_suitable(pgdat);
6966
6967 /*
6968 * We have freed the memory, now we should compact it to make
6969 * allocation of the requested order possible.
6970 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006971 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006972
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006973 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006974
6975 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006976 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006977 * order. The values will either be from a wakeup request or
6978 * the previous request that slept prematurely.
6979 */
6980 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006981 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6982 kswapd_highest_zoneidx(pgdat,
6983 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006984
6985 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6986 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006987 }
6988
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006989 finish_wait(&pgdat->kswapd_wait, &wait);
6990 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6991 }
6992
6993 /*
6994 * After a short sleep, check if it was a premature sleep. If not, then
6995 * go fully to sleep until explicitly woken up.
6996 */
Mel Gormand9f21d42016-07-28 15:46:41 -07006997 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006998 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006999 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7000
7001 /*
7002 * vmstat counters are not perfectly accurate and the estimated
7003 * value for counters such as NR_FREE_PAGES can deviate from the
7004 * true value by nr_online_cpus * threshold. To avoid the zone
7005 * watermarks being breached while under pressure, we reduce the
7006 * per-cpu vmstat threshold while kswapd is awake and restore
7007 * them before going back to sleep.
7008 */
7009 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07007010
7011 if (!kthread_should_stop())
7012 schedule();
7013
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007014 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7015 } else {
7016 if (remaining)
7017 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7018 else
7019 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7020 }
7021 finish_wait(&pgdat->kswapd_wait, &wait);
7022}
7023
Linus Torvalds1da177e2005-04-16 15:20:36 -07007024/*
7025 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07007026 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007027 *
7028 * This basically trickles out pages so that we have _some_
7029 * free memory available even if there is no other activity
7030 * that frees anything up. This is needed for things like routing
7031 * etc, where we otherwise might have all activity going on in
7032 * asynchronous contexts that cannot page things out.
7033 *
7034 * If there are applications that are active memory-allocators
7035 * (most normal use), this basically shouldn't matter.
7036 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307037int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007038{
Mel Gormane716f2e2017-05-03 14:53:45 -07007039 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007040 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07007041 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007042 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10307043 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007044
Rusty Russell174596a2009-01-01 10:12:29 +10307045 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07007046 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007047
7048 /*
7049 * Tell the memory management that we're a "memory allocator",
7050 * and that if we need more memory we should get access to it
7051 * regardless (see "__alloc_pages()"). "kswapd" should
7052 * never get caught in the normal page freeing logic.
7053 *
7054 * (Kswapd normally doesn't need memory anyway, but sometimes
7055 * you need a small amount of memory in order to be able to
7056 * page out something else, and this flag essentially protects
7057 * us from recursively trying to free more memory as we're
7058 * trying to free the first piece of memory in the first place).
7059 */
Christoph Lameter930d9152006-01-08 01:00:47 -08007060 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07007061 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07007062
Qian Cai5644e1fb2020-04-01 21:10:12 -07007063 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007064 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007065 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08007066 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07007067
Qian Cai5644e1fb2020-04-01 21:10:12 -07007068 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007069 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7070 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07007071
Mel Gorman38087d92016-07-28 15:45:49 -07007072kswapd_try_sleep:
7073 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007074 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07007075
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007076 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08007077 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007078 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7079 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007080 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007081 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007082
David Rientjes8fe23e02009-12-14 17:58:33 -08007083 ret = try_to_freeze();
7084 if (kthread_should_stop())
7085 break;
7086
7087 /*
7088 * We can speed up thawing tasks if we don't call balance_pgdat
7089 * after returning from the refrigerator
7090 */
Mel Gorman38087d92016-07-28 15:45:49 -07007091 if (ret)
7092 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07007093
Mel Gorman38087d92016-07-28 15:45:49 -07007094 /*
7095 * Reclaim begins at the requested order but if a high-order
7096 * reclaim fails then kswapd falls back to reclaiming for
7097 * order-0. If that happens, kswapd will consider sleeping
7098 * for the order it finished reclaiming at (reclaim_order)
7099 * but kcompactd is woken to compact for the original
7100 * request (alloc_order).
7101 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007102 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007103 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007104 reclaim_order = balance_pgdat(pgdat, alloc_order,
7105 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007106 if (reclaim_order < alloc_order)
7107 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007108 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007109
Johannes Weiner71abdc12014-06-06 14:35:35 -07007110 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007111
Linus Torvalds1da177e2005-04-16 15:20:36 -07007112 return 0;
7113}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307114EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007115
7116/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007117 * A zone is low on free memory or too fragmented for high-order memory. If
7118 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7119 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7120 * has failed or is not needed, still wake up kcompactd if only compaction is
7121 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007122 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007123void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007124 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007125{
7126 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007127 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007128
Mel Gorman6aa303d2016-09-01 16:14:55 -07007129 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007130 return;
7131
David Rientjes5ecd9d42018-04-05 16:25:16 -07007132 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007133 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007134
Qian Cai5644e1fb2020-04-01 21:10:12 -07007135 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007136 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007137
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007138 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7139 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007140
7141 if (READ_ONCE(pgdat->kswapd_order) < order)
7142 WRITE_ONCE(pgdat->kswapd_order, order);
7143
Con Kolivas8d0986e2005-09-13 01:25:07 -07007144 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007145 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007146
David Rientjes5ecd9d42018-04-05 16:25:16 -07007147 /* Hopeless node, leave it to direct reclaim if possible */
7148 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007149 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7150 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007151 /*
7152 * There may be plenty of free memory available, but it's too
7153 * fragmented for high-order allocations. Wake up kcompactd
7154 * and rely on compaction_suitable() to determine if it's
7155 * needed. If it fails, it will defer subsequent attempts to
7156 * ratelimit its work.
7157 */
7158 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007159 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007160 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007161 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007162
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007163 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007164 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007165 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007166}
7167
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007168#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007169/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007170 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007171 * freed pages.
7172 *
7173 * Rather than trying to age LRUs the aim is to preserve the overall
7174 * LRU order by reclaiming preferentially
7175 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007176 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007177unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007178{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007179 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007180 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007181 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007182 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007183 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007184 .may_writepage = 1,
7185 .may_unmap = 1,
7186 .may_swap = 1,
7187 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007188 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007189 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007190 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007191 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007192
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007193 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007194 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007195 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007196
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007197 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007198
Andrew Morton1732d2b012019-07-16 16:26:15 -07007199 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007200 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007201 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007202
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007203 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007204}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007205#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007206
Yasunori Goto3218ae12006-06-27 02:53:33 -07007207/*
7208 * This kswapd start function will be called by init and node-hot-add.
7209 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7210 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007211void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007212{
7213 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307214 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007215
7216 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007217 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007218
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307219 trace_android_vh_kswapd_per_node(nid, &skip, true);
7220 if (skip)
7221 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007222 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7223 if (IS_ERR(pgdat->kswapd)) {
7224 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007225 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007226 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007227 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007228 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007229}
7230
David Rientjes8fe23e02009-12-14 17:58:33 -08007231/*
Jiang Liud8adde12012-07-11 14:01:52 -07007232 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007233 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007234 */
7235void kswapd_stop(int nid)
7236{
7237 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307238 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007239
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307240 trace_android_vh_kswapd_per_node(nid, &skip, false);
7241 if (skip)
7242 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007243 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007244 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007245 NODE_DATA(nid)->kswapd = NULL;
7246 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007247}
7248
Linus Torvalds1da177e2005-04-16 15:20:36 -07007249static int __init kswapd_init(void)
7250{
Wei Yang6b700b52020-04-01 21:10:09 -07007251 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007252
Linus Torvalds1da177e2005-04-16 15:20:36 -07007253 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007254 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007255 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007256 return 0;
7257}
7258
7259module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007260
7261#ifdef CONFIG_NUMA
7262/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007263 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007264 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007265 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007266 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007267 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007268int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007269
Dave Hansen51998362021-02-24 12:09:15 -08007270/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007271 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007272 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7273 * a zone.
7274 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007275#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007276
Christoph Lameter9eeff232006-01-18 17:42:31 -08007277/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007278 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007279 * occur.
7280 */
7281int sysctl_min_unmapped_ratio = 1;
7282
7283/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007284 * If the number of slab pages in a zone grows beyond this percentage then
7285 * slab reclaim needs to occur.
7286 */
7287int sysctl_min_slab_ratio = 5;
7288
Mel Gorman11fb9982016-07-28 15:46:20 -07007289static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007290{
Mel Gorman11fb9982016-07-28 15:46:20 -07007291 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7292 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7293 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007294
7295 /*
7296 * It's possible for there to be more file mapped pages than
7297 * accounted for by the pages on the file LRU lists because
7298 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7299 */
7300 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7301}
7302
7303/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007304static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007305{
Alexandru Moised031a152015-11-05 18:48:08 -08007306 unsigned long nr_pagecache_reclaimable;
7307 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007308
7309 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007310 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007311 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007312 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007313 * a better estimate
7314 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007315 if (node_reclaim_mode & RECLAIM_UNMAP)
7316 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007317 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007318 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007319
7320 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007321 if (!(node_reclaim_mode & RECLAIM_WRITE))
7322 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007323
7324 /* Watch for any possible underflows due to delta */
7325 if (unlikely(delta > nr_pagecache_reclaimable))
7326 delta = nr_pagecache_reclaimable;
7327
7328 return nr_pagecache_reclaimable - delta;
7329}
7330
Christoph Lameter0ff38492006-09-25 23:31:52 -07007331/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007332 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007333 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007334static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007335{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007336 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007337 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007338 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007339 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007340 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007341 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007342 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007343 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007344 .priority = NODE_RECLAIM_PRIORITY,
7345 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7346 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007347 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007348 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007349 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007350 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007351
Yafang Shao132bb8c2019-05-13 17:17:53 -07007352 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7353 sc.gfp_mask);
7354
Christoph Lameter9eeff232006-01-18 17:42:31 -08007355 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007356 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007357 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007358 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007359 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007360 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007361 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007362 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007363 noreclaim_flag = memalloc_noreclaim_save();
7364 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007365 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007366
Mel Gormana5f5f912016-07-28 15:46:32 -07007367 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007368 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007369 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007370 * priorities until we have enough memory freed.
7371 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007372 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007373 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007374 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007375 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007376
Andrew Morton1732d2b012019-07-16 16:26:15 -07007377 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007378 current->flags &= ~PF_SWAPWRITE;
7379 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007380 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007381 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007382
7383 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7384
Rik van Riela79311c2009-01-06 14:40:01 -08007385 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007386}
Andrew Morton179e9632006-03-22 00:08:18 -08007387
Mel Gormana5f5f912016-07-28 15:46:32 -07007388int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007389{
David Rientjesd773ed62007-10-16 23:26:01 -07007390 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007391
7392 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007393 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007394 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007395 *
Christoph Lameter96146342006-07-03 00:24:13 -07007396 * A small portion of unmapped file backed pages is needed for
7397 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007398 * thrown out if the node is overallocated. So we do not reclaim
7399 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007400 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007401 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007402 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007403 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7404 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007405 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007406
7407 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007408 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007409 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007410 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007411 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007412
7413 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007414 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007415 * have associated processors. This will favor the local processor
7416 * over remote processors and spread off node memory allocations
7417 * as wide as possible.
7418 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007419 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7420 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007421
Mel Gormana5f5f912016-07-28 15:46:32 -07007422 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7423 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007424
Mel Gormana5f5f912016-07-28 15:46:32 -07007425 ret = __node_reclaim(pgdat, gfp_mask, order);
7426 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007427
Mel Gorman24cf725182009-06-16 15:33:23 -07007428 if (!ret)
7429 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7430
David Rientjesd773ed62007-10-16 23:26:01 -07007431 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007432}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007433#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007434
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007435/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007436 * check_move_unevictable_pages - check pages for evictability and move to
7437 * appropriate zone lru list
7438 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007439 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007440 * Checks pages for evictability, if an evictable page is in the unevictable
7441 * lru list, moves it to the appropriate evictable lru list. This function
7442 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007443 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007444void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007445{
Alex Shi6168d0d2020-12-15 12:34:29 -08007446 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007447 int pgscanned = 0;
7448 int pgrescued = 0;
7449 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007450
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007451 for (i = 0; i < pvec->nr; i++) {
7452 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007453 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007454
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007455 if (PageTransTail(page))
7456 continue;
7457
7458 nr_pages = thp_nr_pages(page);
7459 pgscanned += nr_pages;
7460
Alex Shid25b5bd2020-12-15 12:34:16 -08007461 /* block memcg migration during page moving between lru */
7462 if (!TestClearPageLRU(page))
7463 continue;
7464
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007465 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007466 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007467 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007468 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007469 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007470 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007471 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007472 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007473 }
Hugh Dickins24513262012-01-20 14:34:21 -08007474
Alex Shi6168d0d2020-12-15 12:34:29 -08007475 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007476 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7477 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007478 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007479 } else if (pgscanned) {
7480 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007481 }
Hugh Dickins850465792012-01-20 14:34:19 -08007482}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007483EXPORT_SYMBOL_GPL(check_move_unevictable_pages);