blob: 569c368419bc370894a6e44d444f7034bacc931a [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);
Jianxiong Panf36dd9b2023-05-23 13:37:52 +08002025#ifdef CONFIG_AMLOGIC_LMK
2026 int num = NR_INACTIVE_ANON_CMA - NR_ZONE_INACTIVE_ANON +
2027 NR_ZONE_LRU_BASE;
2028 int migrate_type = 0;
2029#endif /* CONFIG_AMLOGIC_LMK */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002030
Yang Shi98879b32019-07-11 20:59:30 -07002031 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002032 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07002033 while (scan < nr_to_scan && !list_empty(src)) {
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002034 struct list_head *move_to = src;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002035 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002036
Linus Torvalds1da177e2005-04-16 15:20:36 -07002037 page = lru_to_page(src);
2038 prefetchw_prev_lru_page(page, src, flags);
2039
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002040 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002041 total_scan += nr_pages;
2042
Zhaoyang Huang45022652023-05-31 10:51:01 +08002043 if (page_zonenum(page) > sc->reclaim_idx ||
2044 skip_cma(page, sc)) {
Yang Shi98879b32019-07-11 20:59:30 -07002045 nr_skipped[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002046 move_to = &pages_skipped;
2047 goto move;
Mel Gormanb2e18752016-07-28 15:45:37 -07002048 }
2049
Minchan Kim791b48b2017-05-12 15:47:06 -07002050 /*
2051 * Do not count skipped pages because that makes the function
2052 * return with no isolated pages if the LRU mostly contains
2053 * ineligible pages. This causes the VM to not reclaim any
2054 * pages, triggering a premature OOM.
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002055 * Account all tail pages of THP.
Minchan Kim791b48b2017-05-12 15:47:06 -07002056 */
Yang Shi98879b32019-07-11 20:59:30 -07002057 scan += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002058
2059 if (!PageLRU(page))
2060 goto move;
2061 if (!sc->may_unmap && page_mapped(page))
2062 goto move;
2063
Alex Shic2135f72021-02-24 12:08:01 -08002064 /*
2065 * Be careful not to clear PageLRU until after we're
2066 * sure the page is not being freed elsewhere -- the
2067 * page release code relies on it.
2068 */
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002069 if (unlikely(!get_page_unless_zero(page)))
2070 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002071
2072 if (!TestClearPageLRU(page)) {
2073 /* Another thread is already isolating this page */
2074 put_page(page);
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002075 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002076 }
2077
2078 nr_taken += nr_pages;
2079 nr_zone_taken[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002080 move_to = dst;
Jianxiong Panf36dd9b2023-05-23 13:37:52 +08002081 #ifdef CONFIG_AMLOGIC_LMK
2082 migrate_type = get_pageblock_migratetype(page);
2083 if (is_migrate_cma(migrate_type) ||
2084 is_migrate_isolate(migrate_type))
2085 __mod_zone_page_state(page_zone(page),
2086 lru + num, -nr_pages);
2087 #endif /* CONFIG_AMLOGIC_LMK */
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002088move:
2089 list_move(&page->lru, move_to);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002090 }
2091
Mel Gormanb2e18752016-07-28 15:45:37 -07002092 /*
2093 * Splice any skipped pages to the start of the LRU list. Note that
2094 * this disrupts the LRU order when reclaiming for lower zones but
2095 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2096 * scanning would soon rescan the same pages to skip and put the
2097 * system at risk of premature OOM.
2098 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002099 if (!list_empty(&pages_skipped)) {
2100 int zid;
2101
Johannes Weiner3db65812017-05-03 14:52:13 -07002102 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002103 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2104 if (!nr_skipped[zid])
2105 continue;
2106
2107 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002108 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002109 }
2110 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002111 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002112 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002113 total_scan, skipped, nr_taken,
2114 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002115 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002116 return nr_taken;
2117}
2118
Nick Piggin62695a82008-10-18 20:26:09 -07002119/**
2120 * isolate_lru_page - tries to isolate a page from its LRU list
2121 * @page: page to isolate from its LRU list
2122 *
2123 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2124 * vmstat statistic corresponding to whatever LRU list the page was on.
2125 *
2126 * Returns 0 if the page was removed from an LRU list.
2127 * Returns -EBUSY if the page was not on an LRU list.
2128 *
2129 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002130 * the active list, it will have PageActive set. If it was found on
2131 * the unevictable list, it will have the PageUnevictable bit set. That flag
2132 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002133 *
2134 * The vmstat statistic corresponding to the list on which the page was
2135 * found will be decremented.
2136 *
2137 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002138 *
Nick Piggin62695a82008-10-18 20:26:09 -07002139 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002140 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002141 * without a stable reference).
2142 * (2) the lru_lock must not be held.
2143 * (3) interrupts must be enabled.
2144 */
2145int isolate_lru_page(struct page *page)
2146{
2147 int ret = -EBUSY;
2148
Sasha Levin309381fea2014-01-23 15:52:54 -08002149 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002150 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002151
Alex Shid25b5bd2020-12-15 12:34:16 -08002152 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002153 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002154
Alex Shid25b5bd2020-12-15 12:34:16 -08002155 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002156 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002157 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002158 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002159 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002160 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002161
Nick Piggin62695a82008-10-18 20:26:09 -07002162 return ret;
2163}
2164
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002165/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002166 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002167 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002168 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2169 * the LRU list will go small and be scanned faster than necessary, leading to
2170 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002171 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002172static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002173 struct scan_control *sc)
2174{
2175 unsigned long inactive, isolated;
2176
2177 if (current_is_kswapd())
2178 return 0;
2179
Johannes Weinerb5ead352019-11-30 17:55:40 -08002180 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002181 return 0;
2182
2183 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002184 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2185 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002186 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002187 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2188 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002189 }
2190
Fengguang Wu3cf23842012-12-18 14:23:31 -08002191 /*
2192 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2193 * won't get blocked by normal direct-reclaimers, forming a circular
2194 * deadlock.
2195 */
Jianxiong Pan710268f2022-02-24 19:30:46 +08002196#ifndef CONFIG_AMLOGIC_MEMORY_EXTEND
Mel Gormand0164ad2015-11-06 16:28:21 -08002197 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002198 inactive >>= 3;
Jianxiong Pan710268f2022-02-24 19:30:46 +08002199#endif
Fengguang Wu3cf23842012-12-18 14:23:31 -08002200
Tao Zeng54f845e2022-01-26 16:04:08 +08002201#ifdef CONFIG_AMLOGIC_CMA
2202 check_cma_isolated(&isolated, inactive, inactive);
2203#endif
Rik van Riel35cd7812009-09-21 17:01:38 -07002204 return isolated > inactive;
2205}
2206
Kirill Tkhaia222f342019-05-13 17:17:00 -07002207/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002208 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2209 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002210 *
2211 * Returns the number of pages moved to the given lruvec.
2212 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002213static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2214 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002215{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002216 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002217 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002218 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002219
Kirill Tkhaia222f342019-05-13 17:17:00 -07002220 while (!list_empty(list)) {
2221 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002222 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002223 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002224 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002225 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002226 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002227 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002228 continue;
2229 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002230
Alex Shi3d06afa2020-12-15 12:33:37 -08002231 /*
2232 * The SetPageLRU needs to be kept here for list integrity.
2233 * Otherwise:
2234 * #0 move_pages_to_lru #1 release_pages
2235 * if !put_page_testzero
2236 * if (put_page_testzero())
2237 * !PageLRU //skip lru_lock
2238 * SetPageLRU()
2239 * list_add(&page->lru,)
2240 * list_add(&page->lru,)
2241 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002242 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002243
Alex Shi3d06afa2020-12-15 12:33:37 -08002244 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002245 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002246
2247 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002248 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002249 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002250 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002251 } else
2252 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002253
2254 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002255 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002256
Alex Shiafca9152020-12-15 12:34:02 -08002257 /*
2258 * All pages were isolated from the same lruvec (and isolation
2259 * inhibits memcg migration).
2260 */
Muchun Song7467c392021-06-28 19:37:59 -07002261 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002262 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002263 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002264 nr_moved += nr_pages;
2265 if (PageActive(page))
2266 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002267 }
Mel Gorman66635622010-08-09 17:19:30 -07002268
Hugh Dickins3f797682012-01-12 17:20:07 -08002269 /*
2270 * To save our caller's stack, now use input list for pages to free.
2271 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002272 list_splice(&pages_to_free, list);
2273
2274 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002275}
2276
2277/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002278 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002279 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002280 * In that case we should only throttle if the backing device it is
2281 * writing to is congested. In other cases it is safe to throttle.
2282 */
2283static int current_may_throttle(void)
2284{
NeilBrowna37b0712020-06-01 21:48:18 -07002285 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002286 current->backing_dev_info == NULL ||
2287 bdi_write_congested(current->backing_dev_info);
2288}
2289
2290/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002291 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002292 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002293 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002294static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002295shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002296 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002297{
2298 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002299 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002300 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002301 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002302 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002303 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002304 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002305 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002306 bool stalled = false;
Minchan Kim7df45e52022-10-27 08:29:17 -07002307 struct blk_plug plug;
2308 bool do_plug = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002309
Mel Gorman599d0c92016-07-28 15:45:31 -07002310 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002311 if (stalled)
2312 return 0;
2313
2314 /* wait a bit for the reclaimer. */
2315 msleep(100);
2316 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002317
2318 /* We are about to die and free our memory. Return now. */
2319 if (fatal_signal_pending(current))
2320 return SWAP_CLUSTER_MAX;
2321 }
2322
Linus Torvalds1da177e2005-04-16 15:20:36 -07002323 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002324
Alex Shi6168d0d2020-12-15 12:34:29 -08002325 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002326
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002327 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002328 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002329
Mel Gorman599d0c92016-07-28 15:45:31 -07002330 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002331 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002332 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002333 __count_vm_events(item, nr_scanned);
2334 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002335 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2336
Alex Shi6168d0d2020-12-15 12:34:29 -08002337 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002338
Hillf Dantond563c052012-03-21 16:34:02 -07002339 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002340 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002341
Minchan Kim7df45e52022-10-27 08:29:17 -07002342 trace_android_vh_shrink_inactive_list_blk_plug(&do_plug);
2343 if (do_plug)
2344 blk_start_plug(&plug);
Shakeel Butt013339d2020-12-14 19:06:39 -08002345 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002346
Alex Shi6168d0d2020-12-15 12:34:29 -08002347 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002348 move_pages_to_lru(lruvec, &page_list);
2349
2350 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002351 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002352 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002353 __count_vm_events(item, nr_reclaimed);
2354 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002355 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002356 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002357
Minchan Kim7df45e52022-10-27 08:29:17 -07002358 if (do_plug)
2359 blk_finish_plug(&plug);
2360
Alex Shi75cc3c92020-12-15 14:20:50 -08002361 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002362 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002363 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002364
Mel Gorman92df3a72011-10-31 17:07:56 -07002365 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002366 * If dirty pages are scanned that are not queued for IO, it
2367 * implies that flushers are not doing their job. This can
2368 * happen when memory pressure pushes dirty pages to the end of
2369 * the LRU before the dirty limits are breached and the dirty
2370 * data has expired. It can also happen when the proportion of
2371 * dirty pages grows not through writes but through memory
2372 * pressure reclaiming all the clean cache. And in some cases,
2373 * the flushers simply cannot keep up with the allocation
2374 * rate. Nudge the flusher threads in case they are asleep.
2375 */
2376 if (stat.nr_unqueued_dirty == nr_taken)
2377 wakeup_flusher_threads(WB_REASON_VMSCAN);
2378
Andrey Ryabinind108c772018-04-10 16:27:59 -07002379 sc->nr.dirty += stat.nr_dirty;
2380 sc->nr.congested += stat.nr_congested;
2381 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2382 sc->nr.writeback += stat.nr_writeback;
2383 sc->nr.immediate += stat.nr_immediate;
2384 sc->nr.taken += nr_taken;
2385 if (file)
2386 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002387
Mel Gorman599d0c92016-07-28 15:45:31 -07002388 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002389 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002390 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002391}
2392
Hugh Dickins15b44732020-12-15 14:21:31 -08002393/*
2394 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2395 *
2396 * We move them the other way if the page is referenced by one or more
2397 * processes.
2398 *
2399 * If the pages are mostly unmapped, the processing is fast and it is
2400 * appropriate to hold lru_lock across the whole operation. But if
2401 * the pages are mapped, the processing is slow (page_referenced()), so
2402 * we should drop lru_lock around each page. It's impossible to balance
2403 * this, so instead we remove the pages from the LRU while processing them.
2404 * It is safe to rely on PG_active against the non-LRU pages in here because
2405 * nobody will play with that bit on a non-LRU page.
2406 *
2407 * The downside is that we have to touch page->_refcount against each page.
2408 * But we had to alter page->flags anyway.
2409 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002410static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002411 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002412 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002413 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002414{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002415 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002416 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002417 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002418 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002419 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002420 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002421 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002422 unsigned nr_deactivate, nr_activate;
2423 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002424 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002425 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002426 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002427
2428 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002429
Alex Shi6168d0d2020-12-15 12:34:29 -08002430 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002431
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002432 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002433 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002434
Mel Gorman599d0c92016-07-28 15:45:31 -07002435 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002436
Shakeel Butt912c0572020-08-06 23:26:32 -07002437 if (!cgroup_reclaim(sc))
2438 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002439 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002440
Alex Shi6168d0d2020-12-15 12:34:29 -08002441 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002442
Linus Torvalds1da177e2005-04-16 15:20:36 -07002443 while (!list_empty(&l_hold)) {
2444 cond_resched();
2445 page = lru_to_page(&l_hold);
2446 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002447
Hugh Dickins39b5f292012-10-08 16:33:18 -07002448 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002449 putback_lru_page(page);
2450 continue;
2451 }
2452
Mel Gormancc715d92012-03-21 16:34:00 -07002453 if (unlikely(buffer_heads_over_limit)) {
2454 if (page_has_private(page) && trylock_page(page)) {
2455 if (page_has_private(page))
2456 try_to_release_page(page, 0);
2457 unlock_page(page);
2458 }
2459 }
2460
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002461 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2462 if (bypass)
2463 goto skip_page_referenced;
2464
Minchan Kimf74aca72022-05-19 14:08:54 -07002465 /* Referenced or rmap lock contention: rotate */
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002466 if (page_referenced(page, 0, sc->target_mem_cgroup,
Minchan Kimf74aca72022-05-19 14:08:54 -07002467 &vm_flags) != 0) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002468 /*
2469 * Identify referenced, file-backed active pages and
2470 * give them one more trip around the active list. So
2471 * that executable code get better chances to stay in
2472 * memory under moderate memory pressure. Anon pages
2473 * are not likely to be evicted by use-once streaming
2474 * IO, plus JVM can create lots of anon VM_EXEC pages,
2475 * so we ignore them here.
2476 */
Huang Ying9de4f222020-04-06 20:04:41 -07002477 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002478 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002479 list_add(&page->lru, &l_active);
2480 continue;
2481 }
2482 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002483skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002484 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002485 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002486 list_add(&page->lru, &l_inactive);
2487 }
2488
Andrew Mortonb5557492009-01-06 14:40:13 -08002489 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002490 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002491 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002492 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002493
Kirill Tkhaia222f342019-05-13 17:17:00 -07002494 nr_activate = move_pages_to_lru(lruvec, &l_active);
2495 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002496 /* Keep all free pages in l_active list */
2497 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002498
2499 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2500 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2501
Mel Gorman599d0c92016-07-28 15:45:31 -07002502 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002503 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002504
Kirill Tkhaif372d892019-05-13 17:16:57 -07002505 mem_cgroup_uncharge_list(&l_active);
2506 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002507 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2508 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002509}
2510
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002511unsigned long reclaim_pages(struct list_head *page_list)
2512{
Yang Shif661d002020-04-01 21:10:05 -07002513 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002514 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002515 LIST_HEAD(node_page_list);
2516 struct reclaim_stat dummy_stat;
2517 struct page *page;
Minchan Kim7df45e52022-10-27 08:29:17 -07002518 struct blk_plug plug;
2519 bool do_plug = false;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002520 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002521 struct scan_control sc = {
2522 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002523 .may_writepage = 1,
2524 .may_unmap = 1,
2525 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002526 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002527 };
2528
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002529 noreclaim_flag = memalloc_noreclaim_save();
2530
Minchan Kim7df45e52022-10-27 08:29:17 -07002531 trace_android_vh_reclaim_pages_plug(&do_plug);
2532 if (do_plug)
2533 blk_start_plug(&plug);
2534
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002535 while (!list_empty(page_list)) {
2536 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002537 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002538 nid = page_to_nid(page);
2539 INIT_LIST_HEAD(&node_page_list);
2540 }
2541
2542 if (nid == page_to_nid(page)) {
2543 ClearPageActive(page);
2544 list_move(&page->lru, &node_page_list);
2545 continue;
2546 }
2547
2548 nr_reclaimed += shrink_page_list(&node_page_list,
2549 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002550 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002551 while (!list_empty(&node_page_list)) {
2552 page = lru_to_page(&node_page_list);
2553 list_del(&page->lru);
2554 putback_lru_page(page);
2555 }
2556
Yang Shif661d002020-04-01 21:10:05 -07002557 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002558 }
2559
2560 if (!list_empty(&node_page_list)) {
2561 nr_reclaimed += shrink_page_list(&node_page_list,
2562 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002563 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002564 while (!list_empty(&node_page_list)) {
2565 page = lru_to_page(&node_page_list);
2566 list_del(&page->lru);
2567 putback_lru_page(page);
2568 }
2569 }
2570
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002571 memalloc_noreclaim_restore(noreclaim_flag);
2572
Minchan Kim7df45e52022-10-27 08:29:17 -07002573 if (do_plug)
2574 blk_finish_plug(&plug);
2575
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002576 return nr_reclaimed;
2577}
2578
Johannes Weinerb91ac372019-11-30 17:56:02 -08002579static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2580 struct lruvec *lruvec, struct scan_control *sc)
2581{
2582 if (is_active_lru(lru)) {
2583 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2584 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2585 else
2586 sc->skipped_deactivate = 1;
2587 return 0;
2588 }
2589
2590 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2591}
2592
Rik van Riel59dc76b2016-05-20 16:56:31 -07002593/*
2594 * The inactive anon list should be small enough that the VM never has
2595 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002596 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002597 * The inactive file list should be small enough to leave most memory
2598 * to the established workingset on the scan-resistant active list,
2599 * but large enough to avoid thrashing the aggregate readahead window.
2600 *
2601 * Both inactive lists should also be large enough that each inactive
2602 * page has a chance to be referenced again before it is reclaimed.
2603 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002604 * If that fails and refaulting is observed, the inactive list grows.
2605 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002606 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002607 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002608 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2609 *
2610 * total target max
2611 * memory ratio inactive
2612 * -------------------------------------
2613 * 10MB 1 5MB
2614 * 100MB 1 50MB
2615 * 1GB 3 250MB
2616 * 10GB 10 0.9GB
2617 * 100GB 31 3GB
2618 * 1TB 101 10GB
2619 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002620 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002621static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002622{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002623 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002624 unsigned long inactive, active;
2625 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002626 unsigned long gb;
2627
Johannes Weinerb91ac372019-11-30 17:56:02 -08002628 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2629 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002630
Johannes Weinerb91ac372019-11-30 17:56:02 -08002631 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002632 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002633 inactive_ratio = int_sqrt(10 * gb);
2634 else
2635 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002636
Rik van Riel59dc76b2016-05-20 16:56:31 -07002637 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002638}
2639
Johannes Weiner9a265112013-02-22 16:32:17 -08002640enum scan_balance {
2641 SCAN_EQUAL,
2642 SCAN_FRACT,
2643 SCAN_ANON,
2644 SCAN_FILE,
2645};
2646
Yu Zhao6d313442022-09-18 02:00:00 -06002647static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2648{
2649 unsigned long file;
2650 struct lruvec *target_lruvec;
2651
Yu Zhao37397872022-09-18 02:00:03 -06002652 if (lru_gen_enabled())
2653 return;
2654
Yu Zhao6d313442022-09-18 02:00:00 -06002655 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2656
2657 /*
2658 * Flush the memory cgroup stats, so that we read accurate per-memcg
2659 * lruvec stats for heuristics.
2660 */
2661 mem_cgroup_flush_stats();
2662
2663 /*
2664 * Determine the scan balance between anon and file LRUs.
2665 */
2666 spin_lock_irq(&target_lruvec->lru_lock);
2667 sc->anon_cost = target_lruvec->anon_cost;
2668 sc->file_cost = target_lruvec->file_cost;
2669 spin_unlock_irq(&target_lruvec->lru_lock);
2670
2671 /*
2672 * Target desirable inactive:active list ratios for the anon
2673 * and file LRU lists.
2674 */
2675 if (!sc->force_deactivate) {
2676 unsigned long refaults;
2677
2678 refaults = lruvec_page_state(target_lruvec,
2679 WORKINGSET_ACTIVATE_ANON);
2680 if (refaults != target_lruvec->refaults[0] ||
2681 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2682 sc->may_deactivate |= DEACTIVATE_ANON;
2683 else
2684 sc->may_deactivate &= ~DEACTIVATE_ANON;
2685
2686 /*
2687 * When refaults are being observed, it means a new
2688 * workingset is being established. Deactivate to get
2689 * rid of any stale active pages quickly.
2690 */
2691 refaults = lruvec_page_state(target_lruvec,
2692 WORKINGSET_ACTIVATE_FILE);
2693 if (refaults != target_lruvec->refaults[1] ||
2694 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2695 sc->may_deactivate |= DEACTIVATE_FILE;
2696 else
2697 sc->may_deactivate &= ~DEACTIVATE_FILE;
2698 } else
2699 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2700
2701 /*
2702 * If we have plenty of inactive file pages that aren't
2703 * thrashing, try to reclaim those first before touching
2704 * anonymous pages.
2705 */
2706 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2707 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2708 sc->cache_trim_mode = 1;
2709 else
2710 sc->cache_trim_mode = 0;
2711
2712 /*
2713 * Prevent the reclaimer from falling into the cache trap: as
2714 * cache pages start out inactive, every cache fault will tip
2715 * the scan balance towards the file LRU. And as the file LRU
2716 * shrinks, so does the window for rotation from references.
2717 * This means we have a runaway feedback loop where a tiny
2718 * thrashing file LRU becomes infinitely more attractive than
2719 * anon pages. Try to detect this based on file LRU size.
2720 */
2721 if (!cgroup_reclaim(sc)) {
2722 unsigned long total_high_wmark = 0;
2723 unsigned long free, anon;
2724 int z;
2725
2726 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2727 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2728 node_page_state(pgdat, NR_INACTIVE_FILE);
2729
2730 for (z = 0; z < MAX_NR_ZONES; z++) {
2731 struct zone *zone = &pgdat->node_zones[z];
2732
2733 if (!managed_zone(zone))
2734 continue;
2735
2736 total_high_wmark += high_wmark_pages(zone);
2737 }
2738
2739 /*
2740 * Consider anon: if that's low too, this isn't a
2741 * runaway file reclaim problem, but rather just
2742 * extreme pressure. Reclaim as per usual then.
2743 */
2744 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2745
2746 sc->file_is_tiny =
2747 file + free <= total_high_wmark &&
2748 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2749 anon >> sc->priority;
2750 }
2751}
2752
Linus Torvalds1da177e2005-04-16 15:20:36 -07002753/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002754 * Determine how aggressively the anon and file LRU lists should be
2755 * scanned. The relative value of each set of LRU lists is determined
2756 * by looking at the fraction of the pages scanned we did rotate back
2757 * onto the active list instead of evict.
2758 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002759 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2760 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002761 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002762static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2763 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002764{
Keith Buscha2a36482021-09-02 14:59:26 -07002765 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002766 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002767 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002768 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002769 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002770 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002771 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002772 unsigned long ap, fp;
2773 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002774 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002775
2776 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002777 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002778 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002779 goto out;
2780 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002781
Johannes Weiner10316b32013-02-22 16:32:14 -08002782 /*
2783 * Global reclaim will swap to prevent OOM even with no
2784 * swappiness, but memcg users want to use this knob to
2785 * disable swapping for individual groups completely when
2786 * using the memory controller's swap limit feature would be
2787 * too expensive.
2788 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002789 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002790 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002791 goto out;
2792 }
2793
2794 /*
2795 * Do not apply any pressure balancing cleverness when the
2796 * system is close to OOM, scan both anon and file equally
2797 * (unless the swappiness setting disagrees with swapping).
2798 */
Johannes Weiner02695172014-08-06 16:06:17 -07002799 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002800 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002801 goto out;
2802 }
2803
Johannes Weiner11d16c22013-02-22 16:32:15 -08002804 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002805 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002806 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002807 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002808 scan_balance = SCAN_ANON;
2809 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002810 }
2811
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002812 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2813
Johannes Weiner62376252014-05-06 12:50:07 -07002814 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002815 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002816 * anything from the anonymous working right now. But when balancing
2817 * anon and page cache files for reclaim, allow swapping of anon pages
2818 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002819 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002820 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002821 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002822 goto out;
2823 }
2824
Johannes Weiner9a265112013-02-22 16:32:17 -08002825 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002826 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002827 * Calculate the pressure balance between anon and file pages.
2828 *
2829 * The amount of pressure we put on each LRU is inversely
2830 * proportional to the cost of reclaiming each list, as
2831 * determined by the share of pages that are refaulting, times
2832 * the relative IO cost of bringing back a swapped out
2833 * anonymous page vs reloading a filesystem page (swappiness).
2834 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002835 * Although we limit that influence to ensure no list gets
2836 * left behind completely: at least a third of the pressure is
2837 * applied, before swappiness.
2838 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002839 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002840 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002841 total_cost = sc->anon_cost + sc->file_cost;
2842 anon_cost = total_cost + sc->anon_cost;
2843 file_cost = total_cost + sc->file_cost;
2844 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002845
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002846 ap = swappiness * (total_cost + 1);
2847 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002848
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002849 fp = (200 - swappiness) * (total_cost + 1);
2850 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002851
Shaohua Li76a33fc2010-05-24 14:32:36 -07002852 fraction[0] = ap;
2853 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002854 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002855out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002856 for_each_evictable_lru(lru) {
2857 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002858 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002859 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002860 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002861
Chris Down9783aa92019-10-06 17:58:32 -07002862 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002863 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2864 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002865
Johannes Weinerf56ce412021-08-19 19:04:21 -07002866 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002867 /*
2868 * Scale a cgroup's reclaim pressure by proportioning
2869 * its current usage to its memory.low or memory.min
2870 * setting.
2871 *
2872 * This is important, as otherwise scanning aggression
2873 * becomes extremely binary -- from nothing as we
2874 * approach the memory protection threshold, to totally
2875 * nominal as we exceed it. This results in requiring
2876 * setting extremely liberal protection thresholds. It
2877 * also means we simply get no protection at all if we
2878 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002879 *
2880 * If there is any protection in place, we reduce scan
2881 * pressure by how much of the total memory used is
2882 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002883 *
Chris Down9de7ca42019-10-06 17:58:35 -07002884 * There is one special case: in the first reclaim pass,
2885 * we skip over all groups that are within their low
2886 * protection. If that fails to reclaim enough pages to
2887 * satisfy the reclaim goal, we come back and override
2888 * the best-effort low protection. However, we still
2889 * ideally want to honor how well-behaved groups are in
2890 * that case instead of simply punishing them all
2891 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002892 * memory they are using, reducing the scan pressure
2893 * again by how much of the total memory used is under
2894 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002895 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002896 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002897 unsigned long protection;
2898
2899 /* memory.low scaling, make sure we retry before OOM */
2900 if (!sc->memcg_low_reclaim && low > min) {
2901 protection = low;
2902 sc->memcg_low_skipped = 1;
2903 } else {
2904 protection = min;
2905 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002906
2907 /* Avoid TOCTOU with earlier protection check */
2908 cgroup_size = max(cgroup_size, protection);
2909
2910 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002911 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002912
2913 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002914 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002915 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002916 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002917 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002918 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002919 } else {
2920 scan = lruvec_size;
2921 }
2922
2923 scan >>= sc->priority;
2924
Johannes Weiner688035f2017-05-03 14:52:07 -07002925 /*
2926 * If the cgroup's already been deleted, make sure to
2927 * scrape out the remaining cache.
2928 */
2929 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002930 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002931
Johannes Weiner688035f2017-05-03 14:52:07 -07002932 switch (scan_balance) {
2933 case SCAN_EQUAL:
2934 /* Scan lists relative to size */
2935 break;
2936 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002937 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002938 * Scan types proportional to swappiness and
2939 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002940 * Make sure we don't miss the last page on
2941 * the offlined memory cgroups because of a
2942 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002943 */
Gavin Shan76073c62020-02-20 20:04:24 -08002944 scan = mem_cgroup_online(memcg) ?
2945 div64_u64(scan * fraction[file], denominator) :
2946 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002947 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002948 break;
2949 case SCAN_FILE:
2950 case SCAN_ANON:
2951 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002952 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002953 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002954 break;
2955 default:
2956 /* Look ma, no brain */
2957 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002958 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002959
Johannes Weiner688035f2017-05-03 14:52:07 -07002960 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002961 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002962}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002963
Dave Hansen2f368a92021-09-02 14:59:23 -07002964/*
2965 * Anonymous LRU management is a waste if there is
2966 * ultimately no way to reclaim the memory.
2967 */
2968static bool can_age_anon_pages(struct pglist_data *pgdat,
2969 struct scan_control *sc)
2970{
2971 /* Aging the anon LRU is valuable if swap is present: */
2972 if (total_swap_pages > 0)
2973 return true;
2974
2975 /* Also valuable if anon pages can be demoted: */
2976 return can_demote(pgdat->node_id, sc);
2977}
2978
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002979#ifdef CONFIG_LRU_GEN
2980
Yu Zhaobaeb9a02022-09-18 02:00:07 -06002981#ifdef CONFIG_LRU_GEN_ENABLED
2982DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2983#define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2984#else
2985DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2986#define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2987#endif
2988
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002989/******************************************************************************
2990 * shorthand helpers
2991 ******************************************************************************/
2992
Yu Zhao37397872022-09-18 02:00:03 -06002993#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2994
2995#define DEFINE_MAX_SEQ(lruvec) \
2996 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2997
2998#define DEFINE_MIN_SEQ(lruvec) \
2999 unsigned long min_seq[ANON_AND_FILE] = { \
3000 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
3001 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
3002 }
3003
Yu Zhaod5b2fa12022-09-18 02:00:02 -06003004#define for_each_gen_type_zone(gen, type, zone) \
3005 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
3006 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
3007 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
3008
Yu Zhaoa3eb6512022-12-21 21:19:04 -07003009#define get_memcg_gen(seq) ((seq) % MEMCG_NR_GENS)
3010#define get_memcg_bin(bin) ((bin) % MEMCG_NR_BINS)
3011
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003012static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
Yu Zhaod5b2fa12022-09-18 02:00:02 -06003013{
3014 struct pglist_data *pgdat = NODE_DATA(nid);
3015
3016#ifdef CONFIG_MEMCG
3017 if (memcg) {
3018 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
3019
3020 /* for hotadd_new_pgdat() */
3021 if (!lruvec->pgdat)
3022 lruvec->pgdat = pgdat;
3023
3024 return lruvec;
3025 }
3026#endif
3027 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3028
3029 return pgdat ? &pgdat->__lruvec : NULL;
3030}
3031
Yu Zhao37397872022-09-18 02:00:03 -06003032static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
3033{
3034 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3035 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3036
Yu Zhaof8b57162022-12-21 21:19:05 -07003037 if (!sc->may_swap)
3038 return 0;
3039
Kalesh Singhb8d031e2023-04-03 15:28:17 -07003040 if (!can_demote(pgdat->node_id, sc) &&
3041 mem_cgroup_get_nr_swap_pages(memcg) <= 0)
Yu Zhao37397872022-09-18 02:00:03 -06003042 return 0;
3043
3044 return mem_cgroup_swappiness(memcg);
3045}
3046
3047static int get_nr_gens(struct lruvec *lruvec, int type)
3048{
3049 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3050}
3051
3052static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3053{
Yu Zhao3c6c3592022-12-21 21:18:59 -07003054 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06003055 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3056 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3057 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3058}
3059
3060/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003061 * mm_struct list
3062 ******************************************************************************/
3063
3064static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3065{
3066 static struct lru_gen_mm_list mm_list = {
3067 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3068 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3069 };
3070
3071#ifdef CONFIG_MEMCG
3072 if (memcg)
3073 return &memcg->mm_list;
3074#endif
3075 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3076
3077 return &mm_list;
3078}
3079
3080void lru_gen_add_mm(struct mm_struct *mm)
3081{
3082 int nid;
3083 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3084 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3085
3086 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3087#ifdef CONFIG_MEMCG
3088 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3089 mm->lru_gen.memcg = memcg;
3090#endif
3091 spin_lock(&mm_list->lock);
3092
3093 for_each_node_state(nid, N_MEMORY) {
3094 struct lruvec *lruvec = get_lruvec(memcg, nid);
3095
3096 if (!lruvec)
3097 continue;
3098
3099 /* the first addition since the last iteration */
3100 if (lruvec->mm_state.tail == &mm_list->fifo)
3101 lruvec->mm_state.tail = &mm->lru_gen.list;
3102 }
3103
3104 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3105
3106 spin_unlock(&mm_list->lock);
3107}
3108
3109void lru_gen_del_mm(struct mm_struct *mm)
3110{
3111 int nid;
3112 struct lru_gen_mm_list *mm_list;
3113 struct mem_cgroup *memcg = NULL;
3114
3115 if (list_empty(&mm->lru_gen.list))
3116 return;
3117
3118#ifdef CONFIG_MEMCG
3119 memcg = mm->lru_gen.memcg;
3120#endif
3121 mm_list = get_mm_list(memcg);
3122
3123 spin_lock(&mm_list->lock);
3124
3125 for_each_node(nid) {
3126 struct lruvec *lruvec = get_lruvec(memcg, nid);
3127
3128 if (!lruvec)
3129 continue;
3130
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003131 /* where the current iteration continues after */
3132 if (lruvec->mm_state.head == &mm->lru_gen.list)
3133 lruvec->mm_state.head = lruvec->mm_state.head->prev;
3134
3135 /* where the last iteration ended before */
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003136 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3137 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003138 }
3139
3140 list_del_init(&mm->lru_gen.list);
3141
3142 spin_unlock(&mm_list->lock);
3143
3144#ifdef CONFIG_MEMCG
3145 mem_cgroup_put(mm->lru_gen.memcg);
3146 mm->lru_gen.memcg = NULL;
3147#endif
3148}
3149
3150#ifdef CONFIG_MEMCG
3151void lru_gen_migrate_mm(struct mm_struct *mm)
3152{
3153 struct mem_cgroup *memcg;
3154 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3155
3156 VM_WARN_ON_ONCE(task->mm != mm);
3157 lockdep_assert_held(&task->alloc_lock);
3158
3159 /* for mm_update_next_owner() */
3160 if (mem_cgroup_disabled())
3161 return;
3162
Yu Zhao578a3a32023-01-15 20:44:05 -07003163 /* migration can happen before addition */
3164 if (!mm->lru_gen.memcg)
3165 return;
3166
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003167 rcu_read_lock();
3168 memcg = mem_cgroup_from_task(task);
3169 rcu_read_unlock();
3170 if (memcg == mm->lru_gen.memcg)
3171 return;
3172
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003173 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3174
3175 lru_gen_del_mm(mm);
3176 lru_gen_add_mm(mm);
3177}
3178#endif
3179
3180/*
3181 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3182 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3183 * bits in a bitmap, k is the number of hash functions and n is the number of
3184 * inserted items.
3185 *
3186 * Page table walkers use one of the two filters to reduce their search space.
3187 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3188 * aging uses the double-buffering technique to flip to the other filter each
3189 * time it produces a new generation. For non-leaf entries that have enough
3190 * leaf entries, the aging carries them over to the next generation in
3191 * walk_pmd_range(); the eviction also report them when walking the rmap
3192 * in lru_gen_look_around().
3193 *
3194 * For future optimizations:
3195 * 1. It's not necessary to keep both filters all the time. The spare one can be
3196 * freed after the RCU grace period and reallocated if needed again.
3197 * 2. And when reallocating, it's worth scaling its size according to the number
3198 * of inserted entries in the other filter, to reduce the memory overhead on
3199 * small systems and false positives on large systems.
3200 * 3. Jenkins' hash function is an alternative to Knuth's.
3201 */
3202#define BLOOM_FILTER_SHIFT 15
3203
3204static inline int filter_gen_from_seq(unsigned long seq)
3205{
3206 return seq % NR_BLOOM_FILTERS;
3207}
3208
3209static void get_item_key(void *item, int *key)
3210{
3211 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3212
3213 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3214
3215 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3216 key[1] = hash >> BLOOM_FILTER_SHIFT;
3217}
3218
3219static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3220{
3221 unsigned long *filter;
3222 int gen = filter_gen_from_seq(seq);
3223
3224 filter = lruvec->mm_state.filters[gen];
3225 if (filter) {
3226 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3227 return;
3228 }
3229
3230 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3231 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3232 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3233}
3234
3235static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3236{
3237 int key[2];
3238 unsigned long *filter;
3239 int gen = filter_gen_from_seq(seq);
3240
3241 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3242 if (!filter)
3243 return;
3244
3245 get_item_key(item, key);
3246
3247 if (!test_bit(key[0], filter))
3248 set_bit(key[0], filter);
3249 if (!test_bit(key[1], filter))
3250 set_bit(key[1], filter);
3251}
3252
3253static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3254{
3255 int key[2];
3256 unsigned long *filter;
3257 int gen = filter_gen_from_seq(seq);
3258
3259 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3260 if (!filter)
3261 return true;
3262
3263 get_item_key(item, key);
3264
3265 return test_bit(key[0], filter) && test_bit(key[1], filter);
3266}
3267
3268static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3269{
3270 int i;
3271 int hist;
3272
3273 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3274
3275 if (walk) {
3276 hist = lru_hist_from_seq(walk->max_seq);
3277
3278 for (i = 0; i < NR_MM_STATS; i++) {
3279 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3280 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3281 walk->mm_stats[i] = 0;
3282 }
3283 }
3284
3285 if (NR_HIST_GENS > 1 && last) {
3286 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3287
3288 for (i = 0; i < NR_MM_STATS; i++)
3289 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3290 }
3291}
3292
3293static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3294{
3295 int type;
3296 unsigned long size = 0;
3297 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3298 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3299
3300 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3301 return true;
3302
3303 clear_bit(key, &mm->lru_gen.bitmap);
3304
3305 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3306 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3307 get_mm_counter(mm, MM_ANONPAGES) +
3308 get_mm_counter(mm, MM_SHMEMPAGES);
3309 }
3310
3311 if (size < MIN_LRU_BATCH)
3312 return true;
3313
3314 return !mmget_not_zero(mm);
3315}
3316
3317static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3318 struct mm_struct **iter)
3319{
3320 bool first = false;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003321 bool last = false;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003322 struct mm_struct *mm = NULL;
3323 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3324 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3325 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3326
3327 /*
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003328 * mm_state->seq is incremented after each iteration of mm_list. There
3329 * are three interesting cases for this page table walker:
3330 * 1. It tries to start a new iteration with a stale max_seq: there is
3331 * nothing left to do.
3332 * 2. It started the next iteration: it needs to reset the Bloom filter
3333 * so that a fresh set of PTE tables can be recorded.
3334 * 3. It ended the current iteration: it needs to reset the mm stats
3335 * counters and tell its caller to increment max_seq.
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003336 */
3337 spin_lock(&mm_list->lock);
3338
3339 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003340
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003341 if (walk->max_seq <= mm_state->seq)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003342 goto done;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003343
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003344 if (!mm_state->head)
3345 mm_state->head = &mm_list->fifo;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003346
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003347 if (mm_state->head == &mm_list->fifo)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003348 first = true;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003349
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003350 do {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003351 mm_state->head = mm_state->head->next;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003352 if (mm_state->head == &mm_list->fifo) {
3353 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3354 last = true;
3355 break;
3356 }
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003357
3358 /* force scan for those added after the last iteration */
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003359 if (!mm_state->tail || mm_state->tail == mm_state->head) {
3360 mm_state->tail = mm_state->head->next;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003361 walk->force_scan = true;
3362 }
3363
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003364 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003365 if (should_skip_mm(mm, walk))
3366 mm = NULL;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003367 } while (!mm);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003368done:
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003369 if (*iter || last)
3370 reset_mm_stats(lruvec, walk, last);
3371
3372 spin_unlock(&mm_list->lock);
3373
3374 if (mm && first)
3375 reset_bloom_filter(lruvec, walk->max_seq + 1);
3376
3377 if (*iter)
3378 mmput_async(*iter);
3379
3380 *iter = mm;
3381
3382 return last;
3383}
3384
3385static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3386{
3387 bool success = false;
3388 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3389 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3390 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3391
3392 spin_lock(&mm_list->lock);
3393
3394 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3395
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003396 if (max_seq > mm_state->seq) {
3397 mm_state->head = NULL;
3398 mm_state->tail = NULL;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003399 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3400 reset_mm_stats(lruvec, NULL, true);
3401 success = true;
3402 }
3403
3404 spin_unlock(&mm_list->lock);
3405
3406 return success;
3407}
3408
3409/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003410 * refault feedback loop
3411 ******************************************************************************/
3412
3413/*
3414 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3415 *
3416 * The P term is refaulted/(evicted+protected) from a tier in the generation
3417 * currently being evicted; the I term is the exponential moving average of the
3418 * P term over the generations previously evicted, using the smoothing factor
3419 * 1/2; the D term isn't supported.
3420 *
3421 * The setpoint (SP) is always the first tier of one type; the process variable
3422 * (PV) is either any tier of the other type or any other tier of the same
3423 * type.
3424 *
3425 * The error is the difference between the SP and the PV; the correction is to
3426 * turn off protection when SP>PV or turn on protection when SP<PV.
3427 *
3428 * For future optimizations:
3429 * 1. The D term may discount the other two terms over time so that long-lived
3430 * generations can resist stale information.
3431 */
3432struct ctrl_pos {
3433 unsigned long refaulted;
3434 unsigned long total;
3435 int gain;
3436};
3437
3438static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3439 struct ctrl_pos *pos)
3440{
Yu Zhao3c6c3592022-12-21 21:18:59 -07003441 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003442 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3443
3444 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3445 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3446 pos->total = lrugen->avg_total[type][tier] +
3447 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3448 if (tier)
3449 pos->total += lrugen->protected[hist][type][tier - 1];
3450 pos->gain = gain;
3451}
3452
3453static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3454{
3455 int hist, tier;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003456 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003457 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3458 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3459
3460 lockdep_assert_held(&lruvec->lru_lock);
3461
3462 if (!carryover && !clear)
3463 return;
3464
3465 hist = lru_hist_from_seq(seq);
3466
3467 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3468 if (carryover) {
3469 unsigned long sum;
3470
3471 sum = lrugen->avg_refaulted[type][tier] +
3472 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3473 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3474
3475 sum = lrugen->avg_total[type][tier] +
3476 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3477 if (tier)
3478 sum += lrugen->protected[hist][type][tier - 1];
3479 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3480 }
3481
3482 if (clear) {
3483 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3484 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3485 if (tier)
3486 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3487 }
3488 }
3489}
3490
3491static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3492{
3493 /*
3494 * Return true if the PV has a limited number of refaults or a lower
3495 * refaulted/total than the SP.
3496 */
3497 return pv->refaulted < MIN_LRU_BATCH ||
3498 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3499 (sp->refaulted + 1) * pv->total * pv->gain;
3500}
3501
3502/******************************************************************************
3503 * the aging
3504 ******************************************************************************/
3505
Yu Zhao0182f922022-09-18 02:00:04 -06003506/* promote pages accessed through page tables */
3507static int page_update_gen(struct page *page, int gen)
3508{
3509 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3510
3511 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3512 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3513
3514 do {
3515 /* lru_gen_del_page() has isolated this page? */
3516 if (!(old_flags & LRU_GEN_MASK)) {
3517 /* for shrink_page_list() */
3518 new_flags = old_flags | BIT(PG_referenced);
3519 continue;
3520 }
3521
3522 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3523 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3524 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3525
3526 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3527}
3528
Yu Zhao37397872022-09-18 02:00:03 -06003529/* protect pages accessed multiple times through file descriptors */
3530static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3531{
3532 int type = page_is_file_lru(page);
Yu Zhao3c6c3592022-12-21 21:18:59 -07003533 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003534 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3535 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3536
3537 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3538
3539 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003540 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3541 /* page_update_gen() has promoted this page? */
3542 if (new_gen >= 0 && new_gen != old_gen)
3543 return new_gen;
3544
Yu Zhao37397872022-09-18 02:00:03 -06003545 new_gen = (old_gen + 1) % MAX_NR_GENS;
3546
3547 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3548 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3549 /* for end_page_writeback() */
3550 if (reclaiming)
3551 new_flags |= BIT(PG_reclaim);
3552 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3553
3554 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3555
3556 return new_gen;
3557}
3558
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003559static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3560 int old_gen, int new_gen)
3561{
3562 int type = page_is_file_lru(page);
3563 int zone = page_zonenum(page);
3564 int delta = thp_nr_pages(page);
3565
3566 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3567 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3568
3569 walk->batched++;
3570
3571 walk->nr_pages[old_gen][type][zone] -= delta;
3572 walk->nr_pages[new_gen][type][zone] += delta;
3573}
3574
3575static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3576{
3577 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003578 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003579
3580 walk->batched = 0;
3581
3582 for_each_gen_type_zone(gen, type, zone) {
3583 enum lru_list lru = type * LRU_INACTIVE_FILE;
3584 int delta = walk->nr_pages[gen][type][zone];
3585
3586 if (!delta)
3587 continue;
3588
3589 walk->nr_pages[gen][type][zone] = 0;
3590 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3591 lrugen->nr_pages[gen][type][zone] + delta);
3592
3593 if (lru_gen_is_active(lruvec, gen))
3594 lru += LRU_ACTIVE;
3595 __update_lru_size(lruvec, lru, zone, delta);
3596 }
3597}
3598
3599static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3600{
3601 struct address_space *mapping;
3602 struct vm_area_struct *vma = args->vma;
3603 struct lru_gen_mm_walk *walk = args->private;
3604
3605 if (!vma_is_accessible(vma))
3606 return true;
3607
3608 if (is_vm_hugetlb_page(vma))
3609 return true;
3610
Yu Zhao3b9ab092022-12-30 14:52:51 -07003611 if (!vma_has_recency(vma))
3612 return true;
3613
3614 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003615 return true;
3616
3617 if (vma == get_gate_vma(vma->vm_mm))
3618 return true;
3619
3620 if (vma_is_anonymous(vma))
3621 return !walk->can_swap;
3622
3623 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3624 return true;
3625
3626 mapping = vma->vm_file->f_mapping;
3627 if (mapping_unevictable(mapping))
3628 return true;
3629
3630 if (shmem_mapping(mapping))
3631 return !walk->can_swap;
3632
3633 /* to exclude special mappings like dax, etc. */
3634 return !mapping->a_ops->readpage;
3635}
3636
3637/*
3638 * Some userspace memory allocators map many single-page VMAs. Instead of
3639 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3640 * table to reduce zigzags and improve cache performance.
3641 */
3642static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3643 unsigned long *vm_start, unsigned long *vm_end)
3644{
3645 unsigned long start = round_up(*vm_end, size);
3646 unsigned long end = (start | ~mask) + 1;
3647
3648 VM_WARN_ON_ONCE(mask & size);
3649 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3650
3651 while (args->vma) {
3652 if (start >= args->vma->vm_end) {
3653 args->vma = args->vma->vm_next;
3654 continue;
3655 }
3656
3657 if (end && end <= args->vma->vm_start)
3658 return false;
3659
3660 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3661 args->vma = args->vma->vm_next;
3662 continue;
3663 }
3664
3665 *vm_start = max(start, args->vma->vm_start);
3666 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3667
3668 return true;
3669 }
3670
3671 return false;
3672}
3673
Yu Zhao0182f922022-09-18 02:00:04 -06003674static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3675{
3676 unsigned long pfn = pte_pfn(pte);
3677
3678 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3679
3680 if (!pte_present(pte) || is_zero_pfn(pfn))
3681 return -1;
3682
3683 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3684 return -1;
3685
3686 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3687 return -1;
3688
3689 return pfn;
3690}
3691
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003692#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3693static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3694{
3695 unsigned long pfn = pmd_pfn(pmd);
3696
3697 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3698
3699 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3700 return -1;
3701
3702 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3703 return -1;
3704
3705 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3706 return -1;
3707
3708 return pfn;
3709}
3710#endif
3711
Yu Zhao0182f922022-09-18 02:00:04 -06003712static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003713 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003714{
3715 struct page *page;
3716
3717 /* try to avoid unnecessary memory loads */
3718 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3719 return NULL;
3720
3721 page = compound_head(pfn_to_page(pfn));
3722 if (page_to_nid(page) != pgdat->node_id)
3723 return NULL;
3724
3725 if (page_memcg_rcu(page) != memcg)
3726 return NULL;
3727
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003728 /* file VMAs can contain anon pages from COW */
3729 if (!page_is_file_lru(page) && !can_swap)
3730 return NULL;
3731
Yu Zhao0182f922022-09-18 02:00:04 -06003732 return page;
3733}
3734
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003735static bool suitable_to_scan(int total, int young)
3736{
3737 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3738
3739 /* suitable if the average number of young PTEs per cacheline is >=1 */
3740 return young * n >= total;
3741}
3742
3743static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3744 struct mm_walk *args)
3745{
3746 int i;
3747 pte_t *pte;
3748 spinlock_t *ptl;
3749 unsigned long addr;
3750 int total = 0;
3751 int young = 0;
3752 struct lru_gen_mm_walk *walk = args->private;
3753 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3754 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3755 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3756
3757 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3758
3759 ptl = pte_lockptr(args->mm, pmd);
3760 if (!spin_trylock(ptl))
3761 return false;
3762
3763 arch_enter_lazy_mmu_mode();
3764
3765 pte = pte_offset_map(pmd, start & PMD_MASK);
3766restart:
3767 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3768 unsigned long pfn;
3769 struct page *page;
3770
3771 total++;
3772 walk->mm_stats[MM_LEAF_TOTAL]++;
3773
3774 pfn = get_pte_pfn(pte[i], args->vma, addr);
3775 if (pfn == -1)
3776 continue;
3777
3778 if (!pte_young(pte[i])) {
3779 walk->mm_stats[MM_LEAF_OLD]++;
3780 continue;
3781 }
3782
3783 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3784 if (!page)
3785 continue;
3786
3787 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3788 VM_WARN_ON_ONCE(true);
3789
3790 young++;
3791 walk->mm_stats[MM_LEAF_YOUNG]++;
3792
3793 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3794 !(PageAnon(page) && PageSwapBacked(page) &&
3795 !PageSwapCache(page)))
3796 set_page_dirty(page);
3797
3798 old_gen = page_update_gen(page, new_gen);
3799 if (old_gen >= 0 && old_gen != new_gen)
3800 update_batch_size(walk, page, old_gen, new_gen);
3801 }
3802
3803 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3804 goto restart;
3805
3806 pte_unmap(pte);
3807
3808 arch_leave_lazy_mmu_mode();
3809 spin_unlock(ptl);
3810
3811 return suitable_to_scan(total, young);
3812}
3813
3814#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3815static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3816 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3817{
3818 int i;
3819 pmd_t *pmd;
3820 spinlock_t *ptl;
3821 struct lru_gen_mm_walk *walk = args->private;
3822 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3823 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3824 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3825
3826 VM_WARN_ON_ONCE(pud_leaf(*pud));
3827
3828 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3829 if (*start == -1) {
3830 *start = next;
3831 return;
3832 }
3833
3834 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3835 if (i && i <= MIN_LRU_BATCH) {
3836 __set_bit(i - 1, bitmap);
3837 return;
3838 }
3839
3840 pmd = pmd_offset(pud, *start);
3841
3842 ptl = pmd_lockptr(args->mm, pmd);
3843 if (!spin_trylock(ptl))
3844 goto done;
3845
3846 arch_enter_lazy_mmu_mode();
3847
3848 do {
3849 unsigned long pfn;
3850 struct page *page;
3851 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3852
3853 pfn = get_pmd_pfn(pmd[i], vma, addr);
3854 if (pfn == -1)
3855 goto next;
3856
3857 if (!pmd_trans_huge(pmd[i])) {
Juergen Gross23811792022-11-23 07:45:10 +01003858 if (arch_has_hw_nonleaf_pmd_young() &&
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003859 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003860 pmdp_test_and_clear_young(vma, addr, pmd + i);
3861 goto next;
3862 }
3863
3864 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3865 if (!page)
3866 goto next;
3867
3868 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3869 goto next;
3870
3871 walk->mm_stats[MM_LEAF_YOUNG]++;
3872
3873 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3874 !(PageAnon(page) && PageSwapBacked(page) &&
3875 !PageSwapCache(page)))
3876 set_page_dirty(page);
3877
3878 old_gen = page_update_gen(page, new_gen);
3879 if (old_gen >= 0 && old_gen != new_gen)
3880 update_batch_size(walk, page, old_gen, new_gen);
3881next:
3882 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3883 } while (i <= MIN_LRU_BATCH);
3884
3885 arch_leave_lazy_mmu_mode();
3886 spin_unlock(ptl);
3887done:
3888 *start = -1;
3889 bitmap_zero(bitmap, MIN_LRU_BATCH);
3890}
3891#else
3892static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3893 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3894{
3895}
3896#endif
3897
3898static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3899 struct mm_walk *args)
3900{
3901 int i;
3902 pmd_t *pmd;
3903 unsigned long next;
3904 unsigned long addr;
3905 struct vm_area_struct *vma;
3906 unsigned long pos = -1;
3907 struct lru_gen_mm_walk *walk = args->private;
3908 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3909
3910 VM_WARN_ON_ONCE(pud_leaf(*pud));
3911
3912 /*
3913 * Finish an entire PMD in two passes: the first only reaches to PTE
3914 * tables to avoid taking the PMD lock; the second, if necessary, takes
3915 * the PMD lock to clear the accessed bit in PMD entries.
3916 */
3917 pmd = pmd_offset(pud, start & PUD_MASK);
3918restart:
3919 /* walk_pte_range() may call get_next_vma() */
3920 vma = args->vma;
3921 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3922 pmd_t val = pmd_read_atomic(pmd + i);
3923
3924 /* for pmd_read_atomic() */
3925 barrier();
3926
3927 next = pmd_addr_end(addr, end);
3928
3929 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3930 walk->mm_stats[MM_LEAF_TOTAL]++;
3931 continue;
3932 }
3933
3934#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3935 if (pmd_trans_huge(val)) {
3936 unsigned long pfn = pmd_pfn(val);
3937 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3938
3939 walk->mm_stats[MM_LEAF_TOTAL]++;
3940
3941 if (!pmd_young(val)) {
3942 walk->mm_stats[MM_LEAF_OLD]++;
3943 continue;
3944 }
3945
3946 /* try to avoid unnecessary memory loads */
3947 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3948 continue;
3949
3950 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3951 continue;
3952 }
3953#endif
3954 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3955
Juergen Gross23811792022-11-23 07:45:10 +01003956 if (arch_has_hw_nonleaf_pmd_young() &&
3957 get_cap(LRU_GEN_NONLEAF_YOUNG)) {
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003958 if (!pmd_young(val))
3959 continue;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003960
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003961 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3962 }
Juergen Gross23811792022-11-23 07:45:10 +01003963
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003964 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3965 continue;
3966
3967 walk->mm_stats[MM_NONLEAF_FOUND]++;
3968
3969 if (!walk_pte_range(&val, addr, next, args))
3970 continue;
3971
3972 walk->mm_stats[MM_NONLEAF_ADDED]++;
3973
3974 /* carry over to the next generation */
3975 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3976 }
3977
3978 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3979
3980 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3981 goto restart;
3982}
3983
3984static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3985 struct mm_walk *args)
3986{
3987 int i;
3988 pud_t *pud;
3989 unsigned long addr;
3990 unsigned long next;
3991 struct lru_gen_mm_walk *walk = args->private;
3992
3993 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3994
3995 pud = pud_offset(p4d, start & P4D_MASK);
3996restart:
3997 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3998 pud_t val = READ_ONCE(pud[i]);
3999
4000 next = pud_addr_end(addr, end);
4001
4002 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
4003 continue;
4004
4005 walk_pmd_range(&val, addr, next, args);
4006
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004007 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
4008 end = (addr | ~PUD_MASK) + 1;
4009 goto done;
4010 }
4011 }
4012
4013 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
4014 goto restart;
4015
4016 end = round_up(end, P4D_SIZE);
4017done:
4018 if (!end || !args->vma)
4019 return 1;
4020
4021 walk->next_addr = max(end, args->vma->vm_start);
4022
4023 return -EAGAIN;
4024}
4025
4026static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
4027{
4028 static const struct mm_walk_ops mm_walk_ops = {
4029 .test_walk = should_skip_vma,
4030 .p4d_entry = walk_pud_range,
4031 };
4032
4033 int err;
4034 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4035
4036 walk->next_addr = FIRST_USER_ADDRESS;
4037
4038 do {
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004039 DEFINE_MAX_SEQ(lruvec);
4040
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004041 err = -EBUSY;
4042
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004043 /* another thread might have called inc_max_seq() */
4044 if (walk->max_seq != max_seq)
4045 break;
4046
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004047 /* page_update_gen() requires stable page_memcg() */
4048 if (!mem_cgroup_trylock_pages(memcg))
4049 break;
4050
4051 /* the caller might be holding the lock for write */
4052 if (mmap_read_trylock(mm)) {
4053 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
4054
4055 mmap_read_unlock(mm);
4056 }
4057
4058 mem_cgroup_unlock_pages();
4059
4060 if (walk->batched) {
4061 spin_lock_irq(&lruvec->lru_lock);
4062 reset_batch_size(lruvec, walk);
4063 spin_unlock_irq(&lruvec->lru_lock);
4064 }
4065
4066 cond_resched();
4067 } while (err == -EAGAIN);
4068}
4069
Yu Zhaof8b57162022-12-21 21:19:05 -07004070static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004071{
4072 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4073
4074 if (pgdat && current_is_kswapd()) {
4075 VM_WARN_ON_ONCE(walk);
4076
4077 walk = &pgdat->mm_walk;
Yu Zhaof8b57162022-12-21 21:19:05 -07004078 } else if (!walk && force_alloc) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004079 VM_WARN_ON_ONCE(current_is_kswapd());
4080
4081 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4082 }
4083
4084 current->reclaim_state->mm_walk = walk;
4085
4086 return walk;
4087}
4088
4089static void clear_mm_walk(void)
4090{
4091 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4092
4093 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4094 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4095
4096 current->reclaim_state->mm_walk = NULL;
4097
4098 if (!current_is_kswapd())
4099 kfree(walk);
4100}
4101
Yu Zhao4983c522022-09-18 02:00:09 -06004102static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004103{
Yu Zhao4983c522022-09-18 02:00:09 -06004104 int zone;
4105 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004106 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06004107 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
Yu Zhao37397872022-09-18 02:00:03 -06004108
Yu Zhao4983c522022-09-18 02:00:09 -06004109 if (type == LRU_GEN_ANON && !can_swap)
4110 goto done;
4111
4112 /* prevent cold/hot inversion if force_scan is true */
4113 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004114 struct list_head *head = &lrugen->pages[old_gen][type][zone];
Yu Zhao4983c522022-09-18 02:00:09 -06004115
4116 while (!list_empty(head)) {
4117 struct page *page = lru_to_page(head);
4118
4119 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4120 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4121 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4122 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4123
4124 new_gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004125 list_move_tail(&page->lru, &lrugen->pages[new_gen][type][zone]);
Yu Zhao4983c522022-09-18 02:00:09 -06004126
4127 if (!--remaining)
4128 return false;
4129 }
4130 }
4131done:
Yu Zhao37397872022-09-18 02:00:03 -06004132 reset_ctrl_pos(lruvec, type, true);
4133 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
Yu Zhao4983c522022-09-18 02:00:09 -06004134
4135 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004136}
4137
4138static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4139{
4140 int gen, type, zone;
4141 bool success = false;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004142 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004143 DEFINE_MIN_SEQ(lruvec);
4144
4145 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4146
4147 /* find the oldest populated generation */
4148 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4149 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4150 gen = lru_gen_from_seq(min_seq[type]);
4151
4152 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004153 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhao37397872022-09-18 02:00:03 -06004154 goto next;
4155 }
4156
4157 min_seq[type]++;
4158 }
4159next:
4160 ;
4161 }
4162
Yu Zhao3c6c3592022-12-21 21:18:59 -07004163 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06004164 if (can_swap) {
4165 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4166 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4167 }
4168
4169 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4170 if (min_seq[type] == lrugen->min_seq[type])
4171 continue;
4172
4173 reset_ctrl_pos(lruvec, type, true);
4174 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4175 success = true;
4176 }
4177
4178 return success;
4179}
4180
Yu Zhao4983c522022-09-18 02:00:09 -06004181static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
Yu Zhao37397872022-09-18 02:00:03 -06004182{
4183 int prev, next;
4184 int type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004185 struct lru_gen_page *lrugen = &lruvec->lrugen;
Kalesh Singh12fb1c32023-08-01 19:56:03 -07004186restart:
Yu Zhao37397872022-09-18 02:00:03 -06004187 spin_lock_irq(&lruvec->lru_lock);
4188
4189 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4190
Yu Zhao37397872022-09-18 02:00:03 -06004191 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4192 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4193 continue;
4194
Yu Zhao4983c522022-09-18 02:00:09 -06004195 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
Yu Zhao37397872022-09-18 02:00:03 -06004196
Kalesh Singh12fb1c32023-08-01 19:56:03 -07004197 if (inc_min_seq(lruvec, type, can_swap))
4198 continue;
4199
4200 spin_unlock_irq(&lruvec->lru_lock);
4201 cond_resched();
4202 goto restart;
Yu Zhao37397872022-09-18 02:00:03 -06004203 }
4204
4205 /*
4206 * Update the active/inactive LRU sizes for compatibility. Both sides of
4207 * the current max_seq need to be covered, since max_seq+1 can overlap
4208 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4209 * overlap, cold/hot inversion happens.
4210 */
4211 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4212 next = lru_gen_from_seq(lrugen->max_seq + 1);
4213
4214 for (type = 0; type < ANON_AND_FILE; type++) {
4215 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4216 enum lru_list lru = type * LRU_INACTIVE_FILE;
4217 long delta = lrugen->nr_pages[prev][type][zone] -
4218 lrugen->nr_pages[next][type][zone];
4219
4220 if (!delta)
4221 continue;
4222
4223 __update_lru_size(lruvec, lru, zone, delta);
4224 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4225 }
4226 }
4227
4228 for (type = 0; type < ANON_AND_FILE; type++)
4229 reset_ctrl_pos(lruvec, type, false);
4230
Yu Zhao430499c2022-09-18 02:00:08 -06004231 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhao37397872022-09-18 02:00:03 -06004232 /* make sure preceding modifications appear */
4233 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004234
Yu Zhao37397872022-09-18 02:00:03 -06004235 spin_unlock_irq(&lruvec->lru_lock);
4236}
4237
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004238static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
Yu Zhao4983c522022-09-18 02:00:09 -06004239 struct scan_control *sc, bool can_swap, bool force_scan)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004240{
4241 bool success;
4242 struct lru_gen_mm_walk *walk;
4243 struct mm_struct *mm = NULL;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004244 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004245
4246 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4247
4248 /* see the comment in iterate_mm_list() */
4249 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4250 success = false;
4251 goto done;
4252 }
4253
4254 /*
4255 * If the hardware doesn't automatically set the accessed bit, fallback
4256 * to lru_gen_look_around(), which only clears the accessed bit in a
4257 * handful of PTEs. Spreading the work out over a period of time usually
4258 * is less efficient, but it avoids bursty page faults.
4259 */
Yu Zhao18580ef2022-12-21 21:19:06 -07004260 if (!arch_has_hw_pte_young() || !get_cap(LRU_GEN_MM_WALK)) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004261 success = iterate_mm_list_nowalk(lruvec, max_seq);
4262 goto done;
4263 }
4264
Yu Zhaof8b57162022-12-21 21:19:05 -07004265 walk = set_mm_walk(NULL, true);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004266 if (!walk) {
4267 success = iterate_mm_list_nowalk(lruvec, max_seq);
4268 goto done;
4269 }
4270
4271 walk->lruvec = lruvec;
4272 walk->max_seq = max_seq;
4273 walk->can_swap = can_swap;
Yu Zhao4983c522022-09-18 02:00:09 -06004274 walk->force_scan = force_scan;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004275
4276 do {
4277 success = iterate_mm_list(lruvec, walk, &mm);
4278 if (mm)
4279 walk_mm(lruvec, mm, walk);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004280 } while (mm);
4281done:
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004282 if (success)
4283 inc_max_seq(lruvec, can_swap, force_scan);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004284
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004285 return success;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004286}
4287
Yu Zhaoa5998f92022-12-21 21:19:02 -07004288static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
Yu Zhao37397872022-09-18 02:00:03 -06004289{
Yu Zhaoa5998f92022-12-21 21:19:02 -07004290 int gen, type, zone;
4291 unsigned long total = 0;
4292 bool can_swap = get_swappiness(lruvec, sc);
4293 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004294 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4295 DEFINE_MAX_SEQ(lruvec);
4296 DEFINE_MIN_SEQ(lruvec);
4297
Yu Zhaoa5998f92022-12-21 21:19:02 -07004298 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4299 unsigned long seq;
4300
4301 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4302 gen = lru_gen_from_seq(seq);
4303
4304 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4305 total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4306 }
4307 }
4308
4309 /* whether the size is big enough to be helpful */
4310 return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4311}
4312
4313static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
4314 unsigned long min_ttl)
4315{
4316 int gen;
4317 unsigned long birth;
4318 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4319 DEFINE_MIN_SEQ(lruvec);
4320
Yu Zhaoa5998f92022-12-21 21:19:02 -07004321 /* see the comment on lru_gen_page */
4322 gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4323 birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4324
4325 if (time_is_after_jiffies(birth + min_ttl))
4326 return false;
4327
4328 if (!lruvec_is_sizable(lruvec, sc))
4329 return false;
4330
Yu Zhao37397872022-09-18 02:00:03 -06004331 mem_cgroup_calculate_protection(NULL, memcg);
4332
Yu Zhaoa5998f92022-12-21 21:19:02 -07004333 return !mem_cgroup_below_min(memcg);
Yu Zhao37397872022-09-18 02:00:03 -06004334}
4335
Yu Zhao430499c2022-09-18 02:00:08 -06004336/* to protect the working set of the last N jiffies */
4337static unsigned long lru_gen_min_ttl __read_mostly;
4338
Yu Zhao37397872022-09-18 02:00:03 -06004339static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4340{
4341 struct mem_cgroup *memcg;
Yu Zhao430499c2022-09-18 02:00:08 -06004342 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhao37397872022-09-18 02:00:03 -06004343
4344 VM_WARN_ON_ONCE(!current_is_kswapd());
4345
Yu Zhaoa5998f92022-12-21 21:19:02 -07004346 /* check the order to exclude compaction-induced reclaim */
4347 if (!min_ttl || sc->order || sc->priority == DEF_PRIORITY)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004348 return;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004349
Yu Zhao37397872022-09-18 02:00:03 -06004350 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4351 do {
4352 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4353
Yu Zhaoa5998f92022-12-21 21:19:02 -07004354 if (lruvec_is_reclaimable(lruvec, sc, min_ttl)) {
4355 mem_cgroup_iter_break(NULL, memcg);
4356 return;
4357 }
Yu Zhao37397872022-09-18 02:00:03 -06004358
4359 cond_resched();
4360 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004361
Yu Zhao430499c2022-09-18 02:00:08 -06004362 /*
4363 * The main goal is to OOM kill if every generation from all memcgs is
4364 * younger than min_ttl. However, another possibility is all memcgs are
Yu Zhaoa5998f92022-12-21 21:19:02 -07004365 * either too small or below min.
Yu Zhao430499c2022-09-18 02:00:08 -06004366 */
4367 if (mutex_trylock(&oom_lock)) {
4368 struct oom_control oc = {
4369 .gfp_mask = sc->gfp_mask,
4370 };
4371
4372 out_of_memory(&oc);
4373
4374 mutex_unlock(&oom_lock);
4375 }
Yu Zhao37397872022-09-18 02:00:03 -06004376}
4377
Yu Zhao0182f922022-09-18 02:00:04 -06004378/*
4379 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004380 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4381 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4382 * the PTE table to the Bloom filter. This forms a feedback loop between the
4383 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004384 */
4385void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4386{
4387 int i;
4388 pte_t *pte;
4389 unsigned long start;
4390 unsigned long end;
4391 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004392 struct lru_gen_mm_walk *walk;
4393 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004394 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4395 struct page *page = pvmw->page;
Kalesh Singh0f986fa2023-08-01 19:56:04 -07004396 bool can_swap = !page_is_file_lru(page);
Yu Zhao0182f922022-09-18 02:00:04 -06004397 struct mem_cgroup *memcg = page_memcg(page);
4398 struct pglist_data *pgdat = page_pgdat(page);
4399 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4400 DEFINE_MAX_SEQ(lruvec);
4401 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4402
4403 lockdep_assert_held(pvmw->ptl);
4404 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4405
4406 if (spin_is_contended(pvmw->ptl))
4407 return;
4408
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004409 /* avoid taking the LRU lock under the PTL when possible */
4410 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4411
Yu Zhao0182f922022-09-18 02:00:04 -06004412 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4413 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4414
4415 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4416 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4417 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4418 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4419 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4420 else {
4421 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4422 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4423 }
4424 }
4425
4426 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4427
4428 rcu_read_lock();
4429 arch_enter_lazy_mmu_mode();
4430
4431 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4432 unsigned long pfn;
4433
4434 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4435 if (pfn == -1)
4436 continue;
4437
4438 if (!pte_young(pte[i]))
4439 continue;
4440
Kalesh Singh0f986fa2023-08-01 19:56:04 -07004441 page = get_pfn_page(pfn, memcg, pgdat, can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004442 if (!page)
4443 continue;
4444
4445 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4446 VM_WARN_ON_ONCE(true);
4447
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004448 young++;
4449
Yu Zhao0182f922022-09-18 02:00:04 -06004450 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4451 !(PageAnon(page) && PageSwapBacked(page) &&
4452 !PageSwapCache(page)))
4453 set_page_dirty(page);
4454
4455 old_gen = page_lru_gen(page);
4456 if (old_gen < 0)
4457 SetPageReferenced(page);
4458 else if (old_gen != new_gen)
4459 __set_bit(i, bitmap);
4460 }
4461
4462 arch_leave_lazy_mmu_mode();
4463 rcu_read_unlock();
4464
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004465 /* feedback from rmap walkers to page table walkers */
4466 if (suitable_to_scan(i, young))
4467 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4468
4469 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004470 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4471 page = pte_page(pte[i]);
4472 activate_page(page);
4473 }
4474 return;
4475 }
4476
4477 /* page_update_gen() requires stable page_memcg() */
4478 if (!mem_cgroup_trylock_pages(memcg))
4479 return;
4480
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004481 if (!walk) {
4482 spin_lock_irq(&lruvec->lru_lock);
4483 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4484 }
Yu Zhao0182f922022-09-18 02:00:04 -06004485
4486 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4487 page = compound_head(pte_page(pte[i]));
4488 if (page_memcg_rcu(page) != memcg)
4489 continue;
4490
4491 old_gen = page_update_gen(page, new_gen);
4492 if (old_gen < 0 || old_gen == new_gen)
4493 continue;
4494
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004495 if (walk)
4496 update_batch_size(walk, page, old_gen, new_gen);
4497 else
4498 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004499 }
4500
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004501 if (!walk)
4502 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004503
4504 mem_cgroup_unlock_pages();
4505}
4506
Yu Zhao37397872022-09-18 02:00:03 -06004507/******************************************************************************
4508 * the eviction
4509 ******************************************************************************/
4510
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004511static bool sort_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc,
4512 int tier_idx)
Yu Zhao37397872022-09-18 02:00:03 -06004513{
4514 bool success;
4515 int gen = page_lru_gen(page);
4516 int type = page_is_file_lru(page);
4517 int zone = page_zonenum(page);
4518 int delta = thp_nr_pages(page);
4519 int refs = page_lru_refs(page);
4520 int tier = lru_tier_from_refs(refs);
Yu Zhao3c6c3592022-12-21 21:18:59 -07004521 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004522
4523 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4524
4525 /* unevictable */
4526 if (!page_evictable(page)) {
4527 success = lru_gen_del_page(lruvec, page, true);
4528 VM_WARN_ON_ONCE_PAGE(!success, page);
4529 SetPageUnevictable(page);
4530 add_page_to_lru_list(page, lruvec);
4531 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4532 return true;
4533 }
4534
4535 /* dirty lazyfree */
4536 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4537 success = lru_gen_del_page(lruvec, page, true);
4538 VM_WARN_ON_ONCE_PAGE(!success, page);
4539 SetPageSwapBacked(page);
4540 add_page_to_lru_list_tail(page, lruvec);
4541 return true;
4542 }
4543
Yu Zhao0182f922022-09-18 02:00:04 -06004544 /* promoted */
4545 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004546 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao0182f922022-09-18 02:00:04 -06004547 return true;
4548 }
4549
Yu Zhao37397872022-09-18 02:00:03 -06004550 /* protected */
4551 if (tier > tier_idx) {
4552 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4553
4554 gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004555 list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004556
4557 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4558 lrugen->protected[hist][type][tier - 1] + delta);
Yu Zhao37397872022-09-18 02:00:03 -06004559 return true;
4560 }
4561
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004562 /* ineligible */
Charan Teja Kallaa8455252023-08-09 13:35:44 +05304563 if (zone > sc->reclaim_idx || skip_cma(page, sc)) {
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004564 gen = page_inc_gen(lruvec, page, false);
4565 list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
4566 return true;
4567 }
4568
Yu Zhao37397872022-09-18 02:00:03 -06004569 /* waiting for writeback */
4570 if (PageLocked(page) || PageWriteback(page) ||
4571 (type == LRU_GEN_FILE && PageDirty(page))) {
4572 gen = page_inc_gen(lruvec, page, true);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004573 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004574 return true;
4575 }
4576
4577 return false;
4578}
4579
4580static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4581{
4582 bool success;
4583
Yu Zhao37397872022-09-18 02:00:03 -06004584 /* swapping inhibited */
Yu Zhaof8b57162022-12-21 21:19:05 -07004585 if (!(sc->gfp_mask & __GFP_IO) &&
Yu Zhao37397872022-09-18 02:00:03 -06004586 (PageDirty(page) ||
4587 (PageAnon(page) && !PageSwapCache(page))))
4588 return false;
4589
4590 /* raced with release_pages() */
4591 if (!get_page_unless_zero(page))
4592 return false;
4593
4594 /* raced with another isolation */
4595 if (!TestClearPageLRU(page)) {
4596 put_page(page);
4597 return false;
4598 }
4599
4600 /* see the comment on MAX_NR_TIERS */
4601 if (!PageReferenced(page))
4602 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4603
4604 /* for shrink_page_list() */
4605 ClearPageReclaim(page);
4606 ClearPageReferenced(page);
4607
4608 success = lru_gen_del_page(lruvec, page, true);
4609 VM_WARN_ON_ONCE_PAGE(!success, page);
4610
4611 return true;
4612}
4613
4614static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4615 int type, int tier, struct list_head *list)
4616{
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004617 int i;
4618 int gen;
Yu Zhao37397872022-09-18 02:00:03 -06004619 enum vm_event_item item;
4620 int sorted = 0;
4621 int scanned = 0;
4622 int isolated = 0;
4623 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004624 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004625 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4626
4627 VM_WARN_ON_ONCE(!list_empty(list));
4628
4629 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4630 return 0;
4631
4632 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4633
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004634 for (i = MAX_NR_ZONES; i > 0; i--) {
Yu Zhao37397872022-09-18 02:00:03 -06004635 LIST_HEAD(moved);
4636 int skipped = 0;
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004637 int zone = (sc->reclaim_idx + i) % MAX_NR_ZONES;
Yu Zhaodf91dc92022-12-21 21:19:00 -07004638 struct list_head *head = &lrugen->pages[gen][type][zone];
Yu Zhao37397872022-09-18 02:00:03 -06004639
4640 while (!list_empty(head)) {
4641 struct page *page = lru_to_page(head);
4642 int delta = thp_nr_pages(page);
4643
4644 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4645 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4646 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4647 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4648
4649 scanned += delta;
4650
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004651 if (sort_page(lruvec, page, sc, tier))
Yu Zhao37397872022-09-18 02:00:03 -06004652 sorted += delta;
4653 else if (isolate_page(lruvec, page, sc)) {
4654 list_add(&page->lru, list);
4655 isolated += delta;
4656 } else {
4657 list_move(&page->lru, &moved);
4658 skipped += delta;
4659 }
4660
4661 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4662 break;
4663 }
4664
4665 if (skipped) {
4666 list_splice(&moved, head);
4667 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4668 }
4669
4670 if (!remaining || isolated >= MIN_LRU_BATCH)
4671 break;
4672 }
4673
4674 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4675 if (!cgroup_reclaim(sc)) {
4676 __count_vm_events(item, isolated);
4677 __count_vm_events(PGREFILL, sorted);
4678 }
4679 __count_memcg_events(memcg, item, isolated);
4680 __count_memcg_events(memcg, PGREFILL, sorted);
4681 __count_vm_events(PGSCAN_ANON + type, isolated);
4682
4683 /*
Yu Zhaof8b57162022-12-21 21:19:05 -07004684 * There might not be eligible pages due to reclaim_idx. Check the
4685 * remaining to prevent livelock if it's not making progress.
Yu Zhao37397872022-09-18 02:00:03 -06004686 */
4687 return isolated || !remaining ? scanned : 0;
4688}
4689
4690static int get_tier_idx(struct lruvec *lruvec, int type)
4691{
4692 int tier;
4693 struct ctrl_pos sp, pv;
4694
4695 /*
4696 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4697 * This value is chosen because any other tier would have at least twice
4698 * as many refaults as the first tier.
4699 */
4700 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4701 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4702 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4703 if (!positive_ctrl_err(&sp, &pv))
4704 break;
4705 }
4706
4707 return tier - 1;
4708}
4709
4710static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4711{
4712 int type, tier;
4713 struct ctrl_pos sp, pv;
4714 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4715
4716 /*
4717 * Compare the first tier of anon with that of file to determine which
4718 * type to scan. Also need to compare other tiers of the selected type
4719 * with the first tier of the other type to determine the last tier (of
4720 * the selected type) to evict.
4721 */
4722 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4723 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4724 type = positive_ctrl_err(&sp, &pv);
4725
4726 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4727 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4728 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4729 if (!positive_ctrl_err(&sp, &pv))
4730 break;
4731 }
4732
4733 *tier_idx = tier - 1;
4734
4735 return type;
4736}
4737
4738static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4739 int *type_scanned, struct list_head *list)
4740{
4741 int i;
4742 int type;
4743 int scanned;
4744 int tier = -1;
4745 DEFINE_MIN_SEQ(lruvec);
4746
4747 /*
4748 * Try to make the obvious choice first. When anon and file are both
4749 * available from the same generation, interpret swappiness 1 as file
4750 * first and 200 as anon first.
4751 */
4752 if (!swappiness)
4753 type = LRU_GEN_FILE;
4754 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4755 type = LRU_GEN_ANON;
4756 else if (swappiness == 1)
4757 type = LRU_GEN_FILE;
4758 else if (swappiness == 200)
4759 type = LRU_GEN_ANON;
4760 else
4761 type = get_type_to_scan(lruvec, swappiness, &tier);
4762
4763 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4764 if (tier < 0)
4765 tier = get_tier_idx(lruvec, type);
4766
4767 scanned = scan_pages(lruvec, sc, type, tier, list);
4768 if (scanned)
4769 break;
4770
4771 type = !type;
4772 tier = -1;
4773 }
4774
4775 *type_scanned = type;
4776
4777 return scanned;
4778}
4779
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004780static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
Yu Zhao37397872022-09-18 02:00:03 -06004781{
4782 int type;
4783 int scanned;
4784 int reclaimed;
4785 LIST_HEAD(list);
Yu Zhao79e66ea2022-11-15 18:38:07 -07004786 LIST_HEAD(clean);
Yu Zhao37397872022-09-18 02:00:03 -06004787 struct page *page;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004788 struct page *next;
Yu Zhao37397872022-09-18 02:00:03 -06004789 enum vm_event_item item;
4790 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004791 struct lru_gen_mm_walk *walk;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004792 bool skip_retry = false;
Yu Zhao37397872022-09-18 02:00:03 -06004793 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4794 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4795
4796 spin_lock_irq(&lruvec->lru_lock);
4797
4798 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4799
4800 scanned += try_to_inc_min_seq(lruvec, swappiness);
4801
4802 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4803 scanned = 0;
4804
4805 spin_unlock_irq(&lruvec->lru_lock);
4806
4807 if (list_empty(&list))
4808 return scanned;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004809retry:
Yu Zhao37397872022-09-18 02:00:03 -06004810 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
Yu Zhao79e66ea2022-11-15 18:38:07 -07004811 sc->nr_reclaimed += reclaimed;
Yu Zhao37397872022-09-18 02:00:03 -06004812
Yu Zhao79e66ea2022-11-15 18:38:07 -07004813 list_for_each_entry_safe_reverse(page, next, &list, lru) {
4814 if (!page_evictable(page)) {
4815 list_del(&page->lru);
4816 putback_lru_page(page);
4817 continue;
4818 }
Yu Zhao37397872022-09-18 02:00:03 -06004819
Yu Zhao37397872022-09-18 02:00:03 -06004820 if (PageReclaim(page) &&
Yu Zhao79e66ea2022-11-15 18:38:07 -07004821 (PageDirty(page) || PageWriteback(page))) {
4822 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4823 if (PageWorkingset(page))
4824 SetPageReferenced(page);
4825 continue;
4826 }
4827
4828 if (skip_retry || PageActive(page) || PageReferenced(page) ||
4829 page_mapped(page) || PageLocked(page) ||
4830 PageDirty(page) || PageWriteback(page)) {
4831 /* don't add rejected pages to the oldest generation */
4832 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
4833 BIT(PG_active));
4834 continue;
4835 }
4836
4837 /* retry pages that may have missed rotate_reclaimable_page() */
4838 list_move(&page->lru, &clean);
4839 sc->nr_scanned -= thp_nr_pages(page);
Yu Zhao37397872022-09-18 02:00:03 -06004840 }
4841
4842 spin_lock_irq(&lruvec->lru_lock);
4843
4844 move_pages_to_lru(lruvec, &list);
4845
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004846 walk = current->reclaim_state->mm_walk;
4847 if (walk && walk->batched)
4848 reset_batch_size(lruvec, walk);
4849
Yu Zhao37397872022-09-18 02:00:03 -06004850 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4851 if (!cgroup_reclaim(sc))
4852 __count_vm_events(item, reclaimed);
4853 __count_memcg_events(memcg, item, reclaimed);
4854 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4855
4856 spin_unlock_irq(&lruvec->lru_lock);
4857
4858 mem_cgroup_uncharge_list(&list);
4859 free_unref_page_list(&list);
4860
Yu Zhao79e66ea2022-11-15 18:38:07 -07004861 INIT_LIST_HEAD(&list);
4862 list_splice_init(&clean, &list);
4863
4864 if (!list_empty(&list)) {
4865 skip_retry = true;
4866 goto retry;
4867 }
Yu Zhao37397872022-09-18 02:00:03 -06004868
4869 return scanned;
4870}
4871
Yu Zhaocb3958d2022-12-21 21:19:03 -07004872static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
4873 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4874{
4875 int gen, type, zone;
4876 unsigned long old = 0;
4877 unsigned long young = 0;
4878 unsigned long total = 0;
4879 struct lru_gen_page *lrugen = &lruvec->lrugen;
4880 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4881 DEFINE_MIN_SEQ(lruvec);
4882
4883 /* whether this lruvec is completely out of cold pages */
4884 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
4885 *nr_to_scan = 0;
4886 return true;
4887 }
4888
4889 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4890 unsigned long seq;
4891
4892 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4893 unsigned long size = 0;
4894
4895 gen = lru_gen_from_seq(seq);
4896
4897 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4898 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4899
4900 total += size;
4901 if (seq == max_seq)
4902 young += size;
4903 else if (seq + MIN_NR_GENS == max_seq)
4904 old += size;
4905 }
4906 }
4907
4908 /* try to scrape all its memory if this memcg was deleted */
4909 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4910
4911 /*
4912 * The aging tries to be lazy to reduce the overhead, while the eviction
4913 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4914 * ideal number of generations is MIN_NR_GENS+1.
4915 */
4916 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4917 return false;
4918
4919 /*
4920 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4921 * of the total number of pages for each generation. A reasonable range
4922 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4923 * aging cares about the upper bound of hot pages, while the eviction
4924 * cares about the lower bound of cold pages.
4925 */
4926 if (young * MIN_NR_GENS > total)
4927 return true;
4928 if (old * (MIN_NR_GENS + 2) < total)
4929 return true;
4930
4931 return false;
4932}
4933
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004934/*
4935 * For future optimizations:
4936 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4937 * reclaim.
4938 */
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004939static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004940{
Yu Zhao37397872022-09-18 02:00:03 -06004941 unsigned long nr_to_scan;
4942 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4943 DEFINE_MAX_SEQ(lruvec);
Yu Zhao37397872022-09-18 02:00:03 -06004944
Yu Zhaof8b57162022-12-21 21:19:05 -07004945 if (mem_cgroup_below_min(memcg))
Yu Zhao37397872022-09-18 02:00:03 -06004946 return 0;
4947
Yu Zhaoa5998f92022-12-21 21:19:02 -07004948 if (!should_run_aging(lruvec, max_seq, sc, can_swap, &nr_to_scan))
Yu Zhao37397872022-09-18 02:00:03 -06004949 return nr_to_scan;
4950
4951 /* skip the aging path at the default priority */
4952 if (sc->priority == DEF_PRIORITY)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004953 return nr_to_scan;
Yu Zhaoa5998f92022-12-21 21:19:02 -07004954
Yu Zhaoa5998f92022-12-21 21:19:02 -07004955 /* skip this lruvec as it's low on cold pages */
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004956 return try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false) ? -1 : 0;
Yu Zhao37397872022-09-18 02:00:03 -06004957}
4958
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004959static unsigned long get_nr_to_reclaim(struct scan_control *sc)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004960{
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004961 /* don't abort memcg reclaim to ensure fairness */
4962 if (!global_reclaim(sc))
4963 return -1;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004964
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004965 return max(sc->nr_to_reclaim, compact_gap(sc->order));
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004966}
4967
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004968static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Yu Zhao37397872022-09-18 02:00:03 -06004969{
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004970 long nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004971 unsigned long scanned = 0;
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004972 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
Yu Zhaof8b57162022-12-21 21:19:05 -07004973 int swappiness = get_swappiness(lruvec, sc);
4974
4975 /* clean file pages are more likely to exist */
4976 if (swappiness && !(sc->gfp_mask & __GFP_IO))
4977 swappiness = 1;
Yu Zhao37397872022-09-18 02:00:03 -06004978
Yu Zhao37397872022-09-18 02:00:03 -06004979 while (true) {
4980 int delta;
Yu Zhao37397872022-09-18 02:00:03 -06004981
Yu Zhaoa5998f92022-12-21 21:19:02 -07004982 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004983 if (nr_to_scan <= 0)
Yu Zhaoa5998f92022-12-21 21:19:02 -07004984 break;
Yu Zhao37397872022-09-18 02:00:03 -06004985
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004986 delta = evict_pages(lruvec, sc, swappiness);
Yu Zhao37397872022-09-18 02:00:03 -06004987 if (!delta)
Yu Zhaoa5998f92022-12-21 21:19:02 -07004988 break;
Yu Zhao37397872022-09-18 02:00:03 -06004989
4990 scanned += delta;
4991 if (scanned >= nr_to_scan)
4992 break;
4993
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004994 if (sc->nr_reclaimed >= nr_to_reclaim)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004995 break;
4996
Yu Zhao37397872022-09-18 02:00:03 -06004997 cond_resched();
4998 }
4999
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005000 /* whether try_to_inc_max_seq() was successful */
5001 return nr_to_scan < 0;
5002}
5003
5004static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
5005{
5006 bool success;
5007 unsigned long scanned = sc->nr_scanned;
5008 unsigned long reclaimed = sc->nr_reclaimed;
5009 int seg = lru_gen_memcg_seg(lruvec);
5010 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5011 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5012
5013 /* see the comment on MEMCG_NR_GENS */
5014 if (!lruvec_is_sizable(lruvec, sc))
5015 return seg != MEMCG_LRU_TAIL ? MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG;
5016
5017 mem_cgroup_calculate_protection(NULL, memcg);
5018
5019 if (mem_cgroup_below_min(memcg))
5020 return MEMCG_LRU_YOUNG;
5021
5022 if (mem_cgroup_below_low(memcg)) {
5023 /* see the comment on MEMCG_NR_GENS */
5024 if (seg != MEMCG_LRU_TAIL)
5025 return MEMCG_LRU_TAIL;
5026
5027 memcg_memory_event(memcg, MEMCG_LOW);
5028 }
5029
5030 success = try_to_shrink_lruvec(lruvec, sc);
5031
5032 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority);
5033
5034 vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned,
5035 sc->nr_reclaimed - reclaimed);
5036
5037 sc->nr_reclaimed += current->reclaim_state->reclaimed_slab;
5038 current->reclaim_state->reclaimed_slab = 0;
5039
5040 return success ? MEMCG_LRU_YOUNG : 0;
5041}
5042
5043#ifdef CONFIG_MEMCG
5044
5045static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5046{
Yu Zhaof7909cb2023-02-13 00:53:22 -07005047 int op;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005048 int gen;
5049 int bin;
5050 int first_bin;
5051 struct lruvec *lruvec;
5052 struct lru_gen_page *lrugen;
Yu Zhaof7909cb2023-02-13 00:53:22 -07005053 struct mem_cgroup *memcg;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005054 const struct hlist_nulls_node *pos;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005055 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
5056
5057 bin = first_bin = prandom_u32_max(MEMCG_NR_BINS);
5058restart:
Yu Zhaof7909cb2023-02-13 00:53:22 -07005059 op = 0;
5060 memcg = NULL;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005061 gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq));
5062
5063 rcu_read_lock();
5064
5065 hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) {
5066 if (op)
5067 lru_gen_rotate_memcg(lruvec, op);
5068
5069 mem_cgroup_put(memcg);
5070
5071 lruvec = container_of(lrugen, struct lruvec, lrugen);
5072 memcg = lruvec_memcg(lruvec);
5073
5074 if (!mem_cgroup_tryget(memcg)) {
5075 op = 0;
5076 memcg = NULL;
5077 continue;
5078 }
5079
5080 rcu_read_unlock();
5081
5082 op = shrink_one(lruvec, sc);
5083
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005084 rcu_read_lock();
Yu Zhaof7909cb2023-02-13 00:53:22 -07005085
5086 if (sc->nr_reclaimed >= nr_to_reclaim)
5087 break;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005088 }
5089
5090 rcu_read_unlock();
5091
Yu Zhaof7909cb2023-02-13 00:53:22 -07005092 if (op)
5093 lru_gen_rotate_memcg(lruvec, op);
5094
5095 mem_cgroup_put(memcg);
5096
5097 if (sc->nr_reclaimed >= nr_to_reclaim)
5098 return;
5099
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005100 /* restart if raced with lru_gen_rotate_memcg() */
5101 if (gen != get_nulls_value(pos))
5102 goto restart;
5103
5104 /* try the rest of the bins of the current generation */
5105 bin = get_memcg_bin(bin + 1);
5106 if (bin != first_bin)
5107 goto restart;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005108}
5109
5110static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5111{
5112 struct blk_plug plug;
5113
5114 VM_WARN_ON_ONCE(global_reclaim(sc));
Yu Zhaof8b57162022-12-21 21:19:05 -07005115 VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005116
5117 lru_add_drain();
5118
5119 blk_start_plug(&plug);
5120
Yu Zhaof8b57162022-12-21 21:19:05 -07005121 set_mm_walk(NULL, false);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005122
5123 if (try_to_shrink_lruvec(lruvec, sc))
5124 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG);
5125
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005126 clear_mm_walk();
5127
Yu Zhao37397872022-09-18 02:00:03 -06005128 blk_finish_plug(&plug);
5129}
5130
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005131#else /* !CONFIG_MEMCG */
5132
5133static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5134{
5135 BUILD_BUG();
5136}
5137
5138static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5139{
5140 BUILD_BUG();
5141}
5142
5143#endif
5144
5145static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc)
5146{
5147 int priority;
5148 unsigned long reclaimable;
5149 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5150
5151 if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH)
5152 return;
5153 /*
5154 * Determine the initial priority based on ((total / MEMCG_NR_GENS) >>
5155 * priority) * reclaimed_to_scanned_ratio = nr_to_reclaim, where the
5156 * estimated reclaimed_to_scanned_ratio = inactive / total.
5157 */
5158 reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE);
5159 if (get_swappiness(lruvec, sc))
5160 reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON);
5161
5162 reclaimable /= MEMCG_NR_GENS;
5163
5164 /* round down reclaimable and round up sc->nr_to_reclaim */
5165 priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1);
5166
5167 sc->priority = clamp(priority, 0, DEF_PRIORITY);
5168}
5169
5170static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5171{
5172 struct blk_plug plug;
5173 unsigned long reclaimed = sc->nr_reclaimed;
5174
5175 VM_WARN_ON_ONCE(!global_reclaim(sc));
5176
Yu Zhaof8b57162022-12-21 21:19:05 -07005177 /*
5178 * Unmapped clean pages are already prioritized. Scanning for more of
5179 * them is likely futile and can cause high reclaim latency when there
5180 * is a large number of memcgs.
5181 */
5182 if (!sc->may_writepage || !sc->may_unmap)
5183 goto done;
5184
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005185 lru_add_drain();
5186
5187 blk_start_plug(&plug);
5188
Yu Zhaof8b57162022-12-21 21:19:05 -07005189 set_mm_walk(pgdat, false);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005190
5191 set_initial_priority(pgdat, sc);
5192
5193 if (current_is_kswapd())
5194 sc->nr_reclaimed = 0;
5195
5196 if (mem_cgroup_disabled())
5197 shrink_one(&pgdat->__lruvec, sc);
5198 else
5199 shrink_many(pgdat, sc);
5200
5201 if (current_is_kswapd())
5202 sc->nr_reclaimed += reclaimed;
5203
5204 clear_mm_walk();
5205
5206 blk_finish_plug(&plug);
Yu Zhaof8b57162022-12-21 21:19:05 -07005207done:
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005208 /* kswapd should never fail */
5209 pgdat->kswapd_failures = 0;
5210}
5211
5212#ifdef CONFIG_MEMCG
5213void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
5214{
5215 int seg;
5216 int old, new;
5217 int bin = prandom_u32_max(MEMCG_NR_BINS);
5218 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5219
5220 spin_lock(&pgdat->memcg_lru.lock);
5221
5222 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
5223
5224 seg = 0;
5225 new = old = lruvec->lrugen.gen;
5226
5227 /* see the comment on MEMCG_NR_GENS */
5228 if (op == MEMCG_LRU_HEAD)
5229 seg = MEMCG_LRU_HEAD;
5230 else if (op == MEMCG_LRU_TAIL)
5231 seg = MEMCG_LRU_TAIL;
5232 else if (op == MEMCG_LRU_OLD)
5233 new = get_memcg_gen(pgdat->memcg_lru.seq);
5234 else if (op == MEMCG_LRU_YOUNG)
5235 new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
5236 else
5237 VM_WARN_ON_ONCE(true);
5238
5239 hlist_nulls_del_rcu(&lruvec->lrugen.list);
5240
5241 if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
5242 hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
5243 else
5244 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
5245
5246 pgdat->memcg_lru.nr_memcgs[old]--;
5247 pgdat->memcg_lru.nr_memcgs[new]++;
5248
5249 lruvec->lrugen.gen = new;
5250 WRITE_ONCE(lruvec->lrugen.seg, seg);
5251
5252 if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
5253 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
5254
5255 spin_unlock(&pgdat->memcg_lru.lock);
5256}
5257#endif
5258
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005259/******************************************************************************
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005260 * state change
5261 ******************************************************************************/
5262
5263static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5264{
Yu Zhao3c6c3592022-12-21 21:18:59 -07005265 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005266
5267 if (lrugen->enabled) {
5268 enum lru_list lru;
5269
5270 for_each_evictable_lru(lru) {
5271 if (!list_empty(&lruvec->lists[lru]))
5272 return false;
5273 }
5274 } else {
5275 int gen, type, zone;
5276
5277 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005278 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005279 return false;
5280 }
5281 }
5282
5283 return true;
5284}
5285
5286static bool fill_evictable(struct lruvec *lruvec)
5287{
5288 enum lru_list lru;
5289 int remaining = MAX_LRU_BATCH;
5290
5291 for_each_evictable_lru(lru) {
5292 int type = is_file_lru(lru);
5293 bool active = is_active_lru(lru);
5294 struct list_head *head = &lruvec->lists[lru];
5295
5296 while (!list_empty(head)) {
5297 bool success;
5298 struct page *page = lru_to_page(head);
5299
5300 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5301 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
5302 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5303 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
5304
5305 del_page_from_lru_list(page, lruvec);
5306 success = lru_gen_add_page(lruvec, page, false);
5307 VM_WARN_ON_ONCE(!success);
5308
5309 if (!--remaining)
5310 return false;
5311 }
5312 }
5313
5314 return true;
5315}
5316
5317static bool drain_evictable(struct lruvec *lruvec)
5318{
5319 int gen, type, zone;
5320 int remaining = MAX_LRU_BATCH;
5321
5322 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005323 struct list_head *head = &lruvec->lrugen.pages[gen][type][zone];
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005324
5325 while (!list_empty(head)) {
5326 bool success;
5327 struct page *page = lru_to_page(head);
5328
5329 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5330 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5331 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5332 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5333
5334 success = lru_gen_del_page(lruvec, page, false);
5335 VM_WARN_ON_ONCE(!success);
5336 add_page_to_lru_list(page, lruvec);
5337
5338 if (!--remaining)
5339 return false;
5340 }
5341 }
5342
5343 return true;
5344}
5345
5346static void lru_gen_change_state(bool enabled)
5347{
5348 static DEFINE_MUTEX(state_mutex);
5349
5350 struct mem_cgroup *memcg;
5351
5352 cgroup_lock();
5353 cpus_read_lock();
5354 get_online_mems();
5355 mutex_lock(&state_mutex);
5356
5357 if (enabled == lru_gen_enabled())
5358 goto unlock;
5359
5360 if (enabled)
5361 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5362 else
5363 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5364
5365 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5366 do {
5367 int nid;
5368
5369 for_each_node(nid) {
5370 struct lruvec *lruvec = get_lruvec(memcg, nid);
5371
5372 if (!lruvec)
5373 continue;
5374
5375 spin_lock_irq(&lruvec->lru_lock);
5376
5377 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5378 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5379
5380 lruvec->lrugen.enabled = enabled;
5381
5382 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5383 spin_unlock_irq(&lruvec->lru_lock);
5384 cond_resched();
5385 spin_lock_irq(&lruvec->lru_lock);
5386 }
5387
5388 spin_unlock_irq(&lruvec->lru_lock);
5389 }
5390
5391 cond_resched();
5392 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5393unlock:
5394 mutex_unlock(&state_mutex);
5395 put_online_mems();
5396 cpus_read_unlock();
5397 cgroup_unlock();
5398}
5399
5400/******************************************************************************
5401 * sysfs interface
5402 ******************************************************************************/
5403
Yu Zhao430499c2022-09-18 02:00:08 -06005404static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5405{
5406 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5407}
5408
Yu Zhao642d9862022-09-18 02:00:10 -06005409/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao430499c2022-09-18 02:00:08 -06005410static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5411 const char *buf, size_t len)
5412{
5413 unsigned int msecs;
5414
5415 if (kstrtouint(buf, 0, &msecs))
5416 return -EINVAL;
5417
5418 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5419
5420 return len;
5421}
5422
5423static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5424 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5425);
5426
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005427static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5428{
5429 unsigned int caps = 0;
5430
5431 if (get_cap(LRU_GEN_CORE))
5432 caps |= BIT(LRU_GEN_CORE);
5433
5434 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5435 caps |= BIT(LRU_GEN_MM_WALK);
5436
Juergen Gross23811792022-11-23 07:45:10 +01005437 if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005438 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5439
5440 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5441}
5442
Yu Zhao642d9862022-09-18 02:00:10 -06005443/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005444static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5445 const char *buf, size_t len)
5446{
5447 int i;
5448 unsigned int caps;
5449
5450 if (tolower(*buf) == 'n')
5451 caps = 0;
5452 else if (tolower(*buf) == 'y')
5453 caps = -1;
5454 else if (kstrtouint(buf, 0, &caps))
5455 return -EINVAL;
5456
5457 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5458 bool enabled = caps & BIT(i);
5459
5460 if (i == LRU_GEN_CORE)
5461 lru_gen_change_state(enabled);
5462 else if (enabled)
5463 static_branch_enable(&lru_gen_caps[i]);
5464 else
5465 static_branch_disable(&lru_gen_caps[i]);
5466 }
5467
5468 return len;
5469}
5470
5471static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5472 enabled, 0644, show_enabled, store_enabled
5473);
5474
5475static struct attribute *lru_gen_attrs[] = {
Yu Zhao430499c2022-09-18 02:00:08 -06005476 &lru_gen_min_ttl_attr.attr,
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005477 &lru_gen_enabled_attr.attr,
5478 NULL
5479};
5480
5481static struct attribute_group lru_gen_attr_group = {
5482 .name = "lru_gen",
5483 .attrs = lru_gen_attrs,
5484};
5485
5486/******************************************************************************
Yu Zhao4983c522022-09-18 02:00:09 -06005487 * debugfs interface
5488 ******************************************************************************/
5489
5490static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5491{
5492 struct mem_cgroup *memcg;
5493 loff_t nr_to_skip = *pos;
5494
5495 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5496 if (!m->private)
5497 return ERR_PTR(-ENOMEM);
5498
5499 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5500 do {
5501 int nid;
5502
5503 for_each_node_state(nid, N_MEMORY) {
5504 if (!nr_to_skip--)
5505 return get_lruvec(memcg, nid);
5506 }
5507 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5508
5509 return NULL;
5510}
5511
5512static void lru_gen_seq_stop(struct seq_file *m, void *v)
5513{
5514 if (!IS_ERR_OR_NULL(v))
5515 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5516
5517 kvfree(m->private);
5518 m->private = NULL;
5519}
5520
5521static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5522{
5523 int nid = lruvec_pgdat(v)->node_id;
5524 struct mem_cgroup *memcg = lruvec_memcg(v);
5525
5526 ++*pos;
5527
5528 nid = next_memory_node(nid);
5529 if (nid == MAX_NUMNODES) {
5530 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5531 if (!memcg)
5532 return NULL;
5533
5534 nid = first_memory_node;
5535 }
5536
5537 return get_lruvec(memcg, nid);
5538}
5539
5540static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5541 unsigned long max_seq, unsigned long *min_seq,
5542 unsigned long seq)
5543{
5544 int i;
5545 int type, tier;
5546 int hist = lru_hist_from_seq(seq);
Yu Zhao3c6c3592022-12-21 21:18:59 -07005547 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005548
5549 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5550 seq_printf(m, " %10d", tier);
5551 for (type = 0; type < ANON_AND_FILE; type++) {
5552 const char *s = " ";
5553 unsigned long n[3] = {};
5554
5555 if (seq == max_seq) {
5556 s = "RT ";
5557 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5558 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5559 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5560 s = "rep";
5561 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5562 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5563 if (tier)
5564 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5565 }
5566
5567 for (i = 0; i < 3; i++)
5568 seq_printf(m, " %10lu%c", n[i], s[i]);
5569 }
5570 seq_putc(m, '\n');
5571 }
5572
5573 seq_puts(m, " ");
5574 for (i = 0; i < NR_MM_STATS; i++) {
5575 const char *s = " ";
5576 unsigned long n = 0;
5577
5578 if (seq == max_seq && NR_HIST_GENS == 1) {
5579 s = "LOYNFA";
5580 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5581 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5582 s = "loynfa";
5583 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5584 }
5585
5586 seq_printf(m, " %10lu%c", n, s[i]);
5587 }
5588 seq_putc(m, '\n');
5589}
5590
Yu Zhao642d9862022-09-18 02:00:10 -06005591/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005592static int lru_gen_seq_show(struct seq_file *m, void *v)
5593{
5594 unsigned long seq;
5595 bool full = !debugfs_real_fops(m->file)->write;
5596 struct lruvec *lruvec = v;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005597 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005598 int nid = lruvec_pgdat(lruvec)->node_id;
5599 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5600 DEFINE_MAX_SEQ(lruvec);
5601 DEFINE_MIN_SEQ(lruvec);
5602
5603 if (nid == first_memory_node) {
5604 const char *path = memcg ? m->private : "";
5605
5606#ifdef CONFIG_MEMCG
5607 if (memcg)
5608 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5609#endif
5610 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5611 }
5612
5613 seq_printf(m, " node %5d\n", nid);
5614
5615 if (!full)
5616 seq = min_seq[LRU_GEN_ANON];
5617 else if (max_seq >= MAX_NR_GENS)
5618 seq = max_seq - MAX_NR_GENS + 1;
5619 else
5620 seq = 0;
5621
5622 for (; seq <= max_seq; seq++) {
5623 int type, zone;
5624 int gen = lru_gen_from_seq(seq);
5625 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5626
5627 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5628
5629 for (type = 0; type < ANON_AND_FILE; type++) {
5630 unsigned long size = 0;
5631 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5632
5633 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5634 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5635
5636 seq_printf(m, " %10lu%c", size, mark);
5637 }
5638
5639 seq_putc(m, '\n');
5640
5641 if (full)
5642 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5643 }
5644
5645 return 0;
5646}
5647
5648static const struct seq_operations lru_gen_seq_ops = {
5649 .start = lru_gen_seq_start,
5650 .stop = lru_gen_seq_stop,
5651 .next = lru_gen_seq_next,
5652 .show = lru_gen_seq_show,
5653};
5654
5655static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5656 bool can_swap, bool force_scan)
5657{
5658 DEFINE_MAX_SEQ(lruvec);
5659 DEFINE_MIN_SEQ(lruvec);
5660
5661 if (seq < max_seq)
5662 return 0;
5663
5664 if (seq > max_seq)
5665 return -EINVAL;
5666
5667 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5668 return -ERANGE;
5669
5670 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5671
5672 return 0;
5673}
5674
5675static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5676 int swappiness, unsigned long nr_to_reclaim)
5677{
5678 DEFINE_MAX_SEQ(lruvec);
5679
5680 if (seq + MIN_NR_GENS > max_seq)
5681 return -EINVAL;
5682
5683 sc->nr_reclaimed = 0;
5684
5685 while (!signal_pending(current)) {
5686 DEFINE_MIN_SEQ(lruvec);
5687
5688 if (seq < min_seq[!swappiness])
5689 return 0;
5690
5691 if (sc->nr_reclaimed >= nr_to_reclaim)
5692 return 0;
5693
Yu Zhao4fc3ef42022-12-21 21:19:01 -07005694 if (!evict_pages(lruvec, sc, swappiness))
Yu Zhao4983c522022-09-18 02:00:09 -06005695 return 0;
5696
5697 cond_resched();
5698 }
5699
5700 return -EINTR;
5701}
5702
5703static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5704 struct scan_control *sc, int swappiness, unsigned long opt)
5705{
5706 struct lruvec *lruvec;
5707 int err = -EINVAL;
5708 struct mem_cgroup *memcg = NULL;
5709
5710 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5711 return -EINVAL;
5712
5713 if (!mem_cgroup_disabled()) {
5714 rcu_read_lock();
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005715
Yu Zhao4983c522022-09-18 02:00:09 -06005716 memcg = mem_cgroup_from_id(memcg_id);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005717 if (!mem_cgroup_tryget(memcg))
Yu Zhao4983c522022-09-18 02:00:09 -06005718 memcg = NULL;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005719
Yu Zhao4983c522022-09-18 02:00:09 -06005720 rcu_read_unlock();
5721
5722 if (!memcg)
5723 return -EINVAL;
5724 }
5725
5726 if (memcg_id != mem_cgroup_id(memcg))
5727 goto done;
5728
5729 lruvec = get_lruvec(memcg, nid);
5730
5731 if (swappiness < 0)
5732 swappiness = get_swappiness(lruvec, sc);
5733 else if (swappiness > 200)
5734 goto done;
5735
5736 switch (cmd) {
5737 case '+':
5738 err = run_aging(lruvec, seq, sc, swappiness, opt);
5739 break;
5740 case '-':
5741 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5742 break;
5743 }
5744done:
5745 mem_cgroup_put(memcg);
5746
5747 return err;
5748}
5749
Yu Zhao642d9862022-09-18 02:00:10 -06005750/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005751static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5752 size_t len, loff_t *pos)
5753{
5754 void *buf;
5755 char *cur, *next;
5756 unsigned int flags;
5757 struct blk_plug plug;
5758 int err = -EINVAL;
5759 struct scan_control sc = {
5760 .may_writepage = true,
5761 .may_unmap = true,
5762 .may_swap = true,
5763 .reclaim_idx = MAX_NR_ZONES - 1,
5764 .gfp_mask = GFP_KERNEL,
5765 };
5766
5767 buf = kvmalloc(len + 1, GFP_KERNEL);
5768 if (!buf)
5769 return -ENOMEM;
5770
5771 if (copy_from_user(buf, src, len)) {
5772 kvfree(buf);
5773 return -EFAULT;
5774 }
5775
5776 set_task_reclaim_state(current, &sc.reclaim_state);
5777 flags = memalloc_noreclaim_save();
5778 blk_start_plug(&plug);
Yu Zhaof8b57162022-12-21 21:19:05 -07005779 if (!set_mm_walk(NULL, true)) {
Yu Zhao4983c522022-09-18 02:00:09 -06005780 err = -ENOMEM;
5781 goto done;
5782 }
5783
5784 next = buf;
5785 next[len] = '\0';
5786
5787 while ((cur = strsep(&next, ",;\n"))) {
5788 int n;
5789 int end;
5790 char cmd;
5791 unsigned int memcg_id;
5792 unsigned int nid;
5793 unsigned long seq;
5794 unsigned int swappiness = -1;
5795 unsigned long opt = -1;
5796
5797 cur = skip_spaces(cur);
5798 if (!*cur)
5799 continue;
5800
5801 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5802 &seq, &end, &swappiness, &end, &opt, &end);
5803 if (n < 4 || cur[end]) {
5804 err = -EINVAL;
5805 break;
5806 }
5807
5808 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5809 if (err)
5810 break;
5811 }
5812done:
5813 clear_mm_walk();
5814 blk_finish_plug(&plug);
5815 memalloc_noreclaim_restore(flags);
5816 set_task_reclaim_state(current, NULL);
5817
5818 kvfree(buf);
5819
5820 return err ? : len;
5821}
5822
5823static int lru_gen_seq_open(struct inode *inode, struct file *file)
5824{
5825 return seq_open(file, &lru_gen_seq_ops);
5826}
5827
5828static const struct file_operations lru_gen_rw_fops = {
5829 .open = lru_gen_seq_open,
5830 .read = seq_read,
5831 .write = lru_gen_seq_write,
5832 .llseek = seq_lseek,
5833 .release = seq_release,
5834};
5835
5836static const struct file_operations lru_gen_ro_fops = {
5837 .open = lru_gen_seq_open,
5838 .read = seq_read,
5839 .llseek = seq_lseek,
5840 .release = seq_release,
5841};
5842
5843/******************************************************************************
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005844 * initialization
5845 ******************************************************************************/
5846
5847void lru_gen_init_lruvec(struct lruvec *lruvec)
5848{
Yu Zhao430499c2022-09-18 02:00:08 -06005849 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005850 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005851 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005852
5853 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005854 lrugen->enabled = lru_gen_enabled();
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005855
Yu Zhao430499c2022-09-18 02:00:08 -06005856 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5857 lrugen->timestamps[i] = jiffies;
5858
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005859 for_each_gen_type_zone(gen, type, zone)
Yu Zhaodf91dc92022-12-21 21:19:00 -07005860 INIT_LIST_HEAD(&lrugen->pages[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005861
5862 lruvec->mm_state.seq = MIN_NR_GENS;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005863}
5864
5865#ifdef CONFIG_MEMCG
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005866
5867void lru_gen_init_pgdat(struct pglist_data *pgdat)
5868{
5869 int i, j;
5870
5871 spin_lock_init(&pgdat->memcg_lru.lock);
5872
5873 for (i = 0; i < MEMCG_NR_GENS; i++) {
5874 for (j = 0; j < MEMCG_NR_BINS; j++)
5875 INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i);
5876 }
5877}
5878
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005879void lru_gen_init_memcg(struct mem_cgroup *memcg)
5880{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005881 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5882 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005883}
5884
5885void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5886{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005887 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005888 int nid;
5889
5890 for_each_node(nid) {
5891 struct lruvec *lruvec = get_lruvec(memcg, nid);
5892
5893 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5894 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005895
5896 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5897 bitmap_free(lruvec->mm_state.filters[i]);
5898 lruvec->mm_state.filters[i] = NULL;
5899 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005900 }
5901}
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005902
5903void lru_gen_online_memcg(struct mem_cgroup *memcg)
5904{
5905 int gen;
5906 int nid;
5907 int bin = prandom_u32_max(MEMCG_NR_BINS);
5908
5909 for_each_node(nid) {
5910 struct pglist_data *pgdat = NODE_DATA(nid);
5911 struct lruvec *lruvec = get_lruvec(memcg, nid);
5912
5913 spin_lock(&pgdat->memcg_lru.lock);
5914
5915 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
5916
5917 gen = get_memcg_gen(pgdat->memcg_lru.seq);
5918
5919 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
5920 pgdat->memcg_lru.nr_memcgs[gen]++;
5921
5922 lruvec->lrugen.gen = gen;
5923
5924 spin_unlock(&pgdat->memcg_lru.lock);
5925 }
5926}
5927
5928void lru_gen_offline_memcg(struct mem_cgroup *memcg)
5929{
5930 int nid;
5931
5932 for_each_node(nid) {
5933 struct lruvec *lruvec = get_lruvec(memcg, nid);
5934
5935 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
5936 }
5937}
5938
5939void lru_gen_release_memcg(struct mem_cgroup *memcg)
5940{
5941 int gen;
5942 int nid;
5943
5944 for_each_node(nid) {
5945 struct pglist_data *pgdat = NODE_DATA(nid);
5946 struct lruvec *lruvec = get_lruvec(memcg, nid);
5947
5948 spin_lock(&pgdat->memcg_lru.lock);
5949
5950 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
5951
5952 gen = lruvec->lrugen.gen;
5953
5954 hlist_nulls_del_rcu(&lruvec->lrugen.list);
5955 pgdat->memcg_lru.nr_memcgs[gen]--;
5956
5957 if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
5958 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
5959
5960 spin_unlock(&pgdat->memcg_lru.lock);
5961 }
5962}
5963
5964#endif /* CONFIG_MEMCG */
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005965
5966static int __init init_lru_gen(void)
5967{
5968 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5969 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5970
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005971 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5972 pr_err("lru_gen: failed to create sysfs group\n");
5973
Yu Zhao4983c522022-09-18 02:00:09 -06005974 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5975 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5976
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005977 return 0;
5978};
5979late_initcall(init_lru_gen);
5980
Yu Zhao37397872022-09-18 02:00:03 -06005981#else /* !CONFIG_LRU_GEN */
5982
5983static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5984{
5985}
5986
5987static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5988{
5989}
5990
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005991static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5992{
5993}
5994
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005995#endif /* CONFIG_LRU_GEN */
5996
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005997static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005998{
5999 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07006000 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006001 unsigned long nr_to_scan;
6002 enum lru_list lru;
6003 unsigned long nr_reclaimed = 0;
6004 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
Johannes Weiner7b3c9402022-08-02 12:28:11 -04006005 bool proportional_reclaim;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006006 struct blk_plug plug;
Minchan Kima8962f62022-11-02 09:04:41 -07006007 bool do_plug = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006008
Yu Zhaoa3eb6512022-12-21 21:19:04 -07006009 if (lru_gen_enabled() && !global_reclaim(sc)) {
Yu Zhao37397872022-09-18 02:00:03 -06006010 lru_gen_shrink_lruvec(lruvec, sc);
6011 return;
6012 }
6013
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006014 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006015
Mel Gormane82e0562013-07-03 15:01:44 -07006016 /* Record the original scan target for proportional adjustments later */
6017 memcpy(targets, nr, sizeof(nr));
6018
Mel Gorman1a501902014-06-04 16:10:49 -07006019 /*
6020 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
6021 * event that can occur when there is little memory pressure e.g.
6022 * multiple streaming readers/writers. Hence, we do not abort scanning
6023 * when the requested number of pages are reclaimed when scanning at
6024 * DEF_PRIORITY on the assumption that the fact we are direct
6025 * reclaiming implies that kswapd is not keeping up and it is best to
6026 * do a batch of work at once. For memcg reclaim one check is made to
6027 * abort proportional reclaim if either the file or anon lru has already
6028 * dropped to zero at the first pass.
6029 */
Johannes Weiner7b3c9402022-08-02 12:28:11 -04006030 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
6031 sc->priority == DEF_PRIORITY);
Mel Gorman1a501902014-06-04 16:10:49 -07006032
Minchan Kima8962f62022-11-02 09:04:41 -07006033 trace_android_vh_shrink_lruvec_blk_plug(&do_plug);
6034 if (do_plug)
6035 blk_start_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006036 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
6037 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07006038 unsigned long nr_anon, nr_file, percentage;
6039 unsigned long nr_scanned;
6040
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006041 for_each_evictable_lru(lru) {
6042 if (nr[lru]) {
6043 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
6044 nr[lru] -= nr_to_scan;
6045
6046 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07006047 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006048 }
6049 }
Mel Gormane82e0562013-07-03 15:01:44 -07006050
Michal Hockobd041732016-12-02 17:26:48 -08006051 cond_resched();
6052
Johannes Weiner7b3c9402022-08-02 12:28:11 -04006053 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
Mel Gormane82e0562013-07-03 15:01:44 -07006054 continue;
6055
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006056 /*
Mel Gormane82e0562013-07-03 15:01:44 -07006057 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07006058 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07006059 * proportionally what was requested by get_scan_count(). We
6060 * stop reclaiming one LRU and reduce the amount scanning
6061 * proportional to the original scan target.
6062 */
6063 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
6064 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
6065
Mel Gorman1a501902014-06-04 16:10:49 -07006066 /*
6067 * It's just vindictive to attack the larger once the smaller
6068 * has gone to zero. And given the way we stop scanning the
6069 * smaller below, this makes sure that we only make one nudge
6070 * towards proportionality once we've got nr_to_reclaim.
6071 */
6072 if (!nr_file || !nr_anon)
6073 break;
6074
Mel Gormane82e0562013-07-03 15:01:44 -07006075 if (nr_file > nr_anon) {
6076 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
6077 targets[LRU_ACTIVE_ANON] + 1;
6078 lru = LRU_BASE;
6079 percentage = nr_anon * 100 / scan_target;
6080 } else {
6081 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
6082 targets[LRU_ACTIVE_FILE] + 1;
6083 lru = LRU_FILE;
6084 percentage = nr_file * 100 / scan_target;
6085 }
6086
6087 /* Stop scanning the smaller of the LRU */
6088 nr[lru] = 0;
6089 nr[lru + LRU_ACTIVE] = 0;
6090
6091 /*
6092 * Recalculate the other LRU scan count based on its original
6093 * scan target and the percentage scanning already complete
6094 */
6095 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
6096 nr_scanned = targets[lru] - nr[lru];
6097 nr[lru] = targets[lru] * (100 - percentage) / 100;
6098 nr[lru] -= min(nr[lru], nr_scanned);
6099
6100 lru += LRU_ACTIVE;
6101 nr_scanned = targets[lru] - nr[lru];
6102 nr[lru] = targets[lru] * (100 - percentage) / 100;
6103 nr[lru] -= min(nr[lru], nr_scanned);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006104 }
Minchan Kima8962f62022-11-02 09:04:41 -07006105 if (do_plug)
6106 blk_finish_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006107 sc->nr_reclaimed += nr_reclaimed;
6108
6109 /*
6110 * Even if we did not try to evict anon pages at all, we want to
6111 * rebalance the anon lru active/inactive ratio.
6112 */
Dave Hansen2f368a92021-09-02 14:59:23 -07006113 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
6114 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006115 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6116 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006117}
6118
Mel Gorman23b9da52012-05-29 15:06:20 -07006119/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006120static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07006121{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08006122 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07006123 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006124 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07006125 return true;
6126
6127 return false;
6128}
6129
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006130/*
Mel Gorman23b9da52012-05-29 15:06:20 -07006131 * Reclaim/compaction is used for high-order allocation requests. It reclaims
6132 * order-0 pages before compacting the zone. should_continue_reclaim() returns
6133 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07006134 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07006135 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08006136 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006137static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08006138 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08006139 struct scan_control *sc)
6140{
6141 unsigned long pages_for_compaction;
6142 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07006143 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006144
6145 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006146 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08006147 return false;
6148
Vlastimil Babka5ee04712019-09-23 15:37:29 -07006149 /*
6150 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
6151 * number of pages that were scanned. This will return to the caller
6152 * with the risk reclaim/compaction and the resulting allocation attempt
6153 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
6154 * allocations through requiring that the full LRU list has been scanned
6155 * first, by assuming that zero delta of sc->nr_scanned means full LRU
6156 * scan, but that approximation was wrong, and there were corner cases
6157 * where always a non-zero amount of pages were scanned.
6158 */
6159 if (!nr_reclaimed)
6160 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006161
Mel Gorman3e7d3442011-01-13 15:45:56 -08006162 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006163 for (z = 0; z <= sc->reclaim_idx; z++) {
6164 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07006165 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07006166 continue;
6167
6168 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07006169 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07006170 case COMPACT_CONTINUE:
6171 return false;
6172 default:
6173 /* check next zone */
6174 ;
6175 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08006176 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07006177
6178 /*
6179 * If we have not reclaimed enough pages for compaction and the
6180 * inactive lists are large enough, continue reclaiming
6181 */
6182 pages_for_compaction = compact_gap(sc->order);
6183 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07006184 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07006185 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
6186
Vlastimil Babka5ee04712019-09-23 15:37:29 -07006187 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006188}
6189
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006190static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006191{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006192 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08006193 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006194
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006195 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08006196 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006197 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006198 unsigned long reclaimed;
6199 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08006200 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08006201
Xunlei Pange3336ca2020-09-04 16:35:27 -07006202 /*
6203 * This loop can become CPU-bound when target memcgs
6204 * aren't eligible for reclaim - either because they
6205 * don't have any reclaimable pages, or because their
6206 * memory is explicitly protected. Avoid soft lockups.
6207 */
6208 cond_resched();
6209
Liujie Xieb7ea1c42022-06-01 15:38:17 +08006210 trace_android_vh_shrink_node_memcgs(memcg, &skip);
6211 if (skip)
6212 continue;
6213
Chris Down45c7f7e2020-08-06 23:22:05 -07006214 mem_cgroup_calculate_protection(target_memcg, memcg);
6215
6216 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08006217 /*
6218 * Hard protection.
6219 * If there is no reclaimable memory, OOM.
6220 */
6221 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07006222 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08006223 /*
6224 * Soft protection.
6225 * Respect the protection only as long as
6226 * there is an unprotected supply
6227 * of reclaimable memory from other cgroups.
6228 */
6229 if (!sc->memcg_low_reclaim) {
6230 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006231 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006232 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08006233 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08006234 }
6235
Johannes Weinerd2af3392019-11-30 17:55:43 -08006236 reclaimed = sc->nr_reclaimed;
6237 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006238
6239 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006240
Johannes Weinerd2af3392019-11-30 17:55:43 -08006241 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
6242 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07006243
Johannes Weinerd2af3392019-11-30 17:55:43 -08006244 /* Record the group's reclaim efficiency */
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006245 if (!sc->proactive)
6246 vmpressure(sc->gfp_mask, memcg, false,
6247 sc->nr_scanned - scanned,
6248 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006249
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006250 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
6251}
6252
Liu Song6c9e09072020-01-30 22:14:08 -08006253static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006254{
6255 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006256 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08006257 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006258 bool reclaimable = false;
6259
Yu Zhaoa3eb6512022-12-21 21:19:04 -07006260 if (lru_gen_enabled() && global_reclaim(sc)) {
6261 lru_gen_shrink_node(pgdat, sc);
6262 return;
6263 }
6264
Johannes Weiner1b051172019-11-30 17:55:52 -08006265 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
6266
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006267again:
6268 memset(&sc->nr, 0, sizeof(sc->nr));
6269
6270 nr_reclaimed = sc->nr_reclaimed;
6271 nr_scanned = sc->nr_scanned;
6272
Yu Zhao6d313442022-09-18 02:00:00 -06006273 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08006274
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006275 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006276
Johannes Weinerd2af3392019-11-30 17:55:43 -08006277 if (reclaim_state) {
6278 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
6279 reclaim_state->reclaimed_slab = 0;
6280 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07006281
Johannes Weinerd2af3392019-11-30 17:55:43 -08006282 /* Record the subtree's reclaim efficiency */
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006283 if (!sc->proactive)
6284 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
6285 sc->nr_scanned - nr_scanned,
6286 sc->nr_reclaimed - nr_reclaimed);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006287
6288 if (sc->nr_reclaimed - nr_reclaimed)
6289 reclaimable = true;
6290
6291 if (current_is_kswapd()) {
6292 /*
6293 * If reclaim is isolating dirty pages under writeback,
6294 * it implies that the long-lived page allocation rate
6295 * is exceeding the page laundering rate. Either the
6296 * global limits are not being effective at throttling
6297 * processes due to the page distribution throughout
6298 * zones or there is heavy usage of a slow backing
6299 * device. The only option is to throttle from reclaim
6300 * context which is not ideal as there is no guarantee
6301 * the dirtying process is throttled in the same way
6302 * balance_dirty_pages() manages.
6303 *
6304 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6305 * count the number of pages under pages flagged for
6306 * immediate reclaim and stall if any are encountered
6307 * in the nr_immediate check below.
6308 */
6309 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
6310 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006311
Johannes Weinerd2af3392019-11-30 17:55:43 -08006312 /* Allow kswapd to start writing pages during reclaim.*/
6313 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
6314 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07006315
6316 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006317 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08006318 * reclaim and under writeback (nr_immediate), it
6319 * implies that pages are cycling through the LRU
6320 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07006321 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08006322 if (sc->nr.immediate)
6323 congestion_wait(BLK_RW_ASYNC, HZ/10);
6324 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07006325
Johannes Weinerd2af3392019-11-30 17:55:43 -08006326 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08006327 * Tag a node/memcg as congested if all the dirty pages
6328 * scanned were backed by a congested BDI and
6329 * wait_iff_congested will stall.
6330 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08006331 * Legacy memcg will stall in page writeback so avoid forcibly
6332 * stalling in wait_iff_congested().
6333 */
Johannes Weiner1b051172019-11-30 17:55:52 -08006334 if ((current_is_kswapd() ||
6335 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08006336 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08006337 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006338
6339 /*
6340 * Stall direct reclaim for IO completions if underlying BDIs
6341 * and node is congested. Allow kswapd to continue until it
6342 * starts encountering unqueued dirty pages or cycling through
6343 * the LRU too quickly.
6344 */
Johannes Weiner1b051172019-11-30 17:55:52 -08006345 if (!current_is_kswapd() && current_may_throttle() &&
6346 !sc->hibernation_mode &&
6347 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08006348 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
6349
6350 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
6351 sc))
6352 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07006353
Johannes Weinerc73322d2017-05-03 14:51:51 -07006354 /*
6355 * Kswapd gives up on balancing particular nodes after too
6356 * many failures to reclaim anything from them and goes to
6357 * sleep. On reclaim progress, reset the failure counter. A
6358 * successful direct reclaim run will revive a dormant kswapd.
6359 */
6360 if (reclaimable)
6361 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006362}
6363
Vlastimil Babka53853e22014-10-09 15:27:02 -07006364/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006365 * Returns true if compaction should go ahead for a costly-order request, or
6366 * the allocation would already succeed without compaction. Return false if we
6367 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07006368 */
Mel Gorman4f588332016-07-28 15:46:38 -07006369static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006370{
Mel Gorman31483b62016-07-28 15:45:46 -07006371 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006372 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006373
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006374 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6375 if (suitable == COMPACT_SUCCESS)
6376 /* Allocation should succeed already. Don't reclaim. */
6377 return true;
6378 if (suitable == COMPACT_SKIPPED)
6379 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006380 return false;
6381
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006382 /*
6383 * Compaction is already possible, but it takes time to run and there
6384 * are potentially other callers using the pages just freed. So proceed
6385 * with reclaim to make a buffer of free pages available to give
6386 * compaction a reasonable chance of completing and allocating the page.
6387 * Note that we won't actually reclaim the whole buffer in one attempt
6388 * as the target watermark in should_continue_reclaim() is lower. But if
6389 * we are already above the high+gap watermark, don't reclaim at all.
6390 */
6391 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6392
6393 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006394}
6395
Linus Torvalds1da177e2005-04-16 15:20:36 -07006396/*
6397 * This is the direct reclaim path, for page-allocating processes. We only
6398 * try to reclaim pages from zones which will satisfy the caller's allocation
6399 * request.
6400 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07006401 * If a zone is deemed to be full of pinned pages then just give it a light
6402 * scan then give up on it.
6403 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07006404static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006405{
Mel Gormandd1a2392008-04-28 02:12:17 -07006406 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07006407 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07006408 unsigned long nr_soft_reclaimed;
6409 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07006410 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07006411 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006412
Mel Gormancc715d92012-03-21 16:34:00 -07006413 /*
6414 * If the number of buffer_heads in the machine exceeds the maximum
6415 * allowed level, force direct reclaim to scan the highmem zone as
6416 * highmem pages could be pinning lowmem pages storing buffer_heads
6417 */
Weijie Yang619d0d762014-04-07 15:36:59 -07006418 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07006419 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07006420 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07006421 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07006422 }
Mel Gormancc715d92012-03-21 16:34:00 -07006423
Mel Gormand4debc62010-08-09 17:19:29 -07006424 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07006425 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07006426 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006427 * Take care memory controller reclaiming has small influence
6428 * to global LRU.
6429 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08006430 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04006431 if (!cpuset_zone_allowed(zone,
6432 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006433 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006434
Johannes Weiner0b064962014-08-06 16:06:12 -07006435 /*
6436 * If we already have plenty of memory free for
6437 * compaction in this zone, don't free any more.
6438 * Even though compaction is invoked for any
6439 * non-zero order, only frequent costly order
6440 * reclamation is disruptive enough to become a
6441 * noticeable problem, like transparent huge
6442 * page allocations.
6443 */
6444 if (IS_ENABLED(CONFIG_COMPACTION) &&
6445 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07006446 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07006447 sc->compaction_ready = true;
6448 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07006449 }
Johannes Weiner0b064962014-08-06 16:06:12 -07006450
Andrew Morton0608f432013-09-24 15:27:41 -07006451 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07006452 * Shrink each node in the zonelist once. If the
6453 * zonelist is ordered by zone (not the default) then a
6454 * node may be shrunk multiple times but in that case
6455 * the user prefers lower zones being preserved.
6456 */
6457 if (zone->zone_pgdat == last_pgdat)
6458 continue;
6459
6460 /*
Andrew Morton0608f432013-09-24 15:27:41 -07006461 * This steals pages from memory cgroups over softlimit
6462 * and returns the number of reclaimed pages and
6463 * scanned pages. This works for global memory pressure
6464 * and balancing, not for a memcg's limit.
6465 */
6466 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006467 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006468 sc->order, sc->gfp_mask,
6469 &nr_soft_scanned);
6470 sc->nr_reclaimed += nr_soft_reclaimed;
6471 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006472 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006473 }
Nick Piggin408d8542006-09-25 23:31:27 -07006474
Mel Gorman79dafcd2016-07-28 15:45:53 -07006475 /* See comment about same check for global reclaim above */
6476 if (zone->zone_pgdat == last_pgdat)
6477 continue;
6478 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006479 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006480 }
Mel Gormane0c23272011-10-31 17:09:33 -07006481
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006482 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006483 * Restore to original mask to avoid the impact on the caller if we
6484 * promoted it to __GFP_HIGHMEM.
6485 */
6486 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006487}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006488
Johannes Weinerb9107182019-11-30 17:55:59 -08006489static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006490{
Johannes Weinerb9107182019-11-30 17:55:59 -08006491 struct lruvec *target_lruvec;
6492 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006493
Yu Zhao37397872022-09-18 02:00:03 -06006494 if (lru_gen_enabled())
6495 return;
6496
Johannes Weinerb9107182019-11-30 17:55:59 -08006497 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006498 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6499 target_lruvec->refaults[0] = refaults;
6500 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6501 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006502}
6503
Linus Torvalds1da177e2005-04-16 15:20:36 -07006504/*
6505 * This is the main entry point to direct page reclaim.
6506 *
6507 * If a full scan of the inactive list fails to free enough memory then we
6508 * are "out of memory" and something needs to be killed.
6509 *
6510 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6511 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006512 * caller can't do much about. We kick the writeback threads and take explicit
6513 * naps in the hope that some of these pages can be written. But if the
6514 * allocating task holds filesystem locks which prevent writeout this might not
6515 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006516 *
6517 * returns: 0, if no pages reclaimed
6518 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006519 */
Mel Gormandac1d272008-04-28 02:12:12 -07006520static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006521 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006522{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006523 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006524 pg_data_t *last_pgdat;
6525 struct zoneref *z;
6526 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006527retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006528 delayacct_freepages_start();
6529
Johannes Weinerb5ead352019-11-30 17:55:40 -08006530 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006531 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006532
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006533 do {
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006534 if (!sc->proactive)
6535 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6536 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006537 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006538 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006539
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006540 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006541 break;
6542
6543 if (sc->compaction_ready)
6544 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006545
6546 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006547 * If we're getting trouble reclaiming, start doing
6548 * writepage even in laptop mode.
6549 */
6550 if (sc->priority < DEF_PRIORITY - 2)
6551 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006552 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006553
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006554 last_pgdat = NULL;
6555 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6556 sc->nodemask) {
6557 if (zone->zone_pgdat == last_pgdat)
6558 continue;
6559 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006560
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006561 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006562
6563 if (cgroup_reclaim(sc)) {
6564 struct lruvec *lruvec;
6565
6566 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6567 zone->zone_pgdat);
6568 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6569 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006570 }
6571
Keika Kobayashi873b4772008-07-25 01:48:52 -07006572 delayacct_freepages_end();
6573
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006574 if (sc->nr_reclaimed)
6575 return sc->nr_reclaimed;
6576
Mel Gorman0cee34f2012-01-12 17:19:49 -08006577 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006578 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006579 return 1;
6580
Johannes Weinerb91ac372019-11-30 17:56:02 -08006581 /*
6582 * We make inactive:active ratio decisions based on the node's
6583 * composition of memory, but a restrictive reclaim_idx or a
6584 * memory.low cgroup setting can exempt large amounts of
6585 * memory from reclaim. Neither of which are very common, so
6586 * instead of doing costly eligibility calculations of the
6587 * entire cgroup subtree up front, we assume the estimates are
6588 * good, and retry with forcible deactivation if that fails.
6589 */
6590 if (sc->skipped_deactivate) {
6591 sc->priority = initial_priority;
6592 sc->force_deactivate = 1;
6593 sc->skipped_deactivate = 0;
6594 goto retry;
6595 }
6596
Johannes Weiner241994ed2015-02-11 15:26:06 -08006597 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006598 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006599 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006600 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006601 sc->memcg_low_reclaim = 1;
6602 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006603 goto retry;
6604 }
6605
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006606 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006607}
6608
Johannes Weinerc73322d2017-05-03 14:51:51 -07006609static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006610{
6611 struct zone *zone;
6612 unsigned long pfmemalloc_reserve = 0;
6613 unsigned long free_pages = 0;
6614 int i;
6615 bool wmark_ok;
6616
Johannes Weinerc73322d2017-05-03 14:51:51 -07006617 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6618 return true;
6619
Mel Gorman55150612012-07-31 16:44:35 -07006620 for (i = 0; i <= ZONE_NORMAL; i++) {
6621 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006622 if (!managed_zone(zone))
6623 continue;
6624
6625 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006626 continue;
6627
Mel Gorman55150612012-07-31 16:44:35 -07006628 pfmemalloc_reserve += min_wmark_pages(zone);
6629 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6630 }
6631
Mel Gorman675becc2014-06-04 16:07:35 -07006632 /* If there are no reserves (unexpected config) then do not throttle */
6633 if (!pfmemalloc_reserve)
6634 return true;
6635
Mel Gorman55150612012-07-31 16:44:35 -07006636 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6637
6638 /* kswapd must be awake if processes are being throttled */
6639 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006640 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6641 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006642
Mel Gorman55150612012-07-31 16:44:35 -07006643 wake_up_interruptible(&pgdat->kswapd_wait);
6644 }
6645
6646 return wmark_ok;
6647}
6648
6649/*
6650 * Throttle direct reclaimers if backing storage is backed by the network
6651 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6652 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006653 * when the low watermark is reached.
6654 *
6655 * Returns true if a fatal signal was delivered during throttling. If this
6656 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006657 */
Mel Gorman50694c22012-11-26 16:29:48 -08006658static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006659 nodemask_t *nodemask)
6660{
Mel Gorman675becc2014-06-04 16:07:35 -07006661 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006662 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006663 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006664
6665 /*
6666 * Kernel threads should not be throttled as they may be indirectly
6667 * responsible for cleaning pages necessary for reclaim to make forward
6668 * progress. kjournald for example may enter direct reclaim while
6669 * committing a transaction where throttling it could forcing other
6670 * processes to block on log_wait_commit().
6671 */
6672 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006673 goto out;
6674
6675 /*
6676 * If a fatal signal is pending, this process should not throttle.
6677 * It should return quickly so it can exit and free its memory
6678 */
6679 if (fatal_signal_pending(current))
6680 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006681
Mel Gorman675becc2014-06-04 16:07:35 -07006682 /*
6683 * Check if the pfmemalloc reserves are ok by finding the first node
6684 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6685 * GFP_KERNEL will be required for allocating network buffers when
6686 * swapping over the network so ZONE_HIGHMEM is unusable.
6687 *
6688 * Throttling is based on the first usable node and throttled processes
6689 * wait on a queue until kswapd makes progress and wakes them. There
6690 * is an affinity then between processes waking up and where reclaim
6691 * progress has been made assuming the process wakes on the same node.
6692 * More importantly, processes running on remote nodes will not compete
6693 * for remote pfmemalloc reserves and processes on different nodes
6694 * should make reasonable progress.
6695 */
6696 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006697 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006698 if (zone_idx(zone) > ZONE_NORMAL)
6699 continue;
6700
6701 /* Throttle based on the first usable node */
6702 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006703 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006704 goto out;
6705 break;
6706 }
6707
6708 /* If no zone was usable by the allocation flags then do not throttle */
6709 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006710 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006711
Mel Gorman68243e72012-07-31 16:44:39 -07006712 /* Account for the throttling */
6713 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6714
Mel Gorman55150612012-07-31 16:44:35 -07006715 /*
6716 * If the caller cannot enter the filesystem, it's possible that it
6717 * is due to the caller holding an FS lock or performing a journal
6718 * transaction in the case of a filesystem like ext[3|4]. In this case,
6719 * it is not safe to block on pfmemalloc_wait as kswapd could be
6720 * blocked waiting on the same lock. Instead, throttle for up to a
6721 * second before continuing.
6722 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006723 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006724 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006725 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006726 else
6727 /* Throttle until kswapd wakes the process */
6728 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6729 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006730
Mel Gorman50694c22012-11-26 16:29:48 -08006731 if (fatal_signal_pending(current))
6732 return true;
6733
6734out:
6735 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006736}
6737
Mel Gormandac1d272008-04-28 02:12:12 -07006738unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006739 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006740{
Mel Gorman33906bc2010-08-09 17:19:16 -07006741 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006742 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006743 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006744 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006745 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006746 .order = order,
6747 .nodemask = nodemask,
6748 .priority = DEF_PRIORITY,
6749 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006750 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006751 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006752 };
6753
Mel Gorman55150612012-07-31 16:44:35 -07006754 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006755 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6756 * Confirm they are large enough for max values.
6757 */
6758 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6759 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6760 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6761
6762 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006763 * Do not enter reclaim if fatal signal was delivered while throttled.
6764 * 1 is returned so that the page allocator does not OOM kill at this
6765 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006766 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006767 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006768 return 1;
6769
Andrew Morton1732d2b012019-07-16 16:26:15 -07006770 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006771 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006772
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006773 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006774
6775 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006776 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006777
6778 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006779}
6780
Andrew Mortonc255a452012-07-31 16:43:02 -07006781#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006782
Michal Hockod2e5fb92019-08-30 16:04:50 -07006783/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006784unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006785 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006786 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006787 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006788{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006789 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006790 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006791 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006792 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006793 .may_writepage = !laptop_mode,
6794 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006795 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006796 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006797 };
Ying Han0ae5e892011-05-26 16:25:25 -07006798
Michal Hockod2e5fb92019-08-30 16:04:50 -07006799 WARN_ON_ONCE(!current->reclaim_state);
6800
Balbir Singh4e416952009-09-23 15:56:39 -07006801 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6802 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006803
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006804 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006805 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006806
Balbir Singh4e416952009-09-23 15:56:39 -07006807 /*
6808 * NOTE: Although we can get the priority field, using it
6809 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006810 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006811 * will pick up pages from other mem cgroup's as well. We hack
6812 * the priority and make it zero.
6813 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006814 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006815
6816 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6817
Ying Han0ae5e892011-05-26 16:25:25 -07006818 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006819
Balbir Singh4e416952009-09-23 15:56:39 -07006820 return sc.nr_reclaimed;
6821}
6822
Johannes Weiner72835c82012-01-12 17:18:32 -08006823unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006824 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006825 gfp_t gfp_mask,
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006826 unsigned int reclaim_options)
Balbir Singh66e17072008-02-07 00:13:56 -08006827{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006828 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006829 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006830 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006831 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006832 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006833 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006834 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006835 .target_mem_cgroup = memcg,
6836 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006837 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006838 .may_unmap = 1,
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006839 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
6840 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
Ying Hana09ed5e2011-05-24 17:12:26 -07006841 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006842 /*
6843 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6844 * equal pressure on all the nodes. This is based on the assumption that
6845 * the reclaim does not bail out early.
6846 */
6847 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006848
Andrew Morton1732d2b012019-07-16 16:26:15 -07006849 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006850 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006851 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006852
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006853 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006854
Vlastimil Babka499118e2017-05-08 15:59:50 -07006855 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006856 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006857 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006858
6859 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006860}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006861EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006862#endif
6863
Yu Zhao37397872022-09-18 02:00:03 -06006864static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006865{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006866 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006867 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006868
Yu Zhao37397872022-09-18 02:00:03 -06006869 if (lru_gen_enabled()) {
6870 lru_gen_age_node(pgdat, sc);
6871 return;
6872 }
6873
Dave Hansen2f368a92021-09-02 14:59:23 -07006874 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006875 return;
6876
Johannes Weinerb91ac372019-11-30 17:56:02 -08006877 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6878 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6879 return;
6880
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006881 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6882 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006883 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6884 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6885 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006886 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6887 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006888}
6889
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006890static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006891{
6892 int i;
6893 struct zone *zone;
6894
6895 /*
6896 * Check for watermark boosts top-down as the higher zones
6897 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006898 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006899 * start prematurely when there is no boosting and a lower
6900 * zone is balanced.
6901 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006902 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006903 zone = pgdat->node_zones + i;
6904 if (!managed_zone(zone))
6905 continue;
6906
6907 if (zone->watermark_boost)
6908 return true;
6909 }
6910
6911 return false;
6912}
6913
Mel Gormane716f2e2017-05-03 14:53:45 -07006914/*
6915 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006916 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006917 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006918static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006919{
Mel Gormane716f2e2017-05-03 14:53:45 -07006920 int i;
6921 unsigned long mark = -1;
6922 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006923
Mel Gorman1c308442018-12-28 00:35:52 -08006924 /*
6925 * Check watermarks bottom-up as lower zones are more likely to
6926 * meet watermarks.
6927 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006928 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006929 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006930
Mel Gormane716f2e2017-05-03 14:53:45 -07006931 if (!managed_zone(zone))
6932 continue;
6933
6934 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006935 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006936 return true;
6937 }
6938
6939 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006940 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006941 * need balancing by definition. This can happen if a zone-restricted
6942 * allocation tries to wake a remote kswapd.
6943 */
6944 if (mark == -1)
6945 return true;
6946
6947 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006948}
6949
Mel Gorman631b6e02017-05-03 14:53:41 -07006950/* Clear pgdat state for congested, dirty or under writeback. */
6951static void clear_pgdat_congested(pg_data_t *pgdat)
6952{
Johannes Weiner1b051172019-11-30 17:55:52 -08006953 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6954
6955 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006956 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6957 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6958}
6959
Mel Gorman1741c872011-01-13 15:46:21 -08006960/*
Mel Gorman55150612012-07-31 16:44:35 -07006961 * Prepare kswapd for sleeping. This verifies that there are no processes
6962 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6963 *
6964 * Returns true if kswapd is ready to sleep
6965 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006966static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6967 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006968{
Mel Gorman55150612012-07-31 16:44:35 -07006969 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006970 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006971 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006972 * race between when kswapd checks the watermarks and a process gets
6973 * throttled. There is also a potential race if processes get
6974 * throttled, kswapd wakes, a large process exits thereby balancing the
6975 * zones, which causes kswapd to exit balance_pgdat() before reaching
6976 * the wake up checks. If kswapd is going to sleep, no process should
6977 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6978 * the wake up is premature, processes will wake kswapd and get
6979 * throttled again. The difference from wake ups in balance_pgdat() is
6980 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006981 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006982 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6983 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006984
Johannes Weinerc73322d2017-05-03 14:51:51 -07006985 /* Hopeless node, leave it to direct reclaim */
6986 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6987 return true;
6988
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006989 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006990 clear_pgdat_congested(pgdat);
6991 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006992 }
6993
Shantanu Goel333b0a42017-05-03 14:53:38 -07006994 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006995}
6996
Linus Torvalds1da177e2005-04-16 15:20:36 -07006997/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006998 * kswapd shrinks a node of pages that are at or below the highest usable
6999 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07007000 *
7001 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07007002 * reclaim or if the lack of progress was due to pages under writeback.
7003 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07007004 */
Mel Gorman1d82de62016-07-28 15:45:43 -07007005static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07007006 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07007007{
Mel Gorman1d82de62016-07-28 15:45:43 -07007008 struct zone *zone;
7009 int z;
Mel Gorman75485362013-07-03 15:01:42 -07007010
Mel Gorman1d82de62016-07-28 15:45:43 -07007011 /* Reclaim a number of pages proportional to the number of zones */
7012 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07007013 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07007014 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07007015 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07007016 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07007017
Mel Gorman1d82de62016-07-28 15:45:43 -07007018 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07007019 }
7020
Mel Gorman1d82de62016-07-28 15:45:43 -07007021 /*
7022 * Historically care was taken to put equal pressure on all zones but
7023 * now pressure is applied based on node LRU order.
7024 */
Mel Gorman970a39a2016-07-28 15:46:35 -07007025 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07007026
7027 /*
7028 * Fragmentation may mean that the system cannot be rebalanced for
7029 * high-order allocations. If twice the allocation size has been
7030 * reclaimed then recheck watermarks only at order-0 to prevent
7031 * excessive reclaim. Assume that a process requested a high-order
7032 * can direct reclaim/compact.
7033 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07007034 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07007035 sc->order = 0;
7036
Mel Gormanb8e83b92013-07-03 15:01:45 -07007037 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07007038}
7039
Mel Gormanc49c2c42021-06-28 19:42:21 -07007040/* Page allocator PCP high watermark is lowered if reclaim is active. */
7041static inline void
7042update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
7043{
7044 int i;
7045 struct zone *zone;
7046
7047 for (i = 0; i <= highest_zoneidx; i++) {
7048 zone = pgdat->node_zones + i;
7049
7050 if (!managed_zone(zone))
7051 continue;
7052
7053 if (active)
7054 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7055 else
7056 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7057 }
7058}
7059
7060static inline void
7061set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7062{
7063 update_reclaim_active(pgdat, highest_zoneidx, true);
7064}
7065
7066static inline void
7067clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7068{
7069 update_reclaim_active(pgdat, highest_zoneidx, false);
7070}
7071
Mel Gorman75485362013-07-03 15:01:42 -07007072/*
Mel Gorman1d82de62016-07-28 15:45:43 -07007073 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
7074 * that are eligible for use by the caller until at least one zone is
7075 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007076 *
Mel Gorman1d82de62016-07-28 15:45:43 -07007077 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007078 *
7079 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07007080 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08007081 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07007082 * or lower is eligible for reclaim until at least one usable zone is
7083 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007084 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007085static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007086{
Linus Torvalds1da177e2005-04-16 15:20:36 -07007087 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07007088 unsigned long nr_soft_reclaimed;
7089 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07007090 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08007091 unsigned long nr_boost_reclaim;
7092 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
7093 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07007094 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08007095 struct scan_control sc = {
7096 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07007097 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07007098 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08007099 };
Omar Sandoval93781322018-06-07 17:07:02 -07007100
Andrew Morton1732d2b012019-07-16 16:26:15 -07007101 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07007102 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007103 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007104
Christoph Lameterf8891e52006-06-30 01:55:45 -07007105 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007106
Mel Gorman1c308442018-12-28 00:35:52 -08007107 /*
7108 * Account for the reclaim boost. Note that the zone boost is left in
7109 * place so that parallel allocations that are near the watermark will
7110 * stall or direct reclaim until kswapd is finished.
7111 */
7112 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007113 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08007114 zone = pgdat->node_zones + i;
7115 if (!managed_zone(zone))
7116 continue;
7117
7118 nr_boost_reclaim += zone->watermark_boost;
7119 zone_boosts[i] = zone->watermark_boost;
7120 }
7121 boosted = nr_boost_reclaim;
7122
7123restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07007124 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007125 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007126 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07007127 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07007128 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08007129 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07007130 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07007131
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007132 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007133
Mel Gorman86c79f62016-07-28 15:45:59 -07007134 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07007135 * If the number of buffer_heads exceeds the maximum allowed
7136 * then consider reclaiming from all zones. This has a dual
7137 * purpose -- on 64-bit systems it is expected that
7138 * buffer_heads are stripped during active rotation. On 32-bit
7139 * systems, highmem pages can pin lowmem memory and shrinking
7140 * buffers can relieve lowmem pressure. Reclaim may still not
7141 * go ahead if all eligible zones for the original allocation
7142 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07007143 */
7144 if (buffer_heads_over_limit) {
7145 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
7146 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07007147 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07007148 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007149
Mel Gorman970a39a2016-07-28 15:46:35 -07007150 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08007151 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007152 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07007153 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08007154
Mel Gorman86c79f62016-07-28 15:45:59 -07007155 /*
Mel Gorman1c308442018-12-28 00:35:52 -08007156 * If the pgdat is imbalanced then ignore boosting and preserve
7157 * the watermarks for a later time and restart. Note that the
7158 * zone watermarks will be still reset at the end of balancing
7159 * on the grounds that the normal reclaim should be enough to
7160 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07007161 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007162 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007163 if (!balanced && nr_boost_reclaim) {
7164 nr_boost_reclaim = 0;
7165 goto restart;
7166 }
7167
7168 /*
7169 * If boosting is not active then only reclaim if there are no
7170 * eligible zones. Note that sc.reclaim_idx is not used as
7171 * buffer_heads_over_limit may have adjusted it.
7172 */
7173 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07007174 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08007175
Mel Gorman1c308442018-12-28 00:35:52 -08007176 /* Limit the priority of boosting to avoid reclaim writeback */
7177 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
7178 raise_priority = false;
7179
7180 /*
7181 * Do not writeback or swap pages for boosted reclaim. The
7182 * intent is to relieve pressure not issue sub-optimal IO
7183 * from reclaim context. If no pages are reclaimed, the
7184 * reclaim will be aborted.
7185 */
7186 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
7187 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08007188
Linus Torvalds1da177e2005-04-16 15:20:36 -07007189 /*
Yu Zhao37397872022-09-18 02:00:03 -06007190 * Do some background aging, to give pages a chance to be
7191 * referenced before reclaiming. All pages are rotated
7192 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07007193 */
Yu Zhao37397872022-09-18 02:00:03 -06007194 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07007195
7196 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007197 * If we're getting trouble reclaiming, start doing writepage
7198 * even in laptop mode.
7199 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07007200 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007201 sc.may_writepage = 1;
7202
Mel Gorman1d82de62016-07-28 15:45:43 -07007203 /* Call soft limit reclaim before calling shrink_node. */
7204 sc.nr_scanned = 0;
7205 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07007206 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07007207 sc.gfp_mask, &nr_soft_scanned);
7208 sc.nr_reclaimed += nr_soft_reclaimed;
7209
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007210 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07007211 * There should be no need to raise the scanning priority if
7212 * enough pages are already being scanned that that high
7213 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007214 */
Mel Gorman970a39a2016-07-28 15:46:35 -07007215 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07007216 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07007217
7218 /*
7219 * If the low watermark is met there is no need for processes
7220 * to be throttled on pfmemalloc_wait as they should not be
7221 * able to safely make forward progress. Wake them
7222 */
7223 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07007224 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08007225 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07007226
Mel Gormanb8e83b92013-07-03 15:01:45 -07007227 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007228 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007229 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007230 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007231 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07007232 break;
7233
7234 /*
7235 * Raise priority if scanning rate is too low or there was no
7236 * progress in reclaiming pages
7237 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07007238 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08007239 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
7240
7241 /*
7242 * If reclaim made no progress for a boost, stop reclaim as
7243 * IO cannot be queued and it could be an infinite loop in
7244 * extreme circumstances.
7245 */
7246 if (nr_boost_reclaim && !nr_reclaimed)
7247 break;
7248
Johannes Weinerc73322d2017-05-03 14:51:51 -07007249 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07007250 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07007251 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007252
Johannes Weinerc73322d2017-05-03 14:51:51 -07007253 if (!sc.nr_reclaimed)
7254 pgdat->kswapd_failures++;
7255
Mel Gormanb8e83b92013-07-03 15:01:45 -07007256out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07007257 clear_reclaim_active(pgdat, highest_zoneidx);
7258
Mel Gorman1c308442018-12-28 00:35:52 -08007259 /* If reclaim was boosted, account for the reclaim done in this pass */
7260 if (boosted) {
7261 unsigned long flags;
7262
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007263 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08007264 if (!zone_boosts[i])
7265 continue;
7266
7267 /* Increments are under the zone lock */
7268 zone = pgdat->node_zones + i;
7269 spin_lock_irqsave(&zone->lock, flags);
7270 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7271 spin_unlock_irqrestore(&zone->lock, flags);
7272 }
7273
7274 /*
7275 * As there is now likely space, wakeup kcompact to defragment
7276 * pageblocks.
7277 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007278 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007279 }
7280
Johannes Weiner2a2e4882017-05-03 14:55:03 -07007281 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007282 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07007283 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07007284 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07007285
Mel Gorman0abdee22011-01-13 15:46:22 -08007286 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07007287 * Return the order kswapd stopped reclaiming at as
7288 * prepare_kswapd_sleep() takes it into account. If another caller
7289 * entered the allocator slow path while kswapd was awake, order will
7290 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08007291 */
Mel Gorman1d82de62016-07-28 15:45:43 -07007292 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007293}
7294
Mel Gormane716f2e2017-05-03 14:53:45 -07007295/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007296 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7297 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7298 * not a valid index then either kswapd runs for first time or kswapd couldn't
7299 * sleep after previous reclaim attempt (node is still unbalanced). In that
7300 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07007301 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007302static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7303 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07007304{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007305 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007306
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007307 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07007308}
7309
Mel Gorman38087d92016-07-28 15:45:49 -07007310static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007311 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007312{
7313 long remaining = 0;
7314 DEFINE_WAIT(wait);
7315
7316 if (freezing(current) || kthread_should_stop())
7317 return;
7318
7319 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7320
Shantanu Goel333b0a42017-05-03 14:53:38 -07007321 /*
7322 * Try to sleep for a short interval. Note that kcompactd will only be
7323 * woken if it is possible to sleep for a short interval. This is
7324 * deliberate on the assumption that if reclaim cannot keep an
7325 * eligible zone balanced that it's also unlikely that compaction will
7326 * succeed.
7327 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007328 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07007329 /*
7330 * Compaction records what page blocks it recently failed to
7331 * isolate pages from and skips them in the future scanning.
7332 * When kswapd is going to sleep, it is reasonable to assume
7333 * that pages and compaction may succeed so reset the cache.
7334 */
7335 reset_isolation_suitable(pgdat);
7336
7337 /*
7338 * We have freed the memory, now we should compact it to make
7339 * allocation of the requested order possible.
7340 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007341 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07007342
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007343 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07007344
7345 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007346 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07007347 * order. The values will either be from a wakeup request or
7348 * the previous request that slept prematurely.
7349 */
7350 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007351 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7352 kswapd_highest_zoneidx(pgdat,
7353 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07007354
7355 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7356 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07007357 }
7358
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007359 finish_wait(&pgdat->kswapd_wait, &wait);
7360 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7361 }
7362
7363 /*
7364 * After a short sleep, check if it was a premature sleep. If not, then
7365 * go fully to sleep until explicitly woken up.
7366 */
Mel Gormand9f21d42016-07-28 15:46:41 -07007367 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007368 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007369 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7370
7371 /*
7372 * vmstat counters are not perfectly accurate and the estimated
7373 * value for counters such as NR_FREE_PAGES can deviate from the
7374 * true value by nr_online_cpus * threshold. To avoid the zone
7375 * watermarks being breached while under pressure, we reduce the
7376 * per-cpu vmstat threshold while kswapd is awake and restore
7377 * them before going back to sleep.
7378 */
7379 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07007380
7381 if (!kthread_should_stop())
7382 schedule();
7383
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007384 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7385 } else {
7386 if (remaining)
7387 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7388 else
7389 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7390 }
7391 finish_wait(&pgdat->kswapd_wait, &wait);
7392}
7393
Linus Torvalds1da177e2005-04-16 15:20:36 -07007394/*
7395 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07007396 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007397 *
7398 * This basically trickles out pages so that we have _some_
7399 * free memory available even if there is no other activity
7400 * that frees anything up. This is needed for things like routing
7401 * etc, where we otherwise might have all activity going on in
7402 * asynchronous contexts that cannot page things out.
7403 *
7404 * If there are applications that are active memory-allocators
7405 * (most normal use), this basically shouldn't matter.
7406 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307407int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007408{
Mel Gormane716f2e2017-05-03 14:53:45 -07007409 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007410 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07007411 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007412 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10307413 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007414
Rusty Russell174596a2009-01-01 10:12:29 +10307415 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07007416 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007417
7418 /*
7419 * Tell the memory management that we're a "memory allocator",
7420 * and that if we need more memory we should get access to it
7421 * regardless (see "__alloc_pages()"). "kswapd" should
7422 * never get caught in the normal page freeing logic.
7423 *
7424 * (Kswapd normally doesn't need memory anyway, but sometimes
7425 * you need a small amount of memory in order to be able to
7426 * page out something else, and this flag essentially protects
7427 * us from recursively trying to free more memory as we're
7428 * trying to free the first piece of memory in the first place).
7429 */
Christoph Lameter930d9152006-01-08 01:00:47 -08007430 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07007431 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07007432
Qian Cai5644e1fb2020-04-01 21:10:12 -07007433 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007434 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007435 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08007436 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07007437
Qian Cai5644e1fb2020-04-01 21:10:12 -07007438 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007439 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7440 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07007441
Mel Gorman38087d92016-07-28 15:45:49 -07007442kswapd_try_sleep:
7443 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007444 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07007445
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007446 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08007447 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007448 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7449 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007450 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007451 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007452
David Rientjes8fe23e02009-12-14 17:58:33 -08007453 ret = try_to_freeze();
7454 if (kthread_should_stop())
7455 break;
7456
7457 /*
7458 * We can speed up thawing tasks if we don't call balance_pgdat
7459 * after returning from the refrigerator
7460 */
Mel Gorman38087d92016-07-28 15:45:49 -07007461 if (ret)
7462 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07007463
Mel Gorman38087d92016-07-28 15:45:49 -07007464 /*
7465 * Reclaim begins at the requested order but if a high-order
7466 * reclaim fails then kswapd falls back to reclaiming for
7467 * order-0. If that happens, kswapd will consider sleeping
7468 * for the order it finished reclaiming at (reclaim_order)
7469 * but kcompactd is woken to compact for the original
7470 * request (alloc_order).
7471 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007472 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007473 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007474 reclaim_order = balance_pgdat(pgdat, alloc_order,
7475 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007476 if (reclaim_order < alloc_order)
7477 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007478 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007479
Johannes Weiner71abdc12014-06-06 14:35:35 -07007480 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007481
Linus Torvalds1da177e2005-04-16 15:20:36 -07007482 return 0;
7483}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307484EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007485
7486/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007487 * A zone is low on free memory or too fragmented for high-order memory. If
7488 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7489 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7490 * has failed or is not needed, still wake up kcompactd if only compaction is
7491 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007492 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007493void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007494 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007495{
7496 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007497 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007498
Mel Gorman6aa303d2016-09-01 16:14:55 -07007499 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007500 return;
7501
David Rientjes5ecd9d42018-04-05 16:25:16 -07007502 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007503 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007504
Qian Cai5644e1fb2020-04-01 21:10:12 -07007505 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007506 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007507
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007508 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7509 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007510
7511 if (READ_ONCE(pgdat->kswapd_order) < order)
7512 WRITE_ONCE(pgdat->kswapd_order, order);
7513
Con Kolivas8d0986e2005-09-13 01:25:07 -07007514 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007515 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007516
David Rientjes5ecd9d42018-04-05 16:25:16 -07007517 /* Hopeless node, leave it to direct reclaim if possible */
7518 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007519 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7520 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007521 /*
7522 * There may be plenty of free memory available, but it's too
7523 * fragmented for high-order allocations. Wake up kcompactd
7524 * and rely on compaction_suitable() to determine if it's
7525 * needed. If it fails, it will defer subsequent attempts to
7526 * ratelimit its work.
7527 */
7528 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007529 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007530 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007531 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007532
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007533 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007534 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007535 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007536}
7537
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007538#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007539/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007540 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007541 * freed pages.
7542 *
7543 * Rather than trying to age LRUs the aim is to preserve the overall
7544 * LRU order by reclaiming preferentially
7545 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007546 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007547unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007548{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007549 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007550 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007551 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007552 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007553 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007554 .may_writepage = 1,
7555 .may_unmap = 1,
7556 .may_swap = 1,
7557 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007558 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007559 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007560 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007561 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007562
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007563 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007564 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007565 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007566
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007567 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007568
Andrew Morton1732d2b012019-07-16 16:26:15 -07007569 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007570 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007571 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007572
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007573 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007574}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007575#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007576
Yasunori Goto3218ae12006-06-27 02:53:33 -07007577/*
7578 * This kswapd start function will be called by init and node-hot-add.
7579 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7580 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007581void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007582{
7583 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307584 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007585
7586 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007587 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007588
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307589 trace_android_vh_kswapd_per_node(nid, &skip, true);
7590 if (skip)
7591 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007592 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7593 if (IS_ERR(pgdat->kswapd)) {
7594 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007595 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007596 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007597 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007598 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007599}
7600
David Rientjes8fe23e02009-12-14 17:58:33 -08007601/*
Jiang Liud8adde12012-07-11 14:01:52 -07007602 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007603 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007604 */
7605void kswapd_stop(int nid)
7606{
7607 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307608 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007609
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307610 trace_android_vh_kswapd_per_node(nid, &skip, false);
7611 if (skip)
7612 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007613 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007614 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007615 NODE_DATA(nid)->kswapd = NULL;
7616 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007617}
7618
Linus Torvalds1da177e2005-04-16 15:20:36 -07007619static int __init kswapd_init(void)
7620{
Wei Yang6b700b52020-04-01 21:10:09 -07007621 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007622
Linus Torvalds1da177e2005-04-16 15:20:36 -07007623 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007624 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007625 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007626 return 0;
7627}
7628
7629module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007630
7631#ifdef CONFIG_NUMA
7632/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007633 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007634 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007635 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007636 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007637 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007638int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007639
Dave Hansen51998362021-02-24 12:09:15 -08007640/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007641 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007642 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7643 * a zone.
7644 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007645#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007646
Christoph Lameter9eeff232006-01-18 17:42:31 -08007647/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007648 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007649 * occur.
7650 */
7651int sysctl_min_unmapped_ratio = 1;
7652
7653/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007654 * If the number of slab pages in a zone grows beyond this percentage then
7655 * slab reclaim needs to occur.
7656 */
7657int sysctl_min_slab_ratio = 5;
7658
Mel Gorman11fb9982016-07-28 15:46:20 -07007659static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007660{
Mel Gorman11fb9982016-07-28 15:46:20 -07007661 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7662 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7663 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007664
7665 /*
7666 * It's possible for there to be more file mapped pages than
7667 * accounted for by the pages on the file LRU lists because
7668 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7669 */
7670 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7671}
7672
7673/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007674static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007675{
Alexandru Moised031a152015-11-05 18:48:08 -08007676 unsigned long nr_pagecache_reclaimable;
7677 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007678
7679 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007680 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007681 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007682 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007683 * a better estimate
7684 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007685 if (node_reclaim_mode & RECLAIM_UNMAP)
7686 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007687 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007688 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007689
7690 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007691 if (!(node_reclaim_mode & RECLAIM_WRITE))
7692 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007693
7694 /* Watch for any possible underflows due to delta */
7695 if (unlikely(delta > nr_pagecache_reclaimable))
7696 delta = nr_pagecache_reclaimable;
7697
7698 return nr_pagecache_reclaimable - delta;
7699}
7700
Christoph Lameter0ff38492006-09-25 23:31:52 -07007701/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007702 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007703 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007704static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007705{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007706 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007707 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007708 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007709 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007710 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007711 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007712 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007713 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007714 .priority = NODE_RECLAIM_PRIORITY,
7715 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7716 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007717 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007718 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007719 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007720 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007721
Yafang Shao132bb8c2019-05-13 17:17:53 -07007722 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7723 sc.gfp_mask);
7724
Christoph Lameter9eeff232006-01-18 17:42:31 -08007725 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007726 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007727 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007728 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007729 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007730 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007731 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007732 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007733 noreclaim_flag = memalloc_noreclaim_save();
7734 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007735 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007736
Mel Gormana5f5f912016-07-28 15:46:32 -07007737 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007738 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007739 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007740 * priorities until we have enough memory freed.
7741 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007742 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007743 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007744 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007745 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007746
Andrew Morton1732d2b012019-07-16 16:26:15 -07007747 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007748 current->flags &= ~PF_SWAPWRITE;
7749 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007750 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007751 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007752
7753 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7754
Rik van Riela79311c2009-01-06 14:40:01 -08007755 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007756}
Andrew Morton179e9632006-03-22 00:08:18 -08007757
Mel Gormana5f5f912016-07-28 15:46:32 -07007758int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007759{
David Rientjesd773ed62007-10-16 23:26:01 -07007760 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007761
7762 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007763 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007764 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007765 *
Christoph Lameter96146342006-07-03 00:24:13 -07007766 * A small portion of unmapped file backed pages is needed for
7767 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007768 * thrown out if the node is overallocated. So we do not reclaim
7769 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007770 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007771 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007772 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007773 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7774 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007775 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007776
7777 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007778 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007779 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007780 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007781 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007782
7783 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007784 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007785 * have associated processors. This will favor the local processor
7786 * over remote processors and spread off node memory allocations
7787 * as wide as possible.
7788 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007789 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7790 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007791
Mel Gormana5f5f912016-07-28 15:46:32 -07007792 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7793 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007794
Mel Gormana5f5f912016-07-28 15:46:32 -07007795 ret = __node_reclaim(pgdat, gfp_mask, order);
7796 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007797
Mel Gorman24cf725182009-06-16 15:33:23 -07007798 if (!ret)
7799 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7800
David Rientjesd773ed62007-10-16 23:26:01 -07007801 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007802}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007803#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007804
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007805/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007806 * check_move_unevictable_pages - check pages for evictability and move to
7807 * appropriate zone lru list
7808 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007809 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007810 * Checks pages for evictability, if an evictable page is in the unevictable
7811 * lru list, moves it to the appropriate evictable lru list. This function
7812 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007813 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007814void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007815{
Alex Shi6168d0d2020-12-15 12:34:29 -08007816 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007817 int pgscanned = 0;
7818 int pgrescued = 0;
7819 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007820
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007821 for (i = 0; i < pvec->nr; i++) {
7822 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007823 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007824
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007825 if (PageTransTail(page))
7826 continue;
7827
7828 nr_pages = thp_nr_pages(page);
7829 pgscanned += nr_pages;
7830
Alex Shid25b5bd2020-12-15 12:34:16 -08007831 /* block memcg migration during page moving between lru */
7832 if (!TestClearPageLRU(page))
7833 continue;
7834
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007835 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007836 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007837 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007838 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007839 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007840 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007841 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007842 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007843 }
Hugh Dickins24513262012-01-20 14:34:21 -08007844
Alex Shi6168d0d2020-12-15 12:34:29 -08007845 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007846 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7847 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007848 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007849 } else if (pgscanned) {
7850 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007851 }
Hugh Dickins850465792012-01-20 14:34:19 -08007852}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007853EXPORT_SYMBOL_GPL(check_move_unevictable_pages);