blob: 69b52e10593902c27c5fbab5ee97770940df4d1e [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
Martin Liud705ab992021-06-23 12:20:18 +080077EXPORT_TRACEPOINT_SYMBOL_GPL(mm_vmscan_direct_reclaim_begin);
78EXPORT_TRACEPOINT_SYMBOL_GPL(mm_vmscan_direct_reclaim_end);
79
Linus Torvalds1da177e2005-04-16 15:20:36 -070080struct scan_control {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -080081 /* How many pages shrink_list() should reclaim */
82 unsigned long nr_to_reclaim;
83
Johannes Weineree814fe2014-08-06 16:06:19 -070084 /*
85 * Nodemask of nodes allowed by the caller. If NULL, all nodes
86 * are scanned.
87 */
88 nodemask_t *nodemask;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -070089
KOSAKI Motohiro5f53e762010-05-24 14:32:37 -070090 /*
Johannes Weinerf16015f2012-01-12 17:17:52 -080091 * The memory cgroup that hit its limit and as a result is the
92 * primary target of this reclaim invocation.
93 */
94 struct mem_cgroup *target_mem_cgroup;
Balbir Singh66e17072008-02-07 00:13:56 -080095
Johannes Weiner7cf111b2020-06-03 16:03:06 -070096 /*
97 * Scan pressure balancing between anon and file LRUs
98 */
99 unsigned long anon_cost;
100 unsigned long file_cost;
101
Johannes Weinerb91ac372019-11-30 17:56:02 -0800102 /* Can active pages be deactivated as part of reclaim? */
103#define DEACTIVATE_ANON 1
104#define DEACTIVATE_FILE 2
105 unsigned int may_deactivate:2;
106 unsigned int force_deactivate:1;
107 unsigned int skipped_deactivate:1;
108
Johannes Weiner1276ad62017-02-24 14:56:11 -0800109 /* Writepage batching in laptop mode; RECLAIM_WRITE */
Johannes Weineree814fe2014-08-06 16:06:19 -0700110 unsigned int may_writepage:1;
111
112 /* Can mapped pages be reclaimed? */
113 unsigned int may_unmap:1;
114
115 /* Can pages be swapped as part of reclaim? */
116 unsigned int may_swap:1;
117
Yisheng Xied6622f62017-05-03 14:53:57 -0700118 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700119 * Cgroup memory below memory.low is protected as long as we
120 * don't threaten to OOM. If any cgroup is reclaimed at
121 * reduced force or passed over entirely due to its memory.low
122 * setting (memcg_low_skipped), and nothing is reclaimed as a
123 * result, then go back for one more cycle that reclaims the protected
124 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700125 */
126 unsigned int memcg_low_reclaim:1;
127 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800128
Johannes Weineree814fe2014-08-06 16:06:19 -0700129 unsigned int hibernation_mode:1;
130
131 /* One of the zones is ready for compaction */
132 unsigned int compaction_ready:1;
133
Johannes Weinerb91ac372019-11-30 17:56:02 -0800134 /* There is easily reclaimable cold cache in the current node */
135 unsigned int cache_trim_mode:1;
136
Johannes Weiner53138ce2019-11-30 17:55:56 -0800137 /* The file pages on the current node are dangerously low */
138 unsigned int file_is_tiny:1;
139
Dave Hansen26aa2d12021-09-02 14:59:16 -0700140 /* Always discard instead of demoting to lower tier memory */
141 unsigned int no_demotion:1;
142
Greg Thelenbb451fd2018-08-17 15:45:19 -0700143 /* Allocation order */
144 s8 order;
145
146 /* Scan (total_size >> priority) pages at once */
147 s8 priority;
148
149 /* The highest zone to isolate pages for reclaim from */
150 s8 reclaim_idx;
151
152 /* This context's GFP mask */
153 gfp_t gfp_mask;
154
Johannes Weineree814fe2014-08-06 16:06:19 -0700155 /* Incremented by the number of inactive pages that were scanned */
156 unsigned long nr_scanned;
157
158 /* Number of pages freed so far during a call to shrink_zones() */
159 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700160
161 struct {
162 unsigned int dirty;
163 unsigned int unqueued_dirty;
164 unsigned int congested;
165 unsigned int writeback;
166 unsigned int immediate;
167 unsigned int file_taken;
168 unsigned int taken;
169 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700170
171 /* for recording the reclaimed slab by now */
172 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700173};
174
Linus Torvalds1da177e2005-04-16 15:20:36 -0700175#ifdef ARCH_HAS_PREFETCHW
176#define prefetchw_prev_lru_page(_page, _base, _field) \
177 do { \
178 if ((_page)->lru.prev != _base) { \
179 struct page *prev; \
180 \
181 prev = lru_to_page(&(_page->lru)); \
182 prefetchw(&prev->_field); \
183 } \
184 } while (0)
185#else
186#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
187#endif
188
189/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700190 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700191 */
192int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700193
Yang Shi0a432dc2019-09-23 15:38:12 -0700194static void set_task_reclaim_state(struct task_struct *task,
195 struct reclaim_state *rs)
196{
197 /* Check for an overwrite */
198 WARN_ON_ONCE(rs && task->reclaim_state);
199
200 /* Check for the nulling of an already-nulled member */
201 WARN_ON_ONCE(!rs && !task->reclaim_state);
202
203 task->reclaim_state = rs;
204}
205
Linus Torvalds1da177e2005-04-16 15:20:36 -0700206static LIST_HEAD(shrinker_list);
207static DECLARE_RWSEM(shrinker_rwsem);
208
Yang Shi0a432dc2019-09-23 15:38:12 -0700209#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700210static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700211
Yang Shi3c6f17e2021-05-04 18:36:33 -0700212/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700213static inline int shrinker_map_size(int nr_items)
214{
215 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
216}
Yang Shi2bfd3632021-05-04 18:36:11 -0700217
Yang Shi3c6f17e2021-05-04 18:36:33 -0700218static inline int shrinker_defer_size(int nr_items)
219{
220 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
221}
222
Yang Shi468ab842021-05-04 18:36:26 -0700223static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
224 int nid)
225{
226 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
227 lockdep_is_held(&shrinker_rwsem));
228}
229
Yang Shie4262c42021-05-04 18:36:23 -0700230static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700231 int map_size, int defer_size,
232 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700233{
Yang Shie4262c42021-05-04 18:36:23 -0700234 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700235 struct mem_cgroup_per_node *pn;
236 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700237 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700238
Yang Shi2bfd3632021-05-04 18:36:11 -0700239 for_each_node(nid) {
240 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700241 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700242 /* Not yet online memcg */
243 if (!old)
244 return 0;
245
246 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
247 if (!new)
248 return -ENOMEM;
249
Yang Shi3c6f17e2021-05-04 18:36:33 -0700250 new->nr_deferred = (atomic_long_t *)(new + 1);
251 new->map = (void *)new->nr_deferred + defer_size;
252
253 /* map: set all old bits, clear all new bits */
254 memset(new->map, (int)0xff, old_map_size);
255 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
256 /* nr_deferred: copy old values, clear all new values */
257 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
258 memset((void *)new->nr_deferred + old_defer_size, 0,
259 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700260
Yang Shie4262c42021-05-04 18:36:23 -0700261 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700262 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700263 }
264
265 return 0;
266}
267
Yang Shie4262c42021-05-04 18:36:23 -0700268void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700269{
270 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700271 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700272 int nid;
273
Yang Shi2bfd3632021-05-04 18:36:11 -0700274 for_each_node(nid) {
275 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700276 info = rcu_dereference_protected(pn->shrinker_info, true);
277 kvfree(info);
278 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700279 }
280}
281
Yang Shie4262c42021-05-04 18:36:23 -0700282int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700283{
Yang Shie4262c42021-05-04 18:36:23 -0700284 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700285 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700286 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700287
Yang Shid27cf2a2021-05-04 18:36:14 -0700288 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700289 map_size = shrinker_map_size(shrinker_nr_max);
290 defer_size = shrinker_defer_size(shrinker_nr_max);
291 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700292 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700293 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
294 if (!info) {
295 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700296 ret = -ENOMEM;
297 break;
298 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700299 info->nr_deferred = (atomic_long_t *)(info + 1);
300 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700301 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700302 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700303 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700304
305 return ret;
306}
307
Yang Shi3c6f17e2021-05-04 18:36:33 -0700308static inline bool need_expand(int nr_max)
309{
310 return round_up(nr_max, BITS_PER_LONG) >
311 round_up(shrinker_nr_max, BITS_PER_LONG);
312}
313
Yang Shie4262c42021-05-04 18:36:23 -0700314static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700315{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700316 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700317 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700318 int map_size, defer_size = 0;
319 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700320 struct mem_cgroup *memcg;
321
Yang Shi3c6f17e2021-05-04 18:36:33 -0700322 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700323 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700324
Yang Shi2bfd3632021-05-04 18:36:11 -0700325 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700326 goto out;
327
328 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700329
Yang Shi3c6f17e2021-05-04 18:36:33 -0700330 map_size = shrinker_map_size(new_nr_max);
331 defer_size = shrinker_defer_size(new_nr_max);
332 old_map_size = shrinker_map_size(shrinker_nr_max);
333 old_defer_size = shrinker_defer_size(shrinker_nr_max);
334
Yang Shi2bfd3632021-05-04 18:36:11 -0700335 memcg = mem_cgroup_iter(NULL, NULL, NULL);
336 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700337 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
338 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700339 if (ret) {
340 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700341 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700342 }
343 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700344out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700345 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700346 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700347
Yang Shi2bfd3632021-05-04 18:36:11 -0700348 return ret;
349}
350
351void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
352{
353 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700354 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700355
356 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700357 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700358 /* Pairs with smp mb in shrink_slab() */
359 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700360 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700361 rcu_read_unlock();
362 }
363}
364
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700365static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700366
367static int prealloc_memcg_shrinker(struct shrinker *shrinker)
368{
369 int id, ret = -ENOMEM;
370
Yang Shi476b30a2021-05-04 18:36:39 -0700371 if (mem_cgroup_disabled())
372 return -ENOSYS;
373
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700374 down_write(&shrinker_rwsem);
375 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700376 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700377 if (id < 0)
378 goto unlock;
379
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700380 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700381 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700382 idr_remove(&shrinker_idr, id);
383 goto unlock;
384 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700385 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700386 shrinker->id = id;
387 ret = 0;
388unlock:
389 up_write(&shrinker_rwsem);
390 return ret;
391}
392
393static void unregister_memcg_shrinker(struct shrinker *shrinker)
394{
395 int id = shrinker->id;
396
397 BUG_ON(id < 0);
398
Yang Shi41ca6682021-05-04 18:36:29 -0700399 lockdep_assert_held(&shrinker_rwsem);
400
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700401 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700402}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700403
Yang Shi86750832021-05-04 18:36:36 -0700404static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
405 struct mem_cgroup *memcg)
406{
407 struct shrinker_info *info;
408
409 info = shrinker_info_protected(memcg, nid);
410 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
411}
412
413static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
414 struct mem_cgroup *memcg)
415{
416 struct shrinker_info *info;
417
418 info = shrinker_info_protected(memcg, nid);
419 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
420}
421
Yang Shia1780152021-05-04 18:36:42 -0700422void reparent_shrinker_deferred(struct mem_cgroup *memcg)
423{
424 int i, nid;
425 long nr;
426 struct mem_cgroup *parent;
427 struct shrinker_info *child_info, *parent_info;
428
429 parent = parent_mem_cgroup(memcg);
430 if (!parent)
431 parent = root_mem_cgroup;
432
433 /* Prevent from concurrent shrinker_info expand */
434 down_read(&shrinker_rwsem);
435 for_each_node(nid) {
436 child_info = shrinker_info_protected(memcg, nid);
437 parent_info = shrinker_info_protected(parent, nid);
438 for (i = 0; i < shrinker_nr_max; i++) {
439 nr = atomic_long_read(&child_info->nr_deferred[i]);
440 atomic_long_add(nr, &parent_info->nr_deferred[i]);
441 }
442 }
443 up_read(&shrinker_rwsem);
444}
445
Johannes Weinerb5ead352019-11-30 17:55:40 -0800446static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800447{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800448 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800449}
Tejun Heo97c93412015-05-22 18:23:36 -0400450
Yu Zhao4fc3ef42022-12-21 21:19:01 -0700451static bool global_reclaim(struct scan_control *sc)
452{
453 return !sc->target_mem_cgroup || mem_cgroup_is_root(sc->target_mem_cgroup);
454}
455
Tejun Heo97c93412015-05-22 18:23:36 -0400456/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800457 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400458 * @sc: scan_control in question
459 *
460 * The normal page dirty throttling mechanism in balance_dirty_pages() is
461 * completely broken with the legacy memcg and direct stalling in
462 * shrink_page_list() is used for throttling instead, which lacks all the
463 * niceties such as fairness, adaptive pausing, bandwidth proportional
464 * allocation and configurability.
465 *
466 * This function tests whether the vmscan currently in progress can assume
467 * that the normal dirty throttling mechanism is operational.
468 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800469static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400470{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800471 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400472 return true;
473#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800474 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400475 return true;
476#endif
477 return false;
478}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800479#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700480static int prealloc_memcg_shrinker(struct shrinker *shrinker)
481{
Yang Shi476b30a2021-05-04 18:36:39 -0700482 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700483}
484
485static void unregister_memcg_shrinker(struct shrinker *shrinker)
486{
487}
488
Yang Shi86750832021-05-04 18:36:36 -0700489static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
490 struct mem_cgroup *memcg)
491{
492 return 0;
493}
494
495static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
496 struct mem_cgroup *memcg)
497{
498 return 0;
499}
500
Johannes Weinerb5ead352019-11-30 17:55:40 -0800501static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800502{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800503 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800504}
Tejun Heo97c93412015-05-22 18:23:36 -0400505
Yu Zhao4fc3ef42022-12-21 21:19:01 -0700506static bool global_reclaim(struct scan_control *sc)
507{
508 return true;
509}
510
Johannes Weinerb5ead352019-11-30 17:55:40 -0800511static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400512{
513 return true;
514}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800515#endif
516
Yang Shi86750832021-05-04 18:36:36 -0700517static long xchg_nr_deferred(struct shrinker *shrinker,
518 struct shrink_control *sc)
519{
520 int nid = sc->nid;
521
522 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
523 nid = 0;
524
525 if (sc->memcg &&
526 (shrinker->flags & SHRINKER_MEMCG_AWARE))
527 return xchg_nr_deferred_memcg(nid, shrinker,
528 sc->memcg);
529
530 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
531}
532
533
534static long add_nr_deferred(long nr, struct shrinker *shrinker,
535 struct shrink_control *sc)
536{
537 int nid = sc->nid;
538
539 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
540 nid = 0;
541
542 if (sc->memcg &&
543 (shrinker->flags & SHRINKER_MEMCG_AWARE))
544 return add_nr_deferred_memcg(nr, nid, shrinker,
545 sc->memcg);
546
547 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
548}
549
Dave Hansen26aa2d12021-09-02 14:59:16 -0700550static bool can_demote(int nid, struct scan_control *sc)
551{
Huang Ying20b51af12021-09-02 14:59:33 -0700552 if (!numa_demotion_enabled)
553 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700554 if (sc) {
555 if (sc->no_demotion)
556 return false;
557 /* It is pointless to do demotion in memcg reclaim */
558 if (cgroup_reclaim(sc))
559 return false;
560 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700561 if (next_demotion_node(nid) == NUMA_NO_NODE)
562 return false;
563
Huang Ying20b51af12021-09-02 14:59:33 -0700564 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700565}
566
Keith Buscha2a36482021-09-02 14:59:26 -0700567static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
568 int nid,
569 struct scan_control *sc)
570{
571 if (memcg == NULL) {
572 /*
573 * For non-memcg reclaim, is there
574 * space in any swap device?
575 */
576 if (get_nr_swap_pages() > 0)
577 return true;
578 } else {
579 /* Is the memcg below its swap limit? */
580 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
581 return true;
582 }
583
584 /*
585 * The page can not be swapped.
586 *
587 * Can it be reclaimed from this node via demotion?
588 */
589 return can_demote(nid, sc);
590}
591
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700592/*
593 * This misses isolated pages which are not accounted for to save counters.
594 * As the data only determines if reclaim or compaction continues, it is
595 * not expected that isolated pages will be a dominating factor.
596 */
597unsigned long zone_reclaimable_pages(struct zone *zone)
598{
599 unsigned long nr;
600
601 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
602 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700603 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700604 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
605 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
606
607 return nr;
608}
609
Michal Hockofd538802017-02-22 15:45:58 -0800610/**
611 * lruvec_lru_size - Returns the number of pages on the given LRU list.
612 * @lruvec: lru vector
613 * @lru: lru to use
614 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
615 */
Yu Zhao20913392021-02-24 12:08:44 -0800616static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
617 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800618{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800619 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800620 int zid;
621
Johannes Weinerde3b0152019-11-30 17:55:31 -0800622 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800623 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800624
Michal Hockofd538802017-02-22 15:45:58 -0800625 if (!managed_zone(zone))
626 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800627
Michal Hockofd538802017-02-22 15:45:58 -0800628 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800629 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800630 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800631 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800632 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800633 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800634}
635
Linus Torvalds1da177e2005-04-16 15:20:36 -0700636/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000637 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700638 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900639int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700640{
Yang Shi476b30a2021-05-04 18:36:39 -0700641 unsigned int size;
642 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000643
Yang Shi476b30a2021-05-04 18:36:39 -0700644 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
645 err = prealloc_memcg_shrinker(shrinker);
646 if (err != -ENOSYS)
647 return err;
648
649 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
650 }
651
652 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000653 if (shrinker->flags & SHRINKER_NUMA_AWARE)
654 size *= nr_node_ids;
655
656 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
657 if (!shrinker->nr_deferred)
658 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700659
Tetsuo Handa8e049442018-04-04 19:53:07 +0900660 return 0;
661}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000662
Tetsuo Handa8e049442018-04-04 19:53:07 +0900663void free_prealloced_shrinker(struct shrinker *shrinker)
664{
Yang Shi41ca6682021-05-04 18:36:29 -0700665 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
666 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700667 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700668 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700669 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700670 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700671
Tetsuo Handa8e049442018-04-04 19:53:07 +0900672 kfree(shrinker->nr_deferred);
673 shrinker->nr_deferred = NULL;
674}
675
676void register_shrinker_prepared(struct shrinker *shrinker)
677{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700678 down_write(&shrinker_rwsem);
679 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700680 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700681 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900682}
683
684int register_shrinker(struct shrinker *shrinker)
685{
686 int err = prealloc_shrinker(shrinker);
687
688 if (err)
689 return err;
690 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000691 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700692}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700693EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700694
695/*
696 * Remove one
697 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700698void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700699{
Yang Shi41ca6682021-05-04 18:36:29 -0700700 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900701 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700702
Linus Torvalds1da177e2005-04-16 15:20:36 -0700703 down_write(&shrinker_rwsem);
704 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700705 shrinker->flags &= ~SHRINKER_REGISTERED;
706 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
707 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700708 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700709
Andrew Vaginae393322013-10-16 13:46:46 -0700710 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900711 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700712}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700713EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700714
715#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000716
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800717static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800718 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700719{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000720 unsigned long freed = 0;
721 unsigned long long delta;
722 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700723 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000724 long nr;
725 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000726 long batch_size = shrinker->batch ? shrinker->batch
727 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800728 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000729
rongqianfeng8da6ee32021-05-21 10:30:14 +0800730 trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
731
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700732 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700733 if (freeable == 0 || freeable == SHRINK_EMPTY)
734 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000735
736 /*
737 * copy the current shrinker scan count into a local variable
738 * and zero it so that other concurrent shrinker invocations
739 * don't also do this scanning work.
740 */
Yang Shi86750832021-05-04 18:36:36 -0700741 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000742
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700743 if (shrinker->seeks) {
744 delta = freeable >> priority;
745 delta *= 4;
746 do_div(delta, shrinker->seeks);
747 } else {
748 /*
749 * These objects don't require any IO to create. Trim
750 * them aggressively under memory pressure to keep
751 * them from causing refetches in the IO caches.
752 */
753 delta = freeable / 2;
754 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700755
Yang Shi18bb4732021-05-04 18:36:45 -0700756 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000757 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700758 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000759
760 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800761 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000762
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800763 /*
764 * Normally, we should not scan less than batch_size objects in one
765 * pass to avoid too frequent shrinker calls, but if the slab has less
766 * than batch_size objects in total and we are really tight on memory,
767 * we will try to reclaim all available objects, otherwise we can end
768 * up failing allocations although there are plenty of reclaimable
769 * objects spread over several slabs with usage less than the
770 * batch_size.
771 *
772 * We detect the "tight on memory" situations by looking at the total
773 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700774 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800775 * scanning at high prio and therefore should try to reclaim as much as
776 * possible.
777 */
778 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700779 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000780 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800781 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000782
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800783 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700784 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000785 ret = shrinker->scan_objects(shrinker, shrinkctl);
786 if (ret == SHRINK_STOP)
787 break;
788 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000789
Chris Wilsond460acb2017-09-06 16:19:26 -0700790 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
791 total_scan -= shrinkctl->nr_scanned;
792 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000793
794 cond_resched();
795 }
796
Yang Shi18bb4732021-05-04 18:36:45 -0700797 /*
798 * The deferred work is increased by any new work (delta) that wasn't
799 * done, decreased by old deferred work that was done now.
800 *
801 * And it is capped to two times of the freeable items.
802 */
803 next_deferred = max_t(long, (nr + delta - scanned), 0);
804 next_deferred = min(next_deferred, (2 * freeable));
805
Glauber Costa1d3d4432013-08-28 10:18:04 +1000806 /*
807 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700808 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000809 */
Yang Shi86750832021-05-04 18:36:36 -0700810 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000811
Yang Shi8efb4b52021-05-04 18:36:08 -0700812 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000813 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700814}
815
Yang Shi0a432dc2019-09-23 15:38:12 -0700816#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700817static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
818 struct mem_cgroup *memcg, int priority)
819{
Yang Shie4262c42021-05-04 18:36:23 -0700820 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700821 unsigned long ret, freed = 0;
822 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700823
Yang Shi0a432dc2019-09-23 15:38:12 -0700824 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700825 return 0;
826
827 if (!down_read_trylock(&shrinker_rwsem))
828 return 0;
829
Yang Shi468ab842021-05-04 18:36:26 -0700830 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700831 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700832 goto unlock;
833
Yang Shie4262c42021-05-04 18:36:23 -0700834 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700835 struct shrink_control sc = {
836 .gfp_mask = gfp_mask,
837 .nid = nid,
838 .memcg = memcg,
839 };
840 struct shrinker *shrinker;
841
842 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700843 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700844 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700845 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700846 continue;
847 }
848
Yang Shi0a432dc2019-09-23 15:38:12 -0700849 /* Call non-slab shrinkers even though kmem is disabled */
850 if (!memcg_kmem_enabled() &&
851 !(shrinker->flags & SHRINKER_NONSLAB))
852 continue;
853
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700854 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700855 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700856 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700857 /*
858 * After the shrinker reported that it had no objects to
859 * free, but before we cleared the corresponding bit in
860 * the memcg shrinker map, a new object might have been
861 * added. To make sure, we have the bit set in this
862 * case, we invoke the shrinker one more time and reset
863 * the bit if it reports that it is not empty anymore.
864 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700865 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700866 *
867 * list_lru_add() shrink_slab_memcg()
868 * list_add_tail() clear_bit()
869 * <MB> <MB>
870 * set_bit() do_shrink_slab()
871 */
872 smp_mb__after_atomic();
873 ret = do_shrink_slab(&sc, shrinker, priority);
874 if (ret == SHRINK_EMPTY)
875 ret = 0;
876 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700877 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700878 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700879 freed += ret;
880
881 if (rwsem_is_contended(&shrinker_rwsem)) {
882 freed = freed ? : 1;
883 break;
884 }
885 }
886unlock:
887 up_read(&shrinker_rwsem);
888 return freed;
889}
Yang Shi0a432dc2019-09-23 15:38:12 -0700890#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700891static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
892 struct mem_cgroup *memcg, int priority)
893{
894 return 0;
895}
Yang Shi0a432dc2019-09-23 15:38:12 -0700896#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700897
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800898/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800899 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800900 * @gfp_mask: allocation context
901 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800902 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800903 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700904 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800905 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700906 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800907 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
908 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700909 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700910 * @memcg specifies the memory cgroup to target. Unaware shrinkers
911 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800912 *
Josef Bacik9092c712018-01-31 16:16:26 -0800913 * @priority is sc->priority, we take the number of objects and >> by priority
914 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700915 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800916 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700917 */
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800918unsigned long shrink_slab(gfp_t gfp_mask, int nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800919 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800920 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700921{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700922 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700923 struct shrinker *shrinker;
wudean842c68a2021-04-27 17:40:41 +0800924 bool bypass = false;
925
926 trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
927 if (bypass)
928 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700929
Yang Shifa1e5122019-08-02 21:48:44 -0700930 /*
931 * The root memcg might be allocated even though memcg is disabled
932 * via "cgroup_disable=memory" boot parameter. This could make
933 * mem_cgroup_is_root() return false, then just run memcg slab
934 * shrink, but skip global shrink. This may result in premature
935 * oom.
936 */
937 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700938 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800939
Tetsuo Handae830c632018-04-05 16:23:35 -0700940 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700941 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700942
943 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800944 struct shrink_control sc = {
945 .gfp_mask = gfp_mask,
946 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800947 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800948 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800949
Kirill Tkhai9b996462018-08-17 15:48:21 -0700950 ret = do_shrink_slab(&sc, shrinker, priority);
951 if (ret == SHRINK_EMPTY)
952 ret = 0;
953 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800954 /*
955 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700956 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800957 * by parallel ongoing shrinking.
958 */
959 if (rwsem_is_contended(&shrinker_rwsem)) {
960 freed = freed ? : 1;
961 break;
962 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700963 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800964
Linus Torvalds1da177e2005-04-16 15:20:36 -0700965 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700966out:
967 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000968 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700969}
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800970EXPORT_SYMBOL_GPL(shrink_slab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700971
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800972void drop_slab_node(int nid)
973{
974 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700975 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800976
977 do {
978 struct mem_cgroup *memcg = NULL;
979
Chunxin Zang069c4112020-10-13 16:56:46 -0700980 if (fatal_signal_pending(current))
981 return;
982
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800983 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700984 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800985 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800986 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800987 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700988 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800989}
990
991void drop_slab(void)
992{
993 int nid;
994
995 for_each_online_node(nid)
996 drop_slab_node(nid);
997}
998
Linus Torvalds1da177e2005-04-16 15:20:36 -0700999static inline int is_page_cache_freeable(struct page *page)
1000{
Johannes Weinerceddc3a2009-09-21 17:03:00 -07001001 /*
1002 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -04001003 * that isolated the page, the page cache and optional buffer
1004 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -07001005 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -07001006 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -04001007 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001008}
1009
Yang Shicb165562019-11-30 17:55:28 -08001010static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001011{
Christoph Lameter930d9152006-01-08 01:00:47 -08001012 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001013 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001014 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001015 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001016 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001017 return 1;
1018 return 0;
1019}
1020
1021/*
1022 * We detected a synchronous write error writing a page out. Probably
1023 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1024 * fsync(), msync() or close().
1025 *
1026 * The tricky part is that after writepage we cannot touch the mapping: nothing
1027 * prevents it from being freed up. But we have a ref on the page and once
1028 * that page is locked, the mapping is pinned.
1029 *
1030 * We're allowed to run sleeping lock_page() here because we know the caller has
1031 * __GFP_FS.
1032 */
1033static void handle_write_error(struct address_space *mapping,
1034 struct page *page, int error)
1035{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001036 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001037 if (page_mapping(page) == mapping)
1038 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001039 unlock_page(page);
1040}
1041
Christoph Lameter04e62a22006-06-23 02:03:38 -07001042/* possible outcome of pageout() */
1043typedef enum {
1044 /* failed to write page out, page is locked */
1045 PAGE_KEEP,
1046 /* move page to the active list, page is locked */
1047 PAGE_ACTIVATE,
1048 /* page has been sent to the disk successfully, page is unlocked */
1049 PAGE_SUCCESS,
1050 /* page is clean and locked */
1051 PAGE_CLEAN,
1052} pageout_t;
1053
Linus Torvalds1da177e2005-04-16 15:20:36 -07001054/*
Andrew Morton1742f192006-03-22 00:08:21 -08001055 * pageout is called by shrink_page_list() for each dirty page.
1056 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001057 */
Yang Shicb165562019-11-30 17:55:28 -08001058static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001059{
1060 /*
1061 * If the page is dirty, only perform writeback if that write
1062 * will be non-blocking. To prevent this allocation from being
1063 * stalled by pagecache activity. But note that there may be
1064 * stalls if we need to run get_block(). We could test
1065 * PagePrivate for that.
1066 *
Al Viro81742022014-04-03 03:17:43 -04001067 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001068 * this page's queue, we can perform writeback even if that
1069 * will block.
1070 *
1071 * If the page is swapcache, write it back even if that would
1072 * block, for some throttling. This happens by accident, because
1073 * swap_backing_dev_info is bust: it doesn't reflect the
1074 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001075 */
1076 if (!is_page_cache_freeable(page))
1077 return PAGE_KEEP;
1078 if (!mapping) {
1079 /*
1080 * Some data journaling orphaned pages can have
1081 * page->mapping == NULL while being dirty with clean buffers.
1082 */
David Howells266cf652009-04-03 16:42:36 +01001083 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001084 if (try_to_free_buffers(page)) {
1085 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001086 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001087 return PAGE_CLEAN;
1088 }
1089 }
1090 return PAGE_KEEP;
1091 }
1092 if (mapping->a_ops->writepage == NULL)
1093 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001094 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001095 return PAGE_KEEP;
1096
1097 if (clear_page_dirty_for_io(page)) {
1098 int res;
1099 struct writeback_control wbc = {
1100 .sync_mode = WB_SYNC_NONE,
1101 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001102 .range_start = 0,
1103 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001104 .for_reclaim = 1,
1105 };
1106
1107 SetPageReclaim(page);
1108 res = mapping->a_ops->writepage(page, &wbc);
1109 if (res < 0)
1110 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001111 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001112 ClearPageReclaim(page);
1113 return PAGE_ACTIVATE;
1114 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001115
Linus Torvalds1da177e2005-04-16 15:20:36 -07001116 if (!PageWriteback(page)) {
1117 /* synchronous write or broken a_ops? */
1118 ClearPageReclaim(page);
1119 }
yalin wang3aa23852016-01-14 15:18:30 -08001120 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001121 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001122 return PAGE_SUCCESS;
1123 }
1124
1125 return PAGE_CLEAN;
1126}
1127
Andrew Mortona649fd92006-10-17 00:09:36 -07001128/*
Nick Piggine2867812008-07-25 19:45:30 -07001129 * Same as remove_mapping, but if the page is removed from the mapping, it
1130 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001131 */
Johannes Weinera5289102014-04-03 14:47:51 -07001132static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001133 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001134{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001135 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001136 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001137
Nick Piggin28e4d962006-09-25 23:31:23 -07001138 BUG_ON(!PageLocked(page));
1139 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001140
Johannes Weiner30472502021-09-02 14:53:18 -07001141 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001142 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001143 * The non racy check for a busy page.
1144 *
1145 * Must be careful with the order of the tests. When someone has
1146 * a ref to the page, it may be possible that they dirty it then
1147 * drop the reference. So if PageDirty is tested before page_count
1148 * here, then the following race may occur:
1149 *
1150 * get_user_pages(&page);
1151 * [user mapping goes away]
1152 * write_to(page);
1153 * !PageDirty(page) [good]
1154 * SetPageDirty(page);
1155 * put_page(page);
1156 * !page_count(page) [good, discard it]
1157 *
1158 * [oops, our write_to data is lost]
1159 *
1160 * Reversing the order of the tests ensures such a situation cannot
1161 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001162 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001163 *
1164 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001165 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001166 */
William Kucharski906d2782019-10-18 20:20:33 -07001167 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001168 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001169 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001170 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001171 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001172 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001173 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001174 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001175
1176 if (PageSwapCache(page)) {
1177 swp_entry_t swap = { .val = page_private(page) };
Yu Zhao37397872022-09-18 02:00:03 -06001178
1179 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001180 if (reclaimed && !mapping_exiting(mapping))
1181 shadow = workingset_eviction(page, target_memcg);
Yu Zhao37397872022-09-18 02:00:03 -06001182 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001183 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001184 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001185 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001186 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001187 void (*freepage)(struct page *);
1188
1189 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001190 /*
1191 * Remember a shadow entry for reclaimed file cache in
1192 * order to detect refaults, thus thrashing, later on.
1193 *
1194 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001195 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001196 * inode reclaim needs to empty out the radix tree or
1197 * the nodes are lost. Don't plant shadows behind its
1198 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001199 *
1200 * We also don't store shadows for DAX mappings because the
1201 * only page cache pages found in these are zero pages
1202 * covering holes, and because we don't want to mix DAX
1203 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001204 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001205 */
Huang Ying9de4f222020-04-06 20:04:41 -07001206 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001207 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001208 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001209 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001210 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001211
1212 if (freepage != NULL)
1213 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001214 }
1215
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001216 return 1;
1217
1218cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001219 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001220 return 0;
1221}
1222
Linus Torvalds1da177e2005-04-16 15:20:36 -07001223/*
Nick Piggine2867812008-07-25 19:45:30 -07001224 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1225 * someone else has a ref on the page, abort and return 0. If it was
1226 * successfully detached, return 1. Assumes the caller has a single ref on
1227 * this page.
1228 */
1229int remove_mapping(struct address_space *mapping, struct page *page)
1230{
Johannes Weinerb9107182019-11-30 17:55:59 -08001231 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001232 /*
1233 * Unfreezing the refcount with 1 rather than 2 effectively
1234 * drops the pagecache ref for us without requiring another
1235 * atomic operation.
1236 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001237 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001238 return 1;
1239 }
1240 return 0;
1241}
1242
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001243/**
1244 * putback_lru_page - put previously isolated page onto appropriate LRU list
1245 * @page: page to be put back to appropriate lru list
1246 *
1247 * Add previously isolated @page to appropriate LRU list.
1248 * Page may still be unevictable for other reasons.
1249 *
1250 * lru_lock must not be held, interrupts must be enabled.
1251 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001252void putback_lru_page(struct page *page)
1253{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001254 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001255 put_page(page); /* drop ref from isolate */
1256}
1257
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001258enum page_references {
1259 PAGEREF_RECLAIM,
1260 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001261 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001262 PAGEREF_ACTIVATE,
1263};
1264
1265static enum page_references page_check_references(struct page *page,
1266 struct scan_control *sc)
1267{
Johannes Weiner645747462010-03-05 13:42:22 -08001268 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001269 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001270
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001271 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1272 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001273 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001274
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001275 /*
1276 * Mlock lost the isolation race with us. Let try_to_unmap()
1277 * move the page to the unevictable list.
1278 */
1279 if (vm_flags & VM_LOCKED)
1280 return PAGEREF_RECLAIM;
1281
Minchan Kimf74aca72022-05-19 14:08:54 -07001282 /* rmap lock contention: rotate */
1283 if (referenced_ptes == -1)
1284 return PAGEREF_KEEP;
1285
Johannes Weiner645747462010-03-05 13:42:22 -08001286 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001287 /*
1288 * All mapped pages start out with page table
1289 * references from the instantiating fault, so we need
1290 * to look twice if a mapped file page is used more
1291 * than once.
1292 *
1293 * Mark it and spare it for another trip around the
1294 * inactive list. Another page table reference will
1295 * lead to its activation.
1296 *
1297 * Note: the mark is set for activated pages as well
1298 * so that recently deactivated but used pages are
1299 * quickly recovered.
1300 */
1301 SetPageReferenced(page);
1302
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001303 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001304 return PAGEREF_ACTIVATE;
1305
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001306 /*
1307 * Activate file-backed executable pages after first usage.
1308 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001309 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001310 return PAGEREF_ACTIVATE;
1311
Johannes Weiner645747462010-03-05 13:42:22 -08001312 return PAGEREF_KEEP;
1313 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001314
1315 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001316 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001317 return PAGEREF_RECLAIM_CLEAN;
1318
1319 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001320}
1321
Mel Gormane2be15f2013-07-03 15:01:57 -07001322/* Check if a page is dirty or under writeback */
1323static void page_check_dirty_writeback(struct page *page,
1324 bool *dirty, bool *writeback)
1325{
Mel Gormanb4597222013-07-03 15:02:05 -07001326 struct address_space *mapping;
1327
Mel Gormane2be15f2013-07-03 15:01:57 -07001328 /*
1329 * Anonymous pages are not handled by flushers and must be written
1330 * from reclaim context. Do not stall reclaim based on them
1331 */
Huang Ying9de4f222020-04-06 20:04:41 -07001332 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001333 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001334 *dirty = false;
1335 *writeback = false;
1336 return;
1337 }
1338
1339 /* By default assume that the page flags are accurate */
1340 *dirty = PageDirty(page);
1341 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001342
1343 /* Verify dirty/writeback state if the filesystem supports it */
1344 if (!page_has_private(page))
1345 return;
1346
1347 mapping = page_mapping(page);
1348 if (mapping && mapping->a_ops->is_dirty_writeback)
1349 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001350}
1351
Dave Hansen26aa2d12021-09-02 14:59:16 -07001352static struct page *alloc_demote_page(struct page *page, unsigned long node)
1353{
1354 struct migration_target_control mtc = {
1355 /*
1356 * Allocate from 'node', or fail quickly and quietly.
1357 * When this happens, 'page' will likely just be discarded
1358 * instead of migrated.
1359 */
1360 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1361 __GFP_THISNODE | __GFP_NOWARN |
1362 __GFP_NOMEMALLOC | GFP_NOWAIT,
1363 .nid = node
1364 };
1365
1366 return alloc_migration_target(page, (unsigned long)&mtc);
1367}
1368
1369/*
1370 * Take pages on @demote_list and attempt to demote them to
1371 * another node. Pages which are not demoted are left on
1372 * @demote_pages.
1373 */
1374static unsigned int demote_page_list(struct list_head *demote_pages,
1375 struct pglist_data *pgdat)
1376{
1377 int target_nid = next_demotion_node(pgdat->node_id);
1378 unsigned int nr_succeeded;
1379 int err;
1380
1381 if (list_empty(demote_pages))
1382 return 0;
1383
1384 if (target_nid == NUMA_NO_NODE)
1385 return 0;
1386
1387 /* Demotion ignores all cpuset and mempolicy settings */
1388 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1389 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1390 &nr_succeeded);
1391
Yang Shi668e4142021-09-02 14:59:19 -07001392 if (current_is_kswapd())
1393 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1394 else
1395 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1396
Dave Hansen26aa2d12021-09-02 14:59:16 -07001397 return nr_succeeded;
1398}
1399
Nick Piggine2867812008-07-25 19:45:30 -07001400/*
Andrew Morton1742f192006-03-22 00:08:21 -08001401 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001402 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001403static unsigned int shrink_page_list(struct list_head *page_list,
1404 struct pglist_data *pgdat,
1405 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001406 struct reclaim_stat *stat,
1407 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001408{
1409 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001410 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001411 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001412 unsigned int nr_reclaimed = 0;
1413 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001414 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001415
Kirill Tkhai060f0052019-03-05 15:48:15 -08001416 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001417 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001418 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001419
Dave Hansen26aa2d12021-09-02 14:59:16 -07001420retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001421 while (!list_empty(page_list)) {
1422 struct address_space *mapping;
1423 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001424 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001425 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001426 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001427
1428 cond_resched();
1429
1430 page = lru_to_page(page_list);
1431 list_del(&page->lru);
1432
Nick Piggin529ae9a2008-08-02 12:01:03 +02001433 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001434 goto keep;
1435
Sasha Levin309381fea2014-01-23 15:52:54 -08001436 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001437
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001438 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001439
1440 /* Account the number of base pages even though THP */
1441 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001442
Hugh Dickins39b5f292012-10-08 16:33:18 -07001443 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001444 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001445
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001446 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001447 goto keep_locked;
1448
Yu Zhao0182f922022-09-18 02:00:04 -06001449 /* page_update_gen() tried to promote this page? */
1450 if (lru_gen_enabled() && !ignore_references &&
1451 page_mapped(page) && PageReferenced(page))
1452 goto keep_locked;
1453
Andy Whitcroftc661b072007-08-22 14:01:26 -07001454 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1455 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1456
Mel Gorman283aba92013-07-03 15:01:51 -07001457 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001458 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001459 * reclaim_congested which affects wait_iff_congested. kswapd
1460 * will stall and start writing pages if the tail of the LRU
1461 * is all dirty unqueued pages.
1462 */
1463 page_check_dirty_writeback(page, &dirty, &writeback);
1464 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001465 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001466
1467 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001468 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001469
Mel Gormand04e8ac2013-07-03 15:02:03 -07001470 /*
1471 * Treat this page as congested if the underlying BDI is or if
1472 * pages are cycling through the LRU so quickly that the
1473 * pages marked for immediate reclaim are making it to the
1474 * end of the LRU a second time.
1475 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001476 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001477 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001478 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001479 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001480 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001481
1482 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001483 * If a page at the tail of the LRU is under writeback, there
1484 * are three cases to consider.
1485 *
1486 * 1) If reclaim is encountering an excessive number of pages
1487 * under writeback and this page is both under writeback and
1488 * PageReclaim then it indicates that pages are being queued
1489 * for IO but are being recycled through the LRU before the
1490 * IO can complete. Waiting on the page itself risks an
1491 * indefinite stall if it is impossible to writeback the
1492 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001493 * note that the LRU is being scanned too quickly and the
1494 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001495 *
Tejun Heo97c93412015-05-22 18:23:36 -04001496 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001497 * not marked for immediate reclaim, or the caller does not
1498 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1499 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001500 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001501 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001502 * Require may_enter_fs because we would wait on fs, which
1503 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001504 * enter reclaim, and deadlock if it waits on a page for
1505 * which it is needed to do the write (loop masks off
1506 * __GFP_IO|__GFP_FS for this reason); but more thought
1507 * would probably show more reasons.
1508 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001509 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001510 * PageReclaim. memcg does not have any dirty pages
1511 * throttling so we could easily OOM just because too many
1512 * pages are in writeback and there is nothing else to
1513 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001514 *
1515 * In cases 1) and 2) we activate the pages to get them out of
1516 * the way while we continue scanning for clean pages on the
1517 * inactive list and refilling from the active list. The
1518 * observation here is that waiting for disk writes is more
1519 * expensive than potentially causing reloads down the line.
1520 * Since they're marked for immediate reclaim, they won't put
1521 * memory pressure on the cache working set any longer than it
1522 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001523 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001524 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001525 /* Case 1 above */
1526 if (current_is_kswapd() &&
1527 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001528 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001529 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001530 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001531
1532 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001533 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001534 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001535 /*
1536 * This is slightly racy - end_page_writeback()
1537 * might have just cleared PageReclaim, then
1538 * setting PageReclaim here end up interpreted
1539 * as PageReadahead - but that does not matter
1540 * enough to care. What we do want is for this
1541 * page to have PageReclaim set next time memcg
1542 * reclaim reaches the tests above, so it will
1543 * then wait_on_page_writeback() to avoid OOM;
1544 * and it's also appropriate in global reclaim.
1545 */
1546 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001547 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001548 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001549
1550 /* Case 3 above */
1551 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001552 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001553 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001554 /* then go back and try same page again */
1555 list_add_tail(&page->lru, page_list);
1556 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001557 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001558 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001559
Minchan Kim8940b342019-09-25 16:49:11 -07001560 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001561 references = page_check_references(page, sc);
1562
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001563 switch (references) {
1564 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001565 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001566 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001567 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001568 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001569 case PAGEREF_RECLAIM:
1570 case PAGEREF_RECLAIM_CLEAN:
1571 ; /* try to reclaim the page below */
1572 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001573
Linus Torvalds1da177e2005-04-16 15:20:36 -07001574 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001575 * Before reclaiming the page, try to relocate
1576 * its contents to another node.
1577 */
1578 if (do_demote_pass &&
1579 (thp_migration_supported() || !PageTransHuge(page))) {
1580 list_add(&page->lru, &demote_pages);
1581 unlock_page(page);
1582 continue;
1583 }
1584
1585 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001586 * Anonymous process memory has backing store?
1587 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001588 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001589 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001590 if (PageAnon(page) && PageSwapBacked(page)) {
1591 if (!PageSwapCache(page)) {
1592 if (!(sc->gfp_mask & __GFP_IO))
1593 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001594 if (page_maybe_dma_pinned(page))
1595 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001596 if (PageTransHuge(page)) {
1597 /* cannot split THP, skip it */
1598 if (!can_split_huge_page(page, NULL))
1599 goto activate_locked;
1600 /*
1601 * Split pages without a PMD map right
1602 * away. Chances are some or all of the
1603 * tail pages can be freed without IO.
1604 */
1605 if (!compound_mapcount(page) &&
1606 split_huge_page_to_list(page,
1607 page_list))
1608 goto activate_locked;
1609 }
1610 if (!add_to_swap(page)) {
1611 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001612 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001613 /* Fallback to swap normal pages */
1614 if (split_huge_page_to_list(page,
1615 page_list))
1616 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001617#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1618 count_vm_event(THP_SWPOUT_FALLBACK);
1619#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001620 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001621 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001622 }
Minchan Kim0f074652017-07-06 15:37:24 -07001623
Kirill Tkhai4b793062020-04-01 21:10:18 -07001624 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001625
1626 /* Adding to swap updated mapping */
1627 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001628 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001629 } else if (unlikely(PageTransHuge(page))) {
1630 /* Split file THP */
1631 if (split_huge_page_to_list(page, page_list))
1632 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001633 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001634
1635 /*
Yang Shi98879b32019-07-11 20:59:30 -07001636 * THP may get split above, need minus tail pages and update
1637 * nr_pages to avoid accounting tail pages twice.
1638 *
1639 * The tail pages that are added into swap cache successfully
1640 * reach here.
1641 */
1642 if ((nr_pages > 1) && !PageTransHuge(page)) {
1643 sc->nr_scanned -= (nr_pages - 1);
1644 nr_pages = 1;
1645 }
1646
1647 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001648 * The page is mapped into the page tables of one or more
1649 * processes. Try to unmap it here.
1650 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001651 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001652 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001653 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001654
1655 if (unlikely(PageTransHuge(page)))
1656 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001657
Yang Shi1fb08ac2021-06-30 18:52:01 -07001658 try_to_unmap(page, flags);
1659 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001660 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001661 if (!was_swapbacked && PageSwapBacked(page))
1662 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001663 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001664 }
1665 }
1666
1667 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001668 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001669 * Only kswapd can writeback filesystem pages
1670 * to avoid risk of stack overflow. But avoid
1671 * injecting inefficient single-page IO into
1672 * flusher writeback as much as possible: only
1673 * write pages when we've encountered many
1674 * dirty pages, and when we've already scanned
1675 * the rest of the LRU for clean pages and see
1676 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001677 */
Huang Ying9de4f222020-04-06 20:04:41 -07001678 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001679 (!current_is_kswapd() || !PageReclaim(page) ||
1680 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001681 /*
1682 * Immediately reclaim when written back.
1683 * Similar in principal to deactivate_page()
1684 * except we already have the page isolated
1685 * and know it's dirty
1686 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001687 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001688 SetPageReclaim(page);
1689
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001690 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001691 }
1692
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001693 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001694 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001695 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001696 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001697 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001698 goto keep_locked;
1699
Mel Gormand950c942015-09-04 15:47:35 -07001700 /*
1701 * Page is dirty. Flush the TLB if a writable entry
1702 * potentially exists to avoid CPU writes after IO
1703 * starts and then write it out here.
1704 */
1705 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001706 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001707 case PAGE_KEEP:
1708 goto keep_locked;
1709 case PAGE_ACTIVATE:
1710 goto activate_locked;
1711 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001712 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001713
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001714 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001715 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001716 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001717 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001718
Linus Torvalds1da177e2005-04-16 15:20:36 -07001719 /*
1720 * A synchronous write - probably a ramdisk. Go
1721 * ahead and try to reclaim the page.
1722 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001723 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001724 goto keep;
1725 if (PageDirty(page) || PageWriteback(page))
1726 goto keep_locked;
1727 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001728 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001729 case PAGE_CLEAN:
1730 ; /* try to free the page below */
1731 }
1732 }
1733
1734 /*
1735 * If the page has buffers, try to free the buffer mappings
1736 * associated with this page. If we succeed we try to free
1737 * the page as well.
1738 *
1739 * We do this even if the page is PageDirty().
1740 * try_to_release_page() does not perform I/O, but it is
1741 * possible for a page to have PageDirty set, but it is actually
1742 * clean (all its buffers are clean). This happens if the
1743 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001744 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001745 * try_to_release_page() will discover that cleanness and will
1746 * drop the buffers and mark the page clean - it can be freed.
1747 *
1748 * Rarely, pages can have buffers and no ->mapping. These are
1749 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001750 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001751 * and if that worked, and the page is no longer mapped into
1752 * process address space (page_count == 1) it can be freed.
1753 * Otherwise, leave the page on the LRU so it is swappable.
1754 */
David Howells266cf652009-04-03 16:42:36 +01001755 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001756 if (!try_to_release_page(page, sc->gfp_mask))
1757 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001758 if (!mapping && page_count(page) == 1) {
1759 unlock_page(page);
1760 if (put_page_testzero(page))
1761 goto free_it;
1762 else {
1763 /*
1764 * rare race with speculative reference.
1765 * the speculative reference will free
1766 * this page shortly, so we may
1767 * increment nr_reclaimed here (and
1768 * leave it off the LRU).
1769 */
1770 nr_reclaimed++;
1771 continue;
1772 }
1773 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001774 }
1775
Shaohua Li802a3a92017-05-03 14:52:32 -07001776 if (PageAnon(page) && !PageSwapBacked(page)) {
1777 /* follow __remove_mapping for reference */
1778 if (!page_ref_freeze(page, 1))
1779 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001780 /*
1781 * The page has only one reference left, which is
1782 * from the isolation. After the caller puts the
1783 * page back on lru and drops the reference, the
1784 * page will be freed anyway. It doesn't matter
1785 * which lru it goes. So we don't bother checking
1786 * PageDirty here.
1787 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001788 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001789 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001790 } else if (!mapping || !__remove_mapping(mapping, page, true,
1791 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001792 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001793
1794 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001795free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001796 /*
1797 * THP may get swapped out in a whole, need account
1798 * all base pages.
1799 */
1800 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001801
1802 /*
1803 * Is there need to periodically free_page_list? It would
1804 * appear not as the counts should be low
1805 */
Yang Shi7ae88532019-09-23 15:38:09 -07001806 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001807 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001808 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001809 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001810 continue;
1811
Yang Shi98879b32019-07-11 20:59:30 -07001812activate_locked_split:
1813 /*
1814 * The tail pages that are failed to add into swap cache
1815 * reach here. Fixup nr_scanned and nr_pages.
1816 */
1817 if (nr_pages > 1) {
1818 sc->nr_scanned -= (nr_pages - 1);
1819 nr_pages = 1;
1820 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001821activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001822 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001823 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1824 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001825 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001826 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001827 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001828 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001829 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001830 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001831 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001832 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001833keep_locked:
1834 unlock_page(page);
1835keep:
1836 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001837 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001838 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001839 /* 'page_list' is always empty here */
1840
1841 /* Migrate pages selected for demotion */
1842 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1843 /* Pages that could not be demoted are still in @demote_pages */
1844 if (!list_empty(&demote_pages)) {
1845 /* Pages which failed to demoted go back on @page_list for retry: */
1846 list_splice_init(&demote_pages, page_list);
1847 do_demote_pass = false;
1848 goto retry;
1849 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001850
Yang Shi98879b32019-07-11 20:59:30 -07001851 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1852
Johannes Weiner747db952014-08-08 14:19:24 -07001853 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001854 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001855 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001856
Linus Torvalds1da177e2005-04-16 15:20:36 -07001857 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001858 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001859
Andrew Morton05ff5132006-03-22 00:08:20 -08001860 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001861}
1862
Maninder Singh730ec8c2020-06-03 16:01:18 -07001863unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001864 struct list_head *page_list)
1865{
1866 struct scan_control sc = {
1867 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001868 .may_unmap = 1,
1869 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001870 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001871 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001872 struct page *page, *next;
1873 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001874 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001875
1876 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001877 if (!PageHuge(page) && page_is_file_lru(page) &&
1878 !PageDirty(page) && !__PageMovable(page) &&
1879 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001880 ClearPageActive(page);
1881 list_move(&page->lru, &clean_pages);
1882 }
1883 }
1884
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001885 /*
1886 * We should be safe here since we are only dealing with file pages and
1887 * we are not kswapd and therefore cannot write dirty file pages. But
1888 * call memalloc_noreclaim_save() anyway, just in case these conditions
1889 * change in the future.
1890 */
1891 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001892 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001893 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001894 memalloc_noreclaim_restore(noreclaim_flag);
1895
Minchan Kim02c6de82012-10-08 16:31:55 -07001896 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001897 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1898 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001899 /*
1900 * Since lazyfree pages are isolated from file LRU from the beginning,
1901 * they will rotate back to anonymous LRU in the end if it failed to
1902 * discard so isolated count will be mismatched.
1903 * Compensate the isolated count for both LRU lists.
1904 */
1905 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1906 stat.nr_lazyfree_fail);
1907 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001908 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001909 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001910}
1911
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001912/*
Mel Gorman7ee36a12016-07-28 15:47:17 -07001913 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001914 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001915 */
1916static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001917 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001918{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001919 int zid;
1920
Mel Gorman7ee36a12016-07-28 15:47:17 -07001921 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1922 if (!nr_zone_taken[zid])
1923 continue;
1924
Wei Yanga892cb62020-06-03 16:01:12 -07001925 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001926 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001927
Mel Gorman7ee36a12016-07-28 15:47:17 -07001928}
1929
Mel Gormanf611fab2021-06-30 18:53:19 -07001930/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001931 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1932 *
1933 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001934 * shrink the lists perform better by taking out a batch of pages
1935 * and working on them outside the LRU lock.
1936 *
1937 * For pagecache intensive workloads, this function is the hottest
1938 * spot in the kernel (apart from copy_*_user functions).
1939 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001940 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001941 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001942 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001943 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001944 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001945 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001946 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001947 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001948 *
1949 * returns how many pages were moved onto *@dst.
1950 */
Andrew Morton69e05942006-03-22 00:08:19 -08001951static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001952 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001953 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001954 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001955{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001956 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001957 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001958 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001959 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07001960 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001961 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07001962 LIST_HEAD(pages_skipped);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001963
Yang Shi98879b32019-07-11 20:59:30 -07001964 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001965 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07001966 while (scan < nr_to_scan && !list_empty(src)) {
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001967 struct list_head *move_to = src;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001968 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001969
Linus Torvalds1da177e2005-04-16 15:20:36 -07001970 page = lru_to_page(src);
1971 prefetchw_prev_lru_page(page, src, flags);
1972
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001973 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001974 total_scan += nr_pages;
1975
Mel Gormanb2e18752016-07-28 15:45:37 -07001976 if (page_zonenum(page) > sc->reclaim_idx) {
Yang Shi98879b32019-07-11 20:59:30 -07001977 nr_skipped[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001978 move_to = &pages_skipped;
1979 goto move;
Mel Gormanb2e18752016-07-28 15:45:37 -07001980 }
1981
Minchan Kim791b48b2017-05-12 15:47:06 -07001982 /*
1983 * Do not count skipped pages because that makes the function
1984 * return with no isolated pages if the LRU mostly contains
1985 * ineligible pages. This causes the VM to not reclaim any
1986 * pages, triggering a premature OOM.
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001987 * Account all tail pages of THP.
Minchan Kim791b48b2017-05-12 15:47:06 -07001988 */
Yang Shi98879b32019-07-11 20:59:30 -07001989 scan += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001990
1991 if (!PageLRU(page))
1992 goto move;
1993 if (!sc->may_unmap && page_mapped(page))
1994 goto move;
1995
Alex Shic2135f72021-02-24 12:08:01 -08001996 /*
1997 * Be careful not to clear PageLRU until after we're
1998 * sure the page is not being freed elsewhere -- the
1999 * page release code relies on it.
2000 */
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002001 if (unlikely(!get_page_unless_zero(page)))
2002 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002003
2004 if (!TestClearPageLRU(page)) {
2005 /* Another thread is already isolating this page */
2006 put_page(page);
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002007 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002008 }
2009
2010 nr_taken += nr_pages;
2011 nr_zone_taken[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002012 move_to = dst;
2013move:
2014 list_move(&page->lru, move_to);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002015 }
2016
Mel Gormanb2e18752016-07-28 15:45:37 -07002017 /*
2018 * Splice any skipped pages to the start of the LRU list. Note that
2019 * this disrupts the LRU order when reclaiming for lower zones but
2020 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2021 * scanning would soon rescan the same pages to skip and put the
2022 * system at risk of premature OOM.
2023 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002024 if (!list_empty(&pages_skipped)) {
2025 int zid;
2026
Johannes Weiner3db65812017-05-03 14:52:13 -07002027 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002028 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2029 if (!nr_skipped[zid])
2030 continue;
2031
2032 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002033 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002034 }
2035 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002036 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002037 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002038 total_scan, skipped, nr_taken,
2039 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002040 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002041 return nr_taken;
2042}
2043
Nick Piggin62695a82008-10-18 20:26:09 -07002044/**
2045 * isolate_lru_page - tries to isolate a page from its LRU list
2046 * @page: page to isolate from its LRU list
2047 *
2048 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2049 * vmstat statistic corresponding to whatever LRU list the page was on.
2050 *
2051 * Returns 0 if the page was removed from an LRU list.
2052 * Returns -EBUSY if the page was not on an LRU list.
2053 *
2054 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002055 * the active list, it will have PageActive set. If it was found on
2056 * the unevictable list, it will have the PageUnevictable bit set. That flag
2057 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002058 *
2059 * The vmstat statistic corresponding to the list on which the page was
2060 * found will be decremented.
2061 *
2062 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002063 *
Nick Piggin62695a82008-10-18 20:26:09 -07002064 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002065 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002066 * without a stable reference).
2067 * (2) the lru_lock must not be held.
2068 * (3) interrupts must be enabled.
2069 */
2070int isolate_lru_page(struct page *page)
2071{
2072 int ret = -EBUSY;
2073
Sasha Levin309381fea2014-01-23 15:52:54 -08002074 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002075 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002076
Alex Shid25b5bd2020-12-15 12:34:16 -08002077 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002078 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002079
Alex Shid25b5bd2020-12-15 12:34:16 -08002080 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002081 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002082 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002083 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002084 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002085 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002086
Nick Piggin62695a82008-10-18 20:26:09 -07002087 return ret;
2088}
2089
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002090/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002091 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002092 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002093 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2094 * the LRU list will go small and be scanned faster than necessary, leading to
2095 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002096 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002097static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002098 struct scan_control *sc)
2099{
2100 unsigned long inactive, isolated;
2101
2102 if (current_is_kswapd())
2103 return 0;
2104
Johannes Weinerb5ead352019-11-30 17:55:40 -08002105 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002106 return 0;
2107
2108 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002109 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2110 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002111 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002112 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2113 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002114 }
2115
Fengguang Wu3cf23842012-12-18 14:23:31 -08002116 /*
2117 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2118 * won't get blocked by normal direct-reclaimers, forming a circular
2119 * deadlock.
2120 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002121 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002122 inactive >>= 3;
2123
Rik van Riel35cd7812009-09-21 17:01:38 -07002124 return isolated > inactive;
2125}
2126
Kirill Tkhaia222f342019-05-13 17:17:00 -07002127/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002128 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2129 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002130 *
2131 * Returns the number of pages moved to the given lruvec.
2132 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002133static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2134 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002135{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002136 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002137 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002138 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002139
Kirill Tkhaia222f342019-05-13 17:17:00 -07002140 while (!list_empty(list)) {
2141 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002142 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002143 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002144 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002145 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002146 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002147 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002148 continue;
2149 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002150
Alex Shi3d06afa2020-12-15 12:33:37 -08002151 /*
2152 * The SetPageLRU needs to be kept here for list integrity.
2153 * Otherwise:
2154 * #0 move_pages_to_lru #1 release_pages
2155 * if !put_page_testzero
2156 * if (put_page_testzero())
2157 * !PageLRU //skip lru_lock
2158 * SetPageLRU()
2159 * list_add(&page->lru,)
2160 * list_add(&page->lru,)
2161 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002162 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002163
Alex Shi3d06afa2020-12-15 12:33:37 -08002164 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002165 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002166
2167 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002168 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002169 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002170 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002171 } else
2172 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002173
2174 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002175 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002176
Alex Shiafca9152020-12-15 12:34:02 -08002177 /*
2178 * All pages were isolated from the same lruvec (and isolation
2179 * inhibits memcg migration).
2180 */
Muchun Song7467c392021-06-28 19:37:59 -07002181 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002182 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002183 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002184 nr_moved += nr_pages;
2185 if (PageActive(page))
2186 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002187 }
Mel Gorman66635622010-08-09 17:19:30 -07002188
Hugh Dickins3f797682012-01-12 17:20:07 -08002189 /*
2190 * To save our caller's stack, now use input list for pages to free.
2191 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002192 list_splice(&pages_to_free, list);
2193
2194 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002195}
2196
2197/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002198 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002199 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002200 * In that case we should only throttle if the backing device it is
2201 * writing to is congested. In other cases it is safe to throttle.
2202 */
2203static int current_may_throttle(void)
2204{
NeilBrowna37b0712020-06-01 21:48:18 -07002205 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002206 current->backing_dev_info == NULL ||
2207 bdi_write_congested(current->backing_dev_info);
2208}
2209
2210/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002211 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002212 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002213 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002214static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002215shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002216 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002217{
2218 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002219 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002220 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002221 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002222 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002223 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002224 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002225 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002226 bool stalled = false;
Minchan Kim7df45e52022-10-27 08:29:17 -07002227 struct blk_plug plug;
2228 bool do_plug = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002229
Mel Gorman599d0c92016-07-28 15:45:31 -07002230 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002231 if (stalled)
2232 return 0;
2233
2234 /* wait a bit for the reclaimer. */
2235 msleep(100);
2236 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002237
2238 /* We are about to die and free our memory. Return now. */
2239 if (fatal_signal_pending(current))
2240 return SWAP_CLUSTER_MAX;
2241 }
2242
Linus Torvalds1da177e2005-04-16 15:20:36 -07002243 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002244
Alex Shi6168d0d2020-12-15 12:34:29 -08002245 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002246
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002247 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002248 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002249
Mel Gorman599d0c92016-07-28 15:45:31 -07002250 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002251 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002252 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002253 __count_vm_events(item, nr_scanned);
2254 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002255 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2256
Alex Shi6168d0d2020-12-15 12:34:29 -08002257 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002258
Hillf Dantond563c052012-03-21 16:34:02 -07002259 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002260 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002261
Minchan Kim7df45e52022-10-27 08:29:17 -07002262 trace_android_vh_shrink_inactive_list_blk_plug(&do_plug);
2263 if (do_plug)
2264 blk_start_plug(&plug);
Shakeel Butt013339d2020-12-14 19:06:39 -08002265 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002266
Alex Shi6168d0d2020-12-15 12:34:29 -08002267 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002268 move_pages_to_lru(lruvec, &page_list);
2269
2270 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002271 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002272 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002273 __count_vm_events(item, nr_reclaimed);
2274 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002275 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002276 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002277
Minchan Kim7df45e52022-10-27 08:29:17 -07002278 if (do_plug)
2279 blk_finish_plug(&plug);
2280
Alex Shi75cc3c92020-12-15 14:20:50 -08002281 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002282 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002283 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002284
Mel Gorman92df3a72011-10-31 17:07:56 -07002285 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002286 * If dirty pages are scanned that are not queued for IO, it
2287 * implies that flushers are not doing their job. This can
2288 * happen when memory pressure pushes dirty pages to the end of
2289 * the LRU before the dirty limits are breached and the dirty
2290 * data has expired. It can also happen when the proportion of
2291 * dirty pages grows not through writes but through memory
2292 * pressure reclaiming all the clean cache. And in some cases,
2293 * the flushers simply cannot keep up with the allocation
2294 * rate. Nudge the flusher threads in case they are asleep.
2295 */
2296 if (stat.nr_unqueued_dirty == nr_taken)
2297 wakeup_flusher_threads(WB_REASON_VMSCAN);
2298
Andrey Ryabinind108c772018-04-10 16:27:59 -07002299 sc->nr.dirty += stat.nr_dirty;
2300 sc->nr.congested += stat.nr_congested;
2301 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2302 sc->nr.writeback += stat.nr_writeback;
2303 sc->nr.immediate += stat.nr_immediate;
2304 sc->nr.taken += nr_taken;
2305 if (file)
2306 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002307
Mel Gorman599d0c92016-07-28 15:45:31 -07002308 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002309 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002310 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002311}
2312
Hugh Dickins15b44732020-12-15 14:21:31 -08002313/*
2314 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2315 *
2316 * We move them the other way if the page is referenced by one or more
2317 * processes.
2318 *
2319 * If the pages are mostly unmapped, the processing is fast and it is
2320 * appropriate to hold lru_lock across the whole operation. But if
2321 * the pages are mapped, the processing is slow (page_referenced()), so
2322 * we should drop lru_lock around each page. It's impossible to balance
2323 * this, so instead we remove the pages from the LRU while processing them.
2324 * It is safe to rely on PG_active against the non-LRU pages in here because
2325 * nobody will play with that bit on a non-LRU page.
2326 *
2327 * The downside is that we have to touch page->_refcount against each page.
2328 * But we had to alter page->flags anyway.
2329 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002330static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002331 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002332 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002333 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002334{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002335 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002336 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002337 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002338 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002339 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002340 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002341 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002342 unsigned nr_deactivate, nr_activate;
2343 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002344 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002345 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002346 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002347
2348 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002349
Alex Shi6168d0d2020-12-15 12:34:29 -08002350 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002351
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002352 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002353 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002354
Mel Gorman599d0c92016-07-28 15:45:31 -07002355 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002356
Shakeel Butt912c0572020-08-06 23:26:32 -07002357 if (!cgroup_reclaim(sc))
2358 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002359 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002360
Alex Shi6168d0d2020-12-15 12:34:29 -08002361 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002362
Linus Torvalds1da177e2005-04-16 15:20:36 -07002363 while (!list_empty(&l_hold)) {
2364 cond_resched();
2365 page = lru_to_page(&l_hold);
2366 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002367
Hugh Dickins39b5f292012-10-08 16:33:18 -07002368 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002369 putback_lru_page(page);
2370 continue;
2371 }
2372
Mel Gormancc715d92012-03-21 16:34:00 -07002373 if (unlikely(buffer_heads_over_limit)) {
2374 if (page_has_private(page) && trylock_page(page)) {
2375 if (page_has_private(page))
2376 try_to_release_page(page, 0);
2377 unlock_page(page);
2378 }
2379 }
2380
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002381 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2382 if (bypass)
2383 goto skip_page_referenced;
2384
Minchan Kimf74aca72022-05-19 14:08:54 -07002385 /* Referenced or rmap lock contention: rotate */
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002386 if (page_referenced(page, 0, sc->target_mem_cgroup,
Minchan Kimf74aca72022-05-19 14:08:54 -07002387 &vm_flags) != 0) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002388 /*
2389 * Identify referenced, file-backed active pages and
2390 * give them one more trip around the active list. So
2391 * that executable code get better chances to stay in
2392 * memory under moderate memory pressure. Anon pages
2393 * are not likely to be evicted by use-once streaming
2394 * IO, plus JVM can create lots of anon VM_EXEC pages,
2395 * so we ignore them here.
2396 */
Huang Ying9de4f222020-04-06 20:04:41 -07002397 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002398 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002399 list_add(&page->lru, &l_active);
2400 continue;
2401 }
2402 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002403skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002404 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002405 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002406 list_add(&page->lru, &l_inactive);
2407 }
2408
Andrew Mortonb5557492009-01-06 14:40:13 -08002409 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002410 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002411 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002412 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002413
Kirill Tkhaia222f342019-05-13 17:17:00 -07002414 nr_activate = move_pages_to_lru(lruvec, &l_active);
2415 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002416 /* Keep all free pages in l_active list */
2417 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002418
2419 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2420 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2421
Mel Gorman599d0c92016-07-28 15:45:31 -07002422 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002423 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002424
Kirill Tkhaif372d892019-05-13 17:16:57 -07002425 mem_cgroup_uncharge_list(&l_active);
2426 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002427 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2428 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002429}
2430
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002431unsigned long reclaim_pages(struct list_head *page_list)
2432{
Yang Shif661d002020-04-01 21:10:05 -07002433 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002434 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002435 LIST_HEAD(node_page_list);
2436 struct reclaim_stat dummy_stat;
2437 struct page *page;
Minchan Kim7df45e52022-10-27 08:29:17 -07002438 struct blk_plug plug;
2439 bool do_plug = false;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002440 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002441 struct scan_control sc = {
2442 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002443 .may_writepage = 1,
2444 .may_unmap = 1,
2445 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002446 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002447 };
2448
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002449 noreclaim_flag = memalloc_noreclaim_save();
2450
Minchan Kim7df45e52022-10-27 08:29:17 -07002451 trace_android_vh_reclaim_pages_plug(&do_plug);
2452 if (do_plug)
2453 blk_start_plug(&plug);
2454
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002455 while (!list_empty(page_list)) {
2456 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002457 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002458 nid = page_to_nid(page);
2459 INIT_LIST_HEAD(&node_page_list);
2460 }
2461
2462 if (nid == page_to_nid(page)) {
2463 ClearPageActive(page);
2464 list_move(&page->lru, &node_page_list);
2465 continue;
2466 }
2467
2468 nr_reclaimed += shrink_page_list(&node_page_list,
2469 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002470 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002471 while (!list_empty(&node_page_list)) {
2472 page = lru_to_page(&node_page_list);
2473 list_del(&page->lru);
2474 putback_lru_page(page);
2475 }
2476
Yang Shif661d002020-04-01 21:10:05 -07002477 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002478 }
2479
2480 if (!list_empty(&node_page_list)) {
2481 nr_reclaimed += shrink_page_list(&node_page_list,
2482 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002483 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002484 while (!list_empty(&node_page_list)) {
2485 page = lru_to_page(&node_page_list);
2486 list_del(&page->lru);
2487 putback_lru_page(page);
2488 }
2489 }
2490
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002491 memalloc_noreclaim_restore(noreclaim_flag);
2492
Minchan Kim7df45e52022-10-27 08:29:17 -07002493 if (do_plug)
2494 blk_finish_plug(&plug);
2495
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002496 return nr_reclaimed;
2497}
2498
Johannes Weinerb91ac372019-11-30 17:56:02 -08002499static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2500 struct lruvec *lruvec, struct scan_control *sc)
2501{
2502 if (is_active_lru(lru)) {
2503 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2504 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2505 else
2506 sc->skipped_deactivate = 1;
2507 return 0;
2508 }
2509
2510 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2511}
2512
Rik van Riel59dc76b2016-05-20 16:56:31 -07002513/*
2514 * The inactive anon list should be small enough that the VM never has
2515 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002516 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002517 * The inactive file list should be small enough to leave most memory
2518 * to the established workingset on the scan-resistant active list,
2519 * but large enough to avoid thrashing the aggregate readahead window.
2520 *
2521 * Both inactive lists should also be large enough that each inactive
2522 * page has a chance to be referenced again before it is reclaimed.
2523 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002524 * If that fails and refaulting is observed, the inactive list grows.
2525 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002526 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002527 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002528 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2529 *
2530 * total target max
2531 * memory ratio inactive
2532 * -------------------------------------
2533 * 10MB 1 5MB
2534 * 100MB 1 50MB
2535 * 1GB 3 250MB
2536 * 10GB 10 0.9GB
2537 * 100GB 31 3GB
2538 * 1TB 101 10GB
2539 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002540 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002541static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002542{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002543 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002544 unsigned long inactive, active;
2545 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002546 unsigned long gb;
2547
Johannes Weinerb91ac372019-11-30 17:56:02 -08002548 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2549 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002550
Johannes Weinerb91ac372019-11-30 17:56:02 -08002551 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002552 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002553 inactive_ratio = int_sqrt(10 * gb);
2554 else
2555 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002556
Rik van Riel59dc76b2016-05-20 16:56:31 -07002557 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002558}
2559
Johannes Weiner9a265112013-02-22 16:32:17 -08002560enum scan_balance {
2561 SCAN_EQUAL,
2562 SCAN_FRACT,
2563 SCAN_ANON,
2564 SCAN_FILE,
2565};
2566
Yu Zhao6d313442022-09-18 02:00:00 -06002567static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2568{
2569 unsigned long file;
2570 struct lruvec *target_lruvec;
2571
Yu Zhao37397872022-09-18 02:00:03 -06002572 if (lru_gen_enabled())
2573 return;
2574
Yu Zhao6d313442022-09-18 02:00:00 -06002575 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2576
2577 /*
2578 * Flush the memory cgroup stats, so that we read accurate per-memcg
2579 * lruvec stats for heuristics.
2580 */
2581 mem_cgroup_flush_stats();
2582
2583 /*
2584 * Determine the scan balance between anon and file LRUs.
2585 */
2586 spin_lock_irq(&target_lruvec->lru_lock);
2587 sc->anon_cost = target_lruvec->anon_cost;
2588 sc->file_cost = target_lruvec->file_cost;
2589 spin_unlock_irq(&target_lruvec->lru_lock);
2590
2591 /*
2592 * Target desirable inactive:active list ratios for the anon
2593 * and file LRU lists.
2594 */
2595 if (!sc->force_deactivate) {
2596 unsigned long refaults;
2597
2598 refaults = lruvec_page_state(target_lruvec,
2599 WORKINGSET_ACTIVATE_ANON);
2600 if (refaults != target_lruvec->refaults[0] ||
2601 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2602 sc->may_deactivate |= DEACTIVATE_ANON;
2603 else
2604 sc->may_deactivate &= ~DEACTIVATE_ANON;
2605
2606 /*
2607 * When refaults are being observed, it means a new
2608 * workingset is being established. Deactivate to get
2609 * rid of any stale active pages quickly.
2610 */
2611 refaults = lruvec_page_state(target_lruvec,
2612 WORKINGSET_ACTIVATE_FILE);
2613 if (refaults != target_lruvec->refaults[1] ||
2614 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2615 sc->may_deactivate |= DEACTIVATE_FILE;
2616 else
2617 sc->may_deactivate &= ~DEACTIVATE_FILE;
2618 } else
2619 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2620
2621 /*
2622 * If we have plenty of inactive file pages that aren't
2623 * thrashing, try to reclaim those first before touching
2624 * anonymous pages.
2625 */
2626 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2627 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2628 sc->cache_trim_mode = 1;
2629 else
2630 sc->cache_trim_mode = 0;
2631
2632 /*
2633 * Prevent the reclaimer from falling into the cache trap: as
2634 * cache pages start out inactive, every cache fault will tip
2635 * the scan balance towards the file LRU. And as the file LRU
2636 * shrinks, so does the window for rotation from references.
2637 * This means we have a runaway feedback loop where a tiny
2638 * thrashing file LRU becomes infinitely more attractive than
2639 * anon pages. Try to detect this based on file LRU size.
2640 */
2641 if (!cgroup_reclaim(sc)) {
2642 unsigned long total_high_wmark = 0;
2643 unsigned long free, anon;
2644 int z;
2645
2646 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2647 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2648 node_page_state(pgdat, NR_INACTIVE_FILE);
2649
2650 for (z = 0; z < MAX_NR_ZONES; z++) {
2651 struct zone *zone = &pgdat->node_zones[z];
2652
2653 if (!managed_zone(zone))
2654 continue;
2655
2656 total_high_wmark += high_wmark_pages(zone);
2657 }
2658
2659 /*
2660 * Consider anon: if that's low too, this isn't a
2661 * runaway file reclaim problem, but rather just
2662 * extreme pressure. Reclaim as per usual then.
2663 */
2664 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2665
2666 sc->file_is_tiny =
2667 file + free <= total_high_wmark &&
2668 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2669 anon >> sc->priority;
2670 }
2671}
2672
Linus Torvalds1da177e2005-04-16 15:20:36 -07002673/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002674 * Determine how aggressively the anon and file LRU lists should be
2675 * scanned. The relative value of each set of LRU lists is determined
2676 * by looking at the fraction of the pages scanned we did rotate back
2677 * onto the active list instead of evict.
2678 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002679 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2680 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002681 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002682static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2683 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002684{
Keith Buscha2a36482021-09-02 14:59:26 -07002685 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002686 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002687 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002688 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002689 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002690 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002691 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002692 unsigned long ap, fp;
2693 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002694 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002695
2696 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002697 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002698 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002699 goto out;
2700 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002701
Johannes Weiner10316b32013-02-22 16:32:14 -08002702 /*
2703 * Global reclaim will swap to prevent OOM even with no
2704 * swappiness, but memcg users want to use this knob to
2705 * disable swapping for individual groups completely when
2706 * using the memory controller's swap limit feature would be
2707 * too expensive.
2708 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002709 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002710 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002711 goto out;
2712 }
2713
2714 /*
2715 * Do not apply any pressure balancing cleverness when the
2716 * system is close to OOM, scan both anon and file equally
2717 * (unless the swappiness setting disagrees with swapping).
2718 */
Johannes Weiner02695172014-08-06 16:06:17 -07002719 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002720 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002721 goto out;
2722 }
2723
Johannes Weiner11d16c22013-02-22 16:32:15 -08002724 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002725 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002726 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002727 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002728 scan_balance = SCAN_ANON;
2729 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002730 }
2731
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002732 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2733
Johannes Weiner62376252014-05-06 12:50:07 -07002734 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002735 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002736 * anything from the anonymous working right now. But when balancing
2737 * anon and page cache files for reclaim, allow swapping of anon pages
2738 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002739 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002740 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002741 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002742 goto out;
2743 }
2744
Johannes Weiner9a265112013-02-22 16:32:17 -08002745 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002746 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002747 * Calculate the pressure balance between anon and file pages.
2748 *
2749 * The amount of pressure we put on each LRU is inversely
2750 * proportional to the cost of reclaiming each list, as
2751 * determined by the share of pages that are refaulting, times
2752 * the relative IO cost of bringing back a swapped out
2753 * anonymous page vs reloading a filesystem page (swappiness).
2754 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002755 * Although we limit that influence to ensure no list gets
2756 * left behind completely: at least a third of the pressure is
2757 * applied, before swappiness.
2758 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002759 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002760 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002761 total_cost = sc->anon_cost + sc->file_cost;
2762 anon_cost = total_cost + sc->anon_cost;
2763 file_cost = total_cost + sc->file_cost;
2764 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002765
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002766 ap = swappiness * (total_cost + 1);
2767 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002768
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002769 fp = (200 - swappiness) * (total_cost + 1);
2770 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002771
Shaohua Li76a33fc2010-05-24 14:32:36 -07002772 fraction[0] = ap;
2773 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002774 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002775out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002776 for_each_evictable_lru(lru) {
2777 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002778 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002779 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002780 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002781
Chris Down9783aa92019-10-06 17:58:32 -07002782 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002783 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2784 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002785
Johannes Weinerf56ce412021-08-19 19:04:21 -07002786 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002787 /*
2788 * Scale a cgroup's reclaim pressure by proportioning
2789 * its current usage to its memory.low or memory.min
2790 * setting.
2791 *
2792 * This is important, as otherwise scanning aggression
2793 * becomes extremely binary -- from nothing as we
2794 * approach the memory protection threshold, to totally
2795 * nominal as we exceed it. This results in requiring
2796 * setting extremely liberal protection thresholds. It
2797 * also means we simply get no protection at all if we
2798 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002799 *
2800 * If there is any protection in place, we reduce scan
2801 * pressure by how much of the total memory used is
2802 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002803 *
Chris Down9de7ca42019-10-06 17:58:35 -07002804 * There is one special case: in the first reclaim pass,
2805 * we skip over all groups that are within their low
2806 * protection. If that fails to reclaim enough pages to
2807 * satisfy the reclaim goal, we come back and override
2808 * the best-effort low protection. However, we still
2809 * ideally want to honor how well-behaved groups are in
2810 * that case instead of simply punishing them all
2811 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002812 * memory they are using, reducing the scan pressure
2813 * again by how much of the total memory used is under
2814 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002815 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002816 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002817 unsigned long protection;
2818
2819 /* memory.low scaling, make sure we retry before OOM */
2820 if (!sc->memcg_low_reclaim && low > min) {
2821 protection = low;
2822 sc->memcg_low_skipped = 1;
2823 } else {
2824 protection = min;
2825 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002826
2827 /* Avoid TOCTOU with earlier protection check */
2828 cgroup_size = max(cgroup_size, protection);
2829
2830 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002831 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002832
2833 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002834 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002835 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002836 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002837 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002838 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002839 } else {
2840 scan = lruvec_size;
2841 }
2842
2843 scan >>= sc->priority;
2844
Johannes Weiner688035f2017-05-03 14:52:07 -07002845 /*
2846 * If the cgroup's already been deleted, make sure to
2847 * scrape out the remaining cache.
2848 */
2849 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002850 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002851
Johannes Weiner688035f2017-05-03 14:52:07 -07002852 switch (scan_balance) {
2853 case SCAN_EQUAL:
2854 /* Scan lists relative to size */
2855 break;
2856 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002857 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002858 * Scan types proportional to swappiness and
2859 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002860 * Make sure we don't miss the last page on
2861 * the offlined memory cgroups because of a
2862 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002863 */
Gavin Shan76073c62020-02-20 20:04:24 -08002864 scan = mem_cgroup_online(memcg) ?
2865 div64_u64(scan * fraction[file], denominator) :
2866 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002867 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002868 break;
2869 case SCAN_FILE:
2870 case SCAN_ANON:
2871 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002872 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002873 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002874 break;
2875 default:
2876 /* Look ma, no brain */
2877 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002878 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002879
Johannes Weiner688035f2017-05-03 14:52:07 -07002880 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002881 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002882}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002883
Dave Hansen2f368a92021-09-02 14:59:23 -07002884/*
2885 * Anonymous LRU management is a waste if there is
2886 * ultimately no way to reclaim the memory.
2887 */
2888static bool can_age_anon_pages(struct pglist_data *pgdat,
2889 struct scan_control *sc)
2890{
2891 /* Aging the anon LRU is valuable if swap is present: */
2892 if (total_swap_pages > 0)
2893 return true;
2894
2895 /* Also valuable if anon pages can be demoted: */
2896 return can_demote(pgdat->node_id, sc);
2897}
2898
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002899#ifdef CONFIG_LRU_GEN
2900
Yu Zhaobaeb9a02022-09-18 02:00:07 -06002901#ifdef CONFIG_LRU_GEN_ENABLED
2902DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2903#define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2904#else
2905DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2906#define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2907#endif
2908
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002909/******************************************************************************
2910 * shorthand helpers
2911 ******************************************************************************/
2912
Yu Zhao37397872022-09-18 02:00:03 -06002913#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2914
2915#define DEFINE_MAX_SEQ(lruvec) \
2916 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2917
2918#define DEFINE_MIN_SEQ(lruvec) \
2919 unsigned long min_seq[ANON_AND_FILE] = { \
2920 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2921 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2922 }
2923
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002924#define for_each_gen_type_zone(gen, type, zone) \
2925 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2926 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2927 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2928
Yu Zhaoa3eb6512022-12-21 21:19:04 -07002929#define get_memcg_gen(seq) ((seq) % MEMCG_NR_GENS)
2930#define get_memcg_bin(bin) ((bin) % MEMCG_NR_BINS)
2931
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002932static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002933{
2934 struct pglist_data *pgdat = NODE_DATA(nid);
2935
2936#ifdef CONFIG_MEMCG
2937 if (memcg) {
2938 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2939
2940 /* for hotadd_new_pgdat() */
2941 if (!lruvec->pgdat)
2942 lruvec->pgdat = pgdat;
2943
2944 return lruvec;
2945 }
2946#endif
2947 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2948
2949 return pgdat ? &pgdat->__lruvec : NULL;
2950}
2951
Yu Zhao37397872022-09-18 02:00:03 -06002952static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2953{
2954 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2955 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2956
Yu Zhaof8b57162022-12-21 21:19:05 -07002957 if (!sc->may_swap)
2958 return 0;
2959
Kalesh Singhb8d031e2023-04-03 15:28:17 -07002960 if (!can_demote(pgdat->node_id, sc) &&
2961 mem_cgroup_get_nr_swap_pages(memcg) <= 0)
Yu Zhao37397872022-09-18 02:00:03 -06002962 return 0;
2963
2964 return mem_cgroup_swappiness(memcg);
2965}
2966
2967static int get_nr_gens(struct lruvec *lruvec, int type)
2968{
2969 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2970}
2971
2972static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2973{
Yu Zhao3c6c3592022-12-21 21:18:59 -07002974 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06002975 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2976 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2977 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2978}
2979
2980/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002981 * mm_struct list
2982 ******************************************************************************/
2983
2984static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
2985{
2986 static struct lru_gen_mm_list mm_list = {
2987 .fifo = LIST_HEAD_INIT(mm_list.fifo),
2988 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
2989 };
2990
2991#ifdef CONFIG_MEMCG
2992 if (memcg)
2993 return &memcg->mm_list;
2994#endif
2995 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2996
2997 return &mm_list;
2998}
2999
3000void lru_gen_add_mm(struct mm_struct *mm)
3001{
3002 int nid;
3003 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3004 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3005
3006 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3007#ifdef CONFIG_MEMCG
3008 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3009 mm->lru_gen.memcg = memcg;
3010#endif
3011 spin_lock(&mm_list->lock);
3012
3013 for_each_node_state(nid, N_MEMORY) {
3014 struct lruvec *lruvec = get_lruvec(memcg, nid);
3015
3016 if (!lruvec)
3017 continue;
3018
3019 /* the first addition since the last iteration */
3020 if (lruvec->mm_state.tail == &mm_list->fifo)
3021 lruvec->mm_state.tail = &mm->lru_gen.list;
3022 }
3023
3024 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3025
3026 spin_unlock(&mm_list->lock);
3027}
3028
3029void lru_gen_del_mm(struct mm_struct *mm)
3030{
3031 int nid;
3032 struct lru_gen_mm_list *mm_list;
3033 struct mem_cgroup *memcg = NULL;
3034
3035 if (list_empty(&mm->lru_gen.list))
3036 return;
3037
3038#ifdef CONFIG_MEMCG
3039 memcg = mm->lru_gen.memcg;
3040#endif
3041 mm_list = get_mm_list(memcg);
3042
3043 spin_lock(&mm_list->lock);
3044
3045 for_each_node(nid) {
3046 struct lruvec *lruvec = get_lruvec(memcg, nid);
3047
3048 if (!lruvec)
3049 continue;
3050
3051 /* where the last iteration ended (exclusive) */
3052 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3053 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3054
3055 /* where the current iteration continues (inclusive) */
3056 if (lruvec->mm_state.head != &mm->lru_gen.list)
3057 continue;
3058
3059 lruvec->mm_state.head = lruvec->mm_state.head->next;
3060 /* the deletion ends the current iteration */
3061 if (lruvec->mm_state.head == &mm_list->fifo)
3062 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3063 }
3064
3065 list_del_init(&mm->lru_gen.list);
3066
3067 spin_unlock(&mm_list->lock);
3068
3069#ifdef CONFIG_MEMCG
3070 mem_cgroup_put(mm->lru_gen.memcg);
3071 mm->lru_gen.memcg = NULL;
3072#endif
3073}
3074
3075#ifdef CONFIG_MEMCG
3076void lru_gen_migrate_mm(struct mm_struct *mm)
3077{
3078 struct mem_cgroup *memcg;
3079 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3080
3081 VM_WARN_ON_ONCE(task->mm != mm);
3082 lockdep_assert_held(&task->alloc_lock);
3083
3084 /* for mm_update_next_owner() */
3085 if (mem_cgroup_disabled())
3086 return;
3087
Yu Zhao578a3a32023-01-15 20:44:05 -07003088 /* migration can happen before addition */
3089 if (!mm->lru_gen.memcg)
3090 return;
3091
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003092 rcu_read_lock();
3093 memcg = mem_cgroup_from_task(task);
3094 rcu_read_unlock();
3095 if (memcg == mm->lru_gen.memcg)
3096 return;
3097
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003098 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3099
3100 lru_gen_del_mm(mm);
3101 lru_gen_add_mm(mm);
3102}
3103#endif
3104
3105/*
3106 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3107 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3108 * bits in a bitmap, k is the number of hash functions and n is the number of
3109 * inserted items.
3110 *
3111 * Page table walkers use one of the two filters to reduce their search space.
3112 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3113 * aging uses the double-buffering technique to flip to the other filter each
3114 * time it produces a new generation. For non-leaf entries that have enough
3115 * leaf entries, the aging carries them over to the next generation in
3116 * walk_pmd_range(); the eviction also report them when walking the rmap
3117 * in lru_gen_look_around().
3118 *
3119 * For future optimizations:
3120 * 1. It's not necessary to keep both filters all the time. The spare one can be
3121 * freed after the RCU grace period and reallocated if needed again.
3122 * 2. And when reallocating, it's worth scaling its size according to the number
3123 * of inserted entries in the other filter, to reduce the memory overhead on
3124 * small systems and false positives on large systems.
3125 * 3. Jenkins' hash function is an alternative to Knuth's.
3126 */
3127#define BLOOM_FILTER_SHIFT 15
3128
3129static inline int filter_gen_from_seq(unsigned long seq)
3130{
3131 return seq % NR_BLOOM_FILTERS;
3132}
3133
3134static void get_item_key(void *item, int *key)
3135{
3136 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3137
3138 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3139
3140 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3141 key[1] = hash >> BLOOM_FILTER_SHIFT;
3142}
3143
3144static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3145{
3146 unsigned long *filter;
3147 int gen = filter_gen_from_seq(seq);
3148
3149 filter = lruvec->mm_state.filters[gen];
3150 if (filter) {
3151 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3152 return;
3153 }
3154
3155 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3156 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3157 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3158}
3159
3160static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3161{
3162 int key[2];
3163 unsigned long *filter;
3164 int gen = filter_gen_from_seq(seq);
3165
3166 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3167 if (!filter)
3168 return;
3169
3170 get_item_key(item, key);
3171
3172 if (!test_bit(key[0], filter))
3173 set_bit(key[0], filter);
3174 if (!test_bit(key[1], filter))
3175 set_bit(key[1], filter);
3176}
3177
3178static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3179{
3180 int key[2];
3181 unsigned long *filter;
3182 int gen = filter_gen_from_seq(seq);
3183
3184 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3185 if (!filter)
3186 return true;
3187
3188 get_item_key(item, key);
3189
3190 return test_bit(key[0], filter) && test_bit(key[1], filter);
3191}
3192
3193static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3194{
3195 int i;
3196 int hist;
3197
3198 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3199
3200 if (walk) {
3201 hist = lru_hist_from_seq(walk->max_seq);
3202
3203 for (i = 0; i < NR_MM_STATS; i++) {
3204 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3205 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3206 walk->mm_stats[i] = 0;
3207 }
3208 }
3209
3210 if (NR_HIST_GENS > 1 && last) {
3211 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3212
3213 for (i = 0; i < NR_MM_STATS; i++)
3214 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3215 }
3216}
3217
3218static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3219{
3220 int type;
3221 unsigned long size = 0;
3222 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3223 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3224
3225 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3226 return true;
3227
3228 clear_bit(key, &mm->lru_gen.bitmap);
3229
3230 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3231 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3232 get_mm_counter(mm, MM_ANONPAGES) +
3233 get_mm_counter(mm, MM_SHMEMPAGES);
3234 }
3235
3236 if (size < MIN_LRU_BATCH)
3237 return true;
3238
3239 return !mmget_not_zero(mm);
3240}
3241
3242static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3243 struct mm_struct **iter)
3244{
3245 bool first = false;
3246 bool last = true;
3247 struct mm_struct *mm = NULL;
3248 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3249 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3250 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3251
3252 /*
3253 * There are four interesting cases for this page table walker:
3254 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3255 * there is nothing left to do.
3256 * 2. It's the first of the current generation, and it needs to reset
3257 * the Bloom filter for the next generation.
3258 * 3. It reaches the end of mm_list, and it needs to increment
3259 * mm_state->seq; the iteration is done.
3260 * 4. It's the last of the current generation, and it needs to reset the
3261 * mm stats counters for the next generation.
3262 */
3263 spin_lock(&mm_list->lock);
3264
3265 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3266 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3267 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3268
3269 if (walk->max_seq <= mm_state->seq) {
3270 if (!*iter)
3271 last = false;
3272 goto done;
3273 }
3274
3275 if (!mm_state->nr_walkers) {
3276 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3277
3278 mm_state->head = mm_list->fifo.next;
3279 first = true;
3280 }
3281
3282 while (!mm && mm_state->head != &mm_list->fifo) {
3283 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3284
3285 mm_state->head = mm_state->head->next;
3286
3287 /* force scan for those added after the last iteration */
3288 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3289 mm_state->tail = mm_state->head;
3290 walk->force_scan = true;
3291 }
3292
3293 if (should_skip_mm(mm, walk))
3294 mm = NULL;
3295 }
3296
3297 if (mm_state->head == &mm_list->fifo)
3298 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3299done:
3300 if (*iter && !mm)
3301 mm_state->nr_walkers--;
3302 if (!*iter && mm)
3303 mm_state->nr_walkers++;
3304
3305 if (mm_state->nr_walkers)
3306 last = false;
3307
3308 if (*iter || last)
3309 reset_mm_stats(lruvec, walk, last);
3310
3311 spin_unlock(&mm_list->lock);
3312
3313 if (mm && first)
3314 reset_bloom_filter(lruvec, walk->max_seq + 1);
3315
3316 if (*iter)
3317 mmput_async(*iter);
3318
3319 *iter = mm;
3320
3321 return last;
3322}
3323
3324static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3325{
3326 bool success = false;
3327 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3328 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3329 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3330
3331 spin_lock(&mm_list->lock);
3332
3333 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3334
3335 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3336 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3337
3338 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3339 reset_mm_stats(lruvec, NULL, true);
3340 success = true;
3341 }
3342
3343 spin_unlock(&mm_list->lock);
3344
3345 return success;
3346}
3347
3348/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003349 * refault feedback loop
3350 ******************************************************************************/
3351
3352/*
3353 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3354 *
3355 * The P term is refaulted/(evicted+protected) from a tier in the generation
3356 * currently being evicted; the I term is the exponential moving average of the
3357 * P term over the generations previously evicted, using the smoothing factor
3358 * 1/2; the D term isn't supported.
3359 *
3360 * The setpoint (SP) is always the first tier of one type; the process variable
3361 * (PV) is either any tier of the other type or any other tier of the same
3362 * type.
3363 *
3364 * The error is the difference between the SP and the PV; the correction is to
3365 * turn off protection when SP>PV or turn on protection when SP<PV.
3366 *
3367 * For future optimizations:
3368 * 1. The D term may discount the other two terms over time so that long-lived
3369 * generations can resist stale information.
3370 */
3371struct ctrl_pos {
3372 unsigned long refaulted;
3373 unsigned long total;
3374 int gain;
3375};
3376
3377static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3378 struct ctrl_pos *pos)
3379{
Yu Zhao3c6c3592022-12-21 21:18:59 -07003380 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003381 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3382
3383 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3384 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3385 pos->total = lrugen->avg_total[type][tier] +
3386 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3387 if (tier)
3388 pos->total += lrugen->protected[hist][type][tier - 1];
3389 pos->gain = gain;
3390}
3391
3392static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3393{
3394 int hist, tier;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003395 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003396 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3397 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3398
3399 lockdep_assert_held(&lruvec->lru_lock);
3400
3401 if (!carryover && !clear)
3402 return;
3403
3404 hist = lru_hist_from_seq(seq);
3405
3406 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3407 if (carryover) {
3408 unsigned long sum;
3409
3410 sum = lrugen->avg_refaulted[type][tier] +
3411 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3412 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3413
3414 sum = lrugen->avg_total[type][tier] +
3415 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3416 if (tier)
3417 sum += lrugen->protected[hist][type][tier - 1];
3418 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3419 }
3420
3421 if (clear) {
3422 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3423 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3424 if (tier)
3425 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3426 }
3427 }
3428}
3429
3430static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3431{
3432 /*
3433 * Return true if the PV has a limited number of refaults or a lower
3434 * refaulted/total than the SP.
3435 */
3436 return pv->refaulted < MIN_LRU_BATCH ||
3437 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3438 (sp->refaulted + 1) * pv->total * pv->gain;
3439}
3440
3441/******************************************************************************
3442 * the aging
3443 ******************************************************************************/
3444
Yu Zhao0182f922022-09-18 02:00:04 -06003445/* promote pages accessed through page tables */
3446static int page_update_gen(struct page *page, int gen)
3447{
3448 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3449
3450 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3451 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3452
3453 do {
3454 /* lru_gen_del_page() has isolated this page? */
3455 if (!(old_flags & LRU_GEN_MASK)) {
3456 /* for shrink_page_list() */
3457 new_flags = old_flags | BIT(PG_referenced);
3458 continue;
3459 }
3460
3461 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3462 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3463 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3464
3465 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3466}
3467
Yu Zhao37397872022-09-18 02:00:03 -06003468/* protect pages accessed multiple times through file descriptors */
3469static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3470{
3471 int type = page_is_file_lru(page);
Yu Zhao3c6c3592022-12-21 21:18:59 -07003472 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003473 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3474 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3475
3476 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3477
3478 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003479 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3480 /* page_update_gen() has promoted this page? */
3481 if (new_gen >= 0 && new_gen != old_gen)
3482 return new_gen;
3483
Yu Zhao37397872022-09-18 02:00:03 -06003484 new_gen = (old_gen + 1) % MAX_NR_GENS;
3485
3486 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3487 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3488 /* for end_page_writeback() */
3489 if (reclaiming)
3490 new_flags |= BIT(PG_reclaim);
3491 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3492
3493 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3494
3495 return new_gen;
3496}
3497
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003498static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3499 int old_gen, int new_gen)
3500{
3501 int type = page_is_file_lru(page);
3502 int zone = page_zonenum(page);
3503 int delta = thp_nr_pages(page);
3504
3505 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3506 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3507
3508 walk->batched++;
3509
3510 walk->nr_pages[old_gen][type][zone] -= delta;
3511 walk->nr_pages[new_gen][type][zone] += delta;
3512}
3513
3514static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3515{
3516 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003517 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003518
3519 walk->batched = 0;
3520
3521 for_each_gen_type_zone(gen, type, zone) {
3522 enum lru_list lru = type * LRU_INACTIVE_FILE;
3523 int delta = walk->nr_pages[gen][type][zone];
3524
3525 if (!delta)
3526 continue;
3527
3528 walk->nr_pages[gen][type][zone] = 0;
3529 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3530 lrugen->nr_pages[gen][type][zone] + delta);
3531
3532 if (lru_gen_is_active(lruvec, gen))
3533 lru += LRU_ACTIVE;
3534 __update_lru_size(lruvec, lru, zone, delta);
3535 }
3536}
3537
3538static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3539{
3540 struct address_space *mapping;
3541 struct vm_area_struct *vma = args->vma;
3542 struct lru_gen_mm_walk *walk = args->private;
3543
3544 if (!vma_is_accessible(vma))
3545 return true;
3546
3547 if (is_vm_hugetlb_page(vma))
3548 return true;
3549
3550 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3551 return true;
3552
3553 if (vma == get_gate_vma(vma->vm_mm))
3554 return true;
3555
3556 if (vma_is_anonymous(vma))
3557 return !walk->can_swap;
3558
3559 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3560 return true;
3561
3562 mapping = vma->vm_file->f_mapping;
3563 if (mapping_unevictable(mapping))
3564 return true;
3565
3566 if (shmem_mapping(mapping))
3567 return !walk->can_swap;
3568
3569 /* to exclude special mappings like dax, etc. */
3570 return !mapping->a_ops->readpage;
3571}
3572
3573/*
3574 * Some userspace memory allocators map many single-page VMAs. Instead of
3575 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3576 * table to reduce zigzags and improve cache performance.
3577 */
3578static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3579 unsigned long *vm_start, unsigned long *vm_end)
3580{
3581 unsigned long start = round_up(*vm_end, size);
3582 unsigned long end = (start | ~mask) + 1;
3583
3584 VM_WARN_ON_ONCE(mask & size);
3585 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3586
3587 while (args->vma) {
3588 if (start >= args->vma->vm_end) {
3589 args->vma = args->vma->vm_next;
3590 continue;
3591 }
3592
3593 if (end && end <= args->vma->vm_start)
3594 return false;
3595
3596 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3597 args->vma = args->vma->vm_next;
3598 continue;
3599 }
3600
3601 *vm_start = max(start, args->vma->vm_start);
3602 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3603
3604 return true;
3605 }
3606
3607 return false;
3608}
3609
Yu Zhao0182f922022-09-18 02:00:04 -06003610static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3611{
3612 unsigned long pfn = pte_pfn(pte);
3613
3614 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3615
3616 if (!pte_present(pte) || is_zero_pfn(pfn))
3617 return -1;
3618
3619 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3620 return -1;
3621
3622 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3623 return -1;
3624
3625 return pfn;
3626}
3627
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003628#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3629static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3630{
3631 unsigned long pfn = pmd_pfn(pmd);
3632
3633 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3634
3635 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3636 return -1;
3637
3638 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3639 return -1;
3640
3641 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3642 return -1;
3643
3644 return pfn;
3645}
3646#endif
3647
Yu Zhao0182f922022-09-18 02:00:04 -06003648static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003649 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003650{
3651 struct page *page;
3652
3653 /* try to avoid unnecessary memory loads */
3654 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3655 return NULL;
3656
3657 page = compound_head(pfn_to_page(pfn));
3658 if (page_to_nid(page) != pgdat->node_id)
3659 return NULL;
3660
3661 if (page_memcg_rcu(page) != memcg)
3662 return NULL;
3663
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003664 /* file VMAs can contain anon pages from COW */
3665 if (!page_is_file_lru(page) && !can_swap)
3666 return NULL;
3667
Yu Zhao0182f922022-09-18 02:00:04 -06003668 return page;
3669}
3670
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003671static bool suitable_to_scan(int total, int young)
3672{
3673 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3674
3675 /* suitable if the average number of young PTEs per cacheline is >=1 */
3676 return young * n >= total;
3677}
3678
3679static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3680 struct mm_walk *args)
3681{
3682 int i;
3683 pte_t *pte;
3684 spinlock_t *ptl;
3685 unsigned long addr;
3686 int total = 0;
3687 int young = 0;
3688 struct lru_gen_mm_walk *walk = args->private;
3689 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3690 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3691 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3692
3693 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3694
3695 ptl = pte_lockptr(args->mm, pmd);
3696 if (!spin_trylock(ptl))
3697 return false;
3698
3699 arch_enter_lazy_mmu_mode();
3700
3701 pte = pte_offset_map(pmd, start & PMD_MASK);
3702restart:
3703 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3704 unsigned long pfn;
3705 struct page *page;
3706
3707 total++;
3708 walk->mm_stats[MM_LEAF_TOTAL]++;
3709
3710 pfn = get_pte_pfn(pte[i], args->vma, addr);
3711 if (pfn == -1)
3712 continue;
3713
3714 if (!pte_young(pte[i])) {
3715 walk->mm_stats[MM_LEAF_OLD]++;
3716 continue;
3717 }
3718
3719 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3720 if (!page)
3721 continue;
3722
3723 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3724 VM_WARN_ON_ONCE(true);
3725
3726 young++;
3727 walk->mm_stats[MM_LEAF_YOUNG]++;
3728
3729 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3730 !(PageAnon(page) && PageSwapBacked(page) &&
3731 !PageSwapCache(page)))
3732 set_page_dirty(page);
3733
3734 old_gen = page_update_gen(page, new_gen);
3735 if (old_gen >= 0 && old_gen != new_gen)
3736 update_batch_size(walk, page, old_gen, new_gen);
3737 }
3738
3739 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3740 goto restart;
3741
3742 pte_unmap(pte);
3743
3744 arch_leave_lazy_mmu_mode();
3745 spin_unlock(ptl);
3746
3747 return suitable_to_scan(total, young);
3748}
3749
3750#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3751static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3752 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3753{
3754 int i;
3755 pmd_t *pmd;
3756 spinlock_t *ptl;
3757 struct lru_gen_mm_walk *walk = args->private;
3758 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3759 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3760 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3761
3762 VM_WARN_ON_ONCE(pud_leaf(*pud));
3763
3764 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3765 if (*start == -1) {
3766 *start = next;
3767 return;
3768 }
3769
3770 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3771 if (i && i <= MIN_LRU_BATCH) {
3772 __set_bit(i - 1, bitmap);
3773 return;
3774 }
3775
3776 pmd = pmd_offset(pud, *start);
3777
3778 ptl = pmd_lockptr(args->mm, pmd);
3779 if (!spin_trylock(ptl))
3780 goto done;
3781
3782 arch_enter_lazy_mmu_mode();
3783
3784 do {
3785 unsigned long pfn;
3786 struct page *page;
3787 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3788
3789 pfn = get_pmd_pfn(pmd[i], vma, addr);
3790 if (pfn == -1)
3791 goto next;
3792
3793 if (!pmd_trans_huge(pmd[i])) {
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003794 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3795 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003796 pmdp_test_and_clear_young(vma, addr, pmd + i);
3797 goto next;
3798 }
3799
3800 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3801 if (!page)
3802 goto next;
3803
3804 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3805 goto next;
3806
3807 walk->mm_stats[MM_LEAF_YOUNG]++;
3808
3809 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3810 !(PageAnon(page) && PageSwapBacked(page) &&
3811 !PageSwapCache(page)))
3812 set_page_dirty(page);
3813
3814 old_gen = page_update_gen(page, new_gen);
3815 if (old_gen >= 0 && old_gen != new_gen)
3816 update_batch_size(walk, page, old_gen, new_gen);
3817next:
3818 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3819 } while (i <= MIN_LRU_BATCH);
3820
3821 arch_leave_lazy_mmu_mode();
3822 spin_unlock(ptl);
3823done:
3824 *start = -1;
3825 bitmap_zero(bitmap, MIN_LRU_BATCH);
3826}
3827#else
3828static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3829 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3830{
3831}
3832#endif
3833
3834static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3835 struct mm_walk *args)
3836{
3837 int i;
3838 pmd_t *pmd;
3839 unsigned long next;
3840 unsigned long addr;
3841 struct vm_area_struct *vma;
3842 unsigned long pos = -1;
3843 struct lru_gen_mm_walk *walk = args->private;
3844 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3845
3846 VM_WARN_ON_ONCE(pud_leaf(*pud));
3847
3848 /*
3849 * Finish an entire PMD in two passes: the first only reaches to PTE
3850 * tables to avoid taking the PMD lock; the second, if necessary, takes
3851 * the PMD lock to clear the accessed bit in PMD entries.
3852 */
3853 pmd = pmd_offset(pud, start & PUD_MASK);
3854restart:
3855 /* walk_pte_range() may call get_next_vma() */
3856 vma = args->vma;
3857 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3858 pmd_t val = pmd_read_atomic(pmd + i);
3859
3860 /* for pmd_read_atomic() */
3861 barrier();
3862
3863 next = pmd_addr_end(addr, end);
3864
3865 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3866 walk->mm_stats[MM_LEAF_TOTAL]++;
3867 continue;
3868 }
3869
3870#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3871 if (pmd_trans_huge(val)) {
3872 unsigned long pfn = pmd_pfn(val);
3873 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3874
3875 walk->mm_stats[MM_LEAF_TOTAL]++;
3876
3877 if (!pmd_young(val)) {
3878 walk->mm_stats[MM_LEAF_OLD]++;
3879 continue;
3880 }
3881
3882 /* try to avoid unnecessary memory loads */
3883 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3884 continue;
3885
3886 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3887 continue;
3888 }
3889#endif
3890 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3891
3892#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003893 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3894 if (!pmd_young(val))
3895 continue;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003896
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003897 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3898 }
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003899#endif
3900 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3901 continue;
3902
3903 walk->mm_stats[MM_NONLEAF_FOUND]++;
3904
3905 if (!walk_pte_range(&val, addr, next, args))
3906 continue;
3907
3908 walk->mm_stats[MM_NONLEAF_ADDED]++;
3909
3910 /* carry over to the next generation */
3911 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3912 }
3913
3914 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3915
3916 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3917 goto restart;
3918}
3919
3920static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3921 struct mm_walk *args)
3922{
3923 int i;
3924 pud_t *pud;
3925 unsigned long addr;
3926 unsigned long next;
3927 struct lru_gen_mm_walk *walk = args->private;
3928
3929 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3930
3931 pud = pud_offset(p4d, start & P4D_MASK);
3932restart:
3933 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3934 pud_t val = READ_ONCE(pud[i]);
3935
3936 next = pud_addr_end(addr, end);
3937
3938 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3939 continue;
3940
3941 walk_pmd_range(&val, addr, next, args);
3942
3943 /* a racy check to curtail the waiting time */
3944 if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
3945 return 1;
3946
3947 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3948 end = (addr | ~PUD_MASK) + 1;
3949 goto done;
3950 }
3951 }
3952
3953 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3954 goto restart;
3955
3956 end = round_up(end, P4D_SIZE);
3957done:
3958 if (!end || !args->vma)
3959 return 1;
3960
3961 walk->next_addr = max(end, args->vma->vm_start);
3962
3963 return -EAGAIN;
3964}
3965
3966static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3967{
3968 static const struct mm_walk_ops mm_walk_ops = {
3969 .test_walk = should_skip_vma,
3970 .p4d_entry = walk_pud_range,
3971 };
3972
3973 int err;
3974 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3975
3976 walk->next_addr = FIRST_USER_ADDRESS;
3977
3978 do {
3979 err = -EBUSY;
3980
3981 /* page_update_gen() requires stable page_memcg() */
3982 if (!mem_cgroup_trylock_pages(memcg))
3983 break;
3984
3985 /* the caller might be holding the lock for write */
3986 if (mmap_read_trylock(mm)) {
3987 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3988
3989 mmap_read_unlock(mm);
3990 }
3991
3992 mem_cgroup_unlock_pages();
3993
3994 if (walk->batched) {
3995 spin_lock_irq(&lruvec->lru_lock);
3996 reset_batch_size(lruvec, walk);
3997 spin_unlock_irq(&lruvec->lru_lock);
3998 }
3999
4000 cond_resched();
4001 } while (err == -EAGAIN);
4002}
4003
Yu Zhaof8b57162022-12-21 21:19:05 -07004004static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004005{
4006 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4007
4008 if (pgdat && current_is_kswapd()) {
4009 VM_WARN_ON_ONCE(walk);
4010
4011 walk = &pgdat->mm_walk;
Yu Zhaof8b57162022-12-21 21:19:05 -07004012 } else if (!walk && force_alloc) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004013 VM_WARN_ON_ONCE(current_is_kswapd());
4014
4015 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4016 }
4017
4018 current->reclaim_state->mm_walk = walk;
4019
4020 return walk;
4021}
4022
4023static void clear_mm_walk(void)
4024{
4025 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4026
4027 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4028 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4029
4030 current->reclaim_state->mm_walk = NULL;
4031
4032 if (!current_is_kswapd())
4033 kfree(walk);
4034}
4035
Yu Zhao4983c522022-09-18 02:00:09 -06004036static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004037{
Yu Zhao4983c522022-09-18 02:00:09 -06004038 int zone;
4039 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004040 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06004041 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
Yu Zhao37397872022-09-18 02:00:03 -06004042
Yu Zhao4983c522022-09-18 02:00:09 -06004043 if (type == LRU_GEN_ANON && !can_swap)
4044 goto done;
4045
4046 /* prevent cold/hot inversion if force_scan is true */
4047 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004048 struct list_head *head = &lrugen->pages[old_gen][type][zone];
Yu Zhao4983c522022-09-18 02:00:09 -06004049
4050 while (!list_empty(head)) {
4051 struct page *page = lru_to_page(head);
4052
4053 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4054 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4055 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4056 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4057
4058 new_gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004059 list_move_tail(&page->lru, &lrugen->pages[new_gen][type][zone]);
Yu Zhao4983c522022-09-18 02:00:09 -06004060
4061 if (!--remaining)
4062 return false;
4063 }
4064 }
4065done:
Yu Zhao37397872022-09-18 02:00:03 -06004066 reset_ctrl_pos(lruvec, type, true);
4067 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
Yu Zhao4983c522022-09-18 02:00:09 -06004068
4069 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004070}
4071
4072static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4073{
4074 int gen, type, zone;
4075 bool success = false;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004076 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004077 DEFINE_MIN_SEQ(lruvec);
4078
4079 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4080
4081 /* find the oldest populated generation */
4082 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4083 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4084 gen = lru_gen_from_seq(min_seq[type]);
4085
4086 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004087 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhao37397872022-09-18 02:00:03 -06004088 goto next;
4089 }
4090
4091 min_seq[type]++;
4092 }
4093next:
4094 ;
4095 }
4096
Yu Zhao3c6c3592022-12-21 21:18:59 -07004097 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06004098 if (can_swap) {
4099 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4100 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4101 }
4102
4103 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4104 if (min_seq[type] == lrugen->min_seq[type])
4105 continue;
4106
4107 reset_ctrl_pos(lruvec, type, true);
4108 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4109 success = true;
4110 }
4111
4112 return success;
4113}
4114
Yu Zhao4983c522022-09-18 02:00:09 -06004115static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
Yu Zhao37397872022-09-18 02:00:03 -06004116{
4117 int prev, next;
4118 int type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004119 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004120
4121 spin_lock_irq(&lruvec->lru_lock);
4122
4123 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4124
Yu Zhao37397872022-09-18 02:00:03 -06004125 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4126 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4127 continue;
4128
Yu Zhao4983c522022-09-18 02:00:09 -06004129 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
Yu Zhao37397872022-09-18 02:00:03 -06004130
Yu Zhao4983c522022-09-18 02:00:09 -06004131 while (!inc_min_seq(lruvec, type, can_swap)) {
4132 spin_unlock_irq(&lruvec->lru_lock);
4133 cond_resched();
4134 spin_lock_irq(&lruvec->lru_lock);
4135 }
Yu Zhao37397872022-09-18 02:00:03 -06004136 }
4137
4138 /*
4139 * Update the active/inactive LRU sizes for compatibility. Both sides of
4140 * the current max_seq need to be covered, since max_seq+1 can overlap
4141 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4142 * overlap, cold/hot inversion happens.
4143 */
4144 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4145 next = lru_gen_from_seq(lrugen->max_seq + 1);
4146
4147 for (type = 0; type < ANON_AND_FILE; type++) {
4148 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4149 enum lru_list lru = type * LRU_INACTIVE_FILE;
4150 long delta = lrugen->nr_pages[prev][type][zone] -
4151 lrugen->nr_pages[next][type][zone];
4152
4153 if (!delta)
4154 continue;
4155
4156 __update_lru_size(lruvec, lru, zone, delta);
4157 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4158 }
4159 }
4160
4161 for (type = 0; type < ANON_AND_FILE; type++)
4162 reset_ctrl_pos(lruvec, type, false);
4163
Yu Zhao430499c2022-09-18 02:00:08 -06004164 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhao37397872022-09-18 02:00:03 -06004165 /* make sure preceding modifications appear */
4166 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004167
Yu Zhao37397872022-09-18 02:00:03 -06004168 spin_unlock_irq(&lruvec->lru_lock);
4169}
4170
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004171static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
Yu Zhao4983c522022-09-18 02:00:09 -06004172 struct scan_control *sc, bool can_swap, bool force_scan)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004173{
4174 bool success;
4175 struct lru_gen_mm_walk *walk;
4176 struct mm_struct *mm = NULL;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004177 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004178
4179 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4180
4181 /* see the comment in iterate_mm_list() */
4182 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4183 success = false;
4184 goto done;
4185 }
4186
4187 /*
4188 * If the hardware doesn't automatically set the accessed bit, fallback
4189 * to lru_gen_look_around(), which only clears the accessed bit in a
4190 * handful of PTEs. Spreading the work out over a period of time usually
4191 * is less efficient, but it avoids bursty page faults.
4192 */
Yu Zhao4983c522022-09-18 02:00:09 -06004193 if (!force_scan && !(arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004194 success = iterate_mm_list_nowalk(lruvec, max_seq);
4195 goto done;
4196 }
4197
Yu Zhaof8b57162022-12-21 21:19:05 -07004198 walk = set_mm_walk(NULL, true);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004199 if (!walk) {
4200 success = iterate_mm_list_nowalk(lruvec, max_seq);
4201 goto done;
4202 }
4203
4204 walk->lruvec = lruvec;
4205 walk->max_seq = max_seq;
4206 walk->can_swap = can_swap;
Yu Zhao4983c522022-09-18 02:00:09 -06004207 walk->force_scan = force_scan;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004208
4209 do {
4210 success = iterate_mm_list(lruvec, walk, &mm);
4211 if (mm)
4212 walk_mm(lruvec, mm, walk);
4213
4214 cond_resched();
4215 } while (mm);
4216done:
4217 if (!success) {
4218 if (sc->priority <= DEF_PRIORITY - 2)
4219 wait_event_killable(lruvec->mm_state.wait,
4220 max_seq < READ_ONCE(lrugen->max_seq));
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004221 return false;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004222 }
4223
4224 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4225
Yu Zhao4983c522022-09-18 02:00:09 -06004226 inc_max_seq(lruvec, can_swap, force_scan);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004227 /* either this sees any waiters or they will see updated max_seq */
4228 if (wq_has_sleeper(&lruvec->mm_state.wait))
4229 wake_up_all(&lruvec->mm_state.wait);
4230
4231 return true;
4232}
4233
Yu Zhaoa5998f92022-12-21 21:19:02 -07004234static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
Yu Zhao37397872022-09-18 02:00:03 -06004235{
Yu Zhaoa5998f92022-12-21 21:19:02 -07004236 int gen, type, zone;
4237 unsigned long total = 0;
4238 bool can_swap = get_swappiness(lruvec, sc);
4239 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004240 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4241 DEFINE_MAX_SEQ(lruvec);
4242 DEFINE_MIN_SEQ(lruvec);
4243
Yu Zhaoa5998f92022-12-21 21:19:02 -07004244 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4245 unsigned long seq;
4246
4247 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4248 gen = lru_gen_from_seq(seq);
4249
4250 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4251 total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4252 }
4253 }
4254
4255 /* whether the size is big enough to be helpful */
4256 return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4257}
4258
4259static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
4260 unsigned long min_ttl)
4261{
4262 int gen;
4263 unsigned long birth;
4264 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4265 DEFINE_MIN_SEQ(lruvec);
4266
Yu Zhaoa5998f92022-12-21 21:19:02 -07004267 /* see the comment on lru_gen_page */
4268 gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4269 birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4270
4271 if (time_is_after_jiffies(birth + min_ttl))
4272 return false;
4273
4274 if (!lruvec_is_sizable(lruvec, sc))
4275 return false;
4276
Yu Zhao37397872022-09-18 02:00:03 -06004277 mem_cgroup_calculate_protection(NULL, memcg);
4278
Yu Zhaoa5998f92022-12-21 21:19:02 -07004279 return !mem_cgroup_below_min(memcg);
Yu Zhao37397872022-09-18 02:00:03 -06004280}
4281
Yu Zhao430499c2022-09-18 02:00:08 -06004282/* to protect the working set of the last N jiffies */
4283static unsigned long lru_gen_min_ttl __read_mostly;
4284
Yu Zhao37397872022-09-18 02:00:03 -06004285static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4286{
4287 struct mem_cgroup *memcg;
Yu Zhao430499c2022-09-18 02:00:08 -06004288 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhao37397872022-09-18 02:00:03 -06004289
4290 VM_WARN_ON_ONCE(!current_is_kswapd());
4291
Yu Zhaoa5998f92022-12-21 21:19:02 -07004292 /* check the order to exclude compaction-induced reclaim */
4293 if (!min_ttl || sc->order || sc->priority == DEF_PRIORITY)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004294 return;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004295
Yu Zhao37397872022-09-18 02:00:03 -06004296 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4297 do {
4298 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4299
Yu Zhaoa5998f92022-12-21 21:19:02 -07004300 if (lruvec_is_reclaimable(lruvec, sc, min_ttl)) {
4301 mem_cgroup_iter_break(NULL, memcg);
4302 return;
4303 }
Yu Zhao37397872022-09-18 02:00:03 -06004304
4305 cond_resched();
4306 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004307
Yu Zhao430499c2022-09-18 02:00:08 -06004308 /*
4309 * The main goal is to OOM kill if every generation from all memcgs is
4310 * younger than min_ttl. However, another possibility is all memcgs are
Yu Zhaoa5998f92022-12-21 21:19:02 -07004311 * either too small or below min.
Yu Zhao430499c2022-09-18 02:00:08 -06004312 */
4313 if (mutex_trylock(&oom_lock)) {
4314 struct oom_control oc = {
4315 .gfp_mask = sc->gfp_mask,
4316 };
4317
4318 out_of_memory(&oc);
4319
4320 mutex_unlock(&oom_lock);
4321 }
Yu Zhao37397872022-09-18 02:00:03 -06004322}
4323
Yu Zhao0182f922022-09-18 02:00:04 -06004324/*
4325 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004326 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4327 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4328 * the PTE table to the Bloom filter. This forms a feedback loop between the
4329 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004330 */
4331void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4332{
4333 int i;
4334 pte_t *pte;
4335 unsigned long start;
4336 unsigned long end;
4337 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004338 struct lru_gen_mm_walk *walk;
4339 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004340 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4341 struct page *page = pvmw->page;
4342 struct mem_cgroup *memcg = page_memcg(page);
4343 struct pglist_data *pgdat = page_pgdat(page);
4344 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4345 DEFINE_MAX_SEQ(lruvec);
4346 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4347
4348 lockdep_assert_held(pvmw->ptl);
4349 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4350
4351 if (spin_is_contended(pvmw->ptl))
4352 return;
4353
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004354 /* avoid taking the LRU lock under the PTL when possible */
4355 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4356
Yu Zhao0182f922022-09-18 02:00:04 -06004357 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4358 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4359
4360 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4361 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4362 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4363 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4364 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4365 else {
4366 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4367 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4368 }
4369 }
4370
4371 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4372
4373 rcu_read_lock();
4374 arch_enter_lazy_mmu_mode();
4375
4376 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4377 unsigned long pfn;
4378
4379 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4380 if (pfn == -1)
4381 continue;
4382
4383 if (!pte_young(pte[i]))
4384 continue;
4385
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004386 page = get_pfn_page(pfn, memcg, pgdat, !walk || walk->can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004387 if (!page)
4388 continue;
4389
4390 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4391 VM_WARN_ON_ONCE(true);
4392
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004393 young++;
4394
Yu Zhao0182f922022-09-18 02:00:04 -06004395 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4396 !(PageAnon(page) && PageSwapBacked(page) &&
4397 !PageSwapCache(page)))
4398 set_page_dirty(page);
4399
4400 old_gen = page_lru_gen(page);
4401 if (old_gen < 0)
4402 SetPageReferenced(page);
4403 else if (old_gen != new_gen)
4404 __set_bit(i, bitmap);
4405 }
4406
4407 arch_leave_lazy_mmu_mode();
4408 rcu_read_unlock();
4409
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004410 /* feedback from rmap walkers to page table walkers */
4411 if (suitable_to_scan(i, young))
4412 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4413
4414 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004415 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4416 page = pte_page(pte[i]);
4417 activate_page(page);
4418 }
4419 return;
4420 }
4421
4422 /* page_update_gen() requires stable page_memcg() */
4423 if (!mem_cgroup_trylock_pages(memcg))
4424 return;
4425
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004426 if (!walk) {
4427 spin_lock_irq(&lruvec->lru_lock);
4428 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4429 }
Yu Zhao0182f922022-09-18 02:00:04 -06004430
4431 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4432 page = compound_head(pte_page(pte[i]));
4433 if (page_memcg_rcu(page) != memcg)
4434 continue;
4435
4436 old_gen = page_update_gen(page, new_gen);
4437 if (old_gen < 0 || old_gen == new_gen)
4438 continue;
4439
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004440 if (walk)
4441 update_batch_size(walk, page, old_gen, new_gen);
4442 else
4443 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004444 }
4445
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004446 if (!walk)
4447 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004448
4449 mem_cgroup_unlock_pages();
4450}
4451
Yu Zhao37397872022-09-18 02:00:03 -06004452/******************************************************************************
4453 * the eviction
4454 ******************************************************************************/
4455
4456static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4457{
4458 bool success;
4459 int gen = page_lru_gen(page);
4460 int type = page_is_file_lru(page);
4461 int zone = page_zonenum(page);
4462 int delta = thp_nr_pages(page);
4463 int refs = page_lru_refs(page);
4464 int tier = lru_tier_from_refs(refs);
Yu Zhao3c6c3592022-12-21 21:18:59 -07004465 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004466
4467 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4468
4469 /* unevictable */
4470 if (!page_evictable(page)) {
4471 success = lru_gen_del_page(lruvec, page, true);
4472 VM_WARN_ON_ONCE_PAGE(!success, page);
4473 SetPageUnevictable(page);
4474 add_page_to_lru_list(page, lruvec);
4475 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4476 return true;
4477 }
4478
4479 /* dirty lazyfree */
4480 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4481 success = lru_gen_del_page(lruvec, page, true);
4482 VM_WARN_ON_ONCE_PAGE(!success, page);
4483 SetPageSwapBacked(page);
4484 add_page_to_lru_list_tail(page, lruvec);
4485 return true;
4486 }
4487
Yu Zhao0182f922022-09-18 02:00:04 -06004488 /* promoted */
4489 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004490 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao0182f922022-09-18 02:00:04 -06004491 return true;
4492 }
4493
Yu Zhao37397872022-09-18 02:00:03 -06004494 /* protected */
4495 if (tier > tier_idx) {
4496 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4497
4498 gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004499 list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004500
4501 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4502 lrugen->protected[hist][type][tier - 1] + delta);
4503 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4504 return true;
4505 }
4506
4507 /* waiting for writeback */
4508 if (PageLocked(page) || PageWriteback(page) ||
4509 (type == LRU_GEN_FILE && PageDirty(page))) {
4510 gen = page_inc_gen(lruvec, page, true);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004511 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004512 return true;
4513 }
4514
4515 return false;
4516}
4517
4518static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4519{
4520 bool success;
4521
Yu Zhao37397872022-09-18 02:00:03 -06004522 /* swapping inhibited */
Yu Zhaof8b57162022-12-21 21:19:05 -07004523 if (!(sc->gfp_mask & __GFP_IO) &&
Yu Zhao37397872022-09-18 02:00:03 -06004524 (PageDirty(page) ||
4525 (PageAnon(page) && !PageSwapCache(page))))
4526 return false;
4527
4528 /* raced with release_pages() */
4529 if (!get_page_unless_zero(page))
4530 return false;
4531
4532 /* raced with another isolation */
4533 if (!TestClearPageLRU(page)) {
4534 put_page(page);
4535 return false;
4536 }
4537
4538 /* see the comment on MAX_NR_TIERS */
4539 if (!PageReferenced(page))
4540 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4541
4542 /* for shrink_page_list() */
4543 ClearPageReclaim(page);
4544 ClearPageReferenced(page);
4545
4546 success = lru_gen_del_page(lruvec, page, true);
4547 VM_WARN_ON_ONCE_PAGE(!success, page);
4548
4549 return true;
4550}
4551
4552static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4553 int type, int tier, struct list_head *list)
4554{
4555 int gen, zone;
4556 enum vm_event_item item;
4557 int sorted = 0;
4558 int scanned = 0;
4559 int isolated = 0;
4560 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004561 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004562 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4563
4564 VM_WARN_ON_ONCE(!list_empty(list));
4565
4566 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4567 return 0;
4568
4569 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4570
4571 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4572 LIST_HEAD(moved);
4573 int skipped = 0;
Yu Zhaodf91dc92022-12-21 21:19:00 -07004574 struct list_head *head = &lrugen->pages[gen][type][zone];
Yu Zhao37397872022-09-18 02:00:03 -06004575
4576 while (!list_empty(head)) {
4577 struct page *page = lru_to_page(head);
4578 int delta = thp_nr_pages(page);
4579
4580 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4581 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4582 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4583 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4584
4585 scanned += delta;
4586
4587 if (sort_page(lruvec, page, tier))
4588 sorted += delta;
4589 else if (isolate_page(lruvec, page, sc)) {
4590 list_add(&page->lru, list);
4591 isolated += delta;
4592 } else {
4593 list_move(&page->lru, &moved);
4594 skipped += delta;
4595 }
4596
4597 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4598 break;
4599 }
4600
4601 if (skipped) {
4602 list_splice(&moved, head);
4603 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4604 }
4605
4606 if (!remaining || isolated >= MIN_LRU_BATCH)
4607 break;
4608 }
4609
4610 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4611 if (!cgroup_reclaim(sc)) {
4612 __count_vm_events(item, isolated);
4613 __count_vm_events(PGREFILL, sorted);
4614 }
4615 __count_memcg_events(memcg, item, isolated);
4616 __count_memcg_events(memcg, PGREFILL, sorted);
4617 __count_vm_events(PGSCAN_ANON + type, isolated);
4618
4619 /*
Yu Zhaof8b57162022-12-21 21:19:05 -07004620 * There might not be eligible pages due to reclaim_idx. Check the
4621 * remaining to prevent livelock if it's not making progress.
Yu Zhao37397872022-09-18 02:00:03 -06004622 */
4623 return isolated || !remaining ? scanned : 0;
4624}
4625
4626static int get_tier_idx(struct lruvec *lruvec, int type)
4627{
4628 int tier;
4629 struct ctrl_pos sp, pv;
4630
4631 /*
4632 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4633 * This value is chosen because any other tier would have at least twice
4634 * as many refaults as the first tier.
4635 */
4636 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4637 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4638 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4639 if (!positive_ctrl_err(&sp, &pv))
4640 break;
4641 }
4642
4643 return tier - 1;
4644}
4645
4646static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4647{
4648 int type, tier;
4649 struct ctrl_pos sp, pv;
4650 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4651
4652 /*
4653 * Compare the first tier of anon with that of file to determine which
4654 * type to scan. Also need to compare other tiers of the selected type
4655 * with the first tier of the other type to determine the last tier (of
4656 * the selected type) to evict.
4657 */
4658 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4659 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4660 type = positive_ctrl_err(&sp, &pv);
4661
4662 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4663 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4664 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4665 if (!positive_ctrl_err(&sp, &pv))
4666 break;
4667 }
4668
4669 *tier_idx = tier - 1;
4670
4671 return type;
4672}
4673
4674static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4675 int *type_scanned, struct list_head *list)
4676{
4677 int i;
4678 int type;
4679 int scanned;
4680 int tier = -1;
4681 DEFINE_MIN_SEQ(lruvec);
4682
4683 /*
4684 * Try to make the obvious choice first. When anon and file are both
4685 * available from the same generation, interpret swappiness 1 as file
4686 * first and 200 as anon first.
4687 */
4688 if (!swappiness)
4689 type = LRU_GEN_FILE;
4690 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4691 type = LRU_GEN_ANON;
4692 else if (swappiness == 1)
4693 type = LRU_GEN_FILE;
4694 else if (swappiness == 200)
4695 type = LRU_GEN_ANON;
4696 else
4697 type = get_type_to_scan(lruvec, swappiness, &tier);
4698
4699 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4700 if (tier < 0)
4701 tier = get_tier_idx(lruvec, type);
4702
4703 scanned = scan_pages(lruvec, sc, type, tier, list);
4704 if (scanned)
4705 break;
4706
4707 type = !type;
4708 tier = -1;
4709 }
4710
4711 *type_scanned = type;
4712
4713 return scanned;
4714}
4715
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004716static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
Yu Zhao37397872022-09-18 02:00:03 -06004717{
4718 int type;
4719 int scanned;
4720 int reclaimed;
4721 LIST_HEAD(list);
Yu Zhao79e66ea2022-11-15 18:38:07 -07004722 LIST_HEAD(clean);
Yu Zhao37397872022-09-18 02:00:03 -06004723 struct page *page;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004724 struct page *next;
Yu Zhao37397872022-09-18 02:00:03 -06004725 enum vm_event_item item;
4726 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004727 struct lru_gen_mm_walk *walk;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004728 bool skip_retry = false;
Yu Zhao37397872022-09-18 02:00:03 -06004729 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4730 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4731
4732 spin_lock_irq(&lruvec->lru_lock);
4733
4734 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4735
4736 scanned += try_to_inc_min_seq(lruvec, swappiness);
4737
4738 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4739 scanned = 0;
4740
4741 spin_unlock_irq(&lruvec->lru_lock);
4742
4743 if (list_empty(&list))
4744 return scanned;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004745retry:
Yu Zhao37397872022-09-18 02:00:03 -06004746 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
Yu Zhao79e66ea2022-11-15 18:38:07 -07004747 sc->nr_reclaimed += reclaimed;
Yu Zhao37397872022-09-18 02:00:03 -06004748
Yu Zhao79e66ea2022-11-15 18:38:07 -07004749 list_for_each_entry_safe_reverse(page, next, &list, lru) {
4750 if (!page_evictable(page)) {
4751 list_del(&page->lru);
4752 putback_lru_page(page);
4753 continue;
4754 }
Yu Zhao37397872022-09-18 02:00:03 -06004755
Yu Zhao37397872022-09-18 02:00:03 -06004756 if (PageReclaim(page) &&
Yu Zhao79e66ea2022-11-15 18:38:07 -07004757 (PageDirty(page) || PageWriteback(page))) {
4758 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4759 if (PageWorkingset(page))
4760 SetPageReferenced(page);
4761 continue;
4762 }
4763
4764 if (skip_retry || PageActive(page) || PageReferenced(page) ||
4765 page_mapped(page) || PageLocked(page) ||
4766 PageDirty(page) || PageWriteback(page)) {
4767 /* don't add rejected pages to the oldest generation */
4768 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
4769 BIT(PG_active));
4770 continue;
4771 }
4772
4773 /* retry pages that may have missed rotate_reclaimable_page() */
4774 list_move(&page->lru, &clean);
4775 sc->nr_scanned -= thp_nr_pages(page);
Yu Zhao37397872022-09-18 02:00:03 -06004776 }
4777
4778 spin_lock_irq(&lruvec->lru_lock);
4779
4780 move_pages_to_lru(lruvec, &list);
4781
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004782 walk = current->reclaim_state->mm_walk;
4783 if (walk && walk->batched)
4784 reset_batch_size(lruvec, walk);
4785
Yu Zhao37397872022-09-18 02:00:03 -06004786 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4787 if (!cgroup_reclaim(sc))
4788 __count_vm_events(item, reclaimed);
4789 __count_memcg_events(memcg, item, reclaimed);
4790 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4791
4792 spin_unlock_irq(&lruvec->lru_lock);
4793
4794 mem_cgroup_uncharge_list(&list);
4795 free_unref_page_list(&list);
4796
Yu Zhao79e66ea2022-11-15 18:38:07 -07004797 INIT_LIST_HEAD(&list);
4798 list_splice_init(&clean, &list);
4799
4800 if (!list_empty(&list)) {
4801 skip_retry = true;
4802 goto retry;
4803 }
Yu Zhao37397872022-09-18 02:00:03 -06004804
4805 return scanned;
4806}
4807
Yu Zhaocb3958d2022-12-21 21:19:03 -07004808static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
4809 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4810{
4811 int gen, type, zone;
4812 unsigned long old = 0;
4813 unsigned long young = 0;
4814 unsigned long total = 0;
4815 struct lru_gen_page *lrugen = &lruvec->lrugen;
4816 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4817 DEFINE_MIN_SEQ(lruvec);
4818
4819 /* whether this lruvec is completely out of cold pages */
4820 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
4821 *nr_to_scan = 0;
4822 return true;
4823 }
4824
4825 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4826 unsigned long seq;
4827
4828 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4829 unsigned long size = 0;
4830
4831 gen = lru_gen_from_seq(seq);
4832
4833 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4834 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4835
4836 total += size;
4837 if (seq == max_seq)
4838 young += size;
4839 else if (seq + MIN_NR_GENS == max_seq)
4840 old += size;
4841 }
4842 }
4843
4844 /* try to scrape all its memory if this memcg was deleted */
4845 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4846
4847 /*
4848 * The aging tries to be lazy to reduce the overhead, while the eviction
4849 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4850 * ideal number of generations is MIN_NR_GENS+1.
4851 */
4852 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4853 return false;
4854
4855 /*
4856 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4857 * of the total number of pages for each generation. A reasonable range
4858 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4859 * aging cares about the upper bound of hot pages, while the eviction
4860 * cares about the lower bound of cold pages.
4861 */
4862 if (young * MIN_NR_GENS > total)
4863 return true;
4864 if (old * (MIN_NR_GENS + 2) < total)
4865 return true;
4866
4867 return false;
4868}
4869
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004870/*
4871 * For future optimizations:
4872 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4873 * reclaim.
4874 */
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004875static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004876{
Yu Zhao37397872022-09-18 02:00:03 -06004877 unsigned long nr_to_scan;
4878 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4879 DEFINE_MAX_SEQ(lruvec);
Yu Zhao37397872022-09-18 02:00:03 -06004880
Yu Zhaof8b57162022-12-21 21:19:05 -07004881 if (mem_cgroup_below_min(memcg))
Yu Zhao37397872022-09-18 02:00:03 -06004882 return 0;
4883
Yu Zhaoa5998f92022-12-21 21:19:02 -07004884 if (!should_run_aging(lruvec, max_seq, sc, can_swap, &nr_to_scan))
Yu Zhao37397872022-09-18 02:00:03 -06004885 return nr_to_scan;
4886
4887 /* skip the aging path at the default priority */
4888 if (sc->priority == DEF_PRIORITY)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004889 return nr_to_scan;
Yu Zhaoa5998f92022-12-21 21:19:02 -07004890
Yu Zhaoa5998f92022-12-21 21:19:02 -07004891 /* skip this lruvec as it's low on cold pages */
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004892 return try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false) ? -1 : 0;
Yu Zhao37397872022-09-18 02:00:03 -06004893}
4894
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004895static unsigned long get_nr_to_reclaim(struct scan_control *sc)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004896{
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004897 /* don't abort memcg reclaim to ensure fairness */
4898 if (!global_reclaim(sc))
4899 return -1;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004900
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004901 return max(sc->nr_to_reclaim, compact_gap(sc->order));
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004902}
4903
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004904static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Yu Zhao37397872022-09-18 02:00:03 -06004905{
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004906 long nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004907 unsigned long scanned = 0;
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004908 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
Yu Zhaof8b57162022-12-21 21:19:05 -07004909 int swappiness = get_swappiness(lruvec, sc);
4910
4911 /* clean file pages are more likely to exist */
4912 if (swappiness && !(sc->gfp_mask & __GFP_IO))
4913 swappiness = 1;
Yu Zhao37397872022-09-18 02:00:03 -06004914
Yu Zhao37397872022-09-18 02:00:03 -06004915 while (true) {
4916 int delta;
Yu Zhao37397872022-09-18 02:00:03 -06004917
Yu Zhaoa5998f92022-12-21 21:19:02 -07004918 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004919 if (nr_to_scan <= 0)
Yu Zhaoa5998f92022-12-21 21:19:02 -07004920 break;
Yu Zhao37397872022-09-18 02:00:03 -06004921
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004922 delta = evict_pages(lruvec, sc, swappiness);
Yu Zhao37397872022-09-18 02:00:03 -06004923 if (!delta)
Yu Zhaoa5998f92022-12-21 21:19:02 -07004924 break;
Yu Zhao37397872022-09-18 02:00:03 -06004925
4926 scanned += delta;
4927 if (scanned >= nr_to_scan)
4928 break;
4929
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004930 if (sc->nr_reclaimed >= nr_to_reclaim)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004931 break;
4932
Yu Zhao37397872022-09-18 02:00:03 -06004933 cond_resched();
4934 }
4935
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004936 /* whether try_to_inc_max_seq() was successful */
4937 return nr_to_scan < 0;
4938}
4939
4940static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
4941{
4942 bool success;
4943 unsigned long scanned = sc->nr_scanned;
4944 unsigned long reclaimed = sc->nr_reclaimed;
4945 int seg = lru_gen_memcg_seg(lruvec);
4946 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4947 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4948
4949 /* see the comment on MEMCG_NR_GENS */
4950 if (!lruvec_is_sizable(lruvec, sc))
4951 return seg != MEMCG_LRU_TAIL ? MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG;
4952
4953 mem_cgroup_calculate_protection(NULL, memcg);
4954
4955 if (mem_cgroup_below_min(memcg))
4956 return MEMCG_LRU_YOUNG;
4957
4958 if (mem_cgroup_below_low(memcg)) {
4959 /* see the comment on MEMCG_NR_GENS */
4960 if (seg != MEMCG_LRU_TAIL)
4961 return MEMCG_LRU_TAIL;
4962
4963 memcg_memory_event(memcg, MEMCG_LOW);
4964 }
4965
4966 success = try_to_shrink_lruvec(lruvec, sc);
4967
4968 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority);
4969
4970 vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned,
4971 sc->nr_reclaimed - reclaimed);
4972
4973 sc->nr_reclaimed += current->reclaim_state->reclaimed_slab;
4974 current->reclaim_state->reclaimed_slab = 0;
4975
4976 return success ? MEMCG_LRU_YOUNG : 0;
4977}
4978
4979#ifdef CONFIG_MEMCG
4980
4981static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
4982{
Yu Zhaof7909cb2023-02-13 00:53:22 -07004983 int op;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004984 int gen;
4985 int bin;
4986 int first_bin;
4987 struct lruvec *lruvec;
4988 struct lru_gen_page *lrugen;
Yu Zhaof7909cb2023-02-13 00:53:22 -07004989 struct mem_cgroup *memcg;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004990 const struct hlist_nulls_node *pos;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004991 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
4992
4993 bin = first_bin = prandom_u32_max(MEMCG_NR_BINS);
4994restart:
Yu Zhaof7909cb2023-02-13 00:53:22 -07004995 op = 0;
4996 memcg = NULL;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004997 gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq));
4998
4999 rcu_read_lock();
5000
5001 hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) {
5002 if (op)
5003 lru_gen_rotate_memcg(lruvec, op);
5004
5005 mem_cgroup_put(memcg);
5006
5007 lruvec = container_of(lrugen, struct lruvec, lrugen);
5008 memcg = lruvec_memcg(lruvec);
5009
5010 if (!mem_cgroup_tryget(memcg)) {
5011 op = 0;
5012 memcg = NULL;
5013 continue;
5014 }
5015
5016 rcu_read_unlock();
5017
5018 op = shrink_one(lruvec, sc);
5019
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005020 rcu_read_lock();
Yu Zhaof7909cb2023-02-13 00:53:22 -07005021
5022 if (sc->nr_reclaimed >= nr_to_reclaim)
5023 break;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005024 }
5025
5026 rcu_read_unlock();
5027
Yu Zhaof7909cb2023-02-13 00:53:22 -07005028 if (op)
5029 lru_gen_rotate_memcg(lruvec, op);
5030
5031 mem_cgroup_put(memcg);
5032
5033 if (sc->nr_reclaimed >= nr_to_reclaim)
5034 return;
5035
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005036 /* restart if raced with lru_gen_rotate_memcg() */
5037 if (gen != get_nulls_value(pos))
5038 goto restart;
5039
5040 /* try the rest of the bins of the current generation */
5041 bin = get_memcg_bin(bin + 1);
5042 if (bin != first_bin)
5043 goto restart;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005044}
5045
5046static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5047{
5048 struct blk_plug plug;
5049
5050 VM_WARN_ON_ONCE(global_reclaim(sc));
Yu Zhaof8b57162022-12-21 21:19:05 -07005051 VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005052
5053 lru_add_drain();
5054
5055 blk_start_plug(&plug);
5056
Yu Zhaof8b57162022-12-21 21:19:05 -07005057 set_mm_walk(NULL, false);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005058
5059 if (try_to_shrink_lruvec(lruvec, sc))
5060 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG);
5061
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005062 clear_mm_walk();
5063
Yu Zhao37397872022-09-18 02:00:03 -06005064 blk_finish_plug(&plug);
5065}
5066
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005067#else /* !CONFIG_MEMCG */
5068
5069static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5070{
5071 BUILD_BUG();
5072}
5073
5074static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5075{
5076 BUILD_BUG();
5077}
5078
5079#endif
5080
5081static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc)
5082{
5083 int priority;
5084 unsigned long reclaimable;
5085 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5086
5087 if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH)
5088 return;
5089 /*
5090 * Determine the initial priority based on ((total / MEMCG_NR_GENS) >>
5091 * priority) * reclaimed_to_scanned_ratio = nr_to_reclaim, where the
5092 * estimated reclaimed_to_scanned_ratio = inactive / total.
5093 */
5094 reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE);
5095 if (get_swappiness(lruvec, sc))
5096 reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON);
5097
5098 reclaimable /= MEMCG_NR_GENS;
5099
5100 /* round down reclaimable and round up sc->nr_to_reclaim */
5101 priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1);
5102
5103 sc->priority = clamp(priority, 0, DEF_PRIORITY);
5104}
5105
5106static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5107{
5108 struct blk_plug plug;
5109 unsigned long reclaimed = sc->nr_reclaimed;
5110
5111 VM_WARN_ON_ONCE(!global_reclaim(sc));
5112
Yu Zhaof8b57162022-12-21 21:19:05 -07005113 /*
5114 * Unmapped clean pages are already prioritized. Scanning for more of
5115 * them is likely futile and can cause high reclaim latency when there
5116 * is a large number of memcgs.
5117 */
5118 if (!sc->may_writepage || !sc->may_unmap)
5119 goto done;
5120
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005121 lru_add_drain();
5122
5123 blk_start_plug(&plug);
5124
Yu Zhaof8b57162022-12-21 21:19:05 -07005125 set_mm_walk(pgdat, false);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005126
5127 set_initial_priority(pgdat, sc);
5128
5129 if (current_is_kswapd())
5130 sc->nr_reclaimed = 0;
5131
5132 if (mem_cgroup_disabled())
5133 shrink_one(&pgdat->__lruvec, sc);
5134 else
5135 shrink_many(pgdat, sc);
5136
5137 if (current_is_kswapd())
5138 sc->nr_reclaimed += reclaimed;
5139
5140 clear_mm_walk();
5141
5142 blk_finish_plug(&plug);
Yu Zhaof8b57162022-12-21 21:19:05 -07005143done:
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005144 /* kswapd should never fail */
5145 pgdat->kswapd_failures = 0;
5146}
5147
5148#ifdef CONFIG_MEMCG
5149void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
5150{
5151 int seg;
5152 int old, new;
5153 int bin = prandom_u32_max(MEMCG_NR_BINS);
5154 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5155
5156 spin_lock(&pgdat->memcg_lru.lock);
5157
5158 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
5159
5160 seg = 0;
5161 new = old = lruvec->lrugen.gen;
5162
5163 /* see the comment on MEMCG_NR_GENS */
5164 if (op == MEMCG_LRU_HEAD)
5165 seg = MEMCG_LRU_HEAD;
5166 else if (op == MEMCG_LRU_TAIL)
5167 seg = MEMCG_LRU_TAIL;
5168 else if (op == MEMCG_LRU_OLD)
5169 new = get_memcg_gen(pgdat->memcg_lru.seq);
5170 else if (op == MEMCG_LRU_YOUNG)
5171 new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
5172 else
5173 VM_WARN_ON_ONCE(true);
5174
5175 hlist_nulls_del_rcu(&lruvec->lrugen.list);
5176
5177 if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
5178 hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
5179 else
5180 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
5181
5182 pgdat->memcg_lru.nr_memcgs[old]--;
5183 pgdat->memcg_lru.nr_memcgs[new]++;
5184
5185 lruvec->lrugen.gen = new;
5186 WRITE_ONCE(lruvec->lrugen.seg, seg);
5187
5188 if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
5189 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
5190
5191 spin_unlock(&pgdat->memcg_lru.lock);
5192}
5193#endif
5194
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005195/******************************************************************************
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005196 * state change
5197 ******************************************************************************/
5198
5199static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5200{
Yu Zhao3c6c3592022-12-21 21:18:59 -07005201 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005202
5203 if (lrugen->enabled) {
5204 enum lru_list lru;
5205
5206 for_each_evictable_lru(lru) {
5207 if (!list_empty(&lruvec->lists[lru]))
5208 return false;
5209 }
5210 } else {
5211 int gen, type, zone;
5212
5213 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005214 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005215 return false;
5216 }
5217 }
5218
5219 return true;
5220}
5221
5222static bool fill_evictable(struct lruvec *lruvec)
5223{
5224 enum lru_list lru;
5225 int remaining = MAX_LRU_BATCH;
5226
5227 for_each_evictable_lru(lru) {
5228 int type = is_file_lru(lru);
5229 bool active = is_active_lru(lru);
5230 struct list_head *head = &lruvec->lists[lru];
5231
5232 while (!list_empty(head)) {
5233 bool success;
5234 struct page *page = lru_to_page(head);
5235
5236 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5237 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
5238 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5239 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
5240
5241 del_page_from_lru_list(page, lruvec);
5242 success = lru_gen_add_page(lruvec, page, false);
5243 VM_WARN_ON_ONCE(!success);
5244
5245 if (!--remaining)
5246 return false;
5247 }
5248 }
5249
5250 return true;
5251}
5252
5253static bool drain_evictable(struct lruvec *lruvec)
5254{
5255 int gen, type, zone;
5256 int remaining = MAX_LRU_BATCH;
5257
5258 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005259 struct list_head *head = &lruvec->lrugen.pages[gen][type][zone];
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005260
5261 while (!list_empty(head)) {
5262 bool success;
5263 struct page *page = lru_to_page(head);
5264
5265 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5266 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5267 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5268 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5269
5270 success = lru_gen_del_page(lruvec, page, false);
5271 VM_WARN_ON_ONCE(!success);
5272 add_page_to_lru_list(page, lruvec);
5273
5274 if (!--remaining)
5275 return false;
5276 }
5277 }
5278
5279 return true;
5280}
5281
5282static void lru_gen_change_state(bool enabled)
5283{
5284 static DEFINE_MUTEX(state_mutex);
5285
5286 struct mem_cgroup *memcg;
5287
5288 cgroup_lock();
5289 cpus_read_lock();
5290 get_online_mems();
5291 mutex_lock(&state_mutex);
5292
5293 if (enabled == lru_gen_enabled())
5294 goto unlock;
5295
5296 if (enabled)
5297 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5298 else
5299 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5300
5301 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5302 do {
5303 int nid;
5304
5305 for_each_node(nid) {
5306 struct lruvec *lruvec = get_lruvec(memcg, nid);
5307
5308 if (!lruvec)
5309 continue;
5310
5311 spin_lock_irq(&lruvec->lru_lock);
5312
5313 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5314 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5315
5316 lruvec->lrugen.enabled = enabled;
5317
5318 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5319 spin_unlock_irq(&lruvec->lru_lock);
5320 cond_resched();
5321 spin_lock_irq(&lruvec->lru_lock);
5322 }
5323
5324 spin_unlock_irq(&lruvec->lru_lock);
5325 }
5326
5327 cond_resched();
5328 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5329unlock:
5330 mutex_unlock(&state_mutex);
5331 put_online_mems();
5332 cpus_read_unlock();
5333 cgroup_unlock();
5334}
5335
5336/******************************************************************************
5337 * sysfs interface
5338 ******************************************************************************/
5339
Yu Zhao430499c2022-09-18 02:00:08 -06005340static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5341{
5342 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5343}
5344
Yu Zhao642d9862022-09-18 02:00:10 -06005345/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao430499c2022-09-18 02:00:08 -06005346static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5347 const char *buf, size_t len)
5348{
5349 unsigned int msecs;
5350
5351 if (kstrtouint(buf, 0, &msecs))
5352 return -EINVAL;
5353
5354 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5355
5356 return len;
5357}
5358
5359static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5360 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5361);
5362
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005363static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5364{
5365 unsigned int caps = 0;
5366
5367 if (get_cap(LRU_GEN_CORE))
5368 caps |= BIT(LRU_GEN_CORE);
5369
5370 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5371 caps |= BIT(LRU_GEN_MM_WALK);
5372
5373 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
5374 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5375
5376 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5377}
5378
Yu Zhao642d9862022-09-18 02:00:10 -06005379/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005380static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5381 const char *buf, size_t len)
5382{
5383 int i;
5384 unsigned int caps;
5385
5386 if (tolower(*buf) == 'n')
5387 caps = 0;
5388 else if (tolower(*buf) == 'y')
5389 caps = -1;
5390 else if (kstrtouint(buf, 0, &caps))
5391 return -EINVAL;
5392
5393 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5394 bool enabled = caps & BIT(i);
5395
5396 if (i == LRU_GEN_CORE)
5397 lru_gen_change_state(enabled);
5398 else if (enabled)
5399 static_branch_enable(&lru_gen_caps[i]);
5400 else
5401 static_branch_disable(&lru_gen_caps[i]);
5402 }
5403
5404 return len;
5405}
5406
5407static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5408 enabled, 0644, show_enabled, store_enabled
5409);
5410
5411static struct attribute *lru_gen_attrs[] = {
Yu Zhao430499c2022-09-18 02:00:08 -06005412 &lru_gen_min_ttl_attr.attr,
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005413 &lru_gen_enabled_attr.attr,
5414 NULL
5415};
5416
5417static struct attribute_group lru_gen_attr_group = {
5418 .name = "lru_gen",
5419 .attrs = lru_gen_attrs,
5420};
5421
5422/******************************************************************************
Yu Zhao4983c522022-09-18 02:00:09 -06005423 * debugfs interface
5424 ******************************************************************************/
5425
5426static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5427{
5428 struct mem_cgroup *memcg;
5429 loff_t nr_to_skip = *pos;
5430
5431 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5432 if (!m->private)
5433 return ERR_PTR(-ENOMEM);
5434
5435 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5436 do {
5437 int nid;
5438
5439 for_each_node_state(nid, N_MEMORY) {
5440 if (!nr_to_skip--)
5441 return get_lruvec(memcg, nid);
5442 }
5443 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5444
5445 return NULL;
5446}
5447
5448static void lru_gen_seq_stop(struct seq_file *m, void *v)
5449{
5450 if (!IS_ERR_OR_NULL(v))
5451 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5452
5453 kvfree(m->private);
5454 m->private = NULL;
5455}
5456
5457static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5458{
5459 int nid = lruvec_pgdat(v)->node_id;
5460 struct mem_cgroup *memcg = lruvec_memcg(v);
5461
5462 ++*pos;
5463
5464 nid = next_memory_node(nid);
5465 if (nid == MAX_NUMNODES) {
5466 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5467 if (!memcg)
5468 return NULL;
5469
5470 nid = first_memory_node;
5471 }
5472
5473 return get_lruvec(memcg, nid);
5474}
5475
5476static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5477 unsigned long max_seq, unsigned long *min_seq,
5478 unsigned long seq)
5479{
5480 int i;
5481 int type, tier;
5482 int hist = lru_hist_from_seq(seq);
Yu Zhao3c6c3592022-12-21 21:18:59 -07005483 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005484
5485 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5486 seq_printf(m, " %10d", tier);
5487 for (type = 0; type < ANON_AND_FILE; type++) {
5488 const char *s = " ";
5489 unsigned long n[3] = {};
5490
5491 if (seq == max_seq) {
5492 s = "RT ";
5493 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5494 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5495 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5496 s = "rep";
5497 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5498 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5499 if (tier)
5500 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5501 }
5502
5503 for (i = 0; i < 3; i++)
5504 seq_printf(m, " %10lu%c", n[i], s[i]);
5505 }
5506 seq_putc(m, '\n');
5507 }
5508
5509 seq_puts(m, " ");
5510 for (i = 0; i < NR_MM_STATS; i++) {
5511 const char *s = " ";
5512 unsigned long n = 0;
5513
5514 if (seq == max_seq && NR_HIST_GENS == 1) {
5515 s = "LOYNFA";
5516 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5517 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5518 s = "loynfa";
5519 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5520 }
5521
5522 seq_printf(m, " %10lu%c", n, s[i]);
5523 }
5524 seq_putc(m, '\n');
5525}
5526
Yu Zhao642d9862022-09-18 02:00:10 -06005527/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005528static int lru_gen_seq_show(struct seq_file *m, void *v)
5529{
5530 unsigned long seq;
5531 bool full = !debugfs_real_fops(m->file)->write;
5532 struct lruvec *lruvec = v;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005533 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005534 int nid = lruvec_pgdat(lruvec)->node_id;
5535 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5536 DEFINE_MAX_SEQ(lruvec);
5537 DEFINE_MIN_SEQ(lruvec);
5538
5539 if (nid == first_memory_node) {
5540 const char *path = memcg ? m->private : "";
5541
5542#ifdef CONFIG_MEMCG
5543 if (memcg)
5544 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5545#endif
5546 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5547 }
5548
5549 seq_printf(m, " node %5d\n", nid);
5550
5551 if (!full)
5552 seq = min_seq[LRU_GEN_ANON];
5553 else if (max_seq >= MAX_NR_GENS)
5554 seq = max_seq - MAX_NR_GENS + 1;
5555 else
5556 seq = 0;
5557
5558 for (; seq <= max_seq; seq++) {
5559 int type, zone;
5560 int gen = lru_gen_from_seq(seq);
5561 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5562
5563 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5564
5565 for (type = 0; type < ANON_AND_FILE; type++) {
5566 unsigned long size = 0;
5567 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5568
5569 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5570 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5571
5572 seq_printf(m, " %10lu%c", size, mark);
5573 }
5574
5575 seq_putc(m, '\n');
5576
5577 if (full)
5578 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5579 }
5580
5581 return 0;
5582}
5583
5584static const struct seq_operations lru_gen_seq_ops = {
5585 .start = lru_gen_seq_start,
5586 .stop = lru_gen_seq_stop,
5587 .next = lru_gen_seq_next,
5588 .show = lru_gen_seq_show,
5589};
5590
5591static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5592 bool can_swap, bool force_scan)
5593{
5594 DEFINE_MAX_SEQ(lruvec);
5595 DEFINE_MIN_SEQ(lruvec);
5596
5597 if (seq < max_seq)
5598 return 0;
5599
5600 if (seq > max_seq)
5601 return -EINVAL;
5602
5603 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5604 return -ERANGE;
5605
5606 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5607
5608 return 0;
5609}
5610
5611static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5612 int swappiness, unsigned long nr_to_reclaim)
5613{
5614 DEFINE_MAX_SEQ(lruvec);
5615
5616 if (seq + MIN_NR_GENS > max_seq)
5617 return -EINVAL;
5618
5619 sc->nr_reclaimed = 0;
5620
5621 while (!signal_pending(current)) {
5622 DEFINE_MIN_SEQ(lruvec);
5623
5624 if (seq < min_seq[!swappiness])
5625 return 0;
5626
5627 if (sc->nr_reclaimed >= nr_to_reclaim)
5628 return 0;
5629
Yu Zhao4fc3ef42022-12-21 21:19:01 -07005630 if (!evict_pages(lruvec, sc, swappiness))
Yu Zhao4983c522022-09-18 02:00:09 -06005631 return 0;
5632
5633 cond_resched();
5634 }
5635
5636 return -EINTR;
5637}
5638
5639static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5640 struct scan_control *sc, int swappiness, unsigned long opt)
5641{
5642 struct lruvec *lruvec;
5643 int err = -EINVAL;
5644 struct mem_cgroup *memcg = NULL;
5645
5646 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5647 return -EINVAL;
5648
5649 if (!mem_cgroup_disabled()) {
5650 rcu_read_lock();
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005651
Yu Zhao4983c522022-09-18 02:00:09 -06005652 memcg = mem_cgroup_from_id(memcg_id);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005653 if (!mem_cgroup_tryget(memcg))
Yu Zhao4983c522022-09-18 02:00:09 -06005654 memcg = NULL;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005655
Yu Zhao4983c522022-09-18 02:00:09 -06005656 rcu_read_unlock();
5657
5658 if (!memcg)
5659 return -EINVAL;
5660 }
5661
5662 if (memcg_id != mem_cgroup_id(memcg))
5663 goto done;
5664
5665 lruvec = get_lruvec(memcg, nid);
5666
5667 if (swappiness < 0)
5668 swappiness = get_swappiness(lruvec, sc);
5669 else if (swappiness > 200)
5670 goto done;
5671
5672 switch (cmd) {
5673 case '+':
5674 err = run_aging(lruvec, seq, sc, swappiness, opt);
5675 break;
5676 case '-':
5677 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5678 break;
5679 }
5680done:
5681 mem_cgroup_put(memcg);
5682
5683 return err;
5684}
5685
Yu Zhao642d9862022-09-18 02:00:10 -06005686/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005687static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5688 size_t len, loff_t *pos)
5689{
5690 void *buf;
5691 char *cur, *next;
5692 unsigned int flags;
5693 struct blk_plug plug;
5694 int err = -EINVAL;
5695 struct scan_control sc = {
5696 .may_writepage = true,
5697 .may_unmap = true,
5698 .may_swap = true,
5699 .reclaim_idx = MAX_NR_ZONES - 1,
5700 .gfp_mask = GFP_KERNEL,
5701 };
5702
5703 buf = kvmalloc(len + 1, GFP_KERNEL);
5704 if (!buf)
5705 return -ENOMEM;
5706
5707 if (copy_from_user(buf, src, len)) {
5708 kvfree(buf);
5709 return -EFAULT;
5710 }
5711
5712 set_task_reclaim_state(current, &sc.reclaim_state);
5713 flags = memalloc_noreclaim_save();
5714 blk_start_plug(&plug);
Yu Zhaof8b57162022-12-21 21:19:05 -07005715 if (!set_mm_walk(NULL, true)) {
Yu Zhao4983c522022-09-18 02:00:09 -06005716 err = -ENOMEM;
5717 goto done;
5718 }
5719
5720 next = buf;
5721 next[len] = '\0';
5722
5723 while ((cur = strsep(&next, ",;\n"))) {
5724 int n;
5725 int end;
5726 char cmd;
5727 unsigned int memcg_id;
5728 unsigned int nid;
5729 unsigned long seq;
5730 unsigned int swappiness = -1;
5731 unsigned long opt = -1;
5732
5733 cur = skip_spaces(cur);
5734 if (!*cur)
5735 continue;
5736
5737 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5738 &seq, &end, &swappiness, &end, &opt, &end);
5739 if (n < 4 || cur[end]) {
5740 err = -EINVAL;
5741 break;
5742 }
5743
5744 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5745 if (err)
5746 break;
5747 }
5748done:
5749 clear_mm_walk();
5750 blk_finish_plug(&plug);
5751 memalloc_noreclaim_restore(flags);
5752 set_task_reclaim_state(current, NULL);
5753
5754 kvfree(buf);
5755
5756 return err ? : len;
5757}
5758
5759static int lru_gen_seq_open(struct inode *inode, struct file *file)
5760{
5761 return seq_open(file, &lru_gen_seq_ops);
5762}
5763
5764static const struct file_operations lru_gen_rw_fops = {
5765 .open = lru_gen_seq_open,
5766 .read = seq_read,
5767 .write = lru_gen_seq_write,
5768 .llseek = seq_lseek,
5769 .release = seq_release,
5770};
5771
5772static const struct file_operations lru_gen_ro_fops = {
5773 .open = lru_gen_seq_open,
5774 .read = seq_read,
5775 .llseek = seq_lseek,
5776 .release = seq_release,
5777};
5778
5779/******************************************************************************
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005780 * initialization
5781 ******************************************************************************/
5782
5783void lru_gen_init_lruvec(struct lruvec *lruvec)
5784{
Yu Zhao430499c2022-09-18 02:00:08 -06005785 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005786 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005787 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005788
5789 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005790 lrugen->enabled = lru_gen_enabled();
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005791
Yu Zhao430499c2022-09-18 02:00:08 -06005792 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5793 lrugen->timestamps[i] = jiffies;
5794
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005795 for_each_gen_type_zone(gen, type, zone)
Yu Zhaodf91dc92022-12-21 21:19:00 -07005796 INIT_LIST_HEAD(&lrugen->pages[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005797
5798 lruvec->mm_state.seq = MIN_NR_GENS;
5799 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005800}
5801
5802#ifdef CONFIG_MEMCG
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005803
5804void lru_gen_init_pgdat(struct pglist_data *pgdat)
5805{
5806 int i, j;
5807
5808 spin_lock_init(&pgdat->memcg_lru.lock);
5809
5810 for (i = 0; i < MEMCG_NR_GENS; i++) {
5811 for (j = 0; j < MEMCG_NR_BINS; j++)
5812 INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i);
5813 }
5814}
5815
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005816void lru_gen_init_memcg(struct mem_cgroup *memcg)
5817{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005818 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5819 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005820}
5821
5822void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5823{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005824 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005825 int nid;
5826
5827 for_each_node(nid) {
5828 struct lruvec *lruvec = get_lruvec(memcg, nid);
5829
5830 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5831 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005832
5833 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5834 bitmap_free(lruvec->mm_state.filters[i]);
5835 lruvec->mm_state.filters[i] = NULL;
5836 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005837 }
5838}
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005839
5840void lru_gen_online_memcg(struct mem_cgroup *memcg)
5841{
5842 int gen;
5843 int nid;
5844 int bin = prandom_u32_max(MEMCG_NR_BINS);
5845
5846 for_each_node(nid) {
5847 struct pglist_data *pgdat = NODE_DATA(nid);
5848 struct lruvec *lruvec = get_lruvec(memcg, nid);
5849
5850 spin_lock(&pgdat->memcg_lru.lock);
5851
5852 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
5853
5854 gen = get_memcg_gen(pgdat->memcg_lru.seq);
5855
5856 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
5857 pgdat->memcg_lru.nr_memcgs[gen]++;
5858
5859 lruvec->lrugen.gen = gen;
5860
5861 spin_unlock(&pgdat->memcg_lru.lock);
5862 }
5863}
5864
5865void lru_gen_offline_memcg(struct mem_cgroup *memcg)
5866{
5867 int nid;
5868
5869 for_each_node(nid) {
5870 struct lruvec *lruvec = get_lruvec(memcg, nid);
5871
5872 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
5873 }
5874}
5875
5876void lru_gen_release_memcg(struct mem_cgroup *memcg)
5877{
5878 int gen;
5879 int nid;
5880
5881 for_each_node(nid) {
5882 struct pglist_data *pgdat = NODE_DATA(nid);
5883 struct lruvec *lruvec = get_lruvec(memcg, nid);
5884
5885 spin_lock(&pgdat->memcg_lru.lock);
5886
5887 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
5888
5889 gen = lruvec->lrugen.gen;
5890
5891 hlist_nulls_del_rcu(&lruvec->lrugen.list);
5892 pgdat->memcg_lru.nr_memcgs[gen]--;
5893
5894 if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
5895 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
5896
5897 spin_unlock(&pgdat->memcg_lru.lock);
5898 }
5899}
5900
5901#endif /* CONFIG_MEMCG */
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005902
5903static int __init init_lru_gen(void)
5904{
5905 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5906 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5907
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005908 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5909 pr_err("lru_gen: failed to create sysfs group\n");
5910
Yu Zhao4983c522022-09-18 02:00:09 -06005911 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5912 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5913
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005914 return 0;
5915};
5916late_initcall(init_lru_gen);
5917
Yu Zhao37397872022-09-18 02:00:03 -06005918#else /* !CONFIG_LRU_GEN */
5919
5920static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5921{
5922}
5923
5924static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5925{
5926}
5927
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005928static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5929{
5930}
5931
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005932#endif /* CONFIG_LRU_GEN */
5933
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005934static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005935{
5936 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005937 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005938 unsigned long nr_to_scan;
5939 enum lru_list lru;
5940 unsigned long nr_reclaimed = 0;
5941 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005942 bool proportional_reclaim;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005943 struct blk_plug plug;
Minchan Kima8962f62022-11-02 09:04:41 -07005944 bool do_plug = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005945
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005946 if (lru_gen_enabled() && !global_reclaim(sc)) {
Yu Zhao37397872022-09-18 02:00:03 -06005947 lru_gen_shrink_lruvec(lruvec, sc);
5948 return;
5949 }
5950
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005951 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005952
Mel Gormane82e0562013-07-03 15:01:44 -07005953 /* Record the original scan target for proportional adjustments later */
5954 memcpy(targets, nr, sizeof(nr));
5955
Mel Gorman1a501902014-06-04 16:10:49 -07005956 /*
5957 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5958 * event that can occur when there is little memory pressure e.g.
5959 * multiple streaming readers/writers. Hence, we do not abort scanning
5960 * when the requested number of pages are reclaimed when scanning at
5961 * DEF_PRIORITY on the assumption that the fact we are direct
5962 * reclaiming implies that kswapd is not keeping up and it is best to
5963 * do a batch of work at once. For memcg reclaim one check is made to
5964 * abort proportional reclaim if either the file or anon lru has already
5965 * dropped to zero at the first pass.
5966 */
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005967 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5968 sc->priority == DEF_PRIORITY);
Mel Gorman1a501902014-06-04 16:10:49 -07005969
Minchan Kima8962f62022-11-02 09:04:41 -07005970 trace_android_vh_shrink_lruvec_blk_plug(&do_plug);
5971 if (do_plug)
5972 blk_start_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005973 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5974 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005975 unsigned long nr_anon, nr_file, percentage;
5976 unsigned long nr_scanned;
5977
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005978 for_each_evictable_lru(lru) {
5979 if (nr[lru]) {
5980 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5981 nr[lru] -= nr_to_scan;
5982
5983 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005984 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005985 }
5986 }
Mel Gormane82e0562013-07-03 15:01:44 -07005987
Michal Hockobd041732016-12-02 17:26:48 -08005988 cond_resched();
5989
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005990 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
Mel Gormane82e0562013-07-03 15:01:44 -07005991 continue;
5992
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005993 /*
Mel Gormane82e0562013-07-03 15:01:44 -07005994 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07005995 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07005996 * proportionally what was requested by get_scan_count(). We
5997 * stop reclaiming one LRU and reduce the amount scanning
5998 * proportional to the original scan target.
5999 */
6000 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
6001 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
6002
Mel Gorman1a501902014-06-04 16:10:49 -07006003 /*
6004 * It's just vindictive to attack the larger once the smaller
6005 * has gone to zero. And given the way we stop scanning the
6006 * smaller below, this makes sure that we only make one nudge
6007 * towards proportionality once we've got nr_to_reclaim.
6008 */
6009 if (!nr_file || !nr_anon)
6010 break;
6011
Mel Gormane82e0562013-07-03 15:01:44 -07006012 if (nr_file > nr_anon) {
6013 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
6014 targets[LRU_ACTIVE_ANON] + 1;
6015 lru = LRU_BASE;
6016 percentage = nr_anon * 100 / scan_target;
6017 } else {
6018 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
6019 targets[LRU_ACTIVE_FILE] + 1;
6020 lru = LRU_FILE;
6021 percentage = nr_file * 100 / scan_target;
6022 }
6023
6024 /* Stop scanning the smaller of the LRU */
6025 nr[lru] = 0;
6026 nr[lru + LRU_ACTIVE] = 0;
6027
6028 /*
6029 * Recalculate the other LRU scan count based on its original
6030 * scan target and the percentage scanning already complete
6031 */
6032 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
6033 nr_scanned = targets[lru] - nr[lru];
6034 nr[lru] = targets[lru] * (100 - percentage) / 100;
6035 nr[lru] -= min(nr[lru], nr_scanned);
6036
6037 lru += LRU_ACTIVE;
6038 nr_scanned = targets[lru] - nr[lru];
6039 nr[lru] = targets[lru] * (100 - percentage) / 100;
6040 nr[lru] -= min(nr[lru], nr_scanned);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006041 }
Minchan Kima8962f62022-11-02 09:04:41 -07006042 if (do_plug)
6043 blk_finish_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006044 sc->nr_reclaimed += nr_reclaimed;
6045
6046 /*
6047 * Even if we did not try to evict anon pages at all, we want to
6048 * rebalance the anon lru active/inactive ratio.
6049 */
Dave Hansen2f368a92021-09-02 14:59:23 -07006050 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
6051 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006052 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6053 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006054}
6055
Mel Gorman23b9da52012-05-29 15:06:20 -07006056/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006057static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07006058{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08006059 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07006060 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006061 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07006062 return true;
6063
6064 return false;
6065}
6066
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006067/*
Mel Gorman23b9da52012-05-29 15:06:20 -07006068 * Reclaim/compaction is used for high-order allocation requests. It reclaims
6069 * order-0 pages before compacting the zone. should_continue_reclaim() returns
6070 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07006071 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07006072 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08006073 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006074static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08006075 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08006076 struct scan_control *sc)
6077{
6078 unsigned long pages_for_compaction;
6079 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07006080 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006081
6082 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006083 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08006084 return false;
6085
Vlastimil Babka5ee04712019-09-23 15:37:29 -07006086 /*
6087 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
6088 * number of pages that were scanned. This will return to the caller
6089 * with the risk reclaim/compaction and the resulting allocation attempt
6090 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
6091 * allocations through requiring that the full LRU list has been scanned
6092 * first, by assuming that zero delta of sc->nr_scanned means full LRU
6093 * scan, but that approximation was wrong, and there were corner cases
6094 * where always a non-zero amount of pages were scanned.
6095 */
6096 if (!nr_reclaimed)
6097 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006098
Mel Gorman3e7d3442011-01-13 15:45:56 -08006099 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006100 for (z = 0; z <= sc->reclaim_idx; z++) {
6101 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07006102 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07006103 continue;
6104
6105 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07006106 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07006107 case COMPACT_CONTINUE:
6108 return false;
6109 default:
6110 /* check next zone */
6111 ;
6112 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08006113 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07006114
6115 /*
6116 * If we have not reclaimed enough pages for compaction and the
6117 * inactive lists are large enough, continue reclaiming
6118 */
6119 pages_for_compaction = compact_gap(sc->order);
6120 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07006121 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07006122 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
6123
Vlastimil Babka5ee04712019-09-23 15:37:29 -07006124 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006125}
6126
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006127static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006128{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006129 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08006130 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006131
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006132 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08006133 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006134 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006135 unsigned long reclaimed;
6136 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08006137 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08006138
Xunlei Pange3336ca2020-09-04 16:35:27 -07006139 /*
6140 * This loop can become CPU-bound when target memcgs
6141 * aren't eligible for reclaim - either because they
6142 * don't have any reclaimable pages, or because their
6143 * memory is explicitly protected. Avoid soft lockups.
6144 */
6145 cond_resched();
6146
Liujie Xieb7ea1c42022-06-01 15:38:17 +08006147 trace_android_vh_shrink_node_memcgs(memcg, &skip);
6148 if (skip)
6149 continue;
6150
Chris Down45c7f7e2020-08-06 23:22:05 -07006151 mem_cgroup_calculate_protection(target_memcg, memcg);
6152
6153 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08006154 /*
6155 * Hard protection.
6156 * If there is no reclaimable memory, OOM.
6157 */
6158 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07006159 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08006160 /*
6161 * Soft protection.
6162 * Respect the protection only as long as
6163 * there is an unprotected supply
6164 * of reclaimable memory from other cgroups.
6165 */
6166 if (!sc->memcg_low_reclaim) {
6167 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006168 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006169 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08006170 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08006171 }
6172
Johannes Weinerd2af3392019-11-30 17:55:43 -08006173 reclaimed = sc->nr_reclaimed;
6174 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006175
6176 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006177
Johannes Weinerd2af3392019-11-30 17:55:43 -08006178 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
6179 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07006180
Johannes Weinerd2af3392019-11-30 17:55:43 -08006181 /* Record the group's reclaim efficiency */
6182 vmpressure(sc->gfp_mask, memcg, false,
6183 sc->nr_scanned - scanned,
6184 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006185
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006186 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
6187}
6188
Liu Song6c9e09072020-01-30 22:14:08 -08006189static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006190{
6191 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006192 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08006193 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006194 bool reclaimable = false;
6195
Yu Zhaoa3eb6512022-12-21 21:19:04 -07006196 if (lru_gen_enabled() && global_reclaim(sc)) {
6197 lru_gen_shrink_node(pgdat, sc);
6198 return;
6199 }
6200
Johannes Weiner1b051172019-11-30 17:55:52 -08006201 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
6202
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006203again:
6204 memset(&sc->nr, 0, sizeof(sc->nr));
6205
6206 nr_reclaimed = sc->nr_reclaimed;
6207 nr_scanned = sc->nr_scanned;
6208
Yu Zhao6d313442022-09-18 02:00:00 -06006209 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08006210
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006211 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006212
Johannes Weinerd2af3392019-11-30 17:55:43 -08006213 if (reclaim_state) {
6214 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
6215 reclaim_state->reclaimed_slab = 0;
6216 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07006217
Johannes Weinerd2af3392019-11-30 17:55:43 -08006218 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08006219 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08006220 sc->nr_scanned - nr_scanned,
6221 sc->nr_reclaimed - nr_reclaimed);
6222
6223 if (sc->nr_reclaimed - nr_reclaimed)
6224 reclaimable = true;
6225
6226 if (current_is_kswapd()) {
6227 /*
6228 * If reclaim is isolating dirty pages under writeback,
6229 * it implies that the long-lived page allocation rate
6230 * is exceeding the page laundering rate. Either the
6231 * global limits are not being effective at throttling
6232 * processes due to the page distribution throughout
6233 * zones or there is heavy usage of a slow backing
6234 * device. The only option is to throttle from reclaim
6235 * context which is not ideal as there is no guarantee
6236 * the dirtying process is throttled in the same way
6237 * balance_dirty_pages() manages.
6238 *
6239 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6240 * count the number of pages under pages flagged for
6241 * immediate reclaim and stall if any are encountered
6242 * in the nr_immediate check below.
6243 */
6244 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
6245 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006246
Johannes Weinerd2af3392019-11-30 17:55:43 -08006247 /* Allow kswapd to start writing pages during reclaim.*/
6248 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
6249 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07006250
6251 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006252 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08006253 * reclaim and under writeback (nr_immediate), it
6254 * implies that pages are cycling through the LRU
6255 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07006256 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08006257 if (sc->nr.immediate)
6258 congestion_wait(BLK_RW_ASYNC, HZ/10);
6259 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07006260
Johannes Weinerd2af3392019-11-30 17:55:43 -08006261 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08006262 * Tag a node/memcg as congested if all the dirty pages
6263 * scanned were backed by a congested BDI and
6264 * wait_iff_congested will stall.
6265 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08006266 * Legacy memcg will stall in page writeback so avoid forcibly
6267 * stalling in wait_iff_congested().
6268 */
Johannes Weiner1b051172019-11-30 17:55:52 -08006269 if ((current_is_kswapd() ||
6270 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08006271 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08006272 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006273
6274 /*
6275 * Stall direct reclaim for IO completions if underlying BDIs
6276 * and node is congested. Allow kswapd to continue until it
6277 * starts encountering unqueued dirty pages or cycling through
6278 * the LRU too quickly.
6279 */
Johannes Weiner1b051172019-11-30 17:55:52 -08006280 if (!current_is_kswapd() && current_may_throttle() &&
6281 !sc->hibernation_mode &&
6282 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08006283 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
6284
6285 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
6286 sc))
6287 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07006288
Johannes Weinerc73322d2017-05-03 14:51:51 -07006289 /*
6290 * Kswapd gives up on balancing particular nodes after too
6291 * many failures to reclaim anything from them and goes to
6292 * sleep. On reclaim progress, reset the failure counter. A
6293 * successful direct reclaim run will revive a dormant kswapd.
6294 */
6295 if (reclaimable)
6296 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006297}
6298
Vlastimil Babka53853e22014-10-09 15:27:02 -07006299/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006300 * Returns true if compaction should go ahead for a costly-order request, or
6301 * the allocation would already succeed without compaction. Return false if we
6302 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07006303 */
Mel Gorman4f588332016-07-28 15:46:38 -07006304static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006305{
Mel Gorman31483b62016-07-28 15:45:46 -07006306 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006307 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006308
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006309 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6310 if (suitable == COMPACT_SUCCESS)
6311 /* Allocation should succeed already. Don't reclaim. */
6312 return true;
6313 if (suitable == COMPACT_SKIPPED)
6314 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006315 return false;
6316
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006317 /*
6318 * Compaction is already possible, but it takes time to run and there
6319 * are potentially other callers using the pages just freed. So proceed
6320 * with reclaim to make a buffer of free pages available to give
6321 * compaction a reasonable chance of completing and allocating the page.
6322 * Note that we won't actually reclaim the whole buffer in one attempt
6323 * as the target watermark in should_continue_reclaim() is lower. But if
6324 * we are already above the high+gap watermark, don't reclaim at all.
6325 */
6326 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6327
6328 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006329}
6330
Linus Torvalds1da177e2005-04-16 15:20:36 -07006331/*
6332 * This is the direct reclaim path, for page-allocating processes. We only
6333 * try to reclaim pages from zones which will satisfy the caller's allocation
6334 * request.
6335 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07006336 * If a zone is deemed to be full of pinned pages then just give it a light
6337 * scan then give up on it.
6338 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07006339static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006340{
Mel Gormandd1a2392008-04-28 02:12:17 -07006341 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07006342 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07006343 unsigned long nr_soft_reclaimed;
6344 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07006345 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07006346 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006347
Mel Gormancc715d92012-03-21 16:34:00 -07006348 /*
6349 * If the number of buffer_heads in the machine exceeds the maximum
6350 * allowed level, force direct reclaim to scan the highmem zone as
6351 * highmem pages could be pinning lowmem pages storing buffer_heads
6352 */
Weijie Yang619d0d762014-04-07 15:36:59 -07006353 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07006354 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07006355 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07006356 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07006357 }
Mel Gormancc715d92012-03-21 16:34:00 -07006358
Mel Gormand4debc62010-08-09 17:19:29 -07006359 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07006360 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07006361 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006362 * Take care memory controller reclaiming has small influence
6363 * to global LRU.
6364 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08006365 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04006366 if (!cpuset_zone_allowed(zone,
6367 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006368 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006369
Johannes Weiner0b064962014-08-06 16:06:12 -07006370 /*
6371 * If we already have plenty of memory free for
6372 * compaction in this zone, don't free any more.
6373 * Even though compaction is invoked for any
6374 * non-zero order, only frequent costly order
6375 * reclamation is disruptive enough to become a
6376 * noticeable problem, like transparent huge
6377 * page allocations.
6378 */
6379 if (IS_ENABLED(CONFIG_COMPACTION) &&
6380 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07006381 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07006382 sc->compaction_ready = true;
6383 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07006384 }
Johannes Weiner0b064962014-08-06 16:06:12 -07006385
Andrew Morton0608f432013-09-24 15:27:41 -07006386 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07006387 * Shrink each node in the zonelist once. If the
6388 * zonelist is ordered by zone (not the default) then a
6389 * node may be shrunk multiple times but in that case
6390 * the user prefers lower zones being preserved.
6391 */
6392 if (zone->zone_pgdat == last_pgdat)
6393 continue;
6394
6395 /*
Andrew Morton0608f432013-09-24 15:27:41 -07006396 * This steals pages from memory cgroups over softlimit
6397 * and returns the number of reclaimed pages and
6398 * scanned pages. This works for global memory pressure
6399 * and balancing, not for a memcg's limit.
6400 */
6401 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006402 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006403 sc->order, sc->gfp_mask,
6404 &nr_soft_scanned);
6405 sc->nr_reclaimed += nr_soft_reclaimed;
6406 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006407 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006408 }
Nick Piggin408d8542006-09-25 23:31:27 -07006409
Mel Gorman79dafcd2016-07-28 15:45:53 -07006410 /* See comment about same check for global reclaim above */
6411 if (zone->zone_pgdat == last_pgdat)
6412 continue;
6413 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006414 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006415 }
Mel Gormane0c23272011-10-31 17:09:33 -07006416
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006417 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006418 * Restore to original mask to avoid the impact on the caller if we
6419 * promoted it to __GFP_HIGHMEM.
6420 */
6421 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006422}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006423
Johannes Weinerb9107182019-11-30 17:55:59 -08006424static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006425{
Johannes Weinerb9107182019-11-30 17:55:59 -08006426 struct lruvec *target_lruvec;
6427 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006428
Yu Zhao37397872022-09-18 02:00:03 -06006429 if (lru_gen_enabled())
6430 return;
6431
Johannes Weinerb9107182019-11-30 17:55:59 -08006432 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006433 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6434 target_lruvec->refaults[0] = refaults;
6435 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6436 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006437}
6438
Linus Torvalds1da177e2005-04-16 15:20:36 -07006439/*
6440 * This is the main entry point to direct page reclaim.
6441 *
6442 * If a full scan of the inactive list fails to free enough memory then we
6443 * are "out of memory" and something needs to be killed.
6444 *
6445 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6446 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006447 * caller can't do much about. We kick the writeback threads and take explicit
6448 * naps in the hope that some of these pages can be written. But if the
6449 * allocating task holds filesystem locks which prevent writeout this might not
6450 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006451 *
6452 * returns: 0, if no pages reclaimed
6453 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006454 */
Mel Gormandac1d272008-04-28 02:12:12 -07006455static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006456 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006457{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006458 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006459 pg_data_t *last_pgdat;
6460 struct zoneref *z;
6461 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006462retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006463 delayacct_freepages_start();
6464
Johannes Weinerb5ead352019-11-30 17:55:40 -08006465 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006466 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006467
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006468 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006469 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6470 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006471 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006472 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006473
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006474 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006475 break;
6476
6477 if (sc->compaction_ready)
6478 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006479
6480 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006481 * If we're getting trouble reclaiming, start doing
6482 * writepage even in laptop mode.
6483 */
6484 if (sc->priority < DEF_PRIORITY - 2)
6485 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006486 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006487
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006488 last_pgdat = NULL;
6489 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6490 sc->nodemask) {
6491 if (zone->zone_pgdat == last_pgdat)
6492 continue;
6493 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006494
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006495 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006496
6497 if (cgroup_reclaim(sc)) {
6498 struct lruvec *lruvec;
6499
6500 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6501 zone->zone_pgdat);
6502 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6503 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006504 }
6505
Keika Kobayashi873b4772008-07-25 01:48:52 -07006506 delayacct_freepages_end();
6507
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006508 if (sc->nr_reclaimed)
6509 return sc->nr_reclaimed;
6510
Mel Gorman0cee34f2012-01-12 17:19:49 -08006511 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006512 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006513 return 1;
6514
Johannes Weinerb91ac372019-11-30 17:56:02 -08006515 /*
6516 * We make inactive:active ratio decisions based on the node's
6517 * composition of memory, but a restrictive reclaim_idx or a
6518 * memory.low cgroup setting can exempt large amounts of
6519 * memory from reclaim. Neither of which are very common, so
6520 * instead of doing costly eligibility calculations of the
6521 * entire cgroup subtree up front, we assume the estimates are
6522 * good, and retry with forcible deactivation if that fails.
6523 */
6524 if (sc->skipped_deactivate) {
6525 sc->priority = initial_priority;
6526 sc->force_deactivate = 1;
6527 sc->skipped_deactivate = 0;
6528 goto retry;
6529 }
6530
Johannes Weiner241994ed2015-02-11 15:26:06 -08006531 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006532 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006533 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006534 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006535 sc->memcg_low_reclaim = 1;
6536 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006537 goto retry;
6538 }
6539
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006540 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006541}
6542
Johannes Weinerc73322d2017-05-03 14:51:51 -07006543static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006544{
6545 struct zone *zone;
6546 unsigned long pfmemalloc_reserve = 0;
6547 unsigned long free_pages = 0;
6548 int i;
6549 bool wmark_ok;
6550
Johannes Weinerc73322d2017-05-03 14:51:51 -07006551 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6552 return true;
6553
Mel Gorman55150612012-07-31 16:44:35 -07006554 for (i = 0; i <= ZONE_NORMAL; i++) {
6555 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006556 if (!managed_zone(zone))
6557 continue;
6558
6559 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006560 continue;
6561
Mel Gorman55150612012-07-31 16:44:35 -07006562 pfmemalloc_reserve += min_wmark_pages(zone);
6563 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6564 }
6565
Mel Gorman675becc2014-06-04 16:07:35 -07006566 /* If there are no reserves (unexpected config) then do not throttle */
6567 if (!pfmemalloc_reserve)
6568 return true;
6569
Mel Gorman55150612012-07-31 16:44:35 -07006570 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6571
6572 /* kswapd must be awake if processes are being throttled */
6573 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006574 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6575 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006576
Mel Gorman55150612012-07-31 16:44:35 -07006577 wake_up_interruptible(&pgdat->kswapd_wait);
6578 }
6579
6580 return wmark_ok;
6581}
6582
6583/*
6584 * Throttle direct reclaimers if backing storage is backed by the network
6585 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6586 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006587 * when the low watermark is reached.
6588 *
6589 * Returns true if a fatal signal was delivered during throttling. If this
6590 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006591 */
Mel Gorman50694c22012-11-26 16:29:48 -08006592static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006593 nodemask_t *nodemask)
6594{
Mel Gorman675becc2014-06-04 16:07:35 -07006595 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006596 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006597 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006598
6599 /*
6600 * Kernel threads should not be throttled as they may be indirectly
6601 * responsible for cleaning pages necessary for reclaim to make forward
6602 * progress. kjournald for example may enter direct reclaim while
6603 * committing a transaction where throttling it could forcing other
6604 * processes to block on log_wait_commit().
6605 */
6606 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006607 goto out;
6608
6609 /*
6610 * If a fatal signal is pending, this process should not throttle.
6611 * It should return quickly so it can exit and free its memory
6612 */
6613 if (fatal_signal_pending(current))
6614 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006615
Mel Gorman675becc2014-06-04 16:07:35 -07006616 /*
6617 * Check if the pfmemalloc reserves are ok by finding the first node
6618 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6619 * GFP_KERNEL will be required for allocating network buffers when
6620 * swapping over the network so ZONE_HIGHMEM is unusable.
6621 *
6622 * Throttling is based on the first usable node and throttled processes
6623 * wait on a queue until kswapd makes progress and wakes them. There
6624 * is an affinity then between processes waking up and where reclaim
6625 * progress has been made assuming the process wakes on the same node.
6626 * More importantly, processes running on remote nodes will not compete
6627 * for remote pfmemalloc reserves and processes on different nodes
6628 * should make reasonable progress.
6629 */
6630 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006631 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006632 if (zone_idx(zone) > ZONE_NORMAL)
6633 continue;
6634
6635 /* Throttle based on the first usable node */
6636 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006637 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006638 goto out;
6639 break;
6640 }
6641
6642 /* If no zone was usable by the allocation flags then do not throttle */
6643 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006644 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006645
Mel Gorman68243e72012-07-31 16:44:39 -07006646 /* Account for the throttling */
6647 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6648
Mel Gorman55150612012-07-31 16:44:35 -07006649 /*
6650 * If the caller cannot enter the filesystem, it's possible that it
6651 * is due to the caller holding an FS lock or performing a journal
6652 * transaction in the case of a filesystem like ext[3|4]. In this case,
6653 * it is not safe to block on pfmemalloc_wait as kswapd could be
6654 * blocked waiting on the same lock. Instead, throttle for up to a
6655 * second before continuing.
6656 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006657 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006658 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006659 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006660 else
6661 /* Throttle until kswapd wakes the process */
6662 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6663 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006664
Mel Gorman50694c22012-11-26 16:29:48 -08006665 if (fatal_signal_pending(current))
6666 return true;
6667
6668out:
6669 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006670}
6671
Mel Gormandac1d272008-04-28 02:12:12 -07006672unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006673 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006674{
Mel Gorman33906bc2010-08-09 17:19:16 -07006675 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006676 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006677 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006678 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006679 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006680 .order = order,
6681 .nodemask = nodemask,
6682 .priority = DEF_PRIORITY,
6683 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006684 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006685 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006686 };
6687
Mel Gorman55150612012-07-31 16:44:35 -07006688 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006689 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6690 * Confirm they are large enough for max values.
6691 */
6692 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6693 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6694 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6695
6696 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006697 * Do not enter reclaim if fatal signal was delivered while throttled.
6698 * 1 is returned so that the page allocator does not OOM kill at this
6699 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006700 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006701 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006702 return 1;
6703
Andrew Morton1732d2b012019-07-16 16:26:15 -07006704 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006705 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006706
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006707 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006708
6709 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006710 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006711
6712 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006713}
6714
Andrew Mortonc255a452012-07-31 16:43:02 -07006715#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006716
Michal Hockod2e5fb92019-08-30 16:04:50 -07006717/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006718unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006719 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006720 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006721 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006722{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006723 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006724 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006725 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006726 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006727 .may_writepage = !laptop_mode,
6728 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006729 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006730 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006731 };
Ying Han0ae5e892011-05-26 16:25:25 -07006732
Michal Hockod2e5fb92019-08-30 16:04:50 -07006733 WARN_ON_ONCE(!current->reclaim_state);
6734
Balbir Singh4e416952009-09-23 15:56:39 -07006735 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6736 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006737
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006738 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006739 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006740
Balbir Singh4e416952009-09-23 15:56:39 -07006741 /*
6742 * NOTE: Although we can get the priority field, using it
6743 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006744 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006745 * will pick up pages from other mem cgroup's as well. We hack
6746 * the priority and make it zero.
6747 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006748 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006749
6750 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6751
Ying Han0ae5e892011-05-26 16:25:25 -07006752 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006753
Balbir Singh4e416952009-09-23 15:56:39 -07006754 return sc.nr_reclaimed;
6755}
6756
Johannes Weiner72835c82012-01-12 17:18:32 -08006757unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006758 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006759 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006760 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08006761{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006762 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006763 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006764 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006765 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006766 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006767 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006768 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006769 .target_mem_cgroup = memcg,
6770 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006771 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006772 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006773 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07006774 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006775 /*
6776 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6777 * equal pressure on all the nodes. This is based on the assumption that
6778 * the reclaim does not bail out early.
6779 */
6780 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006781
Andrew Morton1732d2b012019-07-16 16:26:15 -07006782 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006783 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006784 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006785
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006786 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006787
Vlastimil Babka499118e2017-05-08 15:59:50 -07006788 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006789 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006790 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006791
6792 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006793}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006794EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006795#endif
6796
Yu Zhao37397872022-09-18 02:00:03 -06006797static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006798{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006799 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006800 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006801
Yu Zhao37397872022-09-18 02:00:03 -06006802 if (lru_gen_enabled()) {
6803 lru_gen_age_node(pgdat, sc);
6804 return;
6805 }
6806
Dave Hansen2f368a92021-09-02 14:59:23 -07006807 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006808 return;
6809
Johannes Weinerb91ac372019-11-30 17:56:02 -08006810 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6811 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6812 return;
6813
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006814 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6815 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006816 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6817 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6818 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006819 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6820 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006821}
6822
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006823static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006824{
6825 int i;
6826 struct zone *zone;
6827
6828 /*
6829 * Check for watermark boosts top-down as the higher zones
6830 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006831 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006832 * start prematurely when there is no boosting and a lower
6833 * zone is balanced.
6834 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006835 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006836 zone = pgdat->node_zones + i;
6837 if (!managed_zone(zone))
6838 continue;
6839
6840 if (zone->watermark_boost)
6841 return true;
6842 }
6843
6844 return false;
6845}
6846
Mel Gormane716f2e2017-05-03 14:53:45 -07006847/*
6848 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006849 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006850 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006851static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006852{
Mel Gormane716f2e2017-05-03 14:53:45 -07006853 int i;
6854 unsigned long mark = -1;
6855 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006856
Mel Gorman1c308442018-12-28 00:35:52 -08006857 /*
6858 * Check watermarks bottom-up as lower zones are more likely to
6859 * meet watermarks.
6860 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006861 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006862 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006863
Mel Gormane716f2e2017-05-03 14:53:45 -07006864 if (!managed_zone(zone))
6865 continue;
6866
6867 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006868 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006869 return true;
6870 }
6871
6872 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006873 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006874 * need balancing by definition. This can happen if a zone-restricted
6875 * allocation tries to wake a remote kswapd.
6876 */
6877 if (mark == -1)
6878 return true;
6879
6880 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006881}
6882
Mel Gorman631b6e02017-05-03 14:53:41 -07006883/* Clear pgdat state for congested, dirty or under writeback. */
6884static void clear_pgdat_congested(pg_data_t *pgdat)
6885{
Johannes Weiner1b051172019-11-30 17:55:52 -08006886 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6887
6888 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006889 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6890 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6891}
6892
Mel Gorman1741c872011-01-13 15:46:21 -08006893/*
Mel Gorman55150612012-07-31 16:44:35 -07006894 * Prepare kswapd for sleeping. This verifies that there are no processes
6895 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6896 *
6897 * Returns true if kswapd is ready to sleep
6898 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006899static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6900 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006901{
Mel Gorman55150612012-07-31 16:44:35 -07006902 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006903 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006904 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006905 * race between when kswapd checks the watermarks and a process gets
6906 * throttled. There is also a potential race if processes get
6907 * throttled, kswapd wakes, a large process exits thereby balancing the
6908 * zones, which causes kswapd to exit balance_pgdat() before reaching
6909 * the wake up checks. If kswapd is going to sleep, no process should
6910 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6911 * the wake up is premature, processes will wake kswapd and get
6912 * throttled again. The difference from wake ups in balance_pgdat() is
6913 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006914 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006915 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6916 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006917
Johannes Weinerc73322d2017-05-03 14:51:51 -07006918 /* Hopeless node, leave it to direct reclaim */
6919 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6920 return true;
6921
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006922 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006923 clear_pgdat_congested(pgdat);
6924 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006925 }
6926
Shantanu Goel333b0a42017-05-03 14:53:38 -07006927 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006928}
6929
Linus Torvalds1da177e2005-04-16 15:20:36 -07006930/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006931 * kswapd shrinks a node of pages that are at or below the highest usable
6932 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006933 *
6934 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006935 * reclaim or if the lack of progress was due to pages under writeback.
6936 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006937 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006938static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006939 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006940{
Mel Gorman1d82de62016-07-28 15:45:43 -07006941 struct zone *zone;
6942 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006943
Mel Gorman1d82de62016-07-28 15:45:43 -07006944 /* Reclaim a number of pages proportional to the number of zones */
6945 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006946 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006947 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006948 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006949 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006950
Mel Gorman1d82de62016-07-28 15:45:43 -07006951 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006952 }
6953
Mel Gorman1d82de62016-07-28 15:45:43 -07006954 /*
6955 * Historically care was taken to put equal pressure on all zones but
6956 * now pressure is applied based on node LRU order.
6957 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006958 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006959
6960 /*
6961 * Fragmentation may mean that the system cannot be rebalanced for
6962 * high-order allocations. If twice the allocation size has been
6963 * reclaimed then recheck watermarks only at order-0 to prevent
6964 * excessive reclaim. Assume that a process requested a high-order
6965 * can direct reclaim/compact.
6966 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006967 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006968 sc->order = 0;
6969
Mel Gormanb8e83b92013-07-03 15:01:45 -07006970 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006971}
6972
Mel Gormanc49c2c42021-06-28 19:42:21 -07006973/* Page allocator PCP high watermark is lowered if reclaim is active. */
6974static inline void
6975update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6976{
6977 int i;
6978 struct zone *zone;
6979
6980 for (i = 0; i <= highest_zoneidx; i++) {
6981 zone = pgdat->node_zones + i;
6982
6983 if (!managed_zone(zone))
6984 continue;
6985
6986 if (active)
6987 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6988 else
6989 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6990 }
6991}
6992
6993static inline void
6994set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6995{
6996 update_reclaim_active(pgdat, highest_zoneidx, true);
6997}
6998
6999static inline void
7000clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7001{
7002 update_reclaim_active(pgdat, highest_zoneidx, false);
7003}
7004
Mel Gorman75485362013-07-03 15:01:42 -07007005/*
Mel Gorman1d82de62016-07-28 15:45:43 -07007006 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
7007 * that are eligible for use by the caller until at least one zone is
7008 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007009 *
Mel Gorman1d82de62016-07-28 15:45:43 -07007010 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007011 *
7012 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07007013 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08007014 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07007015 * or lower is eligible for reclaim until at least one usable zone is
7016 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007017 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007018static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007019{
Linus Torvalds1da177e2005-04-16 15:20:36 -07007020 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07007021 unsigned long nr_soft_reclaimed;
7022 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07007023 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08007024 unsigned long nr_boost_reclaim;
7025 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
7026 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07007027 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08007028 struct scan_control sc = {
7029 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07007030 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07007031 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08007032 };
Omar Sandoval93781322018-06-07 17:07:02 -07007033
Andrew Morton1732d2b012019-07-16 16:26:15 -07007034 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07007035 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007036 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007037
Christoph Lameterf8891e52006-06-30 01:55:45 -07007038 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007039
Mel Gorman1c308442018-12-28 00:35:52 -08007040 /*
7041 * Account for the reclaim boost. Note that the zone boost is left in
7042 * place so that parallel allocations that are near the watermark will
7043 * stall or direct reclaim until kswapd is finished.
7044 */
7045 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007046 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08007047 zone = pgdat->node_zones + i;
7048 if (!managed_zone(zone))
7049 continue;
7050
7051 nr_boost_reclaim += zone->watermark_boost;
7052 zone_boosts[i] = zone->watermark_boost;
7053 }
7054 boosted = nr_boost_reclaim;
7055
7056restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07007057 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007058 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007059 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07007060 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07007061 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08007062 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07007063 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07007064
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007065 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007066
Mel Gorman86c79f62016-07-28 15:45:59 -07007067 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07007068 * If the number of buffer_heads exceeds the maximum allowed
7069 * then consider reclaiming from all zones. This has a dual
7070 * purpose -- on 64-bit systems it is expected that
7071 * buffer_heads are stripped during active rotation. On 32-bit
7072 * systems, highmem pages can pin lowmem memory and shrinking
7073 * buffers can relieve lowmem pressure. Reclaim may still not
7074 * go ahead if all eligible zones for the original allocation
7075 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07007076 */
7077 if (buffer_heads_over_limit) {
7078 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
7079 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07007080 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07007081 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007082
Mel Gorman970a39a2016-07-28 15:46:35 -07007083 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08007084 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007085 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07007086 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08007087
Mel Gorman86c79f62016-07-28 15:45:59 -07007088 /*
Mel Gorman1c308442018-12-28 00:35:52 -08007089 * If the pgdat is imbalanced then ignore boosting and preserve
7090 * the watermarks for a later time and restart. Note that the
7091 * zone watermarks will be still reset at the end of balancing
7092 * on the grounds that the normal reclaim should be enough to
7093 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07007094 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007095 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007096 if (!balanced && nr_boost_reclaim) {
7097 nr_boost_reclaim = 0;
7098 goto restart;
7099 }
7100
7101 /*
7102 * If boosting is not active then only reclaim if there are no
7103 * eligible zones. Note that sc.reclaim_idx is not used as
7104 * buffer_heads_over_limit may have adjusted it.
7105 */
7106 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07007107 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08007108
Mel Gorman1c308442018-12-28 00:35:52 -08007109 /* Limit the priority of boosting to avoid reclaim writeback */
7110 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
7111 raise_priority = false;
7112
7113 /*
7114 * Do not writeback or swap pages for boosted reclaim. The
7115 * intent is to relieve pressure not issue sub-optimal IO
7116 * from reclaim context. If no pages are reclaimed, the
7117 * reclaim will be aborted.
7118 */
7119 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
7120 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08007121
Linus Torvalds1da177e2005-04-16 15:20:36 -07007122 /*
Yu Zhao37397872022-09-18 02:00:03 -06007123 * Do some background aging, to give pages a chance to be
7124 * referenced before reclaiming. All pages are rotated
7125 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07007126 */
Yu Zhao37397872022-09-18 02:00:03 -06007127 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07007128
7129 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007130 * If we're getting trouble reclaiming, start doing writepage
7131 * even in laptop mode.
7132 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07007133 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007134 sc.may_writepage = 1;
7135
Mel Gorman1d82de62016-07-28 15:45:43 -07007136 /* Call soft limit reclaim before calling shrink_node. */
7137 sc.nr_scanned = 0;
7138 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07007139 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07007140 sc.gfp_mask, &nr_soft_scanned);
7141 sc.nr_reclaimed += nr_soft_reclaimed;
7142
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007143 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07007144 * There should be no need to raise the scanning priority if
7145 * enough pages are already being scanned that that high
7146 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007147 */
Mel Gorman970a39a2016-07-28 15:46:35 -07007148 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07007149 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07007150
7151 /*
7152 * If the low watermark is met there is no need for processes
7153 * to be throttled on pfmemalloc_wait as they should not be
7154 * able to safely make forward progress. Wake them
7155 */
7156 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07007157 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08007158 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07007159
Mel Gormanb8e83b92013-07-03 15:01:45 -07007160 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007161 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007162 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007163 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007164 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07007165 break;
7166
7167 /*
7168 * Raise priority if scanning rate is too low or there was no
7169 * progress in reclaiming pages
7170 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07007171 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08007172 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
7173
7174 /*
7175 * If reclaim made no progress for a boost, stop reclaim as
7176 * IO cannot be queued and it could be an infinite loop in
7177 * extreme circumstances.
7178 */
7179 if (nr_boost_reclaim && !nr_reclaimed)
7180 break;
7181
Johannes Weinerc73322d2017-05-03 14:51:51 -07007182 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07007183 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07007184 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007185
Johannes Weinerc73322d2017-05-03 14:51:51 -07007186 if (!sc.nr_reclaimed)
7187 pgdat->kswapd_failures++;
7188
Mel Gormanb8e83b92013-07-03 15:01:45 -07007189out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07007190 clear_reclaim_active(pgdat, highest_zoneidx);
7191
Mel Gorman1c308442018-12-28 00:35:52 -08007192 /* If reclaim was boosted, account for the reclaim done in this pass */
7193 if (boosted) {
7194 unsigned long flags;
7195
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007196 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08007197 if (!zone_boosts[i])
7198 continue;
7199
7200 /* Increments are under the zone lock */
7201 zone = pgdat->node_zones + i;
7202 spin_lock_irqsave(&zone->lock, flags);
7203 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7204 spin_unlock_irqrestore(&zone->lock, flags);
7205 }
7206
7207 /*
7208 * As there is now likely space, wakeup kcompact to defragment
7209 * pageblocks.
7210 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007211 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007212 }
7213
Johannes Weiner2a2e4882017-05-03 14:55:03 -07007214 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007215 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07007216 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07007217 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07007218
Mel Gorman0abdee22011-01-13 15:46:22 -08007219 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07007220 * Return the order kswapd stopped reclaiming at as
7221 * prepare_kswapd_sleep() takes it into account. If another caller
7222 * entered the allocator slow path while kswapd was awake, order will
7223 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08007224 */
Mel Gorman1d82de62016-07-28 15:45:43 -07007225 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007226}
7227
Mel Gormane716f2e2017-05-03 14:53:45 -07007228/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007229 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7230 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7231 * not a valid index then either kswapd runs for first time or kswapd couldn't
7232 * sleep after previous reclaim attempt (node is still unbalanced). In that
7233 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07007234 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007235static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7236 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07007237{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007238 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007239
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007240 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07007241}
7242
Mel Gorman38087d92016-07-28 15:45:49 -07007243static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007244 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007245{
7246 long remaining = 0;
7247 DEFINE_WAIT(wait);
7248
7249 if (freezing(current) || kthread_should_stop())
7250 return;
7251
7252 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7253
Shantanu Goel333b0a42017-05-03 14:53:38 -07007254 /*
7255 * Try to sleep for a short interval. Note that kcompactd will only be
7256 * woken if it is possible to sleep for a short interval. This is
7257 * deliberate on the assumption that if reclaim cannot keep an
7258 * eligible zone balanced that it's also unlikely that compaction will
7259 * succeed.
7260 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007261 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07007262 /*
7263 * Compaction records what page blocks it recently failed to
7264 * isolate pages from and skips them in the future scanning.
7265 * When kswapd is going to sleep, it is reasonable to assume
7266 * that pages and compaction may succeed so reset the cache.
7267 */
7268 reset_isolation_suitable(pgdat);
7269
7270 /*
7271 * We have freed the memory, now we should compact it to make
7272 * allocation of the requested order possible.
7273 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007274 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07007275
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007276 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07007277
7278 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007279 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07007280 * order. The values will either be from a wakeup request or
7281 * the previous request that slept prematurely.
7282 */
7283 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007284 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7285 kswapd_highest_zoneidx(pgdat,
7286 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07007287
7288 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7289 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07007290 }
7291
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007292 finish_wait(&pgdat->kswapd_wait, &wait);
7293 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7294 }
7295
7296 /*
7297 * After a short sleep, check if it was a premature sleep. If not, then
7298 * go fully to sleep until explicitly woken up.
7299 */
Mel Gormand9f21d42016-07-28 15:46:41 -07007300 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007301 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007302 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7303
7304 /*
7305 * vmstat counters are not perfectly accurate and the estimated
7306 * value for counters such as NR_FREE_PAGES can deviate from the
7307 * true value by nr_online_cpus * threshold. To avoid the zone
7308 * watermarks being breached while under pressure, we reduce the
7309 * per-cpu vmstat threshold while kswapd is awake and restore
7310 * them before going back to sleep.
7311 */
7312 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07007313
7314 if (!kthread_should_stop())
7315 schedule();
7316
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007317 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7318 } else {
7319 if (remaining)
7320 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7321 else
7322 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7323 }
7324 finish_wait(&pgdat->kswapd_wait, &wait);
7325}
7326
Linus Torvalds1da177e2005-04-16 15:20:36 -07007327/*
7328 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07007329 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007330 *
7331 * This basically trickles out pages so that we have _some_
7332 * free memory available even if there is no other activity
7333 * that frees anything up. This is needed for things like routing
7334 * etc, where we otherwise might have all activity going on in
7335 * asynchronous contexts that cannot page things out.
7336 *
7337 * If there are applications that are active memory-allocators
7338 * (most normal use), this basically shouldn't matter.
7339 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307340int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007341{
Mel Gormane716f2e2017-05-03 14:53:45 -07007342 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007343 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07007344 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007345 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10307346 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007347
Rusty Russell174596a2009-01-01 10:12:29 +10307348 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07007349 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007350
7351 /*
7352 * Tell the memory management that we're a "memory allocator",
7353 * and that if we need more memory we should get access to it
7354 * regardless (see "__alloc_pages()"). "kswapd" should
7355 * never get caught in the normal page freeing logic.
7356 *
7357 * (Kswapd normally doesn't need memory anyway, but sometimes
7358 * you need a small amount of memory in order to be able to
7359 * page out something else, and this flag essentially protects
7360 * us from recursively trying to free more memory as we're
7361 * trying to free the first piece of memory in the first place).
7362 */
Christoph Lameter930d9152006-01-08 01:00:47 -08007363 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07007364 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07007365
Qian Cai5644e1fb2020-04-01 21:10:12 -07007366 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007367 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007368 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08007369 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07007370
Qian Cai5644e1fb2020-04-01 21:10:12 -07007371 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007372 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7373 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07007374
Mel Gorman38087d92016-07-28 15:45:49 -07007375kswapd_try_sleep:
7376 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007377 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07007378
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007379 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08007380 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007381 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7382 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007383 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007384 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007385
David Rientjes8fe23e02009-12-14 17:58:33 -08007386 ret = try_to_freeze();
7387 if (kthread_should_stop())
7388 break;
7389
7390 /*
7391 * We can speed up thawing tasks if we don't call balance_pgdat
7392 * after returning from the refrigerator
7393 */
Mel Gorman38087d92016-07-28 15:45:49 -07007394 if (ret)
7395 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07007396
Mel Gorman38087d92016-07-28 15:45:49 -07007397 /*
7398 * Reclaim begins at the requested order but if a high-order
7399 * reclaim fails then kswapd falls back to reclaiming for
7400 * order-0. If that happens, kswapd will consider sleeping
7401 * for the order it finished reclaiming at (reclaim_order)
7402 * but kcompactd is woken to compact for the original
7403 * request (alloc_order).
7404 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007405 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007406 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007407 reclaim_order = balance_pgdat(pgdat, alloc_order,
7408 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007409 if (reclaim_order < alloc_order)
7410 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007411 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007412
Johannes Weiner71abdc12014-06-06 14:35:35 -07007413 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007414
Linus Torvalds1da177e2005-04-16 15:20:36 -07007415 return 0;
7416}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307417EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007418
7419/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007420 * A zone is low on free memory or too fragmented for high-order memory. If
7421 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7422 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7423 * has failed or is not needed, still wake up kcompactd if only compaction is
7424 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007425 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007426void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007427 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007428{
7429 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007430 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007431
Mel Gorman6aa303d2016-09-01 16:14:55 -07007432 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007433 return;
7434
David Rientjes5ecd9d42018-04-05 16:25:16 -07007435 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007436 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007437
Qian Cai5644e1fb2020-04-01 21:10:12 -07007438 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007439 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007440
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007441 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7442 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007443
7444 if (READ_ONCE(pgdat->kswapd_order) < order)
7445 WRITE_ONCE(pgdat->kswapd_order, order);
7446
Con Kolivas8d0986e2005-09-13 01:25:07 -07007447 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007448 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007449
David Rientjes5ecd9d42018-04-05 16:25:16 -07007450 /* Hopeless node, leave it to direct reclaim if possible */
7451 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007452 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7453 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007454 /*
7455 * There may be plenty of free memory available, but it's too
7456 * fragmented for high-order allocations. Wake up kcompactd
7457 * and rely on compaction_suitable() to determine if it's
7458 * needed. If it fails, it will defer subsequent attempts to
7459 * ratelimit its work.
7460 */
7461 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007462 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007463 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007464 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007465
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007466 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007467 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007468 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007469}
7470
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007471#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007472/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007473 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007474 * freed pages.
7475 *
7476 * Rather than trying to age LRUs the aim is to preserve the overall
7477 * LRU order by reclaiming preferentially
7478 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007479 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007480unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007481{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007482 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007483 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007484 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007485 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007486 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007487 .may_writepage = 1,
7488 .may_unmap = 1,
7489 .may_swap = 1,
7490 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007491 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007492 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007493 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007494 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007495
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007496 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007497 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007498 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007499
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007500 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007501
Andrew Morton1732d2b012019-07-16 16:26:15 -07007502 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007503 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007504 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007505
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007506 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007507}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007508#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007509
Yasunori Goto3218ae12006-06-27 02:53:33 -07007510/*
7511 * This kswapd start function will be called by init and node-hot-add.
7512 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7513 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007514void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007515{
7516 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307517 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007518
7519 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007520 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007521
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307522 trace_android_vh_kswapd_per_node(nid, &skip, true);
7523 if (skip)
7524 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007525 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7526 if (IS_ERR(pgdat->kswapd)) {
7527 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007528 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007529 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007530 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007531 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007532}
7533
David Rientjes8fe23e02009-12-14 17:58:33 -08007534/*
Jiang Liud8adde12012-07-11 14:01:52 -07007535 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007536 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007537 */
7538void kswapd_stop(int nid)
7539{
7540 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307541 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007542
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307543 trace_android_vh_kswapd_per_node(nid, &skip, false);
7544 if (skip)
7545 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007546 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007547 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007548 NODE_DATA(nid)->kswapd = NULL;
7549 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007550}
7551
Linus Torvalds1da177e2005-04-16 15:20:36 -07007552static int __init kswapd_init(void)
7553{
Wei Yang6b700b52020-04-01 21:10:09 -07007554 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007555
Linus Torvalds1da177e2005-04-16 15:20:36 -07007556 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007557 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007558 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007559 return 0;
7560}
7561
7562module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007563
7564#ifdef CONFIG_NUMA
7565/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007566 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007567 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007568 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007569 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007570 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007571int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007572
Dave Hansen51998362021-02-24 12:09:15 -08007573/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007574 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007575 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7576 * a zone.
7577 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007578#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007579
Christoph Lameter9eeff232006-01-18 17:42:31 -08007580/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007581 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007582 * occur.
7583 */
7584int sysctl_min_unmapped_ratio = 1;
7585
7586/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007587 * If the number of slab pages in a zone grows beyond this percentage then
7588 * slab reclaim needs to occur.
7589 */
7590int sysctl_min_slab_ratio = 5;
7591
Mel Gorman11fb9982016-07-28 15:46:20 -07007592static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007593{
Mel Gorman11fb9982016-07-28 15:46:20 -07007594 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7595 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7596 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007597
7598 /*
7599 * It's possible for there to be more file mapped pages than
7600 * accounted for by the pages on the file LRU lists because
7601 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7602 */
7603 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7604}
7605
7606/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007607static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007608{
Alexandru Moised031a152015-11-05 18:48:08 -08007609 unsigned long nr_pagecache_reclaimable;
7610 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007611
7612 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007613 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007614 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007615 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007616 * a better estimate
7617 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007618 if (node_reclaim_mode & RECLAIM_UNMAP)
7619 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007620 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007621 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007622
7623 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007624 if (!(node_reclaim_mode & RECLAIM_WRITE))
7625 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007626
7627 /* Watch for any possible underflows due to delta */
7628 if (unlikely(delta > nr_pagecache_reclaimable))
7629 delta = nr_pagecache_reclaimable;
7630
7631 return nr_pagecache_reclaimable - delta;
7632}
7633
Christoph Lameter0ff38492006-09-25 23:31:52 -07007634/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007635 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007636 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007637static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007638{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007639 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007640 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007641 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007642 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007643 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007644 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007645 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007646 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007647 .priority = NODE_RECLAIM_PRIORITY,
7648 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7649 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007650 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007651 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007652 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007653 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007654
Yafang Shao132bb8c2019-05-13 17:17:53 -07007655 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7656 sc.gfp_mask);
7657
Christoph Lameter9eeff232006-01-18 17:42:31 -08007658 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007659 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007660 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007661 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007662 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007663 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007664 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007665 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007666 noreclaim_flag = memalloc_noreclaim_save();
7667 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007668 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007669
Mel Gormana5f5f912016-07-28 15:46:32 -07007670 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007671 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007672 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007673 * priorities until we have enough memory freed.
7674 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007675 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007676 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007677 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007678 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007679
Andrew Morton1732d2b012019-07-16 16:26:15 -07007680 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007681 current->flags &= ~PF_SWAPWRITE;
7682 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007683 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007684 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007685
7686 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7687
Rik van Riela79311c2009-01-06 14:40:01 -08007688 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007689}
Andrew Morton179e9632006-03-22 00:08:18 -08007690
Mel Gormana5f5f912016-07-28 15:46:32 -07007691int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007692{
David Rientjesd773ed62007-10-16 23:26:01 -07007693 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007694
7695 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007696 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007697 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007698 *
Christoph Lameter96146342006-07-03 00:24:13 -07007699 * A small portion of unmapped file backed pages is needed for
7700 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007701 * thrown out if the node is overallocated. So we do not reclaim
7702 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007703 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007704 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007705 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007706 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7707 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007708 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007709
7710 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007711 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007712 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007713 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007714 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007715
7716 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007717 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007718 * have associated processors. This will favor the local processor
7719 * over remote processors and spread off node memory allocations
7720 * as wide as possible.
7721 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007722 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7723 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007724
Mel Gormana5f5f912016-07-28 15:46:32 -07007725 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7726 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007727
Mel Gormana5f5f912016-07-28 15:46:32 -07007728 ret = __node_reclaim(pgdat, gfp_mask, order);
7729 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007730
Mel Gorman24cf725182009-06-16 15:33:23 -07007731 if (!ret)
7732 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7733
David Rientjesd773ed62007-10-16 23:26:01 -07007734 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007735}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007736#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007737
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007738/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007739 * check_move_unevictable_pages - check pages for evictability and move to
7740 * appropriate zone lru list
7741 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007742 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007743 * Checks pages for evictability, if an evictable page is in the unevictable
7744 * lru list, moves it to the appropriate evictable lru list. This function
7745 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007746 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007747void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007748{
Alex Shi6168d0d2020-12-15 12:34:29 -08007749 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007750 int pgscanned = 0;
7751 int pgrescued = 0;
7752 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007753
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007754 for (i = 0; i < pvec->nr; i++) {
7755 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007756 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007757
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007758 if (PageTransTail(page))
7759 continue;
7760
7761 nr_pages = thp_nr_pages(page);
7762 pgscanned += nr_pages;
7763
Alex Shid25b5bd2020-12-15 12:34:16 -08007764 /* block memcg migration during page moving between lru */
7765 if (!TestClearPageLRU(page))
7766 continue;
7767
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007768 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007769 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007770 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007771 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007772 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007773 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007774 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007775 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007776 }
Hugh Dickins24513262012-01-20 14:34:21 -08007777
Alex Shi6168d0d2020-12-15 12:34:29 -08007778 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007779 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7780 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007781 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007782 } else if (pgscanned) {
7783 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007784 }
Hugh Dickins850465792012-01-20 14:34:19 -08007785}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007786EXPORT_SYMBOL_GPL(check_move_unevictable_pages);