blob: 969deb8a20edf660511f6d558a045ebcfe4dce00 [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
Yu Zhao4fc3ef42022-12-21 21:19:01 -0700455static bool global_reclaim(struct scan_control *sc)
456{
457 return !sc->target_mem_cgroup || mem_cgroup_is_root(sc->target_mem_cgroup);
458}
459
Tejun Heo97c93412015-05-22 18:23:36 -0400460/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800461 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400462 * @sc: scan_control in question
463 *
464 * The normal page dirty throttling mechanism in balance_dirty_pages() is
465 * completely broken with the legacy memcg and direct stalling in
466 * shrink_page_list() is used for throttling instead, which lacks all the
467 * niceties such as fairness, adaptive pausing, bandwidth proportional
468 * allocation and configurability.
469 *
470 * This function tests whether the vmscan currently in progress can assume
471 * that the normal dirty throttling mechanism is operational.
472 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800473static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400474{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800475 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400476 return true;
477#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800478 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400479 return true;
480#endif
481 return false;
482}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800483#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700484static int prealloc_memcg_shrinker(struct shrinker *shrinker)
485{
Yang Shi476b30a2021-05-04 18:36:39 -0700486 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700487}
488
489static void unregister_memcg_shrinker(struct shrinker *shrinker)
490{
491}
492
Yang Shi86750832021-05-04 18:36:36 -0700493static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
494 struct mem_cgroup *memcg)
495{
496 return 0;
497}
498
499static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
500 struct mem_cgroup *memcg)
501{
502 return 0;
503}
504
Johannes Weinerb5ead352019-11-30 17:55:40 -0800505static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800506{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800507 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800508}
Tejun Heo97c93412015-05-22 18:23:36 -0400509
Yu Zhao4fc3ef42022-12-21 21:19:01 -0700510static bool global_reclaim(struct scan_control *sc)
511{
512 return true;
513}
514
Johannes Weinerb5ead352019-11-30 17:55:40 -0800515static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400516{
517 return true;
518}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800519#endif
520
Yang Shi86750832021-05-04 18:36:36 -0700521static long xchg_nr_deferred(struct shrinker *shrinker,
522 struct shrink_control *sc)
523{
524 int nid = sc->nid;
525
526 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
527 nid = 0;
528
529 if (sc->memcg &&
530 (shrinker->flags & SHRINKER_MEMCG_AWARE))
531 return xchg_nr_deferred_memcg(nid, shrinker,
532 sc->memcg);
533
534 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
535}
536
537
538static long add_nr_deferred(long nr, struct shrinker *shrinker,
539 struct shrink_control *sc)
540{
541 int nid = sc->nid;
542
543 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
544 nid = 0;
545
546 if (sc->memcg &&
547 (shrinker->flags & SHRINKER_MEMCG_AWARE))
548 return add_nr_deferred_memcg(nr, nid, shrinker,
549 sc->memcg);
550
551 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
552}
553
Dave Hansen26aa2d12021-09-02 14:59:16 -0700554static bool can_demote(int nid, struct scan_control *sc)
555{
Huang Ying20b51af12021-09-02 14:59:33 -0700556 if (!numa_demotion_enabled)
557 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700558 if (sc) {
559 if (sc->no_demotion)
560 return false;
561 /* It is pointless to do demotion in memcg reclaim */
562 if (cgroup_reclaim(sc))
563 return false;
564 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700565 if (next_demotion_node(nid) == NUMA_NO_NODE)
566 return false;
567
Huang Ying20b51af12021-09-02 14:59:33 -0700568 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700569}
570
Keith Buscha2a36482021-09-02 14:59:26 -0700571static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
572 int nid,
573 struct scan_control *sc)
574{
575 if (memcg == NULL) {
576 /*
577 * For non-memcg reclaim, is there
578 * space in any swap device?
579 */
580 if (get_nr_swap_pages() > 0)
581 return true;
582 } else {
583 /* Is the memcg below its swap limit? */
584 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
585 return true;
586 }
587
588 /*
589 * The page can not be swapped.
590 *
591 * Can it be reclaimed from this node via demotion?
592 */
593 return can_demote(nid, sc);
594}
595
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700596/*
597 * This misses isolated pages which are not accounted for to save counters.
598 * As the data only determines if reclaim or compaction continues, it is
599 * not expected that isolated pages will be a dominating factor.
600 */
601unsigned long zone_reclaimable_pages(struct zone *zone)
602{
603 unsigned long nr;
604
605 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
606 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700607 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700608 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
609 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
610
611 return nr;
612}
613
Michal Hockofd538802017-02-22 15:45:58 -0800614/**
615 * lruvec_lru_size - Returns the number of pages on the given LRU list.
616 * @lruvec: lru vector
617 * @lru: lru to use
618 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
619 */
Yu Zhao20913392021-02-24 12:08:44 -0800620static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
621 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800622{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800623 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800624 int zid;
625
Johannes Weinerde3b0152019-11-30 17:55:31 -0800626 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800627 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800628
Michal Hockofd538802017-02-22 15:45:58 -0800629 if (!managed_zone(zone))
630 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800631
Michal Hockofd538802017-02-22 15:45:58 -0800632 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800633 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800634 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800635 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800636 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800637 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800638}
639
Linus Torvalds1da177e2005-04-16 15:20:36 -0700640/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000641 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700642 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900643int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700644{
Yang Shi476b30a2021-05-04 18:36:39 -0700645 unsigned int size;
646 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000647
Yang Shi476b30a2021-05-04 18:36:39 -0700648 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
649 err = prealloc_memcg_shrinker(shrinker);
650 if (err != -ENOSYS)
651 return err;
652
653 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
654 }
655
656 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000657 if (shrinker->flags & SHRINKER_NUMA_AWARE)
658 size *= nr_node_ids;
659
660 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
661 if (!shrinker->nr_deferred)
662 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700663
Tetsuo Handa8e049442018-04-04 19:53:07 +0900664 return 0;
665}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000666
Tetsuo Handa8e049442018-04-04 19:53:07 +0900667void free_prealloced_shrinker(struct shrinker *shrinker)
668{
Yang Shi41ca6682021-05-04 18:36:29 -0700669 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
670 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700671 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700672 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700673 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700674 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700675
Tetsuo Handa8e049442018-04-04 19:53:07 +0900676 kfree(shrinker->nr_deferred);
677 shrinker->nr_deferred = NULL;
678}
679
680void register_shrinker_prepared(struct shrinker *shrinker)
681{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700682 down_write(&shrinker_rwsem);
683 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700684 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700685 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900686}
687
688int register_shrinker(struct shrinker *shrinker)
689{
690 int err = prealloc_shrinker(shrinker);
691
692 if (err)
693 return err;
694 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000695 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700696}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700697EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700698
699/*
700 * Remove one
701 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700702void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700703{
Yang Shi41ca6682021-05-04 18:36:29 -0700704 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900705 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700706
Linus Torvalds1da177e2005-04-16 15:20:36 -0700707 down_write(&shrinker_rwsem);
708 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700709 shrinker->flags &= ~SHRINKER_REGISTERED;
710 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
711 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700712 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700713
Andrew Vaginae393322013-10-16 13:46:46 -0700714 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900715 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700716}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700717EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700718
719#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000720
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800721static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800722 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700723{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000724 unsigned long freed = 0;
725 unsigned long long delta;
726 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700727 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000728 long nr;
729 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000730 long batch_size = shrinker->batch ? shrinker->batch
731 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800732 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000733
rongqianfeng8da6ee32021-05-21 10:30:14 +0800734 trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
735
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700736 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700737 if (freeable == 0 || freeable == SHRINK_EMPTY)
738 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000739
740 /*
741 * copy the current shrinker scan count into a local variable
742 * and zero it so that other concurrent shrinker invocations
743 * don't also do this scanning work.
744 */
Yang Shi86750832021-05-04 18:36:36 -0700745 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000746
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700747 if (shrinker->seeks) {
748 delta = freeable >> priority;
749 delta *= 4;
750 do_div(delta, shrinker->seeks);
751 } else {
752 /*
753 * These objects don't require any IO to create. Trim
754 * them aggressively under memory pressure to keep
755 * them from causing refetches in the IO caches.
756 */
757 delta = freeable / 2;
758 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700759
Yang Shi18bb4732021-05-04 18:36:45 -0700760 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000761 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700762 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000763
764 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800765 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000766
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800767 /*
768 * Normally, we should not scan less than batch_size objects in one
769 * pass to avoid too frequent shrinker calls, but if the slab has less
770 * than batch_size objects in total and we are really tight on memory,
771 * we will try to reclaim all available objects, otherwise we can end
772 * up failing allocations although there are plenty of reclaimable
773 * objects spread over several slabs with usage less than the
774 * batch_size.
775 *
776 * We detect the "tight on memory" situations by looking at the total
777 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700778 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800779 * scanning at high prio and therefore should try to reclaim as much as
780 * possible.
781 */
782 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700783 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000784 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800785 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000786
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800787 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700788 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000789 ret = shrinker->scan_objects(shrinker, shrinkctl);
790 if (ret == SHRINK_STOP)
791 break;
792 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000793
Chris Wilsond460acb2017-09-06 16:19:26 -0700794 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
795 total_scan -= shrinkctl->nr_scanned;
796 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000797
798 cond_resched();
799 }
800
Yang Shi18bb4732021-05-04 18:36:45 -0700801 /*
802 * The deferred work is increased by any new work (delta) that wasn't
803 * done, decreased by old deferred work that was done now.
804 *
805 * And it is capped to two times of the freeable items.
806 */
807 next_deferred = max_t(long, (nr + delta - scanned), 0);
808 next_deferred = min(next_deferred, (2 * freeable));
809
Glauber Costa1d3d4432013-08-28 10:18:04 +1000810 /*
811 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700812 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000813 */
Yang Shi86750832021-05-04 18:36:36 -0700814 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000815
Yang Shi8efb4b52021-05-04 18:36:08 -0700816 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000817 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700818}
819
Yang Shi0a432dc2019-09-23 15:38:12 -0700820#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700821static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
822 struct mem_cgroup *memcg, int priority)
823{
Yang Shie4262c42021-05-04 18:36:23 -0700824 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700825 unsigned long ret, freed = 0;
826 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700827
Yang Shi0a432dc2019-09-23 15:38:12 -0700828 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700829 return 0;
830
831 if (!down_read_trylock(&shrinker_rwsem))
832 return 0;
833
Yang Shi468ab842021-05-04 18:36:26 -0700834 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700835 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700836 goto unlock;
837
Yang Shie4262c42021-05-04 18:36:23 -0700838 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700839 struct shrink_control sc = {
840 .gfp_mask = gfp_mask,
841 .nid = nid,
842 .memcg = memcg,
843 };
844 struct shrinker *shrinker;
845
846 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700847 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700848 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700849 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700850 continue;
851 }
852
Yang Shi0a432dc2019-09-23 15:38:12 -0700853 /* Call non-slab shrinkers even though kmem is disabled */
854 if (!memcg_kmem_enabled() &&
855 !(shrinker->flags & SHRINKER_NONSLAB))
856 continue;
857
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700858 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700859 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700860 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700861 /*
862 * After the shrinker reported that it had no objects to
863 * free, but before we cleared the corresponding bit in
864 * the memcg shrinker map, a new object might have been
865 * added. To make sure, we have the bit set in this
866 * case, we invoke the shrinker one more time and reset
867 * the bit if it reports that it is not empty anymore.
868 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700869 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700870 *
871 * list_lru_add() shrink_slab_memcg()
872 * list_add_tail() clear_bit()
873 * <MB> <MB>
874 * set_bit() do_shrink_slab()
875 */
876 smp_mb__after_atomic();
877 ret = do_shrink_slab(&sc, shrinker, priority);
878 if (ret == SHRINK_EMPTY)
879 ret = 0;
880 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700881 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700882 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700883 freed += ret;
884
885 if (rwsem_is_contended(&shrinker_rwsem)) {
886 freed = freed ? : 1;
887 break;
888 }
889 }
890unlock:
891 up_read(&shrinker_rwsem);
892 return freed;
893}
Yang Shi0a432dc2019-09-23 15:38:12 -0700894#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700895static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
896 struct mem_cgroup *memcg, int priority)
897{
898 return 0;
899}
Yang Shi0a432dc2019-09-23 15:38:12 -0700900#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700901
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800902/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800903 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800904 * @gfp_mask: allocation context
905 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800906 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800907 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700908 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800909 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700910 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800911 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
912 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700913 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700914 * @memcg specifies the memory cgroup to target. Unaware shrinkers
915 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800916 *
Josef Bacik9092c712018-01-31 16:16:26 -0800917 * @priority is sc->priority, we take the number of objects and >> by priority
918 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700919 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800920 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700921 */
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800922unsigned long shrink_slab(gfp_t gfp_mask, int nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800923 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800924 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700925{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700926 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700927 struct shrinker *shrinker;
wudean842c68a2021-04-27 17:40:41 +0800928 bool bypass = false;
929
930 trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
931 if (bypass)
932 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700933
Yang Shifa1e5122019-08-02 21:48:44 -0700934 /*
935 * The root memcg might be allocated even though memcg is disabled
936 * via "cgroup_disable=memory" boot parameter. This could make
937 * mem_cgroup_is_root() return false, then just run memcg slab
938 * shrink, but skip global shrink. This may result in premature
939 * oom.
940 */
941 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700942 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800943
Tetsuo Handae830c632018-04-05 16:23:35 -0700944 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700945 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700946
947 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800948 struct shrink_control sc = {
949 .gfp_mask = gfp_mask,
950 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800951 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800952 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800953
Kirill Tkhai9b996462018-08-17 15:48:21 -0700954 ret = do_shrink_slab(&sc, shrinker, priority);
955 if (ret == SHRINK_EMPTY)
956 ret = 0;
957 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800958 /*
959 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700960 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800961 * by parallel ongoing shrinking.
962 */
963 if (rwsem_is_contended(&shrinker_rwsem)) {
964 freed = freed ? : 1;
965 break;
966 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700967 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800968
Linus Torvalds1da177e2005-04-16 15:20:36 -0700969 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700970out:
971 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000972 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700973}
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800974EXPORT_SYMBOL_GPL(shrink_slab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700975
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800976void drop_slab_node(int nid)
977{
978 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700979 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800980
981 do {
982 struct mem_cgroup *memcg = NULL;
983
Chunxin Zang069c4112020-10-13 16:56:46 -0700984 if (fatal_signal_pending(current))
985 return;
986
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800987 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700988 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800989 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800990 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800991 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700992 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800993}
994
995void drop_slab(void)
996{
997 int nid;
998
999 for_each_online_node(nid)
1000 drop_slab_node(nid);
1001}
1002
Linus Torvalds1da177e2005-04-16 15:20:36 -07001003static inline int is_page_cache_freeable(struct page *page)
1004{
Johannes Weinerceddc3a2009-09-21 17:03:00 -07001005 /*
1006 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -04001007 * that isolated the page, the page cache and optional buffer
1008 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -07001009 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -07001010 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -04001011 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001012}
1013
Yang Shicb165562019-11-30 17:55:28 -08001014static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001015{
Christoph Lameter930d9152006-01-08 01:00:47 -08001016 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001017 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001018 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001019 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001020 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001021 return 1;
1022 return 0;
1023}
1024
1025/*
1026 * We detected a synchronous write error writing a page out. Probably
1027 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1028 * fsync(), msync() or close().
1029 *
1030 * The tricky part is that after writepage we cannot touch the mapping: nothing
1031 * prevents it from being freed up. But we have a ref on the page and once
1032 * that page is locked, the mapping is pinned.
1033 *
1034 * We're allowed to run sleeping lock_page() here because we know the caller has
1035 * __GFP_FS.
1036 */
1037static void handle_write_error(struct address_space *mapping,
1038 struct page *page, int error)
1039{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001040 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001041 if (page_mapping(page) == mapping)
1042 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001043 unlock_page(page);
1044}
1045
Christoph Lameter04e62a22006-06-23 02:03:38 -07001046/* possible outcome of pageout() */
1047typedef enum {
1048 /* failed to write page out, page is locked */
1049 PAGE_KEEP,
1050 /* move page to the active list, page is locked */
1051 PAGE_ACTIVATE,
1052 /* page has been sent to the disk successfully, page is unlocked */
1053 PAGE_SUCCESS,
1054 /* page is clean and locked */
1055 PAGE_CLEAN,
1056} pageout_t;
1057
Linus Torvalds1da177e2005-04-16 15:20:36 -07001058/*
Andrew Morton1742f192006-03-22 00:08:21 -08001059 * pageout is called by shrink_page_list() for each dirty page.
1060 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001061 */
Yang Shicb165562019-11-30 17:55:28 -08001062static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001063{
1064 /*
1065 * If the page is dirty, only perform writeback if that write
1066 * will be non-blocking. To prevent this allocation from being
1067 * stalled by pagecache activity. But note that there may be
1068 * stalls if we need to run get_block(). We could test
1069 * PagePrivate for that.
1070 *
Al Viro81742022014-04-03 03:17:43 -04001071 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001072 * this page's queue, we can perform writeback even if that
1073 * will block.
1074 *
1075 * If the page is swapcache, write it back even if that would
1076 * block, for some throttling. This happens by accident, because
1077 * swap_backing_dev_info is bust: it doesn't reflect the
1078 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001079 */
1080 if (!is_page_cache_freeable(page))
1081 return PAGE_KEEP;
1082 if (!mapping) {
1083 /*
1084 * Some data journaling orphaned pages can have
1085 * page->mapping == NULL while being dirty with clean buffers.
1086 */
David Howells266cf652009-04-03 16:42:36 +01001087 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001088 if (try_to_free_buffers(page)) {
1089 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001090 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001091 return PAGE_CLEAN;
1092 }
1093 }
1094 return PAGE_KEEP;
1095 }
1096 if (mapping->a_ops->writepage == NULL)
1097 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001098 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001099 return PAGE_KEEP;
1100
1101 if (clear_page_dirty_for_io(page)) {
1102 int res;
1103 struct writeback_control wbc = {
1104 .sync_mode = WB_SYNC_NONE,
1105 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001106 .range_start = 0,
1107 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001108 .for_reclaim = 1,
1109 };
1110
1111 SetPageReclaim(page);
1112 res = mapping->a_ops->writepage(page, &wbc);
1113 if (res < 0)
1114 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001115 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001116 ClearPageReclaim(page);
1117 return PAGE_ACTIVATE;
1118 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001119
Linus Torvalds1da177e2005-04-16 15:20:36 -07001120 if (!PageWriteback(page)) {
1121 /* synchronous write or broken a_ops? */
1122 ClearPageReclaim(page);
1123 }
yalin wang3aa23852016-01-14 15:18:30 -08001124 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001125 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001126 return PAGE_SUCCESS;
1127 }
1128
1129 return PAGE_CLEAN;
1130}
1131
Andrew Mortona649fd92006-10-17 00:09:36 -07001132/*
Nick Piggine2867812008-07-25 19:45:30 -07001133 * Same as remove_mapping, but if the page is removed from the mapping, it
1134 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001135 */
Johannes Weinera5289102014-04-03 14:47:51 -07001136static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001137 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001138{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001139 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001140 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001141
Nick Piggin28e4d962006-09-25 23:31:23 -07001142 BUG_ON(!PageLocked(page));
1143 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001144
Johannes Weiner30472502021-09-02 14:53:18 -07001145 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001146 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001147 * The non racy check for a busy page.
1148 *
1149 * Must be careful with the order of the tests. When someone has
1150 * a ref to the page, it may be possible that they dirty it then
1151 * drop the reference. So if PageDirty is tested before page_count
1152 * here, then the following race may occur:
1153 *
1154 * get_user_pages(&page);
1155 * [user mapping goes away]
1156 * write_to(page);
1157 * !PageDirty(page) [good]
1158 * SetPageDirty(page);
1159 * put_page(page);
1160 * !page_count(page) [good, discard it]
1161 *
1162 * [oops, our write_to data is lost]
1163 *
1164 * Reversing the order of the tests ensures such a situation cannot
1165 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001166 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001167 *
1168 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001169 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001170 */
William Kucharski906d2782019-10-18 20:20:33 -07001171 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001172 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001173 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001174 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001175 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001176 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001177 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001178 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001179
1180 if (PageSwapCache(page)) {
1181 swp_entry_t swap = { .val = page_private(page) };
Yu Zhao37397872022-09-18 02:00:03 -06001182
1183 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001184 if (reclaimed && !mapping_exiting(mapping))
1185 shadow = workingset_eviction(page, target_memcg);
Yu Zhao37397872022-09-18 02:00:03 -06001186 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001187 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001188 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001189 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001190 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001191 void (*freepage)(struct page *);
1192
1193 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001194 /*
1195 * Remember a shadow entry for reclaimed file cache in
1196 * order to detect refaults, thus thrashing, later on.
1197 *
1198 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001199 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001200 * inode reclaim needs to empty out the radix tree or
1201 * the nodes are lost. Don't plant shadows behind its
1202 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001203 *
1204 * We also don't store shadows for DAX mappings because the
1205 * only page cache pages found in these are zero pages
1206 * covering holes, and because we don't want to mix DAX
1207 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001208 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001209 */
Huang Ying9de4f222020-04-06 20:04:41 -07001210 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001211 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001212 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001213 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001214 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001215
1216 if (freepage != NULL)
1217 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001218 }
1219
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001220 return 1;
1221
1222cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001223 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001224 return 0;
1225}
1226
Linus Torvalds1da177e2005-04-16 15:20:36 -07001227/*
Nick Piggine2867812008-07-25 19:45:30 -07001228 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1229 * someone else has a ref on the page, abort and return 0. If it was
1230 * successfully detached, return 1. Assumes the caller has a single ref on
1231 * this page.
1232 */
1233int remove_mapping(struct address_space *mapping, struct page *page)
1234{
Johannes Weinerb9107182019-11-30 17:55:59 -08001235 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001236 /*
1237 * Unfreezing the refcount with 1 rather than 2 effectively
1238 * drops the pagecache ref for us without requiring another
1239 * atomic operation.
1240 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001241 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001242 return 1;
1243 }
1244 return 0;
1245}
1246
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001247/**
1248 * putback_lru_page - put previously isolated page onto appropriate LRU list
1249 * @page: page to be put back to appropriate lru list
1250 *
1251 * Add previously isolated @page to appropriate LRU list.
1252 * Page may still be unevictable for other reasons.
1253 *
1254 * lru_lock must not be held, interrupts must be enabled.
1255 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001256void putback_lru_page(struct page *page)
1257{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001258 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001259 put_page(page); /* drop ref from isolate */
1260}
1261
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001262enum page_references {
1263 PAGEREF_RECLAIM,
1264 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001265 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001266 PAGEREF_ACTIVATE,
1267};
1268
1269static enum page_references page_check_references(struct page *page,
1270 struct scan_control *sc)
1271{
Johannes Weiner645747462010-03-05 13:42:22 -08001272 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001273 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001274
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001275 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1276 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001277 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001278
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001279 /*
1280 * Mlock lost the isolation race with us. Let try_to_unmap()
1281 * move the page to the unevictable list.
1282 */
1283 if (vm_flags & VM_LOCKED)
1284 return PAGEREF_RECLAIM;
1285
Minchan Kimf74aca72022-05-19 14:08:54 -07001286 /* rmap lock contention: rotate */
1287 if (referenced_ptes == -1)
1288 return PAGEREF_KEEP;
1289
Johannes Weiner645747462010-03-05 13:42:22 -08001290 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001291 /*
1292 * All mapped pages start out with page table
1293 * references from the instantiating fault, so we need
1294 * to look twice if a mapped file page is used more
1295 * than once.
1296 *
1297 * Mark it and spare it for another trip around the
1298 * inactive list. Another page table reference will
1299 * lead to its activation.
1300 *
1301 * Note: the mark is set for activated pages as well
1302 * so that recently deactivated but used pages are
1303 * quickly recovered.
1304 */
1305 SetPageReferenced(page);
1306
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001307 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001308 return PAGEREF_ACTIVATE;
1309
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001310 /*
1311 * Activate file-backed executable pages after first usage.
1312 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001313 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001314 return PAGEREF_ACTIVATE;
1315
Johannes Weiner645747462010-03-05 13:42:22 -08001316 return PAGEREF_KEEP;
1317 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001318
1319 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001320 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001321 return PAGEREF_RECLAIM_CLEAN;
1322
1323 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001324}
1325
Mel Gormane2be15f2013-07-03 15:01:57 -07001326/* Check if a page is dirty or under writeback */
1327static void page_check_dirty_writeback(struct page *page,
1328 bool *dirty, bool *writeback)
1329{
Mel Gormanb4597222013-07-03 15:02:05 -07001330 struct address_space *mapping;
1331
Mel Gormane2be15f2013-07-03 15:01:57 -07001332 /*
1333 * Anonymous pages are not handled by flushers and must be written
1334 * from reclaim context. Do not stall reclaim based on them
1335 */
Huang Ying9de4f222020-04-06 20:04:41 -07001336 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001337 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001338 *dirty = false;
1339 *writeback = false;
1340 return;
1341 }
1342
1343 /* By default assume that the page flags are accurate */
1344 *dirty = PageDirty(page);
1345 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001346
1347 /* Verify dirty/writeback state if the filesystem supports it */
1348 if (!page_has_private(page))
1349 return;
1350
1351 mapping = page_mapping(page);
1352 if (mapping && mapping->a_ops->is_dirty_writeback)
1353 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001354}
1355
Dave Hansen26aa2d12021-09-02 14:59:16 -07001356static struct page *alloc_demote_page(struct page *page, unsigned long node)
1357{
1358 struct migration_target_control mtc = {
1359 /*
1360 * Allocate from 'node', or fail quickly and quietly.
1361 * When this happens, 'page' will likely just be discarded
1362 * instead of migrated.
1363 */
1364 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1365 __GFP_THISNODE | __GFP_NOWARN |
1366 __GFP_NOMEMALLOC | GFP_NOWAIT,
1367 .nid = node
1368 };
1369
1370 return alloc_migration_target(page, (unsigned long)&mtc);
1371}
1372
1373/*
1374 * Take pages on @demote_list and attempt to demote them to
1375 * another node. Pages which are not demoted are left on
1376 * @demote_pages.
1377 */
1378static unsigned int demote_page_list(struct list_head *demote_pages,
1379 struct pglist_data *pgdat)
1380{
1381 int target_nid = next_demotion_node(pgdat->node_id);
1382 unsigned int nr_succeeded;
1383 int err;
1384
1385 if (list_empty(demote_pages))
1386 return 0;
1387
1388 if (target_nid == NUMA_NO_NODE)
1389 return 0;
1390
1391 /* Demotion ignores all cpuset and mempolicy settings */
1392 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1393 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1394 &nr_succeeded);
1395
Yang Shi668e4142021-09-02 14:59:19 -07001396 if (current_is_kswapd())
1397 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1398 else
1399 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1400
Dave Hansen26aa2d12021-09-02 14:59:16 -07001401 return nr_succeeded;
1402}
1403
Nick Piggine2867812008-07-25 19:45:30 -07001404/*
Andrew Morton1742f192006-03-22 00:08:21 -08001405 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001406 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001407static unsigned int shrink_page_list(struct list_head *page_list,
1408 struct pglist_data *pgdat,
1409 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001410 struct reclaim_stat *stat,
1411 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001412{
1413 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001414 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001415 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001416 unsigned int nr_reclaimed = 0;
1417 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001418 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001419
Kirill Tkhai060f0052019-03-05 15:48:15 -08001420 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001421 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001422 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001423
Dave Hansen26aa2d12021-09-02 14:59:16 -07001424retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001425 while (!list_empty(page_list)) {
1426 struct address_space *mapping;
1427 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001428 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001429 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001430 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001431
1432 cond_resched();
1433
1434 page = lru_to_page(page_list);
1435 list_del(&page->lru);
1436
Nick Piggin529ae9a2008-08-02 12:01:03 +02001437 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001438 goto keep;
1439
Sasha Levin309381fea2014-01-23 15:52:54 -08001440 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001441
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001442 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001443
1444 /* Account the number of base pages even though THP */
1445 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001446
Hugh Dickins39b5f292012-10-08 16:33:18 -07001447 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001448 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001449
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001450 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001451 goto keep_locked;
1452
Yu Zhao0182f922022-09-18 02:00:04 -06001453 /* page_update_gen() tried to promote this page? */
1454 if (lru_gen_enabled() && !ignore_references &&
1455 page_mapped(page) && PageReferenced(page))
1456 goto keep_locked;
1457
Andy Whitcroftc661b072007-08-22 14:01:26 -07001458 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1459 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1460
Mel Gorman283aba92013-07-03 15:01:51 -07001461 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001462 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001463 * reclaim_congested which affects wait_iff_congested. kswapd
1464 * will stall and start writing pages if the tail of the LRU
1465 * is all dirty unqueued pages.
1466 */
1467 page_check_dirty_writeback(page, &dirty, &writeback);
1468 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001469 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001470
1471 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001472 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001473
Mel Gormand04e8ac2013-07-03 15:02:03 -07001474 /*
1475 * Treat this page as congested if the underlying BDI is or if
1476 * pages are cycling through the LRU so quickly that the
1477 * pages marked for immediate reclaim are making it to the
1478 * end of the LRU a second time.
1479 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001480 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001481 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001482 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001483 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001484 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001485
1486 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001487 * If a page at the tail of the LRU is under writeback, there
1488 * are three cases to consider.
1489 *
1490 * 1) If reclaim is encountering an excessive number of pages
1491 * under writeback and this page is both under writeback and
1492 * PageReclaim then it indicates that pages are being queued
1493 * for IO but are being recycled through the LRU before the
1494 * IO can complete. Waiting on the page itself risks an
1495 * indefinite stall if it is impossible to writeback the
1496 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001497 * note that the LRU is being scanned too quickly and the
1498 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001499 *
Tejun Heo97c93412015-05-22 18:23:36 -04001500 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001501 * not marked for immediate reclaim, or the caller does not
1502 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1503 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001504 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001505 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001506 * Require may_enter_fs because we would wait on fs, which
1507 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001508 * enter reclaim, and deadlock if it waits on a page for
1509 * which it is needed to do the write (loop masks off
1510 * __GFP_IO|__GFP_FS for this reason); but more thought
1511 * would probably show more reasons.
1512 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001513 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001514 * PageReclaim. memcg does not have any dirty pages
1515 * throttling so we could easily OOM just because too many
1516 * pages are in writeback and there is nothing else to
1517 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001518 *
1519 * In cases 1) and 2) we activate the pages to get them out of
1520 * the way while we continue scanning for clean pages on the
1521 * inactive list and refilling from the active list. The
1522 * observation here is that waiting for disk writes is more
1523 * expensive than potentially causing reloads down the line.
1524 * Since they're marked for immediate reclaim, they won't put
1525 * memory pressure on the cache working set any longer than it
1526 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001527 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001528 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001529 /* Case 1 above */
1530 if (current_is_kswapd() &&
1531 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001532 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001533 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001534 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001535
1536 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001537 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001538 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001539 /*
1540 * This is slightly racy - end_page_writeback()
1541 * might have just cleared PageReclaim, then
1542 * setting PageReclaim here end up interpreted
1543 * as PageReadahead - but that does not matter
1544 * enough to care. What we do want is for this
1545 * page to have PageReclaim set next time memcg
1546 * reclaim reaches the tests above, so it will
1547 * then wait_on_page_writeback() to avoid OOM;
1548 * and it's also appropriate in global reclaim.
1549 */
1550 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001551 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001552 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001553
1554 /* Case 3 above */
1555 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001556 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001557 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001558 /* then go back and try same page again */
1559 list_add_tail(&page->lru, page_list);
1560 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001561 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001562 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001563
Minchan Kim8940b342019-09-25 16:49:11 -07001564 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001565 references = page_check_references(page, sc);
1566
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001567 switch (references) {
1568 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001569 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001570 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001571 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001572 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001573 case PAGEREF_RECLAIM:
1574 case PAGEREF_RECLAIM_CLEAN:
1575 ; /* try to reclaim the page below */
1576 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001577
Linus Torvalds1da177e2005-04-16 15:20:36 -07001578 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001579 * Before reclaiming the page, try to relocate
1580 * its contents to another node.
1581 */
1582 if (do_demote_pass &&
1583 (thp_migration_supported() || !PageTransHuge(page))) {
1584 list_add(&page->lru, &demote_pages);
1585 unlock_page(page);
1586 continue;
1587 }
1588
1589 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001590 * Anonymous process memory has backing store?
1591 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001592 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001593 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001594 if (PageAnon(page) && PageSwapBacked(page)) {
1595 if (!PageSwapCache(page)) {
1596 if (!(sc->gfp_mask & __GFP_IO))
1597 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001598 if (page_maybe_dma_pinned(page))
1599 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001600 if (PageTransHuge(page)) {
1601 /* cannot split THP, skip it */
1602 if (!can_split_huge_page(page, NULL))
1603 goto activate_locked;
1604 /*
1605 * Split pages without a PMD map right
1606 * away. Chances are some or all of the
1607 * tail pages can be freed without IO.
1608 */
1609 if (!compound_mapcount(page) &&
1610 split_huge_page_to_list(page,
1611 page_list))
1612 goto activate_locked;
1613 }
1614 if (!add_to_swap(page)) {
1615 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001616 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001617 /* Fallback to swap normal pages */
1618 if (split_huge_page_to_list(page,
1619 page_list))
1620 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001621#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1622 count_vm_event(THP_SWPOUT_FALLBACK);
1623#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001624 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001625 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001626 }
Minchan Kim0f074652017-07-06 15:37:24 -07001627
Kirill Tkhai4b793062020-04-01 21:10:18 -07001628 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001629
1630 /* Adding to swap updated mapping */
1631 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001632 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001633 } else if (unlikely(PageTransHuge(page))) {
1634 /* Split file THP */
1635 if (split_huge_page_to_list(page, page_list))
1636 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001637 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001638
1639 /*
Yang Shi98879b32019-07-11 20:59:30 -07001640 * THP may get split above, need minus tail pages and update
1641 * nr_pages to avoid accounting tail pages twice.
1642 *
1643 * The tail pages that are added into swap cache successfully
1644 * reach here.
1645 */
1646 if ((nr_pages > 1) && !PageTransHuge(page)) {
1647 sc->nr_scanned -= (nr_pages - 1);
1648 nr_pages = 1;
1649 }
1650
1651 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001652 * The page is mapped into the page tables of one or more
1653 * processes. Try to unmap it here.
1654 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001655 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001656 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001657 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001658
1659 if (unlikely(PageTransHuge(page)))
1660 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001661
Yang Shi1fb08ac2021-06-30 18:52:01 -07001662 try_to_unmap(page, flags);
1663 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001664 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001665 if (!was_swapbacked && PageSwapBacked(page))
1666 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001667 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001668 }
1669 }
1670
1671 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001672 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001673 * Only kswapd can writeback filesystem pages
1674 * to avoid risk of stack overflow. But avoid
1675 * injecting inefficient single-page IO into
1676 * flusher writeback as much as possible: only
1677 * write pages when we've encountered many
1678 * dirty pages, and when we've already scanned
1679 * the rest of the LRU for clean pages and see
1680 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001681 */
Huang Ying9de4f222020-04-06 20:04:41 -07001682 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001683 (!current_is_kswapd() || !PageReclaim(page) ||
1684 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001685 /*
1686 * Immediately reclaim when written back.
1687 * Similar in principal to deactivate_page()
1688 * except we already have the page isolated
1689 * and know it's dirty
1690 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001691 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001692 SetPageReclaim(page);
1693
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001694 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001695 }
1696
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001697 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001698 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001699 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001700 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001701 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001702 goto keep_locked;
1703
Mel Gormand950c942015-09-04 15:47:35 -07001704 /*
1705 * Page is dirty. Flush the TLB if a writable entry
1706 * potentially exists to avoid CPU writes after IO
1707 * starts and then write it out here.
1708 */
1709 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001710 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001711 case PAGE_KEEP:
1712 goto keep_locked;
1713 case PAGE_ACTIVATE:
1714 goto activate_locked;
1715 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001716 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001717
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001718 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001719 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001720 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001721 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001722
Linus Torvalds1da177e2005-04-16 15:20:36 -07001723 /*
1724 * A synchronous write - probably a ramdisk. Go
1725 * ahead and try to reclaim the page.
1726 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001727 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001728 goto keep;
1729 if (PageDirty(page) || PageWriteback(page))
1730 goto keep_locked;
1731 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001732 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001733 case PAGE_CLEAN:
1734 ; /* try to free the page below */
1735 }
1736 }
1737
1738 /*
1739 * If the page has buffers, try to free the buffer mappings
1740 * associated with this page. If we succeed we try to free
1741 * the page as well.
1742 *
1743 * We do this even if the page is PageDirty().
1744 * try_to_release_page() does not perform I/O, but it is
1745 * possible for a page to have PageDirty set, but it is actually
1746 * clean (all its buffers are clean). This happens if the
1747 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001748 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001749 * try_to_release_page() will discover that cleanness and will
1750 * drop the buffers and mark the page clean - it can be freed.
1751 *
1752 * Rarely, pages can have buffers and no ->mapping. These are
1753 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001754 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001755 * and if that worked, and the page is no longer mapped into
1756 * process address space (page_count == 1) it can be freed.
1757 * Otherwise, leave the page on the LRU so it is swappable.
1758 */
David Howells266cf652009-04-03 16:42:36 +01001759 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001760 if (!try_to_release_page(page, sc->gfp_mask))
1761 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001762 if (!mapping && page_count(page) == 1) {
1763 unlock_page(page);
1764 if (put_page_testzero(page))
1765 goto free_it;
1766 else {
1767 /*
1768 * rare race with speculative reference.
1769 * the speculative reference will free
1770 * this page shortly, so we may
1771 * increment nr_reclaimed here (and
1772 * leave it off the LRU).
1773 */
1774 nr_reclaimed++;
1775 continue;
1776 }
1777 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001778 }
1779
Shaohua Li802a3a92017-05-03 14:52:32 -07001780 if (PageAnon(page) && !PageSwapBacked(page)) {
1781 /* follow __remove_mapping for reference */
1782 if (!page_ref_freeze(page, 1))
1783 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001784 /*
1785 * The page has only one reference left, which is
1786 * from the isolation. After the caller puts the
1787 * page back on lru and drops the reference, the
1788 * page will be freed anyway. It doesn't matter
1789 * which lru it goes. So we don't bother checking
1790 * PageDirty here.
1791 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001792 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001793 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001794 } else if (!mapping || !__remove_mapping(mapping, page, true,
1795 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001796 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001797
1798 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001799free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001800 /*
1801 * THP may get swapped out in a whole, need account
1802 * all base pages.
1803 */
1804 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001805
1806 /*
1807 * Is there need to periodically free_page_list? It would
1808 * appear not as the counts should be low
1809 */
Yang Shi7ae88532019-09-23 15:38:09 -07001810 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001811 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001812 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001813 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001814 continue;
1815
Yang Shi98879b32019-07-11 20:59:30 -07001816activate_locked_split:
1817 /*
1818 * The tail pages that are failed to add into swap cache
1819 * reach here. Fixup nr_scanned and nr_pages.
1820 */
1821 if (nr_pages > 1) {
1822 sc->nr_scanned -= (nr_pages - 1);
1823 nr_pages = 1;
1824 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001825activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001826 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001827 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1828 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001829 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001830 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001831 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001832 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001833 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001834 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001835 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001836 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001837keep_locked:
1838 unlock_page(page);
1839keep:
1840 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001841 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001842 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001843 /* 'page_list' is always empty here */
1844
1845 /* Migrate pages selected for demotion */
1846 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1847 /* Pages that could not be demoted are still in @demote_pages */
1848 if (!list_empty(&demote_pages)) {
1849 /* Pages which failed to demoted go back on @page_list for retry: */
1850 list_splice_init(&demote_pages, page_list);
1851 do_demote_pass = false;
1852 goto retry;
1853 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001854
Yang Shi98879b32019-07-11 20:59:30 -07001855 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1856
Johannes Weiner747db952014-08-08 14:19:24 -07001857 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001858 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001859 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001860
Linus Torvalds1da177e2005-04-16 15:20:36 -07001861 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001862 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001863
Andrew Morton05ff5132006-03-22 00:08:20 -08001864 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001865}
1866
Maninder Singh730ec8c2020-06-03 16:01:18 -07001867unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001868 struct list_head *page_list)
1869{
1870 struct scan_control sc = {
1871 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001872 .may_unmap = 1,
1873 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001874 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001875 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001876 struct page *page, *next;
1877 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001878 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001879
1880 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001881 if (!PageHuge(page) && page_is_file_lru(page) &&
1882 !PageDirty(page) && !__PageMovable(page) &&
1883 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001884 ClearPageActive(page);
1885 list_move(&page->lru, &clean_pages);
1886 }
1887 }
1888
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001889 /*
1890 * We should be safe here since we are only dealing with file pages and
1891 * we are not kswapd and therefore cannot write dirty file pages. But
1892 * call memalloc_noreclaim_save() anyway, just in case these conditions
1893 * change in the future.
1894 */
1895 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001896 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001897 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001898 memalloc_noreclaim_restore(noreclaim_flag);
1899
Minchan Kim02c6de82012-10-08 16:31:55 -07001900 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001901 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1902 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001903 /*
1904 * Since lazyfree pages are isolated from file LRU from the beginning,
1905 * they will rotate back to anonymous LRU in the end if it failed to
1906 * discard so isolated count will be mismatched.
1907 * Compensate the isolated count for both LRU lists.
1908 */
1909 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1910 stat.nr_lazyfree_fail);
1911 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001912 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001913 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001914}
1915
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001916/*
Mel Gorman7ee36a12016-07-28 15:47:17 -07001917 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001918 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001919 */
1920static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001921 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001922{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001923 int zid;
1924
Mel Gorman7ee36a12016-07-28 15:47:17 -07001925 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1926 if (!nr_zone_taken[zid])
1927 continue;
1928
Wei Yanga892cb62020-06-03 16:01:12 -07001929 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001930 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001931
Mel Gorman7ee36a12016-07-28 15:47:17 -07001932}
1933
Mel Gormanf611fab2021-06-30 18:53:19 -07001934/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001935 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1936 *
1937 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001938 * shrink the lists perform better by taking out a batch of pages
1939 * and working on them outside the LRU lock.
1940 *
1941 * For pagecache intensive workloads, this function is the hottest
1942 * spot in the kernel (apart from copy_*_user functions).
1943 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001944 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001945 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001946 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001947 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001948 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001949 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001950 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001951 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001952 *
1953 * returns how many pages were moved onto *@dst.
1954 */
Andrew Morton69e05942006-03-22 00:08:19 -08001955static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001956 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001957 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001958 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001959{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001960 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001961 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001962 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001963 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07001964 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001965 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07001966 LIST_HEAD(pages_skipped);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001967
Yang Shi98879b32019-07-11 20:59:30 -07001968 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001969 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07001970 while (scan < nr_to_scan && !list_empty(src)) {
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001971 struct list_head *move_to = src;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001972 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001973
Linus Torvalds1da177e2005-04-16 15:20:36 -07001974 page = lru_to_page(src);
1975 prefetchw_prev_lru_page(page, src, flags);
1976
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001977 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001978 total_scan += nr_pages;
1979
Mel Gormanb2e18752016-07-28 15:45:37 -07001980 if (page_zonenum(page) > sc->reclaim_idx) {
Yang Shi98879b32019-07-11 20:59:30 -07001981 nr_skipped[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001982 move_to = &pages_skipped;
1983 goto move;
Mel Gormanb2e18752016-07-28 15:45:37 -07001984 }
1985
Minchan Kim791b48b2017-05-12 15:47:06 -07001986 /*
1987 * Do not count skipped pages because that makes the function
1988 * return with no isolated pages if the LRU mostly contains
1989 * ineligible pages. This causes the VM to not reclaim any
1990 * pages, triggering a premature OOM.
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001991 * Account all tail pages of THP.
Minchan Kim791b48b2017-05-12 15:47:06 -07001992 */
Yang Shi98879b32019-07-11 20:59:30 -07001993 scan += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001994
1995 if (!PageLRU(page))
1996 goto move;
1997 if (!sc->may_unmap && page_mapped(page))
1998 goto move;
1999
Alex Shic2135f72021-02-24 12:08:01 -08002000 /*
2001 * Be careful not to clear PageLRU until after we're
2002 * sure the page is not being freed elsewhere -- the
2003 * page release code relies on it.
2004 */
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002005 if (unlikely(!get_page_unless_zero(page)))
2006 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002007
2008 if (!TestClearPageLRU(page)) {
2009 /* Another thread is already isolating this page */
2010 put_page(page);
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002011 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002012 }
2013
2014 nr_taken += nr_pages;
2015 nr_zone_taken[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002016 move_to = dst;
2017move:
2018 list_move(&page->lru, move_to);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002019 }
2020
Mel Gormanb2e18752016-07-28 15:45:37 -07002021 /*
2022 * Splice any skipped pages to the start of the LRU list. Note that
2023 * this disrupts the LRU order when reclaiming for lower zones but
2024 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2025 * scanning would soon rescan the same pages to skip and put the
2026 * system at risk of premature OOM.
2027 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002028 if (!list_empty(&pages_skipped)) {
2029 int zid;
2030
Johannes Weiner3db65812017-05-03 14:52:13 -07002031 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002032 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2033 if (!nr_skipped[zid])
2034 continue;
2035
2036 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002037 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002038 }
2039 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002040 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002041 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002042 total_scan, skipped, nr_taken,
2043 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002044 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002045 return nr_taken;
2046}
2047
Nick Piggin62695a82008-10-18 20:26:09 -07002048/**
2049 * isolate_lru_page - tries to isolate a page from its LRU list
2050 * @page: page to isolate from its LRU list
2051 *
2052 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2053 * vmstat statistic corresponding to whatever LRU list the page was on.
2054 *
2055 * Returns 0 if the page was removed from an LRU list.
2056 * Returns -EBUSY if the page was not on an LRU list.
2057 *
2058 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002059 * the active list, it will have PageActive set. If it was found on
2060 * the unevictable list, it will have the PageUnevictable bit set. That flag
2061 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002062 *
2063 * The vmstat statistic corresponding to the list on which the page was
2064 * found will be decremented.
2065 *
2066 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002067 *
Nick Piggin62695a82008-10-18 20:26:09 -07002068 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002069 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002070 * without a stable reference).
2071 * (2) the lru_lock must not be held.
2072 * (3) interrupts must be enabled.
2073 */
2074int isolate_lru_page(struct page *page)
2075{
2076 int ret = -EBUSY;
2077
Sasha Levin309381fea2014-01-23 15:52:54 -08002078 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002079 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002080
Alex Shid25b5bd2020-12-15 12:34:16 -08002081 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002082 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002083
Alex Shid25b5bd2020-12-15 12:34:16 -08002084 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002085 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002086 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002087 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002088 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002089 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002090
Nick Piggin62695a82008-10-18 20:26:09 -07002091 return ret;
2092}
2093
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002094/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002095 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002096 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002097 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2098 * the LRU list will go small and be scanned faster than necessary, leading to
2099 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002100 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002101static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002102 struct scan_control *sc)
2103{
2104 unsigned long inactive, isolated;
2105
2106 if (current_is_kswapd())
2107 return 0;
2108
Johannes Weinerb5ead352019-11-30 17:55:40 -08002109 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002110 return 0;
2111
2112 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002113 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2114 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002115 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002116 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2117 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002118 }
2119
Fengguang Wu3cf23842012-12-18 14:23:31 -08002120 /*
2121 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2122 * won't get blocked by normal direct-reclaimers, forming a circular
2123 * deadlock.
2124 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002125 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002126 inactive >>= 3;
2127
Rik van Riel35cd7812009-09-21 17:01:38 -07002128 return isolated > inactive;
2129}
2130
Kirill Tkhaia222f342019-05-13 17:17:00 -07002131/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002132 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2133 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002134 *
2135 * Returns the number of pages moved to the given lruvec.
2136 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002137static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2138 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002139{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002140 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002141 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002142 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002143
Kirill Tkhaia222f342019-05-13 17:17:00 -07002144 while (!list_empty(list)) {
2145 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002146 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002147 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002148 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002149 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002150 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002151 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002152 continue;
2153 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002154
Alex Shi3d06afa2020-12-15 12:33:37 -08002155 /*
2156 * The SetPageLRU needs to be kept here for list integrity.
2157 * Otherwise:
2158 * #0 move_pages_to_lru #1 release_pages
2159 * if !put_page_testzero
2160 * if (put_page_testzero())
2161 * !PageLRU //skip lru_lock
2162 * SetPageLRU()
2163 * list_add(&page->lru,)
2164 * list_add(&page->lru,)
2165 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002166 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002167
Alex Shi3d06afa2020-12-15 12:33:37 -08002168 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002169 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002170
2171 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002172 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002173 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002174 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002175 } else
2176 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002177
2178 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002179 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002180
Alex Shiafca9152020-12-15 12:34:02 -08002181 /*
2182 * All pages were isolated from the same lruvec (and isolation
2183 * inhibits memcg migration).
2184 */
Muchun Song7467c392021-06-28 19:37:59 -07002185 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002186 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002187 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002188 nr_moved += nr_pages;
2189 if (PageActive(page))
2190 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002191 }
Mel Gorman66635622010-08-09 17:19:30 -07002192
Hugh Dickins3f797682012-01-12 17:20:07 -08002193 /*
2194 * To save our caller's stack, now use input list for pages to free.
2195 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002196 list_splice(&pages_to_free, list);
2197
2198 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002199}
2200
2201/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002202 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002203 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002204 * In that case we should only throttle if the backing device it is
2205 * writing to is congested. In other cases it is safe to throttle.
2206 */
2207static int current_may_throttle(void)
2208{
NeilBrowna37b0712020-06-01 21:48:18 -07002209 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002210 current->backing_dev_info == NULL ||
2211 bdi_write_congested(current->backing_dev_info);
2212}
2213
2214/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002215 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002216 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002217 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002218static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002219shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002220 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002221{
2222 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002223 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002224 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002225 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002226 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002227 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002228 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002229 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002230 bool stalled = false;
Minchan Kim7df45e52022-10-27 08:29:17 -07002231 struct blk_plug plug;
2232 bool do_plug = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002233
Mel Gorman599d0c92016-07-28 15:45:31 -07002234 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002235 if (stalled)
2236 return 0;
2237
2238 /* wait a bit for the reclaimer. */
2239 msleep(100);
2240 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002241
2242 /* We are about to die and free our memory. Return now. */
2243 if (fatal_signal_pending(current))
2244 return SWAP_CLUSTER_MAX;
2245 }
2246
Linus Torvalds1da177e2005-04-16 15:20:36 -07002247 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002248
Alex Shi6168d0d2020-12-15 12:34:29 -08002249 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002250
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002251 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002252 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002253
Mel Gorman599d0c92016-07-28 15:45:31 -07002254 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002255 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002256 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002257 __count_vm_events(item, nr_scanned);
2258 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002259 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2260
Alex Shi6168d0d2020-12-15 12:34:29 -08002261 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002262
Hillf Dantond563c052012-03-21 16:34:02 -07002263 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002264 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002265
Minchan Kim7df45e52022-10-27 08:29:17 -07002266 trace_android_vh_shrink_inactive_list_blk_plug(&do_plug);
2267 if (do_plug)
2268 blk_start_plug(&plug);
Shakeel Butt013339d2020-12-14 19:06:39 -08002269 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002270
Alex Shi6168d0d2020-12-15 12:34:29 -08002271 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002272 move_pages_to_lru(lruvec, &page_list);
2273
2274 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002275 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002276 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002277 __count_vm_events(item, nr_reclaimed);
2278 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002279 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002280 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002281
Minchan Kim7df45e52022-10-27 08:29:17 -07002282 if (do_plug)
2283 blk_finish_plug(&plug);
2284
Alex Shi75cc3c92020-12-15 14:20:50 -08002285 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002286 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002287 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002288
Mel Gorman92df3a72011-10-31 17:07:56 -07002289 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002290 * If dirty pages are scanned that are not queued for IO, it
2291 * implies that flushers are not doing their job. This can
2292 * happen when memory pressure pushes dirty pages to the end of
2293 * the LRU before the dirty limits are breached and the dirty
2294 * data has expired. It can also happen when the proportion of
2295 * dirty pages grows not through writes but through memory
2296 * pressure reclaiming all the clean cache. And in some cases,
2297 * the flushers simply cannot keep up with the allocation
2298 * rate. Nudge the flusher threads in case they are asleep.
2299 */
2300 if (stat.nr_unqueued_dirty == nr_taken)
2301 wakeup_flusher_threads(WB_REASON_VMSCAN);
2302
Andrey Ryabinind108c772018-04-10 16:27:59 -07002303 sc->nr.dirty += stat.nr_dirty;
2304 sc->nr.congested += stat.nr_congested;
2305 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2306 sc->nr.writeback += stat.nr_writeback;
2307 sc->nr.immediate += stat.nr_immediate;
2308 sc->nr.taken += nr_taken;
2309 if (file)
2310 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002311
Mel Gorman599d0c92016-07-28 15:45:31 -07002312 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002313 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002314 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002315}
2316
Hugh Dickins15b44732020-12-15 14:21:31 -08002317/*
2318 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2319 *
2320 * We move them the other way if the page is referenced by one or more
2321 * processes.
2322 *
2323 * If the pages are mostly unmapped, the processing is fast and it is
2324 * appropriate to hold lru_lock across the whole operation. But if
2325 * the pages are mapped, the processing is slow (page_referenced()), so
2326 * we should drop lru_lock around each page. It's impossible to balance
2327 * this, so instead we remove the pages from the LRU while processing them.
2328 * It is safe to rely on PG_active against the non-LRU pages in here because
2329 * nobody will play with that bit on a non-LRU page.
2330 *
2331 * The downside is that we have to touch page->_refcount against each page.
2332 * But we had to alter page->flags anyway.
2333 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002334static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002335 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002336 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002337 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002338{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002339 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002340 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002341 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002342 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002343 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002344 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002345 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002346 unsigned nr_deactivate, nr_activate;
2347 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002348 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002349 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002350 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002351
2352 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002353
Alex Shi6168d0d2020-12-15 12:34:29 -08002354 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002355
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002356 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002357 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002358
Mel Gorman599d0c92016-07-28 15:45:31 -07002359 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002360
Shakeel Butt912c0572020-08-06 23:26:32 -07002361 if (!cgroup_reclaim(sc))
2362 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002363 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002364
Alex Shi6168d0d2020-12-15 12:34:29 -08002365 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002366
Linus Torvalds1da177e2005-04-16 15:20:36 -07002367 while (!list_empty(&l_hold)) {
2368 cond_resched();
2369 page = lru_to_page(&l_hold);
2370 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002371
Hugh Dickins39b5f292012-10-08 16:33:18 -07002372 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002373 putback_lru_page(page);
2374 continue;
2375 }
2376
Mel Gormancc715d92012-03-21 16:34:00 -07002377 if (unlikely(buffer_heads_over_limit)) {
2378 if (page_has_private(page) && trylock_page(page)) {
2379 if (page_has_private(page))
2380 try_to_release_page(page, 0);
2381 unlock_page(page);
2382 }
2383 }
2384
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002385 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2386 if (bypass)
2387 goto skip_page_referenced;
2388
Minchan Kimf74aca72022-05-19 14:08:54 -07002389 /* Referenced or rmap lock contention: rotate */
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002390 if (page_referenced(page, 0, sc->target_mem_cgroup,
Minchan Kimf74aca72022-05-19 14:08:54 -07002391 &vm_flags) != 0) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002392 /*
2393 * Identify referenced, file-backed active pages and
2394 * give them one more trip around the active list. So
2395 * that executable code get better chances to stay in
2396 * memory under moderate memory pressure. Anon pages
2397 * are not likely to be evicted by use-once streaming
2398 * IO, plus JVM can create lots of anon VM_EXEC pages,
2399 * so we ignore them here.
2400 */
Huang Ying9de4f222020-04-06 20:04:41 -07002401 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002402 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002403 list_add(&page->lru, &l_active);
2404 continue;
2405 }
2406 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002407skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002408 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002409 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002410 list_add(&page->lru, &l_inactive);
2411 }
2412
Andrew Mortonb5557492009-01-06 14:40:13 -08002413 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002414 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002415 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002416 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002417
Kirill Tkhaia222f342019-05-13 17:17:00 -07002418 nr_activate = move_pages_to_lru(lruvec, &l_active);
2419 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002420 /* Keep all free pages in l_active list */
2421 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002422
2423 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2424 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2425
Mel Gorman599d0c92016-07-28 15:45:31 -07002426 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002427 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002428
Kirill Tkhaif372d892019-05-13 17:16:57 -07002429 mem_cgroup_uncharge_list(&l_active);
2430 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002431 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2432 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002433}
2434
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002435unsigned long reclaim_pages(struct list_head *page_list)
2436{
Yang Shif661d002020-04-01 21:10:05 -07002437 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002438 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002439 LIST_HEAD(node_page_list);
2440 struct reclaim_stat dummy_stat;
2441 struct page *page;
Minchan Kim7df45e52022-10-27 08:29:17 -07002442 struct blk_plug plug;
2443 bool do_plug = false;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002444 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002445 struct scan_control sc = {
2446 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002447 .may_writepage = 1,
2448 .may_unmap = 1,
2449 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002450 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002451 };
2452
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002453 noreclaim_flag = memalloc_noreclaim_save();
2454
Minchan Kim7df45e52022-10-27 08:29:17 -07002455 trace_android_vh_reclaim_pages_plug(&do_plug);
2456 if (do_plug)
2457 blk_start_plug(&plug);
2458
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002459 while (!list_empty(page_list)) {
2460 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002461 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002462 nid = page_to_nid(page);
2463 INIT_LIST_HEAD(&node_page_list);
2464 }
2465
2466 if (nid == page_to_nid(page)) {
2467 ClearPageActive(page);
2468 list_move(&page->lru, &node_page_list);
2469 continue;
2470 }
2471
2472 nr_reclaimed += shrink_page_list(&node_page_list,
2473 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002474 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002475 while (!list_empty(&node_page_list)) {
2476 page = lru_to_page(&node_page_list);
2477 list_del(&page->lru);
2478 putback_lru_page(page);
2479 }
2480
Yang Shif661d002020-04-01 21:10:05 -07002481 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002482 }
2483
2484 if (!list_empty(&node_page_list)) {
2485 nr_reclaimed += shrink_page_list(&node_page_list,
2486 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002487 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002488 while (!list_empty(&node_page_list)) {
2489 page = lru_to_page(&node_page_list);
2490 list_del(&page->lru);
2491 putback_lru_page(page);
2492 }
2493 }
2494
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002495 memalloc_noreclaim_restore(noreclaim_flag);
2496
Minchan Kim7df45e52022-10-27 08:29:17 -07002497 if (do_plug)
2498 blk_finish_plug(&plug);
2499
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002500 return nr_reclaimed;
2501}
2502
Johannes Weinerb91ac372019-11-30 17:56:02 -08002503static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2504 struct lruvec *lruvec, struct scan_control *sc)
2505{
2506 if (is_active_lru(lru)) {
2507 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2508 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2509 else
2510 sc->skipped_deactivate = 1;
2511 return 0;
2512 }
2513
2514 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2515}
2516
Rik van Riel59dc76b2016-05-20 16:56:31 -07002517/*
2518 * The inactive anon list should be small enough that the VM never has
2519 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002520 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002521 * The inactive file list should be small enough to leave most memory
2522 * to the established workingset on the scan-resistant active list,
2523 * but large enough to avoid thrashing the aggregate readahead window.
2524 *
2525 * Both inactive lists should also be large enough that each inactive
2526 * page has a chance to be referenced again before it is reclaimed.
2527 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002528 * If that fails and refaulting is observed, the inactive list grows.
2529 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002530 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002531 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002532 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2533 *
2534 * total target max
2535 * memory ratio inactive
2536 * -------------------------------------
2537 * 10MB 1 5MB
2538 * 100MB 1 50MB
2539 * 1GB 3 250MB
2540 * 10GB 10 0.9GB
2541 * 100GB 31 3GB
2542 * 1TB 101 10GB
2543 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002544 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002545static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002546{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002547 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002548 unsigned long inactive, active;
2549 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002550 unsigned long gb;
2551
Johannes Weinerb91ac372019-11-30 17:56:02 -08002552 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2553 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002554
Johannes Weinerb91ac372019-11-30 17:56:02 -08002555 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002556 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002557 inactive_ratio = int_sqrt(10 * gb);
2558 else
2559 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002560
Rik van Riel59dc76b2016-05-20 16:56:31 -07002561 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002562}
2563
Johannes Weiner9a265112013-02-22 16:32:17 -08002564enum scan_balance {
2565 SCAN_EQUAL,
2566 SCAN_FRACT,
2567 SCAN_ANON,
2568 SCAN_FILE,
2569};
2570
Yu Zhao6d313442022-09-18 02:00:00 -06002571static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2572{
2573 unsigned long file;
2574 struct lruvec *target_lruvec;
2575
Yu Zhao37397872022-09-18 02:00:03 -06002576 if (lru_gen_enabled())
2577 return;
2578
Yu Zhao6d313442022-09-18 02:00:00 -06002579 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2580
2581 /*
2582 * Flush the memory cgroup stats, so that we read accurate per-memcg
2583 * lruvec stats for heuristics.
2584 */
2585 mem_cgroup_flush_stats();
2586
2587 /*
2588 * Determine the scan balance between anon and file LRUs.
2589 */
2590 spin_lock_irq(&target_lruvec->lru_lock);
2591 sc->anon_cost = target_lruvec->anon_cost;
2592 sc->file_cost = target_lruvec->file_cost;
2593 spin_unlock_irq(&target_lruvec->lru_lock);
2594
2595 /*
2596 * Target desirable inactive:active list ratios for the anon
2597 * and file LRU lists.
2598 */
2599 if (!sc->force_deactivate) {
2600 unsigned long refaults;
2601
2602 refaults = lruvec_page_state(target_lruvec,
2603 WORKINGSET_ACTIVATE_ANON);
2604 if (refaults != target_lruvec->refaults[0] ||
2605 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2606 sc->may_deactivate |= DEACTIVATE_ANON;
2607 else
2608 sc->may_deactivate &= ~DEACTIVATE_ANON;
2609
2610 /*
2611 * When refaults are being observed, it means a new
2612 * workingset is being established. Deactivate to get
2613 * rid of any stale active pages quickly.
2614 */
2615 refaults = lruvec_page_state(target_lruvec,
2616 WORKINGSET_ACTIVATE_FILE);
2617 if (refaults != target_lruvec->refaults[1] ||
2618 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2619 sc->may_deactivate |= DEACTIVATE_FILE;
2620 else
2621 sc->may_deactivate &= ~DEACTIVATE_FILE;
2622 } else
2623 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2624
2625 /*
2626 * If we have plenty of inactive file pages that aren't
2627 * thrashing, try to reclaim those first before touching
2628 * anonymous pages.
2629 */
2630 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2631 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2632 sc->cache_trim_mode = 1;
2633 else
2634 sc->cache_trim_mode = 0;
2635
2636 /*
2637 * Prevent the reclaimer from falling into the cache trap: as
2638 * cache pages start out inactive, every cache fault will tip
2639 * the scan balance towards the file LRU. And as the file LRU
2640 * shrinks, so does the window for rotation from references.
2641 * This means we have a runaway feedback loop where a tiny
2642 * thrashing file LRU becomes infinitely more attractive than
2643 * anon pages. Try to detect this based on file LRU size.
2644 */
2645 if (!cgroup_reclaim(sc)) {
2646 unsigned long total_high_wmark = 0;
2647 unsigned long free, anon;
2648 int z;
2649
2650 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2651 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2652 node_page_state(pgdat, NR_INACTIVE_FILE);
2653
2654 for (z = 0; z < MAX_NR_ZONES; z++) {
2655 struct zone *zone = &pgdat->node_zones[z];
2656
2657 if (!managed_zone(zone))
2658 continue;
2659
2660 total_high_wmark += high_wmark_pages(zone);
2661 }
2662
2663 /*
2664 * Consider anon: if that's low too, this isn't a
2665 * runaway file reclaim problem, but rather just
2666 * extreme pressure. Reclaim as per usual then.
2667 */
2668 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2669
2670 sc->file_is_tiny =
2671 file + free <= total_high_wmark &&
2672 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2673 anon >> sc->priority;
2674 }
2675}
2676
Linus Torvalds1da177e2005-04-16 15:20:36 -07002677/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002678 * Determine how aggressively the anon and file LRU lists should be
2679 * scanned. The relative value of each set of LRU lists is determined
2680 * by looking at the fraction of the pages scanned we did rotate back
2681 * onto the active list instead of evict.
2682 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002683 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2684 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002685 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002686static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2687 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002688{
Keith Buscha2a36482021-09-02 14:59:26 -07002689 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002690 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002691 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002692 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002693 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002694 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002695 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002696 unsigned long ap, fp;
2697 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002698 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002699
2700 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002701 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002702 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002703 goto out;
2704 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002705
Johannes Weiner10316b32013-02-22 16:32:14 -08002706 /*
2707 * Global reclaim will swap to prevent OOM even with no
2708 * swappiness, but memcg users want to use this knob to
2709 * disable swapping for individual groups completely when
2710 * using the memory controller's swap limit feature would be
2711 * too expensive.
2712 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002713 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002714 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002715 goto out;
2716 }
2717
2718 /*
2719 * Do not apply any pressure balancing cleverness when the
2720 * system is close to OOM, scan both anon and file equally
2721 * (unless the swappiness setting disagrees with swapping).
2722 */
Johannes Weiner02695172014-08-06 16:06:17 -07002723 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002724 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002725 goto out;
2726 }
2727
Johannes Weiner11d16c22013-02-22 16:32:15 -08002728 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002729 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002730 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002731 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002732 scan_balance = SCAN_ANON;
2733 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002734 }
2735
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002736 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2737
Johannes Weiner62376252014-05-06 12:50:07 -07002738 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002739 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002740 * anything from the anonymous working right now. But when balancing
2741 * anon and page cache files for reclaim, allow swapping of anon pages
2742 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002743 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002744 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002745 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002746 goto out;
2747 }
2748
Johannes Weiner9a265112013-02-22 16:32:17 -08002749 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002750 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002751 * Calculate the pressure balance between anon and file pages.
2752 *
2753 * The amount of pressure we put on each LRU is inversely
2754 * proportional to the cost of reclaiming each list, as
2755 * determined by the share of pages that are refaulting, times
2756 * the relative IO cost of bringing back a swapped out
2757 * anonymous page vs reloading a filesystem page (swappiness).
2758 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002759 * Although we limit that influence to ensure no list gets
2760 * left behind completely: at least a third of the pressure is
2761 * applied, before swappiness.
2762 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002763 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002764 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002765 total_cost = sc->anon_cost + sc->file_cost;
2766 anon_cost = total_cost + sc->anon_cost;
2767 file_cost = total_cost + sc->file_cost;
2768 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002769
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002770 ap = swappiness * (total_cost + 1);
2771 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002772
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002773 fp = (200 - swappiness) * (total_cost + 1);
2774 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002775
Shaohua Li76a33fc2010-05-24 14:32:36 -07002776 fraction[0] = ap;
2777 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002778 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002779out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002780 for_each_evictable_lru(lru) {
2781 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002782 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002783 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002784 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002785
Chris Down9783aa92019-10-06 17:58:32 -07002786 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002787 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2788 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002789
Johannes Weinerf56ce412021-08-19 19:04:21 -07002790 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002791 /*
2792 * Scale a cgroup's reclaim pressure by proportioning
2793 * its current usage to its memory.low or memory.min
2794 * setting.
2795 *
2796 * This is important, as otherwise scanning aggression
2797 * becomes extremely binary -- from nothing as we
2798 * approach the memory protection threshold, to totally
2799 * nominal as we exceed it. This results in requiring
2800 * setting extremely liberal protection thresholds. It
2801 * also means we simply get no protection at all if we
2802 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002803 *
2804 * If there is any protection in place, we reduce scan
2805 * pressure by how much of the total memory used is
2806 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002807 *
Chris Down9de7ca42019-10-06 17:58:35 -07002808 * There is one special case: in the first reclaim pass,
2809 * we skip over all groups that are within their low
2810 * protection. If that fails to reclaim enough pages to
2811 * satisfy the reclaim goal, we come back and override
2812 * the best-effort low protection. However, we still
2813 * ideally want to honor how well-behaved groups are in
2814 * that case instead of simply punishing them all
2815 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002816 * memory they are using, reducing the scan pressure
2817 * again by how much of the total memory used is under
2818 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002819 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002820 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002821 unsigned long protection;
2822
2823 /* memory.low scaling, make sure we retry before OOM */
2824 if (!sc->memcg_low_reclaim && low > min) {
2825 protection = low;
2826 sc->memcg_low_skipped = 1;
2827 } else {
2828 protection = min;
2829 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002830
2831 /* Avoid TOCTOU with earlier protection check */
2832 cgroup_size = max(cgroup_size, protection);
2833
2834 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002835 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002836
2837 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002838 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002839 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002840 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002841 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002842 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002843 } else {
2844 scan = lruvec_size;
2845 }
2846
2847 scan >>= sc->priority;
2848
Johannes Weiner688035f2017-05-03 14:52:07 -07002849 /*
2850 * If the cgroup's already been deleted, make sure to
2851 * scrape out the remaining cache.
2852 */
2853 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002854 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002855
Johannes Weiner688035f2017-05-03 14:52:07 -07002856 switch (scan_balance) {
2857 case SCAN_EQUAL:
2858 /* Scan lists relative to size */
2859 break;
2860 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002861 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002862 * Scan types proportional to swappiness and
2863 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002864 * Make sure we don't miss the last page on
2865 * the offlined memory cgroups because of a
2866 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002867 */
Gavin Shan76073c62020-02-20 20:04:24 -08002868 scan = mem_cgroup_online(memcg) ?
2869 div64_u64(scan * fraction[file], denominator) :
2870 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002871 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002872 break;
2873 case SCAN_FILE:
2874 case SCAN_ANON:
2875 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002876 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002877 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002878 break;
2879 default:
2880 /* Look ma, no brain */
2881 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002882 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002883
Johannes Weiner688035f2017-05-03 14:52:07 -07002884 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002885 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002886}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002887
Dave Hansen2f368a92021-09-02 14:59:23 -07002888/*
2889 * Anonymous LRU management is a waste if there is
2890 * ultimately no way to reclaim the memory.
2891 */
2892static bool can_age_anon_pages(struct pglist_data *pgdat,
2893 struct scan_control *sc)
2894{
2895 /* Aging the anon LRU is valuable if swap is present: */
2896 if (total_swap_pages > 0)
2897 return true;
2898
2899 /* Also valuable if anon pages can be demoted: */
2900 return can_demote(pgdat->node_id, sc);
2901}
2902
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002903#ifdef CONFIG_LRU_GEN
2904
Yu Zhaobaeb9a02022-09-18 02:00:07 -06002905#ifdef CONFIG_LRU_GEN_ENABLED
2906DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2907#define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2908#else
2909DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2910#define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2911#endif
2912
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002913/******************************************************************************
2914 * shorthand helpers
2915 ******************************************************************************/
2916
Yu Zhao37397872022-09-18 02:00:03 -06002917#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2918
2919#define DEFINE_MAX_SEQ(lruvec) \
2920 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2921
2922#define DEFINE_MIN_SEQ(lruvec) \
2923 unsigned long min_seq[ANON_AND_FILE] = { \
2924 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2925 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2926 }
2927
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002928#define for_each_gen_type_zone(gen, type, zone) \
2929 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2930 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2931 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2932
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002933static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002934{
2935 struct pglist_data *pgdat = NODE_DATA(nid);
2936
2937#ifdef CONFIG_MEMCG
2938 if (memcg) {
2939 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2940
2941 /* for hotadd_new_pgdat() */
2942 if (!lruvec->pgdat)
2943 lruvec->pgdat = pgdat;
2944
2945 return lruvec;
2946 }
2947#endif
2948 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2949
2950 return pgdat ? &pgdat->__lruvec : NULL;
2951}
2952
Yu Zhao37397872022-09-18 02:00:03 -06002953static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2954{
2955 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2956 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2957
Kalesh Singh650081b2023-02-14 14:17:57 -08002958 if (!can_demote(pgdat->node_id, sc))
Yu Zhao37397872022-09-18 02:00:03 -06002959 return 0;
2960
2961 return mem_cgroup_swappiness(memcg);
2962}
2963
2964static int get_nr_gens(struct lruvec *lruvec, int type)
2965{
2966 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2967}
2968
2969static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2970{
Yu Zhao3c6c3592022-12-21 21:18:59 -07002971 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06002972 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2973 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2974 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2975}
2976
2977/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002978 * mm_struct list
2979 ******************************************************************************/
2980
2981static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
2982{
2983 static struct lru_gen_mm_list mm_list = {
2984 .fifo = LIST_HEAD_INIT(mm_list.fifo),
2985 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
2986 };
2987
2988#ifdef CONFIG_MEMCG
2989 if (memcg)
2990 return &memcg->mm_list;
2991#endif
2992 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2993
2994 return &mm_list;
2995}
2996
2997void lru_gen_add_mm(struct mm_struct *mm)
2998{
2999 int nid;
3000 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3001 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3002
3003 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3004#ifdef CONFIG_MEMCG
3005 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3006 mm->lru_gen.memcg = memcg;
3007#endif
3008 spin_lock(&mm_list->lock);
3009
3010 for_each_node_state(nid, N_MEMORY) {
3011 struct lruvec *lruvec = get_lruvec(memcg, nid);
3012
3013 if (!lruvec)
3014 continue;
3015
3016 /* the first addition since the last iteration */
3017 if (lruvec->mm_state.tail == &mm_list->fifo)
3018 lruvec->mm_state.tail = &mm->lru_gen.list;
3019 }
3020
3021 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3022
3023 spin_unlock(&mm_list->lock);
3024}
3025
3026void lru_gen_del_mm(struct mm_struct *mm)
3027{
3028 int nid;
3029 struct lru_gen_mm_list *mm_list;
3030 struct mem_cgroup *memcg = NULL;
3031
3032 if (list_empty(&mm->lru_gen.list))
3033 return;
3034
3035#ifdef CONFIG_MEMCG
3036 memcg = mm->lru_gen.memcg;
3037#endif
3038 mm_list = get_mm_list(memcg);
3039
3040 spin_lock(&mm_list->lock);
3041
3042 for_each_node(nid) {
3043 struct lruvec *lruvec = get_lruvec(memcg, nid);
3044
3045 if (!lruvec)
3046 continue;
3047
3048 /* where the last iteration ended (exclusive) */
3049 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3050 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3051
3052 /* where the current iteration continues (inclusive) */
3053 if (lruvec->mm_state.head != &mm->lru_gen.list)
3054 continue;
3055
3056 lruvec->mm_state.head = lruvec->mm_state.head->next;
3057 /* the deletion ends the current iteration */
3058 if (lruvec->mm_state.head == &mm_list->fifo)
3059 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3060 }
3061
3062 list_del_init(&mm->lru_gen.list);
3063
3064 spin_unlock(&mm_list->lock);
3065
3066#ifdef CONFIG_MEMCG
3067 mem_cgroup_put(mm->lru_gen.memcg);
3068 mm->lru_gen.memcg = NULL;
3069#endif
3070}
3071
3072#ifdef CONFIG_MEMCG
3073void lru_gen_migrate_mm(struct mm_struct *mm)
3074{
3075 struct mem_cgroup *memcg;
3076 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3077
3078 VM_WARN_ON_ONCE(task->mm != mm);
3079 lockdep_assert_held(&task->alloc_lock);
3080
3081 /* for mm_update_next_owner() */
3082 if (mem_cgroup_disabled())
3083 return;
3084
Yu Zhao578a3a32023-01-15 20:44:05 -07003085 /* migration can happen before addition */
3086 if (!mm->lru_gen.memcg)
3087 return;
3088
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003089 rcu_read_lock();
3090 memcg = mem_cgroup_from_task(task);
3091 rcu_read_unlock();
3092 if (memcg == mm->lru_gen.memcg)
3093 return;
3094
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003095 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3096
3097 lru_gen_del_mm(mm);
3098 lru_gen_add_mm(mm);
3099}
3100#endif
3101
3102/*
3103 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3104 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3105 * bits in a bitmap, k is the number of hash functions and n is the number of
3106 * inserted items.
3107 *
3108 * Page table walkers use one of the two filters to reduce their search space.
3109 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3110 * aging uses the double-buffering technique to flip to the other filter each
3111 * time it produces a new generation. For non-leaf entries that have enough
3112 * leaf entries, the aging carries them over to the next generation in
3113 * walk_pmd_range(); the eviction also report them when walking the rmap
3114 * in lru_gen_look_around().
3115 *
3116 * For future optimizations:
3117 * 1. It's not necessary to keep both filters all the time. The spare one can be
3118 * freed after the RCU grace period and reallocated if needed again.
3119 * 2. And when reallocating, it's worth scaling its size according to the number
3120 * of inserted entries in the other filter, to reduce the memory overhead on
3121 * small systems and false positives on large systems.
3122 * 3. Jenkins' hash function is an alternative to Knuth's.
3123 */
3124#define BLOOM_FILTER_SHIFT 15
3125
3126static inline int filter_gen_from_seq(unsigned long seq)
3127{
3128 return seq % NR_BLOOM_FILTERS;
3129}
3130
3131static void get_item_key(void *item, int *key)
3132{
3133 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3134
3135 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3136
3137 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3138 key[1] = hash >> BLOOM_FILTER_SHIFT;
3139}
3140
3141static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3142{
3143 unsigned long *filter;
3144 int gen = filter_gen_from_seq(seq);
3145
3146 filter = lruvec->mm_state.filters[gen];
3147 if (filter) {
3148 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3149 return;
3150 }
3151
3152 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3153 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3154 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3155}
3156
3157static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3158{
3159 int key[2];
3160 unsigned long *filter;
3161 int gen = filter_gen_from_seq(seq);
3162
3163 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3164 if (!filter)
3165 return;
3166
3167 get_item_key(item, key);
3168
3169 if (!test_bit(key[0], filter))
3170 set_bit(key[0], filter);
3171 if (!test_bit(key[1], filter))
3172 set_bit(key[1], filter);
3173}
3174
3175static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3176{
3177 int key[2];
3178 unsigned long *filter;
3179 int gen = filter_gen_from_seq(seq);
3180
3181 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3182 if (!filter)
3183 return true;
3184
3185 get_item_key(item, key);
3186
3187 return test_bit(key[0], filter) && test_bit(key[1], filter);
3188}
3189
3190static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3191{
3192 int i;
3193 int hist;
3194
3195 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3196
3197 if (walk) {
3198 hist = lru_hist_from_seq(walk->max_seq);
3199
3200 for (i = 0; i < NR_MM_STATS; i++) {
3201 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3202 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3203 walk->mm_stats[i] = 0;
3204 }
3205 }
3206
3207 if (NR_HIST_GENS > 1 && last) {
3208 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3209
3210 for (i = 0; i < NR_MM_STATS; i++)
3211 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3212 }
3213}
3214
3215static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3216{
3217 int type;
3218 unsigned long size = 0;
3219 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3220 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3221
3222 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3223 return true;
3224
3225 clear_bit(key, &mm->lru_gen.bitmap);
3226
3227 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3228 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3229 get_mm_counter(mm, MM_ANONPAGES) +
3230 get_mm_counter(mm, MM_SHMEMPAGES);
3231 }
3232
3233 if (size < MIN_LRU_BATCH)
3234 return true;
3235
3236 return !mmget_not_zero(mm);
3237}
3238
3239static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3240 struct mm_struct **iter)
3241{
3242 bool first = false;
3243 bool last = true;
3244 struct mm_struct *mm = NULL;
3245 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3246 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3247 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3248
3249 /*
3250 * There are four interesting cases for this page table walker:
3251 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3252 * there is nothing left to do.
3253 * 2. It's the first of the current generation, and it needs to reset
3254 * the Bloom filter for the next generation.
3255 * 3. It reaches the end of mm_list, and it needs to increment
3256 * mm_state->seq; the iteration is done.
3257 * 4. It's the last of the current generation, and it needs to reset the
3258 * mm stats counters for the next generation.
3259 */
3260 spin_lock(&mm_list->lock);
3261
3262 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3263 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3264 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3265
3266 if (walk->max_seq <= mm_state->seq) {
3267 if (!*iter)
3268 last = false;
3269 goto done;
3270 }
3271
3272 if (!mm_state->nr_walkers) {
3273 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3274
3275 mm_state->head = mm_list->fifo.next;
3276 first = true;
3277 }
3278
3279 while (!mm && mm_state->head != &mm_list->fifo) {
3280 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3281
3282 mm_state->head = mm_state->head->next;
3283
3284 /* force scan for those added after the last iteration */
3285 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3286 mm_state->tail = mm_state->head;
3287 walk->force_scan = true;
3288 }
3289
3290 if (should_skip_mm(mm, walk))
3291 mm = NULL;
3292 }
3293
3294 if (mm_state->head == &mm_list->fifo)
3295 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3296done:
3297 if (*iter && !mm)
3298 mm_state->nr_walkers--;
3299 if (!*iter && mm)
3300 mm_state->nr_walkers++;
3301
3302 if (mm_state->nr_walkers)
3303 last = false;
3304
3305 if (*iter || last)
3306 reset_mm_stats(lruvec, walk, last);
3307
3308 spin_unlock(&mm_list->lock);
3309
3310 if (mm && first)
3311 reset_bloom_filter(lruvec, walk->max_seq + 1);
3312
3313 if (*iter)
3314 mmput_async(*iter);
3315
3316 *iter = mm;
3317
3318 return last;
3319}
3320
3321static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3322{
3323 bool success = false;
3324 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3325 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3326 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3327
3328 spin_lock(&mm_list->lock);
3329
3330 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3331
3332 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3333 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3334
3335 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3336 reset_mm_stats(lruvec, NULL, true);
3337 success = true;
3338 }
3339
3340 spin_unlock(&mm_list->lock);
3341
3342 return success;
3343}
3344
3345/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003346 * refault feedback loop
3347 ******************************************************************************/
3348
3349/*
3350 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3351 *
3352 * The P term is refaulted/(evicted+protected) from a tier in the generation
3353 * currently being evicted; the I term is the exponential moving average of the
3354 * P term over the generations previously evicted, using the smoothing factor
3355 * 1/2; the D term isn't supported.
3356 *
3357 * The setpoint (SP) is always the first tier of one type; the process variable
3358 * (PV) is either any tier of the other type or any other tier of the same
3359 * type.
3360 *
3361 * The error is the difference between the SP and the PV; the correction is to
3362 * turn off protection when SP>PV or turn on protection when SP<PV.
3363 *
3364 * For future optimizations:
3365 * 1. The D term may discount the other two terms over time so that long-lived
3366 * generations can resist stale information.
3367 */
3368struct ctrl_pos {
3369 unsigned long refaulted;
3370 unsigned long total;
3371 int gain;
3372};
3373
3374static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3375 struct ctrl_pos *pos)
3376{
Yu Zhao3c6c3592022-12-21 21:18:59 -07003377 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003378 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3379
3380 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3381 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3382 pos->total = lrugen->avg_total[type][tier] +
3383 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3384 if (tier)
3385 pos->total += lrugen->protected[hist][type][tier - 1];
3386 pos->gain = gain;
3387}
3388
3389static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3390{
3391 int hist, tier;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003392 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003393 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3394 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3395
3396 lockdep_assert_held(&lruvec->lru_lock);
3397
3398 if (!carryover && !clear)
3399 return;
3400
3401 hist = lru_hist_from_seq(seq);
3402
3403 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3404 if (carryover) {
3405 unsigned long sum;
3406
3407 sum = lrugen->avg_refaulted[type][tier] +
3408 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3409 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3410
3411 sum = lrugen->avg_total[type][tier] +
3412 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3413 if (tier)
3414 sum += lrugen->protected[hist][type][tier - 1];
3415 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3416 }
3417
3418 if (clear) {
3419 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3420 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3421 if (tier)
3422 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3423 }
3424 }
3425}
3426
3427static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3428{
3429 /*
3430 * Return true if the PV has a limited number of refaults or a lower
3431 * refaulted/total than the SP.
3432 */
3433 return pv->refaulted < MIN_LRU_BATCH ||
3434 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3435 (sp->refaulted + 1) * pv->total * pv->gain;
3436}
3437
3438/******************************************************************************
3439 * the aging
3440 ******************************************************************************/
3441
Yu Zhao0182f922022-09-18 02:00:04 -06003442/* promote pages accessed through page tables */
3443static int page_update_gen(struct page *page, int gen)
3444{
3445 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3446
3447 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3448 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3449
3450 do {
3451 /* lru_gen_del_page() has isolated this page? */
3452 if (!(old_flags & LRU_GEN_MASK)) {
3453 /* for shrink_page_list() */
3454 new_flags = old_flags | BIT(PG_referenced);
3455 continue;
3456 }
3457
3458 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3459 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3460 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3461
3462 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3463}
3464
Yu Zhao37397872022-09-18 02:00:03 -06003465/* protect pages accessed multiple times through file descriptors */
3466static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3467{
3468 int type = page_is_file_lru(page);
Yu Zhao3c6c3592022-12-21 21:18:59 -07003469 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003470 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3471 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3472
3473 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3474
3475 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003476 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3477 /* page_update_gen() has promoted this page? */
3478 if (new_gen >= 0 && new_gen != old_gen)
3479 return new_gen;
3480
Yu Zhao37397872022-09-18 02:00:03 -06003481 new_gen = (old_gen + 1) % MAX_NR_GENS;
3482
3483 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3484 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3485 /* for end_page_writeback() */
3486 if (reclaiming)
3487 new_flags |= BIT(PG_reclaim);
3488 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3489
3490 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3491
3492 return new_gen;
3493}
3494
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003495static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3496 int old_gen, int new_gen)
3497{
3498 int type = page_is_file_lru(page);
3499 int zone = page_zonenum(page);
3500 int delta = thp_nr_pages(page);
3501
3502 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3503 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3504
3505 walk->batched++;
3506
3507 walk->nr_pages[old_gen][type][zone] -= delta;
3508 walk->nr_pages[new_gen][type][zone] += delta;
3509}
3510
3511static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3512{
3513 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003514 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003515
3516 walk->batched = 0;
3517
3518 for_each_gen_type_zone(gen, type, zone) {
3519 enum lru_list lru = type * LRU_INACTIVE_FILE;
3520 int delta = walk->nr_pages[gen][type][zone];
3521
3522 if (!delta)
3523 continue;
3524
3525 walk->nr_pages[gen][type][zone] = 0;
3526 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3527 lrugen->nr_pages[gen][type][zone] + delta);
3528
3529 if (lru_gen_is_active(lruvec, gen))
3530 lru += LRU_ACTIVE;
3531 __update_lru_size(lruvec, lru, zone, delta);
3532 }
3533}
3534
3535static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3536{
3537 struct address_space *mapping;
3538 struct vm_area_struct *vma = args->vma;
3539 struct lru_gen_mm_walk *walk = args->private;
3540
3541 if (!vma_is_accessible(vma))
3542 return true;
3543
3544 if (is_vm_hugetlb_page(vma))
3545 return true;
3546
3547 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3548 return true;
3549
3550 if (vma == get_gate_vma(vma->vm_mm))
3551 return true;
3552
3553 if (vma_is_anonymous(vma))
3554 return !walk->can_swap;
3555
3556 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3557 return true;
3558
3559 mapping = vma->vm_file->f_mapping;
3560 if (mapping_unevictable(mapping))
3561 return true;
3562
3563 if (shmem_mapping(mapping))
3564 return !walk->can_swap;
3565
3566 /* to exclude special mappings like dax, etc. */
3567 return !mapping->a_ops->readpage;
3568}
3569
3570/*
3571 * Some userspace memory allocators map many single-page VMAs. Instead of
3572 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3573 * table to reduce zigzags and improve cache performance.
3574 */
3575static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3576 unsigned long *vm_start, unsigned long *vm_end)
3577{
3578 unsigned long start = round_up(*vm_end, size);
3579 unsigned long end = (start | ~mask) + 1;
3580
3581 VM_WARN_ON_ONCE(mask & size);
3582 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3583
3584 while (args->vma) {
3585 if (start >= args->vma->vm_end) {
3586 args->vma = args->vma->vm_next;
3587 continue;
3588 }
3589
3590 if (end && end <= args->vma->vm_start)
3591 return false;
3592
3593 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3594 args->vma = args->vma->vm_next;
3595 continue;
3596 }
3597
3598 *vm_start = max(start, args->vma->vm_start);
3599 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3600
3601 return true;
3602 }
3603
3604 return false;
3605}
3606
Yu Zhao0182f922022-09-18 02:00:04 -06003607static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3608{
3609 unsigned long pfn = pte_pfn(pte);
3610
3611 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3612
3613 if (!pte_present(pte) || is_zero_pfn(pfn))
3614 return -1;
3615
3616 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3617 return -1;
3618
3619 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3620 return -1;
3621
3622 return pfn;
3623}
3624
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003625#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3626static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3627{
3628 unsigned long pfn = pmd_pfn(pmd);
3629
3630 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3631
3632 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3633 return -1;
3634
3635 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3636 return -1;
3637
3638 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3639 return -1;
3640
3641 return pfn;
3642}
3643#endif
3644
Yu Zhao0182f922022-09-18 02:00:04 -06003645static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003646 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003647{
3648 struct page *page;
3649
3650 /* try to avoid unnecessary memory loads */
3651 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3652 return NULL;
3653
3654 page = compound_head(pfn_to_page(pfn));
3655 if (page_to_nid(page) != pgdat->node_id)
3656 return NULL;
3657
3658 if (page_memcg_rcu(page) != memcg)
3659 return NULL;
3660
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003661 /* file VMAs can contain anon pages from COW */
3662 if (!page_is_file_lru(page) && !can_swap)
3663 return NULL;
3664
Yu Zhao0182f922022-09-18 02:00:04 -06003665 return page;
3666}
3667
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003668static bool suitable_to_scan(int total, int young)
3669{
3670 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3671
3672 /* suitable if the average number of young PTEs per cacheline is >=1 */
3673 return young * n >= total;
3674}
3675
3676static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3677 struct mm_walk *args)
3678{
3679 int i;
3680 pte_t *pte;
3681 spinlock_t *ptl;
3682 unsigned long addr;
3683 int total = 0;
3684 int young = 0;
3685 struct lru_gen_mm_walk *walk = args->private;
3686 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3687 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3688 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3689
3690 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3691
3692 ptl = pte_lockptr(args->mm, pmd);
3693 if (!spin_trylock(ptl))
3694 return false;
3695
3696 arch_enter_lazy_mmu_mode();
3697
3698 pte = pte_offset_map(pmd, start & PMD_MASK);
3699restart:
3700 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3701 unsigned long pfn;
3702 struct page *page;
3703
3704 total++;
3705 walk->mm_stats[MM_LEAF_TOTAL]++;
3706
3707 pfn = get_pte_pfn(pte[i], args->vma, addr);
3708 if (pfn == -1)
3709 continue;
3710
3711 if (!pte_young(pte[i])) {
3712 walk->mm_stats[MM_LEAF_OLD]++;
3713 continue;
3714 }
3715
3716 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3717 if (!page)
3718 continue;
3719
3720 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3721 VM_WARN_ON_ONCE(true);
3722
3723 young++;
3724 walk->mm_stats[MM_LEAF_YOUNG]++;
3725
3726 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3727 !(PageAnon(page) && PageSwapBacked(page) &&
3728 !PageSwapCache(page)))
3729 set_page_dirty(page);
3730
3731 old_gen = page_update_gen(page, new_gen);
3732 if (old_gen >= 0 && old_gen != new_gen)
3733 update_batch_size(walk, page, old_gen, new_gen);
3734 }
3735
3736 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3737 goto restart;
3738
3739 pte_unmap(pte);
3740
3741 arch_leave_lazy_mmu_mode();
3742 spin_unlock(ptl);
3743
3744 return suitable_to_scan(total, young);
3745}
3746
3747#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3748static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3749 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3750{
3751 int i;
3752 pmd_t *pmd;
3753 spinlock_t *ptl;
3754 struct lru_gen_mm_walk *walk = args->private;
3755 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3756 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3757 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3758
3759 VM_WARN_ON_ONCE(pud_leaf(*pud));
3760
3761 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3762 if (*start == -1) {
3763 *start = next;
3764 return;
3765 }
3766
3767 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3768 if (i && i <= MIN_LRU_BATCH) {
3769 __set_bit(i - 1, bitmap);
3770 return;
3771 }
3772
3773 pmd = pmd_offset(pud, *start);
3774
3775 ptl = pmd_lockptr(args->mm, pmd);
3776 if (!spin_trylock(ptl))
3777 goto done;
3778
3779 arch_enter_lazy_mmu_mode();
3780
3781 do {
3782 unsigned long pfn;
3783 struct page *page;
3784 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3785
3786 pfn = get_pmd_pfn(pmd[i], vma, addr);
3787 if (pfn == -1)
3788 goto next;
3789
3790 if (!pmd_trans_huge(pmd[i])) {
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003791 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3792 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003793 pmdp_test_and_clear_young(vma, addr, pmd + i);
3794 goto next;
3795 }
3796
3797 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3798 if (!page)
3799 goto next;
3800
3801 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3802 goto next;
3803
3804 walk->mm_stats[MM_LEAF_YOUNG]++;
3805
3806 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3807 !(PageAnon(page) && PageSwapBacked(page) &&
3808 !PageSwapCache(page)))
3809 set_page_dirty(page);
3810
3811 old_gen = page_update_gen(page, new_gen);
3812 if (old_gen >= 0 && old_gen != new_gen)
3813 update_batch_size(walk, page, old_gen, new_gen);
3814next:
3815 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3816 } while (i <= MIN_LRU_BATCH);
3817
3818 arch_leave_lazy_mmu_mode();
3819 spin_unlock(ptl);
3820done:
3821 *start = -1;
3822 bitmap_zero(bitmap, MIN_LRU_BATCH);
3823}
3824#else
3825static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3826 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3827{
3828}
3829#endif
3830
3831static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3832 struct mm_walk *args)
3833{
3834 int i;
3835 pmd_t *pmd;
3836 unsigned long next;
3837 unsigned long addr;
3838 struct vm_area_struct *vma;
3839 unsigned long pos = -1;
3840 struct lru_gen_mm_walk *walk = args->private;
3841 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3842
3843 VM_WARN_ON_ONCE(pud_leaf(*pud));
3844
3845 /*
3846 * Finish an entire PMD in two passes: the first only reaches to PTE
3847 * tables to avoid taking the PMD lock; the second, if necessary, takes
3848 * the PMD lock to clear the accessed bit in PMD entries.
3849 */
3850 pmd = pmd_offset(pud, start & PUD_MASK);
3851restart:
3852 /* walk_pte_range() may call get_next_vma() */
3853 vma = args->vma;
3854 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3855 pmd_t val = pmd_read_atomic(pmd + i);
3856
3857 /* for pmd_read_atomic() */
3858 barrier();
3859
3860 next = pmd_addr_end(addr, end);
3861
3862 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3863 walk->mm_stats[MM_LEAF_TOTAL]++;
3864 continue;
3865 }
3866
3867#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3868 if (pmd_trans_huge(val)) {
3869 unsigned long pfn = pmd_pfn(val);
3870 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3871
3872 walk->mm_stats[MM_LEAF_TOTAL]++;
3873
3874 if (!pmd_young(val)) {
3875 walk->mm_stats[MM_LEAF_OLD]++;
3876 continue;
3877 }
3878
3879 /* try to avoid unnecessary memory loads */
3880 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3881 continue;
3882
3883 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3884 continue;
3885 }
3886#endif
3887 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3888
3889#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003890 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3891 if (!pmd_young(val))
3892 continue;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003893
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003894 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3895 }
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003896#endif
3897 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3898 continue;
3899
3900 walk->mm_stats[MM_NONLEAF_FOUND]++;
3901
3902 if (!walk_pte_range(&val, addr, next, args))
3903 continue;
3904
3905 walk->mm_stats[MM_NONLEAF_ADDED]++;
3906
3907 /* carry over to the next generation */
3908 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3909 }
3910
3911 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3912
3913 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3914 goto restart;
3915}
3916
3917static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3918 struct mm_walk *args)
3919{
3920 int i;
3921 pud_t *pud;
3922 unsigned long addr;
3923 unsigned long next;
3924 struct lru_gen_mm_walk *walk = args->private;
3925
3926 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3927
3928 pud = pud_offset(p4d, start & P4D_MASK);
3929restart:
3930 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3931 pud_t val = READ_ONCE(pud[i]);
3932
3933 next = pud_addr_end(addr, end);
3934
3935 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3936 continue;
3937
3938 walk_pmd_range(&val, addr, next, args);
3939
3940 /* a racy check to curtail the waiting time */
3941 if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
3942 return 1;
3943
3944 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3945 end = (addr | ~PUD_MASK) + 1;
3946 goto done;
3947 }
3948 }
3949
3950 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3951 goto restart;
3952
3953 end = round_up(end, P4D_SIZE);
3954done:
3955 if (!end || !args->vma)
3956 return 1;
3957
3958 walk->next_addr = max(end, args->vma->vm_start);
3959
3960 return -EAGAIN;
3961}
3962
3963static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3964{
3965 static const struct mm_walk_ops mm_walk_ops = {
3966 .test_walk = should_skip_vma,
3967 .p4d_entry = walk_pud_range,
3968 };
3969
3970 int err;
3971 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3972
3973 walk->next_addr = FIRST_USER_ADDRESS;
3974
3975 do {
3976 err = -EBUSY;
3977
3978 /* page_update_gen() requires stable page_memcg() */
3979 if (!mem_cgroup_trylock_pages(memcg))
3980 break;
3981
3982 /* the caller might be holding the lock for write */
3983 if (mmap_read_trylock(mm)) {
3984 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3985
3986 mmap_read_unlock(mm);
3987 }
3988
3989 mem_cgroup_unlock_pages();
3990
3991 if (walk->batched) {
3992 spin_lock_irq(&lruvec->lru_lock);
3993 reset_batch_size(lruvec, walk);
3994 spin_unlock_irq(&lruvec->lru_lock);
3995 }
3996
3997 cond_resched();
3998 } while (err == -EAGAIN);
3999}
4000
4001static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
4002{
4003 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4004
4005 if (pgdat && current_is_kswapd()) {
4006 VM_WARN_ON_ONCE(walk);
4007
4008 walk = &pgdat->mm_walk;
4009 } else if (!pgdat && !walk) {
4010 VM_WARN_ON_ONCE(current_is_kswapd());
4011
4012 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4013 }
4014
4015 current->reclaim_state->mm_walk = walk;
4016
4017 return walk;
4018}
4019
4020static void clear_mm_walk(void)
4021{
4022 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4023
4024 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4025 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4026
4027 current->reclaim_state->mm_walk = NULL;
4028
4029 if (!current_is_kswapd())
4030 kfree(walk);
4031}
4032
Yu Zhao4983c522022-09-18 02:00:09 -06004033static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004034{
Yu Zhao4983c522022-09-18 02:00:09 -06004035 int zone;
4036 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004037 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06004038 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
Yu Zhao37397872022-09-18 02:00:03 -06004039
Yu Zhao4983c522022-09-18 02:00:09 -06004040 if (type == LRU_GEN_ANON && !can_swap)
4041 goto done;
4042
4043 /* prevent cold/hot inversion if force_scan is true */
4044 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004045 struct list_head *head = &lrugen->pages[old_gen][type][zone];
Yu Zhao4983c522022-09-18 02:00:09 -06004046
4047 while (!list_empty(head)) {
4048 struct page *page = lru_to_page(head);
4049
4050 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4051 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4052 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4053 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4054
4055 new_gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004056 list_move_tail(&page->lru, &lrugen->pages[new_gen][type][zone]);
Yu Zhao4983c522022-09-18 02:00:09 -06004057
4058 if (!--remaining)
4059 return false;
4060 }
4061 }
4062done:
Yu Zhao37397872022-09-18 02:00:03 -06004063 reset_ctrl_pos(lruvec, type, true);
4064 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
Yu Zhao4983c522022-09-18 02:00:09 -06004065
4066 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004067}
4068
4069static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4070{
4071 int gen, type, zone;
4072 bool success = false;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004073 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004074 DEFINE_MIN_SEQ(lruvec);
4075
4076 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4077
4078 /* find the oldest populated generation */
4079 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4080 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4081 gen = lru_gen_from_seq(min_seq[type]);
4082
4083 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004084 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhao37397872022-09-18 02:00:03 -06004085 goto next;
4086 }
4087
4088 min_seq[type]++;
4089 }
4090next:
4091 ;
4092 }
4093
Yu Zhao3c6c3592022-12-21 21:18:59 -07004094 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06004095 if (can_swap) {
4096 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4097 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4098 }
4099
4100 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4101 if (min_seq[type] == lrugen->min_seq[type])
4102 continue;
4103
4104 reset_ctrl_pos(lruvec, type, true);
4105 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4106 success = true;
4107 }
4108
4109 return success;
4110}
4111
Yu Zhao4983c522022-09-18 02:00:09 -06004112static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
Yu Zhao37397872022-09-18 02:00:03 -06004113{
4114 int prev, next;
4115 int type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004116 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004117
4118 spin_lock_irq(&lruvec->lru_lock);
4119
4120 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4121
Yu Zhao37397872022-09-18 02:00:03 -06004122 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4123 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4124 continue;
4125
Yu Zhao4983c522022-09-18 02:00:09 -06004126 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
Yu Zhao37397872022-09-18 02:00:03 -06004127
Yu Zhao4983c522022-09-18 02:00:09 -06004128 while (!inc_min_seq(lruvec, type, can_swap)) {
4129 spin_unlock_irq(&lruvec->lru_lock);
4130 cond_resched();
4131 spin_lock_irq(&lruvec->lru_lock);
4132 }
Yu Zhao37397872022-09-18 02:00:03 -06004133 }
4134
4135 /*
4136 * Update the active/inactive LRU sizes for compatibility. Both sides of
4137 * the current max_seq need to be covered, since max_seq+1 can overlap
4138 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4139 * overlap, cold/hot inversion happens.
4140 */
4141 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4142 next = lru_gen_from_seq(lrugen->max_seq + 1);
4143
4144 for (type = 0; type < ANON_AND_FILE; type++) {
4145 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4146 enum lru_list lru = type * LRU_INACTIVE_FILE;
4147 long delta = lrugen->nr_pages[prev][type][zone] -
4148 lrugen->nr_pages[next][type][zone];
4149
4150 if (!delta)
4151 continue;
4152
4153 __update_lru_size(lruvec, lru, zone, delta);
4154 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4155 }
4156 }
4157
4158 for (type = 0; type < ANON_AND_FILE; type++)
4159 reset_ctrl_pos(lruvec, type, false);
4160
Yu Zhao430499c2022-09-18 02:00:08 -06004161 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhao37397872022-09-18 02:00:03 -06004162 /* make sure preceding modifications appear */
4163 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004164
Yu Zhao37397872022-09-18 02:00:03 -06004165 spin_unlock_irq(&lruvec->lru_lock);
4166}
4167
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004168static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
Yu Zhao4983c522022-09-18 02:00:09 -06004169 struct scan_control *sc, bool can_swap, bool force_scan)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004170{
4171 bool success;
4172 struct lru_gen_mm_walk *walk;
4173 struct mm_struct *mm = NULL;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004174 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004175
4176 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4177
4178 /* see the comment in iterate_mm_list() */
4179 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4180 success = false;
4181 goto done;
4182 }
4183
4184 /*
4185 * If the hardware doesn't automatically set the accessed bit, fallback
4186 * to lru_gen_look_around(), which only clears the accessed bit in a
4187 * handful of PTEs. Spreading the work out over a period of time usually
4188 * is less efficient, but it avoids bursty page faults.
4189 */
Yu Zhao4983c522022-09-18 02:00:09 -06004190 if (!force_scan && !(arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004191 success = iterate_mm_list_nowalk(lruvec, max_seq);
4192 goto done;
4193 }
4194
4195 walk = set_mm_walk(NULL);
4196 if (!walk) {
4197 success = iterate_mm_list_nowalk(lruvec, max_seq);
4198 goto done;
4199 }
4200
4201 walk->lruvec = lruvec;
4202 walk->max_seq = max_seq;
4203 walk->can_swap = can_swap;
Yu Zhao4983c522022-09-18 02:00:09 -06004204 walk->force_scan = force_scan;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004205
4206 do {
4207 success = iterate_mm_list(lruvec, walk, &mm);
4208 if (mm)
4209 walk_mm(lruvec, mm, walk);
4210
4211 cond_resched();
4212 } while (mm);
4213done:
4214 if (!success) {
4215 if (sc->priority <= DEF_PRIORITY - 2)
4216 wait_event_killable(lruvec->mm_state.wait,
4217 max_seq < READ_ONCE(lrugen->max_seq));
4218
4219 return max_seq < READ_ONCE(lrugen->max_seq);
4220 }
4221
4222 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4223
Yu Zhao4983c522022-09-18 02:00:09 -06004224 inc_max_seq(lruvec, can_swap, force_scan);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004225 /* either this sees any waiters or they will see updated max_seq */
4226 if (wq_has_sleeper(&lruvec->mm_state.wait))
4227 wake_up_all(&lruvec->mm_state.wait);
4228
4229 return true;
4230}
4231
Yu Zhao37397872022-09-18 02:00:03 -06004232static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
4233 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4234{
4235 int gen, type, zone;
4236 unsigned long old = 0;
4237 unsigned long young = 0;
4238 unsigned long total = 0;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004239 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004240 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4241
4242 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4243 unsigned long seq;
4244
4245 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4246 unsigned long size = 0;
4247
4248 gen = lru_gen_from_seq(seq);
4249
4250 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4251 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4252
4253 total += size;
4254 if (seq == max_seq)
4255 young += size;
4256 else if (seq + MIN_NR_GENS == max_seq)
4257 old += size;
4258 }
4259 }
4260
4261 /* try to scrape all its memory if this memcg was deleted */
4262 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4263
4264 /*
4265 * The aging tries to be lazy to reduce the overhead, while the eviction
4266 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4267 * ideal number of generations is MIN_NR_GENS+1.
4268 */
4269 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
4270 return true;
4271 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4272 return false;
4273
4274 /*
4275 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4276 * of the total number of pages for each generation. A reasonable range
4277 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4278 * aging cares about the upper bound of hot pages, while the eviction
4279 * cares about the lower bound of cold pages.
4280 */
4281 if (young * MIN_NR_GENS > total)
4282 return true;
4283 if (old * (MIN_NR_GENS + 2) < total)
4284 return true;
4285
4286 return false;
4287}
4288
Yu Zhao430499c2022-09-18 02:00:08 -06004289static bool age_lruvec(struct lruvec *lruvec, struct scan_control *sc, unsigned long min_ttl)
Yu Zhao37397872022-09-18 02:00:03 -06004290{
4291 bool need_aging;
4292 unsigned long nr_to_scan;
4293 int swappiness = get_swappiness(lruvec, sc);
4294 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4295 DEFINE_MAX_SEQ(lruvec);
4296 DEFINE_MIN_SEQ(lruvec);
4297
4298 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
4299
4300 mem_cgroup_calculate_protection(NULL, memcg);
4301
4302 if (mem_cgroup_below_min(memcg))
Yu Zhao430499c2022-09-18 02:00:08 -06004303 return false;
Yu Zhao37397872022-09-18 02:00:03 -06004304
4305 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
Yu Zhao430499c2022-09-18 02:00:08 -06004306
4307 if (min_ttl) {
4308 int gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4309 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4310
4311 if (time_is_after_jiffies(birth + min_ttl))
4312 return false;
4313
4314 /* the size is likely too small to be helpful */
4315 if (!nr_to_scan && sc->priority != DEF_PRIORITY)
4316 return false;
4317 }
4318
Yu Zhao37397872022-09-18 02:00:03 -06004319 if (need_aging)
Yu Zhao4983c522022-09-18 02:00:09 -06004320 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
Yu Zhao430499c2022-09-18 02:00:08 -06004321
4322 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004323}
4324
Yu Zhao430499c2022-09-18 02:00:08 -06004325/* to protect the working set of the last N jiffies */
4326static unsigned long lru_gen_min_ttl __read_mostly;
4327
Yu Zhao37397872022-09-18 02:00:03 -06004328static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4329{
4330 struct mem_cgroup *memcg;
Yu Zhao430499c2022-09-18 02:00:08 -06004331 bool success = false;
4332 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhao37397872022-09-18 02:00:03 -06004333
4334 VM_WARN_ON_ONCE(!current_is_kswapd());
4335
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004336 sc->last_reclaimed = sc->nr_reclaimed;
4337
4338 /*
4339 * To reduce the chance of going into the aging path, which can be
4340 * costly, optimistically skip it if the flag below was cleared in the
4341 * eviction path. This improves the overall performance when multiple
4342 * memcgs are available.
4343 */
4344 if (!sc->memcgs_need_aging) {
4345 sc->memcgs_need_aging = true;
4346 return;
4347 }
4348
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004349 set_mm_walk(pgdat);
4350
Yu Zhao37397872022-09-18 02:00:03 -06004351 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4352 do {
4353 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4354
Yu Zhao430499c2022-09-18 02:00:08 -06004355 if (age_lruvec(lruvec, sc, min_ttl))
4356 success = true;
Yu Zhao37397872022-09-18 02:00:03 -06004357
4358 cond_resched();
4359 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004360
4361 clear_mm_walk();
Yu Zhao430499c2022-09-18 02:00:08 -06004362
4363 /* check the order to exclude compaction-induced reclaim */
4364 if (success || !min_ttl || sc->order)
4365 return;
4366
4367 /*
4368 * The main goal is to OOM kill if every generation from all memcgs is
4369 * younger than min_ttl. However, another possibility is all memcgs are
4370 * either below min or empty.
4371 */
4372 if (mutex_trylock(&oom_lock)) {
4373 struct oom_control oc = {
4374 .gfp_mask = sc->gfp_mask,
4375 };
4376
4377 out_of_memory(&oc);
4378
4379 mutex_unlock(&oom_lock);
4380 }
Yu Zhao37397872022-09-18 02:00:03 -06004381}
4382
Yu Zhao0182f922022-09-18 02:00:04 -06004383/*
4384 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004385 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4386 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4387 * the PTE table to the Bloom filter. This forms a feedback loop between the
4388 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004389 */
4390void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4391{
4392 int i;
4393 pte_t *pte;
4394 unsigned long start;
4395 unsigned long end;
4396 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004397 struct lru_gen_mm_walk *walk;
4398 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004399 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4400 struct page *page = pvmw->page;
4401 struct mem_cgroup *memcg = page_memcg(page);
4402 struct pglist_data *pgdat = page_pgdat(page);
4403 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4404 DEFINE_MAX_SEQ(lruvec);
4405 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4406
4407 lockdep_assert_held(pvmw->ptl);
4408 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4409
4410 if (spin_is_contended(pvmw->ptl))
4411 return;
4412
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004413 /* avoid taking the LRU lock under the PTL when possible */
4414 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4415
Yu Zhao0182f922022-09-18 02:00:04 -06004416 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4417 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4418
4419 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4420 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4421 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4422 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4423 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4424 else {
4425 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4426 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4427 }
4428 }
4429
4430 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4431
4432 rcu_read_lock();
4433 arch_enter_lazy_mmu_mode();
4434
4435 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4436 unsigned long pfn;
4437
4438 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4439 if (pfn == -1)
4440 continue;
4441
4442 if (!pte_young(pte[i]))
4443 continue;
4444
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004445 page = get_pfn_page(pfn, memcg, pgdat, !walk || walk->can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004446 if (!page)
4447 continue;
4448
4449 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4450 VM_WARN_ON_ONCE(true);
4451
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004452 young++;
4453
Yu Zhao0182f922022-09-18 02:00:04 -06004454 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4455 !(PageAnon(page) && PageSwapBacked(page) &&
4456 !PageSwapCache(page)))
4457 set_page_dirty(page);
4458
4459 old_gen = page_lru_gen(page);
4460 if (old_gen < 0)
4461 SetPageReferenced(page);
4462 else if (old_gen != new_gen)
4463 __set_bit(i, bitmap);
4464 }
4465
4466 arch_leave_lazy_mmu_mode();
4467 rcu_read_unlock();
4468
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004469 /* feedback from rmap walkers to page table walkers */
4470 if (suitable_to_scan(i, young))
4471 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4472
4473 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004474 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4475 page = pte_page(pte[i]);
4476 activate_page(page);
4477 }
4478 return;
4479 }
4480
4481 /* page_update_gen() requires stable page_memcg() */
4482 if (!mem_cgroup_trylock_pages(memcg))
4483 return;
4484
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004485 if (!walk) {
4486 spin_lock_irq(&lruvec->lru_lock);
4487 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4488 }
Yu Zhao0182f922022-09-18 02:00:04 -06004489
4490 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4491 page = compound_head(pte_page(pte[i]));
4492 if (page_memcg_rcu(page) != memcg)
4493 continue;
4494
4495 old_gen = page_update_gen(page, new_gen);
4496 if (old_gen < 0 || old_gen == new_gen)
4497 continue;
4498
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004499 if (walk)
4500 update_batch_size(walk, page, old_gen, new_gen);
4501 else
4502 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004503 }
4504
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004505 if (!walk)
4506 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004507
4508 mem_cgroup_unlock_pages();
4509}
4510
Yu Zhao37397872022-09-18 02:00:03 -06004511/******************************************************************************
4512 * the eviction
4513 ******************************************************************************/
4514
4515static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4516{
4517 bool success;
4518 int gen = page_lru_gen(page);
4519 int type = page_is_file_lru(page);
4520 int zone = page_zonenum(page);
4521 int delta = thp_nr_pages(page);
4522 int refs = page_lru_refs(page);
4523 int tier = lru_tier_from_refs(refs);
Yu Zhao3c6c3592022-12-21 21:18:59 -07004524 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004525
4526 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4527
4528 /* unevictable */
4529 if (!page_evictable(page)) {
4530 success = lru_gen_del_page(lruvec, page, true);
4531 VM_WARN_ON_ONCE_PAGE(!success, page);
4532 SetPageUnevictable(page);
4533 add_page_to_lru_list(page, lruvec);
4534 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4535 return true;
4536 }
4537
4538 /* dirty lazyfree */
4539 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4540 success = lru_gen_del_page(lruvec, page, true);
4541 VM_WARN_ON_ONCE_PAGE(!success, page);
4542 SetPageSwapBacked(page);
4543 add_page_to_lru_list_tail(page, lruvec);
4544 return true;
4545 }
4546
Yu Zhao0182f922022-09-18 02:00:04 -06004547 /* promoted */
4548 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004549 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao0182f922022-09-18 02:00:04 -06004550 return true;
4551 }
4552
Yu Zhao37397872022-09-18 02:00:03 -06004553 /* protected */
4554 if (tier > tier_idx) {
4555 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4556
4557 gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004558 list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004559
4560 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4561 lrugen->protected[hist][type][tier - 1] + delta);
4562 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4563 return true;
4564 }
4565
4566 /* waiting for writeback */
4567 if (PageLocked(page) || PageWriteback(page) ||
4568 (type == LRU_GEN_FILE && PageDirty(page))) {
4569 gen = page_inc_gen(lruvec, page, true);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004570 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004571 return true;
4572 }
4573
4574 return false;
4575}
4576
4577static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4578{
4579 bool success;
4580
4581 /* unmapping inhibited */
4582 if (!sc->may_unmap && page_mapped(page))
4583 return false;
4584
4585 /* swapping inhibited */
4586 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4587 (PageDirty(page) ||
4588 (PageAnon(page) && !PageSwapCache(page))))
4589 return false;
4590
4591 /* raced with release_pages() */
4592 if (!get_page_unless_zero(page))
4593 return false;
4594
4595 /* raced with another isolation */
4596 if (!TestClearPageLRU(page)) {
4597 put_page(page);
4598 return false;
4599 }
4600
4601 /* see the comment on MAX_NR_TIERS */
4602 if (!PageReferenced(page))
4603 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4604
4605 /* for shrink_page_list() */
4606 ClearPageReclaim(page);
4607 ClearPageReferenced(page);
4608
4609 success = lru_gen_del_page(lruvec, page, true);
4610 VM_WARN_ON_ONCE_PAGE(!success, page);
4611
4612 return true;
4613}
4614
4615static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4616 int type, int tier, struct list_head *list)
4617{
4618 int gen, zone;
4619 enum vm_event_item item;
4620 int sorted = 0;
4621 int scanned = 0;
4622 int isolated = 0;
4623 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004624 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004625 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4626
4627 VM_WARN_ON_ONCE(!list_empty(list));
4628
4629 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4630 return 0;
4631
4632 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4633
4634 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4635 LIST_HEAD(moved);
4636 int skipped = 0;
Yu Zhaodf91dc92022-12-21 21:19:00 -07004637 struct list_head *head = &lrugen->pages[gen][type][zone];
Yu Zhao37397872022-09-18 02:00:03 -06004638
4639 while (!list_empty(head)) {
4640 struct page *page = lru_to_page(head);
4641 int delta = thp_nr_pages(page);
4642
4643 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4644 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4645 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4646 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4647
4648 scanned += delta;
4649
4650 if (sort_page(lruvec, page, tier))
4651 sorted += delta;
4652 else if (isolate_page(lruvec, page, sc)) {
4653 list_add(&page->lru, list);
4654 isolated += delta;
4655 } else {
4656 list_move(&page->lru, &moved);
4657 skipped += delta;
4658 }
4659
4660 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4661 break;
4662 }
4663
4664 if (skipped) {
4665 list_splice(&moved, head);
4666 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4667 }
4668
4669 if (!remaining || isolated >= MIN_LRU_BATCH)
4670 break;
4671 }
4672
4673 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4674 if (!cgroup_reclaim(sc)) {
4675 __count_vm_events(item, isolated);
4676 __count_vm_events(PGREFILL, sorted);
4677 }
4678 __count_memcg_events(memcg, item, isolated);
4679 __count_memcg_events(memcg, PGREFILL, sorted);
4680 __count_vm_events(PGSCAN_ANON + type, isolated);
4681
4682 /*
4683 * There might not be eligible pages due to reclaim_idx, may_unmap and
4684 * may_writepage. Check the remaining to prevent livelock if it's not
4685 * making progress.
4686 */
4687 return isolated || !remaining ? scanned : 0;
4688}
4689
4690static int get_tier_idx(struct lruvec *lruvec, int type)
4691{
4692 int tier;
4693 struct ctrl_pos sp, pv;
4694
4695 /*
4696 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4697 * This value is chosen because any other tier would have at least twice
4698 * as many refaults as the first tier.
4699 */
4700 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4701 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4702 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4703 if (!positive_ctrl_err(&sp, &pv))
4704 break;
4705 }
4706
4707 return tier - 1;
4708}
4709
4710static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4711{
4712 int type, tier;
4713 struct ctrl_pos sp, pv;
4714 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4715
4716 /*
4717 * Compare the first tier of anon with that of file to determine which
4718 * type to scan. Also need to compare other tiers of the selected type
4719 * with the first tier of the other type to determine the last tier (of
4720 * the selected type) to evict.
4721 */
4722 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4723 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4724 type = positive_ctrl_err(&sp, &pv);
4725
4726 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4727 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4728 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4729 if (!positive_ctrl_err(&sp, &pv))
4730 break;
4731 }
4732
4733 *tier_idx = tier - 1;
4734
4735 return type;
4736}
4737
4738static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4739 int *type_scanned, struct list_head *list)
4740{
4741 int i;
4742 int type;
4743 int scanned;
4744 int tier = -1;
4745 DEFINE_MIN_SEQ(lruvec);
4746
4747 /*
4748 * Try to make the obvious choice first. When anon and file are both
4749 * available from the same generation, interpret swappiness 1 as file
4750 * first and 200 as anon first.
4751 */
4752 if (!swappiness)
4753 type = LRU_GEN_FILE;
4754 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4755 type = LRU_GEN_ANON;
4756 else if (swappiness == 1)
4757 type = LRU_GEN_FILE;
4758 else if (swappiness == 200)
4759 type = LRU_GEN_ANON;
4760 else
4761 type = get_type_to_scan(lruvec, swappiness, &tier);
4762
4763 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4764 if (tier < 0)
4765 tier = get_tier_idx(lruvec, type);
4766
4767 scanned = scan_pages(lruvec, sc, type, tier, list);
4768 if (scanned)
4769 break;
4770
4771 type = !type;
4772 tier = -1;
4773 }
4774
4775 *type_scanned = type;
4776
4777 return scanned;
4778}
4779
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004780static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
Yu Zhao37397872022-09-18 02:00:03 -06004781{
4782 int type;
4783 int scanned;
4784 int reclaimed;
4785 LIST_HEAD(list);
Yu Zhao79e66ea2022-11-15 18:38:07 -07004786 LIST_HEAD(clean);
Yu Zhao37397872022-09-18 02:00:03 -06004787 struct page *page;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004788 struct page *next;
Yu Zhao37397872022-09-18 02:00:03 -06004789 enum vm_event_item item;
4790 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004791 struct lru_gen_mm_walk *walk;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004792 bool skip_retry = false;
Yu Zhao37397872022-09-18 02:00:03 -06004793 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4794 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4795
4796 spin_lock_irq(&lruvec->lru_lock);
4797
4798 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4799
4800 scanned += try_to_inc_min_seq(lruvec, swappiness);
4801
4802 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4803 scanned = 0;
4804
4805 spin_unlock_irq(&lruvec->lru_lock);
4806
4807 if (list_empty(&list))
4808 return scanned;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004809retry:
Yu Zhao37397872022-09-18 02:00:03 -06004810 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
Yu Zhao79e66ea2022-11-15 18:38:07 -07004811 sc->nr_reclaimed += reclaimed;
Yu Zhao37397872022-09-18 02:00:03 -06004812
Yu Zhao79e66ea2022-11-15 18:38:07 -07004813 list_for_each_entry_safe_reverse(page, next, &list, lru) {
4814 if (!page_evictable(page)) {
4815 list_del(&page->lru);
4816 putback_lru_page(page);
4817 continue;
4818 }
Yu Zhao37397872022-09-18 02:00:03 -06004819
Yu Zhao37397872022-09-18 02:00:03 -06004820 if (PageReclaim(page) &&
Yu Zhao79e66ea2022-11-15 18:38:07 -07004821 (PageDirty(page) || PageWriteback(page))) {
4822 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4823 if (PageWorkingset(page))
4824 SetPageReferenced(page);
4825 continue;
4826 }
4827
4828 if (skip_retry || PageActive(page) || PageReferenced(page) ||
4829 page_mapped(page) || PageLocked(page) ||
4830 PageDirty(page) || PageWriteback(page)) {
4831 /* don't add rejected pages to the oldest generation */
4832 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
4833 BIT(PG_active));
4834 continue;
4835 }
4836
4837 /* retry pages that may have missed rotate_reclaimable_page() */
4838 list_move(&page->lru, &clean);
4839 sc->nr_scanned -= thp_nr_pages(page);
Yu Zhao37397872022-09-18 02:00:03 -06004840 }
4841
4842 spin_lock_irq(&lruvec->lru_lock);
4843
4844 move_pages_to_lru(lruvec, &list);
4845
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004846 walk = current->reclaim_state->mm_walk;
4847 if (walk && walk->batched)
4848 reset_batch_size(lruvec, walk);
4849
Yu Zhao37397872022-09-18 02:00:03 -06004850 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4851 if (!cgroup_reclaim(sc))
4852 __count_vm_events(item, reclaimed);
4853 __count_memcg_events(memcg, item, reclaimed);
4854 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4855
4856 spin_unlock_irq(&lruvec->lru_lock);
4857
4858 mem_cgroup_uncharge_list(&list);
4859 free_unref_page_list(&list);
4860
Yu Zhao79e66ea2022-11-15 18:38:07 -07004861 INIT_LIST_HEAD(&list);
4862 list_splice_init(&clean, &list);
4863
4864 if (!list_empty(&list)) {
4865 skip_retry = true;
4866 goto retry;
4867 }
Yu Zhao37397872022-09-18 02:00:03 -06004868
4869 return scanned;
4870}
4871
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004872/*
4873 * For future optimizations:
4874 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4875 * reclaim.
4876 */
Yu Zhao37397872022-09-18 02:00:03 -06004877static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004878 bool can_swap, bool *need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004879{
Yu Zhao37397872022-09-18 02:00:03 -06004880 unsigned long nr_to_scan;
4881 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4882 DEFINE_MAX_SEQ(lruvec);
4883 DEFINE_MIN_SEQ(lruvec);
4884
4885 if (mem_cgroup_below_min(memcg) ||
4886 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4887 return 0;
4888
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004889 *need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
4890 if (!*need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004891 return nr_to_scan;
4892
4893 /* skip the aging path at the default priority */
4894 if (sc->priority == DEF_PRIORITY)
4895 goto done;
4896
4897 /* leave the work to lru_gen_age_node() */
4898 if (current_is_kswapd())
4899 return 0;
4900
Yu Zhao4983c522022-09-18 02:00:09 -06004901 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004902 return nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004903done:
4904 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
4905}
4906
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004907static unsigned long get_nr_to_reclaim(struct scan_control *sc)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004908{
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004909 /* don't abort memcg reclaim to ensure fairness */
4910 if (!global_reclaim(sc))
4911 return -1;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004912
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004913 /* discount the previous progress for kswapd */
4914 if (current_is_kswapd())
4915 return sc->nr_to_reclaim + sc->last_reclaimed;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004916
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004917 return max(sc->nr_to_reclaim, compact_gap(sc->order));
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004918}
4919
Yu Zhao37397872022-09-18 02:00:03 -06004920static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4921{
4922 struct blk_plug plug;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004923 bool need_aging = false;
Yu Zhao37397872022-09-18 02:00:03 -06004924 unsigned long scanned = 0;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004925 unsigned long reclaimed = sc->nr_reclaimed;
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004926 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
Yu Zhao37397872022-09-18 02:00:03 -06004927
4928 lru_add_drain();
4929
4930 blk_start_plug(&plug);
4931
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004932 set_mm_walk(lruvec_pgdat(lruvec));
4933
Yu Zhao37397872022-09-18 02:00:03 -06004934 while (true) {
4935 int delta;
4936 int swappiness;
4937 unsigned long nr_to_scan;
4938
4939 if (sc->may_swap)
4940 swappiness = get_swappiness(lruvec, sc);
4941 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4942 swappiness = 1;
4943 else
4944 swappiness = 0;
4945
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004946 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, &need_aging);
Yu Zhao37397872022-09-18 02:00:03 -06004947 if (!nr_to_scan)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004948 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004949
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004950 delta = evict_pages(lruvec, sc, swappiness);
Yu Zhao37397872022-09-18 02:00:03 -06004951 if (!delta)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004952 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004953
4954 scanned += delta;
4955 if (scanned >= nr_to_scan)
4956 break;
4957
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004958 if (sc->nr_reclaimed >= nr_to_reclaim)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004959 break;
4960
Yu Zhao37397872022-09-18 02:00:03 -06004961 cond_resched();
4962 }
4963
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004964 /* see the comment in lru_gen_age_node() */
4965 if (sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH && !need_aging)
4966 sc->memcgs_need_aging = false;
4967done:
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004968 clear_mm_walk();
4969
Yu Zhao37397872022-09-18 02:00:03 -06004970 blk_finish_plug(&plug);
4971}
4972
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004973/******************************************************************************
Yu Zhaobaeb9a02022-09-18 02:00:07 -06004974 * state change
4975 ******************************************************************************/
4976
4977static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
4978{
Yu Zhao3c6c3592022-12-21 21:18:59 -07004979 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06004980
4981 if (lrugen->enabled) {
4982 enum lru_list lru;
4983
4984 for_each_evictable_lru(lru) {
4985 if (!list_empty(&lruvec->lists[lru]))
4986 return false;
4987 }
4988 } else {
4989 int gen, type, zone;
4990
4991 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004992 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhaobaeb9a02022-09-18 02:00:07 -06004993 return false;
4994 }
4995 }
4996
4997 return true;
4998}
4999
5000static bool fill_evictable(struct lruvec *lruvec)
5001{
5002 enum lru_list lru;
5003 int remaining = MAX_LRU_BATCH;
5004
5005 for_each_evictable_lru(lru) {
5006 int type = is_file_lru(lru);
5007 bool active = is_active_lru(lru);
5008 struct list_head *head = &lruvec->lists[lru];
5009
5010 while (!list_empty(head)) {
5011 bool success;
5012 struct page *page = lru_to_page(head);
5013
5014 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5015 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
5016 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5017 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
5018
5019 del_page_from_lru_list(page, lruvec);
5020 success = lru_gen_add_page(lruvec, page, false);
5021 VM_WARN_ON_ONCE(!success);
5022
5023 if (!--remaining)
5024 return false;
5025 }
5026 }
5027
5028 return true;
5029}
5030
5031static bool drain_evictable(struct lruvec *lruvec)
5032{
5033 int gen, type, zone;
5034 int remaining = MAX_LRU_BATCH;
5035
5036 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005037 struct list_head *head = &lruvec->lrugen.pages[gen][type][zone];
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005038
5039 while (!list_empty(head)) {
5040 bool success;
5041 struct page *page = lru_to_page(head);
5042
5043 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5044 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5045 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5046 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5047
5048 success = lru_gen_del_page(lruvec, page, false);
5049 VM_WARN_ON_ONCE(!success);
5050 add_page_to_lru_list(page, lruvec);
5051
5052 if (!--remaining)
5053 return false;
5054 }
5055 }
5056
5057 return true;
5058}
5059
5060static void lru_gen_change_state(bool enabled)
5061{
5062 static DEFINE_MUTEX(state_mutex);
5063
5064 struct mem_cgroup *memcg;
5065
5066 cgroup_lock();
5067 cpus_read_lock();
5068 get_online_mems();
5069 mutex_lock(&state_mutex);
5070
5071 if (enabled == lru_gen_enabled())
5072 goto unlock;
5073
5074 if (enabled)
5075 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5076 else
5077 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5078
5079 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5080 do {
5081 int nid;
5082
5083 for_each_node(nid) {
5084 struct lruvec *lruvec = get_lruvec(memcg, nid);
5085
5086 if (!lruvec)
5087 continue;
5088
5089 spin_lock_irq(&lruvec->lru_lock);
5090
5091 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5092 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5093
5094 lruvec->lrugen.enabled = enabled;
5095
5096 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5097 spin_unlock_irq(&lruvec->lru_lock);
5098 cond_resched();
5099 spin_lock_irq(&lruvec->lru_lock);
5100 }
5101
5102 spin_unlock_irq(&lruvec->lru_lock);
5103 }
5104
5105 cond_resched();
5106 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5107unlock:
5108 mutex_unlock(&state_mutex);
5109 put_online_mems();
5110 cpus_read_unlock();
5111 cgroup_unlock();
5112}
5113
5114/******************************************************************************
5115 * sysfs interface
5116 ******************************************************************************/
5117
Yu Zhao430499c2022-09-18 02:00:08 -06005118static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5119{
5120 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5121}
5122
Yu Zhao642d9862022-09-18 02:00:10 -06005123/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao430499c2022-09-18 02:00:08 -06005124static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5125 const char *buf, size_t len)
5126{
5127 unsigned int msecs;
5128
5129 if (kstrtouint(buf, 0, &msecs))
5130 return -EINVAL;
5131
5132 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5133
5134 return len;
5135}
5136
5137static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5138 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5139);
5140
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005141static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5142{
5143 unsigned int caps = 0;
5144
5145 if (get_cap(LRU_GEN_CORE))
5146 caps |= BIT(LRU_GEN_CORE);
5147
5148 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5149 caps |= BIT(LRU_GEN_MM_WALK);
5150
5151 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
5152 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5153
5154 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5155}
5156
Yu Zhao642d9862022-09-18 02:00:10 -06005157/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005158static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5159 const char *buf, size_t len)
5160{
5161 int i;
5162 unsigned int caps;
5163
5164 if (tolower(*buf) == 'n')
5165 caps = 0;
5166 else if (tolower(*buf) == 'y')
5167 caps = -1;
5168 else if (kstrtouint(buf, 0, &caps))
5169 return -EINVAL;
5170
5171 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5172 bool enabled = caps & BIT(i);
5173
5174 if (i == LRU_GEN_CORE)
5175 lru_gen_change_state(enabled);
5176 else if (enabled)
5177 static_branch_enable(&lru_gen_caps[i]);
5178 else
5179 static_branch_disable(&lru_gen_caps[i]);
5180 }
5181
5182 return len;
5183}
5184
5185static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5186 enabled, 0644, show_enabled, store_enabled
5187);
5188
5189static struct attribute *lru_gen_attrs[] = {
Yu Zhao430499c2022-09-18 02:00:08 -06005190 &lru_gen_min_ttl_attr.attr,
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005191 &lru_gen_enabled_attr.attr,
5192 NULL
5193};
5194
5195static struct attribute_group lru_gen_attr_group = {
5196 .name = "lru_gen",
5197 .attrs = lru_gen_attrs,
5198};
5199
5200/******************************************************************************
Yu Zhao4983c522022-09-18 02:00:09 -06005201 * debugfs interface
5202 ******************************************************************************/
5203
5204static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5205{
5206 struct mem_cgroup *memcg;
5207 loff_t nr_to_skip = *pos;
5208
5209 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5210 if (!m->private)
5211 return ERR_PTR(-ENOMEM);
5212
5213 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5214 do {
5215 int nid;
5216
5217 for_each_node_state(nid, N_MEMORY) {
5218 if (!nr_to_skip--)
5219 return get_lruvec(memcg, nid);
5220 }
5221 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5222
5223 return NULL;
5224}
5225
5226static void lru_gen_seq_stop(struct seq_file *m, void *v)
5227{
5228 if (!IS_ERR_OR_NULL(v))
5229 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5230
5231 kvfree(m->private);
5232 m->private = NULL;
5233}
5234
5235static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5236{
5237 int nid = lruvec_pgdat(v)->node_id;
5238 struct mem_cgroup *memcg = lruvec_memcg(v);
5239
5240 ++*pos;
5241
5242 nid = next_memory_node(nid);
5243 if (nid == MAX_NUMNODES) {
5244 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5245 if (!memcg)
5246 return NULL;
5247
5248 nid = first_memory_node;
5249 }
5250
5251 return get_lruvec(memcg, nid);
5252}
5253
5254static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5255 unsigned long max_seq, unsigned long *min_seq,
5256 unsigned long seq)
5257{
5258 int i;
5259 int type, tier;
5260 int hist = lru_hist_from_seq(seq);
Yu Zhao3c6c3592022-12-21 21:18:59 -07005261 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005262
5263 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5264 seq_printf(m, " %10d", tier);
5265 for (type = 0; type < ANON_AND_FILE; type++) {
5266 const char *s = " ";
5267 unsigned long n[3] = {};
5268
5269 if (seq == max_seq) {
5270 s = "RT ";
5271 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5272 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5273 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5274 s = "rep";
5275 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5276 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5277 if (tier)
5278 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5279 }
5280
5281 for (i = 0; i < 3; i++)
5282 seq_printf(m, " %10lu%c", n[i], s[i]);
5283 }
5284 seq_putc(m, '\n');
5285 }
5286
5287 seq_puts(m, " ");
5288 for (i = 0; i < NR_MM_STATS; i++) {
5289 const char *s = " ";
5290 unsigned long n = 0;
5291
5292 if (seq == max_seq && NR_HIST_GENS == 1) {
5293 s = "LOYNFA";
5294 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5295 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5296 s = "loynfa";
5297 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5298 }
5299
5300 seq_printf(m, " %10lu%c", n, s[i]);
5301 }
5302 seq_putc(m, '\n');
5303}
5304
Yu Zhao642d9862022-09-18 02:00:10 -06005305/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005306static int lru_gen_seq_show(struct seq_file *m, void *v)
5307{
5308 unsigned long seq;
5309 bool full = !debugfs_real_fops(m->file)->write;
5310 struct lruvec *lruvec = v;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005311 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005312 int nid = lruvec_pgdat(lruvec)->node_id;
5313 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5314 DEFINE_MAX_SEQ(lruvec);
5315 DEFINE_MIN_SEQ(lruvec);
5316
5317 if (nid == first_memory_node) {
5318 const char *path = memcg ? m->private : "";
5319
5320#ifdef CONFIG_MEMCG
5321 if (memcg)
5322 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5323#endif
5324 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5325 }
5326
5327 seq_printf(m, " node %5d\n", nid);
5328
5329 if (!full)
5330 seq = min_seq[LRU_GEN_ANON];
5331 else if (max_seq >= MAX_NR_GENS)
5332 seq = max_seq - MAX_NR_GENS + 1;
5333 else
5334 seq = 0;
5335
5336 for (; seq <= max_seq; seq++) {
5337 int type, zone;
5338 int gen = lru_gen_from_seq(seq);
5339 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5340
5341 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5342
5343 for (type = 0; type < ANON_AND_FILE; type++) {
5344 unsigned long size = 0;
5345 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5346
5347 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5348 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5349
5350 seq_printf(m, " %10lu%c", size, mark);
5351 }
5352
5353 seq_putc(m, '\n');
5354
5355 if (full)
5356 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5357 }
5358
5359 return 0;
5360}
5361
5362static const struct seq_operations lru_gen_seq_ops = {
5363 .start = lru_gen_seq_start,
5364 .stop = lru_gen_seq_stop,
5365 .next = lru_gen_seq_next,
5366 .show = lru_gen_seq_show,
5367};
5368
5369static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5370 bool can_swap, bool force_scan)
5371{
5372 DEFINE_MAX_SEQ(lruvec);
5373 DEFINE_MIN_SEQ(lruvec);
5374
5375 if (seq < max_seq)
5376 return 0;
5377
5378 if (seq > max_seq)
5379 return -EINVAL;
5380
5381 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5382 return -ERANGE;
5383
5384 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5385
5386 return 0;
5387}
5388
5389static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5390 int swappiness, unsigned long nr_to_reclaim)
5391{
5392 DEFINE_MAX_SEQ(lruvec);
5393
5394 if (seq + MIN_NR_GENS > max_seq)
5395 return -EINVAL;
5396
5397 sc->nr_reclaimed = 0;
5398
5399 while (!signal_pending(current)) {
5400 DEFINE_MIN_SEQ(lruvec);
5401
5402 if (seq < min_seq[!swappiness])
5403 return 0;
5404
5405 if (sc->nr_reclaimed >= nr_to_reclaim)
5406 return 0;
5407
Yu Zhao4fc3ef42022-12-21 21:19:01 -07005408 if (!evict_pages(lruvec, sc, swappiness))
Yu Zhao4983c522022-09-18 02:00:09 -06005409 return 0;
5410
5411 cond_resched();
5412 }
5413
5414 return -EINTR;
5415}
5416
5417static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5418 struct scan_control *sc, int swappiness, unsigned long opt)
5419{
5420 struct lruvec *lruvec;
5421 int err = -EINVAL;
5422 struct mem_cgroup *memcg = NULL;
5423
5424 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5425 return -EINVAL;
5426
5427 if (!mem_cgroup_disabled()) {
5428 rcu_read_lock();
5429 memcg = mem_cgroup_from_id(memcg_id);
5430#ifdef CONFIG_MEMCG
5431 if (memcg && !css_tryget(&memcg->css))
5432 memcg = NULL;
5433#endif
5434 rcu_read_unlock();
5435
5436 if (!memcg)
5437 return -EINVAL;
5438 }
5439
5440 if (memcg_id != mem_cgroup_id(memcg))
5441 goto done;
5442
5443 lruvec = get_lruvec(memcg, nid);
5444
5445 if (swappiness < 0)
5446 swappiness = get_swappiness(lruvec, sc);
5447 else if (swappiness > 200)
5448 goto done;
5449
5450 switch (cmd) {
5451 case '+':
5452 err = run_aging(lruvec, seq, sc, swappiness, opt);
5453 break;
5454 case '-':
5455 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5456 break;
5457 }
5458done:
5459 mem_cgroup_put(memcg);
5460
5461 return err;
5462}
5463
Yu Zhao642d9862022-09-18 02:00:10 -06005464/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005465static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5466 size_t len, loff_t *pos)
5467{
5468 void *buf;
5469 char *cur, *next;
5470 unsigned int flags;
5471 struct blk_plug plug;
5472 int err = -EINVAL;
5473 struct scan_control sc = {
5474 .may_writepage = true,
5475 .may_unmap = true,
5476 .may_swap = true,
5477 .reclaim_idx = MAX_NR_ZONES - 1,
5478 .gfp_mask = GFP_KERNEL,
5479 };
5480
5481 buf = kvmalloc(len + 1, GFP_KERNEL);
5482 if (!buf)
5483 return -ENOMEM;
5484
5485 if (copy_from_user(buf, src, len)) {
5486 kvfree(buf);
5487 return -EFAULT;
5488 }
5489
5490 set_task_reclaim_state(current, &sc.reclaim_state);
5491 flags = memalloc_noreclaim_save();
5492 blk_start_plug(&plug);
5493 if (!set_mm_walk(NULL)) {
5494 err = -ENOMEM;
5495 goto done;
5496 }
5497
5498 next = buf;
5499 next[len] = '\0';
5500
5501 while ((cur = strsep(&next, ",;\n"))) {
5502 int n;
5503 int end;
5504 char cmd;
5505 unsigned int memcg_id;
5506 unsigned int nid;
5507 unsigned long seq;
5508 unsigned int swappiness = -1;
5509 unsigned long opt = -1;
5510
5511 cur = skip_spaces(cur);
5512 if (!*cur)
5513 continue;
5514
5515 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5516 &seq, &end, &swappiness, &end, &opt, &end);
5517 if (n < 4 || cur[end]) {
5518 err = -EINVAL;
5519 break;
5520 }
5521
5522 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5523 if (err)
5524 break;
5525 }
5526done:
5527 clear_mm_walk();
5528 blk_finish_plug(&plug);
5529 memalloc_noreclaim_restore(flags);
5530 set_task_reclaim_state(current, NULL);
5531
5532 kvfree(buf);
5533
5534 return err ? : len;
5535}
5536
5537static int lru_gen_seq_open(struct inode *inode, struct file *file)
5538{
5539 return seq_open(file, &lru_gen_seq_ops);
5540}
5541
5542static const struct file_operations lru_gen_rw_fops = {
5543 .open = lru_gen_seq_open,
5544 .read = seq_read,
5545 .write = lru_gen_seq_write,
5546 .llseek = seq_lseek,
5547 .release = seq_release,
5548};
5549
5550static const struct file_operations lru_gen_ro_fops = {
5551 .open = lru_gen_seq_open,
5552 .read = seq_read,
5553 .llseek = seq_lseek,
5554 .release = seq_release,
5555};
5556
5557/******************************************************************************
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005558 * initialization
5559 ******************************************************************************/
5560
5561void lru_gen_init_lruvec(struct lruvec *lruvec)
5562{
Yu Zhao430499c2022-09-18 02:00:08 -06005563 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005564 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005565 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005566
5567 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005568 lrugen->enabled = lru_gen_enabled();
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005569
Yu Zhao430499c2022-09-18 02:00:08 -06005570 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5571 lrugen->timestamps[i] = jiffies;
5572
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005573 for_each_gen_type_zone(gen, type, zone)
Yu Zhaodf91dc92022-12-21 21:19:00 -07005574 INIT_LIST_HEAD(&lrugen->pages[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005575
5576 lruvec->mm_state.seq = MIN_NR_GENS;
5577 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005578}
5579
5580#ifdef CONFIG_MEMCG
5581void lru_gen_init_memcg(struct mem_cgroup *memcg)
5582{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005583 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5584 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005585}
5586
5587void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5588{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005589 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005590 int nid;
5591
5592 for_each_node(nid) {
5593 struct lruvec *lruvec = get_lruvec(memcg, nid);
5594
5595 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5596 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005597
5598 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5599 bitmap_free(lruvec->mm_state.filters[i]);
5600 lruvec->mm_state.filters[i] = NULL;
5601 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005602 }
5603}
5604#endif
5605
5606static int __init init_lru_gen(void)
5607{
5608 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5609 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5610
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005611 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5612 pr_err("lru_gen: failed to create sysfs group\n");
5613
Yu Zhao4983c522022-09-18 02:00:09 -06005614 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5615 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5616
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005617 return 0;
5618};
5619late_initcall(init_lru_gen);
5620
Yu Zhao37397872022-09-18 02:00:03 -06005621#else /* !CONFIG_LRU_GEN */
5622
5623static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5624{
5625}
5626
5627static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5628{
5629}
5630
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005631#endif /* CONFIG_LRU_GEN */
5632
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005633static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005634{
5635 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005636 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005637 unsigned long nr_to_scan;
5638 enum lru_list lru;
5639 unsigned long nr_reclaimed = 0;
5640 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005641 bool proportional_reclaim;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005642 struct blk_plug plug;
Minchan Kima8962f62022-11-02 09:04:41 -07005643 bool do_plug = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005644
Yu Zhao37397872022-09-18 02:00:03 -06005645 if (lru_gen_enabled()) {
5646 lru_gen_shrink_lruvec(lruvec, sc);
5647 return;
5648 }
5649
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005650 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005651
Mel Gormane82e0562013-07-03 15:01:44 -07005652 /* Record the original scan target for proportional adjustments later */
5653 memcpy(targets, nr, sizeof(nr));
5654
Mel Gorman1a501902014-06-04 16:10:49 -07005655 /*
5656 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5657 * event that can occur when there is little memory pressure e.g.
5658 * multiple streaming readers/writers. Hence, we do not abort scanning
5659 * when the requested number of pages are reclaimed when scanning at
5660 * DEF_PRIORITY on the assumption that the fact we are direct
5661 * reclaiming implies that kswapd is not keeping up and it is best to
5662 * do a batch of work at once. For memcg reclaim one check is made to
5663 * abort proportional reclaim if either the file or anon lru has already
5664 * dropped to zero at the first pass.
5665 */
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005666 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5667 sc->priority == DEF_PRIORITY);
Mel Gorman1a501902014-06-04 16:10:49 -07005668
Minchan Kima8962f62022-11-02 09:04:41 -07005669 trace_android_vh_shrink_lruvec_blk_plug(&do_plug);
5670 if (do_plug)
5671 blk_start_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005672 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5673 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005674 unsigned long nr_anon, nr_file, percentage;
5675 unsigned long nr_scanned;
5676
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005677 for_each_evictable_lru(lru) {
5678 if (nr[lru]) {
5679 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5680 nr[lru] -= nr_to_scan;
5681
5682 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005683 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005684 }
5685 }
Mel Gormane82e0562013-07-03 15:01:44 -07005686
Michal Hockobd041732016-12-02 17:26:48 -08005687 cond_resched();
5688
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005689 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
Mel Gormane82e0562013-07-03 15:01:44 -07005690 continue;
5691
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005692 /*
Mel Gormane82e0562013-07-03 15:01:44 -07005693 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07005694 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07005695 * proportionally what was requested by get_scan_count(). We
5696 * stop reclaiming one LRU and reduce the amount scanning
5697 * proportional to the original scan target.
5698 */
5699 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5700 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5701
Mel Gorman1a501902014-06-04 16:10:49 -07005702 /*
5703 * It's just vindictive to attack the larger once the smaller
5704 * has gone to zero. And given the way we stop scanning the
5705 * smaller below, this makes sure that we only make one nudge
5706 * towards proportionality once we've got nr_to_reclaim.
5707 */
5708 if (!nr_file || !nr_anon)
5709 break;
5710
Mel Gormane82e0562013-07-03 15:01:44 -07005711 if (nr_file > nr_anon) {
5712 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5713 targets[LRU_ACTIVE_ANON] + 1;
5714 lru = LRU_BASE;
5715 percentage = nr_anon * 100 / scan_target;
5716 } else {
5717 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5718 targets[LRU_ACTIVE_FILE] + 1;
5719 lru = LRU_FILE;
5720 percentage = nr_file * 100 / scan_target;
5721 }
5722
5723 /* Stop scanning the smaller of the LRU */
5724 nr[lru] = 0;
5725 nr[lru + LRU_ACTIVE] = 0;
5726
5727 /*
5728 * Recalculate the other LRU scan count based on its original
5729 * scan target and the percentage scanning already complete
5730 */
5731 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5732 nr_scanned = targets[lru] - nr[lru];
5733 nr[lru] = targets[lru] * (100 - percentage) / 100;
5734 nr[lru] -= min(nr[lru], nr_scanned);
5735
5736 lru += LRU_ACTIVE;
5737 nr_scanned = targets[lru] - nr[lru];
5738 nr[lru] = targets[lru] * (100 - percentage) / 100;
5739 nr[lru] -= min(nr[lru], nr_scanned);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005740 }
Minchan Kima8962f62022-11-02 09:04:41 -07005741 if (do_plug)
5742 blk_finish_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005743 sc->nr_reclaimed += nr_reclaimed;
5744
5745 /*
5746 * Even if we did not try to evict anon pages at all, we want to
5747 * rebalance the anon lru active/inactive ratio.
5748 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005749 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5750 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005751 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5752 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005753}
5754
Mel Gorman23b9da52012-05-29 15:06:20 -07005755/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005756static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005757{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005758 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005759 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005760 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005761 return true;
5762
5763 return false;
5764}
5765
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005766/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005767 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5768 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5769 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005770 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005771 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005772 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005773static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005774 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005775 struct scan_control *sc)
5776{
5777 unsigned long pages_for_compaction;
5778 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005779 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005780
5781 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005782 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005783 return false;
5784
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005785 /*
5786 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5787 * number of pages that were scanned. This will return to the caller
5788 * with the risk reclaim/compaction and the resulting allocation attempt
5789 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5790 * allocations through requiring that the full LRU list has been scanned
5791 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5792 * scan, but that approximation was wrong, and there were corner cases
5793 * where always a non-zero amount of pages were scanned.
5794 */
5795 if (!nr_reclaimed)
5796 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005797
Mel Gorman3e7d3442011-01-13 15:45:56 -08005798 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005799 for (z = 0; z <= sc->reclaim_idx; z++) {
5800 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005801 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005802 continue;
5803
5804 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005805 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005806 case COMPACT_CONTINUE:
5807 return false;
5808 default:
5809 /* check next zone */
5810 ;
5811 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005812 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005813
5814 /*
5815 * If we have not reclaimed enough pages for compaction and the
5816 * inactive lists are large enough, continue reclaiming
5817 */
5818 pages_for_compaction = compact_gap(sc->order);
5819 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005820 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005821 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5822
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005823 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005824}
5825
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005826static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005827{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005828 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005829 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005830
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005831 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005832 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005833 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005834 unsigned long reclaimed;
5835 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005836 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08005837
Xunlei Pange3336ca2020-09-04 16:35:27 -07005838 /*
5839 * This loop can become CPU-bound when target memcgs
5840 * aren't eligible for reclaim - either because they
5841 * don't have any reclaimable pages, or because their
5842 * memory is explicitly protected. Avoid soft lockups.
5843 */
5844 cond_resched();
5845
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005846 trace_android_vh_shrink_node_memcgs(memcg, &skip);
5847 if (skip)
5848 continue;
5849
Chris Down45c7f7e2020-08-06 23:22:05 -07005850 mem_cgroup_calculate_protection(target_memcg, memcg);
5851
5852 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005853 /*
5854 * Hard protection.
5855 * If there is no reclaimable memory, OOM.
5856 */
5857 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005858 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005859 /*
5860 * Soft protection.
5861 * Respect the protection only as long as
5862 * there is an unprotected supply
5863 * of reclaimable memory from other cgroups.
5864 */
5865 if (!sc->memcg_low_reclaim) {
5866 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005867 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005868 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005869 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005870 }
5871
Johannes Weinerd2af3392019-11-30 17:55:43 -08005872 reclaimed = sc->nr_reclaimed;
5873 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005874
5875 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005876
Johannes Weinerd2af3392019-11-30 17:55:43 -08005877 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5878 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005879
Johannes Weinerd2af3392019-11-30 17:55:43 -08005880 /* Record the group's reclaim efficiency */
5881 vmpressure(sc->gfp_mask, memcg, false,
5882 sc->nr_scanned - scanned,
5883 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005884
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005885 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5886}
5887
Liu Song6c9e09072020-01-30 22:14:08 -08005888static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005889{
5890 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005891 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005892 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005893 bool reclaimable = false;
5894
Johannes Weiner1b051172019-11-30 17:55:52 -08005895 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5896
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005897again:
5898 memset(&sc->nr, 0, sizeof(sc->nr));
5899
5900 nr_reclaimed = sc->nr_reclaimed;
5901 nr_scanned = sc->nr_scanned;
5902
Yu Zhao6d313442022-09-18 02:00:00 -06005903 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005904
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005905 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005906
Johannes Weinerd2af3392019-11-30 17:55:43 -08005907 if (reclaim_state) {
5908 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5909 reclaim_state->reclaimed_slab = 0;
5910 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005911
Johannes Weinerd2af3392019-11-30 17:55:43 -08005912 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005913 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005914 sc->nr_scanned - nr_scanned,
5915 sc->nr_reclaimed - nr_reclaimed);
5916
5917 if (sc->nr_reclaimed - nr_reclaimed)
5918 reclaimable = true;
5919
5920 if (current_is_kswapd()) {
5921 /*
5922 * If reclaim is isolating dirty pages under writeback,
5923 * it implies that the long-lived page allocation rate
5924 * is exceeding the page laundering rate. Either the
5925 * global limits are not being effective at throttling
5926 * processes due to the page distribution throughout
5927 * zones or there is heavy usage of a slow backing
5928 * device. The only option is to throttle from reclaim
5929 * context which is not ideal as there is no guarantee
5930 * the dirtying process is throttled in the same way
5931 * balance_dirty_pages() manages.
5932 *
5933 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5934 * count the number of pages under pages flagged for
5935 * immediate reclaim and stall if any are encountered
5936 * in the nr_immediate check below.
5937 */
5938 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5939 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005940
Johannes Weinerd2af3392019-11-30 17:55:43 -08005941 /* Allow kswapd to start writing pages during reclaim.*/
5942 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5943 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005944
5945 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005946 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005947 * reclaim and under writeback (nr_immediate), it
5948 * implies that pages are cycling through the LRU
5949 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005950 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005951 if (sc->nr.immediate)
5952 congestion_wait(BLK_RW_ASYNC, HZ/10);
5953 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005954
Johannes Weinerd2af3392019-11-30 17:55:43 -08005955 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005956 * Tag a node/memcg as congested if all the dirty pages
5957 * scanned were backed by a congested BDI and
5958 * wait_iff_congested will stall.
5959 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005960 * Legacy memcg will stall in page writeback so avoid forcibly
5961 * stalling in wait_iff_congested().
5962 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005963 if ((current_is_kswapd() ||
5964 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005965 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005966 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005967
5968 /*
5969 * Stall direct reclaim for IO completions if underlying BDIs
5970 * and node is congested. Allow kswapd to continue until it
5971 * starts encountering unqueued dirty pages or cycling through
5972 * the LRU too quickly.
5973 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005974 if (!current_is_kswapd() && current_may_throttle() &&
5975 !sc->hibernation_mode &&
5976 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005977 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5978
5979 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5980 sc))
5981 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005982
Johannes Weinerc73322d2017-05-03 14:51:51 -07005983 /*
5984 * Kswapd gives up on balancing particular nodes after too
5985 * many failures to reclaim anything from them and goes to
5986 * sleep. On reclaim progress, reset the failure counter. A
5987 * successful direct reclaim run will revive a dormant kswapd.
5988 */
5989 if (reclaimable)
5990 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005991}
5992
Vlastimil Babka53853e22014-10-09 15:27:02 -07005993/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005994 * Returns true if compaction should go ahead for a costly-order request, or
5995 * the allocation would already succeed without compaction. Return false if we
5996 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07005997 */
Mel Gorman4f588332016-07-28 15:46:38 -07005998static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005999{
Mel Gorman31483b62016-07-28 15:45:46 -07006000 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006001 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006002
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006003 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6004 if (suitable == COMPACT_SUCCESS)
6005 /* Allocation should succeed already. Don't reclaim. */
6006 return true;
6007 if (suitable == COMPACT_SKIPPED)
6008 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006009 return false;
6010
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006011 /*
6012 * Compaction is already possible, but it takes time to run and there
6013 * are potentially other callers using the pages just freed. So proceed
6014 * with reclaim to make a buffer of free pages available to give
6015 * compaction a reasonable chance of completing and allocating the page.
6016 * Note that we won't actually reclaim the whole buffer in one attempt
6017 * as the target watermark in should_continue_reclaim() is lower. But if
6018 * we are already above the high+gap watermark, don't reclaim at all.
6019 */
6020 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6021
6022 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006023}
6024
Linus Torvalds1da177e2005-04-16 15:20:36 -07006025/*
6026 * This is the direct reclaim path, for page-allocating processes. We only
6027 * try to reclaim pages from zones which will satisfy the caller's allocation
6028 * request.
6029 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07006030 * If a zone is deemed to be full of pinned pages then just give it a light
6031 * scan then give up on it.
6032 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07006033static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006034{
Mel Gormandd1a2392008-04-28 02:12:17 -07006035 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07006036 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07006037 unsigned long nr_soft_reclaimed;
6038 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07006039 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07006040 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006041
Mel Gormancc715d92012-03-21 16:34:00 -07006042 /*
6043 * If the number of buffer_heads in the machine exceeds the maximum
6044 * allowed level, force direct reclaim to scan the highmem zone as
6045 * highmem pages could be pinning lowmem pages storing buffer_heads
6046 */
Weijie Yang619d0d762014-04-07 15:36:59 -07006047 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07006048 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07006049 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07006050 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07006051 }
Mel Gormancc715d92012-03-21 16:34:00 -07006052
Mel Gormand4debc62010-08-09 17:19:29 -07006053 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07006054 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07006055 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006056 * Take care memory controller reclaiming has small influence
6057 * to global LRU.
6058 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08006059 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04006060 if (!cpuset_zone_allowed(zone,
6061 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006062 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006063
Johannes Weiner0b064962014-08-06 16:06:12 -07006064 /*
6065 * If we already have plenty of memory free for
6066 * compaction in this zone, don't free any more.
6067 * Even though compaction is invoked for any
6068 * non-zero order, only frequent costly order
6069 * reclamation is disruptive enough to become a
6070 * noticeable problem, like transparent huge
6071 * page allocations.
6072 */
6073 if (IS_ENABLED(CONFIG_COMPACTION) &&
6074 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07006075 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07006076 sc->compaction_ready = true;
6077 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07006078 }
Johannes Weiner0b064962014-08-06 16:06:12 -07006079
Andrew Morton0608f432013-09-24 15:27:41 -07006080 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07006081 * Shrink each node in the zonelist once. If the
6082 * zonelist is ordered by zone (not the default) then a
6083 * node may be shrunk multiple times but in that case
6084 * the user prefers lower zones being preserved.
6085 */
6086 if (zone->zone_pgdat == last_pgdat)
6087 continue;
6088
6089 /*
Andrew Morton0608f432013-09-24 15:27:41 -07006090 * This steals pages from memory cgroups over softlimit
6091 * and returns the number of reclaimed pages and
6092 * scanned pages. This works for global memory pressure
6093 * and balancing, not for a memcg's limit.
6094 */
6095 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006096 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006097 sc->order, sc->gfp_mask,
6098 &nr_soft_scanned);
6099 sc->nr_reclaimed += nr_soft_reclaimed;
6100 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006101 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006102 }
Nick Piggin408d8542006-09-25 23:31:27 -07006103
Mel Gorman79dafcd2016-07-28 15:45:53 -07006104 /* See comment about same check for global reclaim above */
6105 if (zone->zone_pgdat == last_pgdat)
6106 continue;
6107 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006108 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006109 }
Mel Gormane0c23272011-10-31 17:09:33 -07006110
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006111 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006112 * Restore to original mask to avoid the impact on the caller if we
6113 * promoted it to __GFP_HIGHMEM.
6114 */
6115 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006116}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006117
Johannes Weinerb9107182019-11-30 17:55:59 -08006118static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006119{
Johannes Weinerb9107182019-11-30 17:55:59 -08006120 struct lruvec *target_lruvec;
6121 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006122
Yu Zhao37397872022-09-18 02:00:03 -06006123 if (lru_gen_enabled())
6124 return;
6125
Johannes Weinerb9107182019-11-30 17:55:59 -08006126 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006127 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6128 target_lruvec->refaults[0] = refaults;
6129 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6130 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006131}
6132
Linus Torvalds1da177e2005-04-16 15:20:36 -07006133/*
6134 * This is the main entry point to direct page reclaim.
6135 *
6136 * If a full scan of the inactive list fails to free enough memory then we
6137 * are "out of memory" and something needs to be killed.
6138 *
6139 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6140 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006141 * caller can't do much about. We kick the writeback threads and take explicit
6142 * naps in the hope that some of these pages can be written. But if the
6143 * allocating task holds filesystem locks which prevent writeout this might not
6144 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006145 *
6146 * returns: 0, if no pages reclaimed
6147 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006148 */
Mel Gormandac1d272008-04-28 02:12:12 -07006149static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006150 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006151{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006152 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006153 pg_data_t *last_pgdat;
6154 struct zoneref *z;
6155 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006156retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006157 delayacct_freepages_start();
6158
Johannes Weinerb5ead352019-11-30 17:55:40 -08006159 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006160 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006161
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006162 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006163 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6164 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006165 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006166 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006167
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006168 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006169 break;
6170
6171 if (sc->compaction_ready)
6172 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006173
6174 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006175 * If we're getting trouble reclaiming, start doing
6176 * writepage even in laptop mode.
6177 */
6178 if (sc->priority < DEF_PRIORITY - 2)
6179 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006180 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006181
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006182 last_pgdat = NULL;
6183 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6184 sc->nodemask) {
6185 if (zone->zone_pgdat == last_pgdat)
6186 continue;
6187 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006188
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006189 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006190
6191 if (cgroup_reclaim(sc)) {
6192 struct lruvec *lruvec;
6193
6194 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6195 zone->zone_pgdat);
6196 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6197 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006198 }
6199
Keika Kobayashi873b4772008-07-25 01:48:52 -07006200 delayacct_freepages_end();
6201
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006202 if (sc->nr_reclaimed)
6203 return sc->nr_reclaimed;
6204
Mel Gorman0cee34f2012-01-12 17:19:49 -08006205 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006206 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006207 return 1;
6208
Johannes Weinerb91ac372019-11-30 17:56:02 -08006209 /*
6210 * We make inactive:active ratio decisions based on the node's
6211 * composition of memory, but a restrictive reclaim_idx or a
6212 * memory.low cgroup setting can exempt large amounts of
6213 * memory from reclaim. Neither of which are very common, so
6214 * instead of doing costly eligibility calculations of the
6215 * entire cgroup subtree up front, we assume the estimates are
6216 * good, and retry with forcible deactivation if that fails.
6217 */
6218 if (sc->skipped_deactivate) {
6219 sc->priority = initial_priority;
6220 sc->force_deactivate = 1;
6221 sc->skipped_deactivate = 0;
6222 goto retry;
6223 }
6224
Johannes Weiner241994ed2015-02-11 15:26:06 -08006225 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006226 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006227 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006228 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006229 sc->memcg_low_reclaim = 1;
6230 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006231 goto retry;
6232 }
6233
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006234 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006235}
6236
Johannes Weinerc73322d2017-05-03 14:51:51 -07006237static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006238{
6239 struct zone *zone;
6240 unsigned long pfmemalloc_reserve = 0;
6241 unsigned long free_pages = 0;
6242 int i;
6243 bool wmark_ok;
6244
Johannes Weinerc73322d2017-05-03 14:51:51 -07006245 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6246 return true;
6247
Mel Gorman55150612012-07-31 16:44:35 -07006248 for (i = 0; i <= ZONE_NORMAL; i++) {
6249 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006250 if (!managed_zone(zone))
6251 continue;
6252
6253 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006254 continue;
6255
Mel Gorman55150612012-07-31 16:44:35 -07006256 pfmemalloc_reserve += min_wmark_pages(zone);
6257 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6258 }
6259
Mel Gorman675becc2014-06-04 16:07:35 -07006260 /* If there are no reserves (unexpected config) then do not throttle */
6261 if (!pfmemalloc_reserve)
6262 return true;
6263
Mel Gorman55150612012-07-31 16:44:35 -07006264 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6265
6266 /* kswapd must be awake if processes are being throttled */
6267 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006268 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6269 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006270
Mel Gorman55150612012-07-31 16:44:35 -07006271 wake_up_interruptible(&pgdat->kswapd_wait);
6272 }
6273
6274 return wmark_ok;
6275}
6276
6277/*
6278 * Throttle direct reclaimers if backing storage is backed by the network
6279 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6280 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006281 * when the low watermark is reached.
6282 *
6283 * Returns true if a fatal signal was delivered during throttling. If this
6284 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006285 */
Mel Gorman50694c22012-11-26 16:29:48 -08006286static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006287 nodemask_t *nodemask)
6288{
Mel Gorman675becc2014-06-04 16:07:35 -07006289 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006290 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006291 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006292
6293 /*
6294 * Kernel threads should not be throttled as they may be indirectly
6295 * responsible for cleaning pages necessary for reclaim to make forward
6296 * progress. kjournald for example may enter direct reclaim while
6297 * committing a transaction where throttling it could forcing other
6298 * processes to block on log_wait_commit().
6299 */
6300 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006301 goto out;
6302
6303 /*
6304 * If a fatal signal is pending, this process should not throttle.
6305 * It should return quickly so it can exit and free its memory
6306 */
6307 if (fatal_signal_pending(current))
6308 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006309
Mel Gorman675becc2014-06-04 16:07:35 -07006310 /*
6311 * Check if the pfmemalloc reserves are ok by finding the first node
6312 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6313 * GFP_KERNEL will be required for allocating network buffers when
6314 * swapping over the network so ZONE_HIGHMEM is unusable.
6315 *
6316 * Throttling is based on the first usable node and throttled processes
6317 * wait on a queue until kswapd makes progress and wakes them. There
6318 * is an affinity then between processes waking up and where reclaim
6319 * progress has been made assuming the process wakes on the same node.
6320 * More importantly, processes running on remote nodes will not compete
6321 * for remote pfmemalloc reserves and processes on different nodes
6322 * should make reasonable progress.
6323 */
6324 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006325 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006326 if (zone_idx(zone) > ZONE_NORMAL)
6327 continue;
6328
6329 /* Throttle based on the first usable node */
6330 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006331 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006332 goto out;
6333 break;
6334 }
6335
6336 /* If no zone was usable by the allocation flags then do not throttle */
6337 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006338 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006339
Mel Gorman68243e72012-07-31 16:44:39 -07006340 /* Account for the throttling */
6341 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6342
Mel Gorman55150612012-07-31 16:44:35 -07006343 /*
6344 * If the caller cannot enter the filesystem, it's possible that it
6345 * is due to the caller holding an FS lock or performing a journal
6346 * transaction in the case of a filesystem like ext[3|4]. In this case,
6347 * it is not safe to block on pfmemalloc_wait as kswapd could be
6348 * blocked waiting on the same lock. Instead, throttle for up to a
6349 * second before continuing.
6350 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006351 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006352 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006353 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006354 else
6355 /* Throttle until kswapd wakes the process */
6356 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6357 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006358
Mel Gorman50694c22012-11-26 16:29:48 -08006359 if (fatal_signal_pending(current))
6360 return true;
6361
6362out:
6363 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006364}
6365
Mel Gormandac1d272008-04-28 02:12:12 -07006366unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006367 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006368{
Mel Gorman33906bc2010-08-09 17:19:16 -07006369 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006370 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006371 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006372 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006373 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006374 .order = order,
6375 .nodemask = nodemask,
6376 .priority = DEF_PRIORITY,
6377 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006378 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006379 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006380 };
6381
Mel Gorman55150612012-07-31 16:44:35 -07006382 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006383 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6384 * Confirm they are large enough for max values.
6385 */
6386 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6387 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6388 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6389
6390 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006391 * Do not enter reclaim if fatal signal was delivered while throttled.
6392 * 1 is returned so that the page allocator does not OOM kill at this
6393 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006394 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006395 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006396 return 1;
6397
Andrew Morton1732d2b012019-07-16 16:26:15 -07006398 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006399 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006400
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006401 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006402
6403 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006404 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006405
6406 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006407}
6408
Andrew Mortonc255a452012-07-31 16:43:02 -07006409#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006410
Michal Hockod2e5fb92019-08-30 16:04:50 -07006411/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006412unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006413 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006414 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006415 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006416{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006417 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006418 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006419 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006420 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006421 .may_writepage = !laptop_mode,
6422 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006423 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006424 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006425 };
Ying Han0ae5e892011-05-26 16:25:25 -07006426
Michal Hockod2e5fb92019-08-30 16:04:50 -07006427 WARN_ON_ONCE(!current->reclaim_state);
6428
Balbir Singh4e416952009-09-23 15:56:39 -07006429 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6430 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006431
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006432 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006433 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006434
Balbir Singh4e416952009-09-23 15:56:39 -07006435 /*
6436 * NOTE: Although we can get the priority field, using it
6437 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006438 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006439 * will pick up pages from other mem cgroup's as well. We hack
6440 * the priority and make it zero.
6441 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006442 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006443
6444 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6445
Ying Han0ae5e892011-05-26 16:25:25 -07006446 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006447
Balbir Singh4e416952009-09-23 15:56:39 -07006448 return sc.nr_reclaimed;
6449}
6450
Johannes Weiner72835c82012-01-12 17:18:32 -08006451unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006452 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006453 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006454 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08006455{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006456 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006457 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006458 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006459 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006460 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006461 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006462 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006463 .target_mem_cgroup = memcg,
6464 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006465 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006466 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006467 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07006468 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006469 /*
6470 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6471 * equal pressure on all the nodes. This is based on the assumption that
6472 * the reclaim does not bail out early.
6473 */
6474 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006475
Andrew Morton1732d2b012019-07-16 16:26:15 -07006476 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006477 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006478 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006479
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006480 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006481
Vlastimil Babka499118e2017-05-08 15:59:50 -07006482 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006483 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006484 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006485
6486 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006487}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006488EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006489#endif
6490
Yu Zhao37397872022-09-18 02:00:03 -06006491static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006492{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006493 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006494 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006495
Yu Zhao37397872022-09-18 02:00:03 -06006496 if (lru_gen_enabled()) {
6497 lru_gen_age_node(pgdat, sc);
6498 return;
6499 }
6500
Dave Hansen2f368a92021-09-02 14:59:23 -07006501 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006502 return;
6503
Johannes Weinerb91ac372019-11-30 17:56:02 -08006504 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6505 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6506 return;
6507
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006508 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6509 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006510 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6511 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6512 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006513 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6514 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006515}
6516
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006517static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006518{
6519 int i;
6520 struct zone *zone;
6521
6522 /*
6523 * Check for watermark boosts top-down as the higher zones
6524 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006525 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006526 * start prematurely when there is no boosting and a lower
6527 * zone is balanced.
6528 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006529 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006530 zone = pgdat->node_zones + i;
6531 if (!managed_zone(zone))
6532 continue;
6533
6534 if (zone->watermark_boost)
6535 return true;
6536 }
6537
6538 return false;
6539}
6540
Mel Gormane716f2e2017-05-03 14:53:45 -07006541/*
6542 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006543 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006544 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006545static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006546{
Mel Gormane716f2e2017-05-03 14:53:45 -07006547 int i;
6548 unsigned long mark = -1;
6549 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006550
Mel Gorman1c308442018-12-28 00:35:52 -08006551 /*
6552 * Check watermarks bottom-up as lower zones are more likely to
6553 * meet watermarks.
6554 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006555 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006556 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006557
Mel Gormane716f2e2017-05-03 14:53:45 -07006558 if (!managed_zone(zone))
6559 continue;
6560
6561 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006562 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006563 return true;
6564 }
6565
6566 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006567 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006568 * need balancing by definition. This can happen if a zone-restricted
6569 * allocation tries to wake a remote kswapd.
6570 */
6571 if (mark == -1)
6572 return true;
6573
6574 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006575}
6576
Mel Gorman631b6e02017-05-03 14:53:41 -07006577/* Clear pgdat state for congested, dirty or under writeback. */
6578static void clear_pgdat_congested(pg_data_t *pgdat)
6579{
Johannes Weiner1b051172019-11-30 17:55:52 -08006580 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6581
6582 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006583 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6584 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6585}
6586
Mel Gorman1741c872011-01-13 15:46:21 -08006587/*
Mel Gorman55150612012-07-31 16:44:35 -07006588 * Prepare kswapd for sleeping. This verifies that there are no processes
6589 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6590 *
6591 * Returns true if kswapd is ready to sleep
6592 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006593static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6594 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006595{
Mel Gorman55150612012-07-31 16:44:35 -07006596 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006597 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006598 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006599 * race between when kswapd checks the watermarks and a process gets
6600 * throttled. There is also a potential race if processes get
6601 * throttled, kswapd wakes, a large process exits thereby balancing the
6602 * zones, which causes kswapd to exit balance_pgdat() before reaching
6603 * the wake up checks. If kswapd is going to sleep, no process should
6604 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6605 * the wake up is premature, processes will wake kswapd and get
6606 * throttled again. The difference from wake ups in balance_pgdat() is
6607 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006608 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006609 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6610 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006611
Johannes Weinerc73322d2017-05-03 14:51:51 -07006612 /* Hopeless node, leave it to direct reclaim */
6613 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6614 return true;
6615
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006616 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006617 clear_pgdat_congested(pgdat);
6618 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006619 }
6620
Shantanu Goel333b0a42017-05-03 14:53:38 -07006621 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006622}
6623
Linus Torvalds1da177e2005-04-16 15:20:36 -07006624/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006625 * kswapd shrinks a node of pages that are at or below the highest usable
6626 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006627 *
6628 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006629 * reclaim or if the lack of progress was due to pages under writeback.
6630 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006631 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006632static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006633 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006634{
Mel Gorman1d82de62016-07-28 15:45:43 -07006635 struct zone *zone;
6636 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006637
Mel Gorman1d82de62016-07-28 15:45:43 -07006638 /* Reclaim a number of pages proportional to the number of zones */
6639 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006640 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006641 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006642 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006643 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006644
Mel Gorman1d82de62016-07-28 15:45:43 -07006645 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006646 }
6647
Mel Gorman1d82de62016-07-28 15:45:43 -07006648 /*
6649 * Historically care was taken to put equal pressure on all zones but
6650 * now pressure is applied based on node LRU order.
6651 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006652 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006653
6654 /*
6655 * Fragmentation may mean that the system cannot be rebalanced for
6656 * high-order allocations. If twice the allocation size has been
6657 * reclaimed then recheck watermarks only at order-0 to prevent
6658 * excessive reclaim. Assume that a process requested a high-order
6659 * can direct reclaim/compact.
6660 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006661 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006662 sc->order = 0;
6663
Mel Gormanb8e83b92013-07-03 15:01:45 -07006664 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006665}
6666
Mel Gormanc49c2c42021-06-28 19:42:21 -07006667/* Page allocator PCP high watermark is lowered if reclaim is active. */
6668static inline void
6669update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6670{
6671 int i;
6672 struct zone *zone;
6673
6674 for (i = 0; i <= highest_zoneidx; i++) {
6675 zone = pgdat->node_zones + i;
6676
6677 if (!managed_zone(zone))
6678 continue;
6679
6680 if (active)
6681 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6682 else
6683 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6684 }
6685}
6686
6687static inline void
6688set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6689{
6690 update_reclaim_active(pgdat, highest_zoneidx, true);
6691}
6692
6693static inline void
6694clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6695{
6696 update_reclaim_active(pgdat, highest_zoneidx, false);
6697}
6698
Mel Gorman75485362013-07-03 15:01:42 -07006699/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006700 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6701 * that are eligible for use by the caller until at least one zone is
6702 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006703 *
Mel Gorman1d82de62016-07-28 15:45:43 -07006704 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006705 *
6706 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07006707 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08006708 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07006709 * or lower is eligible for reclaim until at least one usable zone is
6710 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006711 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006712static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006713{
Linus Torvalds1da177e2005-04-16 15:20:36 -07006714 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07006715 unsigned long nr_soft_reclaimed;
6716 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07006717 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08006718 unsigned long nr_boost_reclaim;
6719 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6720 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07006721 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08006722 struct scan_control sc = {
6723 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07006724 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006725 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08006726 };
Omar Sandoval93781322018-06-07 17:07:02 -07006727
Andrew Morton1732d2b012019-07-16 16:26:15 -07006728 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07006729 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006730 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006731
Christoph Lameterf8891e52006-06-30 01:55:45 -07006732 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006733
Mel Gorman1c308442018-12-28 00:35:52 -08006734 /*
6735 * Account for the reclaim boost. Note that the zone boost is left in
6736 * place so that parallel allocations that are near the watermark will
6737 * stall or direct reclaim until kswapd is finished.
6738 */
6739 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006740 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006741 zone = pgdat->node_zones + i;
6742 if (!managed_zone(zone))
6743 continue;
6744
6745 nr_boost_reclaim += zone->watermark_boost;
6746 zone_boosts[i] = zone->watermark_boost;
6747 }
6748 boosted = nr_boost_reclaim;
6749
6750restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006751 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006752 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006753 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006754 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006755 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006756 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006757 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006758
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006759 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006760
Mel Gorman86c79f62016-07-28 15:45:59 -07006761 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006762 * If the number of buffer_heads exceeds the maximum allowed
6763 * then consider reclaiming from all zones. This has a dual
6764 * purpose -- on 64-bit systems it is expected that
6765 * buffer_heads are stripped during active rotation. On 32-bit
6766 * systems, highmem pages can pin lowmem memory and shrinking
6767 * buffers can relieve lowmem pressure. Reclaim may still not
6768 * go ahead if all eligible zones for the original allocation
6769 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006770 */
6771 if (buffer_heads_over_limit) {
6772 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6773 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006774 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006775 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006776
Mel Gorman970a39a2016-07-28 15:46:35 -07006777 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006778 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006779 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006780 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006781
Mel Gorman86c79f62016-07-28 15:45:59 -07006782 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006783 * If the pgdat is imbalanced then ignore boosting and preserve
6784 * the watermarks for a later time and restart. Note that the
6785 * zone watermarks will be still reset at the end of balancing
6786 * on the grounds that the normal reclaim should be enough to
6787 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006788 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006789 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006790 if (!balanced && nr_boost_reclaim) {
6791 nr_boost_reclaim = 0;
6792 goto restart;
6793 }
6794
6795 /*
6796 * If boosting is not active then only reclaim if there are no
6797 * eligible zones. Note that sc.reclaim_idx is not used as
6798 * buffer_heads_over_limit may have adjusted it.
6799 */
6800 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006801 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006802
Mel Gorman1c308442018-12-28 00:35:52 -08006803 /* Limit the priority of boosting to avoid reclaim writeback */
6804 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6805 raise_priority = false;
6806
6807 /*
6808 * Do not writeback or swap pages for boosted reclaim. The
6809 * intent is to relieve pressure not issue sub-optimal IO
6810 * from reclaim context. If no pages are reclaimed, the
6811 * reclaim will be aborted.
6812 */
6813 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6814 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006815
Linus Torvalds1da177e2005-04-16 15:20:36 -07006816 /*
Yu Zhao37397872022-09-18 02:00:03 -06006817 * Do some background aging, to give pages a chance to be
6818 * referenced before reclaiming. All pages are rotated
6819 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07006820 */
Yu Zhao37397872022-09-18 02:00:03 -06006821 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006822
6823 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006824 * If we're getting trouble reclaiming, start doing writepage
6825 * even in laptop mode.
6826 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006827 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006828 sc.may_writepage = 1;
6829
Mel Gorman1d82de62016-07-28 15:45:43 -07006830 /* Call soft limit reclaim before calling shrink_node. */
6831 sc.nr_scanned = 0;
6832 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006833 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006834 sc.gfp_mask, &nr_soft_scanned);
6835 sc.nr_reclaimed += nr_soft_reclaimed;
6836
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006837 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006838 * There should be no need to raise the scanning priority if
6839 * enough pages are already being scanned that that high
6840 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006841 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006842 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006843 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006844
6845 /*
6846 * If the low watermark is met there is no need for processes
6847 * to be throttled on pfmemalloc_wait as they should not be
6848 * able to safely make forward progress. Wake them
6849 */
6850 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006851 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006852 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006853
Mel Gormanb8e83b92013-07-03 15:01:45 -07006854 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006855 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006856 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006857 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006858 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006859 break;
6860
6861 /*
6862 * Raise priority if scanning rate is too low or there was no
6863 * progress in reclaiming pages
6864 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006865 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006866 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6867
6868 /*
6869 * If reclaim made no progress for a boost, stop reclaim as
6870 * IO cannot be queued and it could be an infinite loop in
6871 * extreme circumstances.
6872 */
6873 if (nr_boost_reclaim && !nr_reclaimed)
6874 break;
6875
Johannes Weinerc73322d2017-05-03 14:51:51 -07006876 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006877 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006878 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006879
Johannes Weinerc73322d2017-05-03 14:51:51 -07006880 if (!sc.nr_reclaimed)
6881 pgdat->kswapd_failures++;
6882
Mel Gormanb8e83b92013-07-03 15:01:45 -07006883out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006884 clear_reclaim_active(pgdat, highest_zoneidx);
6885
Mel Gorman1c308442018-12-28 00:35:52 -08006886 /* If reclaim was boosted, account for the reclaim done in this pass */
6887 if (boosted) {
6888 unsigned long flags;
6889
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006890 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006891 if (!zone_boosts[i])
6892 continue;
6893
6894 /* Increments are under the zone lock */
6895 zone = pgdat->node_zones + i;
6896 spin_lock_irqsave(&zone->lock, flags);
6897 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6898 spin_unlock_irqrestore(&zone->lock, flags);
6899 }
6900
6901 /*
6902 * As there is now likely space, wakeup kcompact to defragment
6903 * pageblocks.
6904 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006905 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006906 }
6907
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006908 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006909 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006910 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006911 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006912
Mel Gorman0abdee22011-01-13 15:46:22 -08006913 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006914 * Return the order kswapd stopped reclaiming at as
6915 * prepare_kswapd_sleep() takes it into account. If another caller
6916 * entered the allocator slow path while kswapd was awake, order will
6917 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006918 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006919 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006920}
6921
Mel Gormane716f2e2017-05-03 14:53:45 -07006922/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006923 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6924 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6925 * not a valid index then either kswapd runs for first time or kswapd couldn't
6926 * sleep after previous reclaim attempt (node is still unbalanced). In that
6927 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006928 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006929static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6930 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006931{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006932 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006933
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006934 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006935}
6936
Mel Gorman38087d92016-07-28 15:45:49 -07006937static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006938 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006939{
6940 long remaining = 0;
6941 DEFINE_WAIT(wait);
6942
6943 if (freezing(current) || kthread_should_stop())
6944 return;
6945
6946 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6947
Shantanu Goel333b0a42017-05-03 14:53:38 -07006948 /*
6949 * Try to sleep for a short interval. Note that kcompactd will only be
6950 * woken if it is possible to sleep for a short interval. This is
6951 * deliberate on the assumption that if reclaim cannot keep an
6952 * eligible zone balanced that it's also unlikely that compaction will
6953 * succeed.
6954 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006955 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006956 /*
6957 * Compaction records what page blocks it recently failed to
6958 * isolate pages from and skips them in the future scanning.
6959 * When kswapd is going to sleep, it is reasonable to assume
6960 * that pages and compaction may succeed so reset the cache.
6961 */
6962 reset_isolation_suitable(pgdat);
6963
6964 /*
6965 * We have freed the memory, now we should compact it to make
6966 * allocation of the requested order possible.
6967 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006968 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006969
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006970 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006971
6972 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006973 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006974 * order. The values will either be from a wakeup request or
6975 * the previous request that slept prematurely.
6976 */
6977 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006978 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6979 kswapd_highest_zoneidx(pgdat,
6980 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006981
6982 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6983 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006984 }
6985
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006986 finish_wait(&pgdat->kswapd_wait, &wait);
6987 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6988 }
6989
6990 /*
6991 * After a short sleep, check if it was a premature sleep. If not, then
6992 * go fully to sleep until explicitly woken up.
6993 */
Mel Gormand9f21d42016-07-28 15:46:41 -07006994 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006995 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006996 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6997
6998 /*
6999 * vmstat counters are not perfectly accurate and the estimated
7000 * value for counters such as NR_FREE_PAGES can deviate from the
7001 * true value by nr_online_cpus * threshold. To avoid the zone
7002 * watermarks being breached while under pressure, we reduce the
7003 * per-cpu vmstat threshold while kswapd is awake and restore
7004 * them before going back to sleep.
7005 */
7006 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07007007
7008 if (!kthread_should_stop())
7009 schedule();
7010
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007011 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7012 } else {
7013 if (remaining)
7014 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7015 else
7016 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7017 }
7018 finish_wait(&pgdat->kswapd_wait, &wait);
7019}
7020
Linus Torvalds1da177e2005-04-16 15:20:36 -07007021/*
7022 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07007023 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007024 *
7025 * This basically trickles out pages so that we have _some_
7026 * free memory available even if there is no other activity
7027 * that frees anything up. This is needed for things like routing
7028 * etc, where we otherwise might have all activity going on in
7029 * asynchronous contexts that cannot page things out.
7030 *
7031 * If there are applications that are active memory-allocators
7032 * (most normal use), this basically shouldn't matter.
7033 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307034int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007035{
Mel Gormane716f2e2017-05-03 14:53:45 -07007036 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007037 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07007038 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007039 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10307040 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007041
Rusty Russell174596a2009-01-01 10:12:29 +10307042 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07007043 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007044
7045 /*
7046 * Tell the memory management that we're a "memory allocator",
7047 * and that if we need more memory we should get access to it
7048 * regardless (see "__alloc_pages()"). "kswapd" should
7049 * never get caught in the normal page freeing logic.
7050 *
7051 * (Kswapd normally doesn't need memory anyway, but sometimes
7052 * you need a small amount of memory in order to be able to
7053 * page out something else, and this flag essentially protects
7054 * us from recursively trying to free more memory as we're
7055 * trying to free the first piece of memory in the first place).
7056 */
Christoph Lameter930d9152006-01-08 01:00:47 -08007057 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07007058 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07007059
Qian Cai5644e1fb2020-04-01 21:10:12 -07007060 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007061 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007062 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08007063 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07007064
Qian Cai5644e1fb2020-04-01 21:10:12 -07007065 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007066 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7067 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07007068
Mel Gorman38087d92016-07-28 15:45:49 -07007069kswapd_try_sleep:
7070 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007071 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07007072
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007073 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08007074 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007075 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7076 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007077 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007078 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007079
David Rientjes8fe23e02009-12-14 17:58:33 -08007080 ret = try_to_freeze();
7081 if (kthread_should_stop())
7082 break;
7083
7084 /*
7085 * We can speed up thawing tasks if we don't call balance_pgdat
7086 * after returning from the refrigerator
7087 */
Mel Gorman38087d92016-07-28 15:45:49 -07007088 if (ret)
7089 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07007090
Mel Gorman38087d92016-07-28 15:45:49 -07007091 /*
7092 * Reclaim begins at the requested order but if a high-order
7093 * reclaim fails then kswapd falls back to reclaiming for
7094 * order-0. If that happens, kswapd will consider sleeping
7095 * for the order it finished reclaiming at (reclaim_order)
7096 * but kcompactd is woken to compact for the original
7097 * request (alloc_order).
7098 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007099 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007100 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007101 reclaim_order = balance_pgdat(pgdat, alloc_order,
7102 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007103 if (reclaim_order < alloc_order)
7104 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007105 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007106
Johannes Weiner71abdc12014-06-06 14:35:35 -07007107 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007108
Linus Torvalds1da177e2005-04-16 15:20:36 -07007109 return 0;
7110}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307111EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007112
7113/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007114 * A zone is low on free memory or too fragmented for high-order memory. If
7115 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7116 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7117 * has failed or is not needed, still wake up kcompactd if only compaction is
7118 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007119 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007120void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007121 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007122{
7123 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007124 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007125
Mel Gorman6aa303d2016-09-01 16:14:55 -07007126 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007127 return;
7128
David Rientjes5ecd9d42018-04-05 16:25:16 -07007129 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007130 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007131
Qian Cai5644e1fb2020-04-01 21:10:12 -07007132 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007133 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007134
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007135 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7136 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007137
7138 if (READ_ONCE(pgdat->kswapd_order) < order)
7139 WRITE_ONCE(pgdat->kswapd_order, order);
7140
Con Kolivas8d0986e2005-09-13 01:25:07 -07007141 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007142 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007143
David Rientjes5ecd9d42018-04-05 16:25:16 -07007144 /* Hopeless node, leave it to direct reclaim if possible */
7145 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007146 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7147 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007148 /*
7149 * There may be plenty of free memory available, but it's too
7150 * fragmented for high-order allocations. Wake up kcompactd
7151 * and rely on compaction_suitable() to determine if it's
7152 * needed. If it fails, it will defer subsequent attempts to
7153 * ratelimit its work.
7154 */
7155 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007156 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007157 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007158 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007159
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007160 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007161 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007162 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007163}
7164
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007165#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007166/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007167 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007168 * freed pages.
7169 *
7170 * Rather than trying to age LRUs the aim is to preserve the overall
7171 * LRU order by reclaiming preferentially
7172 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007173 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007174unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007175{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007176 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007177 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007178 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007179 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007180 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007181 .may_writepage = 1,
7182 .may_unmap = 1,
7183 .may_swap = 1,
7184 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007185 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007186 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007187 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007188 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007189
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007190 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007191 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007192 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007193
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007194 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007195
Andrew Morton1732d2b012019-07-16 16:26:15 -07007196 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007197 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007198 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007199
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007200 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007201}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007202#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007203
Yasunori Goto3218ae12006-06-27 02:53:33 -07007204/*
7205 * This kswapd start function will be called by init and node-hot-add.
7206 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7207 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007208void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007209{
7210 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307211 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007212
7213 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007214 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007215
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307216 trace_android_vh_kswapd_per_node(nid, &skip, true);
7217 if (skip)
7218 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007219 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7220 if (IS_ERR(pgdat->kswapd)) {
7221 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007222 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007223 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007224 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007225 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007226}
7227
David Rientjes8fe23e02009-12-14 17:58:33 -08007228/*
Jiang Liud8adde12012-07-11 14:01:52 -07007229 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007230 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007231 */
7232void kswapd_stop(int nid)
7233{
7234 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307235 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007236
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307237 trace_android_vh_kswapd_per_node(nid, &skip, false);
7238 if (skip)
7239 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007240 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007241 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007242 NODE_DATA(nid)->kswapd = NULL;
7243 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007244}
7245
Linus Torvalds1da177e2005-04-16 15:20:36 -07007246static int __init kswapd_init(void)
7247{
Wei Yang6b700b52020-04-01 21:10:09 -07007248 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007249
Linus Torvalds1da177e2005-04-16 15:20:36 -07007250 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007251 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007252 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007253 return 0;
7254}
7255
7256module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007257
7258#ifdef CONFIG_NUMA
7259/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007260 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007261 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007262 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007263 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007264 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007265int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007266
Dave Hansen51998362021-02-24 12:09:15 -08007267/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007268 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007269 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7270 * a zone.
7271 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007272#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007273
Christoph Lameter9eeff232006-01-18 17:42:31 -08007274/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007275 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007276 * occur.
7277 */
7278int sysctl_min_unmapped_ratio = 1;
7279
7280/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007281 * If the number of slab pages in a zone grows beyond this percentage then
7282 * slab reclaim needs to occur.
7283 */
7284int sysctl_min_slab_ratio = 5;
7285
Mel Gorman11fb9982016-07-28 15:46:20 -07007286static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007287{
Mel Gorman11fb9982016-07-28 15:46:20 -07007288 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7289 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7290 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007291
7292 /*
7293 * It's possible for there to be more file mapped pages than
7294 * accounted for by the pages on the file LRU lists because
7295 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7296 */
7297 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7298}
7299
7300/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007301static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007302{
Alexandru Moised031a152015-11-05 18:48:08 -08007303 unsigned long nr_pagecache_reclaimable;
7304 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007305
7306 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007307 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007308 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007309 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007310 * a better estimate
7311 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007312 if (node_reclaim_mode & RECLAIM_UNMAP)
7313 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007314 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007315 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007316
7317 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007318 if (!(node_reclaim_mode & RECLAIM_WRITE))
7319 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007320
7321 /* Watch for any possible underflows due to delta */
7322 if (unlikely(delta > nr_pagecache_reclaimable))
7323 delta = nr_pagecache_reclaimable;
7324
7325 return nr_pagecache_reclaimable - delta;
7326}
7327
Christoph Lameter0ff38492006-09-25 23:31:52 -07007328/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007329 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007330 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007331static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007332{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007333 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007334 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007335 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007336 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007337 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007338 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007339 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007340 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007341 .priority = NODE_RECLAIM_PRIORITY,
7342 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7343 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007344 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007345 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007346 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007347 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007348
Yafang Shao132bb8c2019-05-13 17:17:53 -07007349 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7350 sc.gfp_mask);
7351
Christoph Lameter9eeff232006-01-18 17:42:31 -08007352 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007353 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007354 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007355 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007356 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007357 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007358 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007359 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007360 noreclaim_flag = memalloc_noreclaim_save();
7361 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007362 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007363
Mel Gormana5f5f912016-07-28 15:46:32 -07007364 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007365 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007366 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007367 * priorities until we have enough memory freed.
7368 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007369 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007370 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007371 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007372 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007373
Andrew Morton1732d2b012019-07-16 16:26:15 -07007374 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007375 current->flags &= ~PF_SWAPWRITE;
7376 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007377 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007378 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007379
7380 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7381
Rik van Riela79311c2009-01-06 14:40:01 -08007382 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007383}
Andrew Morton179e9632006-03-22 00:08:18 -08007384
Mel Gormana5f5f912016-07-28 15:46:32 -07007385int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007386{
David Rientjesd773ed62007-10-16 23:26:01 -07007387 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007388
7389 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007390 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007391 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007392 *
Christoph Lameter96146342006-07-03 00:24:13 -07007393 * A small portion of unmapped file backed pages is needed for
7394 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007395 * thrown out if the node is overallocated. So we do not reclaim
7396 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007397 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007398 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007399 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007400 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7401 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007402 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007403
7404 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007405 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007406 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007407 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007408 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007409
7410 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007411 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007412 * have associated processors. This will favor the local processor
7413 * over remote processors and spread off node memory allocations
7414 * as wide as possible.
7415 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007416 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7417 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007418
Mel Gormana5f5f912016-07-28 15:46:32 -07007419 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7420 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007421
Mel Gormana5f5f912016-07-28 15:46:32 -07007422 ret = __node_reclaim(pgdat, gfp_mask, order);
7423 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007424
Mel Gorman24cf725182009-06-16 15:33:23 -07007425 if (!ret)
7426 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7427
David Rientjesd773ed62007-10-16 23:26:01 -07007428 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007429}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007430#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007431
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007432/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007433 * check_move_unevictable_pages - check pages for evictability and move to
7434 * appropriate zone lru list
7435 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007436 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007437 * Checks pages for evictability, if an evictable page is in the unevictable
7438 * lru list, moves it to the appropriate evictable lru list. This function
7439 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007440 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007441void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007442{
Alex Shi6168d0d2020-12-15 12:34:29 -08007443 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007444 int pgscanned = 0;
7445 int pgrescued = 0;
7446 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007447
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007448 for (i = 0; i < pvec->nr; i++) {
7449 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007450 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007451
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007452 if (PageTransTail(page))
7453 continue;
7454
7455 nr_pages = thp_nr_pages(page);
7456 pgscanned += nr_pages;
7457
Alex Shid25b5bd2020-12-15 12:34:16 -08007458 /* block memcg migration during page moving between lru */
7459 if (!TestClearPageLRU(page))
7460 continue;
7461
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007462 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007463 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007464 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007465 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007466 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007467 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007468 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007469 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007470 }
Hugh Dickins24513262012-01-20 14:34:21 -08007471
Alex Shi6168d0d2020-12-15 12:34:29 -08007472 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007473 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7474 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007475 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007476 } else if (pgscanned) {
7477 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007478 }
Hugh Dickins850465792012-01-20 14:34:19 -08007479}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007480EXPORT_SYMBOL_GPL(check_move_unevictable_pages);