blob: 37e503d1bcf1d8c83fd78e7afbf0b45335a10fff [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001// SPDX-License-Identifier: GPL-2.0
Linus Torvalds1da177e2005-04-16 15:20:36 -07002/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07003 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
4 *
5 * Swap reorganised 29.12.95, Stephen Tweedie.
6 * kswapd added: 7.1.96 sct
7 * Removed kswapd_ctl limits, and swap out as many pages as needed
8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
10 * Multiqueue VM started 5.8.00, Rik van Riel.
11 */
12
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070013#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
Linus Torvalds1da177e2005-04-16 15:20:36 -070015#include <linux/mm.h>
Ingo Molnar5b3cc152017-02-02 20:43:54 +010016#include <linux/sched/mm.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070017#include <linux/module.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090018#include <linux/gfp.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070019#include <linux/kernel_stat.h>
20#include <linux/swap.h>
21#include <linux/pagemap.h>
22#include <linux/init.h>
23#include <linux/highmem.h>
Anton Vorontsov70ddf632013-04-29 15:08:31 -070024#include <linux/vmpressure.h>
Andrew Mortone129b5c2006-09-27 01:50:00 -070025#include <linux/vmstat.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070026#include <linux/file.h>
27#include <linux/writeback.h>
28#include <linux/blkdev.h>
29#include <linux/buffer_head.h> /* for try_to_release_page(),
30 buffer_heads_over_limit */
31#include <linux/mm_inline.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070032#include <linux/backing-dev.h>
33#include <linux/rmap.h>
34#include <linux/topology.h>
35#include <linux/cpu.h>
36#include <linux/cpuset.h>
Mel Gorman3e7d3442011-01-13 15:45:56 -080037#include <linux/compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070038#include <linux/notifier.h>
39#include <linux/rwsem.h>
Rafael J. Wysocki248a0302006-03-22 00:09:04 -080040#include <linux/delay.h>
Yasunori Goto3218ae12006-06-27 02:53:33 -070041#include <linux/kthread.h>
Nigel Cunningham7dfb7102006-12-06 20:34:23 -080042#include <linux/freezer.h>
Balbir Singh66e17072008-02-07 00:13:56 -080043#include <linux/memcontrol.h>
Dave Hansen26aa2d12021-09-02 14:59:16 -070044#include <linux/migrate.h>
Keika Kobayashi873b4772008-07-25 01:48:52 -070045#include <linux/delayacct.h>
Lee Schermerhornaf936a12008-10-18 20:26:53 -070046#include <linux/sysctl.h>
KOSAKI Motohiro929bea72011-04-14 15:22:12 -070047#include <linux/oom.h>
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +000048#include <linux/pagevec.h>
Linus Torvalds268bb0c2011-05-20 12:50:29 -070049#include <linux/prefetch.h>
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070050#include <linux/printk.h>
Ross Zwislerf9fe48b2016-01-22 15:10:40 -080051#include <linux/dax.h>
Johannes Weinereb414682018-10-26 15:06:27 -070052#include <linux/psi.h>
Yu Zhao7f53b0e2022-09-18 02:00:05 -060053#include <linux/pagewalk.h>
54#include <linux/shmem_fs.h>
Yu Zhaobaeb9a02022-09-18 02:00:07 -060055#include <linux/ctype.h>
Yu Zhao4983c522022-09-18 02:00:09 -060056#include <linux/debugfs.h>
Yu Zhaoa3eb6512022-12-21 21:19:04 -070057#include <linux/rculist_nulls.h>
58#include <linux/random.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070059
60#include <asm/tlbflush.h>
61#include <asm/div64.h>
62
63#include <linux/swapops.h>
Rafael Aquini117aad12013-09-30 13:45:16 -070064#include <linux/balloon_compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070065
Nick Piggin0f8053a2006-03-22 00:08:33 -080066#include "internal.h"
67
Mel Gorman33906bc2010-08-09 17:19:16 -070068#define CREATE_TRACE_POINTS
69#include <trace/events/vmscan.h>
70
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -070071#undef CREATE_TRACE_POINTS
72#include <trace/hooks/vmscan.h>
73
Minchan Kim7df45e52022-10-27 08:29:17 -070074#undef CREATE_TRACE_POINTS
75#include <trace/hooks/mm.h>
76
Tao Zeng54f845e2022-01-26 16:04:08 +080077#ifdef CONFIG_AMLOGIC_CMA
78#include <linux/amlogic/aml_cma.h>
79#endif
Jianxiong Pan07622f02022-09-22 17:25:35 +080080#ifdef CONFIG_AMLOGIC_PIN_LOCKED_FILE
81#include <linux/amlogic/pin_file.h>
82#endif
Tao Zeng54f845e2022-01-26 16:04:08 +080083
Martin Liud705ab992021-06-23 12:20:18 +080084EXPORT_TRACEPOINT_SYMBOL_GPL(mm_vmscan_direct_reclaim_begin);
85EXPORT_TRACEPOINT_SYMBOL_GPL(mm_vmscan_direct_reclaim_end);
86
Linus Torvalds1da177e2005-04-16 15:20:36 -070087struct scan_control {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -080088 /* How many pages shrink_list() should reclaim */
89 unsigned long nr_to_reclaim;
90
Johannes Weineree814fe2014-08-06 16:06:19 -070091 /*
92 * Nodemask of nodes allowed by the caller. If NULL, all nodes
93 * are scanned.
94 */
95 nodemask_t *nodemask;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -070096
KOSAKI Motohiro5f53e762010-05-24 14:32:37 -070097 /*
Johannes Weinerf16015f2012-01-12 17:17:52 -080098 * The memory cgroup that hit its limit and as a result is the
99 * primary target of this reclaim invocation.
100 */
101 struct mem_cgroup *target_mem_cgroup;
Balbir Singh66e17072008-02-07 00:13:56 -0800102
Johannes Weiner7cf111b2020-06-03 16:03:06 -0700103 /*
104 * Scan pressure balancing between anon and file LRUs
105 */
106 unsigned long anon_cost;
107 unsigned long file_cost;
108
Johannes Weinerb91ac372019-11-30 17:56:02 -0800109 /* Can active pages be deactivated as part of reclaim? */
110#define DEACTIVATE_ANON 1
111#define DEACTIVATE_FILE 2
112 unsigned int may_deactivate:2;
113 unsigned int force_deactivate:1;
114 unsigned int skipped_deactivate:1;
115
Johannes Weiner1276ad62017-02-24 14:56:11 -0800116 /* Writepage batching in laptop mode; RECLAIM_WRITE */
Johannes Weineree814fe2014-08-06 16:06:19 -0700117 unsigned int may_writepage:1;
118
119 /* Can mapped pages be reclaimed? */
120 unsigned int may_unmap:1;
121
122 /* Can pages be swapped as part of reclaim? */
123 unsigned int may_swap:1;
124
Yosry Ahmed17bdc392022-07-14 06:49:18 +0000125 /* Proactive reclaim invoked by userspace through memory.reclaim */
126 unsigned int proactive:1;
127
Yisheng Xied6622f62017-05-03 14:53:57 -0700128 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700129 * Cgroup memory below memory.low is protected as long as we
130 * don't threaten to OOM. If any cgroup is reclaimed at
131 * reduced force or passed over entirely due to its memory.low
132 * setting (memcg_low_skipped), and nothing is reclaimed as a
133 * result, then go back for one more cycle that reclaims the protected
134 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700135 */
136 unsigned int memcg_low_reclaim:1;
137 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800138
Johannes Weineree814fe2014-08-06 16:06:19 -0700139 unsigned int hibernation_mode:1;
140
141 /* One of the zones is ready for compaction */
142 unsigned int compaction_ready:1;
143
Johannes Weinerb91ac372019-11-30 17:56:02 -0800144 /* There is easily reclaimable cold cache in the current node */
145 unsigned int cache_trim_mode:1;
146
Johannes Weiner53138ce2019-11-30 17:55:56 -0800147 /* The file pages on the current node are dangerously low */
148 unsigned int file_is_tiny:1;
149
Dave Hansen26aa2d12021-09-02 14:59:16 -0700150 /* Always discard instead of demoting to lower tier memory */
151 unsigned int no_demotion:1;
152
Greg Thelenbb451fd2018-08-17 15:45:19 -0700153 /* Allocation order */
154 s8 order;
155
156 /* Scan (total_size >> priority) pages at once */
157 s8 priority;
158
159 /* The highest zone to isolate pages for reclaim from */
160 s8 reclaim_idx;
161
162 /* This context's GFP mask */
163 gfp_t gfp_mask;
164
Johannes Weineree814fe2014-08-06 16:06:19 -0700165 /* Incremented by the number of inactive pages that were scanned */
166 unsigned long nr_scanned;
167
168 /* Number of pages freed so far during a call to shrink_zones() */
169 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700170
171 struct {
172 unsigned int dirty;
173 unsigned int unqueued_dirty;
174 unsigned int congested;
175 unsigned int writeback;
176 unsigned int immediate;
177 unsigned int file_taken;
178 unsigned int taken;
179 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700180
181 /* for recording the reclaimed slab by now */
182 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700183};
184
Linus Torvalds1da177e2005-04-16 15:20:36 -0700185#ifdef ARCH_HAS_PREFETCHW
186#define prefetchw_prev_lru_page(_page, _base, _field) \
187 do { \
188 if ((_page)->lru.prev != _base) { \
189 struct page *prev; \
190 \
191 prev = lru_to_page(&(_page->lru)); \
192 prefetchw(&prev->_field); \
193 } \
194 } while (0)
195#else
196#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
197#endif
198
199/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700200 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700201 */
202int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700203
Yang Shi0a432dc2019-09-23 15:38:12 -0700204static void set_task_reclaim_state(struct task_struct *task,
205 struct reclaim_state *rs)
206{
207 /* Check for an overwrite */
208 WARN_ON_ONCE(rs && task->reclaim_state);
209
210 /* Check for the nulling of an already-nulled member */
211 WARN_ON_ONCE(!rs && !task->reclaim_state);
212
213 task->reclaim_state = rs;
214}
215
Linus Torvalds1da177e2005-04-16 15:20:36 -0700216static LIST_HEAD(shrinker_list);
217static DECLARE_RWSEM(shrinker_rwsem);
218
Yang Shi0a432dc2019-09-23 15:38:12 -0700219#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700220static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700221
Yang Shi3c6f17e2021-05-04 18:36:33 -0700222/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700223static inline int shrinker_map_size(int nr_items)
224{
225 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
226}
Yang Shi2bfd3632021-05-04 18:36:11 -0700227
Yang Shi3c6f17e2021-05-04 18:36:33 -0700228static inline int shrinker_defer_size(int nr_items)
229{
230 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
231}
232
Yang Shi468ab842021-05-04 18:36:26 -0700233static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
234 int nid)
235{
236 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
237 lockdep_is_held(&shrinker_rwsem));
238}
239
Yang Shie4262c42021-05-04 18:36:23 -0700240static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700241 int map_size, int defer_size,
242 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700243{
Yang Shie4262c42021-05-04 18:36:23 -0700244 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700245 struct mem_cgroup_per_node *pn;
246 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700247 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700248
Yang Shi2bfd3632021-05-04 18:36:11 -0700249 for_each_node(nid) {
250 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700251 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700252 /* Not yet online memcg */
253 if (!old)
254 return 0;
255
256 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
257 if (!new)
258 return -ENOMEM;
259
Yang Shi3c6f17e2021-05-04 18:36:33 -0700260 new->nr_deferred = (atomic_long_t *)(new + 1);
261 new->map = (void *)new->nr_deferred + defer_size;
262
263 /* map: set all old bits, clear all new bits */
264 memset(new->map, (int)0xff, old_map_size);
265 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
266 /* nr_deferred: copy old values, clear all new values */
267 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
268 memset((void *)new->nr_deferred + old_defer_size, 0,
269 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700270
Yang Shie4262c42021-05-04 18:36:23 -0700271 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700272 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700273 }
274
275 return 0;
276}
277
Yang Shie4262c42021-05-04 18:36:23 -0700278void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700279{
280 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700281 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700282 int nid;
283
Yang Shi2bfd3632021-05-04 18:36:11 -0700284 for_each_node(nid) {
285 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700286 info = rcu_dereference_protected(pn->shrinker_info, true);
287 kvfree(info);
288 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700289 }
290}
291
Yang Shie4262c42021-05-04 18:36:23 -0700292int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700293{
Yang Shie4262c42021-05-04 18:36:23 -0700294 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700295 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700296 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700297
Yang Shid27cf2a2021-05-04 18:36:14 -0700298 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700299 map_size = shrinker_map_size(shrinker_nr_max);
300 defer_size = shrinker_defer_size(shrinker_nr_max);
301 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700302 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700303 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
304 if (!info) {
305 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700306 ret = -ENOMEM;
307 break;
308 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700309 info->nr_deferred = (atomic_long_t *)(info + 1);
310 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700311 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700312 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700313 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700314
315 return ret;
316}
317
Yang Shi3c6f17e2021-05-04 18:36:33 -0700318static inline bool need_expand(int nr_max)
319{
320 return round_up(nr_max, BITS_PER_LONG) >
321 round_up(shrinker_nr_max, BITS_PER_LONG);
322}
323
Yang Shie4262c42021-05-04 18:36:23 -0700324static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700325{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700326 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700327 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700328 int map_size, defer_size = 0;
329 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700330 struct mem_cgroup *memcg;
331
Yang Shi3c6f17e2021-05-04 18:36:33 -0700332 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700333 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700334
Yang Shi2bfd3632021-05-04 18:36:11 -0700335 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700336 goto out;
337
338 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700339
Yang Shi3c6f17e2021-05-04 18:36:33 -0700340 map_size = shrinker_map_size(new_nr_max);
341 defer_size = shrinker_defer_size(new_nr_max);
342 old_map_size = shrinker_map_size(shrinker_nr_max);
343 old_defer_size = shrinker_defer_size(shrinker_nr_max);
344
Yang Shi2bfd3632021-05-04 18:36:11 -0700345 memcg = mem_cgroup_iter(NULL, NULL, NULL);
346 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700347 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
348 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700349 if (ret) {
350 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700351 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700352 }
353 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700354out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700355 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700356 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700357
Yang Shi2bfd3632021-05-04 18:36:11 -0700358 return ret;
359}
360
361void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
362{
363 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700364 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700365
366 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700367 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700368 /* Pairs with smp mb in shrink_slab() */
369 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700370 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700371 rcu_read_unlock();
372 }
373}
374
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700375static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700376
377static int prealloc_memcg_shrinker(struct shrinker *shrinker)
378{
379 int id, ret = -ENOMEM;
380
Yang Shi476b30a2021-05-04 18:36:39 -0700381 if (mem_cgroup_disabled())
382 return -ENOSYS;
383
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700384 down_write(&shrinker_rwsem);
385 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700386 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700387 if (id < 0)
388 goto unlock;
389
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700390 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700391 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700392 idr_remove(&shrinker_idr, id);
393 goto unlock;
394 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700395 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700396 shrinker->id = id;
397 ret = 0;
398unlock:
399 up_write(&shrinker_rwsem);
400 return ret;
401}
402
403static void unregister_memcg_shrinker(struct shrinker *shrinker)
404{
405 int id = shrinker->id;
406
407 BUG_ON(id < 0);
408
Yang Shi41ca6682021-05-04 18:36:29 -0700409 lockdep_assert_held(&shrinker_rwsem);
410
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700411 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700412}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700413
Yang Shi86750832021-05-04 18:36:36 -0700414static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
415 struct mem_cgroup *memcg)
416{
417 struct shrinker_info *info;
418
419 info = shrinker_info_protected(memcg, nid);
420 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
421}
422
423static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
424 struct mem_cgroup *memcg)
425{
426 struct shrinker_info *info;
427
428 info = shrinker_info_protected(memcg, nid);
429 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
430}
431
Yang Shia1780152021-05-04 18:36:42 -0700432void reparent_shrinker_deferred(struct mem_cgroup *memcg)
433{
434 int i, nid;
435 long nr;
436 struct mem_cgroup *parent;
437 struct shrinker_info *child_info, *parent_info;
438
439 parent = parent_mem_cgroup(memcg);
440 if (!parent)
441 parent = root_mem_cgroup;
442
443 /* Prevent from concurrent shrinker_info expand */
444 down_read(&shrinker_rwsem);
445 for_each_node(nid) {
446 child_info = shrinker_info_protected(memcg, nid);
447 parent_info = shrinker_info_protected(parent, nid);
448 for (i = 0; i < shrinker_nr_max; i++) {
449 nr = atomic_long_read(&child_info->nr_deferred[i]);
450 atomic_long_add(nr, &parent_info->nr_deferred[i]);
451 }
452 }
453 up_read(&shrinker_rwsem);
454}
455
Johannes Weinerb5ead352019-11-30 17:55:40 -0800456static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800457{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800458 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800459}
Tejun Heo97c93412015-05-22 18:23:36 -0400460
Yu Zhao4fc3ef42022-12-21 21:19:01 -0700461static bool global_reclaim(struct scan_control *sc)
462{
463 return !sc->target_mem_cgroup || mem_cgroup_is_root(sc->target_mem_cgroup);
464}
465
Tejun Heo97c93412015-05-22 18:23:36 -0400466/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800467 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400468 * @sc: scan_control in question
469 *
470 * The normal page dirty throttling mechanism in balance_dirty_pages() is
471 * completely broken with the legacy memcg and direct stalling in
472 * shrink_page_list() is used for throttling instead, which lacks all the
473 * niceties such as fairness, adaptive pausing, bandwidth proportional
474 * allocation and configurability.
475 *
476 * This function tests whether the vmscan currently in progress can assume
477 * that the normal dirty throttling mechanism is operational.
478 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800479static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400480{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800481 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400482 return true;
483#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800484 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400485 return true;
486#endif
487 return false;
488}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800489#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700490static int prealloc_memcg_shrinker(struct shrinker *shrinker)
491{
Yang Shi476b30a2021-05-04 18:36:39 -0700492 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700493}
494
495static void unregister_memcg_shrinker(struct shrinker *shrinker)
496{
497}
498
Yang Shi86750832021-05-04 18:36:36 -0700499static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
500 struct mem_cgroup *memcg)
501{
502 return 0;
503}
504
505static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
506 struct mem_cgroup *memcg)
507{
508 return 0;
509}
510
Johannes Weinerb5ead352019-11-30 17:55:40 -0800511static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800512{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800513 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800514}
Tejun Heo97c93412015-05-22 18:23:36 -0400515
Yu Zhao4fc3ef42022-12-21 21:19:01 -0700516static bool global_reclaim(struct scan_control *sc)
517{
518 return true;
519}
520
Johannes Weinerb5ead352019-11-30 17:55:40 -0800521static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400522{
523 return true;
524}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800525#endif
526
Yang Shi86750832021-05-04 18:36:36 -0700527static long xchg_nr_deferred(struct shrinker *shrinker,
528 struct shrink_control *sc)
529{
530 int nid = sc->nid;
531
532 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
533 nid = 0;
534
535 if (sc->memcg &&
536 (shrinker->flags & SHRINKER_MEMCG_AWARE))
537 return xchg_nr_deferred_memcg(nid, shrinker,
538 sc->memcg);
539
540 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
541}
542
543
544static long add_nr_deferred(long nr, struct shrinker *shrinker,
545 struct shrink_control *sc)
546{
547 int nid = sc->nid;
548
549 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
550 nid = 0;
551
552 if (sc->memcg &&
553 (shrinker->flags & SHRINKER_MEMCG_AWARE))
554 return add_nr_deferred_memcg(nr, nid, shrinker,
555 sc->memcg);
556
557 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
558}
559
Dave Hansen26aa2d12021-09-02 14:59:16 -0700560static bool can_demote(int nid, struct scan_control *sc)
561{
Huang Ying20b51af12021-09-02 14:59:33 -0700562 if (!numa_demotion_enabled)
563 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700564 if (sc) {
565 if (sc->no_demotion)
566 return false;
567 /* It is pointless to do demotion in memcg reclaim */
568 if (cgroup_reclaim(sc))
569 return false;
570 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700571 if (next_demotion_node(nid) == NUMA_NO_NODE)
572 return false;
573
Huang Ying20b51af12021-09-02 14:59:33 -0700574 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700575}
576
Keith Buscha2a36482021-09-02 14:59:26 -0700577static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
578 int nid,
579 struct scan_control *sc)
580{
581 if (memcg == NULL) {
582 /*
583 * For non-memcg reclaim, is there
584 * space in any swap device?
585 */
586 if (get_nr_swap_pages() > 0)
587 return true;
588 } else {
589 /* Is the memcg below its swap limit? */
590 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
591 return true;
592 }
593
594 /*
595 * The page can not be swapped.
596 *
597 * Can it be reclaimed from this node via demotion?
598 */
599 return can_demote(nid, sc);
600}
601
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700602/*
603 * This misses isolated pages which are not accounted for to save counters.
604 * As the data only determines if reclaim or compaction continues, it is
605 * not expected that isolated pages will be a dominating factor.
606 */
607unsigned long zone_reclaimable_pages(struct zone *zone)
608{
609 unsigned long nr;
610
611 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
612 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700613 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700614 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
615 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
616
617 return nr;
618}
619
Michal Hockofd538802017-02-22 15:45:58 -0800620/**
621 * lruvec_lru_size - Returns the number of pages on the given LRU list.
622 * @lruvec: lru vector
623 * @lru: lru to use
624 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
625 */
Yu Zhao20913392021-02-24 12:08:44 -0800626static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
627 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800628{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800629 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800630 int zid;
631
Johannes Weinerde3b0152019-11-30 17:55:31 -0800632 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800633 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800634
Michal Hockofd538802017-02-22 15:45:58 -0800635 if (!managed_zone(zone))
636 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800637
Michal Hockofd538802017-02-22 15:45:58 -0800638 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800639 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800640 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800641 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800642 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800643 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800644}
645
Linus Torvalds1da177e2005-04-16 15:20:36 -0700646/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000647 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700648 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900649int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700650{
Yang Shi476b30a2021-05-04 18:36:39 -0700651 unsigned int size;
652 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000653
Yang Shi476b30a2021-05-04 18:36:39 -0700654 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
655 err = prealloc_memcg_shrinker(shrinker);
656 if (err != -ENOSYS)
657 return err;
658
659 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
660 }
661
662 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000663 if (shrinker->flags & SHRINKER_NUMA_AWARE)
664 size *= nr_node_ids;
665
666 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
667 if (!shrinker->nr_deferred)
668 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700669
Tetsuo Handa8e049442018-04-04 19:53:07 +0900670 return 0;
671}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000672
Tetsuo Handa8e049442018-04-04 19:53:07 +0900673void free_prealloced_shrinker(struct shrinker *shrinker)
674{
Yang Shi41ca6682021-05-04 18:36:29 -0700675 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
676 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700677 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700678 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700679 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700680 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700681
Tetsuo Handa8e049442018-04-04 19:53:07 +0900682 kfree(shrinker->nr_deferred);
683 shrinker->nr_deferred = NULL;
684}
685
686void register_shrinker_prepared(struct shrinker *shrinker)
687{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700688 down_write(&shrinker_rwsem);
689 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700690 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700691 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900692}
693
694int register_shrinker(struct shrinker *shrinker)
695{
696 int err = prealloc_shrinker(shrinker);
697
698 if (err)
699 return err;
700 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000701 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700702}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700703EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700704
705/*
706 * Remove one
707 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700708void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700709{
Yang Shi41ca6682021-05-04 18:36:29 -0700710 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900711 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700712
Linus Torvalds1da177e2005-04-16 15:20:36 -0700713 down_write(&shrinker_rwsem);
714 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700715 shrinker->flags &= ~SHRINKER_REGISTERED;
716 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
717 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700718 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700719
Andrew Vaginae393322013-10-16 13:46:46 -0700720 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900721 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700722}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700723EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700724
725#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000726
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800727static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800728 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700729{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000730 unsigned long freed = 0;
731 unsigned long long delta;
732 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700733 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000734 long nr;
735 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000736 long batch_size = shrinker->batch ? shrinker->batch
737 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800738 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000739
rongqianfeng8da6ee32021-05-21 10:30:14 +0800740 trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
741
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700742 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700743 if (freeable == 0 || freeable == SHRINK_EMPTY)
744 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000745
746 /*
747 * copy the current shrinker scan count into a local variable
748 * and zero it so that other concurrent shrinker invocations
749 * don't also do this scanning work.
750 */
Yang Shi86750832021-05-04 18:36:36 -0700751 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000752
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700753 if (shrinker->seeks) {
754 delta = freeable >> priority;
755 delta *= 4;
756 do_div(delta, shrinker->seeks);
757 } else {
758 /*
759 * These objects don't require any IO to create. Trim
760 * them aggressively under memory pressure to keep
761 * them from causing refetches in the IO caches.
762 */
763 delta = freeable / 2;
764 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700765
Yang Shi18bb4732021-05-04 18:36:45 -0700766 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000767 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700768 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000769
770 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800771 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000772
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800773 /*
774 * Normally, we should not scan less than batch_size objects in one
775 * pass to avoid too frequent shrinker calls, but if the slab has less
776 * than batch_size objects in total and we are really tight on memory,
777 * we will try to reclaim all available objects, otherwise we can end
778 * up failing allocations although there are plenty of reclaimable
779 * objects spread over several slabs with usage less than the
780 * batch_size.
781 *
782 * We detect the "tight on memory" situations by looking at the total
783 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700784 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800785 * scanning at high prio and therefore should try to reclaim as much as
786 * possible.
787 */
788 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700789 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000790 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800791 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000792
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800793 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700794 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000795 ret = shrinker->scan_objects(shrinker, shrinkctl);
796 if (ret == SHRINK_STOP)
797 break;
798 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000799
Chris Wilsond460acb2017-09-06 16:19:26 -0700800 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
801 total_scan -= shrinkctl->nr_scanned;
802 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000803
804 cond_resched();
805 }
806
Yang Shi18bb4732021-05-04 18:36:45 -0700807 /*
808 * The deferred work is increased by any new work (delta) that wasn't
809 * done, decreased by old deferred work that was done now.
810 *
811 * And it is capped to two times of the freeable items.
812 */
813 next_deferred = max_t(long, (nr + delta - scanned), 0);
814 next_deferred = min(next_deferred, (2 * freeable));
815
Glauber Costa1d3d4432013-08-28 10:18:04 +1000816 /*
817 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700818 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000819 */
Yang Shi86750832021-05-04 18:36:36 -0700820 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000821
Yang Shi8efb4b52021-05-04 18:36:08 -0700822 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000823 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700824}
825
Yang Shi0a432dc2019-09-23 15:38:12 -0700826#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700827static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
828 struct mem_cgroup *memcg, int priority)
829{
Yang Shie4262c42021-05-04 18:36:23 -0700830 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700831 unsigned long ret, freed = 0;
832 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700833
Yang Shi0a432dc2019-09-23 15:38:12 -0700834 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700835 return 0;
836
837 if (!down_read_trylock(&shrinker_rwsem))
838 return 0;
839
Yang Shi468ab842021-05-04 18:36:26 -0700840 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700841 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700842 goto unlock;
843
Yang Shie4262c42021-05-04 18:36:23 -0700844 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700845 struct shrink_control sc = {
846 .gfp_mask = gfp_mask,
847 .nid = nid,
848 .memcg = memcg,
849 };
850 struct shrinker *shrinker;
851
852 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700853 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700854 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700855 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700856 continue;
857 }
858
Yang Shi0a432dc2019-09-23 15:38:12 -0700859 /* Call non-slab shrinkers even though kmem is disabled */
860 if (!memcg_kmem_enabled() &&
861 !(shrinker->flags & SHRINKER_NONSLAB))
862 continue;
863
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700864 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700865 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700866 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700867 /*
868 * After the shrinker reported that it had no objects to
869 * free, but before we cleared the corresponding bit in
870 * the memcg shrinker map, a new object might have been
871 * added. To make sure, we have the bit set in this
872 * case, we invoke the shrinker one more time and reset
873 * the bit if it reports that it is not empty anymore.
874 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700875 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700876 *
877 * list_lru_add() shrink_slab_memcg()
878 * list_add_tail() clear_bit()
879 * <MB> <MB>
880 * set_bit() do_shrink_slab()
881 */
882 smp_mb__after_atomic();
883 ret = do_shrink_slab(&sc, shrinker, priority);
884 if (ret == SHRINK_EMPTY)
885 ret = 0;
886 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700887 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700888 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700889 freed += ret;
890
891 if (rwsem_is_contended(&shrinker_rwsem)) {
892 freed = freed ? : 1;
893 break;
894 }
895 }
896unlock:
897 up_read(&shrinker_rwsem);
898 return freed;
899}
Yang Shi0a432dc2019-09-23 15:38:12 -0700900#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700901static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
902 struct mem_cgroup *memcg, int priority)
903{
904 return 0;
905}
Yang Shi0a432dc2019-09-23 15:38:12 -0700906#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700907
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800908/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800909 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800910 * @gfp_mask: allocation context
911 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800912 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800913 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700914 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800915 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700916 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800917 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
918 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700919 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700920 * @memcg specifies the memory cgroup to target. Unaware shrinkers
921 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800922 *
Josef Bacik9092c712018-01-31 16:16:26 -0800923 * @priority is sc->priority, we take the number of objects and >> by priority
924 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700925 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800926 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700927 */
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800928unsigned long shrink_slab(gfp_t gfp_mask, int nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800929 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800930 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700931{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700932 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700933 struct shrinker *shrinker;
wudean842c68a2021-04-27 17:40:41 +0800934 bool bypass = false;
935
936 trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
937 if (bypass)
938 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700939
Yang Shifa1e5122019-08-02 21:48:44 -0700940 /*
941 * The root memcg might be allocated even though memcg is disabled
942 * via "cgroup_disable=memory" boot parameter. This could make
943 * mem_cgroup_is_root() return false, then just run memcg slab
944 * shrink, but skip global shrink. This may result in premature
945 * oom.
946 */
947 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700948 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800949
Tetsuo Handae830c632018-04-05 16:23:35 -0700950 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700951 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700952
953 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800954 struct shrink_control sc = {
955 .gfp_mask = gfp_mask,
956 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800957 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800958 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800959
Kirill Tkhai9b996462018-08-17 15:48:21 -0700960 ret = do_shrink_slab(&sc, shrinker, priority);
961 if (ret == SHRINK_EMPTY)
962 ret = 0;
963 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800964 /*
965 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700966 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800967 * by parallel ongoing shrinking.
968 */
969 if (rwsem_is_contended(&shrinker_rwsem)) {
970 freed = freed ? : 1;
971 break;
972 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700973 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800974
Linus Torvalds1da177e2005-04-16 15:20:36 -0700975 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700976out:
977 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000978 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700979}
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800980EXPORT_SYMBOL_GPL(shrink_slab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700981
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800982void drop_slab_node(int nid)
983{
984 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700985 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800986
987 do {
988 struct mem_cgroup *memcg = NULL;
989
Chunxin Zang069c4112020-10-13 16:56:46 -0700990 if (fatal_signal_pending(current))
991 return;
992
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800993 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700994 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800995 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800996 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800997 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700998 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800999}
1000
1001void drop_slab(void)
1002{
1003 int nid;
1004
1005 for_each_online_node(nid)
1006 drop_slab_node(nid);
1007}
1008
Linus Torvalds1da177e2005-04-16 15:20:36 -07001009static inline int is_page_cache_freeable(struct page *page)
1010{
Johannes Weinerceddc3a2009-09-21 17:03:00 -07001011 /*
1012 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -04001013 * that isolated the page, the page cache and optional buffer
1014 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -07001015 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -07001016 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -04001017 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001018}
1019
Yang Shicb165562019-11-30 17:55:28 -08001020static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001021{
Christoph Lameter930d9152006-01-08 01:00:47 -08001022 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001023 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001024 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001025 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001026 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001027 return 1;
1028 return 0;
1029}
1030
1031/*
1032 * We detected a synchronous write error writing a page out. Probably
1033 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1034 * fsync(), msync() or close().
1035 *
1036 * The tricky part is that after writepage we cannot touch the mapping: nothing
1037 * prevents it from being freed up. But we have a ref on the page and once
1038 * that page is locked, the mapping is pinned.
1039 *
1040 * We're allowed to run sleeping lock_page() here because we know the caller has
1041 * __GFP_FS.
1042 */
1043static void handle_write_error(struct address_space *mapping,
1044 struct page *page, int error)
1045{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001046 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001047 if (page_mapping(page) == mapping)
1048 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001049 unlock_page(page);
1050}
1051
Christoph Lameter04e62a22006-06-23 02:03:38 -07001052/* possible outcome of pageout() */
1053typedef enum {
1054 /* failed to write page out, page is locked */
1055 PAGE_KEEP,
1056 /* move page to the active list, page is locked */
1057 PAGE_ACTIVATE,
1058 /* page has been sent to the disk successfully, page is unlocked */
1059 PAGE_SUCCESS,
1060 /* page is clean and locked */
1061 PAGE_CLEAN,
1062} pageout_t;
1063
Linus Torvalds1da177e2005-04-16 15:20:36 -07001064/*
Andrew Morton1742f192006-03-22 00:08:21 -08001065 * pageout is called by shrink_page_list() for each dirty page.
1066 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001067 */
Yang Shicb165562019-11-30 17:55:28 -08001068static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001069{
1070 /*
1071 * If the page is dirty, only perform writeback if that write
1072 * will be non-blocking. To prevent this allocation from being
1073 * stalled by pagecache activity. But note that there may be
1074 * stalls if we need to run get_block(). We could test
1075 * PagePrivate for that.
1076 *
Al Viro81742022014-04-03 03:17:43 -04001077 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001078 * this page's queue, we can perform writeback even if that
1079 * will block.
1080 *
1081 * If the page is swapcache, write it back even if that would
1082 * block, for some throttling. This happens by accident, because
1083 * swap_backing_dev_info is bust: it doesn't reflect the
1084 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001085 */
1086 if (!is_page_cache_freeable(page))
1087 return PAGE_KEEP;
1088 if (!mapping) {
1089 /*
1090 * Some data journaling orphaned pages can have
1091 * page->mapping == NULL while being dirty with clean buffers.
1092 */
David Howells266cf652009-04-03 16:42:36 +01001093 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001094 if (try_to_free_buffers(page)) {
1095 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001096 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001097 return PAGE_CLEAN;
1098 }
1099 }
1100 return PAGE_KEEP;
1101 }
1102 if (mapping->a_ops->writepage == NULL)
1103 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001104 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001105 return PAGE_KEEP;
1106
1107 if (clear_page_dirty_for_io(page)) {
1108 int res;
1109 struct writeback_control wbc = {
1110 .sync_mode = WB_SYNC_NONE,
1111 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001112 .range_start = 0,
1113 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001114 .for_reclaim = 1,
1115 };
1116
1117 SetPageReclaim(page);
1118 res = mapping->a_ops->writepage(page, &wbc);
1119 if (res < 0)
1120 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001121 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001122 ClearPageReclaim(page);
1123 return PAGE_ACTIVATE;
1124 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001125
Linus Torvalds1da177e2005-04-16 15:20:36 -07001126 if (!PageWriteback(page)) {
1127 /* synchronous write or broken a_ops? */
1128 ClearPageReclaim(page);
1129 }
yalin wang3aa23852016-01-14 15:18:30 -08001130 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001131 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001132 return PAGE_SUCCESS;
1133 }
1134
1135 return PAGE_CLEAN;
1136}
1137
Andrew Mortona649fd92006-10-17 00:09:36 -07001138/*
Nick Piggine2867812008-07-25 19:45:30 -07001139 * Same as remove_mapping, but if the page is removed from the mapping, it
1140 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001141 */
Johannes Weinera5289102014-04-03 14:47:51 -07001142static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001143 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001144{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001145 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001146 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001147
Nick Piggin28e4d962006-09-25 23:31:23 -07001148 BUG_ON(!PageLocked(page));
1149 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001150
Johannes Weiner30472502021-09-02 14:53:18 -07001151 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001152 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001153 * The non racy check for a busy page.
1154 *
1155 * Must be careful with the order of the tests. When someone has
1156 * a ref to the page, it may be possible that they dirty it then
1157 * drop the reference. So if PageDirty is tested before page_count
1158 * here, then the following race may occur:
1159 *
1160 * get_user_pages(&page);
1161 * [user mapping goes away]
1162 * write_to(page);
1163 * !PageDirty(page) [good]
1164 * SetPageDirty(page);
1165 * put_page(page);
1166 * !page_count(page) [good, discard it]
1167 *
1168 * [oops, our write_to data is lost]
1169 *
1170 * Reversing the order of the tests ensures such a situation cannot
1171 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001172 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001173 *
1174 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001175 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001176 */
William Kucharski906d2782019-10-18 20:20:33 -07001177 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001178 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001179 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001180 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001181 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001182 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001183 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001184 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001185
1186 if (PageSwapCache(page)) {
1187 swp_entry_t swap = { .val = page_private(page) };
Yu Zhao37397872022-09-18 02:00:03 -06001188
1189 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001190 if (reclaimed && !mapping_exiting(mapping))
1191 shadow = workingset_eviction(page, target_memcg);
Yu Zhao37397872022-09-18 02:00:03 -06001192 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001193 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001194 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001195 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001196 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001197 void (*freepage)(struct page *);
1198
1199 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001200 /*
1201 * Remember a shadow entry for reclaimed file cache in
1202 * order to detect refaults, thus thrashing, later on.
1203 *
1204 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001205 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001206 * inode reclaim needs to empty out the radix tree or
1207 * the nodes are lost. Don't plant shadows behind its
1208 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001209 *
1210 * We also don't store shadows for DAX mappings because the
1211 * only page cache pages found in these are zero pages
1212 * covering holes, and because we don't want to mix DAX
1213 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001214 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001215 */
Huang Ying9de4f222020-04-06 20:04:41 -07001216 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001217 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001218 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001219 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001220 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001221
1222 if (freepage != NULL)
1223 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001224 }
1225
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001226 return 1;
1227
1228cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001229 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001230 return 0;
1231}
1232
Linus Torvalds1da177e2005-04-16 15:20:36 -07001233/*
Nick Piggine2867812008-07-25 19:45:30 -07001234 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1235 * someone else has a ref on the page, abort and return 0. If it was
1236 * successfully detached, return 1. Assumes the caller has a single ref on
1237 * this page.
1238 */
1239int remove_mapping(struct address_space *mapping, struct page *page)
1240{
Johannes Weinerb9107182019-11-30 17:55:59 -08001241 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001242 /*
1243 * Unfreezing the refcount with 1 rather than 2 effectively
1244 * drops the pagecache ref for us without requiring another
1245 * atomic operation.
1246 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001247 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001248 return 1;
1249 }
1250 return 0;
1251}
1252
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001253/**
1254 * putback_lru_page - put previously isolated page onto appropriate LRU list
1255 * @page: page to be put back to appropriate lru list
1256 *
1257 * Add previously isolated @page to appropriate LRU list.
1258 * Page may still be unevictable for other reasons.
1259 *
1260 * lru_lock must not be held, interrupts must be enabled.
1261 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001262void putback_lru_page(struct page *page)
1263{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001264 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001265 put_page(page); /* drop ref from isolate */
1266}
1267
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001268enum page_references {
1269 PAGEREF_RECLAIM,
1270 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001271 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001272 PAGEREF_ACTIVATE,
1273};
1274
1275static enum page_references page_check_references(struct page *page,
1276 struct scan_control *sc)
1277{
Johannes Weiner645747462010-03-05 13:42:22 -08001278 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001279 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001280
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001281 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1282 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001283 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001284
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001285 /*
1286 * Mlock lost the isolation race with us. Let try_to_unmap()
1287 * move the page to the unevictable list.
1288 */
1289 if (vm_flags & VM_LOCKED)
1290 return PAGEREF_RECLAIM;
1291
Minchan Kimf74aca72022-05-19 14:08:54 -07001292 /* rmap lock contention: rotate */
1293 if (referenced_ptes == -1)
1294 return PAGEREF_KEEP;
1295
Johannes Weiner645747462010-03-05 13:42:22 -08001296 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001297 /*
1298 * All mapped pages start out with page table
1299 * references from the instantiating fault, so we need
1300 * to look twice if a mapped file page is used more
1301 * than once.
1302 *
1303 * Mark it and spare it for another trip around the
1304 * inactive list. Another page table reference will
1305 * lead to its activation.
1306 *
1307 * Note: the mark is set for activated pages as well
1308 * so that recently deactivated but used pages are
1309 * quickly recovered.
1310 */
1311 SetPageReferenced(page);
1312
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001313 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001314 return PAGEREF_ACTIVATE;
1315
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001316 /*
1317 * Activate file-backed executable pages after first usage.
1318 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001319 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001320 return PAGEREF_ACTIVATE;
1321
Johannes Weiner645747462010-03-05 13:42:22 -08001322 return PAGEREF_KEEP;
1323 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001324
1325 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001326 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001327 return PAGEREF_RECLAIM_CLEAN;
1328
1329 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001330}
1331
Mel Gormane2be15f2013-07-03 15:01:57 -07001332/* Check if a page is dirty or under writeback */
1333static void page_check_dirty_writeback(struct page *page,
1334 bool *dirty, bool *writeback)
1335{
Mel Gormanb4597222013-07-03 15:02:05 -07001336 struct address_space *mapping;
1337
Mel Gormane2be15f2013-07-03 15:01:57 -07001338 /*
1339 * Anonymous pages are not handled by flushers and must be written
1340 * from reclaim context. Do not stall reclaim based on them
1341 */
Huang Ying9de4f222020-04-06 20:04:41 -07001342 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001343 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001344 *dirty = false;
1345 *writeback = false;
1346 return;
1347 }
1348
1349 /* By default assume that the page flags are accurate */
1350 *dirty = PageDirty(page);
1351 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001352
1353 /* Verify dirty/writeback state if the filesystem supports it */
1354 if (!page_has_private(page))
1355 return;
1356
1357 mapping = page_mapping(page);
1358 if (mapping && mapping->a_ops->is_dirty_writeback)
1359 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001360}
1361
Dave Hansen26aa2d12021-09-02 14:59:16 -07001362static struct page *alloc_demote_page(struct page *page, unsigned long node)
1363{
1364 struct migration_target_control mtc = {
1365 /*
1366 * Allocate from 'node', or fail quickly and quietly.
1367 * When this happens, 'page' will likely just be discarded
1368 * instead of migrated.
1369 */
1370 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1371 __GFP_THISNODE | __GFP_NOWARN |
1372 __GFP_NOMEMALLOC | GFP_NOWAIT,
1373 .nid = node
1374 };
1375
1376 return alloc_migration_target(page, (unsigned long)&mtc);
1377}
1378
1379/*
1380 * Take pages on @demote_list and attempt to demote them to
1381 * another node. Pages which are not demoted are left on
1382 * @demote_pages.
1383 */
1384static unsigned int demote_page_list(struct list_head *demote_pages,
1385 struct pglist_data *pgdat)
1386{
1387 int target_nid = next_demotion_node(pgdat->node_id);
1388 unsigned int nr_succeeded;
1389 int err;
1390
1391 if (list_empty(demote_pages))
1392 return 0;
1393
1394 if (target_nid == NUMA_NO_NODE)
1395 return 0;
1396
1397 /* Demotion ignores all cpuset and mempolicy settings */
1398 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1399 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1400 &nr_succeeded);
1401
Yang Shi668e4142021-09-02 14:59:19 -07001402 if (current_is_kswapd())
1403 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1404 else
1405 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1406
Dave Hansen26aa2d12021-09-02 14:59:16 -07001407 return nr_succeeded;
1408}
1409
Jianxiong Pan710268f2022-02-24 19:30:46 +08001410#ifdef CONFIG_AMLOGIC_SWAPD_OPT
1411static int can_unmap_files(struct scan_control *sc, struct page *page)
1412{
1413 if (!current_is_kswapd())
1414 return 1;
1415 if (page_mapcount(page) > 1)
1416 return 0;
1417 return 1;
1418}
1419#endif
1420
Nick Piggine2867812008-07-25 19:45:30 -07001421/*
Andrew Morton1742f192006-03-22 00:08:21 -08001422 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001423 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001424static unsigned int shrink_page_list(struct list_head *page_list,
1425 struct pglist_data *pgdat,
1426 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001427 struct reclaim_stat *stat,
1428 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001429{
1430 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001431 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001432 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001433 unsigned int nr_reclaimed = 0;
1434 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001435 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001436
Kirill Tkhai060f0052019-03-05 15:48:15 -08001437 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001438 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001439 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001440
Dave Hansen26aa2d12021-09-02 14:59:16 -07001441retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001442 while (!list_empty(page_list)) {
1443 struct address_space *mapping;
1444 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001445 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001446 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001447 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001448
1449 cond_resched();
1450
1451 page = lru_to_page(page_list);
1452 list_del(&page->lru);
1453
Nick Piggin529ae9a2008-08-02 12:01:03 +02001454 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001455 goto keep;
1456
Sasha Levin309381fea2014-01-23 15:52:54 -08001457 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001458
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001459 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001460
1461 /* Account the number of base pages even though THP */
1462 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001463
Hugh Dickins39b5f292012-10-08 16:33:18 -07001464 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001465 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001466
Jianxiong Pan710268f2022-02-24 19:30:46 +08001467 #ifdef CONFIG_AMLOGIC_SWAPD_OPT
1468 if (!can_unmap_files(sc, page))
1469 #else
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001470 if (!sc->may_unmap && page_mapped(page))
Jianxiong Pan710268f2022-02-24 19:30:46 +08001471 #endif
Christoph Lameter80e43422006-02-11 17:55:53 -08001472 goto keep_locked;
1473
Yu Zhao0182f922022-09-18 02:00:04 -06001474 /* page_update_gen() tried to promote this page? */
1475 if (lru_gen_enabled() && !ignore_references &&
1476 page_mapped(page) && PageReferenced(page))
1477 goto keep_locked;
1478
Andy Whitcroftc661b072007-08-22 14:01:26 -07001479 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1480 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1481
Mel Gorman283aba92013-07-03 15:01:51 -07001482 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001483 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001484 * reclaim_congested which affects wait_iff_congested. kswapd
1485 * will stall and start writing pages if the tail of the LRU
1486 * is all dirty unqueued pages.
1487 */
1488 page_check_dirty_writeback(page, &dirty, &writeback);
1489 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001490 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001491
1492 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001493 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001494
Mel Gormand04e8ac2013-07-03 15:02:03 -07001495 /*
1496 * Treat this page as congested if the underlying BDI is or if
1497 * pages are cycling through the LRU so quickly that the
1498 * pages marked for immediate reclaim are making it to the
1499 * end of the LRU a second time.
1500 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001501 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001502 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001503 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001504 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001505 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001506
1507 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001508 * If a page at the tail of the LRU is under writeback, there
1509 * are three cases to consider.
1510 *
1511 * 1) If reclaim is encountering an excessive number of pages
1512 * under writeback and this page is both under writeback and
1513 * PageReclaim then it indicates that pages are being queued
1514 * for IO but are being recycled through the LRU before the
1515 * IO can complete. Waiting on the page itself risks an
1516 * indefinite stall if it is impossible to writeback the
1517 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001518 * note that the LRU is being scanned too quickly and the
1519 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001520 *
Tejun Heo97c93412015-05-22 18:23:36 -04001521 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001522 * not marked for immediate reclaim, or the caller does not
1523 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1524 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001525 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001526 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001527 * Require may_enter_fs because we would wait on fs, which
1528 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001529 * enter reclaim, and deadlock if it waits on a page for
1530 * which it is needed to do the write (loop masks off
1531 * __GFP_IO|__GFP_FS for this reason); but more thought
1532 * would probably show more reasons.
1533 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001534 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001535 * PageReclaim. memcg does not have any dirty pages
1536 * throttling so we could easily OOM just because too many
1537 * pages are in writeback and there is nothing else to
1538 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001539 *
1540 * In cases 1) and 2) we activate the pages to get them out of
1541 * the way while we continue scanning for clean pages on the
1542 * inactive list and refilling from the active list. The
1543 * observation here is that waiting for disk writes is more
1544 * expensive than potentially causing reloads down the line.
1545 * Since they're marked for immediate reclaim, they won't put
1546 * memory pressure on the cache working set any longer than it
1547 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001548 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001549 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001550 /* Case 1 above */
1551 if (current_is_kswapd() &&
1552 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001553 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001554 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001555 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001556
1557 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001558 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001559 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001560 /*
1561 * This is slightly racy - end_page_writeback()
1562 * might have just cleared PageReclaim, then
1563 * setting PageReclaim here end up interpreted
1564 * as PageReadahead - but that does not matter
1565 * enough to care. What we do want is for this
1566 * page to have PageReclaim set next time memcg
1567 * reclaim reaches the tests above, so it will
1568 * then wait_on_page_writeback() to avoid OOM;
1569 * and it's also appropriate in global reclaim.
1570 */
1571 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001572 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001573 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001574
1575 /* Case 3 above */
1576 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001577 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001578 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001579 /* then go back and try same page again */
1580 list_add_tail(&page->lru, page_list);
1581 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001582 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001583 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001584
Minchan Kim8940b342019-09-25 16:49:11 -07001585 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001586 references = page_check_references(page, sc);
1587
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001588 switch (references) {
1589 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001590 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001591 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001592 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001593 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001594 case PAGEREF_RECLAIM:
1595 case PAGEREF_RECLAIM_CLEAN:
1596 ; /* try to reclaim the page below */
1597 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001598
Linus Torvalds1da177e2005-04-16 15:20:36 -07001599 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001600 * Before reclaiming the page, try to relocate
1601 * its contents to another node.
1602 */
1603 if (do_demote_pass &&
1604 (thp_migration_supported() || !PageTransHuge(page))) {
1605 list_add(&page->lru, &demote_pages);
1606 unlock_page(page);
1607 continue;
1608 }
1609
1610 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001611 * Anonymous process memory has backing store?
1612 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001613 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001614 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001615 if (PageAnon(page) && PageSwapBacked(page)) {
1616 if (!PageSwapCache(page)) {
1617 if (!(sc->gfp_mask & __GFP_IO))
1618 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001619 if (page_maybe_dma_pinned(page))
1620 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001621 if (PageTransHuge(page)) {
1622 /* cannot split THP, skip it */
1623 if (!can_split_huge_page(page, NULL))
1624 goto activate_locked;
1625 /*
1626 * Split pages without a PMD map right
1627 * away. Chances are some or all of the
1628 * tail pages can be freed without IO.
1629 */
1630 if (!compound_mapcount(page) &&
1631 split_huge_page_to_list(page,
1632 page_list))
1633 goto activate_locked;
1634 }
1635 if (!add_to_swap(page)) {
1636 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001637 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001638 /* Fallback to swap normal pages */
1639 if (split_huge_page_to_list(page,
1640 page_list))
1641 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001642#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1643 count_vm_event(THP_SWPOUT_FALLBACK);
1644#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001645 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001646 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001647 }
Minchan Kim0f074652017-07-06 15:37:24 -07001648
Kirill Tkhai4b793062020-04-01 21:10:18 -07001649 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001650
1651 /* Adding to swap updated mapping */
1652 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001653 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001654 } else if (unlikely(PageTransHuge(page))) {
1655 /* Split file THP */
1656 if (split_huge_page_to_list(page, page_list))
1657 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001658 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001659
1660 /*
Yang Shi98879b32019-07-11 20:59:30 -07001661 * THP may get split above, need minus tail pages and update
1662 * nr_pages to avoid accounting tail pages twice.
1663 *
1664 * The tail pages that are added into swap cache successfully
1665 * reach here.
1666 */
1667 if ((nr_pages > 1) && !PageTransHuge(page)) {
1668 sc->nr_scanned -= (nr_pages - 1);
1669 nr_pages = 1;
1670 }
1671
1672 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001673 * The page is mapped into the page tables of one or more
1674 * processes. Try to unmap it here.
1675 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001676 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001677 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001678 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001679
Jianxiong Pan07622f02022-09-22 17:25:35 +08001680#ifdef CONFIG_AMLOGIC_PIN_LOCKED_FILE
1681 if (mapping &&
1682 test_bit(AS_LOCK_MAPPING, &mapping->flags) &&
1683 !aml_is_pin_locked_file(page) &&
1684 !PageMlocked(page))
1685 flags |= TTU_IGNORE_MLOCK;
1686#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001687 if (unlikely(PageTransHuge(page)))
1688 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001689
Yang Shi1fb08ac2021-06-30 18:52:01 -07001690 try_to_unmap(page, flags);
1691 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001692 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001693 if (!was_swapbacked && PageSwapBacked(page))
1694 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001695 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001696 }
1697 }
1698
1699 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001700 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001701 * Only kswapd can writeback filesystem pages
1702 * to avoid risk of stack overflow. But avoid
1703 * injecting inefficient single-page IO into
1704 * flusher writeback as much as possible: only
1705 * write pages when we've encountered many
1706 * dirty pages, and when we've already scanned
1707 * the rest of the LRU for clean pages and see
1708 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001709 */
Huang Ying9de4f222020-04-06 20:04:41 -07001710 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001711 (!current_is_kswapd() || !PageReclaim(page) ||
1712 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001713 /*
1714 * Immediately reclaim when written back.
1715 * Similar in principal to deactivate_page()
1716 * except we already have the page isolated
1717 * and know it's dirty
1718 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001719 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001720 SetPageReclaim(page);
1721
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001722 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001723 }
1724
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001725 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001726 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001727 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001728 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001729 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001730 goto keep_locked;
1731
Mel Gormand950c942015-09-04 15:47:35 -07001732 /*
1733 * Page is dirty. Flush the TLB if a writable entry
1734 * potentially exists to avoid CPU writes after IO
1735 * starts and then write it out here.
1736 */
1737 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001738 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001739 case PAGE_KEEP:
1740 goto keep_locked;
1741 case PAGE_ACTIVATE:
1742 goto activate_locked;
1743 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001744 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001745
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001746 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001747 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001748 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001749 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001750
Linus Torvalds1da177e2005-04-16 15:20:36 -07001751 /*
1752 * A synchronous write - probably a ramdisk. Go
1753 * ahead and try to reclaim the page.
1754 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001755 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001756 goto keep;
1757 if (PageDirty(page) || PageWriteback(page))
1758 goto keep_locked;
1759 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001760 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001761 case PAGE_CLEAN:
1762 ; /* try to free the page below */
1763 }
1764 }
1765
1766 /*
1767 * If the page has buffers, try to free the buffer mappings
1768 * associated with this page. If we succeed we try to free
1769 * the page as well.
1770 *
1771 * We do this even if the page is PageDirty().
1772 * try_to_release_page() does not perform I/O, but it is
1773 * possible for a page to have PageDirty set, but it is actually
1774 * clean (all its buffers are clean). This happens if the
1775 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001776 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001777 * try_to_release_page() will discover that cleanness and will
1778 * drop the buffers and mark the page clean - it can be freed.
1779 *
1780 * Rarely, pages can have buffers and no ->mapping. These are
1781 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001782 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001783 * and if that worked, and the page is no longer mapped into
1784 * process address space (page_count == 1) it can be freed.
1785 * Otherwise, leave the page on the LRU so it is swappable.
1786 */
David Howells266cf652009-04-03 16:42:36 +01001787 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001788 if (!try_to_release_page(page, sc->gfp_mask))
1789 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001790 if (!mapping && page_count(page) == 1) {
1791 unlock_page(page);
1792 if (put_page_testzero(page))
1793 goto free_it;
1794 else {
1795 /*
1796 * rare race with speculative reference.
1797 * the speculative reference will free
1798 * this page shortly, so we may
1799 * increment nr_reclaimed here (and
1800 * leave it off the LRU).
1801 */
1802 nr_reclaimed++;
1803 continue;
1804 }
1805 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001806 }
1807
Shaohua Li802a3a92017-05-03 14:52:32 -07001808 if (PageAnon(page) && !PageSwapBacked(page)) {
1809 /* follow __remove_mapping for reference */
1810 if (!page_ref_freeze(page, 1))
1811 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001812 /*
1813 * The page has only one reference left, which is
1814 * from the isolation. After the caller puts the
1815 * page back on lru and drops the reference, the
1816 * page will be freed anyway. It doesn't matter
1817 * which lru it goes. So we don't bother checking
1818 * PageDirty here.
1819 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001820 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001821 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001822 } else if (!mapping || !__remove_mapping(mapping, page, true,
1823 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001824 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001825
1826 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001827free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001828 /*
1829 * THP may get swapped out in a whole, need account
1830 * all base pages.
1831 */
1832 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001833
1834 /*
1835 * Is there need to periodically free_page_list? It would
1836 * appear not as the counts should be low
1837 */
Yang Shi7ae88532019-09-23 15:38:09 -07001838 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001839 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001840 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001841 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001842 continue;
1843
Yang Shi98879b32019-07-11 20:59:30 -07001844activate_locked_split:
1845 /*
1846 * The tail pages that are failed to add into swap cache
1847 * reach here. Fixup nr_scanned and nr_pages.
1848 */
1849 if (nr_pages > 1) {
1850 sc->nr_scanned -= (nr_pages - 1);
1851 nr_pages = 1;
1852 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001853activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001854 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001855 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1856 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001857 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001858 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001859 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001860 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001861 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001862 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001863 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001864 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001865keep_locked:
1866 unlock_page(page);
1867keep:
1868 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001869 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001870 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001871 /* 'page_list' is always empty here */
1872
1873 /* Migrate pages selected for demotion */
1874 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1875 /* Pages that could not be demoted are still in @demote_pages */
1876 if (!list_empty(&demote_pages)) {
1877 /* Pages which failed to demoted go back on @page_list for retry: */
1878 list_splice_init(&demote_pages, page_list);
1879 do_demote_pass = false;
1880 goto retry;
1881 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001882
Yang Shi98879b32019-07-11 20:59:30 -07001883 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1884
Johannes Weiner747db952014-08-08 14:19:24 -07001885 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001886 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001887 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001888
Linus Torvalds1da177e2005-04-16 15:20:36 -07001889 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001890 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001891
Andrew Morton05ff5132006-03-22 00:08:20 -08001892 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001893}
1894
Maninder Singh730ec8c2020-06-03 16:01:18 -07001895unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001896 struct list_head *page_list)
1897{
1898 struct scan_control sc = {
1899 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001900 .may_unmap = 1,
1901 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001902 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001903 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001904 struct page *page, *next;
1905 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001906 unsigned int noreclaim_flag;
Tao Zeng54f845e2022-01-26 16:04:08 +08001907#ifdef CONFIG_AMLOGIC_CMA
1908 LIST_HEAD(high_active_pages);
1909#endif
Minchan Kim02c6de82012-10-08 16:31:55 -07001910
1911 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001912 if (!PageHuge(page) && page_is_file_lru(page) &&
1913 !PageDirty(page) && !__PageMovable(page) &&
1914 !PageUnevictable(page)) {
Tao Zeng54f845e2022-01-26 16:04:08 +08001915 #ifdef CONFIG_AMLOGIC_CMA
1916 cma_keep_high_active(page, &high_active_pages,
1917 &clean_pages);
1918 #else
Minchan Kim02c6de82012-10-08 16:31:55 -07001919 ClearPageActive(page);
1920 list_move(&page->lru, &clean_pages);
Tao Zeng54f845e2022-01-26 16:04:08 +08001921 #endif
Minchan Kim02c6de82012-10-08 16:31:55 -07001922 }
1923 }
1924
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001925 /*
1926 * We should be safe here since we are only dealing with file pages and
1927 * we are not kswapd and therefore cannot write dirty file pages. But
1928 * call memalloc_noreclaim_save() anyway, just in case these conditions
1929 * change in the future.
1930 */
1931 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001932 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001933 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001934 memalloc_noreclaim_restore(noreclaim_flag);
1935
Minchan Kim02c6de82012-10-08 16:31:55 -07001936 list_splice(&clean_pages, page_list);
Tao Zeng54f845e2022-01-26 16:04:08 +08001937#ifdef CONFIG_AMLOGIC_CMA
1938 list_splice(&high_active_pages, page_list);
1939#endif
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001940 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1941 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001942 /*
1943 * Since lazyfree pages are isolated from file LRU from the beginning,
1944 * they will rotate back to anonymous LRU in the end if it failed to
1945 * discard so isolated count will be mismatched.
1946 * Compensate the isolated count for both LRU lists.
1947 */
1948 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1949 stat.nr_lazyfree_fail);
1950 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001951 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001952 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001953}
1954
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001955/*
Mel Gorman7ee36a12016-07-28 15:47:17 -07001956 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001957 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001958 */
1959static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001960 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001961{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001962 int zid;
1963
Mel Gorman7ee36a12016-07-28 15:47:17 -07001964 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1965 if (!nr_zone_taken[zid])
1966 continue;
1967
Wei Yanga892cb62020-06-03 16:01:12 -07001968 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001969 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001970
Mel Gorman7ee36a12016-07-28 15:47:17 -07001971}
1972
Zhaoyang Huang45022652023-05-31 10:51:01 +08001973#ifdef CONFIG_CMA
1974/*
1975 * It is waste of effort to scan and reclaim CMA pages if it is not available
1976 * for current allocation context. Kswapd can not be enrolled as it can not
1977 * distinguish this scenario by using sc->gfp_mask = GFP_KERNEL
1978 */
1979static bool skip_cma(struct page *page, struct scan_control *sc)
1980{
1981 return !current_is_kswapd() &&
1982 gfp_migratetype(sc->gfp_mask) != MIGRATE_MOVABLE &&
1983 get_pageblock_migratetype(page) == MIGRATE_CMA;
1984}
1985#else
1986static bool skip_cma(struct page *page, struct scan_control *sc)
1987{
1988 return false;
1989}
1990#endif
1991
Mel Gormanf611fab2021-06-30 18:53:19 -07001992/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001993 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1994 *
1995 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001996 * shrink the lists perform better by taking out a batch of pages
1997 * and working on them outside the LRU lock.
1998 *
1999 * For pagecache intensive workloads, this function is the hottest
2000 * spot in the kernel (apart from copy_*_user functions).
2001 *
Hugh Dickins15b44732020-12-15 14:21:31 -08002002 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002003 *
Minchan Kim791b48b2017-05-12 15:47:06 -07002004 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002005 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07002006 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08002007 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07002008 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002009 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07002010 *
2011 * returns how many pages were moved onto *@dst.
2012 */
Andrew Morton69e05942006-03-22 00:08:19 -08002013static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002014 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07002015 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002016 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002017{
Hugh Dickins75b00af2012-05-29 15:07:09 -07002018 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08002019 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07002020 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002021 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07002022 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002023 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002024 LIST_HEAD(pages_skipped);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002025
Yang Shi98879b32019-07-11 20:59:30 -07002026 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002027 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07002028 while (scan < nr_to_scan && !list_empty(src)) {
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002029 struct list_head *move_to = src;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002030 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002031
Linus Torvalds1da177e2005-04-16 15:20:36 -07002032 page = lru_to_page(src);
2033 prefetchw_prev_lru_page(page, src, flags);
2034
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002035 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002036 total_scan += nr_pages;
2037
Zhaoyang Huang45022652023-05-31 10:51:01 +08002038 if (page_zonenum(page) > sc->reclaim_idx ||
2039 skip_cma(page, sc)) {
Yang Shi98879b32019-07-11 20:59:30 -07002040 nr_skipped[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002041 move_to = &pages_skipped;
2042 goto move;
Mel Gormanb2e18752016-07-28 15:45:37 -07002043 }
2044
Minchan Kim791b48b2017-05-12 15:47:06 -07002045 /*
2046 * Do not count skipped pages because that makes the function
2047 * return with no isolated pages if the LRU mostly contains
2048 * ineligible pages. This causes the VM to not reclaim any
2049 * pages, triggering a premature OOM.
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002050 * Account all tail pages of THP.
Minchan Kim791b48b2017-05-12 15:47:06 -07002051 */
Yang Shi98879b32019-07-11 20:59:30 -07002052 scan += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002053
2054 if (!PageLRU(page))
2055 goto move;
2056 if (!sc->may_unmap && page_mapped(page))
2057 goto move;
2058
Alex Shic2135f72021-02-24 12:08:01 -08002059 /*
2060 * Be careful not to clear PageLRU until after we're
2061 * sure the page is not being freed elsewhere -- the
2062 * page release code relies on it.
2063 */
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002064 if (unlikely(!get_page_unless_zero(page)))
2065 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002066
2067 if (!TestClearPageLRU(page)) {
2068 /* Another thread is already isolating this page */
2069 put_page(page);
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002070 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002071 }
2072
2073 nr_taken += nr_pages;
2074 nr_zone_taken[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002075 move_to = dst;
2076move:
2077 list_move(&page->lru, move_to);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002078 }
2079
Mel Gormanb2e18752016-07-28 15:45:37 -07002080 /*
2081 * Splice any skipped pages to the start of the LRU list. Note that
2082 * this disrupts the LRU order when reclaiming for lower zones but
2083 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2084 * scanning would soon rescan the same pages to skip and put the
2085 * system at risk of premature OOM.
2086 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002087 if (!list_empty(&pages_skipped)) {
2088 int zid;
2089
Johannes Weiner3db65812017-05-03 14:52:13 -07002090 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002091 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2092 if (!nr_skipped[zid])
2093 continue;
2094
2095 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002096 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002097 }
2098 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002099 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002100 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002101 total_scan, skipped, nr_taken,
2102 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002103 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002104 return nr_taken;
2105}
2106
Nick Piggin62695a82008-10-18 20:26:09 -07002107/**
2108 * isolate_lru_page - tries to isolate a page from its LRU list
2109 * @page: page to isolate from its LRU list
2110 *
2111 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2112 * vmstat statistic corresponding to whatever LRU list the page was on.
2113 *
2114 * Returns 0 if the page was removed from an LRU list.
2115 * Returns -EBUSY if the page was not on an LRU list.
2116 *
2117 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002118 * the active list, it will have PageActive set. If it was found on
2119 * the unevictable list, it will have the PageUnevictable bit set. That flag
2120 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002121 *
2122 * The vmstat statistic corresponding to the list on which the page was
2123 * found will be decremented.
2124 *
2125 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002126 *
Nick Piggin62695a82008-10-18 20:26:09 -07002127 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002128 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002129 * without a stable reference).
2130 * (2) the lru_lock must not be held.
2131 * (3) interrupts must be enabled.
2132 */
2133int isolate_lru_page(struct page *page)
2134{
2135 int ret = -EBUSY;
2136
Sasha Levin309381fea2014-01-23 15:52:54 -08002137 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002138 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002139
Alex Shid25b5bd2020-12-15 12:34:16 -08002140 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002141 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002142
Alex Shid25b5bd2020-12-15 12:34:16 -08002143 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002144 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002145 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002146 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002147 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002148 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002149
Nick Piggin62695a82008-10-18 20:26:09 -07002150 return ret;
2151}
2152
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002153/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002154 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002155 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002156 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2157 * the LRU list will go small and be scanned faster than necessary, leading to
2158 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002159 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002160static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002161 struct scan_control *sc)
2162{
2163 unsigned long inactive, isolated;
2164
2165 if (current_is_kswapd())
2166 return 0;
2167
Johannes Weinerb5ead352019-11-30 17:55:40 -08002168 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002169 return 0;
2170
2171 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002172 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2173 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002174 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002175 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2176 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002177 }
2178
Fengguang Wu3cf23842012-12-18 14:23:31 -08002179 /*
2180 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2181 * won't get blocked by normal direct-reclaimers, forming a circular
2182 * deadlock.
2183 */
Jianxiong Pan710268f2022-02-24 19:30:46 +08002184#ifndef CONFIG_AMLOGIC_MEMORY_EXTEND
Mel Gormand0164ad2015-11-06 16:28:21 -08002185 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002186 inactive >>= 3;
Jianxiong Pan710268f2022-02-24 19:30:46 +08002187#endif
Fengguang Wu3cf23842012-12-18 14:23:31 -08002188
Tao Zeng54f845e2022-01-26 16:04:08 +08002189#ifdef CONFIG_AMLOGIC_CMA
2190 check_cma_isolated(&isolated, inactive, inactive);
2191#endif
Rik van Riel35cd7812009-09-21 17:01:38 -07002192 return isolated > inactive;
2193}
2194
Kirill Tkhaia222f342019-05-13 17:17:00 -07002195/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002196 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2197 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002198 *
2199 * Returns the number of pages moved to the given lruvec.
2200 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002201static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2202 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002203{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002204 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002205 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002206 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002207
Kirill Tkhaia222f342019-05-13 17:17:00 -07002208 while (!list_empty(list)) {
2209 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002210 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002211 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002212 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002213 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002214 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002215 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002216 continue;
2217 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002218
Alex Shi3d06afa2020-12-15 12:33:37 -08002219 /*
2220 * The SetPageLRU needs to be kept here for list integrity.
2221 * Otherwise:
2222 * #0 move_pages_to_lru #1 release_pages
2223 * if !put_page_testzero
2224 * if (put_page_testzero())
2225 * !PageLRU //skip lru_lock
2226 * SetPageLRU()
2227 * list_add(&page->lru,)
2228 * list_add(&page->lru,)
2229 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002230 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002231
Alex Shi3d06afa2020-12-15 12:33:37 -08002232 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002233 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002234
2235 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002236 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002237 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002238 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002239 } else
2240 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002241
2242 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002243 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002244
Alex Shiafca9152020-12-15 12:34:02 -08002245 /*
2246 * All pages were isolated from the same lruvec (and isolation
2247 * inhibits memcg migration).
2248 */
Muchun Song7467c392021-06-28 19:37:59 -07002249 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002250 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002251 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002252 nr_moved += nr_pages;
2253 if (PageActive(page))
2254 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002255 }
Mel Gorman66635622010-08-09 17:19:30 -07002256
Hugh Dickins3f797682012-01-12 17:20:07 -08002257 /*
2258 * To save our caller's stack, now use input list for pages to free.
2259 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002260 list_splice(&pages_to_free, list);
2261
2262 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002263}
2264
2265/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002266 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002267 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002268 * In that case we should only throttle if the backing device it is
2269 * writing to is congested. In other cases it is safe to throttle.
2270 */
2271static int current_may_throttle(void)
2272{
NeilBrowna37b0712020-06-01 21:48:18 -07002273 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002274 current->backing_dev_info == NULL ||
2275 bdi_write_congested(current->backing_dev_info);
2276}
2277
2278/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002279 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002280 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002281 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002282static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002283shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002284 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002285{
2286 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002287 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002288 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002289 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002290 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002291 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002292 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002293 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002294 bool stalled = false;
Minchan Kim7df45e52022-10-27 08:29:17 -07002295 struct blk_plug plug;
2296 bool do_plug = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002297
Mel Gorman599d0c92016-07-28 15:45:31 -07002298 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002299 if (stalled)
2300 return 0;
2301
2302 /* wait a bit for the reclaimer. */
2303 msleep(100);
2304 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002305
2306 /* We are about to die and free our memory. Return now. */
2307 if (fatal_signal_pending(current))
2308 return SWAP_CLUSTER_MAX;
2309 }
2310
Linus Torvalds1da177e2005-04-16 15:20:36 -07002311 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002312
Alex Shi6168d0d2020-12-15 12:34:29 -08002313 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002314
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002315 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002316 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002317
Mel Gorman599d0c92016-07-28 15:45:31 -07002318 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002319 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002320 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002321 __count_vm_events(item, nr_scanned);
2322 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002323 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2324
Alex Shi6168d0d2020-12-15 12:34:29 -08002325 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002326
Hillf Dantond563c052012-03-21 16:34:02 -07002327 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002328 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002329
Minchan Kim7df45e52022-10-27 08:29:17 -07002330 trace_android_vh_shrink_inactive_list_blk_plug(&do_plug);
2331 if (do_plug)
2332 blk_start_plug(&plug);
Shakeel Butt013339d2020-12-14 19:06:39 -08002333 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002334
Alex Shi6168d0d2020-12-15 12:34:29 -08002335 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002336 move_pages_to_lru(lruvec, &page_list);
2337
2338 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002339 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002340 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002341 __count_vm_events(item, nr_reclaimed);
2342 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002343 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002344 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002345
Minchan Kim7df45e52022-10-27 08:29:17 -07002346 if (do_plug)
2347 blk_finish_plug(&plug);
2348
Alex Shi75cc3c92020-12-15 14:20:50 -08002349 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002350 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002351 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002352
Mel Gorman92df3a72011-10-31 17:07:56 -07002353 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002354 * If dirty pages are scanned that are not queued for IO, it
2355 * implies that flushers are not doing their job. This can
2356 * happen when memory pressure pushes dirty pages to the end of
2357 * the LRU before the dirty limits are breached and the dirty
2358 * data has expired. It can also happen when the proportion of
2359 * dirty pages grows not through writes but through memory
2360 * pressure reclaiming all the clean cache. And in some cases,
2361 * the flushers simply cannot keep up with the allocation
2362 * rate. Nudge the flusher threads in case they are asleep.
2363 */
2364 if (stat.nr_unqueued_dirty == nr_taken)
2365 wakeup_flusher_threads(WB_REASON_VMSCAN);
2366
Andrey Ryabinind108c772018-04-10 16:27:59 -07002367 sc->nr.dirty += stat.nr_dirty;
2368 sc->nr.congested += stat.nr_congested;
2369 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2370 sc->nr.writeback += stat.nr_writeback;
2371 sc->nr.immediate += stat.nr_immediate;
2372 sc->nr.taken += nr_taken;
2373 if (file)
2374 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002375
Mel Gorman599d0c92016-07-28 15:45:31 -07002376 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002377 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002378 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002379}
2380
Hugh Dickins15b44732020-12-15 14:21:31 -08002381/*
2382 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2383 *
2384 * We move them the other way if the page is referenced by one or more
2385 * processes.
2386 *
2387 * If the pages are mostly unmapped, the processing is fast and it is
2388 * appropriate to hold lru_lock across the whole operation. But if
2389 * the pages are mapped, the processing is slow (page_referenced()), so
2390 * we should drop lru_lock around each page. It's impossible to balance
2391 * this, so instead we remove the pages from the LRU while processing them.
2392 * It is safe to rely on PG_active against the non-LRU pages in here because
2393 * nobody will play with that bit on a non-LRU page.
2394 *
2395 * The downside is that we have to touch page->_refcount against each page.
2396 * But we had to alter page->flags anyway.
2397 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002398static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002399 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002400 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002401 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002402{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002403 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002404 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002405 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002406 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002407 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002408 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002409 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002410 unsigned nr_deactivate, nr_activate;
2411 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002412 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002413 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002414 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002415
2416 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002417
Alex Shi6168d0d2020-12-15 12:34:29 -08002418 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002419
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002420 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002421 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002422
Mel Gorman599d0c92016-07-28 15:45:31 -07002423 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002424
Shakeel Butt912c0572020-08-06 23:26:32 -07002425 if (!cgroup_reclaim(sc))
2426 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002427 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002428
Alex Shi6168d0d2020-12-15 12:34:29 -08002429 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002430
Linus Torvalds1da177e2005-04-16 15:20:36 -07002431 while (!list_empty(&l_hold)) {
2432 cond_resched();
2433 page = lru_to_page(&l_hold);
2434 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002435
Hugh Dickins39b5f292012-10-08 16:33:18 -07002436 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002437 putback_lru_page(page);
2438 continue;
2439 }
2440
Mel Gormancc715d92012-03-21 16:34:00 -07002441 if (unlikely(buffer_heads_over_limit)) {
2442 if (page_has_private(page) && trylock_page(page)) {
2443 if (page_has_private(page))
2444 try_to_release_page(page, 0);
2445 unlock_page(page);
2446 }
2447 }
2448
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002449 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2450 if (bypass)
2451 goto skip_page_referenced;
2452
Minchan Kimf74aca72022-05-19 14:08:54 -07002453 /* Referenced or rmap lock contention: rotate */
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002454 if (page_referenced(page, 0, sc->target_mem_cgroup,
Minchan Kimf74aca72022-05-19 14:08:54 -07002455 &vm_flags) != 0) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002456 /*
2457 * Identify referenced, file-backed active pages and
2458 * give them one more trip around the active list. So
2459 * that executable code get better chances to stay in
2460 * memory under moderate memory pressure. Anon pages
2461 * are not likely to be evicted by use-once streaming
2462 * IO, plus JVM can create lots of anon VM_EXEC pages,
2463 * so we ignore them here.
2464 */
Huang Ying9de4f222020-04-06 20:04:41 -07002465 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002466 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002467 list_add(&page->lru, &l_active);
2468 continue;
2469 }
2470 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002471skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002472 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002473 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002474 list_add(&page->lru, &l_inactive);
2475 }
2476
Andrew Mortonb5557492009-01-06 14:40:13 -08002477 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002478 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002479 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002480 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002481
Kirill Tkhaia222f342019-05-13 17:17:00 -07002482 nr_activate = move_pages_to_lru(lruvec, &l_active);
2483 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002484 /* Keep all free pages in l_active list */
2485 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002486
2487 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2488 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2489
Mel Gorman599d0c92016-07-28 15:45:31 -07002490 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002491 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002492
Kirill Tkhaif372d892019-05-13 17:16:57 -07002493 mem_cgroup_uncharge_list(&l_active);
2494 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002495 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2496 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002497}
2498
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002499unsigned long reclaim_pages(struct list_head *page_list)
2500{
Yang Shif661d002020-04-01 21:10:05 -07002501 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002502 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002503 LIST_HEAD(node_page_list);
2504 struct reclaim_stat dummy_stat;
2505 struct page *page;
Minchan Kim7df45e52022-10-27 08:29:17 -07002506 struct blk_plug plug;
2507 bool do_plug = false;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002508 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002509 struct scan_control sc = {
2510 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002511 .may_writepage = 1,
2512 .may_unmap = 1,
2513 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002514 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002515 };
2516
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002517 noreclaim_flag = memalloc_noreclaim_save();
2518
Minchan Kim7df45e52022-10-27 08:29:17 -07002519 trace_android_vh_reclaim_pages_plug(&do_plug);
2520 if (do_plug)
2521 blk_start_plug(&plug);
2522
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002523 while (!list_empty(page_list)) {
2524 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002525 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002526 nid = page_to_nid(page);
2527 INIT_LIST_HEAD(&node_page_list);
2528 }
2529
2530 if (nid == page_to_nid(page)) {
2531 ClearPageActive(page);
2532 list_move(&page->lru, &node_page_list);
2533 continue;
2534 }
2535
2536 nr_reclaimed += shrink_page_list(&node_page_list,
2537 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002538 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002539 while (!list_empty(&node_page_list)) {
2540 page = lru_to_page(&node_page_list);
2541 list_del(&page->lru);
2542 putback_lru_page(page);
2543 }
2544
Yang Shif661d002020-04-01 21:10:05 -07002545 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002546 }
2547
2548 if (!list_empty(&node_page_list)) {
2549 nr_reclaimed += shrink_page_list(&node_page_list,
2550 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002551 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002552 while (!list_empty(&node_page_list)) {
2553 page = lru_to_page(&node_page_list);
2554 list_del(&page->lru);
2555 putback_lru_page(page);
2556 }
2557 }
2558
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002559 memalloc_noreclaim_restore(noreclaim_flag);
2560
Minchan Kim7df45e52022-10-27 08:29:17 -07002561 if (do_plug)
2562 blk_finish_plug(&plug);
2563
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002564 return nr_reclaimed;
2565}
2566
Johannes Weinerb91ac372019-11-30 17:56:02 -08002567static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2568 struct lruvec *lruvec, struct scan_control *sc)
2569{
2570 if (is_active_lru(lru)) {
2571 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2572 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2573 else
2574 sc->skipped_deactivate = 1;
2575 return 0;
2576 }
2577
2578 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2579}
2580
Rik van Riel59dc76b2016-05-20 16:56:31 -07002581/*
2582 * The inactive anon list should be small enough that the VM never has
2583 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002584 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002585 * The inactive file list should be small enough to leave most memory
2586 * to the established workingset on the scan-resistant active list,
2587 * but large enough to avoid thrashing the aggregate readahead window.
2588 *
2589 * Both inactive lists should also be large enough that each inactive
2590 * page has a chance to be referenced again before it is reclaimed.
2591 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002592 * If that fails and refaulting is observed, the inactive list grows.
2593 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002594 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002595 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002596 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2597 *
2598 * total target max
2599 * memory ratio inactive
2600 * -------------------------------------
2601 * 10MB 1 5MB
2602 * 100MB 1 50MB
2603 * 1GB 3 250MB
2604 * 10GB 10 0.9GB
2605 * 100GB 31 3GB
2606 * 1TB 101 10GB
2607 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002608 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002609static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002610{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002611 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002612 unsigned long inactive, active;
2613 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002614 unsigned long gb;
2615
Johannes Weinerb91ac372019-11-30 17:56:02 -08002616 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2617 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002618
Johannes Weinerb91ac372019-11-30 17:56:02 -08002619 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002620 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002621 inactive_ratio = int_sqrt(10 * gb);
2622 else
2623 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002624
Rik van Riel59dc76b2016-05-20 16:56:31 -07002625 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002626}
2627
Johannes Weiner9a265112013-02-22 16:32:17 -08002628enum scan_balance {
2629 SCAN_EQUAL,
2630 SCAN_FRACT,
2631 SCAN_ANON,
2632 SCAN_FILE,
2633};
2634
Yu Zhao6d313442022-09-18 02:00:00 -06002635static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2636{
2637 unsigned long file;
2638 struct lruvec *target_lruvec;
2639
Yu Zhao37397872022-09-18 02:00:03 -06002640 if (lru_gen_enabled())
2641 return;
2642
Yu Zhao6d313442022-09-18 02:00:00 -06002643 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2644
2645 /*
2646 * Flush the memory cgroup stats, so that we read accurate per-memcg
2647 * lruvec stats for heuristics.
2648 */
2649 mem_cgroup_flush_stats();
2650
2651 /*
2652 * Determine the scan balance between anon and file LRUs.
2653 */
2654 spin_lock_irq(&target_lruvec->lru_lock);
2655 sc->anon_cost = target_lruvec->anon_cost;
2656 sc->file_cost = target_lruvec->file_cost;
2657 spin_unlock_irq(&target_lruvec->lru_lock);
2658
2659 /*
2660 * Target desirable inactive:active list ratios for the anon
2661 * and file LRU lists.
2662 */
2663 if (!sc->force_deactivate) {
2664 unsigned long refaults;
2665
2666 refaults = lruvec_page_state(target_lruvec,
2667 WORKINGSET_ACTIVATE_ANON);
2668 if (refaults != target_lruvec->refaults[0] ||
2669 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2670 sc->may_deactivate |= DEACTIVATE_ANON;
2671 else
2672 sc->may_deactivate &= ~DEACTIVATE_ANON;
2673
2674 /*
2675 * When refaults are being observed, it means a new
2676 * workingset is being established. Deactivate to get
2677 * rid of any stale active pages quickly.
2678 */
2679 refaults = lruvec_page_state(target_lruvec,
2680 WORKINGSET_ACTIVATE_FILE);
2681 if (refaults != target_lruvec->refaults[1] ||
2682 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2683 sc->may_deactivate |= DEACTIVATE_FILE;
2684 else
2685 sc->may_deactivate &= ~DEACTIVATE_FILE;
2686 } else
2687 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2688
2689 /*
2690 * If we have plenty of inactive file pages that aren't
2691 * thrashing, try to reclaim those first before touching
2692 * anonymous pages.
2693 */
2694 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2695 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2696 sc->cache_trim_mode = 1;
2697 else
2698 sc->cache_trim_mode = 0;
2699
2700 /*
2701 * Prevent the reclaimer from falling into the cache trap: as
2702 * cache pages start out inactive, every cache fault will tip
2703 * the scan balance towards the file LRU. And as the file LRU
2704 * shrinks, so does the window for rotation from references.
2705 * This means we have a runaway feedback loop where a tiny
2706 * thrashing file LRU becomes infinitely more attractive than
2707 * anon pages. Try to detect this based on file LRU size.
2708 */
2709 if (!cgroup_reclaim(sc)) {
2710 unsigned long total_high_wmark = 0;
2711 unsigned long free, anon;
2712 int z;
2713
2714 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2715 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2716 node_page_state(pgdat, NR_INACTIVE_FILE);
2717
2718 for (z = 0; z < MAX_NR_ZONES; z++) {
2719 struct zone *zone = &pgdat->node_zones[z];
2720
2721 if (!managed_zone(zone))
2722 continue;
2723
2724 total_high_wmark += high_wmark_pages(zone);
2725 }
2726
2727 /*
2728 * Consider anon: if that's low too, this isn't a
2729 * runaway file reclaim problem, but rather just
2730 * extreme pressure. Reclaim as per usual then.
2731 */
2732 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2733
2734 sc->file_is_tiny =
2735 file + free <= total_high_wmark &&
2736 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2737 anon >> sc->priority;
2738 }
2739}
2740
Linus Torvalds1da177e2005-04-16 15:20:36 -07002741/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002742 * Determine how aggressively the anon and file LRU lists should be
2743 * scanned. The relative value of each set of LRU lists is determined
2744 * by looking at the fraction of the pages scanned we did rotate back
2745 * onto the active list instead of evict.
2746 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002747 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2748 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002749 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002750static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2751 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002752{
Keith Buscha2a36482021-09-02 14:59:26 -07002753 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002754 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002755 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002756 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002757 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002758 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002759 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002760 unsigned long ap, fp;
2761 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002762 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002763
2764 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002765 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002766 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002767 goto out;
2768 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002769
Johannes Weiner10316b32013-02-22 16:32:14 -08002770 /*
2771 * Global reclaim will swap to prevent OOM even with no
2772 * swappiness, but memcg users want to use this knob to
2773 * disable swapping for individual groups completely when
2774 * using the memory controller's swap limit feature would be
2775 * too expensive.
2776 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002777 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002778 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002779 goto out;
2780 }
2781
2782 /*
2783 * Do not apply any pressure balancing cleverness when the
2784 * system is close to OOM, scan both anon and file equally
2785 * (unless the swappiness setting disagrees with swapping).
2786 */
Johannes Weiner02695172014-08-06 16:06:17 -07002787 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002788 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002789 goto out;
2790 }
2791
Johannes Weiner11d16c22013-02-22 16:32:15 -08002792 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002793 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002794 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002795 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002796 scan_balance = SCAN_ANON;
2797 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002798 }
2799
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002800 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2801
Johannes Weiner62376252014-05-06 12:50:07 -07002802 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002803 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002804 * anything from the anonymous working right now. But when balancing
2805 * anon and page cache files for reclaim, allow swapping of anon pages
2806 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002807 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002808 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002809 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002810 goto out;
2811 }
2812
Johannes Weiner9a265112013-02-22 16:32:17 -08002813 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002814 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002815 * Calculate the pressure balance between anon and file pages.
2816 *
2817 * The amount of pressure we put on each LRU is inversely
2818 * proportional to the cost of reclaiming each list, as
2819 * determined by the share of pages that are refaulting, times
2820 * the relative IO cost of bringing back a swapped out
2821 * anonymous page vs reloading a filesystem page (swappiness).
2822 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002823 * Although we limit that influence to ensure no list gets
2824 * left behind completely: at least a third of the pressure is
2825 * applied, before swappiness.
2826 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002827 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002828 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002829 total_cost = sc->anon_cost + sc->file_cost;
2830 anon_cost = total_cost + sc->anon_cost;
2831 file_cost = total_cost + sc->file_cost;
2832 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002833
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002834 ap = swappiness * (total_cost + 1);
2835 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002836
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002837 fp = (200 - swappiness) * (total_cost + 1);
2838 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002839
Shaohua Li76a33fc2010-05-24 14:32:36 -07002840 fraction[0] = ap;
2841 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002842 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002843out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002844 for_each_evictable_lru(lru) {
2845 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002846 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002847 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002848 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002849
Chris Down9783aa92019-10-06 17:58:32 -07002850 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002851 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2852 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002853
Johannes Weinerf56ce412021-08-19 19:04:21 -07002854 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002855 /*
2856 * Scale a cgroup's reclaim pressure by proportioning
2857 * its current usage to its memory.low or memory.min
2858 * setting.
2859 *
2860 * This is important, as otherwise scanning aggression
2861 * becomes extremely binary -- from nothing as we
2862 * approach the memory protection threshold, to totally
2863 * nominal as we exceed it. This results in requiring
2864 * setting extremely liberal protection thresholds. It
2865 * also means we simply get no protection at all if we
2866 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002867 *
2868 * If there is any protection in place, we reduce scan
2869 * pressure by how much of the total memory used is
2870 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002871 *
Chris Down9de7ca42019-10-06 17:58:35 -07002872 * There is one special case: in the first reclaim pass,
2873 * we skip over all groups that are within their low
2874 * protection. If that fails to reclaim enough pages to
2875 * satisfy the reclaim goal, we come back and override
2876 * the best-effort low protection. However, we still
2877 * ideally want to honor how well-behaved groups are in
2878 * that case instead of simply punishing them all
2879 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002880 * memory they are using, reducing the scan pressure
2881 * again by how much of the total memory used is under
2882 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002883 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002884 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002885 unsigned long protection;
2886
2887 /* memory.low scaling, make sure we retry before OOM */
2888 if (!sc->memcg_low_reclaim && low > min) {
2889 protection = low;
2890 sc->memcg_low_skipped = 1;
2891 } else {
2892 protection = min;
2893 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002894
2895 /* Avoid TOCTOU with earlier protection check */
2896 cgroup_size = max(cgroup_size, protection);
2897
2898 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002899 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002900
2901 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002902 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002903 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002904 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002905 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002906 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002907 } else {
2908 scan = lruvec_size;
2909 }
2910
2911 scan >>= sc->priority;
2912
Johannes Weiner688035f2017-05-03 14:52:07 -07002913 /*
2914 * If the cgroup's already been deleted, make sure to
2915 * scrape out the remaining cache.
2916 */
2917 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002918 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002919
Johannes Weiner688035f2017-05-03 14:52:07 -07002920 switch (scan_balance) {
2921 case SCAN_EQUAL:
2922 /* Scan lists relative to size */
2923 break;
2924 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002925 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002926 * Scan types proportional to swappiness and
2927 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002928 * Make sure we don't miss the last page on
2929 * the offlined memory cgroups because of a
2930 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002931 */
Gavin Shan76073c62020-02-20 20:04:24 -08002932 scan = mem_cgroup_online(memcg) ?
2933 div64_u64(scan * fraction[file], denominator) :
2934 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002935 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002936 break;
2937 case SCAN_FILE:
2938 case SCAN_ANON:
2939 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002940 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002941 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002942 break;
2943 default:
2944 /* Look ma, no brain */
2945 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002946 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002947
Johannes Weiner688035f2017-05-03 14:52:07 -07002948 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002949 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002950}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002951
Dave Hansen2f368a92021-09-02 14:59:23 -07002952/*
2953 * Anonymous LRU management is a waste if there is
2954 * ultimately no way to reclaim the memory.
2955 */
2956static bool can_age_anon_pages(struct pglist_data *pgdat,
2957 struct scan_control *sc)
2958{
2959 /* Aging the anon LRU is valuable if swap is present: */
2960 if (total_swap_pages > 0)
2961 return true;
2962
2963 /* Also valuable if anon pages can be demoted: */
2964 return can_demote(pgdat->node_id, sc);
2965}
2966
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002967#ifdef CONFIG_LRU_GEN
2968
Yu Zhaobaeb9a02022-09-18 02:00:07 -06002969#ifdef CONFIG_LRU_GEN_ENABLED
2970DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2971#define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2972#else
2973DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2974#define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2975#endif
2976
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002977/******************************************************************************
2978 * shorthand helpers
2979 ******************************************************************************/
2980
Yu Zhao37397872022-09-18 02:00:03 -06002981#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2982
2983#define DEFINE_MAX_SEQ(lruvec) \
2984 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2985
2986#define DEFINE_MIN_SEQ(lruvec) \
2987 unsigned long min_seq[ANON_AND_FILE] = { \
2988 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2989 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2990 }
2991
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002992#define for_each_gen_type_zone(gen, type, zone) \
2993 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2994 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2995 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2996
Yu Zhaoa3eb6512022-12-21 21:19:04 -07002997#define get_memcg_gen(seq) ((seq) % MEMCG_NR_GENS)
2998#define get_memcg_bin(bin) ((bin) % MEMCG_NR_BINS)
2999
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003000static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
Yu Zhaod5b2fa12022-09-18 02:00:02 -06003001{
3002 struct pglist_data *pgdat = NODE_DATA(nid);
3003
3004#ifdef CONFIG_MEMCG
3005 if (memcg) {
3006 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
3007
3008 /* for hotadd_new_pgdat() */
3009 if (!lruvec->pgdat)
3010 lruvec->pgdat = pgdat;
3011
3012 return lruvec;
3013 }
3014#endif
3015 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3016
3017 return pgdat ? &pgdat->__lruvec : NULL;
3018}
3019
Yu Zhao37397872022-09-18 02:00:03 -06003020static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
3021{
3022 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3023 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3024
Yu Zhaof8b57162022-12-21 21:19:05 -07003025 if (!sc->may_swap)
3026 return 0;
3027
Kalesh Singhb8d031e2023-04-03 15:28:17 -07003028 if (!can_demote(pgdat->node_id, sc) &&
3029 mem_cgroup_get_nr_swap_pages(memcg) <= 0)
Yu Zhao37397872022-09-18 02:00:03 -06003030 return 0;
3031
3032 return mem_cgroup_swappiness(memcg);
3033}
3034
3035static int get_nr_gens(struct lruvec *lruvec, int type)
3036{
3037 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3038}
3039
3040static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3041{
Yu Zhao3c6c3592022-12-21 21:18:59 -07003042 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06003043 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3044 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3045 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3046}
3047
3048/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003049 * mm_struct list
3050 ******************************************************************************/
3051
3052static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3053{
3054 static struct lru_gen_mm_list mm_list = {
3055 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3056 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3057 };
3058
3059#ifdef CONFIG_MEMCG
3060 if (memcg)
3061 return &memcg->mm_list;
3062#endif
3063 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3064
3065 return &mm_list;
3066}
3067
3068void lru_gen_add_mm(struct mm_struct *mm)
3069{
3070 int nid;
3071 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3072 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3073
3074 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3075#ifdef CONFIG_MEMCG
3076 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3077 mm->lru_gen.memcg = memcg;
3078#endif
3079 spin_lock(&mm_list->lock);
3080
3081 for_each_node_state(nid, N_MEMORY) {
3082 struct lruvec *lruvec = get_lruvec(memcg, nid);
3083
3084 if (!lruvec)
3085 continue;
3086
3087 /* the first addition since the last iteration */
3088 if (lruvec->mm_state.tail == &mm_list->fifo)
3089 lruvec->mm_state.tail = &mm->lru_gen.list;
3090 }
3091
3092 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3093
3094 spin_unlock(&mm_list->lock);
3095}
3096
3097void lru_gen_del_mm(struct mm_struct *mm)
3098{
3099 int nid;
3100 struct lru_gen_mm_list *mm_list;
3101 struct mem_cgroup *memcg = NULL;
3102
3103 if (list_empty(&mm->lru_gen.list))
3104 return;
3105
3106#ifdef CONFIG_MEMCG
3107 memcg = mm->lru_gen.memcg;
3108#endif
3109 mm_list = get_mm_list(memcg);
3110
3111 spin_lock(&mm_list->lock);
3112
3113 for_each_node(nid) {
3114 struct lruvec *lruvec = get_lruvec(memcg, nid);
3115
3116 if (!lruvec)
3117 continue;
3118
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003119 /* where the current iteration continues after */
3120 if (lruvec->mm_state.head == &mm->lru_gen.list)
3121 lruvec->mm_state.head = lruvec->mm_state.head->prev;
3122
3123 /* where the last iteration ended before */
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003124 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3125 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003126 }
3127
3128 list_del_init(&mm->lru_gen.list);
3129
3130 spin_unlock(&mm_list->lock);
3131
3132#ifdef CONFIG_MEMCG
3133 mem_cgroup_put(mm->lru_gen.memcg);
3134 mm->lru_gen.memcg = NULL;
3135#endif
3136}
3137
3138#ifdef CONFIG_MEMCG
3139void lru_gen_migrate_mm(struct mm_struct *mm)
3140{
3141 struct mem_cgroup *memcg;
3142 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3143
3144 VM_WARN_ON_ONCE(task->mm != mm);
3145 lockdep_assert_held(&task->alloc_lock);
3146
3147 /* for mm_update_next_owner() */
3148 if (mem_cgroup_disabled())
3149 return;
3150
Yu Zhao578a3a32023-01-15 20:44:05 -07003151 /* migration can happen before addition */
3152 if (!mm->lru_gen.memcg)
3153 return;
3154
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003155 rcu_read_lock();
3156 memcg = mem_cgroup_from_task(task);
3157 rcu_read_unlock();
3158 if (memcg == mm->lru_gen.memcg)
3159 return;
3160
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003161 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3162
3163 lru_gen_del_mm(mm);
3164 lru_gen_add_mm(mm);
3165}
3166#endif
3167
3168/*
3169 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3170 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3171 * bits in a bitmap, k is the number of hash functions and n is the number of
3172 * inserted items.
3173 *
3174 * Page table walkers use one of the two filters to reduce their search space.
3175 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3176 * aging uses the double-buffering technique to flip to the other filter each
3177 * time it produces a new generation. For non-leaf entries that have enough
3178 * leaf entries, the aging carries them over to the next generation in
3179 * walk_pmd_range(); the eviction also report them when walking the rmap
3180 * in lru_gen_look_around().
3181 *
3182 * For future optimizations:
3183 * 1. It's not necessary to keep both filters all the time. The spare one can be
3184 * freed after the RCU grace period and reallocated if needed again.
3185 * 2. And when reallocating, it's worth scaling its size according to the number
3186 * of inserted entries in the other filter, to reduce the memory overhead on
3187 * small systems and false positives on large systems.
3188 * 3. Jenkins' hash function is an alternative to Knuth's.
3189 */
3190#define BLOOM_FILTER_SHIFT 15
3191
3192static inline int filter_gen_from_seq(unsigned long seq)
3193{
3194 return seq % NR_BLOOM_FILTERS;
3195}
3196
3197static void get_item_key(void *item, int *key)
3198{
3199 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3200
3201 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3202
3203 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3204 key[1] = hash >> BLOOM_FILTER_SHIFT;
3205}
3206
3207static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3208{
3209 unsigned long *filter;
3210 int gen = filter_gen_from_seq(seq);
3211
3212 filter = lruvec->mm_state.filters[gen];
3213 if (filter) {
3214 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3215 return;
3216 }
3217
3218 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3219 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3220 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3221}
3222
3223static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3224{
3225 int key[2];
3226 unsigned long *filter;
3227 int gen = filter_gen_from_seq(seq);
3228
3229 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3230 if (!filter)
3231 return;
3232
3233 get_item_key(item, key);
3234
3235 if (!test_bit(key[0], filter))
3236 set_bit(key[0], filter);
3237 if (!test_bit(key[1], filter))
3238 set_bit(key[1], filter);
3239}
3240
3241static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3242{
3243 int key[2];
3244 unsigned long *filter;
3245 int gen = filter_gen_from_seq(seq);
3246
3247 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3248 if (!filter)
3249 return true;
3250
3251 get_item_key(item, key);
3252
3253 return test_bit(key[0], filter) && test_bit(key[1], filter);
3254}
3255
3256static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3257{
3258 int i;
3259 int hist;
3260
3261 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3262
3263 if (walk) {
3264 hist = lru_hist_from_seq(walk->max_seq);
3265
3266 for (i = 0; i < NR_MM_STATS; i++) {
3267 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3268 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3269 walk->mm_stats[i] = 0;
3270 }
3271 }
3272
3273 if (NR_HIST_GENS > 1 && last) {
3274 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3275
3276 for (i = 0; i < NR_MM_STATS; i++)
3277 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3278 }
3279}
3280
3281static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3282{
3283 int type;
3284 unsigned long size = 0;
3285 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3286 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3287
3288 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3289 return true;
3290
3291 clear_bit(key, &mm->lru_gen.bitmap);
3292
3293 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3294 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3295 get_mm_counter(mm, MM_ANONPAGES) +
3296 get_mm_counter(mm, MM_SHMEMPAGES);
3297 }
3298
3299 if (size < MIN_LRU_BATCH)
3300 return true;
3301
3302 return !mmget_not_zero(mm);
3303}
3304
3305static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3306 struct mm_struct **iter)
3307{
3308 bool first = false;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003309 bool last = false;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003310 struct mm_struct *mm = NULL;
3311 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3312 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3313 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3314
3315 /*
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003316 * mm_state->seq is incremented after each iteration of mm_list. There
3317 * are three interesting cases for this page table walker:
3318 * 1. It tries to start a new iteration with a stale max_seq: there is
3319 * nothing left to do.
3320 * 2. It started the next iteration: it needs to reset the Bloom filter
3321 * so that a fresh set of PTE tables can be recorded.
3322 * 3. It ended the current iteration: it needs to reset the mm stats
3323 * counters and tell its caller to increment max_seq.
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003324 */
3325 spin_lock(&mm_list->lock);
3326
3327 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003328
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003329 if (walk->max_seq <= mm_state->seq)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003330 goto done;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003331
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003332 if (!mm_state->head)
3333 mm_state->head = &mm_list->fifo;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003334
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003335 if (mm_state->head == &mm_list->fifo)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003336 first = true;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003337
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003338 do {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003339 mm_state->head = mm_state->head->next;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003340 if (mm_state->head == &mm_list->fifo) {
3341 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3342 last = true;
3343 break;
3344 }
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003345
3346 /* force scan for those added after the last iteration */
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003347 if (!mm_state->tail || mm_state->tail == mm_state->head) {
3348 mm_state->tail = mm_state->head->next;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003349 walk->force_scan = true;
3350 }
3351
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003352 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003353 if (should_skip_mm(mm, walk))
3354 mm = NULL;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003355 } while (!mm);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003356done:
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003357 if (*iter || last)
3358 reset_mm_stats(lruvec, walk, last);
3359
3360 spin_unlock(&mm_list->lock);
3361
3362 if (mm && first)
3363 reset_bloom_filter(lruvec, walk->max_seq + 1);
3364
3365 if (*iter)
3366 mmput_async(*iter);
3367
3368 *iter = mm;
3369
3370 return last;
3371}
3372
3373static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3374{
3375 bool success = false;
3376 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3377 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3378 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3379
3380 spin_lock(&mm_list->lock);
3381
3382 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3383
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003384 if (max_seq > mm_state->seq) {
3385 mm_state->head = NULL;
3386 mm_state->tail = NULL;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003387 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3388 reset_mm_stats(lruvec, NULL, true);
3389 success = true;
3390 }
3391
3392 spin_unlock(&mm_list->lock);
3393
3394 return success;
3395}
3396
3397/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003398 * refault feedback loop
3399 ******************************************************************************/
3400
3401/*
3402 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3403 *
3404 * The P term is refaulted/(evicted+protected) from a tier in the generation
3405 * currently being evicted; the I term is the exponential moving average of the
3406 * P term over the generations previously evicted, using the smoothing factor
3407 * 1/2; the D term isn't supported.
3408 *
3409 * The setpoint (SP) is always the first tier of one type; the process variable
3410 * (PV) is either any tier of the other type or any other tier of the same
3411 * type.
3412 *
3413 * The error is the difference between the SP and the PV; the correction is to
3414 * turn off protection when SP>PV or turn on protection when SP<PV.
3415 *
3416 * For future optimizations:
3417 * 1. The D term may discount the other two terms over time so that long-lived
3418 * generations can resist stale information.
3419 */
3420struct ctrl_pos {
3421 unsigned long refaulted;
3422 unsigned long total;
3423 int gain;
3424};
3425
3426static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3427 struct ctrl_pos *pos)
3428{
Yu Zhao3c6c3592022-12-21 21:18:59 -07003429 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003430 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3431
3432 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3433 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3434 pos->total = lrugen->avg_total[type][tier] +
3435 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3436 if (tier)
3437 pos->total += lrugen->protected[hist][type][tier - 1];
3438 pos->gain = gain;
3439}
3440
3441static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3442{
3443 int hist, tier;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003444 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003445 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3446 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3447
3448 lockdep_assert_held(&lruvec->lru_lock);
3449
3450 if (!carryover && !clear)
3451 return;
3452
3453 hist = lru_hist_from_seq(seq);
3454
3455 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3456 if (carryover) {
3457 unsigned long sum;
3458
3459 sum = lrugen->avg_refaulted[type][tier] +
3460 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3461 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3462
3463 sum = lrugen->avg_total[type][tier] +
3464 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3465 if (tier)
3466 sum += lrugen->protected[hist][type][tier - 1];
3467 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3468 }
3469
3470 if (clear) {
3471 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3472 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3473 if (tier)
3474 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3475 }
3476 }
3477}
3478
3479static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3480{
3481 /*
3482 * Return true if the PV has a limited number of refaults or a lower
3483 * refaulted/total than the SP.
3484 */
3485 return pv->refaulted < MIN_LRU_BATCH ||
3486 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3487 (sp->refaulted + 1) * pv->total * pv->gain;
3488}
3489
3490/******************************************************************************
3491 * the aging
3492 ******************************************************************************/
3493
Yu Zhao0182f922022-09-18 02:00:04 -06003494/* promote pages accessed through page tables */
3495static int page_update_gen(struct page *page, int gen)
3496{
3497 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3498
3499 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3500 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3501
3502 do {
3503 /* lru_gen_del_page() has isolated this page? */
3504 if (!(old_flags & LRU_GEN_MASK)) {
3505 /* for shrink_page_list() */
3506 new_flags = old_flags | BIT(PG_referenced);
3507 continue;
3508 }
3509
3510 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3511 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3512 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3513
3514 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3515}
3516
Yu Zhao37397872022-09-18 02:00:03 -06003517/* protect pages accessed multiple times through file descriptors */
3518static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3519{
3520 int type = page_is_file_lru(page);
Yu Zhao3c6c3592022-12-21 21:18:59 -07003521 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003522 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3523 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3524
3525 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3526
3527 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003528 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3529 /* page_update_gen() has promoted this page? */
3530 if (new_gen >= 0 && new_gen != old_gen)
3531 return new_gen;
3532
Yu Zhao37397872022-09-18 02:00:03 -06003533 new_gen = (old_gen + 1) % MAX_NR_GENS;
3534
3535 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3536 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3537 /* for end_page_writeback() */
3538 if (reclaiming)
3539 new_flags |= BIT(PG_reclaim);
3540 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3541
3542 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3543
3544 return new_gen;
3545}
3546
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003547static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3548 int old_gen, int new_gen)
3549{
3550 int type = page_is_file_lru(page);
3551 int zone = page_zonenum(page);
3552 int delta = thp_nr_pages(page);
3553
3554 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3555 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3556
3557 walk->batched++;
3558
3559 walk->nr_pages[old_gen][type][zone] -= delta;
3560 walk->nr_pages[new_gen][type][zone] += delta;
3561}
3562
3563static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3564{
3565 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003566 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003567
3568 walk->batched = 0;
3569
3570 for_each_gen_type_zone(gen, type, zone) {
3571 enum lru_list lru = type * LRU_INACTIVE_FILE;
3572 int delta = walk->nr_pages[gen][type][zone];
3573
3574 if (!delta)
3575 continue;
3576
3577 walk->nr_pages[gen][type][zone] = 0;
3578 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3579 lrugen->nr_pages[gen][type][zone] + delta);
3580
3581 if (lru_gen_is_active(lruvec, gen))
3582 lru += LRU_ACTIVE;
3583 __update_lru_size(lruvec, lru, zone, delta);
3584 }
3585}
3586
3587static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3588{
3589 struct address_space *mapping;
3590 struct vm_area_struct *vma = args->vma;
3591 struct lru_gen_mm_walk *walk = args->private;
3592
3593 if (!vma_is_accessible(vma))
3594 return true;
3595
3596 if (is_vm_hugetlb_page(vma))
3597 return true;
3598
Yu Zhao3b9ab092022-12-30 14:52:51 -07003599 if (!vma_has_recency(vma))
3600 return true;
3601
3602 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003603 return true;
3604
3605 if (vma == get_gate_vma(vma->vm_mm))
3606 return true;
3607
3608 if (vma_is_anonymous(vma))
3609 return !walk->can_swap;
3610
3611 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3612 return true;
3613
3614 mapping = vma->vm_file->f_mapping;
3615 if (mapping_unevictable(mapping))
3616 return true;
3617
3618 if (shmem_mapping(mapping))
3619 return !walk->can_swap;
3620
3621 /* to exclude special mappings like dax, etc. */
3622 return !mapping->a_ops->readpage;
3623}
3624
3625/*
3626 * Some userspace memory allocators map many single-page VMAs. Instead of
3627 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3628 * table to reduce zigzags and improve cache performance.
3629 */
3630static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3631 unsigned long *vm_start, unsigned long *vm_end)
3632{
3633 unsigned long start = round_up(*vm_end, size);
3634 unsigned long end = (start | ~mask) + 1;
3635
3636 VM_WARN_ON_ONCE(mask & size);
3637 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3638
3639 while (args->vma) {
3640 if (start >= args->vma->vm_end) {
3641 args->vma = args->vma->vm_next;
3642 continue;
3643 }
3644
3645 if (end && end <= args->vma->vm_start)
3646 return false;
3647
3648 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3649 args->vma = args->vma->vm_next;
3650 continue;
3651 }
3652
3653 *vm_start = max(start, args->vma->vm_start);
3654 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3655
3656 return true;
3657 }
3658
3659 return false;
3660}
3661
Yu Zhao0182f922022-09-18 02:00:04 -06003662static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3663{
3664 unsigned long pfn = pte_pfn(pte);
3665
3666 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3667
3668 if (!pte_present(pte) || is_zero_pfn(pfn))
3669 return -1;
3670
3671 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3672 return -1;
3673
3674 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3675 return -1;
3676
3677 return pfn;
3678}
3679
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003680#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3681static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3682{
3683 unsigned long pfn = pmd_pfn(pmd);
3684
3685 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3686
3687 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3688 return -1;
3689
3690 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3691 return -1;
3692
3693 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3694 return -1;
3695
3696 return pfn;
3697}
3698#endif
3699
Yu Zhao0182f922022-09-18 02:00:04 -06003700static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003701 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003702{
3703 struct page *page;
3704
3705 /* try to avoid unnecessary memory loads */
3706 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3707 return NULL;
3708
3709 page = compound_head(pfn_to_page(pfn));
3710 if (page_to_nid(page) != pgdat->node_id)
3711 return NULL;
3712
3713 if (page_memcg_rcu(page) != memcg)
3714 return NULL;
3715
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003716 /* file VMAs can contain anon pages from COW */
3717 if (!page_is_file_lru(page) && !can_swap)
3718 return NULL;
3719
Yu Zhao0182f922022-09-18 02:00:04 -06003720 return page;
3721}
3722
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003723static bool suitable_to_scan(int total, int young)
3724{
3725 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3726
3727 /* suitable if the average number of young PTEs per cacheline is >=1 */
3728 return young * n >= total;
3729}
3730
3731static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3732 struct mm_walk *args)
3733{
3734 int i;
3735 pte_t *pte;
3736 spinlock_t *ptl;
3737 unsigned long addr;
3738 int total = 0;
3739 int young = 0;
3740 struct lru_gen_mm_walk *walk = args->private;
3741 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3742 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3743 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3744
3745 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3746
3747 ptl = pte_lockptr(args->mm, pmd);
3748 if (!spin_trylock(ptl))
3749 return false;
3750
3751 arch_enter_lazy_mmu_mode();
3752
3753 pte = pte_offset_map(pmd, start & PMD_MASK);
3754restart:
3755 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3756 unsigned long pfn;
3757 struct page *page;
3758
3759 total++;
3760 walk->mm_stats[MM_LEAF_TOTAL]++;
3761
3762 pfn = get_pte_pfn(pte[i], args->vma, addr);
3763 if (pfn == -1)
3764 continue;
3765
3766 if (!pte_young(pte[i])) {
3767 walk->mm_stats[MM_LEAF_OLD]++;
3768 continue;
3769 }
3770
3771 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3772 if (!page)
3773 continue;
3774
3775 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3776 VM_WARN_ON_ONCE(true);
3777
3778 young++;
3779 walk->mm_stats[MM_LEAF_YOUNG]++;
3780
3781 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3782 !(PageAnon(page) && PageSwapBacked(page) &&
3783 !PageSwapCache(page)))
3784 set_page_dirty(page);
3785
3786 old_gen = page_update_gen(page, new_gen);
3787 if (old_gen >= 0 && old_gen != new_gen)
3788 update_batch_size(walk, page, old_gen, new_gen);
3789 }
3790
3791 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3792 goto restart;
3793
3794 pte_unmap(pte);
3795
3796 arch_leave_lazy_mmu_mode();
3797 spin_unlock(ptl);
3798
3799 return suitable_to_scan(total, young);
3800}
3801
3802#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3803static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3804 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3805{
3806 int i;
3807 pmd_t *pmd;
3808 spinlock_t *ptl;
3809 struct lru_gen_mm_walk *walk = args->private;
3810 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3811 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3812 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3813
3814 VM_WARN_ON_ONCE(pud_leaf(*pud));
3815
3816 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3817 if (*start == -1) {
3818 *start = next;
3819 return;
3820 }
3821
3822 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3823 if (i && i <= MIN_LRU_BATCH) {
3824 __set_bit(i - 1, bitmap);
3825 return;
3826 }
3827
3828 pmd = pmd_offset(pud, *start);
3829
3830 ptl = pmd_lockptr(args->mm, pmd);
3831 if (!spin_trylock(ptl))
3832 goto done;
3833
3834 arch_enter_lazy_mmu_mode();
3835
3836 do {
3837 unsigned long pfn;
3838 struct page *page;
3839 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3840
3841 pfn = get_pmd_pfn(pmd[i], vma, addr);
3842 if (pfn == -1)
3843 goto next;
3844
3845 if (!pmd_trans_huge(pmd[i])) {
Juergen Gross23811792022-11-23 07:45:10 +01003846 if (arch_has_hw_nonleaf_pmd_young() &&
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003847 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003848 pmdp_test_and_clear_young(vma, addr, pmd + i);
3849 goto next;
3850 }
3851
3852 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3853 if (!page)
3854 goto next;
3855
3856 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3857 goto next;
3858
3859 walk->mm_stats[MM_LEAF_YOUNG]++;
3860
3861 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3862 !(PageAnon(page) && PageSwapBacked(page) &&
3863 !PageSwapCache(page)))
3864 set_page_dirty(page);
3865
3866 old_gen = page_update_gen(page, new_gen);
3867 if (old_gen >= 0 && old_gen != new_gen)
3868 update_batch_size(walk, page, old_gen, new_gen);
3869next:
3870 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3871 } while (i <= MIN_LRU_BATCH);
3872
3873 arch_leave_lazy_mmu_mode();
3874 spin_unlock(ptl);
3875done:
3876 *start = -1;
3877 bitmap_zero(bitmap, MIN_LRU_BATCH);
3878}
3879#else
3880static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3881 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3882{
3883}
3884#endif
3885
3886static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3887 struct mm_walk *args)
3888{
3889 int i;
3890 pmd_t *pmd;
3891 unsigned long next;
3892 unsigned long addr;
3893 struct vm_area_struct *vma;
3894 unsigned long pos = -1;
3895 struct lru_gen_mm_walk *walk = args->private;
3896 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3897
3898 VM_WARN_ON_ONCE(pud_leaf(*pud));
3899
3900 /*
3901 * Finish an entire PMD in two passes: the first only reaches to PTE
3902 * tables to avoid taking the PMD lock; the second, if necessary, takes
3903 * the PMD lock to clear the accessed bit in PMD entries.
3904 */
3905 pmd = pmd_offset(pud, start & PUD_MASK);
3906restart:
3907 /* walk_pte_range() may call get_next_vma() */
3908 vma = args->vma;
3909 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3910 pmd_t val = pmd_read_atomic(pmd + i);
3911
3912 /* for pmd_read_atomic() */
3913 barrier();
3914
3915 next = pmd_addr_end(addr, end);
3916
3917 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3918 walk->mm_stats[MM_LEAF_TOTAL]++;
3919 continue;
3920 }
3921
3922#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3923 if (pmd_trans_huge(val)) {
3924 unsigned long pfn = pmd_pfn(val);
3925 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3926
3927 walk->mm_stats[MM_LEAF_TOTAL]++;
3928
3929 if (!pmd_young(val)) {
3930 walk->mm_stats[MM_LEAF_OLD]++;
3931 continue;
3932 }
3933
3934 /* try to avoid unnecessary memory loads */
3935 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3936 continue;
3937
3938 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3939 continue;
3940 }
3941#endif
3942 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3943
Juergen Gross23811792022-11-23 07:45:10 +01003944 if (arch_has_hw_nonleaf_pmd_young() &&
3945 get_cap(LRU_GEN_NONLEAF_YOUNG)) {
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003946 if (!pmd_young(val))
3947 continue;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003948
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003949 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3950 }
Juergen Gross23811792022-11-23 07:45:10 +01003951
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003952 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3953 continue;
3954
3955 walk->mm_stats[MM_NONLEAF_FOUND]++;
3956
3957 if (!walk_pte_range(&val, addr, next, args))
3958 continue;
3959
3960 walk->mm_stats[MM_NONLEAF_ADDED]++;
3961
3962 /* carry over to the next generation */
3963 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3964 }
3965
3966 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3967
3968 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3969 goto restart;
3970}
3971
3972static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3973 struct mm_walk *args)
3974{
3975 int i;
3976 pud_t *pud;
3977 unsigned long addr;
3978 unsigned long next;
3979 struct lru_gen_mm_walk *walk = args->private;
3980
3981 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3982
3983 pud = pud_offset(p4d, start & P4D_MASK);
3984restart:
3985 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3986 pud_t val = READ_ONCE(pud[i]);
3987
3988 next = pud_addr_end(addr, end);
3989
3990 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3991 continue;
3992
3993 walk_pmd_range(&val, addr, next, args);
3994
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003995 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3996 end = (addr | ~PUD_MASK) + 1;
3997 goto done;
3998 }
3999 }
4000
4001 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
4002 goto restart;
4003
4004 end = round_up(end, P4D_SIZE);
4005done:
4006 if (!end || !args->vma)
4007 return 1;
4008
4009 walk->next_addr = max(end, args->vma->vm_start);
4010
4011 return -EAGAIN;
4012}
4013
4014static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
4015{
4016 static const struct mm_walk_ops mm_walk_ops = {
4017 .test_walk = should_skip_vma,
4018 .p4d_entry = walk_pud_range,
4019 };
4020
4021 int err;
4022 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4023
4024 walk->next_addr = FIRST_USER_ADDRESS;
4025
4026 do {
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004027 DEFINE_MAX_SEQ(lruvec);
4028
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004029 err = -EBUSY;
4030
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004031 /* another thread might have called inc_max_seq() */
4032 if (walk->max_seq != max_seq)
4033 break;
4034
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004035 /* page_update_gen() requires stable page_memcg() */
4036 if (!mem_cgroup_trylock_pages(memcg))
4037 break;
4038
4039 /* the caller might be holding the lock for write */
4040 if (mmap_read_trylock(mm)) {
4041 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
4042
4043 mmap_read_unlock(mm);
4044 }
4045
4046 mem_cgroup_unlock_pages();
4047
4048 if (walk->batched) {
4049 spin_lock_irq(&lruvec->lru_lock);
4050 reset_batch_size(lruvec, walk);
4051 spin_unlock_irq(&lruvec->lru_lock);
4052 }
4053
4054 cond_resched();
4055 } while (err == -EAGAIN);
4056}
4057
Yu Zhaof8b57162022-12-21 21:19:05 -07004058static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004059{
4060 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4061
4062 if (pgdat && current_is_kswapd()) {
4063 VM_WARN_ON_ONCE(walk);
4064
4065 walk = &pgdat->mm_walk;
Yu Zhaof8b57162022-12-21 21:19:05 -07004066 } else if (!walk && force_alloc) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004067 VM_WARN_ON_ONCE(current_is_kswapd());
4068
4069 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4070 }
4071
4072 current->reclaim_state->mm_walk = walk;
4073
4074 return walk;
4075}
4076
4077static void clear_mm_walk(void)
4078{
4079 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4080
4081 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4082 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4083
4084 current->reclaim_state->mm_walk = NULL;
4085
4086 if (!current_is_kswapd())
4087 kfree(walk);
4088}
4089
Yu Zhao4983c522022-09-18 02:00:09 -06004090static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004091{
Yu Zhao4983c522022-09-18 02:00:09 -06004092 int zone;
4093 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004094 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06004095 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
Yu Zhao37397872022-09-18 02:00:03 -06004096
Yu Zhao4983c522022-09-18 02:00:09 -06004097 if (type == LRU_GEN_ANON && !can_swap)
4098 goto done;
4099
4100 /* prevent cold/hot inversion if force_scan is true */
4101 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004102 struct list_head *head = &lrugen->pages[old_gen][type][zone];
Yu Zhao4983c522022-09-18 02:00:09 -06004103
4104 while (!list_empty(head)) {
4105 struct page *page = lru_to_page(head);
4106
4107 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4108 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4109 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4110 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4111
4112 new_gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004113 list_move_tail(&page->lru, &lrugen->pages[new_gen][type][zone]);
Yu Zhao4983c522022-09-18 02:00:09 -06004114
4115 if (!--remaining)
4116 return false;
4117 }
4118 }
4119done:
Yu Zhao37397872022-09-18 02:00:03 -06004120 reset_ctrl_pos(lruvec, type, true);
4121 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
Yu Zhao4983c522022-09-18 02:00:09 -06004122
4123 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004124}
4125
4126static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4127{
4128 int gen, type, zone;
4129 bool success = false;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004130 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004131 DEFINE_MIN_SEQ(lruvec);
4132
4133 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4134
4135 /* find the oldest populated generation */
4136 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4137 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4138 gen = lru_gen_from_seq(min_seq[type]);
4139
4140 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004141 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhao37397872022-09-18 02:00:03 -06004142 goto next;
4143 }
4144
4145 min_seq[type]++;
4146 }
4147next:
4148 ;
4149 }
4150
Yu Zhao3c6c3592022-12-21 21:18:59 -07004151 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06004152 if (can_swap) {
4153 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4154 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4155 }
4156
4157 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4158 if (min_seq[type] == lrugen->min_seq[type])
4159 continue;
4160
4161 reset_ctrl_pos(lruvec, type, true);
4162 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4163 success = true;
4164 }
4165
4166 return success;
4167}
4168
Yu Zhao4983c522022-09-18 02:00:09 -06004169static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
Yu Zhao37397872022-09-18 02:00:03 -06004170{
4171 int prev, next;
4172 int type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004173 struct lru_gen_page *lrugen = &lruvec->lrugen;
Kalesh Singh12fb1c32023-08-01 19:56:03 -07004174restart:
Yu Zhao37397872022-09-18 02:00:03 -06004175 spin_lock_irq(&lruvec->lru_lock);
4176
4177 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4178
Yu Zhao37397872022-09-18 02:00:03 -06004179 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4180 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4181 continue;
4182
Yu Zhao4983c522022-09-18 02:00:09 -06004183 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
Yu Zhao37397872022-09-18 02:00:03 -06004184
Kalesh Singh12fb1c32023-08-01 19:56:03 -07004185 if (inc_min_seq(lruvec, type, can_swap))
4186 continue;
4187
4188 spin_unlock_irq(&lruvec->lru_lock);
4189 cond_resched();
4190 goto restart;
Yu Zhao37397872022-09-18 02:00:03 -06004191 }
4192
4193 /*
4194 * Update the active/inactive LRU sizes for compatibility. Both sides of
4195 * the current max_seq need to be covered, since max_seq+1 can overlap
4196 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4197 * overlap, cold/hot inversion happens.
4198 */
4199 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4200 next = lru_gen_from_seq(lrugen->max_seq + 1);
4201
4202 for (type = 0; type < ANON_AND_FILE; type++) {
4203 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4204 enum lru_list lru = type * LRU_INACTIVE_FILE;
4205 long delta = lrugen->nr_pages[prev][type][zone] -
4206 lrugen->nr_pages[next][type][zone];
4207
4208 if (!delta)
4209 continue;
4210
4211 __update_lru_size(lruvec, lru, zone, delta);
4212 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4213 }
4214 }
4215
4216 for (type = 0; type < ANON_AND_FILE; type++)
4217 reset_ctrl_pos(lruvec, type, false);
4218
Yu Zhao430499c2022-09-18 02:00:08 -06004219 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhao37397872022-09-18 02:00:03 -06004220 /* make sure preceding modifications appear */
4221 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004222
Yu Zhao37397872022-09-18 02:00:03 -06004223 spin_unlock_irq(&lruvec->lru_lock);
4224}
4225
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004226static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
Yu Zhao4983c522022-09-18 02:00:09 -06004227 struct scan_control *sc, bool can_swap, bool force_scan)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004228{
4229 bool success;
4230 struct lru_gen_mm_walk *walk;
4231 struct mm_struct *mm = NULL;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004232 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004233
4234 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4235
4236 /* see the comment in iterate_mm_list() */
4237 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4238 success = false;
4239 goto done;
4240 }
4241
4242 /*
4243 * If the hardware doesn't automatically set the accessed bit, fallback
4244 * to lru_gen_look_around(), which only clears the accessed bit in a
4245 * handful of PTEs. Spreading the work out over a period of time usually
4246 * is less efficient, but it avoids bursty page faults.
4247 */
Yu Zhao18580ef2022-12-21 21:19:06 -07004248 if (!arch_has_hw_pte_young() || !get_cap(LRU_GEN_MM_WALK)) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004249 success = iterate_mm_list_nowalk(lruvec, max_seq);
4250 goto done;
4251 }
4252
Yu Zhaof8b57162022-12-21 21:19:05 -07004253 walk = set_mm_walk(NULL, true);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004254 if (!walk) {
4255 success = iterate_mm_list_nowalk(lruvec, max_seq);
4256 goto done;
4257 }
4258
4259 walk->lruvec = lruvec;
4260 walk->max_seq = max_seq;
4261 walk->can_swap = can_swap;
Yu Zhao4983c522022-09-18 02:00:09 -06004262 walk->force_scan = force_scan;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004263
4264 do {
4265 success = iterate_mm_list(lruvec, walk, &mm);
4266 if (mm)
4267 walk_mm(lruvec, mm, walk);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004268 } while (mm);
4269done:
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004270 if (success)
4271 inc_max_seq(lruvec, can_swap, force_scan);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004272
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004273 return success;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004274}
4275
Yu Zhaoa5998f92022-12-21 21:19:02 -07004276static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
Yu Zhao37397872022-09-18 02:00:03 -06004277{
Yu Zhaoa5998f92022-12-21 21:19:02 -07004278 int gen, type, zone;
4279 unsigned long total = 0;
4280 bool can_swap = get_swappiness(lruvec, sc);
4281 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004282 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4283 DEFINE_MAX_SEQ(lruvec);
4284 DEFINE_MIN_SEQ(lruvec);
4285
Yu Zhaoa5998f92022-12-21 21:19:02 -07004286 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4287 unsigned long seq;
4288
4289 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4290 gen = lru_gen_from_seq(seq);
4291
4292 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4293 total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4294 }
4295 }
4296
4297 /* whether the size is big enough to be helpful */
4298 return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4299}
4300
4301static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
4302 unsigned long min_ttl)
4303{
4304 int gen;
4305 unsigned long birth;
4306 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4307 DEFINE_MIN_SEQ(lruvec);
4308
Yu Zhaoa5998f92022-12-21 21:19:02 -07004309 /* see the comment on lru_gen_page */
4310 gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4311 birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4312
4313 if (time_is_after_jiffies(birth + min_ttl))
4314 return false;
4315
4316 if (!lruvec_is_sizable(lruvec, sc))
4317 return false;
4318
Yu Zhao37397872022-09-18 02:00:03 -06004319 mem_cgroup_calculate_protection(NULL, memcg);
4320
Yu Zhaoa5998f92022-12-21 21:19:02 -07004321 return !mem_cgroup_below_min(memcg);
Yu Zhao37397872022-09-18 02:00:03 -06004322}
4323
Yu Zhao430499c2022-09-18 02:00:08 -06004324/* to protect the working set of the last N jiffies */
4325static unsigned long lru_gen_min_ttl __read_mostly;
4326
Yu Zhao37397872022-09-18 02:00:03 -06004327static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4328{
4329 struct mem_cgroup *memcg;
Yu Zhao430499c2022-09-18 02:00:08 -06004330 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhao37397872022-09-18 02:00:03 -06004331
4332 VM_WARN_ON_ONCE(!current_is_kswapd());
4333
Yu Zhaoa5998f92022-12-21 21:19:02 -07004334 /* check the order to exclude compaction-induced reclaim */
4335 if (!min_ttl || sc->order || sc->priority == DEF_PRIORITY)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004336 return;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004337
Yu Zhao37397872022-09-18 02:00:03 -06004338 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4339 do {
4340 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4341
Yu Zhaoa5998f92022-12-21 21:19:02 -07004342 if (lruvec_is_reclaimable(lruvec, sc, min_ttl)) {
4343 mem_cgroup_iter_break(NULL, memcg);
4344 return;
4345 }
Yu Zhao37397872022-09-18 02:00:03 -06004346
4347 cond_resched();
4348 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004349
Yu Zhao430499c2022-09-18 02:00:08 -06004350 /*
4351 * The main goal is to OOM kill if every generation from all memcgs is
4352 * younger than min_ttl. However, another possibility is all memcgs are
Yu Zhaoa5998f92022-12-21 21:19:02 -07004353 * either too small or below min.
Yu Zhao430499c2022-09-18 02:00:08 -06004354 */
4355 if (mutex_trylock(&oom_lock)) {
4356 struct oom_control oc = {
4357 .gfp_mask = sc->gfp_mask,
4358 };
4359
4360 out_of_memory(&oc);
4361
4362 mutex_unlock(&oom_lock);
4363 }
Yu Zhao37397872022-09-18 02:00:03 -06004364}
4365
Yu Zhao0182f922022-09-18 02:00:04 -06004366/*
4367 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004368 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4369 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4370 * the PTE table to the Bloom filter. This forms a feedback loop between the
4371 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004372 */
4373void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4374{
4375 int i;
4376 pte_t *pte;
4377 unsigned long start;
4378 unsigned long end;
4379 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004380 struct lru_gen_mm_walk *walk;
4381 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004382 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4383 struct page *page = pvmw->page;
Kalesh Singh0f986fa2023-08-01 19:56:04 -07004384 bool can_swap = !page_is_file_lru(page);
Yu Zhao0182f922022-09-18 02:00:04 -06004385 struct mem_cgroup *memcg = page_memcg(page);
4386 struct pglist_data *pgdat = page_pgdat(page);
4387 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4388 DEFINE_MAX_SEQ(lruvec);
4389 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4390
4391 lockdep_assert_held(pvmw->ptl);
4392 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4393
4394 if (spin_is_contended(pvmw->ptl))
4395 return;
4396
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004397 /* avoid taking the LRU lock under the PTL when possible */
4398 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4399
Yu Zhao0182f922022-09-18 02:00:04 -06004400 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4401 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4402
4403 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4404 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4405 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4406 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4407 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4408 else {
4409 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4410 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4411 }
4412 }
4413
4414 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4415
4416 rcu_read_lock();
4417 arch_enter_lazy_mmu_mode();
4418
4419 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4420 unsigned long pfn;
4421
4422 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4423 if (pfn == -1)
4424 continue;
4425
4426 if (!pte_young(pte[i]))
4427 continue;
4428
Kalesh Singh0f986fa2023-08-01 19:56:04 -07004429 page = get_pfn_page(pfn, memcg, pgdat, can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004430 if (!page)
4431 continue;
4432
4433 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4434 VM_WARN_ON_ONCE(true);
4435
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004436 young++;
4437
Yu Zhao0182f922022-09-18 02:00:04 -06004438 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4439 !(PageAnon(page) && PageSwapBacked(page) &&
4440 !PageSwapCache(page)))
4441 set_page_dirty(page);
4442
4443 old_gen = page_lru_gen(page);
4444 if (old_gen < 0)
4445 SetPageReferenced(page);
4446 else if (old_gen != new_gen)
4447 __set_bit(i, bitmap);
4448 }
4449
4450 arch_leave_lazy_mmu_mode();
4451 rcu_read_unlock();
4452
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004453 /* feedback from rmap walkers to page table walkers */
4454 if (suitable_to_scan(i, young))
4455 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4456
4457 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004458 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4459 page = pte_page(pte[i]);
4460 activate_page(page);
4461 }
4462 return;
4463 }
4464
4465 /* page_update_gen() requires stable page_memcg() */
4466 if (!mem_cgroup_trylock_pages(memcg))
4467 return;
4468
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004469 if (!walk) {
4470 spin_lock_irq(&lruvec->lru_lock);
4471 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4472 }
Yu Zhao0182f922022-09-18 02:00:04 -06004473
4474 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4475 page = compound_head(pte_page(pte[i]));
4476 if (page_memcg_rcu(page) != memcg)
4477 continue;
4478
4479 old_gen = page_update_gen(page, new_gen);
4480 if (old_gen < 0 || old_gen == new_gen)
4481 continue;
4482
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004483 if (walk)
4484 update_batch_size(walk, page, old_gen, new_gen);
4485 else
4486 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004487 }
4488
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004489 if (!walk)
4490 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004491
4492 mem_cgroup_unlock_pages();
4493}
4494
Yu Zhao37397872022-09-18 02:00:03 -06004495/******************************************************************************
4496 * the eviction
4497 ******************************************************************************/
4498
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004499static bool sort_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc,
4500 int tier_idx)
Yu Zhao37397872022-09-18 02:00:03 -06004501{
4502 bool success;
4503 int gen = page_lru_gen(page);
4504 int type = page_is_file_lru(page);
4505 int zone = page_zonenum(page);
4506 int delta = thp_nr_pages(page);
4507 int refs = page_lru_refs(page);
4508 int tier = lru_tier_from_refs(refs);
Yu Zhao3c6c3592022-12-21 21:18:59 -07004509 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004510
4511 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4512
4513 /* unevictable */
4514 if (!page_evictable(page)) {
4515 success = lru_gen_del_page(lruvec, page, true);
4516 VM_WARN_ON_ONCE_PAGE(!success, page);
4517 SetPageUnevictable(page);
4518 add_page_to_lru_list(page, lruvec);
4519 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4520 return true;
4521 }
4522
4523 /* dirty lazyfree */
4524 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4525 success = lru_gen_del_page(lruvec, page, true);
4526 VM_WARN_ON_ONCE_PAGE(!success, page);
4527 SetPageSwapBacked(page);
4528 add_page_to_lru_list_tail(page, lruvec);
4529 return true;
4530 }
4531
Yu Zhao0182f922022-09-18 02:00:04 -06004532 /* promoted */
4533 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004534 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao0182f922022-09-18 02:00:04 -06004535 return true;
4536 }
4537
Yu Zhao37397872022-09-18 02:00:03 -06004538 /* protected */
4539 if (tier > tier_idx) {
4540 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4541
4542 gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004543 list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004544
4545 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4546 lrugen->protected[hist][type][tier - 1] + delta);
Yu Zhao37397872022-09-18 02:00:03 -06004547 return true;
4548 }
4549
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004550 /* ineligible */
Charan Teja Kallaa8455252023-08-09 13:35:44 +05304551 if (zone > sc->reclaim_idx || skip_cma(page, sc)) {
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004552 gen = page_inc_gen(lruvec, page, false);
4553 list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
4554 return true;
4555 }
4556
Yu Zhao37397872022-09-18 02:00:03 -06004557 /* waiting for writeback */
4558 if (PageLocked(page) || PageWriteback(page) ||
4559 (type == LRU_GEN_FILE && PageDirty(page))) {
4560 gen = page_inc_gen(lruvec, page, true);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004561 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004562 return true;
4563 }
4564
4565 return false;
4566}
4567
4568static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4569{
4570 bool success;
4571
Yu Zhao37397872022-09-18 02:00:03 -06004572 /* swapping inhibited */
Yu Zhaof8b57162022-12-21 21:19:05 -07004573 if (!(sc->gfp_mask & __GFP_IO) &&
Yu Zhao37397872022-09-18 02:00:03 -06004574 (PageDirty(page) ||
4575 (PageAnon(page) && !PageSwapCache(page))))
4576 return false;
4577
4578 /* raced with release_pages() */
4579 if (!get_page_unless_zero(page))
4580 return false;
4581
4582 /* raced with another isolation */
4583 if (!TestClearPageLRU(page)) {
4584 put_page(page);
4585 return false;
4586 }
4587
4588 /* see the comment on MAX_NR_TIERS */
4589 if (!PageReferenced(page))
4590 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4591
4592 /* for shrink_page_list() */
4593 ClearPageReclaim(page);
4594 ClearPageReferenced(page);
4595
4596 success = lru_gen_del_page(lruvec, page, true);
4597 VM_WARN_ON_ONCE_PAGE(!success, page);
4598
4599 return true;
4600}
4601
4602static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4603 int type, int tier, struct list_head *list)
4604{
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004605 int i;
4606 int gen;
Yu Zhao37397872022-09-18 02:00:03 -06004607 enum vm_event_item item;
4608 int sorted = 0;
4609 int scanned = 0;
4610 int isolated = 0;
4611 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004612 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004613 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4614
4615 VM_WARN_ON_ONCE(!list_empty(list));
4616
4617 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4618 return 0;
4619
4620 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4621
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004622 for (i = MAX_NR_ZONES; i > 0; i--) {
Yu Zhao37397872022-09-18 02:00:03 -06004623 LIST_HEAD(moved);
4624 int skipped = 0;
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004625 int zone = (sc->reclaim_idx + i) % MAX_NR_ZONES;
Yu Zhaodf91dc92022-12-21 21:19:00 -07004626 struct list_head *head = &lrugen->pages[gen][type][zone];
Yu Zhao37397872022-09-18 02:00:03 -06004627
4628 while (!list_empty(head)) {
4629 struct page *page = lru_to_page(head);
4630 int delta = thp_nr_pages(page);
4631
4632 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4633 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4634 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4635 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4636
4637 scanned += delta;
4638
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004639 if (sort_page(lruvec, page, sc, tier))
Yu Zhao37397872022-09-18 02:00:03 -06004640 sorted += delta;
4641 else if (isolate_page(lruvec, page, sc)) {
4642 list_add(&page->lru, list);
4643 isolated += delta;
4644 } else {
4645 list_move(&page->lru, &moved);
4646 skipped += delta;
4647 }
4648
4649 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4650 break;
4651 }
4652
4653 if (skipped) {
4654 list_splice(&moved, head);
4655 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4656 }
4657
4658 if (!remaining || isolated >= MIN_LRU_BATCH)
4659 break;
4660 }
4661
4662 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4663 if (!cgroup_reclaim(sc)) {
4664 __count_vm_events(item, isolated);
4665 __count_vm_events(PGREFILL, sorted);
4666 }
4667 __count_memcg_events(memcg, item, isolated);
4668 __count_memcg_events(memcg, PGREFILL, sorted);
4669 __count_vm_events(PGSCAN_ANON + type, isolated);
4670
4671 /*
Yu Zhaof8b57162022-12-21 21:19:05 -07004672 * There might not be eligible pages due to reclaim_idx. Check the
4673 * remaining to prevent livelock if it's not making progress.
Yu Zhao37397872022-09-18 02:00:03 -06004674 */
4675 return isolated || !remaining ? scanned : 0;
4676}
4677
4678static int get_tier_idx(struct lruvec *lruvec, int type)
4679{
4680 int tier;
4681 struct ctrl_pos sp, pv;
4682
4683 /*
4684 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4685 * This value is chosen because any other tier would have at least twice
4686 * as many refaults as the first tier.
4687 */
4688 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4689 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4690 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4691 if (!positive_ctrl_err(&sp, &pv))
4692 break;
4693 }
4694
4695 return tier - 1;
4696}
4697
4698static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4699{
4700 int type, tier;
4701 struct ctrl_pos sp, pv;
4702 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4703
4704 /*
4705 * Compare the first tier of anon with that of file to determine which
4706 * type to scan. Also need to compare other tiers of the selected type
4707 * with the first tier of the other type to determine the last tier (of
4708 * the selected type) to evict.
4709 */
4710 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4711 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4712 type = positive_ctrl_err(&sp, &pv);
4713
4714 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4715 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4716 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4717 if (!positive_ctrl_err(&sp, &pv))
4718 break;
4719 }
4720
4721 *tier_idx = tier - 1;
4722
4723 return type;
4724}
4725
4726static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4727 int *type_scanned, struct list_head *list)
4728{
4729 int i;
4730 int type;
4731 int scanned;
4732 int tier = -1;
4733 DEFINE_MIN_SEQ(lruvec);
4734
4735 /*
4736 * Try to make the obvious choice first. When anon and file are both
4737 * available from the same generation, interpret swappiness 1 as file
4738 * first and 200 as anon first.
4739 */
4740 if (!swappiness)
4741 type = LRU_GEN_FILE;
4742 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4743 type = LRU_GEN_ANON;
4744 else if (swappiness == 1)
4745 type = LRU_GEN_FILE;
4746 else if (swappiness == 200)
4747 type = LRU_GEN_ANON;
4748 else
4749 type = get_type_to_scan(lruvec, swappiness, &tier);
4750
4751 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4752 if (tier < 0)
4753 tier = get_tier_idx(lruvec, type);
4754
4755 scanned = scan_pages(lruvec, sc, type, tier, list);
4756 if (scanned)
4757 break;
4758
4759 type = !type;
4760 tier = -1;
4761 }
4762
4763 *type_scanned = type;
4764
4765 return scanned;
4766}
4767
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004768static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
Yu Zhao37397872022-09-18 02:00:03 -06004769{
4770 int type;
4771 int scanned;
4772 int reclaimed;
4773 LIST_HEAD(list);
Yu Zhao79e66ea2022-11-15 18:38:07 -07004774 LIST_HEAD(clean);
Yu Zhao37397872022-09-18 02:00:03 -06004775 struct page *page;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004776 struct page *next;
Yu Zhao37397872022-09-18 02:00:03 -06004777 enum vm_event_item item;
4778 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004779 struct lru_gen_mm_walk *walk;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004780 bool skip_retry = false;
Yu Zhao37397872022-09-18 02:00:03 -06004781 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4782 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4783
4784 spin_lock_irq(&lruvec->lru_lock);
4785
4786 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4787
4788 scanned += try_to_inc_min_seq(lruvec, swappiness);
4789
4790 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4791 scanned = 0;
4792
4793 spin_unlock_irq(&lruvec->lru_lock);
4794
4795 if (list_empty(&list))
4796 return scanned;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004797retry:
Yu Zhao37397872022-09-18 02:00:03 -06004798 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
Yu Zhao79e66ea2022-11-15 18:38:07 -07004799 sc->nr_reclaimed += reclaimed;
Yu Zhao37397872022-09-18 02:00:03 -06004800
Yu Zhao79e66ea2022-11-15 18:38:07 -07004801 list_for_each_entry_safe_reverse(page, next, &list, lru) {
4802 if (!page_evictable(page)) {
4803 list_del(&page->lru);
4804 putback_lru_page(page);
4805 continue;
4806 }
Yu Zhao37397872022-09-18 02:00:03 -06004807
Yu Zhao37397872022-09-18 02:00:03 -06004808 if (PageReclaim(page) &&
Yu Zhao79e66ea2022-11-15 18:38:07 -07004809 (PageDirty(page) || PageWriteback(page))) {
4810 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4811 if (PageWorkingset(page))
4812 SetPageReferenced(page);
4813 continue;
4814 }
4815
4816 if (skip_retry || PageActive(page) || PageReferenced(page) ||
4817 page_mapped(page) || PageLocked(page) ||
4818 PageDirty(page) || PageWriteback(page)) {
4819 /* don't add rejected pages to the oldest generation */
4820 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
4821 BIT(PG_active));
4822 continue;
4823 }
4824
4825 /* retry pages that may have missed rotate_reclaimable_page() */
4826 list_move(&page->lru, &clean);
4827 sc->nr_scanned -= thp_nr_pages(page);
Yu Zhao37397872022-09-18 02:00:03 -06004828 }
4829
4830 spin_lock_irq(&lruvec->lru_lock);
4831
4832 move_pages_to_lru(lruvec, &list);
4833
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004834 walk = current->reclaim_state->mm_walk;
4835 if (walk && walk->batched)
4836 reset_batch_size(lruvec, walk);
4837
Yu Zhao37397872022-09-18 02:00:03 -06004838 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4839 if (!cgroup_reclaim(sc))
4840 __count_vm_events(item, reclaimed);
4841 __count_memcg_events(memcg, item, reclaimed);
4842 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4843
4844 spin_unlock_irq(&lruvec->lru_lock);
4845
4846 mem_cgroup_uncharge_list(&list);
4847 free_unref_page_list(&list);
4848
Yu Zhao79e66ea2022-11-15 18:38:07 -07004849 INIT_LIST_HEAD(&list);
4850 list_splice_init(&clean, &list);
4851
4852 if (!list_empty(&list)) {
4853 skip_retry = true;
4854 goto retry;
4855 }
Yu Zhao37397872022-09-18 02:00:03 -06004856
4857 return scanned;
4858}
4859
Yu Zhaocb3958d2022-12-21 21:19:03 -07004860static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
4861 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4862{
4863 int gen, type, zone;
4864 unsigned long old = 0;
4865 unsigned long young = 0;
4866 unsigned long total = 0;
4867 struct lru_gen_page *lrugen = &lruvec->lrugen;
4868 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4869 DEFINE_MIN_SEQ(lruvec);
4870
4871 /* whether this lruvec is completely out of cold pages */
4872 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
4873 *nr_to_scan = 0;
4874 return true;
4875 }
4876
4877 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4878 unsigned long seq;
4879
4880 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4881 unsigned long size = 0;
4882
4883 gen = lru_gen_from_seq(seq);
4884
4885 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4886 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4887
4888 total += size;
4889 if (seq == max_seq)
4890 young += size;
4891 else if (seq + MIN_NR_GENS == max_seq)
4892 old += size;
4893 }
4894 }
4895
4896 /* try to scrape all its memory if this memcg was deleted */
4897 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4898
4899 /*
4900 * The aging tries to be lazy to reduce the overhead, while the eviction
4901 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4902 * ideal number of generations is MIN_NR_GENS+1.
4903 */
4904 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4905 return false;
4906
4907 /*
4908 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4909 * of the total number of pages for each generation. A reasonable range
4910 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4911 * aging cares about the upper bound of hot pages, while the eviction
4912 * cares about the lower bound of cold pages.
4913 */
4914 if (young * MIN_NR_GENS > total)
4915 return true;
4916 if (old * (MIN_NR_GENS + 2) < total)
4917 return true;
4918
4919 return false;
4920}
4921
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004922/*
4923 * For future optimizations:
4924 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4925 * reclaim.
4926 */
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004927static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004928{
Yu Zhao37397872022-09-18 02:00:03 -06004929 unsigned long nr_to_scan;
4930 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4931 DEFINE_MAX_SEQ(lruvec);
Yu Zhao37397872022-09-18 02:00:03 -06004932
Yu Zhaof8b57162022-12-21 21:19:05 -07004933 if (mem_cgroup_below_min(memcg))
Yu Zhao37397872022-09-18 02:00:03 -06004934 return 0;
4935
Yu Zhaoa5998f92022-12-21 21:19:02 -07004936 if (!should_run_aging(lruvec, max_seq, sc, can_swap, &nr_to_scan))
Yu Zhao37397872022-09-18 02:00:03 -06004937 return nr_to_scan;
4938
4939 /* skip the aging path at the default priority */
4940 if (sc->priority == DEF_PRIORITY)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004941 return nr_to_scan;
Yu Zhaoa5998f92022-12-21 21:19:02 -07004942
Yu Zhaoa5998f92022-12-21 21:19:02 -07004943 /* skip this lruvec as it's low on cold pages */
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004944 return try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false) ? -1 : 0;
Yu Zhao37397872022-09-18 02:00:03 -06004945}
4946
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004947static unsigned long get_nr_to_reclaim(struct scan_control *sc)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004948{
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004949 /* don't abort memcg reclaim to ensure fairness */
4950 if (!global_reclaim(sc))
4951 return -1;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004952
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004953 return max(sc->nr_to_reclaim, compact_gap(sc->order));
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004954}
4955
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004956static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Yu Zhao37397872022-09-18 02:00:03 -06004957{
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004958 long nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004959 unsigned long scanned = 0;
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004960 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
Yu Zhaof8b57162022-12-21 21:19:05 -07004961 int swappiness = get_swappiness(lruvec, sc);
4962
4963 /* clean file pages are more likely to exist */
4964 if (swappiness && !(sc->gfp_mask & __GFP_IO))
4965 swappiness = 1;
Yu Zhao37397872022-09-18 02:00:03 -06004966
Yu Zhao37397872022-09-18 02:00:03 -06004967 while (true) {
4968 int delta;
Yu Zhao37397872022-09-18 02:00:03 -06004969
Yu Zhaoa5998f92022-12-21 21:19:02 -07004970 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004971 if (nr_to_scan <= 0)
Yu Zhaoa5998f92022-12-21 21:19:02 -07004972 break;
Yu Zhao37397872022-09-18 02:00:03 -06004973
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004974 delta = evict_pages(lruvec, sc, swappiness);
Yu Zhao37397872022-09-18 02:00:03 -06004975 if (!delta)
Yu Zhaoa5998f92022-12-21 21:19:02 -07004976 break;
Yu Zhao37397872022-09-18 02:00:03 -06004977
4978 scanned += delta;
4979 if (scanned >= nr_to_scan)
4980 break;
4981
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004982 if (sc->nr_reclaimed >= nr_to_reclaim)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004983 break;
4984
Yu Zhao37397872022-09-18 02:00:03 -06004985 cond_resched();
4986 }
4987
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004988 /* whether try_to_inc_max_seq() was successful */
4989 return nr_to_scan < 0;
4990}
4991
4992static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
4993{
4994 bool success;
4995 unsigned long scanned = sc->nr_scanned;
4996 unsigned long reclaimed = sc->nr_reclaimed;
4997 int seg = lru_gen_memcg_seg(lruvec);
4998 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4999 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5000
5001 /* see the comment on MEMCG_NR_GENS */
5002 if (!lruvec_is_sizable(lruvec, sc))
5003 return seg != MEMCG_LRU_TAIL ? MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG;
5004
5005 mem_cgroup_calculate_protection(NULL, memcg);
5006
5007 if (mem_cgroup_below_min(memcg))
5008 return MEMCG_LRU_YOUNG;
5009
5010 if (mem_cgroup_below_low(memcg)) {
5011 /* see the comment on MEMCG_NR_GENS */
5012 if (seg != MEMCG_LRU_TAIL)
5013 return MEMCG_LRU_TAIL;
5014
5015 memcg_memory_event(memcg, MEMCG_LOW);
5016 }
5017
5018 success = try_to_shrink_lruvec(lruvec, sc);
5019
5020 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority);
5021
5022 vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned,
5023 sc->nr_reclaimed - reclaimed);
5024
5025 sc->nr_reclaimed += current->reclaim_state->reclaimed_slab;
5026 current->reclaim_state->reclaimed_slab = 0;
5027
5028 return success ? MEMCG_LRU_YOUNG : 0;
5029}
5030
5031#ifdef CONFIG_MEMCG
5032
5033static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5034{
Yu Zhaof7909cb2023-02-13 00:53:22 -07005035 int op;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005036 int gen;
5037 int bin;
5038 int first_bin;
5039 struct lruvec *lruvec;
5040 struct lru_gen_page *lrugen;
Yu Zhaof7909cb2023-02-13 00:53:22 -07005041 struct mem_cgroup *memcg;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005042 const struct hlist_nulls_node *pos;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005043 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
5044
5045 bin = first_bin = prandom_u32_max(MEMCG_NR_BINS);
5046restart:
Yu Zhaof7909cb2023-02-13 00:53:22 -07005047 op = 0;
5048 memcg = NULL;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005049 gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq));
5050
5051 rcu_read_lock();
5052
5053 hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) {
5054 if (op)
5055 lru_gen_rotate_memcg(lruvec, op);
5056
5057 mem_cgroup_put(memcg);
5058
5059 lruvec = container_of(lrugen, struct lruvec, lrugen);
5060 memcg = lruvec_memcg(lruvec);
5061
5062 if (!mem_cgroup_tryget(memcg)) {
5063 op = 0;
5064 memcg = NULL;
5065 continue;
5066 }
5067
5068 rcu_read_unlock();
5069
5070 op = shrink_one(lruvec, sc);
5071
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005072 rcu_read_lock();
Yu Zhaof7909cb2023-02-13 00:53:22 -07005073
5074 if (sc->nr_reclaimed >= nr_to_reclaim)
5075 break;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005076 }
5077
5078 rcu_read_unlock();
5079
Yu Zhaof7909cb2023-02-13 00:53:22 -07005080 if (op)
5081 lru_gen_rotate_memcg(lruvec, op);
5082
5083 mem_cgroup_put(memcg);
5084
5085 if (sc->nr_reclaimed >= nr_to_reclaim)
5086 return;
5087
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005088 /* restart if raced with lru_gen_rotate_memcg() */
5089 if (gen != get_nulls_value(pos))
5090 goto restart;
5091
5092 /* try the rest of the bins of the current generation */
5093 bin = get_memcg_bin(bin + 1);
5094 if (bin != first_bin)
5095 goto restart;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005096}
5097
5098static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5099{
5100 struct blk_plug plug;
5101
5102 VM_WARN_ON_ONCE(global_reclaim(sc));
Yu Zhaof8b57162022-12-21 21:19:05 -07005103 VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005104
5105 lru_add_drain();
5106
5107 blk_start_plug(&plug);
5108
Yu Zhaof8b57162022-12-21 21:19:05 -07005109 set_mm_walk(NULL, false);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005110
5111 if (try_to_shrink_lruvec(lruvec, sc))
5112 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG);
5113
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005114 clear_mm_walk();
5115
Yu Zhao37397872022-09-18 02:00:03 -06005116 blk_finish_plug(&plug);
5117}
5118
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005119#else /* !CONFIG_MEMCG */
5120
5121static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5122{
5123 BUILD_BUG();
5124}
5125
5126static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5127{
5128 BUILD_BUG();
5129}
5130
5131#endif
5132
5133static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc)
5134{
5135 int priority;
5136 unsigned long reclaimable;
5137 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5138
5139 if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH)
5140 return;
5141 /*
5142 * Determine the initial priority based on ((total / MEMCG_NR_GENS) >>
5143 * priority) * reclaimed_to_scanned_ratio = nr_to_reclaim, where the
5144 * estimated reclaimed_to_scanned_ratio = inactive / total.
5145 */
5146 reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE);
5147 if (get_swappiness(lruvec, sc))
5148 reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON);
5149
5150 reclaimable /= MEMCG_NR_GENS;
5151
5152 /* round down reclaimable and round up sc->nr_to_reclaim */
5153 priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1);
5154
5155 sc->priority = clamp(priority, 0, DEF_PRIORITY);
5156}
5157
5158static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5159{
5160 struct blk_plug plug;
5161 unsigned long reclaimed = sc->nr_reclaimed;
5162
5163 VM_WARN_ON_ONCE(!global_reclaim(sc));
5164
Yu Zhaof8b57162022-12-21 21:19:05 -07005165 /*
5166 * Unmapped clean pages are already prioritized. Scanning for more of
5167 * them is likely futile and can cause high reclaim latency when there
5168 * is a large number of memcgs.
5169 */
5170 if (!sc->may_writepage || !sc->may_unmap)
5171 goto done;
5172
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005173 lru_add_drain();
5174
5175 blk_start_plug(&plug);
5176
Yu Zhaof8b57162022-12-21 21:19:05 -07005177 set_mm_walk(pgdat, false);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005178
5179 set_initial_priority(pgdat, sc);
5180
5181 if (current_is_kswapd())
5182 sc->nr_reclaimed = 0;
5183
5184 if (mem_cgroup_disabled())
5185 shrink_one(&pgdat->__lruvec, sc);
5186 else
5187 shrink_many(pgdat, sc);
5188
5189 if (current_is_kswapd())
5190 sc->nr_reclaimed += reclaimed;
5191
5192 clear_mm_walk();
5193
5194 blk_finish_plug(&plug);
Yu Zhaof8b57162022-12-21 21:19:05 -07005195done:
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005196 /* kswapd should never fail */
5197 pgdat->kswapd_failures = 0;
5198}
5199
5200#ifdef CONFIG_MEMCG
5201void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
5202{
5203 int seg;
5204 int old, new;
5205 int bin = prandom_u32_max(MEMCG_NR_BINS);
5206 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5207
5208 spin_lock(&pgdat->memcg_lru.lock);
5209
5210 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
5211
5212 seg = 0;
5213 new = old = lruvec->lrugen.gen;
5214
5215 /* see the comment on MEMCG_NR_GENS */
5216 if (op == MEMCG_LRU_HEAD)
5217 seg = MEMCG_LRU_HEAD;
5218 else if (op == MEMCG_LRU_TAIL)
5219 seg = MEMCG_LRU_TAIL;
5220 else if (op == MEMCG_LRU_OLD)
5221 new = get_memcg_gen(pgdat->memcg_lru.seq);
5222 else if (op == MEMCG_LRU_YOUNG)
5223 new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
5224 else
5225 VM_WARN_ON_ONCE(true);
5226
5227 hlist_nulls_del_rcu(&lruvec->lrugen.list);
5228
5229 if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
5230 hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
5231 else
5232 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
5233
5234 pgdat->memcg_lru.nr_memcgs[old]--;
5235 pgdat->memcg_lru.nr_memcgs[new]++;
5236
5237 lruvec->lrugen.gen = new;
5238 WRITE_ONCE(lruvec->lrugen.seg, seg);
5239
5240 if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
5241 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
5242
5243 spin_unlock(&pgdat->memcg_lru.lock);
5244}
5245#endif
5246
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005247/******************************************************************************
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005248 * state change
5249 ******************************************************************************/
5250
5251static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5252{
Yu Zhao3c6c3592022-12-21 21:18:59 -07005253 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005254
5255 if (lrugen->enabled) {
5256 enum lru_list lru;
5257
5258 for_each_evictable_lru(lru) {
5259 if (!list_empty(&lruvec->lists[lru]))
5260 return false;
5261 }
5262 } else {
5263 int gen, type, zone;
5264
5265 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005266 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005267 return false;
5268 }
5269 }
5270
5271 return true;
5272}
5273
5274static bool fill_evictable(struct lruvec *lruvec)
5275{
5276 enum lru_list lru;
5277 int remaining = MAX_LRU_BATCH;
5278
5279 for_each_evictable_lru(lru) {
5280 int type = is_file_lru(lru);
5281 bool active = is_active_lru(lru);
5282 struct list_head *head = &lruvec->lists[lru];
5283
5284 while (!list_empty(head)) {
5285 bool success;
5286 struct page *page = lru_to_page(head);
5287
5288 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5289 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
5290 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5291 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
5292
5293 del_page_from_lru_list(page, lruvec);
5294 success = lru_gen_add_page(lruvec, page, false);
5295 VM_WARN_ON_ONCE(!success);
5296
5297 if (!--remaining)
5298 return false;
5299 }
5300 }
5301
5302 return true;
5303}
5304
5305static bool drain_evictable(struct lruvec *lruvec)
5306{
5307 int gen, type, zone;
5308 int remaining = MAX_LRU_BATCH;
5309
5310 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005311 struct list_head *head = &lruvec->lrugen.pages[gen][type][zone];
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005312
5313 while (!list_empty(head)) {
5314 bool success;
5315 struct page *page = lru_to_page(head);
5316
5317 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5318 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5319 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5320 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5321
5322 success = lru_gen_del_page(lruvec, page, false);
5323 VM_WARN_ON_ONCE(!success);
5324 add_page_to_lru_list(page, lruvec);
5325
5326 if (!--remaining)
5327 return false;
5328 }
5329 }
5330
5331 return true;
5332}
5333
5334static void lru_gen_change_state(bool enabled)
5335{
5336 static DEFINE_MUTEX(state_mutex);
5337
5338 struct mem_cgroup *memcg;
5339
5340 cgroup_lock();
5341 cpus_read_lock();
5342 get_online_mems();
5343 mutex_lock(&state_mutex);
5344
5345 if (enabled == lru_gen_enabled())
5346 goto unlock;
5347
5348 if (enabled)
5349 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5350 else
5351 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5352
5353 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5354 do {
5355 int nid;
5356
5357 for_each_node(nid) {
5358 struct lruvec *lruvec = get_lruvec(memcg, nid);
5359
5360 if (!lruvec)
5361 continue;
5362
5363 spin_lock_irq(&lruvec->lru_lock);
5364
5365 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5366 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5367
5368 lruvec->lrugen.enabled = enabled;
5369
5370 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5371 spin_unlock_irq(&lruvec->lru_lock);
5372 cond_resched();
5373 spin_lock_irq(&lruvec->lru_lock);
5374 }
5375
5376 spin_unlock_irq(&lruvec->lru_lock);
5377 }
5378
5379 cond_resched();
5380 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5381unlock:
5382 mutex_unlock(&state_mutex);
5383 put_online_mems();
5384 cpus_read_unlock();
5385 cgroup_unlock();
5386}
5387
5388/******************************************************************************
5389 * sysfs interface
5390 ******************************************************************************/
5391
Yu Zhao430499c2022-09-18 02:00:08 -06005392static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5393{
5394 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5395}
5396
Yu Zhao642d9862022-09-18 02:00:10 -06005397/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao430499c2022-09-18 02:00:08 -06005398static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5399 const char *buf, size_t len)
5400{
5401 unsigned int msecs;
5402
5403 if (kstrtouint(buf, 0, &msecs))
5404 return -EINVAL;
5405
5406 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5407
5408 return len;
5409}
5410
5411static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5412 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5413);
5414
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005415static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5416{
5417 unsigned int caps = 0;
5418
5419 if (get_cap(LRU_GEN_CORE))
5420 caps |= BIT(LRU_GEN_CORE);
5421
5422 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5423 caps |= BIT(LRU_GEN_MM_WALK);
5424
Juergen Gross23811792022-11-23 07:45:10 +01005425 if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005426 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5427
5428 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5429}
5430
Yu Zhao642d9862022-09-18 02:00:10 -06005431/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005432static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5433 const char *buf, size_t len)
5434{
5435 int i;
5436 unsigned int caps;
5437
5438 if (tolower(*buf) == 'n')
5439 caps = 0;
5440 else if (tolower(*buf) == 'y')
5441 caps = -1;
5442 else if (kstrtouint(buf, 0, &caps))
5443 return -EINVAL;
5444
5445 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5446 bool enabled = caps & BIT(i);
5447
5448 if (i == LRU_GEN_CORE)
5449 lru_gen_change_state(enabled);
5450 else if (enabled)
5451 static_branch_enable(&lru_gen_caps[i]);
5452 else
5453 static_branch_disable(&lru_gen_caps[i]);
5454 }
5455
5456 return len;
5457}
5458
5459static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5460 enabled, 0644, show_enabled, store_enabled
5461);
5462
5463static struct attribute *lru_gen_attrs[] = {
Yu Zhao430499c2022-09-18 02:00:08 -06005464 &lru_gen_min_ttl_attr.attr,
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005465 &lru_gen_enabled_attr.attr,
5466 NULL
5467};
5468
5469static struct attribute_group lru_gen_attr_group = {
5470 .name = "lru_gen",
5471 .attrs = lru_gen_attrs,
5472};
5473
5474/******************************************************************************
Yu Zhao4983c522022-09-18 02:00:09 -06005475 * debugfs interface
5476 ******************************************************************************/
5477
5478static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5479{
5480 struct mem_cgroup *memcg;
5481 loff_t nr_to_skip = *pos;
5482
5483 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5484 if (!m->private)
5485 return ERR_PTR(-ENOMEM);
5486
5487 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5488 do {
5489 int nid;
5490
5491 for_each_node_state(nid, N_MEMORY) {
5492 if (!nr_to_skip--)
5493 return get_lruvec(memcg, nid);
5494 }
5495 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5496
5497 return NULL;
5498}
5499
5500static void lru_gen_seq_stop(struct seq_file *m, void *v)
5501{
5502 if (!IS_ERR_OR_NULL(v))
5503 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5504
5505 kvfree(m->private);
5506 m->private = NULL;
5507}
5508
5509static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5510{
5511 int nid = lruvec_pgdat(v)->node_id;
5512 struct mem_cgroup *memcg = lruvec_memcg(v);
5513
5514 ++*pos;
5515
5516 nid = next_memory_node(nid);
5517 if (nid == MAX_NUMNODES) {
5518 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5519 if (!memcg)
5520 return NULL;
5521
5522 nid = first_memory_node;
5523 }
5524
5525 return get_lruvec(memcg, nid);
5526}
5527
5528static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5529 unsigned long max_seq, unsigned long *min_seq,
5530 unsigned long seq)
5531{
5532 int i;
5533 int type, tier;
5534 int hist = lru_hist_from_seq(seq);
Yu Zhao3c6c3592022-12-21 21:18:59 -07005535 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005536
5537 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5538 seq_printf(m, " %10d", tier);
5539 for (type = 0; type < ANON_AND_FILE; type++) {
5540 const char *s = " ";
5541 unsigned long n[3] = {};
5542
5543 if (seq == max_seq) {
5544 s = "RT ";
5545 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5546 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5547 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5548 s = "rep";
5549 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5550 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5551 if (tier)
5552 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5553 }
5554
5555 for (i = 0; i < 3; i++)
5556 seq_printf(m, " %10lu%c", n[i], s[i]);
5557 }
5558 seq_putc(m, '\n');
5559 }
5560
5561 seq_puts(m, " ");
5562 for (i = 0; i < NR_MM_STATS; i++) {
5563 const char *s = " ";
5564 unsigned long n = 0;
5565
5566 if (seq == max_seq && NR_HIST_GENS == 1) {
5567 s = "LOYNFA";
5568 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5569 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5570 s = "loynfa";
5571 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5572 }
5573
5574 seq_printf(m, " %10lu%c", n, s[i]);
5575 }
5576 seq_putc(m, '\n');
5577}
5578
Yu Zhao642d9862022-09-18 02:00:10 -06005579/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005580static int lru_gen_seq_show(struct seq_file *m, void *v)
5581{
5582 unsigned long seq;
5583 bool full = !debugfs_real_fops(m->file)->write;
5584 struct lruvec *lruvec = v;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005585 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005586 int nid = lruvec_pgdat(lruvec)->node_id;
5587 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5588 DEFINE_MAX_SEQ(lruvec);
5589 DEFINE_MIN_SEQ(lruvec);
5590
5591 if (nid == first_memory_node) {
5592 const char *path = memcg ? m->private : "";
5593
5594#ifdef CONFIG_MEMCG
5595 if (memcg)
5596 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5597#endif
5598 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5599 }
5600
5601 seq_printf(m, " node %5d\n", nid);
5602
5603 if (!full)
5604 seq = min_seq[LRU_GEN_ANON];
5605 else if (max_seq >= MAX_NR_GENS)
5606 seq = max_seq - MAX_NR_GENS + 1;
5607 else
5608 seq = 0;
5609
5610 for (; seq <= max_seq; seq++) {
5611 int type, zone;
5612 int gen = lru_gen_from_seq(seq);
5613 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5614
5615 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5616
5617 for (type = 0; type < ANON_AND_FILE; type++) {
5618 unsigned long size = 0;
5619 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5620
5621 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5622 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5623
5624 seq_printf(m, " %10lu%c", size, mark);
5625 }
5626
5627 seq_putc(m, '\n');
5628
5629 if (full)
5630 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5631 }
5632
5633 return 0;
5634}
5635
5636static const struct seq_operations lru_gen_seq_ops = {
5637 .start = lru_gen_seq_start,
5638 .stop = lru_gen_seq_stop,
5639 .next = lru_gen_seq_next,
5640 .show = lru_gen_seq_show,
5641};
5642
5643static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5644 bool can_swap, bool force_scan)
5645{
5646 DEFINE_MAX_SEQ(lruvec);
5647 DEFINE_MIN_SEQ(lruvec);
5648
5649 if (seq < max_seq)
5650 return 0;
5651
5652 if (seq > max_seq)
5653 return -EINVAL;
5654
5655 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5656 return -ERANGE;
5657
5658 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5659
5660 return 0;
5661}
5662
5663static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5664 int swappiness, unsigned long nr_to_reclaim)
5665{
5666 DEFINE_MAX_SEQ(lruvec);
5667
5668 if (seq + MIN_NR_GENS > max_seq)
5669 return -EINVAL;
5670
5671 sc->nr_reclaimed = 0;
5672
5673 while (!signal_pending(current)) {
5674 DEFINE_MIN_SEQ(lruvec);
5675
5676 if (seq < min_seq[!swappiness])
5677 return 0;
5678
5679 if (sc->nr_reclaimed >= nr_to_reclaim)
5680 return 0;
5681
Yu Zhao4fc3ef42022-12-21 21:19:01 -07005682 if (!evict_pages(lruvec, sc, swappiness))
Yu Zhao4983c522022-09-18 02:00:09 -06005683 return 0;
5684
5685 cond_resched();
5686 }
5687
5688 return -EINTR;
5689}
5690
5691static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5692 struct scan_control *sc, int swappiness, unsigned long opt)
5693{
5694 struct lruvec *lruvec;
5695 int err = -EINVAL;
5696 struct mem_cgroup *memcg = NULL;
5697
5698 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5699 return -EINVAL;
5700
5701 if (!mem_cgroup_disabled()) {
5702 rcu_read_lock();
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005703
Yu Zhao4983c522022-09-18 02:00:09 -06005704 memcg = mem_cgroup_from_id(memcg_id);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005705 if (!mem_cgroup_tryget(memcg))
Yu Zhao4983c522022-09-18 02:00:09 -06005706 memcg = NULL;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005707
Yu Zhao4983c522022-09-18 02:00:09 -06005708 rcu_read_unlock();
5709
5710 if (!memcg)
5711 return -EINVAL;
5712 }
5713
5714 if (memcg_id != mem_cgroup_id(memcg))
5715 goto done;
5716
5717 lruvec = get_lruvec(memcg, nid);
5718
5719 if (swappiness < 0)
5720 swappiness = get_swappiness(lruvec, sc);
5721 else if (swappiness > 200)
5722 goto done;
5723
5724 switch (cmd) {
5725 case '+':
5726 err = run_aging(lruvec, seq, sc, swappiness, opt);
5727 break;
5728 case '-':
5729 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5730 break;
5731 }
5732done:
5733 mem_cgroup_put(memcg);
5734
5735 return err;
5736}
5737
Yu Zhao642d9862022-09-18 02:00:10 -06005738/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005739static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5740 size_t len, loff_t *pos)
5741{
5742 void *buf;
5743 char *cur, *next;
5744 unsigned int flags;
5745 struct blk_plug plug;
5746 int err = -EINVAL;
5747 struct scan_control sc = {
5748 .may_writepage = true,
5749 .may_unmap = true,
5750 .may_swap = true,
5751 .reclaim_idx = MAX_NR_ZONES - 1,
5752 .gfp_mask = GFP_KERNEL,
5753 };
5754
5755 buf = kvmalloc(len + 1, GFP_KERNEL);
5756 if (!buf)
5757 return -ENOMEM;
5758
5759 if (copy_from_user(buf, src, len)) {
5760 kvfree(buf);
5761 return -EFAULT;
5762 }
5763
5764 set_task_reclaim_state(current, &sc.reclaim_state);
5765 flags = memalloc_noreclaim_save();
5766 blk_start_plug(&plug);
Yu Zhaof8b57162022-12-21 21:19:05 -07005767 if (!set_mm_walk(NULL, true)) {
Yu Zhao4983c522022-09-18 02:00:09 -06005768 err = -ENOMEM;
5769 goto done;
5770 }
5771
5772 next = buf;
5773 next[len] = '\0';
5774
5775 while ((cur = strsep(&next, ",;\n"))) {
5776 int n;
5777 int end;
5778 char cmd;
5779 unsigned int memcg_id;
5780 unsigned int nid;
5781 unsigned long seq;
5782 unsigned int swappiness = -1;
5783 unsigned long opt = -1;
5784
5785 cur = skip_spaces(cur);
5786 if (!*cur)
5787 continue;
5788
5789 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5790 &seq, &end, &swappiness, &end, &opt, &end);
5791 if (n < 4 || cur[end]) {
5792 err = -EINVAL;
5793 break;
5794 }
5795
5796 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5797 if (err)
5798 break;
5799 }
5800done:
5801 clear_mm_walk();
5802 blk_finish_plug(&plug);
5803 memalloc_noreclaim_restore(flags);
5804 set_task_reclaim_state(current, NULL);
5805
5806 kvfree(buf);
5807
5808 return err ? : len;
5809}
5810
5811static int lru_gen_seq_open(struct inode *inode, struct file *file)
5812{
5813 return seq_open(file, &lru_gen_seq_ops);
5814}
5815
5816static const struct file_operations lru_gen_rw_fops = {
5817 .open = lru_gen_seq_open,
5818 .read = seq_read,
5819 .write = lru_gen_seq_write,
5820 .llseek = seq_lseek,
5821 .release = seq_release,
5822};
5823
5824static const struct file_operations lru_gen_ro_fops = {
5825 .open = lru_gen_seq_open,
5826 .read = seq_read,
5827 .llseek = seq_lseek,
5828 .release = seq_release,
5829};
5830
5831/******************************************************************************
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005832 * initialization
5833 ******************************************************************************/
5834
5835void lru_gen_init_lruvec(struct lruvec *lruvec)
5836{
Yu Zhao430499c2022-09-18 02:00:08 -06005837 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005838 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005839 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005840
5841 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005842 lrugen->enabled = lru_gen_enabled();
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005843
Yu Zhao430499c2022-09-18 02:00:08 -06005844 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5845 lrugen->timestamps[i] = jiffies;
5846
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005847 for_each_gen_type_zone(gen, type, zone)
Yu Zhaodf91dc92022-12-21 21:19:00 -07005848 INIT_LIST_HEAD(&lrugen->pages[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005849
5850 lruvec->mm_state.seq = MIN_NR_GENS;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005851}
5852
5853#ifdef CONFIG_MEMCG
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005854
5855void lru_gen_init_pgdat(struct pglist_data *pgdat)
5856{
5857 int i, j;
5858
5859 spin_lock_init(&pgdat->memcg_lru.lock);
5860
5861 for (i = 0; i < MEMCG_NR_GENS; i++) {
5862 for (j = 0; j < MEMCG_NR_BINS; j++)
5863 INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i);
5864 }
5865}
5866
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005867void lru_gen_init_memcg(struct mem_cgroup *memcg)
5868{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005869 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5870 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005871}
5872
5873void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5874{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005875 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005876 int nid;
5877
5878 for_each_node(nid) {
5879 struct lruvec *lruvec = get_lruvec(memcg, nid);
5880
5881 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5882 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005883
5884 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5885 bitmap_free(lruvec->mm_state.filters[i]);
5886 lruvec->mm_state.filters[i] = NULL;
5887 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005888 }
5889}
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005890
5891void lru_gen_online_memcg(struct mem_cgroup *memcg)
5892{
5893 int gen;
5894 int nid;
5895 int bin = prandom_u32_max(MEMCG_NR_BINS);
5896
5897 for_each_node(nid) {
5898 struct pglist_data *pgdat = NODE_DATA(nid);
5899 struct lruvec *lruvec = get_lruvec(memcg, nid);
5900
5901 spin_lock(&pgdat->memcg_lru.lock);
5902
5903 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
5904
5905 gen = get_memcg_gen(pgdat->memcg_lru.seq);
5906
5907 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
5908 pgdat->memcg_lru.nr_memcgs[gen]++;
5909
5910 lruvec->lrugen.gen = gen;
5911
5912 spin_unlock(&pgdat->memcg_lru.lock);
5913 }
5914}
5915
5916void lru_gen_offline_memcg(struct mem_cgroup *memcg)
5917{
5918 int nid;
5919
5920 for_each_node(nid) {
5921 struct lruvec *lruvec = get_lruvec(memcg, nid);
5922
5923 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
5924 }
5925}
5926
5927void lru_gen_release_memcg(struct mem_cgroup *memcg)
5928{
5929 int gen;
5930 int nid;
5931
5932 for_each_node(nid) {
5933 struct pglist_data *pgdat = NODE_DATA(nid);
5934 struct lruvec *lruvec = get_lruvec(memcg, nid);
5935
5936 spin_lock(&pgdat->memcg_lru.lock);
5937
5938 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
5939
5940 gen = lruvec->lrugen.gen;
5941
5942 hlist_nulls_del_rcu(&lruvec->lrugen.list);
5943 pgdat->memcg_lru.nr_memcgs[gen]--;
5944
5945 if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
5946 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
5947
5948 spin_unlock(&pgdat->memcg_lru.lock);
5949 }
5950}
5951
5952#endif /* CONFIG_MEMCG */
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005953
5954static int __init init_lru_gen(void)
5955{
5956 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5957 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5958
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005959 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5960 pr_err("lru_gen: failed to create sysfs group\n");
5961
Yu Zhao4983c522022-09-18 02:00:09 -06005962 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5963 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5964
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005965 return 0;
5966};
5967late_initcall(init_lru_gen);
5968
Yu Zhao37397872022-09-18 02:00:03 -06005969#else /* !CONFIG_LRU_GEN */
5970
5971static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5972{
5973}
5974
5975static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5976{
5977}
5978
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005979static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5980{
5981}
5982
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005983#endif /* CONFIG_LRU_GEN */
5984
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005985static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005986{
5987 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005988 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005989 unsigned long nr_to_scan;
5990 enum lru_list lru;
5991 unsigned long nr_reclaimed = 0;
5992 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005993 bool proportional_reclaim;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005994 struct blk_plug plug;
Minchan Kima8962f62022-11-02 09:04:41 -07005995 bool do_plug = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005996
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005997 if (lru_gen_enabled() && !global_reclaim(sc)) {
Yu Zhao37397872022-09-18 02:00:03 -06005998 lru_gen_shrink_lruvec(lruvec, sc);
5999 return;
6000 }
6001
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006002 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006003
Mel Gormane82e0562013-07-03 15:01:44 -07006004 /* Record the original scan target for proportional adjustments later */
6005 memcpy(targets, nr, sizeof(nr));
6006
Mel Gorman1a501902014-06-04 16:10:49 -07006007 /*
6008 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
6009 * event that can occur when there is little memory pressure e.g.
6010 * multiple streaming readers/writers. Hence, we do not abort scanning
6011 * when the requested number of pages are reclaimed when scanning at
6012 * DEF_PRIORITY on the assumption that the fact we are direct
6013 * reclaiming implies that kswapd is not keeping up and it is best to
6014 * do a batch of work at once. For memcg reclaim one check is made to
6015 * abort proportional reclaim if either the file or anon lru has already
6016 * dropped to zero at the first pass.
6017 */
Johannes Weiner7b3c9402022-08-02 12:28:11 -04006018 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
6019 sc->priority == DEF_PRIORITY);
Mel Gorman1a501902014-06-04 16:10:49 -07006020
Minchan Kima8962f62022-11-02 09:04:41 -07006021 trace_android_vh_shrink_lruvec_blk_plug(&do_plug);
6022 if (do_plug)
6023 blk_start_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006024 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
6025 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07006026 unsigned long nr_anon, nr_file, percentage;
6027 unsigned long nr_scanned;
6028
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006029 for_each_evictable_lru(lru) {
6030 if (nr[lru]) {
6031 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
6032 nr[lru] -= nr_to_scan;
6033
6034 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07006035 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006036 }
6037 }
Mel Gormane82e0562013-07-03 15:01:44 -07006038
Michal Hockobd041732016-12-02 17:26:48 -08006039 cond_resched();
6040
Johannes Weiner7b3c9402022-08-02 12:28:11 -04006041 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
Mel Gormane82e0562013-07-03 15:01:44 -07006042 continue;
6043
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006044 /*
Mel Gormane82e0562013-07-03 15:01:44 -07006045 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07006046 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07006047 * proportionally what was requested by get_scan_count(). We
6048 * stop reclaiming one LRU and reduce the amount scanning
6049 * proportional to the original scan target.
6050 */
6051 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
6052 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
6053
Mel Gorman1a501902014-06-04 16:10:49 -07006054 /*
6055 * It's just vindictive to attack the larger once the smaller
6056 * has gone to zero. And given the way we stop scanning the
6057 * smaller below, this makes sure that we only make one nudge
6058 * towards proportionality once we've got nr_to_reclaim.
6059 */
6060 if (!nr_file || !nr_anon)
6061 break;
6062
Mel Gormane82e0562013-07-03 15:01:44 -07006063 if (nr_file > nr_anon) {
6064 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
6065 targets[LRU_ACTIVE_ANON] + 1;
6066 lru = LRU_BASE;
6067 percentage = nr_anon * 100 / scan_target;
6068 } else {
6069 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
6070 targets[LRU_ACTIVE_FILE] + 1;
6071 lru = LRU_FILE;
6072 percentage = nr_file * 100 / scan_target;
6073 }
6074
6075 /* Stop scanning the smaller of the LRU */
6076 nr[lru] = 0;
6077 nr[lru + LRU_ACTIVE] = 0;
6078
6079 /*
6080 * Recalculate the other LRU scan count based on its original
6081 * scan target and the percentage scanning already complete
6082 */
6083 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
6084 nr_scanned = targets[lru] - nr[lru];
6085 nr[lru] = targets[lru] * (100 - percentage) / 100;
6086 nr[lru] -= min(nr[lru], nr_scanned);
6087
6088 lru += LRU_ACTIVE;
6089 nr_scanned = targets[lru] - nr[lru];
6090 nr[lru] = targets[lru] * (100 - percentage) / 100;
6091 nr[lru] -= min(nr[lru], nr_scanned);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006092 }
Minchan Kima8962f62022-11-02 09:04:41 -07006093 if (do_plug)
6094 blk_finish_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006095 sc->nr_reclaimed += nr_reclaimed;
6096
6097 /*
6098 * Even if we did not try to evict anon pages at all, we want to
6099 * rebalance the anon lru active/inactive ratio.
6100 */
Dave Hansen2f368a92021-09-02 14:59:23 -07006101 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
6102 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006103 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6104 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006105}
6106
Mel Gorman23b9da52012-05-29 15:06:20 -07006107/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006108static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07006109{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08006110 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07006111 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006112 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07006113 return true;
6114
6115 return false;
6116}
6117
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006118/*
Mel Gorman23b9da52012-05-29 15:06:20 -07006119 * Reclaim/compaction is used for high-order allocation requests. It reclaims
6120 * order-0 pages before compacting the zone. should_continue_reclaim() returns
6121 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07006122 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07006123 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08006124 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006125static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08006126 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08006127 struct scan_control *sc)
6128{
6129 unsigned long pages_for_compaction;
6130 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07006131 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006132
6133 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006134 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08006135 return false;
6136
Vlastimil Babka5ee04712019-09-23 15:37:29 -07006137 /*
6138 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
6139 * number of pages that were scanned. This will return to the caller
6140 * with the risk reclaim/compaction and the resulting allocation attempt
6141 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
6142 * allocations through requiring that the full LRU list has been scanned
6143 * first, by assuming that zero delta of sc->nr_scanned means full LRU
6144 * scan, but that approximation was wrong, and there were corner cases
6145 * where always a non-zero amount of pages were scanned.
6146 */
6147 if (!nr_reclaimed)
6148 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006149
Mel Gorman3e7d3442011-01-13 15:45:56 -08006150 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006151 for (z = 0; z <= sc->reclaim_idx; z++) {
6152 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07006153 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07006154 continue;
6155
6156 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07006157 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07006158 case COMPACT_CONTINUE:
6159 return false;
6160 default:
6161 /* check next zone */
6162 ;
6163 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08006164 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07006165
6166 /*
6167 * If we have not reclaimed enough pages for compaction and the
6168 * inactive lists are large enough, continue reclaiming
6169 */
6170 pages_for_compaction = compact_gap(sc->order);
6171 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07006172 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07006173 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
6174
Vlastimil Babka5ee04712019-09-23 15:37:29 -07006175 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006176}
6177
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006178static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006179{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006180 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08006181 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006182
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006183 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08006184 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006185 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006186 unsigned long reclaimed;
6187 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08006188 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08006189
Xunlei Pange3336ca2020-09-04 16:35:27 -07006190 /*
6191 * This loop can become CPU-bound when target memcgs
6192 * aren't eligible for reclaim - either because they
6193 * don't have any reclaimable pages, or because their
6194 * memory is explicitly protected. Avoid soft lockups.
6195 */
6196 cond_resched();
6197
Liujie Xieb7ea1c42022-06-01 15:38:17 +08006198 trace_android_vh_shrink_node_memcgs(memcg, &skip);
6199 if (skip)
6200 continue;
6201
Chris Down45c7f7e2020-08-06 23:22:05 -07006202 mem_cgroup_calculate_protection(target_memcg, memcg);
6203
6204 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08006205 /*
6206 * Hard protection.
6207 * If there is no reclaimable memory, OOM.
6208 */
6209 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07006210 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08006211 /*
6212 * Soft protection.
6213 * Respect the protection only as long as
6214 * there is an unprotected supply
6215 * of reclaimable memory from other cgroups.
6216 */
6217 if (!sc->memcg_low_reclaim) {
6218 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006219 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006220 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08006221 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08006222 }
6223
Johannes Weinerd2af3392019-11-30 17:55:43 -08006224 reclaimed = sc->nr_reclaimed;
6225 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006226
6227 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006228
Johannes Weinerd2af3392019-11-30 17:55:43 -08006229 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
6230 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07006231
Johannes Weinerd2af3392019-11-30 17:55:43 -08006232 /* Record the group's reclaim efficiency */
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006233 if (!sc->proactive)
6234 vmpressure(sc->gfp_mask, memcg, false,
6235 sc->nr_scanned - scanned,
6236 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006237
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006238 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
6239}
6240
Liu Song6c9e09072020-01-30 22:14:08 -08006241static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006242{
6243 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006244 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08006245 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006246 bool reclaimable = false;
6247
Yu Zhaoa3eb6512022-12-21 21:19:04 -07006248 if (lru_gen_enabled() && global_reclaim(sc)) {
6249 lru_gen_shrink_node(pgdat, sc);
6250 return;
6251 }
6252
Johannes Weiner1b051172019-11-30 17:55:52 -08006253 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
6254
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006255again:
6256 memset(&sc->nr, 0, sizeof(sc->nr));
6257
6258 nr_reclaimed = sc->nr_reclaimed;
6259 nr_scanned = sc->nr_scanned;
6260
Yu Zhao6d313442022-09-18 02:00:00 -06006261 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08006262
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006263 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006264
Johannes Weinerd2af3392019-11-30 17:55:43 -08006265 if (reclaim_state) {
6266 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
6267 reclaim_state->reclaimed_slab = 0;
6268 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07006269
Johannes Weinerd2af3392019-11-30 17:55:43 -08006270 /* Record the subtree's reclaim efficiency */
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006271 if (!sc->proactive)
6272 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
6273 sc->nr_scanned - nr_scanned,
6274 sc->nr_reclaimed - nr_reclaimed);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006275
6276 if (sc->nr_reclaimed - nr_reclaimed)
6277 reclaimable = true;
6278
6279 if (current_is_kswapd()) {
6280 /*
6281 * If reclaim is isolating dirty pages under writeback,
6282 * it implies that the long-lived page allocation rate
6283 * is exceeding the page laundering rate. Either the
6284 * global limits are not being effective at throttling
6285 * processes due to the page distribution throughout
6286 * zones or there is heavy usage of a slow backing
6287 * device. The only option is to throttle from reclaim
6288 * context which is not ideal as there is no guarantee
6289 * the dirtying process is throttled in the same way
6290 * balance_dirty_pages() manages.
6291 *
6292 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6293 * count the number of pages under pages flagged for
6294 * immediate reclaim and stall if any are encountered
6295 * in the nr_immediate check below.
6296 */
6297 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
6298 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006299
Johannes Weinerd2af3392019-11-30 17:55:43 -08006300 /* Allow kswapd to start writing pages during reclaim.*/
6301 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
6302 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07006303
6304 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006305 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08006306 * reclaim and under writeback (nr_immediate), it
6307 * implies that pages are cycling through the LRU
6308 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07006309 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08006310 if (sc->nr.immediate)
6311 congestion_wait(BLK_RW_ASYNC, HZ/10);
6312 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07006313
Johannes Weinerd2af3392019-11-30 17:55:43 -08006314 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08006315 * Tag a node/memcg as congested if all the dirty pages
6316 * scanned were backed by a congested BDI and
6317 * wait_iff_congested will stall.
6318 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08006319 * Legacy memcg will stall in page writeback so avoid forcibly
6320 * stalling in wait_iff_congested().
6321 */
Johannes Weiner1b051172019-11-30 17:55:52 -08006322 if ((current_is_kswapd() ||
6323 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08006324 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08006325 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006326
6327 /*
6328 * Stall direct reclaim for IO completions if underlying BDIs
6329 * and node is congested. Allow kswapd to continue until it
6330 * starts encountering unqueued dirty pages or cycling through
6331 * the LRU too quickly.
6332 */
Johannes Weiner1b051172019-11-30 17:55:52 -08006333 if (!current_is_kswapd() && current_may_throttle() &&
6334 !sc->hibernation_mode &&
6335 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08006336 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
6337
6338 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
6339 sc))
6340 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07006341
Johannes Weinerc73322d2017-05-03 14:51:51 -07006342 /*
6343 * Kswapd gives up on balancing particular nodes after too
6344 * many failures to reclaim anything from them and goes to
6345 * sleep. On reclaim progress, reset the failure counter. A
6346 * successful direct reclaim run will revive a dormant kswapd.
6347 */
6348 if (reclaimable)
6349 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006350}
6351
Vlastimil Babka53853e22014-10-09 15:27:02 -07006352/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006353 * Returns true if compaction should go ahead for a costly-order request, or
6354 * the allocation would already succeed without compaction. Return false if we
6355 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07006356 */
Mel Gorman4f588332016-07-28 15:46:38 -07006357static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006358{
Mel Gorman31483b62016-07-28 15:45:46 -07006359 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006360 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006361
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006362 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6363 if (suitable == COMPACT_SUCCESS)
6364 /* Allocation should succeed already. Don't reclaim. */
6365 return true;
6366 if (suitable == COMPACT_SKIPPED)
6367 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006368 return false;
6369
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006370 /*
6371 * Compaction is already possible, but it takes time to run and there
6372 * are potentially other callers using the pages just freed. So proceed
6373 * with reclaim to make a buffer of free pages available to give
6374 * compaction a reasonable chance of completing and allocating the page.
6375 * Note that we won't actually reclaim the whole buffer in one attempt
6376 * as the target watermark in should_continue_reclaim() is lower. But if
6377 * we are already above the high+gap watermark, don't reclaim at all.
6378 */
6379 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6380
6381 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006382}
6383
Linus Torvalds1da177e2005-04-16 15:20:36 -07006384/*
6385 * This is the direct reclaim path, for page-allocating processes. We only
6386 * try to reclaim pages from zones which will satisfy the caller's allocation
6387 * request.
6388 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07006389 * If a zone is deemed to be full of pinned pages then just give it a light
6390 * scan then give up on it.
6391 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07006392static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006393{
Mel Gormandd1a2392008-04-28 02:12:17 -07006394 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07006395 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07006396 unsigned long nr_soft_reclaimed;
6397 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07006398 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07006399 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006400
Mel Gormancc715d92012-03-21 16:34:00 -07006401 /*
6402 * If the number of buffer_heads in the machine exceeds the maximum
6403 * allowed level, force direct reclaim to scan the highmem zone as
6404 * highmem pages could be pinning lowmem pages storing buffer_heads
6405 */
Weijie Yang619d0d762014-04-07 15:36:59 -07006406 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07006407 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07006408 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07006409 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07006410 }
Mel Gormancc715d92012-03-21 16:34:00 -07006411
Mel Gormand4debc62010-08-09 17:19:29 -07006412 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07006413 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07006414 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006415 * Take care memory controller reclaiming has small influence
6416 * to global LRU.
6417 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08006418 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04006419 if (!cpuset_zone_allowed(zone,
6420 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006421 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006422
Johannes Weiner0b064962014-08-06 16:06:12 -07006423 /*
6424 * If we already have plenty of memory free for
6425 * compaction in this zone, don't free any more.
6426 * Even though compaction is invoked for any
6427 * non-zero order, only frequent costly order
6428 * reclamation is disruptive enough to become a
6429 * noticeable problem, like transparent huge
6430 * page allocations.
6431 */
6432 if (IS_ENABLED(CONFIG_COMPACTION) &&
6433 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07006434 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07006435 sc->compaction_ready = true;
6436 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07006437 }
Johannes Weiner0b064962014-08-06 16:06:12 -07006438
Andrew Morton0608f432013-09-24 15:27:41 -07006439 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07006440 * Shrink each node in the zonelist once. If the
6441 * zonelist is ordered by zone (not the default) then a
6442 * node may be shrunk multiple times but in that case
6443 * the user prefers lower zones being preserved.
6444 */
6445 if (zone->zone_pgdat == last_pgdat)
6446 continue;
6447
6448 /*
Andrew Morton0608f432013-09-24 15:27:41 -07006449 * This steals pages from memory cgroups over softlimit
6450 * and returns the number of reclaimed pages and
6451 * scanned pages. This works for global memory pressure
6452 * and balancing, not for a memcg's limit.
6453 */
6454 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006455 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006456 sc->order, sc->gfp_mask,
6457 &nr_soft_scanned);
6458 sc->nr_reclaimed += nr_soft_reclaimed;
6459 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006460 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006461 }
Nick Piggin408d8542006-09-25 23:31:27 -07006462
Mel Gorman79dafcd2016-07-28 15:45:53 -07006463 /* See comment about same check for global reclaim above */
6464 if (zone->zone_pgdat == last_pgdat)
6465 continue;
6466 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006467 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006468 }
Mel Gormane0c23272011-10-31 17:09:33 -07006469
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006470 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006471 * Restore to original mask to avoid the impact on the caller if we
6472 * promoted it to __GFP_HIGHMEM.
6473 */
6474 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006475}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006476
Johannes Weinerb9107182019-11-30 17:55:59 -08006477static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006478{
Johannes Weinerb9107182019-11-30 17:55:59 -08006479 struct lruvec *target_lruvec;
6480 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006481
Yu Zhao37397872022-09-18 02:00:03 -06006482 if (lru_gen_enabled())
6483 return;
6484
Johannes Weinerb9107182019-11-30 17:55:59 -08006485 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006486 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6487 target_lruvec->refaults[0] = refaults;
6488 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6489 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006490}
6491
Linus Torvalds1da177e2005-04-16 15:20:36 -07006492/*
6493 * This is the main entry point to direct page reclaim.
6494 *
6495 * If a full scan of the inactive list fails to free enough memory then we
6496 * are "out of memory" and something needs to be killed.
6497 *
6498 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6499 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006500 * caller can't do much about. We kick the writeback threads and take explicit
6501 * naps in the hope that some of these pages can be written. But if the
6502 * allocating task holds filesystem locks which prevent writeout this might not
6503 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006504 *
6505 * returns: 0, if no pages reclaimed
6506 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006507 */
Mel Gormandac1d272008-04-28 02:12:12 -07006508static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006509 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006510{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006511 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006512 pg_data_t *last_pgdat;
6513 struct zoneref *z;
6514 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006515retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006516 delayacct_freepages_start();
6517
Johannes Weinerb5ead352019-11-30 17:55:40 -08006518 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006519 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006520
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006521 do {
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006522 if (!sc->proactive)
6523 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6524 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006525 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006526 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006527
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006528 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006529 break;
6530
6531 if (sc->compaction_ready)
6532 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006533
6534 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006535 * If we're getting trouble reclaiming, start doing
6536 * writepage even in laptop mode.
6537 */
6538 if (sc->priority < DEF_PRIORITY - 2)
6539 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006540 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006541
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006542 last_pgdat = NULL;
6543 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6544 sc->nodemask) {
6545 if (zone->zone_pgdat == last_pgdat)
6546 continue;
6547 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006548
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006549 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006550
6551 if (cgroup_reclaim(sc)) {
6552 struct lruvec *lruvec;
6553
6554 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6555 zone->zone_pgdat);
6556 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6557 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006558 }
6559
Keika Kobayashi873b4772008-07-25 01:48:52 -07006560 delayacct_freepages_end();
6561
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006562 if (sc->nr_reclaimed)
6563 return sc->nr_reclaimed;
6564
Mel Gorman0cee34f2012-01-12 17:19:49 -08006565 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006566 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006567 return 1;
6568
Johannes Weinerb91ac372019-11-30 17:56:02 -08006569 /*
6570 * We make inactive:active ratio decisions based on the node's
6571 * composition of memory, but a restrictive reclaim_idx or a
6572 * memory.low cgroup setting can exempt large amounts of
6573 * memory from reclaim. Neither of which are very common, so
6574 * instead of doing costly eligibility calculations of the
6575 * entire cgroup subtree up front, we assume the estimates are
6576 * good, and retry with forcible deactivation if that fails.
6577 */
6578 if (sc->skipped_deactivate) {
6579 sc->priority = initial_priority;
6580 sc->force_deactivate = 1;
6581 sc->skipped_deactivate = 0;
6582 goto retry;
6583 }
6584
Johannes Weiner241994ed2015-02-11 15:26:06 -08006585 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006586 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006587 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006588 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006589 sc->memcg_low_reclaim = 1;
6590 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006591 goto retry;
6592 }
6593
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006594 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006595}
6596
Johannes Weinerc73322d2017-05-03 14:51:51 -07006597static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006598{
6599 struct zone *zone;
6600 unsigned long pfmemalloc_reserve = 0;
6601 unsigned long free_pages = 0;
6602 int i;
6603 bool wmark_ok;
6604
Johannes Weinerc73322d2017-05-03 14:51:51 -07006605 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6606 return true;
6607
Mel Gorman55150612012-07-31 16:44:35 -07006608 for (i = 0; i <= ZONE_NORMAL; i++) {
6609 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006610 if (!managed_zone(zone))
6611 continue;
6612
6613 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006614 continue;
6615
Mel Gorman55150612012-07-31 16:44:35 -07006616 pfmemalloc_reserve += min_wmark_pages(zone);
6617 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6618 }
6619
Mel Gorman675becc2014-06-04 16:07:35 -07006620 /* If there are no reserves (unexpected config) then do not throttle */
6621 if (!pfmemalloc_reserve)
6622 return true;
6623
Mel Gorman55150612012-07-31 16:44:35 -07006624 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6625
6626 /* kswapd must be awake if processes are being throttled */
6627 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006628 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6629 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006630
Mel Gorman55150612012-07-31 16:44:35 -07006631 wake_up_interruptible(&pgdat->kswapd_wait);
6632 }
6633
6634 return wmark_ok;
6635}
6636
6637/*
6638 * Throttle direct reclaimers if backing storage is backed by the network
6639 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6640 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006641 * when the low watermark is reached.
6642 *
6643 * Returns true if a fatal signal was delivered during throttling. If this
6644 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006645 */
Mel Gorman50694c22012-11-26 16:29:48 -08006646static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006647 nodemask_t *nodemask)
6648{
Mel Gorman675becc2014-06-04 16:07:35 -07006649 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006650 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006651 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006652
6653 /*
6654 * Kernel threads should not be throttled as they may be indirectly
6655 * responsible for cleaning pages necessary for reclaim to make forward
6656 * progress. kjournald for example may enter direct reclaim while
6657 * committing a transaction where throttling it could forcing other
6658 * processes to block on log_wait_commit().
6659 */
6660 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006661 goto out;
6662
6663 /*
6664 * If a fatal signal is pending, this process should not throttle.
6665 * It should return quickly so it can exit and free its memory
6666 */
6667 if (fatal_signal_pending(current))
6668 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006669
Mel Gorman675becc2014-06-04 16:07:35 -07006670 /*
6671 * Check if the pfmemalloc reserves are ok by finding the first node
6672 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6673 * GFP_KERNEL will be required for allocating network buffers when
6674 * swapping over the network so ZONE_HIGHMEM is unusable.
6675 *
6676 * Throttling is based on the first usable node and throttled processes
6677 * wait on a queue until kswapd makes progress and wakes them. There
6678 * is an affinity then between processes waking up and where reclaim
6679 * progress has been made assuming the process wakes on the same node.
6680 * More importantly, processes running on remote nodes will not compete
6681 * for remote pfmemalloc reserves and processes on different nodes
6682 * should make reasonable progress.
6683 */
6684 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006685 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006686 if (zone_idx(zone) > ZONE_NORMAL)
6687 continue;
6688
6689 /* Throttle based on the first usable node */
6690 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006691 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006692 goto out;
6693 break;
6694 }
6695
6696 /* If no zone was usable by the allocation flags then do not throttle */
6697 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006698 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006699
Mel Gorman68243e72012-07-31 16:44:39 -07006700 /* Account for the throttling */
6701 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6702
Mel Gorman55150612012-07-31 16:44:35 -07006703 /*
6704 * If the caller cannot enter the filesystem, it's possible that it
6705 * is due to the caller holding an FS lock or performing a journal
6706 * transaction in the case of a filesystem like ext[3|4]. In this case,
6707 * it is not safe to block on pfmemalloc_wait as kswapd could be
6708 * blocked waiting on the same lock. Instead, throttle for up to a
6709 * second before continuing.
6710 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006711 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006712 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006713 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006714 else
6715 /* Throttle until kswapd wakes the process */
6716 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6717 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006718
Mel Gorman50694c22012-11-26 16:29:48 -08006719 if (fatal_signal_pending(current))
6720 return true;
6721
6722out:
6723 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006724}
6725
Mel Gormandac1d272008-04-28 02:12:12 -07006726unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006727 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006728{
Mel Gorman33906bc2010-08-09 17:19:16 -07006729 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006730 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006731 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006732 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006733 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006734 .order = order,
6735 .nodemask = nodemask,
6736 .priority = DEF_PRIORITY,
6737 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006738 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006739 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006740 };
6741
Mel Gorman55150612012-07-31 16:44:35 -07006742 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006743 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6744 * Confirm they are large enough for max values.
6745 */
6746 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6747 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6748 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6749
6750 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006751 * Do not enter reclaim if fatal signal was delivered while throttled.
6752 * 1 is returned so that the page allocator does not OOM kill at this
6753 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006754 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006755 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006756 return 1;
6757
Andrew Morton1732d2b012019-07-16 16:26:15 -07006758 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006759 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006760
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006761 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006762
6763 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006764 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006765
6766 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006767}
6768
Andrew Mortonc255a452012-07-31 16:43:02 -07006769#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006770
Michal Hockod2e5fb92019-08-30 16:04:50 -07006771/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006772unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006773 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006774 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006775 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006776{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006777 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006778 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006779 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006780 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006781 .may_writepage = !laptop_mode,
6782 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006783 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006784 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006785 };
Ying Han0ae5e892011-05-26 16:25:25 -07006786
Michal Hockod2e5fb92019-08-30 16:04:50 -07006787 WARN_ON_ONCE(!current->reclaim_state);
6788
Balbir Singh4e416952009-09-23 15:56:39 -07006789 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6790 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006791
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006792 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006793 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006794
Balbir Singh4e416952009-09-23 15:56:39 -07006795 /*
6796 * NOTE: Although we can get the priority field, using it
6797 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006798 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006799 * will pick up pages from other mem cgroup's as well. We hack
6800 * the priority and make it zero.
6801 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006802 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006803
6804 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6805
Ying Han0ae5e892011-05-26 16:25:25 -07006806 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006807
Balbir Singh4e416952009-09-23 15:56:39 -07006808 return sc.nr_reclaimed;
6809}
6810
Johannes Weiner72835c82012-01-12 17:18:32 -08006811unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006812 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006813 gfp_t gfp_mask,
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006814 unsigned int reclaim_options)
Balbir Singh66e17072008-02-07 00:13:56 -08006815{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006816 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006817 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006818 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006819 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006820 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006821 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006822 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006823 .target_mem_cgroup = memcg,
6824 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006825 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006826 .may_unmap = 1,
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006827 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
6828 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
Ying Hana09ed5e2011-05-24 17:12:26 -07006829 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006830 /*
6831 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6832 * equal pressure on all the nodes. This is based on the assumption that
6833 * the reclaim does not bail out early.
6834 */
6835 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006836
Andrew Morton1732d2b012019-07-16 16:26:15 -07006837 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006838 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006839 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006840
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006841 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006842
Vlastimil Babka499118e2017-05-08 15:59:50 -07006843 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006844 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006845 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006846
6847 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006848}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006849EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006850#endif
6851
Yu Zhao37397872022-09-18 02:00:03 -06006852static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006853{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006854 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006855 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006856
Yu Zhao37397872022-09-18 02:00:03 -06006857 if (lru_gen_enabled()) {
6858 lru_gen_age_node(pgdat, sc);
6859 return;
6860 }
6861
Dave Hansen2f368a92021-09-02 14:59:23 -07006862 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006863 return;
6864
Johannes Weinerb91ac372019-11-30 17:56:02 -08006865 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6866 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6867 return;
6868
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006869 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6870 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006871 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6872 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6873 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006874 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6875 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006876}
6877
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006878static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006879{
6880 int i;
6881 struct zone *zone;
6882
6883 /*
6884 * Check for watermark boosts top-down as the higher zones
6885 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006886 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006887 * start prematurely when there is no boosting and a lower
6888 * zone is balanced.
6889 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006890 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006891 zone = pgdat->node_zones + i;
6892 if (!managed_zone(zone))
6893 continue;
6894
6895 if (zone->watermark_boost)
6896 return true;
6897 }
6898
6899 return false;
6900}
6901
Mel Gormane716f2e2017-05-03 14:53:45 -07006902/*
6903 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006904 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006905 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006906static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006907{
Mel Gormane716f2e2017-05-03 14:53:45 -07006908 int i;
6909 unsigned long mark = -1;
6910 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006911
Mel Gorman1c308442018-12-28 00:35:52 -08006912 /*
6913 * Check watermarks bottom-up as lower zones are more likely to
6914 * meet watermarks.
6915 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006916 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006917 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006918
Mel Gormane716f2e2017-05-03 14:53:45 -07006919 if (!managed_zone(zone))
6920 continue;
6921
6922 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006923 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006924 return true;
6925 }
6926
6927 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006928 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006929 * need balancing by definition. This can happen if a zone-restricted
6930 * allocation tries to wake a remote kswapd.
6931 */
6932 if (mark == -1)
6933 return true;
6934
6935 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006936}
6937
Mel Gorman631b6e02017-05-03 14:53:41 -07006938/* Clear pgdat state for congested, dirty or under writeback. */
6939static void clear_pgdat_congested(pg_data_t *pgdat)
6940{
Johannes Weiner1b051172019-11-30 17:55:52 -08006941 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6942
6943 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006944 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6945 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6946}
6947
Mel Gorman1741c872011-01-13 15:46:21 -08006948/*
Mel Gorman55150612012-07-31 16:44:35 -07006949 * Prepare kswapd for sleeping. This verifies that there are no processes
6950 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6951 *
6952 * Returns true if kswapd is ready to sleep
6953 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006954static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6955 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006956{
Mel Gorman55150612012-07-31 16:44:35 -07006957 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006958 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006959 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006960 * race between when kswapd checks the watermarks and a process gets
6961 * throttled. There is also a potential race if processes get
6962 * throttled, kswapd wakes, a large process exits thereby balancing the
6963 * zones, which causes kswapd to exit balance_pgdat() before reaching
6964 * the wake up checks. If kswapd is going to sleep, no process should
6965 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6966 * the wake up is premature, processes will wake kswapd and get
6967 * throttled again. The difference from wake ups in balance_pgdat() is
6968 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006969 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006970 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6971 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006972
Johannes Weinerc73322d2017-05-03 14:51:51 -07006973 /* Hopeless node, leave it to direct reclaim */
6974 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6975 return true;
6976
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006977 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006978 clear_pgdat_congested(pgdat);
6979 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006980 }
6981
Shantanu Goel333b0a42017-05-03 14:53:38 -07006982 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006983}
6984
Linus Torvalds1da177e2005-04-16 15:20:36 -07006985/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006986 * kswapd shrinks a node of pages that are at or below the highest usable
6987 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006988 *
6989 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006990 * reclaim or if the lack of progress was due to pages under writeback.
6991 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006992 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006993static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006994 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006995{
Mel Gorman1d82de62016-07-28 15:45:43 -07006996 struct zone *zone;
6997 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006998
Mel Gorman1d82de62016-07-28 15:45:43 -07006999 /* Reclaim a number of pages proportional to the number of zones */
7000 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07007001 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07007002 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07007003 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07007004 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07007005
Mel Gorman1d82de62016-07-28 15:45:43 -07007006 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07007007 }
7008
Mel Gorman1d82de62016-07-28 15:45:43 -07007009 /*
7010 * Historically care was taken to put equal pressure on all zones but
7011 * now pressure is applied based on node LRU order.
7012 */
Mel Gorman970a39a2016-07-28 15:46:35 -07007013 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07007014
7015 /*
7016 * Fragmentation may mean that the system cannot be rebalanced for
7017 * high-order allocations. If twice the allocation size has been
7018 * reclaimed then recheck watermarks only at order-0 to prevent
7019 * excessive reclaim. Assume that a process requested a high-order
7020 * can direct reclaim/compact.
7021 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07007022 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07007023 sc->order = 0;
7024
Mel Gormanb8e83b92013-07-03 15:01:45 -07007025 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07007026}
7027
Mel Gormanc49c2c42021-06-28 19:42:21 -07007028/* Page allocator PCP high watermark is lowered if reclaim is active. */
7029static inline void
7030update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
7031{
7032 int i;
7033 struct zone *zone;
7034
7035 for (i = 0; i <= highest_zoneidx; i++) {
7036 zone = pgdat->node_zones + i;
7037
7038 if (!managed_zone(zone))
7039 continue;
7040
7041 if (active)
7042 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7043 else
7044 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7045 }
7046}
7047
7048static inline void
7049set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7050{
7051 update_reclaim_active(pgdat, highest_zoneidx, true);
7052}
7053
7054static inline void
7055clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7056{
7057 update_reclaim_active(pgdat, highest_zoneidx, false);
7058}
7059
Mel Gorman75485362013-07-03 15:01:42 -07007060/*
Mel Gorman1d82de62016-07-28 15:45:43 -07007061 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
7062 * that are eligible for use by the caller until at least one zone is
7063 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007064 *
Mel Gorman1d82de62016-07-28 15:45:43 -07007065 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007066 *
7067 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07007068 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08007069 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07007070 * or lower is eligible for reclaim until at least one usable zone is
7071 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007072 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007073static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007074{
Linus Torvalds1da177e2005-04-16 15:20:36 -07007075 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07007076 unsigned long nr_soft_reclaimed;
7077 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07007078 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08007079 unsigned long nr_boost_reclaim;
7080 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
7081 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07007082 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08007083 struct scan_control sc = {
7084 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07007085 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07007086 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08007087 };
Omar Sandoval93781322018-06-07 17:07:02 -07007088
Andrew Morton1732d2b012019-07-16 16:26:15 -07007089 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07007090 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007091 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007092
Christoph Lameterf8891e52006-06-30 01:55:45 -07007093 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007094
Mel Gorman1c308442018-12-28 00:35:52 -08007095 /*
7096 * Account for the reclaim boost. Note that the zone boost is left in
7097 * place so that parallel allocations that are near the watermark will
7098 * stall or direct reclaim until kswapd is finished.
7099 */
7100 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007101 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08007102 zone = pgdat->node_zones + i;
7103 if (!managed_zone(zone))
7104 continue;
7105
7106 nr_boost_reclaim += zone->watermark_boost;
7107 zone_boosts[i] = zone->watermark_boost;
7108 }
7109 boosted = nr_boost_reclaim;
7110
7111restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07007112 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007113 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007114 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07007115 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07007116 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08007117 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07007118 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07007119
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007120 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007121
Mel Gorman86c79f62016-07-28 15:45:59 -07007122 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07007123 * If the number of buffer_heads exceeds the maximum allowed
7124 * then consider reclaiming from all zones. This has a dual
7125 * purpose -- on 64-bit systems it is expected that
7126 * buffer_heads are stripped during active rotation. On 32-bit
7127 * systems, highmem pages can pin lowmem memory and shrinking
7128 * buffers can relieve lowmem pressure. Reclaim may still not
7129 * go ahead if all eligible zones for the original allocation
7130 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07007131 */
7132 if (buffer_heads_over_limit) {
7133 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
7134 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07007135 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07007136 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007137
Mel Gorman970a39a2016-07-28 15:46:35 -07007138 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08007139 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007140 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07007141 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08007142
Mel Gorman86c79f62016-07-28 15:45:59 -07007143 /*
Mel Gorman1c308442018-12-28 00:35:52 -08007144 * If the pgdat is imbalanced then ignore boosting and preserve
7145 * the watermarks for a later time and restart. Note that the
7146 * zone watermarks will be still reset at the end of balancing
7147 * on the grounds that the normal reclaim should be enough to
7148 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07007149 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007150 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007151 if (!balanced && nr_boost_reclaim) {
7152 nr_boost_reclaim = 0;
7153 goto restart;
7154 }
7155
7156 /*
7157 * If boosting is not active then only reclaim if there are no
7158 * eligible zones. Note that sc.reclaim_idx is not used as
7159 * buffer_heads_over_limit may have adjusted it.
7160 */
7161 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07007162 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08007163
Mel Gorman1c308442018-12-28 00:35:52 -08007164 /* Limit the priority of boosting to avoid reclaim writeback */
7165 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
7166 raise_priority = false;
7167
7168 /*
7169 * Do not writeback or swap pages for boosted reclaim. The
7170 * intent is to relieve pressure not issue sub-optimal IO
7171 * from reclaim context. If no pages are reclaimed, the
7172 * reclaim will be aborted.
7173 */
7174 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
7175 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08007176
Linus Torvalds1da177e2005-04-16 15:20:36 -07007177 /*
Yu Zhao37397872022-09-18 02:00:03 -06007178 * Do some background aging, to give pages a chance to be
7179 * referenced before reclaiming. All pages are rotated
7180 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07007181 */
Yu Zhao37397872022-09-18 02:00:03 -06007182 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07007183
7184 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007185 * If we're getting trouble reclaiming, start doing writepage
7186 * even in laptop mode.
7187 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07007188 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007189 sc.may_writepage = 1;
7190
Mel Gorman1d82de62016-07-28 15:45:43 -07007191 /* Call soft limit reclaim before calling shrink_node. */
7192 sc.nr_scanned = 0;
7193 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07007194 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07007195 sc.gfp_mask, &nr_soft_scanned);
7196 sc.nr_reclaimed += nr_soft_reclaimed;
7197
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007198 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07007199 * There should be no need to raise the scanning priority if
7200 * enough pages are already being scanned that that high
7201 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007202 */
Mel Gorman970a39a2016-07-28 15:46:35 -07007203 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07007204 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07007205
7206 /*
7207 * If the low watermark is met there is no need for processes
7208 * to be throttled on pfmemalloc_wait as they should not be
7209 * able to safely make forward progress. Wake them
7210 */
7211 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07007212 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08007213 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07007214
Mel Gormanb8e83b92013-07-03 15:01:45 -07007215 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007216 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007217 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007218 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007219 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07007220 break;
7221
7222 /*
7223 * Raise priority if scanning rate is too low or there was no
7224 * progress in reclaiming pages
7225 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07007226 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08007227 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
7228
7229 /*
7230 * If reclaim made no progress for a boost, stop reclaim as
7231 * IO cannot be queued and it could be an infinite loop in
7232 * extreme circumstances.
7233 */
7234 if (nr_boost_reclaim && !nr_reclaimed)
7235 break;
7236
Johannes Weinerc73322d2017-05-03 14:51:51 -07007237 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07007238 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07007239 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007240
Johannes Weinerc73322d2017-05-03 14:51:51 -07007241 if (!sc.nr_reclaimed)
7242 pgdat->kswapd_failures++;
7243
Mel Gormanb8e83b92013-07-03 15:01:45 -07007244out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07007245 clear_reclaim_active(pgdat, highest_zoneidx);
7246
Mel Gorman1c308442018-12-28 00:35:52 -08007247 /* If reclaim was boosted, account for the reclaim done in this pass */
7248 if (boosted) {
7249 unsigned long flags;
7250
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007251 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08007252 if (!zone_boosts[i])
7253 continue;
7254
7255 /* Increments are under the zone lock */
7256 zone = pgdat->node_zones + i;
7257 spin_lock_irqsave(&zone->lock, flags);
7258 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7259 spin_unlock_irqrestore(&zone->lock, flags);
7260 }
7261
7262 /*
7263 * As there is now likely space, wakeup kcompact to defragment
7264 * pageblocks.
7265 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007266 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007267 }
7268
Johannes Weiner2a2e4882017-05-03 14:55:03 -07007269 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007270 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07007271 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07007272 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07007273
Mel Gorman0abdee22011-01-13 15:46:22 -08007274 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07007275 * Return the order kswapd stopped reclaiming at as
7276 * prepare_kswapd_sleep() takes it into account. If another caller
7277 * entered the allocator slow path while kswapd was awake, order will
7278 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08007279 */
Mel Gorman1d82de62016-07-28 15:45:43 -07007280 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007281}
7282
Mel Gormane716f2e2017-05-03 14:53:45 -07007283/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007284 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7285 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7286 * not a valid index then either kswapd runs for first time or kswapd couldn't
7287 * sleep after previous reclaim attempt (node is still unbalanced). In that
7288 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07007289 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007290static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7291 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07007292{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007293 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007294
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007295 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07007296}
7297
Mel Gorman38087d92016-07-28 15:45:49 -07007298static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007299 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007300{
7301 long remaining = 0;
7302 DEFINE_WAIT(wait);
7303
7304 if (freezing(current) || kthread_should_stop())
7305 return;
7306
7307 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7308
Shantanu Goel333b0a42017-05-03 14:53:38 -07007309 /*
7310 * Try to sleep for a short interval. Note that kcompactd will only be
7311 * woken if it is possible to sleep for a short interval. This is
7312 * deliberate on the assumption that if reclaim cannot keep an
7313 * eligible zone balanced that it's also unlikely that compaction will
7314 * succeed.
7315 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007316 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07007317 /*
7318 * Compaction records what page blocks it recently failed to
7319 * isolate pages from and skips them in the future scanning.
7320 * When kswapd is going to sleep, it is reasonable to assume
7321 * that pages and compaction may succeed so reset the cache.
7322 */
7323 reset_isolation_suitable(pgdat);
7324
7325 /*
7326 * We have freed the memory, now we should compact it to make
7327 * allocation of the requested order possible.
7328 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007329 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07007330
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007331 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07007332
7333 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007334 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07007335 * order. The values will either be from a wakeup request or
7336 * the previous request that slept prematurely.
7337 */
7338 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007339 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7340 kswapd_highest_zoneidx(pgdat,
7341 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07007342
7343 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7344 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07007345 }
7346
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007347 finish_wait(&pgdat->kswapd_wait, &wait);
7348 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7349 }
7350
7351 /*
7352 * After a short sleep, check if it was a premature sleep. If not, then
7353 * go fully to sleep until explicitly woken up.
7354 */
Mel Gormand9f21d42016-07-28 15:46:41 -07007355 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007356 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007357 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7358
7359 /*
7360 * vmstat counters are not perfectly accurate and the estimated
7361 * value for counters such as NR_FREE_PAGES can deviate from the
7362 * true value by nr_online_cpus * threshold. To avoid the zone
7363 * watermarks being breached while under pressure, we reduce the
7364 * per-cpu vmstat threshold while kswapd is awake and restore
7365 * them before going back to sleep.
7366 */
7367 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07007368
7369 if (!kthread_should_stop())
7370 schedule();
7371
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007372 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7373 } else {
7374 if (remaining)
7375 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7376 else
7377 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7378 }
7379 finish_wait(&pgdat->kswapd_wait, &wait);
7380}
7381
Linus Torvalds1da177e2005-04-16 15:20:36 -07007382/*
7383 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07007384 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007385 *
7386 * This basically trickles out pages so that we have _some_
7387 * free memory available even if there is no other activity
7388 * that frees anything up. This is needed for things like routing
7389 * etc, where we otherwise might have all activity going on in
7390 * asynchronous contexts that cannot page things out.
7391 *
7392 * If there are applications that are active memory-allocators
7393 * (most normal use), this basically shouldn't matter.
7394 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307395int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007396{
Mel Gormane716f2e2017-05-03 14:53:45 -07007397 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007398 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07007399 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007400 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10307401 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007402
Rusty Russell174596a2009-01-01 10:12:29 +10307403 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07007404 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007405
7406 /*
7407 * Tell the memory management that we're a "memory allocator",
7408 * and that if we need more memory we should get access to it
7409 * regardless (see "__alloc_pages()"). "kswapd" should
7410 * never get caught in the normal page freeing logic.
7411 *
7412 * (Kswapd normally doesn't need memory anyway, but sometimes
7413 * you need a small amount of memory in order to be able to
7414 * page out something else, and this flag essentially protects
7415 * us from recursively trying to free more memory as we're
7416 * trying to free the first piece of memory in the first place).
7417 */
Christoph Lameter930d9152006-01-08 01:00:47 -08007418 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07007419 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07007420
Qian Cai5644e1fb2020-04-01 21:10:12 -07007421 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007422 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007423 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08007424 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07007425
Qian Cai5644e1fb2020-04-01 21:10:12 -07007426 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007427 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7428 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07007429
Mel Gorman38087d92016-07-28 15:45:49 -07007430kswapd_try_sleep:
7431 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007432 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07007433
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007434 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08007435 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007436 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7437 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007438 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007439 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007440
David Rientjes8fe23e02009-12-14 17:58:33 -08007441 ret = try_to_freeze();
7442 if (kthread_should_stop())
7443 break;
7444
7445 /*
7446 * We can speed up thawing tasks if we don't call balance_pgdat
7447 * after returning from the refrigerator
7448 */
Mel Gorman38087d92016-07-28 15:45:49 -07007449 if (ret)
7450 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07007451
Mel Gorman38087d92016-07-28 15:45:49 -07007452 /*
7453 * Reclaim begins at the requested order but if a high-order
7454 * reclaim fails then kswapd falls back to reclaiming for
7455 * order-0. If that happens, kswapd will consider sleeping
7456 * for the order it finished reclaiming at (reclaim_order)
7457 * but kcompactd is woken to compact for the original
7458 * request (alloc_order).
7459 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007460 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007461 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007462 reclaim_order = balance_pgdat(pgdat, alloc_order,
7463 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007464 if (reclaim_order < alloc_order)
7465 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007466 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007467
Johannes Weiner71abdc12014-06-06 14:35:35 -07007468 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007469
Linus Torvalds1da177e2005-04-16 15:20:36 -07007470 return 0;
7471}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307472EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007473
7474/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007475 * A zone is low on free memory or too fragmented for high-order memory. If
7476 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7477 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7478 * has failed or is not needed, still wake up kcompactd if only compaction is
7479 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007480 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007481void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007482 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007483{
7484 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007485 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007486
Mel Gorman6aa303d2016-09-01 16:14:55 -07007487 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007488 return;
7489
David Rientjes5ecd9d42018-04-05 16:25:16 -07007490 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007491 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007492
Qian Cai5644e1fb2020-04-01 21:10:12 -07007493 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007494 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007495
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007496 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7497 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007498
7499 if (READ_ONCE(pgdat->kswapd_order) < order)
7500 WRITE_ONCE(pgdat->kswapd_order, order);
7501
Con Kolivas8d0986e2005-09-13 01:25:07 -07007502 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007503 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007504
David Rientjes5ecd9d42018-04-05 16:25:16 -07007505 /* Hopeless node, leave it to direct reclaim if possible */
7506 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007507 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7508 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007509 /*
7510 * There may be plenty of free memory available, but it's too
7511 * fragmented for high-order allocations. Wake up kcompactd
7512 * and rely on compaction_suitable() to determine if it's
7513 * needed. If it fails, it will defer subsequent attempts to
7514 * ratelimit its work.
7515 */
7516 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007517 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007518 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007519 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007520
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007521 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007522 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007523 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007524}
7525
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007526#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007527/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007528 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007529 * freed pages.
7530 *
7531 * Rather than trying to age LRUs the aim is to preserve the overall
7532 * LRU order by reclaiming preferentially
7533 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007534 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007535unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007536{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007537 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007538 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007539 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007540 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007541 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007542 .may_writepage = 1,
7543 .may_unmap = 1,
7544 .may_swap = 1,
7545 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007546 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007547 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007548 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007549 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007550
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007551 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007552 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007553 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007554
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007555 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007556
Andrew Morton1732d2b012019-07-16 16:26:15 -07007557 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007558 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007559 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007560
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007561 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007562}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007563#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007564
Yasunori Goto3218ae12006-06-27 02:53:33 -07007565/*
7566 * This kswapd start function will be called by init and node-hot-add.
7567 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7568 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007569void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007570{
7571 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307572 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007573
7574 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007575 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007576
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307577 trace_android_vh_kswapd_per_node(nid, &skip, true);
7578 if (skip)
7579 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007580 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7581 if (IS_ERR(pgdat->kswapd)) {
7582 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007583 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007584 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007585 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007586 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007587}
7588
David Rientjes8fe23e02009-12-14 17:58:33 -08007589/*
Jiang Liud8adde12012-07-11 14:01:52 -07007590 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007591 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007592 */
7593void kswapd_stop(int nid)
7594{
7595 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307596 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007597
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307598 trace_android_vh_kswapd_per_node(nid, &skip, false);
7599 if (skip)
7600 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007601 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007602 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007603 NODE_DATA(nid)->kswapd = NULL;
7604 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007605}
7606
Linus Torvalds1da177e2005-04-16 15:20:36 -07007607static int __init kswapd_init(void)
7608{
Wei Yang6b700b52020-04-01 21:10:09 -07007609 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007610
Linus Torvalds1da177e2005-04-16 15:20:36 -07007611 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007612 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007613 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007614 return 0;
7615}
7616
7617module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007618
7619#ifdef CONFIG_NUMA
7620/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007621 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007622 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007623 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007624 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007625 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007626int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007627
Dave Hansen51998362021-02-24 12:09:15 -08007628/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007629 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007630 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7631 * a zone.
7632 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007633#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007634
Christoph Lameter9eeff232006-01-18 17:42:31 -08007635/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007636 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007637 * occur.
7638 */
7639int sysctl_min_unmapped_ratio = 1;
7640
7641/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007642 * If the number of slab pages in a zone grows beyond this percentage then
7643 * slab reclaim needs to occur.
7644 */
7645int sysctl_min_slab_ratio = 5;
7646
Mel Gorman11fb9982016-07-28 15:46:20 -07007647static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007648{
Mel Gorman11fb9982016-07-28 15:46:20 -07007649 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7650 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7651 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007652
7653 /*
7654 * It's possible for there to be more file mapped pages than
7655 * accounted for by the pages on the file LRU lists because
7656 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7657 */
7658 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7659}
7660
7661/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007662static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007663{
Alexandru Moised031a152015-11-05 18:48:08 -08007664 unsigned long nr_pagecache_reclaimable;
7665 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007666
7667 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007668 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007669 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007670 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007671 * a better estimate
7672 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007673 if (node_reclaim_mode & RECLAIM_UNMAP)
7674 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007675 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007676 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007677
7678 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007679 if (!(node_reclaim_mode & RECLAIM_WRITE))
7680 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007681
7682 /* Watch for any possible underflows due to delta */
7683 if (unlikely(delta > nr_pagecache_reclaimable))
7684 delta = nr_pagecache_reclaimable;
7685
7686 return nr_pagecache_reclaimable - delta;
7687}
7688
Christoph Lameter0ff38492006-09-25 23:31:52 -07007689/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007690 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007691 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007692static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007693{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007694 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007695 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007696 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007697 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007698 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007699 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007700 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007701 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007702 .priority = NODE_RECLAIM_PRIORITY,
7703 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7704 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007705 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007706 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007707 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007708 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007709
Yafang Shao132bb8c2019-05-13 17:17:53 -07007710 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7711 sc.gfp_mask);
7712
Christoph Lameter9eeff232006-01-18 17:42:31 -08007713 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007714 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007715 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007716 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007717 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007718 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007719 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007720 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007721 noreclaim_flag = memalloc_noreclaim_save();
7722 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007723 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007724
Mel Gormana5f5f912016-07-28 15:46:32 -07007725 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007726 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007727 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007728 * priorities until we have enough memory freed.
7729 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007730 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007731 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007732 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007733 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007734
Andrew Morton1732d2b012019-07-16 16:26:15 -07007735 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007736 current->flags &= ~PF_SWAPWRITE;
7737 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007738 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007739 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007740
7741 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7742
Rik van Riela79311c2009-01-06 14:40:01 -08007743 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007744}
Andrew Morton179e9632006-03-22 00:08:18 -08007745
Mel Gormana5f5f912016-07-28 15:46:32 -07007746int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007747{
David Rientjesd773ed62007-10-16 23:26:01 -07007748 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007749
7750 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007751 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007752 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007753 *
Christoph Lameter96146342006-07-03 00:24:13 -07007754 * A small portion of unmapped file backed pages is needed for
7755 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007756 * thrown out if the node is overallocated. So we do not reclaim
7757 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007758 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007759 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007760 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007761 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7762 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007763 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007764
7765 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007766 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007767 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007768 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007769 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007770
7771 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007772 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007773 * have associated processors. This will favor the local processor
7774 * over remote processors and spread off node memory allocations
7775 * as wide as possible.
7776 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007777 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7778 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007779
Mel Gormana5f5f912016-07-28 15:46:32 -07007780 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7781 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007782
Mel Gormana5f5f912016-07-28 15:46:32 -07007783 ret = __node_reclaim(pgdat, gfp_mask, order);
7784 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007785
Mel Gorman24cf725182009-06-16 15:33:23 -07007786 if (!ret)
7787 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7788
David Rientjesd773ed62007-10-16 23:26:01 -07007789 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007790}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007791#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007792
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007793/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007794 * check_move_unevictable_pages - check pages for evictability and move to
7795 * appropriate zone lru list
7796 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007797 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007798 * Checks pages for evictability, if an evictable page is in the unevictable
7799 * lru list, moves it to the appropriate evictable lru list. This function
7800 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007801 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007802void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007803{
Alex Shi6168d0d2020-12-15 12:34:29 -08007804 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007805 int pgscanned = 0;
7806 int pgrescued = 0;
7807 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007808
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007809 for (i = 0; i < pvec->nr; i++) {
7810 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007811 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007812
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007813 if (PageTransTail(page))
7814 continue;
7815
7816 nr_pages = thp_nr_pages(page);
7817 pgscanned += nr_pages;
7818
Alex Shid25b5bd2020-12-15 12:34:16 -08007819 /* block memcg migration during page moving between lru */
7820 if (!TestClearPageLRU(page))
7821 continue;
7822
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007823 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007824 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007825 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007826 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007827 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007828 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007829 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007830 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007831 }
Hugh Dickins24513262012-01-20 14:34:21 -08007832
Alex Shi6168d0d2020-12-15 12:34:29 -08007833 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007834 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7835 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007836 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007837 } else if (pgscanned) {
7838 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007839 }
Hugh Dickins850465792012-01-20 14:34:19 -08007840}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007841EXPORT_SYMBOL_GPL(check_move_unevictable_pages);