blob: 7c4c9535ab09c3421c8c04c09c7097bbfeaa2ba9 [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
Yosry Ahmed17bdc392022-07-14 06:49:18 +0000118 /* Proactive reclaim invoked by userspace through memory.reclaim */
119 unsigned int proactive:1;
120
Yisheng Xied6622f62017-05-03 14:53:57 -0700121 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700122 * Cgroup memory below memory.low is protected as long as we
123 * don't threaten to OOM. If any cgroup is reclaimed at
124 * reduced force or passed over entirely due to its memory.low
125 * setting (memcg_low_skipped), and nothing is reclaimed as a
126 * result, then go back for one more cycle that reclaims the protected
127 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700128 */
129 unsigned int memcg_low_reclaim:1;
130 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800131
Johannes Weineree814fe2014-08-06 16:06:19 -0700132 unsigned int hibernation_mode:1;
133
134 /* One of the zones is ready for compaction */
135 unsigned int compaction_ready:1;
136
Johannes Weinerb91ac372019-11-30 17:56:02 -0800137 /* There is easily reclaimable cold cache in the current node */
138 unsigned int cache_trim_mode:1;
139
Johannes Weiner53138ce2019-11-30 17:55:56 -0800140 /* The file pages on the current node are dangerously low */
141 unsigned int file_is_tiny:1;
142
Dave Hansen26aa2d12021-09-02 14:59:16 -0700143 /* Always discard instead of demoting to lower tier memory */
144 unsigned int no_demotion:1;
145
Greg Thelenbb451fd2018-08-17 15:45:19 -0700146 /* Allocation order */
147 s8 order;
148
149 /* Scan (total_size >> priority) pages at once */
150 s8 priority;
151
152 /* The highest zone to isolate pages for reclaim from */
153 s8 reclaim_idx;
154
155 /* This context's GFP mask */
156 gfp_t gfp_mask;
157
Johannes Weineree814fe2014-08-06 16:06:19 -0700158 /* Incremented by the number of inactive pages that were scanned */
159 unsigned long nr_scanned;
160
161 /* Number of pages freed so far during a call to shrink_zones() */
162 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700163
164 struct {
165 unsigned int dirty;
166 unsigned int unqueued_dirty;
167 unsigned int congested;
168 unsigned int writeback;
169 unsigned int immediate;
170 unsigned int file_taken;
171 unsigned int taken;
172 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700173
174 /* for recording the reclaimed slab by now */
175 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700176};
177
Linus Torvalds1da177e2005-04-16 15:20:36 -0700178#ifdef ARCH_HAS_PREFETCHW
179#define prefetchw_prev_lru_page(_page, _base, _field) \
180 do { \
181 if ((_page)->lru.prev != _base) { \
182 struct page *prev; \
183 \
184 prev = lru_to_page(&(_page->lru)); \
185 prefetchw(&prev->_field); \
186 } \
187 } while (0)
188#else
189#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
190#endif
191
192/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700193 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700194 */
195int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700196
Yang Shi0a432dc2019-09-23 15:38:12 -0700197static void set_task_reclaim_state(struct task_struct *task,
198 struct reclaim_state *rs)
199{
200 /* Check for an overwrite */
201 WARN_ON_ONCE(rs && task->reclaim_state);
202
203 /* Check for the nulling of an already-nulled member */
204 WARN_ON_ONCE(!rs && !task->reclaim_state);
205
206 task->reclaim_state = rs;
207}
208
Linus Torvalds1da177e2005-04-16 15:20:36 -0700209static LIST_HEAD(shrinker_list);
210static DECLARE_RWSEM(shrinker_rwsem);
211
Yang Shi0a432dc2019-09-23 15:38:12 -0700212#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700213static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700214
Yang Shi3c6f17e2021-05-04 18:36:33 -0700215/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700216static inline int shrinker_map_size(int nr_items)
217{
218 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
219}
Yang Shi2bfd3632021-05-04 18:36:11 -0700220
Yang Shi3c6f17e2021-05-04 18:36:33 -0700221static inline int shrinker_defer_size(int nr_items)
222{
223 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
224}
225
Yang Shi468ab842021-05-04 18:36:26 -0700226static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
227 int nid)
228{
229 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
230 lockdep_is_held(&shrinker_rwsem));
231}
232
Yang Shie4262c42021-05-04 18:36:23 -0700233static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700234 int map_size, int defer_size,
235 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700236{
Yang Shie4262c42021-05-04 18:36:23 -0700237 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700238 struct mem_cgroup_per_node *pn;
239 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700240 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700241
Yang Shi2bfd3632021-05-04 18:36:11 -0700242 for_each_node(nid) {
243 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700244 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700245 /* Not yet online memcg */
246 if (!old)
247 return 0;
248
249 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
250 if (!new)
251 return -ENOMEM;
252
Yang Shi3c6f17e2021-05-04 18:36:33 -0700253 new->nr_deferred = (atomic_long_t *)(new + 1);
254 new->map = (void *)new->nr_deferred + defer_size;
255
256 /* map: set all old bits, clear all new bits */
257 memset(new->map, (int)0xff, old_map_size);
258 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
259 /* nr_deferred: copy old values, clear all new values */
260 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
261 memset((void *)new->nr_deferred + old_defer_size, 0,
262 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700263
Yang Shie4262c42021-05-04 18:36:23 -0700264 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700265 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700266 }
267
268 return 0;
269}
270
Yang Shie4262c42021-05-04 18:36:23 -0700271void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700272{
273 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700274 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700275 int nid;
276
Yang Shi2bfd3632021-05-04 18:36:11 -0700277 for_each_node(nid) {
278 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700279 info = rcu_dereference_protected(pn->shrinker_info, true);
280 kvfree(info);
281 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700282 }
283}
284
Yang Shie4262c42021-05-04 18:36:23 -0700285int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700286{
Yang Shie4262c42021-05-04 18:36:23 -0700287 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700288 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700289 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700290
Yang Shid27cf2a2021-05-04 18:36:14 -0700291 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700292 map_size = shrinker_map_size(shrinker_nr_max);
293 defer_size = shrinker_defer_size(shrinker_nr_max);
294 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700295 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700296 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
297 if (!info) {
298 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700299 ret = -ENOMEM;
300 break;
301 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700302 info->nr_deferred = (atomic_long_t *)(info + 1);
303 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700304 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700305 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700306 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700307
308 return ret;
309}
310
Yang Shi3c6f17e2021-05-04 18:36:33 -0700311static inline bool need_expand(int nr_max)
312{
313 return round_up(nr_max, BITS_PER_LONG) >
314 round_up(shrinker_nr_max, BITS_PER_LONG);
315}
316
Yang Shie4262c42021-05-04 18:36:23 -0700317static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700318{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700319 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700320 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700321 int map_size, defer_size = 0;
322 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700323 struct mem_cgroup *memcg;
324
Yang Shi3c6f17e2021-05-04 18:36:33 -0700325 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700326 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700327
Yang Shi2bfd3632021-05-04 18:36:11 -0700328 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700329 goto out;
330
331 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700332
Yang Shi3c6f17e2021-05-04 18:36:33 -0700333 map_size = shrinker_map_size(new_nr_max);
334 defer_size = shrinker_defer_size(new_nr_max);
335 old_map_size = shrinker_map_size(shrinker_nr_max);
336 old_defer_size = shrinker_defer_size(shrinker_nr_max);
337
Yang Shi2bfd3632021-05-04 18:36:11 -0700338 memcg = mem_cgroup_iter(NULL, NULL, NULL);
339 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700340 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
341 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700342 if (ret) {
343 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700344 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700345 }
346 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700347out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700348 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700349 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700350
Yang Shi2bfd3632021-05-04 18:36:11 -0700351 return ret;
352}
353
354void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
355{
356 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700357 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700358
359 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700360 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700361 /* Pairs with smp mb in shrink_slab() */
362 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700363 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700364 rcu_read_unlock();
365 }
366}
367
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700368static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700369
370static int prealloc_memcg_shrinker(struct shrinker *shrinker)
371{
372 int id, ret = -ENOMEM;
373
Yang Shi476b30a2021-05-04 18:36:39 -0700374 if (mem_cgroup_disabled())
375 return -ENOSYS;
376
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700377 down_write(&shrinker_rwsem);
378 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700379 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700380 if (id < 0)
381 goto unlock;
382
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700383 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700384 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700385 idr_remove(&shrinker_idr, id);
386 goto unlock;
387 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700388 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700389 shrinker->id = id;
390 ret = 0;
391unlock:
392 up_write(&shrinker_rwsem);
393 return ret;
394}
395
396static void unregister_memcg_shrinker(struct shrinker *shrinker)
397{
398 int id = shrinker->id;
399
400 BUG_ON(id < 0);
401
Yang Shi41ca6682021-05-04 18:36:29 -0700402 lockdep_assert_held(&shrinker_rwsem);
403
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700404 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700405}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700406
Yang Shi86750832021-05-04 18:36:36 -0700407static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
408 struct mem_cgroup *memcg)
409{
410 struct shrinker_info *info;
411
412 info = shrinker_info_protected(memcg, nid);
413 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
414}
415
416static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
417 struct mem_cgroup *memcg)
418{
419 struct shrinker_info *info;
420
421 info = shrinker_info_protected(memcg, nid);
422 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
423}
424
Yang Shia1780152021-05-04 18:36:42 -0700425void reparent_shrinker_deferred(struct mem_cgroup *memcg)
426{
427 int i, nid;
428 long nr;
429 struct mem_cgroup *parent;
430 struct shrinker_info *child_info, *parent_info;
431
432 parent = parent_mem_cgroup(memcg);
433 if (!parent)
434 parent = root_mem_cgroup;
435
436 /* Prevent from concurrent shrinker_info expand */
437 down_read(&shrinker_rwsem);
438 for_each_node(nid) {
439 child_info = shrinker_info_protected(memcg, nid);
440 parent_info = shrinker_info_protected(parent, nid);
441 for (i = 0; i < shrinker_nr_max; i++) {
442 nr = atomic_long_read(&child_info->nr_deferred[i]);
443 atomic_long_add(nr, &parent_info->nr_deferred[i]);
444 }
445 }
446 up_read(&shrinker_rwsem);
447}
448
Johannes Weinerb5ead352019-11-30 17:55:40 -0800449static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800450{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800451 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800452}
Tejun Heo97c93412015-05-22 18:23:36 -0400453
Yu Zhao4fc3ef42022-12-21 21:19:01 -0700454static bool global_reclaim(struct scan_control *sc)
455{
456 return !sc->target_mem_cgroup || mem_cgroup_is_root(sc->target_mem_cgroup);
457}
458
Tejun Heo97c93412015-05-22 18:23:36 -0400459/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800460 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400461 * @sc: scan_control in question
462 *
463 * The normal page dirty throttling mechanism in balance_dirty_pages() is
464 * completely broken with the legacy memcg and direct stalling in
465 * shrink_page_list() is used for throttling instead, which lacks all the
466 * niceties such as fairness, adaptive pausing, bandwidth proportional
467 * allocation and configurability.
468 *
469 * This function tests whether the vmscan currently in progress can assume
470 * that the normal dirty throttling mechanism is operational.
471 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800472static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400473{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800474 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400475 return true;
476#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800477 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400478 return true;
479#endif
480 return false;
481}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800482#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700483static int prealloc_memcg_shrinker(struct shrinker *shrinker)
484{
Yang Shi476b30a2021-05-04 18:36:39 -0700485 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700486}
487
488static void unregister_memcg_shrinker(struct shrinker *shrinker)
489{
490}
491
Yang Shi86750832021-05-04 18:36:36 -0700492static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
493 struct mem_cgroup *memcg)
494{
495 return 0;
496}
497
498static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
499 struct mem_cgroup *memcg)
500{
501 return 0;
502}
503
Johannes Weinerb5ead352019-11-30 17:55:40 -0800504static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800505{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800506 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800507}
Tejun Heo97c93412015-05-22 18:23:36 -0400508
Yu Zhao4fc3ef42022-12-21 21:19:01 -0700509static bool global_reclaim(struct scan_control *sc)
510{
511 return true;
512}
513
Johannes Weinerb5ead352019-11-30 17:55:40 -0800514static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400515{
516 return true;
517}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800518#endif
519
Yang Shi86750832021-05-04 18:36:36 -0700520static long xchg_nr_deferred(struct shrinker *shrinker,
521 struct shrink_control *sc)
522{
523 int nid = sc->nid;
524
525 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
526 nid = 0;
527
528 if (sc->memcg &&
529 (shrinker->flags & SHRINKER_MEMCG_AWARE))
530 return xchg_nr_deferred_memcg(nid, shrinker,
531 sc->memcg);
532
533 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
534}
535
536
537static long add_nr_deferred(long nr, struct shrinker *shrinker,
538 struct shrink_control *sc)
539{
540 int nid = sc->nid;
541
542 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
543 nid = 0;
544
545 if (sc->memcg &&
546 (shrinker->flags & SHRINKER_MEMCG_AWARE))
547 return add_nr_deferred_memcg(nr, nid, shrinker,
548 sc->memcg);
549
550 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
551}
552
Dave Hansen26aa2d12021-09-02 14:59:16 -0700553static bool can_demote(int nid, struct scan_control *sc)
554{
Huang Ying20b51af12021-09-02 14:59:33 -0700555 if (!numa_demotion_enabled)
556 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700557 if (sc) {
558 if (sc->no_demotion)
559 return false;
560 /* It is pointless to do demotion in memcg reclaim */
561 if (cgroup_reclaim(sc))
562 return false;
563 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700564 if (next_demotion_node(nid) == NUMA_NO_NODE)
565 return false;
566
Huang Ying20b51af12021-09-02 14:59:33 -0700567 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700568}
569
Keith Buscha2a36482021-09-02 14:59:26 -0700570static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
571 int nid,
572 struct scan_control *sc)
573{
574 if (memcg == NULL) {
575 /*
576 * For non-memcg reclaim, is there
577 * space in any swap device?
578 */
579 if (get_nr_swap_pages() > 0)
580 return true;
581 } else {
582 /* Is the memcg below its swap limit? */
583 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
584 return true;
585 }
586
587 /*
588 * The page can not be swapped.
589 *
590 * Can it be reclaimed from this node via demotion?
591 */
592 return can_demote(nid, sc);
593}
594
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700595/*
596 * This misses isolated pages which are not accounted for to save counters.
597 * As the data only determines if reclaim or compaction continues, it is
598 * not expected that isolated pages will be a dominating factor.
599 */
600unsigned long zone_reclaimable_pages(struct zone *zone)
601{
602 unsigned long nr;
603
604 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
605 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700606 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700607 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
608 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
609
610 return nr;
611}
612
Michal Hockofd538802017-02-22 15:45:58 -0800613/**
614 * lruvec_lru_size - Returns the number of pages on the given LRU list.
615 * @lruvec: lru vector
616 * @lru: lru to use
617 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
618 */
Yu Zhao20913392021-02-24 12:08:44 -0800619static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
620 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800621{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800622 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800623 int zid;
624
Johannes Weinerde3b0152019-11-30 17:55:31 -0800625 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800626 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800627
Michal Hockofd538802017-02-22 15:45:58 -0800628 if (!managed_zone(zone))
629 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800630
Michal Hockofd538802017-02-22 15:45:58 -0800631 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800632 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800633 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800634 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800635 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800636 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800637}
638
Linus Torvalds1da177e2005-04-16 15:20:36 -0700639/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000640 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700641 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900642int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700643{
Yang Shi476b30a2021-05-04 18:36:39 -0700644 unsigned int size;
645 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000646
Yang Shi476b30a2021-05-04 18:36:39 -0700647 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
648 err = prealloc_memcg_shrinker(shrinker);
649 if (err != -ENOSYS)
650 return err;
651
652 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
653 }
654
655 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000656 if (shrinker->flags & SHRINKER_NUMA_AWARE)
657 size *= nr_node_ids;
658
659 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
660 if (!shrinker->nr_deferred)
661 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700662
Tetsuo Handa8e049442018-04-04 19:53:07 +0900663 return 0;
664}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000665
Tetsuo Handa8e049442018-04-04 19:53:07 +0900666void free_prealloced_shrinker(struct shrinker *shrinker)
667{
Yang Shi41ca6682021-05-04 18:36:29 -0700668 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
669 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700670 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700671 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700672 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700673 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700674
Tetsuo Handa8e049442018-04-04 19:53:07 +0900675 kfree(shrinker->nr_deferred);
676 shrinker->nr_deferred = NULL;
677}
678
679void register_shrinker_prepared(struct shrinker *shrinker)
680{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700681 down_write(&shrinker_rwsem);
682 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700683 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700684 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900685}
686
687int register_shrinker(struct shrinker *shrinker)
688{
689 int err = prealloc_shrinker(shrinker);
690
691 if (err)
692 return err;
693 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000694 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700695}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700696EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700697
698/*
699 * Remove one
700 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700701void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700702{
Yang Shi41ca6682021-05-04 18:36:29 -0700703 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900704 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700705
Linus Torvalds1da177e2005-04-16 15:20:36 -0700706 down_write(&shrinker_rwsem);
707 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700708 shrinker->flags &= ~SHRINKER_REGISTERED;
709 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
710 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700711 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700712
Andrew Vaginae393322013-10-16 13:46:46 -0700713 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900714 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700715}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700716EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700717
718#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000719
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800720static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800721 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700722{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000723 unsigned long freed = 0;
724 unsigned long long delta;
725 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700726 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000727 long nr;
728 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000729 long batch_size = shrinker->batch ? shrinker->batch
730 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800731 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000732
rongqianfeng8da6ee32021-05-21 10:30:14 +0800733 trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
734
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700735 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700736 if (freeable == 0 || freeable == SHRINK_EMPTY)
737 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000738
739 /*
740 * copy the current shrinker scan count into a local variable
741 * and zero it so that other concurrent shrinker invocations
742 * don't also do this scanning work.
743 */
Yang Shi86750832021-05-04 18:36:36 -0700744 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000745
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700746 if (shrinker->seeks) {
747 delta = freeable >> priority;
748 delta *= 4;
749 do_div(delta, shrinker->seeks);
750 } else {
751 /*
752 * These objects don't require any IO to create. Trim
753 * them aggressively under memory pressure to keep
754 * them from causing refetches in the IO caches.
755 */
756 delta = freeable / 2;
757 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700758
Yang Shi18bb4732021-05-04 18:36:45 -0700759 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000760 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700761 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000762
763 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800764 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000765
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800766 /*
767 * Normally, we should not scan less than batch_size objects in one
768 * pass to avoid too frequent shrinker calls, but if the slab has less
769 * than batch_size objects in total and we are really tight on memory,
770 * we will try to reclaim all available objects, otherwise we can end
771 * up failing allocations although there are plenty of reclaimable
772 * objects spread over several slabs with usage less than the
773 * batch_size.
774 *
775 * We detect the "tight on memory" situations by looking at the total
776 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700777 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800778 * scanning at high prio and therefore should try to reclaim as much as
779 * possible.
780 */
781 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700782 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000783 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800784 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000785
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800786 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700787 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000788 ret = shrinker->scan_objects(shrinker, shrinkctl);
789 if (ret == SHRINK_STOP)
790 break;
791 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000792
Chris Wilsond460acb2017-09-06 16:19:26 -0700793 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
794 total_scan -= shrinkctl->nr_scanned;
795 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000796
797 cond_resched();
798 }
799
Yang Shi18bb4732021-05-04 18:36:45 -0700800 /*
801 * The deferred work is increased by any new work (delta) that wasn't
802 * done, decreased by old deferred work that was done now.
803 *
804 * And it is capped to two times of the freeable items.
805 */
806 next_deferred = max_t(long, (nr + delta - scanned), 0);
807 next_deferred = min(next_deferred, (2 * freeable));
808
Glauber Costa1d3d4432013-08-28 10:18:04 +1000809 /*
810 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700811 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000812 */
Yang Shi86750832021-05-04 18:36:36 -0700813 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000814
Yang Shi8efb4b52021-05-04 18:36:08 -0700815 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000816 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700817}
818
Yang Shi0a432dc2019-09-23 15:38:12 -0700819#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700820static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
821 struct mem_cgroup *memcg, int priority)
822{
Yang Shie4262c42021-05-04 18:36:23 -0700823 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700824 unsigned long ret, freed = 0;
825 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700826
Yang Shi0a432dc2019-09-23 15:38:12 -0700827 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700828 return 0;
829
830 if (!down_read_trylock(&shrinker_rwsem))
831 return 0;
832
Yang Shi468ab842021-05-04 18:36:26 -0700833 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700834 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700835 goto unlock;
836
Yang Shie4262c42021-05-04 18:36:23 -0700837 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700838 struct shrink_control sc = {
839 .gfp_mask = gfp_mask,
840 .nid = nid,
841 .memcg = memcg,
842 };
843 struct shrinker *shrinker;
844
845 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700846 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700847 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700848 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700849 continue;
850 }
851
Yang Shi0a432dc2019-09-23 15:38:12 -0700852 /* Call non-slab shrinkers even though kmem is disabled */
853 if (!memcg_kmem_enabled() &&
854 !(shrinker->flags & SHRINKER_NONSLAB))
855 continue;
856
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700857 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700858 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700859 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700860 /*
861 * After the shrinker reported that it had no objects to
862 * free, but before we cleared the corresponding bit in
863 * the memcg shrinker map, a new object might have been
864 * added. To make sure, we have the bit set in this
865 * case, we invoke the shrinker one more time and reset
866 * the bit if it reports that it is not empty anymore.
867 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700868 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700869 *
870 * list_lru_add() shrink_slab_memcg()
871 * list_add_tail() clear_bit()
872 * <MB> <MB>
873 * set_bit() do_shrink_slab()
874 */
875 smp_mb__after_atomic();
876 ret = do_shrink_slab(&sc, shrinker, priority);
877 if (ret == SHRINK_EMPTY)
878 ret = 0;
879 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700880 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700881 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700882 freed += ret;
883
884 if (rwsem_is_contended(&shrinker_rwsem)) {
885 freed = freed ? : 1;
886 break;
887 }
888 }
889unlock:
890 up_read(&shrinker_rwsem);
891 return freed;
892}
Yang Shi0a432dc2019-09-23 15:38:12 -0700893#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700894static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
895 struct mem_cgroup *memcg, int priority)
896{
897 return 0;
898}
Yang Shi0a432dc2019-09-23 15:38:12 -0700899#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700900
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800901/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800902 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800903 * @gfp_mask: allocation context
904 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800905 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800906 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700907 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800908 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700909 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800910 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
911 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700912 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700913 * @memcg specifies the memory cgroup to target. Unaware shrinkers
914 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800915 *
Josef Bacik9092c712018-01-31 16:16:26 -0800916 * @priority is sc->priority, we take the number of objects and >> by priority
917 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700918 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800919 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700920 */
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800921unsigned long shrink_slab(gfp_t gfp_mask, int nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800922 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800923 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700924{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700925 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700926 struct shrinker *shrinker;
wudean842c68a2021-04-27 17:40:41 +0800927 bool bypass = false;
928
929 trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
930 if (bypass)
931 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700932
Yang Shifa1e5122019-08-02 21:48:44 -0700933 /*
934 * The root memcg might be allocated even though memcg is disabled
935 * via "cgroup_disable=memory" boot parameter. This could make
936 * mem_cgroup_is_root() return false, then just run memcg slab
937 * shrink, but skip global shrink. This may result in premature
938 * oom.
939 */
940 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700941 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800942
Tetsuo Handae830c632018-04-05 16:23:35 -0700943 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700944 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700945
946 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800947 struct shrink_control sc = {
948 .gfp_mask = gfp_mask,
949 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800950 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800951 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800952
Kirill Tkhai9b996462018-08-17 15:48:21 -0700953 ret = do_shrink_slab(&sc, shrinker, priority);
954 if (ret == SHRINK_EMPTY)
955 ret = 0;
956 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800957 /*
958 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700959 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800960 * by parallel ongoing shrinking.
961 */
962 if (rwsem_is_contended(&shrinker_rwsem)) {
963 freed = freed ? : 1;
964 break;
965 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700966 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800967
Linus Torvalds1da177e2005-04-16 15:20:36 -0700968 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700969out:
970 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000971 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700972}
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800973EXPORT_SYMBOL_GPL(shrink_slab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700974
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800975void drop_slab_node(int nid)
976{
977 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700978 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800979
980 do {
981 struct mem_cgroup *memcg = NULL;
982
Chunxin Zang069c4112020-10-13 16:56:46 -0700983 if (fatal_signal_pending(current))
984 return;
985
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800986 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700987 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800988 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800989 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800990 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700991 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800992}
993
994void drop_slab(void)
995{
996 int nid;
997
998 for_each_online_node(nid)
999 drop_slab_node(nid);
1000}
1001
Linus Torvalds1da177e2005-04-16 15:20:36 -07001002static inline int is_page_cache_freeable(struct page *page)
1003{
Johannes Weinerceddc3a2009-09-21 17:03:00 -07001004 /*
1005 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -04001006 * that isolated the page, the page cache and optional buffer
1007 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -07001008 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -07001009 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -04001010 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001011}
1012
Yang Shicb165562019-11-30 17:55:28 -08001013static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001014{
Christoph Lameter930d9152006-01-08 01:00:47 -08001015 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001016 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001017 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001018 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001019 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001020 return 1;
1021 return 0;
1022}
1023
1024/*
1025 * We detected a synchronous write error writing a page out. Probably
1026 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1027 * fsync(), msync() or close().
1028 *
1029 * The tricky part is that after writepage we cannot touch the mapping: nothing
1030 * prevents it from being freed up. But we have a ref on the page and once
1031 * that page is locked, the mapping is pinned.
1032 *
1033 * We're allowed to run sleeping lock_page() here because we know the caller has
1034 * __GFP_FS.
1035 */
1036static void handle_write_error(struct address_space *mapping,
1037 struct page *page, int error)
1038{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001039 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001040 if (page_mapping(page) == mapping)
1041 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001042 unlock_page(page);
1043}
1044
Christoph Lameter04e62a22006-06-23 02:03:38 -07001045/* possible outcome of pageout() */
1046typedef enum {
1047 /* failed to write page out, page is locked */
1048 PAGE_KEEP,
1049 /* move page to the active list, page is locked */
1050 PAGE_ACTIVATE,
1051 /* page has been sent to the disk successfully, page is unlocked */
1052 PAGE_SUCCESS,
1053 /* page is clean and locked */
1054 PAGE_CLEAN,
1055} pageout_t;
1056
Linus Torvalds1da177e2005-04-16 15:20:36 -07001057/*
Andrew Morton1742f192006-03-22 00:08:21 -08001058 * pageout is called by shrink_page_list() for each dirty page.
1059 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001060 */
Yang Shicb165562019-11-30 17:55:28 -08001061static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001062{
1063 /*
1064 * If the page is dirty, only perform writeback if that write
1065 * will be non-blocking. To prevent this allocation from being
1066 * stalled by pagecache activity. But note that there may be
1067 * stalls if we need to run get_block(). We could test
1068 * PagePrivate for that.
1069 *
Al Viro81742022014-04-03 03:17:43 -04001070 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001071 * this page's queue, we can perform writeback even if that
1072 * will block.
1073 *
1074 * If the page is swapcache, write it back even if that would
1075 * block, for some throttling. This happens by accident, because
1076 * swap_backing_dev_info is bust: it doesn't reflect the
1077 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001078 */
1079 if (!is_page_cache_freeable(page))
1080 return PAGE_KEEP;
1081 if (!mapping) {
1082 /*
1083 * Some data journaling orphaned pages can have
1084 * page->mapping == NULL while being dirty with clean buffers.
1085 */
David Howells266cf652009-04-03 16:42:36 +01001086 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001087 if (try_to_free_buffers(page)) {
1088 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001089 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001090 return PAGE_CLEAN;
1091 }
1092 }
1093 return PAGE_KEEP;
1094 }
1095 if (mapping->a_ops->writepage == NULL)
1096 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001097 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001098 return PAGE_KEEP;
1099
1100 if (clear_page_dirty_for_io(page)) {
1101 int res;
1102 struct writeback_control wbc = {
1103 .sync_mode = WB_SYNC_NONE,
1104 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001105 .range_start = 0,
1106 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001107 .for_reclaim = 1,
1108 };
1109
1110 SetPageReclaim(page);
1111 res = mapping->a_ops->writepage(page, &wbc);
1112 if (res < 0)
1113 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001114 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001115 ClearPageReclaim(page);
1116 return PAGE_ACTIVATE;
1117 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001118
Linus Torvalds1da177e2005-04-16 15:20:36 -07001119 if (!PageWriteback(page)) {
1120 /* synchronous write or broken a_ops? */
1121 ClearPageReclaim(page);
1122 }
yalin wang3aa23852016-01-14 15:18:30 -08001123 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001124 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001125 return PAGE_SUCCESS;
1126 }
1127
1128 return PAGE_CLEAN;
1129}
1130
Andrew Mortona649fd92006-10-17 00:09:36 -07001131/*
Nick Piggine2867812008-07-25 19:45:30 -07001132 * Same as remove_mapping, but if the page is removed from the mapping, it
1133 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001134 */
Johannes Weinera5289102014-04-03 14:47:51 -07001135static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001136 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001137{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001138 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001139 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001140
Nick Piggin28e4d962006-09-25 23:31:23 -07001141 BUG_ON(!PageLocked(page));
1142 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001143
Johannes Weiner30472502021-09-02 14:53:18 -07001144 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001145 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001146 * The non racy check for a busy page.
1147 *
1148 * Must be careful with the order of the tests. When someone has
1149 * a ref to the page, it may be possible that they dirty it then
1150 * drop the reference. So if PageDirty is tested before page_count
1151 * here, then the following race may occur:
1152 *
1153 * get_user_pages(&page);
1154 * [user mapping goes away]
1155 * write_to(page);
1156 * !PageDirty(page) [good]
1157 * SetPageDirty(page);
1158 * put_page(page);
1159 * !page_count(page) [good, discard it]
1160 *
1161 * [oops, our write_to data is lost]
1162 *
1163 * Reversing the order of the tests ensures such a situation cannot
1164 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001165 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001166 *
1167 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001168 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001169 */
William Kucharski906d2782019-10-18 20:20:33 -07001170 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001171 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001172 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001173 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001174 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001175 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001176 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001177 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001178
1179 if (PageSwapCache(page)) {
1180 swp_entry_t swap = { .val = page_private(page) };
Yu Zhao37397872022-09-18 02:00:03 -06001181
1182 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001183 if (reclaimed && !mapping_exiting(mapping))
1184 shadow = workingset_eviction(page, target_memcg);
Yu Zhao37397872022-09-18 02:00:03 -06001185 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001186 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001187 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001188 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001189 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001190 void (*freepage)(struct page *);
1191
1192 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001193 /*
1194 * Remember a shadow entry for reclaimed file cache in
1195 * order to detect refaults, thus thrashing, later on.
1196 *
1197 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001198 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001199 * inode reclaim needs to empty out the radix tree or
1200 * the nodes are lost. Don't plant shadows behind its
1201 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001202 *
1203 * We also don't store shadows for DAX mappings because the
1204 * only page cache pages found in these are zero pages
1205 * covering holes, and because we don't want to mix DAX
1206 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001207 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001208 */
Huang Ying9de4f222020-04-06 20:04:41 -07001209 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001210 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001211 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001212 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001213 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001214
1215 if (freepage != NULL)
1216 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001217 }
1218
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001219 return 1;
1220
1221cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001222 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001223 return 0;
1224}
1225
Linus Torvalds1da177e2005-04-16 15:20:36 -07001226/*
Nick Piggine2867812008-07-25 19:45:30 -07001227 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1228 * someone else has a ref on the page, abort and return 0. If it was
1229 * successfully detached, return 1. Assumes the caller has a single ref on
1230 * this page.
1231 */
1232int remove_mapping(struct address_space *mapping, struct page *page)
1233{
Johannes Weinerb9107182019-11-30 17:55:59 -08001234 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001235 /*
1236 * Unfreezing the refcount with 1 rather than 2 effectively
1237 * drops the pagecache ref for us without requiring another
1238 * atomic operation.
1239 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001240 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001241 return 1;
1242 }
1243 return 0;
1244}
1245
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001246/**
1247 * putback_lru_page - put previously isolated page onto appropriate LRU list
1248 * @page: page to be put back to appropriate lru list
1249 *
1250 * Add previously isolated @page to appropriate LRU list.
1251 * Page may still be unevictable for other reasons.
1252 *
1253 * lru_lock must not be held, interrupts must be enabled.
1254 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001255void putback_lru_page(struct page *page)
1256{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001257 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001258 put_page(page); /* drop ref from isolate */
1259}
1260
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001261enum page_references {
1262 PAGEREF_RECLAIM,
1263 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001264 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001265 PAGEREF_ACTIVATE,
1266};
1267
1268static enum page_references page_check_references(struct page *page,
1269 struct scan_control *sc)
1270{
Johannes Weiner645747462010-03-05 13:42:22 -08001271 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001272 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001273
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001274 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1275 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001276 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001277
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001278 /*
1279 * Mlock lost the isolation race with us. Let try_to_unmap()
1280 * move the page to the unevictable list.
1281 */
1282 if (vm_flags & VM_LOCKED)
1283 return PAGEREF_RECLAIM;
1284
Minchan Kimf74aca72022-05-19 14:08:54 -07001285 /* rmap lock contention: rotate */
1286 if (referenced_ptes == -1)
1287 return PAGEREF_KEEP;
1288
Johannes Weiner645747462010-03-05 13:42:22 -08001289 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001290 /*
1291 * All mapped pages start out with page table
1292 * references from the instantiating fault, so we need
1293 * to look twice if a mapped file page is used more
1294 * than once.
1295 *
1296 * Mark it and spare it for another trip around the
1297 * inactive list. Another page table reference will
1298 * lead to its activation.
1299 *
1300 * Note: the mark is set for activated pages as well
1301 * so that recently deactivated but used pages are
1302 * quickly recovered.
1303 */
1304 SetPageReferenced(page);
1305
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001306 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001307 return PAGEREF_ACTIVATE;
1308
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001309 /*
1310 * Activate file-backed executable pages after first usage.
1311 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001312 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001313 return PAGEREF_ACTIVATE;
1314
Johannes Weiner645747462010-03-05 13:42:22 -08001315 return PAGEREF_KEEP;
1316 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001317
1318 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001319 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001320 return PAGEREF_RECLAIM_CLEAN;
1321
1322 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001323}
1324
Mel Gormane2be15f2013-07-03 15:01:57 -07001325/* Check if a page is dirty or under writeback */
1326static void page_check_dirty_writeback(struct page *page,
1327 bool *dirty, bool *writeback)
1328{
Mel Gormanb4597222013-07-03 15:02:05 -07001329 struct address_space *mapping;
1330
Mel Gormane2be15f2013-07-03 15:01:57 -07001331 /*
1332 * Anonymous pages are not handled by flushers and must be written
1333 * from reclaim context. Do not stall reclaim based on them
1334 */
Huang Ying9de4f222020-04-06 20:04:41 -07001335 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001336 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001337 *dirty = false;
1338 *writeback = false;
1339 return;
1340 }
1341
1342 /* By default assume that the page flags are accurate */
1343 *dirty = PageDirty(page);
1344 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001345
1346 /* Verify dirty/writeback state if the filesystem supports it */
1347 if (!page_has_private(page))
1348 return;
1349
1350 mapping = page_mapping(page);
1351 if (mapping && mapping->a_ops->is_dirty_writeback)
1352 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001353}
1354
Dave Hansen26aa2d12021-09-02 14:59:16 -07001355static struct page *alloc_demote_page(struct page *page, unsigned long node)
1356{
1357 struct migration_target_control mtc = {
1358 /*
1359 * Allocate from 'node', or fail quickly and quietly.
1360 * When this happens, 'page' will likely just be discarded
1361 * instead of migrated.
1362 */
1363 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1364 __GFP_THISNODE | __GFP_NOWARN |
1365 __GFP_NOMEMALLOC | GFP_NOWAIT,
1366 .nid = node
1367 };
1368
1369 return alloc_migration_target(page, (unsigned long)&mtc);
1370}
1371
1372/*
1373 * Take pages on @demote_list and attempt to demote them to
1374 * another node. Pages which are not demoted are left on
1375 * @demote_pages.
1376 */
1377static unsigned int demote_page_list(struct list_head *demote_pages,
1378 struct pglist_data *pgdat)
1379{
1380 int target_nid = next_demotion_node(pgdat->node_id);
1381 unsigned int nr_succeeded;
1382 int err;
1383
1384 if (list_empty(demote_pages))
1385 return 0;
1386
1387 if (target_nid == NUMA_NO_NODE)
1388 return 0;
1389
1390 /* Demotion ignores all cpuset and mempolicy settings */
1391 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1392 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1393 &nr_succeeded);
1394
Yang Shi668e4142021-09-02 14:59:19 -07001395 if (current_is_kswapd())
1396 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1397 else
1398 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1399
Dave Hansen26aa2d12021-09-02 14:59:16 -07001400 return nr_succeeded;
1401}
1402
Nick Piggine2867812008-07-25 19:45:30 -07001403/*
Andrew Morton1742f192006-03-22 00:08:21 -08001404 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001405 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001406static unsigned int shrink_page_list(struct list_head *page_list,
1407 struct pglist_data *pgdat,
1408 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001409 struct reclaim_stat *stat,
1410 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001411{
1412 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001413 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001414 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001415 unsigned int nr_reclaimed = 0;
1416 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001417 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001418
Kirill Tkhai060f0052019-03-05 15:48:15 -08001419 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001420 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001421 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001422
Dave Hansen26aa2d12021-09-02 14:59:16 -07001423retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001424 while (!list_empty(page_list)) {
1425 struct address_space *mapping;
1426 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001427 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001428 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001429 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001430
1431 cond_resched();
1432
1433 page = lru_to_page(page_list);
1434 list_del(&page->lru);
1435
Nick Piggin529ae9a2008-08-02 12:01:03 +02001436 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001437 goto keep;
1438
Sasha Levin309381fea2014-01-23 15:52:54 -08001439 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001440
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001441 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001442
1443 /* Account the number of base pages even though THP */
1444 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001445
Hugh Dickins39b5f292012-10-08 16:33:18 -07001446 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001447 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001448
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001449 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001450 goto keep_locked;
1451
Yu Zhao0182f922022-09-18 02:00:04 -06001452 /* page_update_gen() tried to promote this page? */
1453 if (lru_gen_enabled() && !ignore_references &&
1454 page_mapped(page) && PageReferenced(page))
1455 goto keep_locked;
1456
Andy Whitcroftc661b072007-08-22 14:01:26 -07001457 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1458 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1459
Mel Gorman283aba92013-07-03 15:01:51 -07001460 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001461 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001462 * reclaim_congested which affects wait_iff_congested. kswapd
1463 * will stall and start writing pages if the tail of the LRU
1464 * is all dirty unqueued pages.
1465 */
1466 page_check_dirty_writeback(page, &dirty, &writeback);
1467 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001468 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001469
1470 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001471 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001472
Mel Gormand04e8ac2013-07-03 15:02:03 -07001473 /*
1474 * Treat this page as congested if the underlying BDI is or if
1475 * pages are cycling through the LRU so quickly that the
1476 * pages marked for immediate reclaim are making it to the
1477 * end of the LRU a second time.
1478 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001479 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001480 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001481 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001482 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001483 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001484
1485 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001486 * If a page at the tail of the LRU is under writeback, there
1487 * are three cases to consider.
1488 *
1489 * 1) If reclaim is encountering an excessive number of pages
1490 * under writeback and this page is both under writeback and
1491 * PageReclaim then it indicates that pages are being queued
1492 * for IO but are being recycled through the LRU before the
1493 * IO can complete. Waiting on the page itself risks an
1494 * indefinite stall if it is impossible to writeback the
1495 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001496 * note that the LRU is being scanned too quickly and the
1497 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001498 *
Tejun Heo97c93412015-05-22 18:23:36 -04001499 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001500 * not marked for immediate reclaim, or the caller does not
1501 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1502 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001503 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001504 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001505 * Require may_enter_fs because we would wait on fs, which
1506 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001507 * enter reclaim, and deadlock if it waits on a page for
1508 * which it is needed to do the write (loop masks off
1509 * __GFP_IO|__GFP_FS for this reason); but more thought
1510 * would probably show more reasons.
1511 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001512 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001513 * PageReclaim. memcg does not have any dirty pages
1514 * throttling so we could easily OOM just because too many
1515 * pages are in writeback and there is nothing else to
1516 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001517 *
1518 * In cases 1) and 2) we activate the pages to get them out of
1519 * the way while we continue scanning for clean pages on the
1520 * inactive list and refilling from the active list. The
1521 * observation here is that waiting for disk writes is more
1522 * expensive than potentially causing reloads down the line.
1523 * Since they're marked for immediate reclaim, they won't put
1524 * memory pressure on the cache working set any longer than it
1525 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001526 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001527 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001528 /* Case 1 above */
1529 if (current_is_kswapd() &&
1530 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001531 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001532 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001533 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001534
1535 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001536 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001537 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001538 /*
1539 * This is slightly racy - end_page_writeback()
1540 * might have just cleared PageReclaim, then
1541 * setting PageReclaim here end up interpreted
1542 * as PageReadahead - but that does not matter
1543 * enough to care. What we do want is for this
1544 * page to have PageReclaim set next time memcg
1545 * reclaim reaches the tests above, so it will
1546 * then wait_on_page_writeback() to avoid OOM;
1547 * and it's also appropriate in global reclaim.
1548 */
1549 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001550 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001551 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001552
1553 /* Case 3 above */
1554 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001555 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001556 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001557 /* then go back and try same page again */
1558 list_add_tail(&page->lru, page_list);
1559 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001560 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001561 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001562
Minchan Kim8940b342019-09-25 16:49:11 -07001563 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001564 references = page_check_references(page, sc);
1565
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001566 switch (references) {
1567 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001568 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001569 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001570 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001571 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001572 case PAGEREF_RECLAIM:
1573 case PAGEREF_RECLAIM_CLEAN:
1574 ; /* try to reclaim the page below */
1575 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001576
Linus Torvalds1da177e2005-04-16 15:20:36 -07001577 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001578 * Before reclaiming the page, try to relocate
1579 * its contents to another node.
1580 */
1581 if (do_demote_pass &&
1582 (thp_migration_supported() || !PageTransHuge(page))) {
1583 list_add(&page->lru, &demote_pages);
1584 unlock_page(page);
1585 continue;
1586 }
1587
1588 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001589 * Anonymous process memory has backing store?
1590 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001591 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001592 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001593 if (PageAnon(page) && PageSwapBacked(page)) {
1594 if (!PageSwapCache(page)) {
1595 if (!(sc->gfp_mask & __GFP_IO))
1596 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001597 if (page_maybe_dma_pinned(page))
1598 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001599 if (PageTransHuge(page)) {
1600 /* cannot split THP, skip it */
1601 if (!can_split_huge_page(page, NULL))
1602 goto activate_locked;
1603 /*
1604 * Split pages without a PMD map right
1605 * away. Chances are some or all of the
1606 * tail pages can be freed without IO.
1607 */
1608 if (!compound_mapcount(page) &&
1609 split_huge_page_to_list(page,
1610 page_list))
1611 goto activate_locked;
1612 }
1613 if (!add_to_swap(page)) {
1614 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001615 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001616 /* Fallback to swap normal pages */
1617 if (split_huge_page_to_list(page,
1618 page_list))
1619 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001620#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1621 count_vm_event(THP_SWPOUT_FALLBACK);
1622#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001623 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001624 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001625 }
Minchan Kim0f074652017-07-06 15:37:24 -07001626
Kirill Tkhai4b793062020-04-01 21:10:18 -07001627 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001628
1629 /* Adding to swap updated mapping */
1630 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001631 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001632 } else if (unlikely(PageTransHuge(page))) {
1633 /* Split file THP */
1634 if (split_huge_page_to_list(page, page_list))
1635 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001636 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001637
1638 /*
Yang Shi98879b32019-07-11 20:59:30 -07001639 * THP may get split above, need minus tail pages and update
1640 * nr_pages to avoid accounting tail pages twice.
1641 *
1642 * The tail pages that are added into swap cache successfully
1643 * reach here.
1644 */
1645 if ((nr_pages > 1) && !PageTransHuge(page)) {
1646 sc->nr_scanned -= (nr_pages - 1);
1647 nr_pages = 1;
1648 }
1649
1650 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001651 * The page is mapped into the page tables of one or more
1652 * processes. Try to unmap it here.
1653 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001654 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001655 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001656 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001657
1658 if (unlikely(PageTransHuge(page)))
1659 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001660
Yang Shi1fb08ac2021-06-30 18:52:01 -07001661 try_to_unmap(page, flags);
1662 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001663 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001664 if (!was_swapbacked && PageSwapBacked(page))
1665 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001666 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001667 }
1668 }
1669
1670 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001671 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001672 * Only kswapd can writeback filesystem pages
1673 * to avoid risk of stack overflow. But avoid
1674 * injecting inefficient single-page IO into
1675 * flusher writeback as much as possible: only
1676 * write pages when we've encountered many
1677 * dirty pages, and when we've already scanned
1678 * the rest of the LRU for clean pages and see
1679 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001680 */
Huang Ying9de4f222020-04-06 20:04:41 -07001681 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001682 (!current_is_kswapd() || !PageReclaim(page) ||
1683 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001684 /*
1685 * Immediately reclaim when written back.
1686 * Similar in principal to deactivate_page()
1687 * except we already have the page isolated
1688 * and know it's dirty
1689 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001690 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001691 SetPageReclaim(page);
1692
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001693 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001694 }
1695
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001696 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001697 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001698 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001699 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001700 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001701 goto keep_locked;
1702
Mel Gormand950c942015-09-04 15:47:35 -07001703 /*
1704 * Page is dirty. Flush the TLB if a writable entry
1705 * potentially exists to avoid CPU writes after IO
1706 * starts and then write it out here.
1707 */
1708 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001709 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001710 case PAGE_KEEP:
1711 goto keep_locked;
1712 case PAGE_ACTIVATE:
1713 goto activate_locked;
1714 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001715 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001716
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001717 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001718 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001719 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001720 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001721
Linus Torvalds1da177e2005-04-16 15:20:36 -07001722 /*
1723 * A synchronous write - probably a ramdisk. Go
1724 * ahead and try to reclaim the page.
1725 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001726 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001727 goto keep;
1728 if (PageDirty(page) || PageWriteback(page))
1729 goto keep_locked;
1730 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001731 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001732 case PAGE_CLEAN:
1733 ; /* try to free the page below */
1734 }
1735 }
1736
1737 /*
1738 * If the page has buffers, try to free the buffer mappings
1739 * associated with this page. If we succeed we try to free
1740 * the page as well.
1741 *
1742 * We do this even if the page is PageDirty().
1743 * try_to_release_page() does not perform I/O, but it is
1744 * possible for a page to have PageDirty set, but it is actually
1745 * clean (all its buffers are clean). This happens if the
1746 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001747 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001748 * try_to_release_page() will discover that cleanness and will
1749 * drop the buffers and mark the page clean - it can be freed.
1750 *
1751 * Rarely, pages can have buffers and no ->mapping. These are
1752 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001753 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001754 * and if that worked, and the page is no longer mapped into
1755 * process address space (page_count == 1) it can be freed.
1756 * Otherwise, leave the page on the LRU so it is swappable.
1757 */
David Howells266cf652009-04-03 16:42:36 +01001758 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001759 if (!try_to_release_page(page, sc->gfp_mask))
1760 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001761 if (!mapping && page_count(page) == 1) {
1762 unlock_page(page);
1763 if (put_page_testzero(page))
1764 goto free_it;
1765 else {
1766 /*
1767 * rare race with speculative reference.
1768 * the speculative reference will free
1769 * this page shortly, so we may
1770 * increment nr_reclaimed here (and
1771 * leave it off the LRU).
1772 */
1773 nr_reclaimed++;
1774 continue;
1775 }
1776 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001777 }
1778
Shaohua Li802a3a92017-05-03 14:52:32 -07001779 if (PageAnon(page) && !PageSwapBacked(page)) {
1780 /* follow __remove_mapping for reference */
1781 if (!page_ref_freeze(page, 1))
1782 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001783 /*
1784 * The page has only one reference left, which is
1785 * from the isolation. After the caller puts the
1786 * page back on lru and drops the reference, the
1787 * page will be freed anyway. It doesn't matter
1788 * which lru it goes. So we don't bother checking
1789 * PageDirty here.
1790 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001791 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001792 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001793 } else if (!mapping || !__remove_mapping(mapping, page, true,
1794 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001795 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001796
1797 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001798free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001799 /*
1800 * THP may get swapped out in a whole, need account
1801 * all base pages.
1802 */
1803 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001804
1805 /*
1806 * Is there need to periodically free_page_list? It would
1807 * appear not as the counts should be low
1808 */
Yang Shi7ae88532019-09-23 15:38:09 -07001809 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001810 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001811 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001812 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001813 continue;
1814
Yang Shi98879b32019-07-11 20:59:30 -07001815activate_locked_split:
1816 /*
1817 * The tail pages that are failed to add into swap cache
1818 * reach here. Fixup nr_scanned and nr_pages.
1819 */
1820 if (nr_pages > 1) {
1821 sc->nr_scanned -= (nr_pages - 1);
1822 nr_pages = 1;
1823 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001824activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001825 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001826 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1827 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001828 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001829 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001830 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001831 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001832 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001833 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001834 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001835 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001836keep_locked:
1837 unlock_page(page);
1838keep:
1839 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001840 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001841 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001842 /* 'page_list' is always empty here */
1843
1844 /* Migrate pages selected for demotion */
1845 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1846 /* Pages that could not be demoted are still in @demote_pages */
1847 if (!list_empty(&demote_pages)) {
1848 /* Pages which failed to demoted go back on @page_list for retry: */
1849 list_splice_init(&demote_pages, page_list);
1850 do_demote_pass = false;
1851 goto retry;
1852 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001853
Yang Shi98879b32019-07-11 20:59:30 -07001854 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1855
Johannes Weiner747db952014-08-08 14:19:24 -07001856 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001857 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001858 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001859
Linus Torvalds1da177e2005-04-16 15:20:36 -07001860 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001861 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001862
Andrew Morton05ff5132006-03-22 00:08:20 -08001863 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001864}
1865
Maninder Singh730ec8c2020-06-03 16:01:18 -07001866unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001867 struct list_head *page_list)
1868{
1869 struct scan_control sc = {
1870 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001871 .may_unmap = 1,
1872 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001873 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001874 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001875 struct page *page, *next;
1876 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001877 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001878
1879 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001880 if (!PageHuge(page) && page_is_file_lru(page) &&
1881 !PageDirty(page) && !__PageMovable(page) &&
1882 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001883 ClearPageActive(page);
1884 list_move(&page->lru, &clean_pages);
1885 }
1886 }
1887
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001888 /*
1889 * We should be safe here since we are only dealing with file pages and
1890 * we are not kswapd and therefore cannot write dirty file pages. But
1891 * call memalloc_noreclaim_save() anyway, just in case these conditions
1892 * change in the future.
1893 */
1894 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001895 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001896 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001897 memalloc_noreclaim_restore(noreclaim_flag);
1898
Minchan Kim02c6de82012-10-08 16:31:55 -07001899 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001900 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1901 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001902 /*
1903 * Since lazyfree pages are isolated from file LRU from the beginning,
1904 * they will rotate back to anonymous LRU in the end if it failed to
1905 * discard so isolated count will be mismatched.
1906 * Compensate the isolated count for both LRU lists.
1907 */
1908 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1909 stat.nr_lazyfree_fail);
1910 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001911 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001912 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001913}
1914
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001915/*
Mel Gorman7ee36a12016-07-28 15:47:17 -07001916 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001917 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001918 */
1919static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001920 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001921{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001922 int zid;
1923
Mel Gorman7ee36a12016-07-28 15:47:17 -07001924 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1925 if (!nr_zone_taken[zid])
1926 continue;
1927
Wei Yanga892cb62020-06-03 16:01:12 -07001928 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001929 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001930
Mel Gorman7ee36a12016-07-28 15:47:17 -07001931}
1932
Zhaoyang Huang45022652023-05-31 10:51:01 +08001933#ifdef CONFIG_CMA
1934/*
1935 * It is waste of effort to scan and reclaim CMA pages if it is not available
1936 * for current allocation context. Kswapd can not be enrolled as it can not
1937 * distinguish this scenario by using sc->gfp_mask = GFP_KERNEL
1938 */
1939static bool skip_cma(struct page *page, struct scan_control *sc)
1940{
1941 return !current_is_kswapd() &&
1942 gfp_migratetype(sc->gfp_mask) != MIGRATE_MOVABLE &&
1943 get_pageblock_migratetype(page) == MIGRATE_CMA;
1944}
1945#else
1946static bool skip_cma(struct page *page, struct scan_control *sc)
1947{
1948 return false;
1949}
1950#endif
1951
Mel Gormanf611fab2021-06-30 18:53:19 -07001952/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001953 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1954 *
1955 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001956 * shrink the lists perform better by taking out a batch of pages
1957 * and working on them outside the LRU lock.
1958 *
1959 * For pagecache intensive workloads, this function is the hottest
1960 * spot in the kernel (apart from copy_*_user functions).
1961 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001962 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001963 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001964 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001965 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001966 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001967 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001968 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001969 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001970 *
1971 * returns how many pages were moved onto *@dst.
1972 */
Andrew Morton69e05942006-03-22 00:08:19 -08001973static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001974 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001975 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001976 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001977{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001978 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001979 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001980 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001981 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07001982 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001983 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07001984 LIST_HEAD(pages_skipped);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001985
Yang Shi98879b32019-07-11 20:59:30 -07001986 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001987 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07001988 while (scan < nr_to_scan && !list_empty(src)) {
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001989 struct list_head *move_to = src;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001990 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001991
Linus Torvalds1da177e2005-04-16 15:20:36 -07001992 page = lru_to_page(src);
1993 prefetchw_prev_lru_page(page, src, flags);
1994
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001995 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001996 total_scan += nr_pages;
1997
Zhaoyang Huang45022652023-05-31 10:51:01 +08001998 if (page_zonenum(page) > sc->reclaim_idx ||
1999 skip_cma(page, sc)) {
Yang Shi98879b32019-07-11 20:59:30 -07002000 nr_skipped[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002001 move_to = &pages_skipped;
2002 goto move;
Mel Gormanb2e18752016-07-28 15:45:37 -07002003 }
2004
Minchan Kim791b48b2017-05-12 15:47:06 -07002005 /*
2006 * Do not count skipped pages because that makes the function
2007 * return with no isolated pages if the LRU mostly contains
2008 * ineligible pages. This causes the VM to not reclaim any
2009 * pages, triggering a premature OOM.
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002010 * Account all tail pages of THP.
Minchan Kim791b48b2017-05-12 15:47:06 -07002011 */
Yang Shi98879b32019-07-11 20:59:30 -07002012 scan += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002013
2014 if (!PageLRU(page))
2015 goto move;
2016 if (!sc->may_unmap && page_mapped(page))
2017 goto move;
2018
Alex Shic2135f72021-02-24 12:08:01 -08002019 /*
2020 * Be careful not to clear PageLRU until after we're
2021 * sure the page is not being freed elsewhere -- the
2022 * page release code relies on it.
2023 */
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002024 if (unlikely(!get_page_unless_zero(page)))
2025 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002026
2027 if (!TestClearPageLRU(page)) {
2028 /* Another thread is already isolating this page */
2029 put_page(page);
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002030 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08002031 }
2032
2033 nr_taken += nr_pages;
2034 nr_zone_taken[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002035 move_to = dst;
2036move:
2037 list_move(&page->lru, move_to);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002038 }
2039
Mel Gormanb2e18752016-07-28 15:45:37 -07002040 /*
2041 * Splice any skipped pages to the start of the LRU list. Note that
2042 * this disrupts the LRU order when reclaiming for lower zones but
2043 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2044 * scanning would soon rescan the same pages to skip and put the
2045 * system at risk of premature OOM.
2046 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002047 if (!list_empty(&pages_skipped)) {
2048 int zid;
2049
Johannes Weiner3db65812017-05-03 14:52:13 -07002050 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002051 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2052 if (!nr_skipped[zid])
2053 continue;
2054
2055 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002056 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002057 }
2058 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002059 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002060 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002061 total_scan, skipped, nr_taken,
2062 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002063 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002064 return nr_taken;
2065}
2066
Nick Piggin62695a82008-10-18 20:26:09 -07002067/**
2068 * isolate_lru_page - tries to isolate a page from its LRU list
2069 * @page: page to isolate from its LRU list
2070 *
2071 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2072 * vmstat statistic corresponding to whatever LRU list the page was on.
2073 *
2074 * Returns 0 if the page was removed from an LRU list.
2075 * Returns -EBUSY if the page was not on an LRU list.
2076 *
2077 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002078 * the active list, it will have PageActive set. If it was found on
2079 * the unevictable list, it will have the PageUnevictable bit set. That flag
2080 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002081 *
2082 * The vmstat statistic corresponding to the list on which the page was
2083 * found will be decremented.
2084 *
2085 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002086 *
Nick Piggin62695a82008-10-18 20:26:09 -07002087 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002088 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002089 * without a stable reference).
2090 * (2) the lru_lock must not be held.
2091 * (3) interrupts must be enabled.
2092 */
2093int isolate_lru_page(struct page *page)
2094{
2095 int ret = -EBUSY;
2096
Sasha Levin309381fea2014-01-23 15:52:54 -08002097 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002098 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002099
Alex Shid25b5bd2020-12-15 12:34:16 -08002100 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002101 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002102
Alex Shid25b5bd2020-12-15 12:34:16 -08002103 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002104 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002105 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002106 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002107 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002108 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002109
Nick Piggin62695a82008-10-18 20:26:09 -07002110 return ret;
2111}
2112
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002113/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002114 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002115 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002116 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2117 * the LRU list will go small and be scanned faster than necessary, leading to
2118 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002119 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002120static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002121 struct scan_control *sc)
2122{
2123 unsigned long inactive, isolated;
2124
2125 if (current_is_kswapd())
2126 return 0;
2127
Johannes Weinerb5ead352019-11-30 17:55:40 -08002128 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002129 return 0;
2130
2131 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002132 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2133 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002134 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002135 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2136 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002137 }
2138
Fengguang Wu3cf23842012-12-18 14:23:31 -08002139 /*
2140 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2141 * won't get blocked by normal direct-reclaimers, forming a circular
2142 * deadlock.
2143 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002144 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002145 inactive >>= 3;
2146
Rik van Riel35cd7812009-09-21 17:01:38 -07002147 return isolated > inactive;
2148}
2149
Kirill Tkhaia222f342019-05-13 17:17:00 -07002150/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002151 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2152 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002153 *
2154 * Returns the number of pages moved to the given lruvec.
2155 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002156static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2157 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002158{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002159 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002160 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002161 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002162
Kirill Tkhaia222f342019-05-13 17:17:00 -07002163 while (!list_empty(list)) {
2164 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002165 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002166 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002167 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002168 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002169 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002170 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002171 continue;
2172 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002173
Alex Shi3d06afa2020-12-15 12:33:37 -08002174 /*
2175 * The SetPageLRU needs to be kept here for list integrity.
2176 * Otherwise:
2177 * #0 move_pages_to_lru #1 release_pages
2178 * if !put_page_testzero
2179 * if (put_page_testzero())
2180 * !PageLRU //skip lru_lock
2181 * SetPageLRU()
2182 * list_add(&page->lru,)
2183 * list_add(&page->lru,)
2184 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002185 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002186
Alex Shi3d06afa2020-12-15 12:33:37 -08002187 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002188 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002189
2190 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002191 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002192 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002193 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002194 } else
2195 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002196
2197 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002198 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002199
Alex Shiafca9152020-12-15 12:34:02 -08002200 /*
2201 * All pages were isolated from the same lruvec (and isolation
2202 * inhibits memcg migration).
2203 */
Muchun Song7467c392021-06-28 19:37:59 -07002204 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002205 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002206 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002207 nr_moved += nr_pages;
2208 if (PageActive(page))
2209 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002210 }
Mel Gorman66635622010-08-09 17:19:30 -07002211
Hugh Dickins3f797682012-01-12 17:20:07 -08002212 /*
2213 * To save our caller's stack, now use input list for pages to free.
2214 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002215 list_splice(&pages_to_free, list);
2216
2217 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002218}
2219
2220/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002221 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002222 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002223 * In that case we should only throttle if the backing device it is
2224 * writing to is congested. In other cases it is safe to throttle.
2225 */
2226static int current_may_throttle(void)
2227{
NeilBrowna37b0712020-06-01 21:48:18 -07002228 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002229 current->backing_dev_info == NULL ||
2230 bdi_write_congested(current->backing_dev_info);
2231}
2232
2233/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002234 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002235 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002236 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002237static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002238shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002239 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002240{
2241 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002242 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002243 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002244 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002245 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002246 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002247 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002248 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002249 bool stalled = false;
Minchan Kim7df45e52022-10-27 08:29:17 -07002250 struct blk_plug plug;
2251 bool do_plug = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002252
Mel Gorman599d0c92016-07-28 15:45:31 -07002253 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002254 if (stalled)
2255 return 0;
2256
2257 /* wait a bit for the reclaimer. */
2258 msleep(100);
2259 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002260
2261 /* We are about to die and free our memory. Return now. */
2262 if (fatal_signal_pending(current))
2263 return SWAP_CLUSTER_MAX;
2264 }
2265
Linus Torvalds1da177e2005-04-16 15:20:36 -07002266 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002267
Alex Shi6168d0d2020-12-15 12:34:29 -08002268 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002269
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002270 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002271 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002272
Mel Gorman599d0c92016-07-28 15:45:31 -07002273 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002274 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002275 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002276 __count_vm_events(item, nr_scanned);
2277 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002278 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2279
Alex Shi6168d0d2020-12-15 12:34:29 -08002280 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002281
Hillf Dantond563c052012-03-21 16:34:02 -07002282 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002283 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002284
Minchan Kim7df45e52022-10-27 08:29:17 -07002285 trace_android_vh_shrink_inactive_list_blk_plug(&do_plug);
2286 if (do_plug)
2287 blk_start_plug(&plug);
Shakeel Butt013339d2020-12-14 19:06:39 -08002288 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002289
Alex Shi6168d0d2020-12-15 12:34:29 -08002290 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002291 move_pages_to_lru(lruvec, &page_list);
2292
2293 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002294 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002295 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002296 __count_vm_events(item, nr_reclaimed);
2297 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002298 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002299 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002300
Minchan Kim7df45e52022-10-27 08:29:17 -07002301 if (do_plug)
2302 blk_finish_plug(&plug);
2303
Alex Shi75cc3c92020-12-15 14:20:50 -08002304 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002305 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002306 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002307
Mel Gorman92df3a72011-10-31 17:07:56 -07002308 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002309 * If dirty pages are scanned that are not queued for IO, it
2310 * implies that flushers are not doing their job. This can
2311 * happen when memory pressure pushes dirty pages to the end of
2312 * the LRU before the dirty limits are breached and the dirty
2313 * data has expired. It can also happen when the proportion of
2314 * dirty pages grows not through writes but through memory
2315 * pressure reclaiming all the clean cache. And in some cases,
2316 * the flushers simply cannot keep up with the allocation
2317 * rate. Nudge the flusher threads in case they are asleep.
2318 */
2319 if (stat.nr_unqueued_dirty == nr_taken)
2320 wakeup_flusher_threads(WB_REASON_VMSCAN);
2321
Andrey Ryabinind108c772018-04-10 16:27:59 -07002322 sc->nr.dirty += stat.nr_dirty;
2323 sc->nr.congested += stat.nr_congested;
2324 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2325 sc->nr.writeback += stat.nr_writeback;
2326 sc->nr.immediate += stat.nr_immediate;
2327 sc->nr.taken += nr_taken;
2328 if (file)
2329 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002330
Mel Gorman599d0c92016-07-28 15:45:31 -07002331 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002332 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002333 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002334}
2335
Hugh Dickins15b44732020-12-15 14:21:31 -08002336/*
2337 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2338 *
2339 * We move them the other way if the page is referenced by one or more
2340 * processes.
2341 *
2342 * If the pages are mostly unmapped, the processing is fast and it is
2343 * appropriate to hold lru_lock across the whole operation. But if
2344 * the pages are mapped, the processing is slow (page_referenced()), so
2345 * we should drop lru_lock around each page. It's impossible to balance
2346 * this, so instead we remove the pages from the LRU while processing them.
2347 * It is safe to rely on PG_active against the non-LRU pages in here because
2348 * nobody will play with that bit on a non-LRU page.
2349 *
2350 * The downside is that we have to touch page->_refcount against each page.
2351 * But we had to alter page->flags anyway.
2352 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002353static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002354 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002355 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002356 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002357{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002358 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002359 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002360 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002361 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002362 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002363 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002364 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002365 unsigned nr_deactivate, nr_activate;
2366 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002367 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002368 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002369 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002370
2371 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002372
Alex Shi6168d0d2020-12-15 12:34:29 -08002373 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002374
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002375 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002376 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002377
Mel Gorman599d0c92016-07-28 15:45:31 -07002378 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002379
Shakeel Butt912c0572020-08-06 23:26:32 -07002380 if (!cgroup_reclaim(sc))
2381 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002382 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002383
Alex Shi6168d0d2020-12-15 12:34:29 -08002384 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002385
Linus Torvalds1da177e2005-04-16 15:20:36 -07002386 while (!list_empty(&l_hold)) {
2387 cond_resched();
2388 page = lru_to_page(&l_hold);
2389 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002390
Hugh Dickins39b5f292012-10-08 16:33:18 -07002391 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002392 putback_lru_page(page);
2393 continue;
2394 }
2395
Mel Gormancc715d92012-03-21 16:34:00 -07002396 if (unlikely(buffer_heads_over_limit)) {
2397 if (page_has_private(page) && trylock_page(page)) {
2398 if (page_has_private(page))
2399 try_to_release_page(page, 0);
2400 unlock_page(page);
2401 }
2402 }
2403
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002404 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2405 if (bypass)
2406 goto skip_page_referenced;
2407
Minchan Kimf74aca72022-05-19 14:08:54 -07002408 /* Referenced or rmap lock contention: rotate */
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002409 if (page_referenced(page, 0, sc->target_mem_cgroup,
Minchan Kimf74aca72022-05-19 14:08:54 -07002410 &vm_flags) != 0) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002411 /*
2412 * Identify referenced, file-backed active pages and
2413 * give them one more trip around the active list. So
2414 * that executable code get better chances to stay in
2415 * memory under moderate memory pressure. Anon pages
2416 * are not likely to be evicted by use-once streaming
2417 * IO, plus JVM can create lots of anon VM_EXEC pages,
2418 * so we ignore them here.
2419 */
Huang Ying9de4f222020-04-06 20:04:41 -07002420 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002421 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002422 list_add(&page->lru, &l_active);
2423 continue;
2424 }
2425 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002426skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002427 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002428 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002429 list_add(&page->lru, &l_inactive);
2430 }
2431
Andrew Mortonb5557492009-01-06 14:40:13 -08002432 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002433 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002434 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002435 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002436
Kirill Tkhaia222f342019-05-13 17:17:00 -07002437 nr_activate = move_pages_to_lru(lruvec, &l_active);
2438 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002439 /* Keep all free pages in l_active list */
2440 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002441
2442 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2443 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2444
Mel Gorman599d0c92016-07-28 15:45:31 -07002445 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002446 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002447
Kirill Tkhaif372d892019-05-13 17:16:57 -07002448 mem_cgroup_uncharge_list(&l_active);
2449 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002450 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2451 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002452}
2453
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002454unsigned long reclaim_pages(struct list_head *page_list)
2455{
Yang Shif661d002020-04-01 21:10:05 -07002456 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002457 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002458 LIST_HEAD(node_page_list);
2459 struct reclaim_stat dummy_stat;
2460 struct page *page;
Minchan Kim7df45e52022-10-27 08:29:17 -07002461 struct blk_plug plug;
2462 bool do_plug = false;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002463 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002464 struct scan_control sc = {
2465 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002466 .may_writepage = 1,
2467 .may_unmap = 1,
2468 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002469 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002470 };
2471
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002472 noreclaim_flag = memalloc_noreclaim_save();
2473
Minchan Kim7df45e52022-10-27 08:29:17 -07002474 trace_android_vh_reclaim_pages_plug(&do_plug);
2475 if (do_plug)
2476 blk_start_plug(&plug);
2477
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002478 while (!list_empty(page_list)) {
2479 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002480 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002481 nid = page_to_nid(page);
2482 INIT_LIST_HEAD(&node_page_list);
2483 }
2484
2485 if (nid == page_to_nid(page)) {
2486 ClearPageActive(page);
2487 list_move(&page->lru, &node_page_list);
2488 continue;
2489 }
2490
2491 nr_reclaimed += shrink_page_list(&node_page_list,
2492 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002493 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002494 while (!list_empty(&node_page_list)) {
2495 page = lru_to_page(&node_page_list);
2496 list_del(&page->lru);
2497 putback_lru_page(page);
2498 }
2499
Yang Shif661d002020-04-01 21:10:05 -07002500 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002501 }
2502
2503 if (!list_empty(&node_page_list)) {
2504 nr_reclaimed += shrink_page_list(&node_page_list,
2505 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002506 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002507 while (!list_empty(&node_page_list)) {
2508 page = lru_to_page(&node_page_list);
2509 list_del(&page->lru);
2510 putback_lru_page(page);
2511 }
2512 }
2513
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002514 memalloc_noreclaim_restore(noreclaim_flag);
2515
Minchan Kim7df45e52022-10-27 08:29:17 -07002516 if (do_plug)
2517 blk_finish_plug(&plug);
2518
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002519 return nr_reclaimed;
2520}
2521
Johannes Weinerb91ac372019-11-30 17:56:02 -08002522static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2523 struct lruvec *lruvec, struct scan_control *sc)
2524{
2525 if (is_active_lru(lru)) {
2526 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2527 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2528 else
2529 sc->skipped_deactivate = 1;
2530 return 0;
2531 }
2532
2533 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2534}
2535
Rik van Riel59dc76b2016-05-20 16:56:31 -07002536/*
2537 * The inactive anon list should be small enough that the VM never has
2538 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002539 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002540 * The inactive file list should be small enough to leave most memory
2541 * to the established workingset on the scan-resistant active list,
2542 * but large enough to avoid thrashing the aggregate readahead window.
2543 *
2544 * Both inactive lists should also be large enough that each inactive
2545 * page has a chance to be referenced again before it is reclaimed.
2546 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002547 * If that fails and refaulting is observed, the inactive list grows.
2548 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002549 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002550 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002551 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2552 *
2553 * total target max
2554 * memory ratio inactive
2555 * -------------------------------------
2556 * 10MB 1 5MB
2557 * 100MB 1 50MB
2558 * 1GB 3 250MB
2559 * 10GB 10 0.9GB
2560 * 100GB 31 3GB
2561 * 1TB 101 10GB
2562 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002563 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002564static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002565{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002566 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002567 unsigned long inactive, active;
2568 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002569 unsigned long gb;
2570
Johannes Weinerb91ac372019-11-30 17:56:02 -08002571 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2572 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002573
Johannes Weinerb91ac372019-11-30 17:56:02 -08002574 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002575 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002576 inactive_ratio = int_sqrt(10 * gb);
2577 else
2578 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002579
Rik van Riel59dc76b2016-05-20 16:56:31 -07002580 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002581}
2582
Johannes Weiner9a265112013-02-22 16:32:17 -08002583enum scan_balance {
2584 SCAN_EQUAL,
2585 SCAN_FRACT,
2586 SCAN_ANON,
2587 SCAN_FILE,
2588};
2589
Yu Zhao6d313442022-09-18 02:00:00 -06002590static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2591{
2592 unsigned long file;
2593 struct lruvec *target_lruvec;
2594
Yu Zhao37397872022-09-18 02:00:03 -06002595 if (lru_gen_enabled())
2596 return;
2597
Yu Zhao6d313442022-09-18 02:00:00 -06002598 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2599
2600 /*
2601 * Flush the memory cgroup stats, so that we read accurate per-memcg
2602 * lruvec stats for heuristics.
2603 */
2604 mem_cgroup_flush_stats();
2605
2606 /*
2607 * Determine the scan balance between anon and file LRUs.
2608 */
2609 spin_lock_irq(&target_lruvec->lru_lock);
2610 sc->anon_cost = target_lruvec->anon_cost;
2611 sc->file_cost = target_lruvec->file_cost;
2612 spin_unlock_irq(&target_lruvec->lru_lock);
2613
2614 /*
2615 * Target desirable inactive:active list ratios for the anon
2616 * and file LRU lists.
2617 */
2618 if (!sc->force_deactivate) {
2619 unsigned long refaults;
2620
2621 refaults = lruvec_page_state(target_lruvec,
2622 WORKINGSET_ACTIVATE_ANON);
2623 if (refaults != target_lruvec->refaults[0] ||
2624 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2625 sc->may_deactivate |= DEACTIVATE_ANON;
2626 else
2627 sc->may_deactivate &= ~DEACTIVATE_ANON;
2628
2629 /*
2630 * When refaults are being observed, it means a new
2631 * workingset is being established. Deactivate to get
2632 * rid of any stale active pages quickly.
2633 */
2634 refaults = lruvec_page_state(target_lruvec,
2635 WORKINGSET_ACTIVATE_FILE);
2636 if (refaults != target_lruvec->refaults[1] ||
2637 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2638 sc->may_deactivate |= DEACTIVATE_FILE;
2639 else
2640 sc->may_deactivate &= ~DEACTIVATE_FILE;
2641 } else
2642 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2643
2644 /*
2645 * If we have plenty of inactive file pages that aren't
2646 * thrashing, try to reclaim those first before touching
2647 * anonymous pages.
2648 */
2649 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2650 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2651 sc->cache_trim_mode = 1;
2652 else
2653 sc->cache_trim_mode = 0;
2654
2655 /*
2656 * Prevent the reclaimer from falling into the cache trap: as
2657 * cache pages start out inactive, every cache fault will tip
2658 * the scan balance towards the file LRU. And as the file LRU
2659 * shrinks, so does the window for rotation from references.
2660 * This means we have a runaway feedback loop where a tiny
2661 * thrashing file LRU becomes infinitely more attractive than
2662 * anon pages. Try to detect this based on file LRU size.
2663 */
2664 if (!cgroup_reclaim(sc)) {
2665 unsigned long total_high_wmark = 0;
2666 unsigned long free, anon;
2667 int z;
2668
2669 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2670 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2671 node_page_state(pgdat, NR_INACTIVE_FILE);
2672
2673 for (z = 0; z < MAX_NR_ZONES; z++) {
2674 struct zone *zone = &pgdat->node_zones[z];
2675
2676 if (!managed_zone(zone))
2677 continue;
2678
2679 total_high_wmark += high_wmark_pages(zone);
2680 }
2681
2682 /*
2683 * Consider anon: if that's low too, this isn't a
2684 * runaway file reclaim problem, but rather just
2685 * extreme pressure. Reclaim as per usual then.
2686 */
2687 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2688
2689 sc->file_is_tiny =
2690 file + free <= total_high_wmark &&
2691 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2692 anon >> sc->priority;
2693 }
2694}
2695
Linus Torvalds1da177e2005-04-16 15:20:36 -07002696/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002697 * Determine how aggressively the anon and file LRU lists should be
2698 * scanned. The relative value of each set of LRU lists is determined
2699 * by looking at the fraction of the pages scanned we did rotate back
2700 * onto the active list instead of evict.
2701 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002702 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2703 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002704 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002705static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2706 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002707{
Keith Buscha2a36482021-09-02 14:59:26 -07002708 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002709 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002710 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002711 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002712 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002713 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002714 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002715 unsigned long ap, fp;
2716 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002717 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002718
2719 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002720 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002721 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002722 goto out;
2723 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002724
Johannes Weiner10316b32013-02-22 16:32:14 -08002725 /*
2726 * Global reclaim will swap to prevent OOM even with no
2727 * swappiness, but memcg users want to use this knob to
2728 * disable swapping for individual groups completely when
2729 * using the memory controller's swap limit feature would be
2730 * too expensive.
2731 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002732 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002733 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002734 goto out;
2735 }
2736
2737 /*
2738 * Do not apply any pressure balancing cleverness when the
2739 * system is close to OOM, scan both anon and file equally
2740 * (unless the swappiness setting disagrees with swapping).
2741 */
Johannes Weiner02695172014-08-06 16:06:17 -07002742 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002743 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002744 goto out;
2745 }
2746
Johannes Weiner11d16c22013-02-22 16:32:15 -08002747 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002748 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002749 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002750 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002751 scan_balance = SCAN_ANON;
2752 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002753 }
2754
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002755 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2756
Johannes Weiner62376252014-05-06 12:50:07 -07002757 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002758 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002759 * anything from the anonymous working right now. But when balancing
2760 * anon and page cache files for reclaim, allow swapping of anon pages
2761 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002762 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002763 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002764 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002765 goto out;
2766 }
2767
Johannes Weiner9a265112013-02-22 16:32:17 -08002768 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002769 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002770 * Calculate the pressure balance between anon and file pages.
2771 *
2772 * The amount of pressure we put on each LRU is inversely
2773 * proportional to the cost of reclaiming each list, as
2774 * determined by the share of pages that are refaulting, times
2775 * the relative IO cost of bringing back a swapped out
2776 * anonymous page vs reloading a filesystem page (swappiness).
2777 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002778 * Although we limit that influence to ensure no list gets
2779 * left behind completely: at least a third of the pressure is
2780 * applied, before swappiness.
2781 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002782 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002783 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002784 total_cost = sc->anon_cost + sc->file_cost;
2785 anon_cost = total_cost + sc->anon_cost;
2786 file_cost = total_cost + sc->file_cost;
2787 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002788
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002789 ap = swappiness * (total_cost + 1);
2790 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002791
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002792 fp = (200 - swappiness) * (total_cost + 1);
2793 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002794
Shaohua Li76a33fc2010-05-24 14:32:36 -07002795 fraction[0] = ap;
2796 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002797 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002798out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002799 for_each_evictable_lru(lru) {
2800 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002801 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002802 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002803 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002804
Chris Down9783aa92019-10-06 17:58:32 -07002805 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002806 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2807 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002808
Johannes Weinerf56ce412021-08-19 19:04:21 -07002809 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002810 /*
2811 * Scale a cgroup's reclaim pressure by proportioning
2812 * its current usage to its memory.low or memory.min
2813 * setting.
2814 *
2815 * This is important, as otherwise scanning aggression
2816 * becomes extremely binary -- from nothing as we
2817 * approach the memory protection threshold, to totally
2818 * nominal as we exceed it. This results in requiring
2819 * setting extremely liberal protection thresholds. It
2820 * also means we simply get no protection at all if we
2821 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002822 *
2823 * If there is any protection in place, we reduce scan
2824 * pressure by how much of the total memory used is
2825 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002826 *
Chris Down9de7ca42019-10-06 17:58:35 -07002827 * There is one special case: in the first reclaim pass,
2828 * we skip over all groups that are within their low
2829 * protection. If that fails to reclaim enough pages to
2830 * satisfy the reclaim goal, we come back and override
2831 * the best-effort low protection. However, we still
2832 * ideally want to honor how well-behaved groups are in
2833 * that case instead of simply punishing them all
2834 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002835 * memory they are using, reducing the scan pressure
2836 * again by how much of the total memory used is under
2837 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002838 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002839 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002840 unsigned long protection;
2841
2842 /* memory.low scaling, make sure we retry before OOM */
2843 if (!sc->memcg_low_reclaim && low > min) {
2844 protection = low;
2845 sc->memcg_low_skipped = 1;
2846 } else {
2847 protection = min;
2848 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002849
2850 /* Avoid TOCTOU with earlier protection check */
2851 cgroup_size = max(cgroup_size, protection);
2852
2853 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002854 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002855
2856 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002857 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002858 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002859 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002860 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002861 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002862 } else {
2863 scan = lruvec_size;
2864 }
2865
2866 scan >>= sc->priority;
2867
Johannes Weiner688035f2017-05-03 14:52:07 -07002868 /*
2869 * If the cgroup's already been deleted, make sure to
2870 * scrape out the remaining cache.
2871 */
2872 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002873 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002874
Johannes Weiner688035f2017-05-03 14:52:07 -07002875 switch (scan_balance) {
2876 case SCAN_EQUAL:
2877 /* Scan lists relative to size */
2878 break;
2879 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002880 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002881 * Scan types proportional to swappiness and
2882 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002883 * Make sure we don't miss the last page on
2884 * the offlined memory cgroups because of a
2885 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002886 */
Gavin Shan76073c62020-02-20 20:04:24 -08002887 scan = mem_cgroup_online(memcg) ?
2888 div64_u64(scan * fraction[file], denominator) :
2889 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002890 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002891 break;
2892 case SCAN_FILE:
2893 case SCAN_ANON:
2894 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002895 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002896 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002897 break;
2898 default:
2899 /* Look ma, no brain */
2900 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002901 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002902
Johannes Weiner688035f2017-05-03 14:52:07 -07002903 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002904 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002905}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002906
Dave Hansen2f368a92021-09-02 14:59:23 -07002907/*
2908 * Anonymous LRU management is a waste if there is
2909 * ultimately no way to reclaim the memory.
2910 */
2911static bool can_age_anon_pages(struct pglist_data *pgdat,
2912 struct scan_control *sc)
2913{
2914 /* Aging the anon LRU is valuable if swap is present: */
2915 if (total_swap_pages > 0)
2916 return true;
2917
2918 /* Also valuable if anon pages can be demoted: */
2919 return can_demote(pgdat->node_id, sc);
2920}
2921
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002922#ifdef CONFIG_LRU_GEN
2923
Yu Zhaobaeb9a02022-09-18 02:00:07 -06002924#ifdef CONFIG_LRU_GEN_ENABLED
2925DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2926#define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2927#else
2928DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2929#define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2930#endif
2931
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002932/******************************************************************************
2933 * shorthand helpers
2934 ******************************************************************************/
2935
Yu Zhao37397872022-09-18 02:00:03 -06002936#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2937
2938#define DEFINE_MAX_SEQ(lruvec) \
2939 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2940
2941#define DEFINE_MIN_SEQ(lruvec) \
2942 unsigned long min_seq[ANON_AND_FILE] = { \
2943 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2944 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2945 }
2946
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002947#define for_each_gen_type_zone(gen, type, zone) \
2948 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2949 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2950 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2951
Yu Zhaoa3eb6512022-12-21 21:19:04 -07002952#define get_memcg_gen(seq) ((seq) % MEMCG_NR_GENS)
2953#define get_memcg_bin(bin) ((bin) % MEMCG_NR_BINS)
2954
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002955static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002956{
2957 struct pglist_data *pgdat = NODE_DATA(nid);
2958
2959#ifdef CONFIG_MEMCG
2960 if (memcg) {
2961 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2962
2963 /* for hotadd_new_pgdat() */
2964 if (!lruvec->pgdat)
2965 lruvec->pgdat = pgdat;
2966
2967 return lruvec;
2968 }
2969#endif
2970 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2971
2972 return pgdat ? &pgdat->__lruvec : NULL;
2973}
2974
Yu Zhao37397872022-09-18 02:00:03 -06002975static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2976{
2977 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2978 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2979
Yu Zhaof8b57162022-12-21 21:19:05 -07002980 if (!sc->may_swap)
2981 return 0;
2982
Kalesh Singhb8d031e2023-04-03 15:28:17 -07002983 if (!can_demote(pgdat->node_id, sc) &&
2984 mem_cgroup_get_nr_swap_pages(memcg) <= 0)
Yu Zhao37397872022-09-18 02:00:03 -06002985 return 0;
2986
2987 return mem_cgroup_swappiness(memcg);
2988}
2989
2990static int get_nr_gens(struct lruvec *lruvec, int type)
2991{
2992 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2993}
2994
2995static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2996{
Yu Zhao3c6c3592022-12-21 21:18:59 -07002997 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06002998 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2999 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3000 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3001}
3002
3003/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003004 * mm_struct list
3005 ******************************************************************************/
3006
3007static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3008{
3009 static struct lru_gen_mm_list mm_list = {
3010 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3011 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3012 };
3013
3014#ifdef CONFIG_MEMCG
3015 if (memcg)
3016 return &memcg->mm_list;
3017#endif
3018 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3019
3020 return &mm_list;
3021}
3022
3023void lru_gen_add_mm(struct mm_struct *mm)
3024{
3025 int nid;
3026 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3027 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3028
3029 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3030#ifdef CONFIG_MEMCG
3031 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3032 mm->lru_gen.memcg = memcg;
3033#endif
3034 spin_lock(&mm_list->lock);
3035
3036 for_each_node_state(nid, N_MEMORY) {
3037 struct lruvec *lruvec = get_lruvec(memcg, nid);
3038
3039 if (!lruvec)
3040 continue;
3041
3042 /* the first addition since the last iteration */
3043 if (lruvec->mm_state.tail == &mm_list->fifo)
3044 lruvec->mm_state.tail = &mm->lru_gen.list;
3045 }
3046
3047 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3048
3049 spin_unlock(&mm_list->lock);
3050}
3051
3052void lru_gen_del_mm(struct mm_struct *mm)
3053{
3054 int nid;
3055 struct lru_gen_mm_list *mm_list;
3056 struct mem_cgroup *memcg = NULL;
3057
3058 if (list_empty(&mm->lru_gen.list))
3059 return;
3060
3061#ifdef CONFIG_MEMCG
3062 memcg = mm->lru_gen.memcg;
3063#endif
3064 mm_list = get_mm_list(memcg);
3065
3066 spin_lock(&mm_list->lock);
3067
3068 for_each_node(nid) {
3069 struct lruvec *lruvec = get_lruvec(memcg, nid);
3070
3071 if (!lruvec)
3072 continue;
3073
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003074 /* where the current iteration continues after */
3075 if (lruvec->mm_state.head == &mm->lru_gen.list)
3076 lruvec->mm_state.head = lruvec->mm_state.head->prev;
3077
3078 /* where the last iteration ended before */
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003079 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3080 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003081 }
3082
3083 list_del_init(&mm->lru_gen.list);
3084
3085 spin_unlock(&mm_list->lock);
3086
3087#ifdef CONFIG_MEMCG
3088 mem_cgroup_put(mm->lru_gen.memcg);
3089 mm->lru_gen.memcg = NULL;
3090#endif
3091}
3092
3093#ifdef CONFIG_MEMCG
3094void lru_gen_migrate_mm(struct mm_struct *mm)
3095{
3096 struct mem_cgroup *memcg;
3097 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3098
3099 VM_WARN_ON_ONCE(task->mm != mm);
3100 lockdep_assert_held(&task->alloc_lock);
3101
3102 /* for mm_update_next_owner() */
3103 if (mem_cgroup_disabled())
3104 return;
3105
Yu Zhao578a3a32023-01-15 20:44:05 -07003106 /* migration can happen before addition */
3107 if (!mm->lru_gen.memcg)
3108 return;
3109
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003110 rcu_read_lock();
3111 memcg = mem_cgroup_from_task(task);
3112 rcu_read_unlock();
3113 if (memcg == mm->lru_gen.memcg)
3114 return;
3115
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003116 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3117
3118 lru_gen_del_mm(mm);
3119 lru_gen_add_mm(mm);
3120}
3121#endif
3122
3123/*
3124 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3125 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3126 * bits in a bitmap, k is the number of hash functions and n is the number of
3127 * inserted items.
3128 *
3129 * Page table walkers use one of the two filters to reduce their search space.
3130 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3131 * aging uses the double-buffering technique to flip to the other filter each
3132 * time it produces a new generation. For non-leaf entries that have enough
3133 * leaf entries, the aging carries them over to the next generation in
3134 * walk_pmd_range(); the eviction also report them when walking the rmap
3135 * in lru_gen_look_around().
3136 *
3137 * For future optimizations:
3138 * 1. It's not necessary to keep both filters all the time. The spare one can be
3139 * freed after the RCU grace period and reallocated if needed again.
3140 * 2. And when reallocating, it's worth scaling its size according to the number
3141 * of inserted entries in the other filter, to reduce the memory overhead on
3142 * small systems and false positives on large systems.
3143 * 3. Jenkins' hash function is an alternative to Knuth's.
3144 */
3145#define BLOOM_FILTER_SHIFT 15
3146
3147static inline int filter_gen_from_seq(unsigned long seq)
3148{
3149 return seq % NR_BLOOM_FILTERS;
3150}
3151
3152static void get_item_key(void *item, int *key)
3153{
3154 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3155
3156 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3157
3158 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3159 key[1] = hash >> BLOOM_FILTER_SHIFT;
3160}
3161
3162static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3163{
3164 unsigned long *filter;
3165 int gen = filter_gen_from_seq(seq);
3166
3167 filter = lruvec->mm_state.filters[gen];
3168 if (filter) {
3169 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3170 return;
3171 }
3172
3173 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3174 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3175 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3176}
3177
3178static void update_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;
3187
3188 get_item_key(item, key);
3189
3190 if (!test_bit(key[0], filter))
3191 set_bit(key[0], filter);
3192 if (!test_bit(key[1], filter))
3193 set_bit(key[1], filter);
3194}
3195
3196static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3197{
3198 int key[2];
3199 unsigned long *filter;
3200 int gen = filter_gen_from_seq(seq);
3201
3202 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3203 if (!filter)
3204 return true;
3205
3206 get_item_key(item, key);
3207
3208 return test_bit(key[0], filter) && test_bit(key[1], filter);
3209}
3210
3211static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3212{
3213 int i;
3214 int hist;
3215
3216 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3217
3218 if (walk) {
3219 hist = lru_hist_from_seq(walk->max_seq);
3220
3221 for (i = 0; i < NR_MM_STATS; i++) {
3222 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3223 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3224 walk->mm_stats[i] = 0;
3225 }
3226 }
3227
3228 if (NR_HIST_GENS > 1 && last) {
3229 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3230
3231 for (i = 0; i < NR_MM_STATS; i++)
3232 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3233 }
3234}
3235
3236static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3237{
3238 int type;
3239 unsigned long size = 0;
3240 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3241 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3242
3243 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3244 return true;
3245
3246 clear_bit(key, &mm->lru_gen.bitmap);
3247
3248 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3249 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3250 get_mm_counter(mm, MM_ANONPAGES) +
3251 get_mm_counter(mm, MM_SHMEMPAGES);
3252 }
3253
3254 if (size < MIN_LRU_BATCH)
3255 return true;
3256
3257 return !mmget_not_zero(mm);
3258}
3259
3260static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3261 struct mm_struct **iter)
3262{
3263 bool first = false;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003264 bool last = false;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003265 struct mm_struct *mm = NULL;
3266 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3267 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3268 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3269
3270 /*
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003271 * mm_state->seq is incremented after each iteration of mm_list. There
3272 * are three interesting cases for this page table walker:
3273 * 1. It tries to start a new iteration with a stale max_seq: there is
3274 * nothing left to do.
3275 * 2. It started the next iteration: it needs to reset the Bloom filter
3276 * so that a fresh set of PTE tables can be recorded.
3277 * 3. It ended the current iteration: it needs to reset the mm stats
3278 * counters and tell its caller to increment max_seq.
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003279 */
3280 spin_lock(&mm_list->lock);
3281
3282 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003283
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003284 if (walk->max_seq <= mm_state->seq)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003285 goto done;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003286
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003287 if (!mm_state->head)
3288 mm_state->head = &mm_list->fifo;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003289
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003290 if (mm_state->head == &mm_list->fifo)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003291 first = true;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003292
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003293 do {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003294 mm_state->head = mm_state->head->next;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003295 if (mm_state->head == &mm_list->fifo) {
3296 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3297 last = true;
3298 break;
3299 }
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003300
3301 /* force scan for those added after the last iteration */
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003302 if (!mm_state->tail || mm_state->tail == mm_state->head) {
3303 mm_state->tail = mm_state->head->next;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003304 walk->force_scan = true;
3305 }
3306
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003307 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003308 if (should_skip_mm(mm, walk))
3309 mm = NULL;
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003310 } while (!mm);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003311done:
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003312 if (*iter || last)
3313 reset_mm_stats(lruvec, walk, last);
3314
3315 spin_unlock(&mm_list->lock);
3316
3317 if (mm && first)
3318 reset_bloom_filter(lruvec, walk->max_seq + 1);
3319
3320 if (*iter)
3321 mmput_async(*iter);
3322
3323 *iter = mm;
3324
3325 return last;
3326}
3327
3328static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3329{
3330 bool success = false;
3331 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3332 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3333 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3334
3335 spin_lock(&mm_list->lock);
3336
3337 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3338
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003339 if (max_seq > mm_state->seq) {
3340 mm_state->head = NULL;
3341 mm_state->tail = NULL;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003342 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3343 reset_mm_stats(lruvec, NULL, true);
3344 success = true;
3345 }
3346
3347 spin_unlock(&mm_list->lock);
3348
3349 return success;
3350}
3351
3352/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003353 * refault feedback loop
3354 ******************************************************************************/
3355
3356/*
3357 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3358 *
3359 * The P term is refaulted/(evicted+protected) from a tier in the generation
3360 * currently being evicted; the I term is the exponential moving average of the
3361 * P term over the generations previously evicted, using the smoothing factor
3362 * 1/2; the D term isn't supported.
3363 *
3364 * The setpoint (SP) is always the first tier of one type; the process variable
3365 * (PV) is either any tier of the other type or any other tier of the same
3366 * type.
3367 *
3368 * The error is the difference between the SP and the PV; the correction is to
3369 * turn off protection when SP>PV or turn on protection when SP<PV.
3370 *
3371 * For future optimizations:
3372 * 1. The D term may discount the other two terms over time so that long-lived
3373 * generations can resist stale information.
3374 */
3375struct ctrl_pos {
3376 unsigned long refaulted;
3377 unsigned long total;
3378 int gain;
3379};
3380
3381static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3382 struct ctrl_pos *pos)
3383{
Yu Zhao3c6c3592022-12-21 21:18:59 -07003384 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003385 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3386
3387 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3388 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3389 pos->total = lrugen->avg_total[type][tier] +
3390 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3391 if (tier)
3392 pos->total += lrugen->protected[hist][type][tier - 1];
3393 pos->gain = gain;
3394}
3395
3396static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3397{
3398 int hist, tier;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003399 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003400 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3401 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3402
3403 lockdep_assert_held(&lruvec->lru_lock);
3404
3405 if (!carryover && !clear)
3406 return;
3407
3408 hist = lru_hist_from_seq(seq);
3409
3410 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3411 if (carryover) {
3412 unsigned long sum;
3413
3414 sum = lrugen->avg_refaulted[type][tier] +
3415 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3416 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3417
3418 sum = lrugen->avg_total[type][tier] +
3419 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3420 if (tier)
3421 sum += lrugen->protected[hist][type][tier - 1];
3422 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3423 }
3424
3425 if (clear) {
3426 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3427 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3428 if (tier)
3429 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3430 }
3431 }
3432}
3433
3434static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3435{
3436 /*
3437 * Return true if the PV has a limited number of refaults or a lower
3438 * refaulted/total than the SP.
3439 */
3440 return pv->refaulted < MIN_LRU_BATCH ||
3441 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3442 (sp->refaulted + 1) * pv->total * pv->gain;
3443}
3444
3445/******************************************************************************
3446 * the aging
3447 ******************************************************************************/
3448
Yu Zhao0182f922022-09-18 02:00:04 -06003449/* promote pages accessed through page tables */
3450static int page_update_gen(struct page *page, int gen)
3451{
3452 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3453
3454 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3455 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3456
3457 do {
3458 /* lru_gen_del_page() has isolated this page? */
3459 if (!(old_flags & LRU_GEN_MASK)) {
3460 /* for shrink_page_list() */
3461 new_flags = old_flags | BIT(PG_referenced);
3462 continue;
3463 }
3464
3465 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3466 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3467 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3468
3469 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3470}
3471
Yu Zhao37397872022-09-18 02:00:03 -06003472/* protect pages accessed multiple times through file descriptors */
3473static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3474{
3475 int type = page_is_file_lru(page);
Yu Zhao3c6c3592022-12-21 21:18:59 -07003476 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06003477 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3478 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3479
3480 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3481
3482 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003483 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3484 /* page_update_gen() has promoted this page? */
3485 if (new_gen >= 0 && new_gen != old_gen)
3486 return new_gen;
3487
Yu Zhao37397872022-09-18 02:00:03 -06003488 new_gen = (old_gen + 1) % MAX_NR_GENS;
3489
3490 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3491 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3492 /* for end_page_writeback() */
3493 if (reclaiming)
3494 new_flags |= BIT(PG_reclaim);
3495 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3496
3497 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3498
3499 return new_gen;
3500}
3501
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003502static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3503 int old_gen, int new_gen)
3504{
3505 int type = page_is_file_lru(page);
3506 int zone = page_zonenum(page);
3507 int delta = thp_nr_pages(page);
3508
3509 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3510 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3511
3512 walk->batched++;
3513
3514 walk->nr_pages[old_gen][type][zone] -= delta;
3515 walk->nr_pages[new_gen][type][zone] += delta;
3516}
3517
3518static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3519{
3520 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07003521 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003522
3523 walk->batched = 0;
3524
3525 for_each_gen_type_zone(gen, type, zone) {
3526 enum lru_list lru = type * LRU_INACTIVE_FILE;
3527 int delta = walk->nr_pages[gen][type][zone];
3528
3529 if (!delta)
3530 continue;
3531
3532 walk->nr_pages[gen][type][zone] = 0;
3533 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3534 lrugen->nr_pages[gen][type][zone] + delta);
3535
3536 if (lru_gen_is_active(lruvec, gen))
3537 lru += LRU_ACTIVE;
3538 __update_lru_size(lruvec, lru, zone, delta);
3539 }
3540}
3541
3542static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3543{
3544 struct address_space *mapping;
3545 struct vm_area_struct *vma = args->vma;
3546 struct lru_gen_mm_walk *walk = args->private;
3547
3548 if (!vma_is_accessible(vma))
3549 return true;
3550
3551 if (is_vm_hugetlb_page(vma))
3552 return true;
3553
Yu Zhao3b9ab092022-12-30 14:52:51 -07003554 if (!vma_has_recency(vma))
3555 return true;
3556
3557 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003558 return true;
3559
3560 if (vma == get_gate_vma(vma->vm_mm))
3561 return true;
3562
3563 if (vma_is_anonymous(vma))
3564 return !walk->can_swap;
3565
3566 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3567 return true;
3568
3569 mapping = vma->vm_file->f_mapping;
3570 if (mapping_unevictable(mapping))
3571 return true;
3572
3573 if (shmem_mapping(mapping))
3574 return !walk->can_swap;
3575
3576 /* to exclude special mappings like dax, etc. */
3577 return !mapping->a_ops->readpage;
3578}
3579
3580/*
3581 * Some userspace memory allocators map many single-page VMAs. Instead of
3582 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3583 * table to reduce zigzags and improve cache performance.
3584 */
3585static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3586 unsigned long *vm_start, unsigned long *vm_end)
3587{
3588 unsigned long start = round_up(*vm_end, size);
3589 unsigned long end = (start | ~mask) + 1;
3590
3591 VM_WARN_ON_ONCE(mask & size);
3592 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3593
3594 while (args->vma) {
3595 if (start >= args->vma->vm_end) {
3596 args->vma = args->vma->vm_next;
3597 continue;
3598 }
3599
3600 if (end && end <= args->vma->vm_start)
3601 return false;
3602
3603 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3604 args->vma = args->vma->vm_next;
3605 continue;
3606 }
3607
3608 *vm_start = max(start, args->vma->vm_start);
3609 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3610
3611 return true;
3612 }
3613
3614 return false;
3615}
3616
Yu Zhao0182f922022-09-18 02:00:04 -06003617static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3618{
3619 unsigned long pfn = pte_pfn(pte);
3620
3621 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3622
3623 if (!pte_present(pte) || is_zero_pfn(pfn))
3624 return -1;
3625
3626 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3627 return -1;
3628
3629 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3630 return -1;
3631
3632 return pfn;
3633}
3634
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003635#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3636static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3637{
3638 unsigned long pfn = pmd_pfn(pmd);
3639
3640 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3641
3642 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3643 return -1;
3644
3645 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3646 return -1;
3647
3648 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3649 return -1;
3650
3651 return pfn;
3652}
3653#endif
3654
Yu Zhao0182f922022-09-18 02:00:04 -06003655static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003656 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003657{
3658 struct page *page;
3659
3660 /* try to avoid unnecessary memory loads */
3661 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3662 return NULL;
3663
3664 page = compound_head(pfn_to_page(pfn));
3665 if (page_to_nid(page) != pgdat->node_id)
3666 return NULL;
3667
3668 if (page_memcg_rcu(page) != memcg)
3669 return NULL;
3670
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003671 /* file VMAs can contain anon pages from COW */
3672 if (!page_is_file_lru(page) && !can_swap)
3673 return NULL;
3674
Yu Zhao0182f922022-09-18 02:00:04 -06003675 return page;
3676}
3677
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003678static bool suitable_to_scan(int total, int young)
3679{
3680 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3681
3682 /* suitable if the average number of young PTEs per cacheline is >=1 */
3683 return young * n >= total;
3684}
3685
3686static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3687 struct mm_walk *args)
3688{
3689 int i;
3690 pte_t *pte;
3691 spinlock_t *ptl;
3692 unsigned long addr;
3693 int total = 0;
3694 int young = 0;
3695 struct lru_gen_mm_walk *walk = args->private;
3696 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3697 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3698 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3699
3700 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3701
3702 ptl = pte_lockptr(args->mm, pmd);
3703 if (!spin_trylock(ptl))
3704 return false;
3705
3706 arch_enter_lazy_mmu_mode();
3707
3708 pte = pte_offset_map(pmd, start & PMD_MASK);
3709restart:
3710 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3711 unsigned long pfn;
3712 struct page *page;
3713
3714 total++;
3715 walk->mm_stats[MM_LEAF_TOTAL]++;
3716
3717 pfn = get_pte_pfn(pte[i], args->vma, addr);
3718 if (pfn == -1)
3719 continue;
3720
3721 if (!pte_young(pte[i])) {
3722 walk->mm_stats[MM_LEAF_OLD]++;
3723 continue;
3724 }
3725
3726 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3727 if (!page)
3728 continue;
3729
3730 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3731 VM_WARN_ON_ONCE(true);
3732
3733 young++;
3734 walk->mm_stats[MM_LEAF_YOUNG]++;
3735
3736 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3737 !(PageAnon(page) && PageSwapBacked(page) &&
3738 !PageSwapCache(page)))
3739 set_page_dirty(page);
3740
3741 old_gen = page_update_gen(page, new_gen);
3742 if (old_gen >= 0 && old_gen != new_gen)
3743 update_batch_size(walk, page, old_gen, new_gen);
3744 }
3745
3746 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3747 goto restart;
3748
3749 pte_unmap(pte);
3750
3751 arch_leave_lazy_mmu_mode();
3752 spin_unlock(ptl);
3753
3754 return suitable_to_scan(total, young);
3755}
3756
3757#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3758static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3759 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3760{
3761 int i;
3762 pmd_t *pmd;
3763 spinlock_t *ptl;
3764 struct lru_gen_mm_walk *walk = args->private;
3765 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3766 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3767 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3768
3769 VM_WARN_ON_ONCE(pud_leaf(*pud));
3770
3771 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3772 if (*start == -1) {
3773 *start = next;
3774 return;
3775 }
3776
3777 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3778 if (i && i <= MIN_LRU_BATCH) {
3779 __set_bit(i - 1, bitmap);
3780 return;
3781 }
3782
3783 pmd = pmd_offset(pud, *start);
3784
3785 ptl = pmd_lockptr(args->mm, pmd);
3786 if (!spin_trylock(ptl))
3787 goto done;
3788
3789 arch_enter_lazy_mmu_mode();
3790
3791 do {
3792 unsigned long pfn;
3793 struct page *page;
3794 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3795
3796 pfn = get_pmd_pfn(pmd[i], vma, addr);
3797 if (pfn == -1)
3798 goto next;
3799
3800 if (!pmd_trans_huge(pmd[i])) {
Juergen Gross23811792022-11-23 07:45:10 +01003801 if (arch_has_hw_nonleaf_pmd_young() &&
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003802 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003803 pmdp_test_and_clear_young(vma, addr, pmd + i);
3804 goto next;
3805 }
3806
3807 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3808 if (!page)
3809 goto next;
3810
3811 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3812 goto next;
3813
3814 walk->mm_stats[MM_LEAF_YOUNG]++;
3815
3816 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3817 !(PageAnon(page) && PageSwapBacked(page) &&
3818 !PageSwapCache(page)))
3819 set_page_dirty(page);
3820
3821 old_gen = page_update_gen(page, new_gen);
3822 if (old_gen >= 0 && old_gen != new_gen)
3823 update_batch_size(walk, page, old_gen, new_gen);
3824next:
3825 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3826 } while (i <= MIN_LRU_BATCH);
3827
3828 arch_leave_lazy_mmu_mode();
3829 spin_unlock(ptl);
3830done:
3831 *start = -1;
3832 bitmap_zero(bitmap, MIN_LRU_BATCH);
3833}
3834#else
3835static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3836 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3837{
3838}
3839#endif
3840
3841static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3842 struct mm_walk *args)
3843{
3844 int i;
3845 pmd_t *pmd;
3846 unsigned long next;
3847 unsigned long addr;
3848 struct vm_area_struct *vma;
3849 unsigned long pos = -1;
3850 struct lru_gen_mm_walk *walk = args->private;
3851 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3852
3853 VM_WARN_ON_ONCE(pud_leaf(*pud));
3854
3855 /*
3856 * Finish an entire PMD in two passes: the first only reaches to PTE
3857 * tables to avoid taking the PMD lock; the second, if necessary, takes
3858 * the PMD lock to clear the accessed bit in PMD entries.
3859 */
3860 pmd = pmd_offset(pud, start & PUD_MASK);
3861restart:
3862 /* walk_pte_range() may call get_next_vma() */
3863 vma = args->vma;
3864 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3865 pmd_t val = pmd_read_atomic(pmd + i);
3866
3867 /* for pmd_read_atomic() */
3868 barrier();
3869
3870 next = pmd_addr_end(addr, end);
3871
3872 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3873 walk->mm_stats[MM_LEAF_TOTAL]++;
3874 continue;
3875 }
3876
3877#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3878 if (pmd_trans_huge(val)) {
3879 unsigned long pfn = pmd_pfn(val);
3880 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3881
3882 walk->mm_stats[MM_LEAF_TOTAL]++;
3883
3884 if (!pmd_young(val)) {
3885 walk->mm_stats[MM_LEAF_OLD]++;
3886 continue;
3887 }
3888
3889 /* try to avoid unnecessary memory loads */
3890 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3891 continue;
3892
3893 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3894 continue;
3895 }
3896#endif
3897 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3898
Juergen Gross23811792022-11-23 07:45:10 +01003899 if (arch_has_hw_nonleaf_pmd_young() &&
3900 get_cap(LRU_GEN_NONLEAF_YOUNG)) {
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003901 if (!pmd_young(val))
3902 continue;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003903
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003904 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3905 }
Juergen Gross23811792022-11-23 07:45:10 +01003906
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003907 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3908 continue;
3909
3910 walk->mm_stats[MM_NONLEAF_FOUND]++;
3911
3912 if (!walk_pte_range(&val, addr, next, args))
3913 continue;
3914
3915 walk->mm_stats[MM_NONLEAF_ADDED]++;
3916
3917 /* carry over to the next generation */
3918 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3919 }
3920
3921 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3922
3923 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3924 goto restart;
3925}
3926
3927static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3928 struct mm_walk *args)
3929{
3930 int i;
3931 pud_t *pud;
3932 unsigned long addr;
3933 unsigned long next;
3934 struct lru_gen_mm_walk *walk = args->private;
3935
3936 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3937
3938 pud = pud_offset(p4d, start & P4D_MASK);
3939restart:
3940 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3941 pud_t val = READ_ONCE(pud[i]);
3942
3943 next = pud_addr_end(addr, end);
3944
3945 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3946 continue;
3947
3948 walk_pmd_range(&val, addr, next, args);
3949
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003950 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3951 end = (addr | ~PUD_MASK) + 1;
3952 goto done;
3953 }
3954 }
3955
3956 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3957 goto restart;
3958
3959 end = round_up(end, P4D_SIZE);
3960done:
3961 if (!end || !args->vma)
3962 return 1;
3963
3964 walk->next_addr = max(end, args->vma->vm_start);
3965
3966 return -EAGAIN;
3967}
3968
3969static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3970{
3971 static const struct mm_walk_ops mm_walk_ops = {
3972 .test_walk = should_skip_vma,
3973 .p4d_entry = walk_pud_range,
3974 };
3975
3976 int err;
3977 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3978
3979 walk->next_addr = FIRST_USER_ADDRESS;
3980
3981 do {
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003982 DEFINE_MAX_SEQ(lruvec);
3983
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003984 err = -EBUSY;
3985
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07003986 /* another thread might have called inc_max_seq() */
3987 if (walk->max_seq != max_seq)
3988 break;
3989
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003990 /* page_update_gen() requires stable page_memcg() */
3991 if (!mem_cgroup_trylock_pages(memcg))
3992 break;
3993
3994 /* the caller might be holding the lock for write */
3995 if (mmap_read_trylock(mm)) {
3996 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3997
3998 mmap_read_unlock(mm);
3999 }
4000
4001 mem_cgroup_unlock_pages();
4002
4003 if (walk->batched) {
4004 spin_lock_irq(&lruvec->lru_lock);
4005 reset_batch_size(lruvec, walk);
4006 spin_unlock_irq(&lruvec->lru_lock);
4007 }
4008
4009 cond_resched();
4010 } while (err == -EAGAIN);
4011}
4012
Yu Zhaof8b57162022-12-21 21:19:05 -07004013static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat, bool force_alloc)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004014{
4015 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4016
4017 if (pgdat && current_is_kswapd()) {
4018 VM_WARN_ON_ONCE(walk);
4019
4020 walk = &pgdat->mm_walk;
Yu Zhaof8b57162022-12-21 21:19:05 -07004021 } else if (!walk && force_alloc) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004022 VM_WARN_ON_ONCE(current_is_kswapd());
4023
4024 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4025 }
4026
4027 current->reclaim_state->mm_walk = walk;
4028
4029 return walk;
4030}
4031
4032static void clear_mm_walk(void)
4033{
4034 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4035
4036 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4037 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4038
4039 current->reclaim_state->mm_walk = NULL;
4040
4041 if (!current_is_kswapd())
4042 kfree(walk);
4043}
4044
Yu Zhao4983c522022-09-18 02:00:09 -06004045static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004046{
Yu Zhao4983c522022-09-18 02:00:09 -06004047 int zone;
4048 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004049 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06004050 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
Yu Zhao37397872022-09-18 02:00:03 -06004051
Yu Zhao4983c522022-09-18 02:00:09 -06004052 if (type == LRU_GEN_ANON && !can_swap)
4053 goto done;
4054
4055 /* prevent cold/hot inversion if force_scan is true */
4056 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004057 struct list_head *head = &lrugen->pages[old_gen][type][zone];
Yu Zhao4983c522022-09-18 02:00:09 -06004058
4059 while (!list_empty(head)) {
4060 struct page *page = lru_to_page(head);
4061
4062 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4063 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4064 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4065 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4066
4067 new_gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004068 list_move_tail(&page->lru, &lrugen->pages[new_gen][type][zone]);
Yu Zhao4983c522022-09-18 02:00:09 -06004069
4070 if (!--remaining)
4071 return false;
4072 }
4073 }
4074done:
Yu Zhao37397872022-09-18 02:00:03 -06004075 reset_ctrl_pos(lruvec, type, true);
4076 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
Yu Zhao4983c522022-09-18 02:00:09 -06004077
4078 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004079}
4080
4081static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4082{
4083 int gen, type, zone;
4084 bool success = false;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004085 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004086 DEFINE_MIN_SEQ(lruvec);
4087
4088 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4089
4090 /* find the oldest populated generation */
4091 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4092 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4093 gen = lru_gen_from_seq(min_seq[type]);
4094
4095 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004096 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhao37397872022-09-18 02:00:03 -06004097 goto next;
4098 }
4099
4100 min_seq[type]++;
4101 }
4102next:
4103 ;
4104 }
4105
Yu Zhao3c6c3592022-12-21 21:18:59 -07004106 /* see the comment on lru_gen_page */
Yu Zhao37397872022-09-18 02:00:03 -06004107 if (can_swap) {
4108 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4109 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4110 }
4111
4112 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4113 if (min_seq[type] == lrugen->min_seq[type])
4114 continue;
4115
4116 reset_ctrl_pos(lruvec, type, true);
4117 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4118 success = true;
4119 }
4120
4121 return success;
4122}
4123
Yu Zhao4983c522022-09-18 02:00:09 -06004124static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
Yu Zhao37397872022-09-18 02:00:03 -06004125{
4126 int prev, next;
4127 int type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004128 struct lru_gen_page *lrugen = &lruvec->lrugen;
Kalesh Singh12fb1c32023-08-01 19:56:03 -07004129restart:
Yu Zhao37397872022-09-18 02:00:03 -06004130 spin_lock_irq(&lruvec->lru_lock);
4131
4132 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4133
Yu Zhao37397872022-09-18 02:00:03 -06004134 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4135 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4136 continue;
4137
Yu Zhao4983c522022-09-18 02:00:09 -06004138 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
Yu Zhao37397872022-09-18 02:00:03 -06004139
Kalesh Singh12fb1c32023-08-01 19:56:03 -07004140 if (inc_min_seq(lruvec, type, can_swap))
4141 continue;
4142
4143 spin_unlock_irq(&lruvec->lru_lock);
4144 cond_resched();
4145 goto restart;
Yu Zhao37397872022-09-18 02:00:03 -06004146 }
4147
4148 /*
4149 * Update the active/inactive LRU sizes for compatibility. Both sides of
4150 * the current max_seq need to be covered, since max_seq+1 can overlap
4151 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4152 * overlap, cold/hot inversion happens.
4153 */
4154 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4155 next = lru_gen_from_seq(lrugen->max_seq + 1);
4156
4157 for (type = 0; type < ANON_AND_FILE; type++) {
4158 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4159 enum lru_list lru = type * LRU_INACTIVE_FILE;
4160 long delta = lrugen->nr_pages[prev][type][zone] -
4161 lrugen->nr_pages[next][type][zone];
4162
4163 if (!delta)
4164 continue;
4165
4166 __update_lru_size(lruvec, lru, zone, delta);
4167 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4168 }
4169 }
4170
4171 for (type = 0; type < ANON_AND_FILE; type++)
4172 reset_ctrl_pos(lruvec, type, false);
4173
Yu Zhao430499c2022-09-18 02:00:08 -06004174 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhao37397872022-09-18 02:00:03 -06004175 /* make sure preceding modifications appear */
4176 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004177
Yu Zhao37397872022-09-18 02:00:03 -06004178 spin_unlock_irq(&lruvec->lru_lock);
4179}
4180
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004181static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
Yu Zhao4983c522022-09-18 02:00:09 -06004182 struct scan_control *sc, bool can_swap, bool force_scan)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004183{
4184 bool success;
4185 struct lru_gen_mm_walk *walk;
4186 struct mm_struct *mm = NULL;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004187 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004188
4189 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4190
4191 /* see the comment in iterate_mm_list() */
4192 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4193 success = false;
4194 goto done;
4195 }
4196
4197 /*
4198 * If the hardware doesn't automatically set the accessed bit, fallback
4199 * to lru_gen_look_around(), which only clears the accessed bit in a
4200 * handful of PTEs. Spreading the work out over a period of time usually
4201 * is less efficient, but it avoids bursty page faults.
4202 */
Yu Zhao18580ef2022-12-21 21:19:06 -07004203 if (!arch_has_hw_pte_young() || !get_cap(LRU_GEN_MM_WALK)) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004204 success = iterate_mm_list_nowalk(lruvec, max_seq);
4205 goto done;
4206 }
4207
Yu Zhaof8b57162022-12-21 21:19:05 -07004208 walk = set_mm_walk(NULL, true);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004209 if (!walk) {
4210 success = iterate_mm_list_nowalk(lruvec, max_seq);
4211 goto done;
4212 }
4213
4214 walk->lruvec = lruvec;
4215 walk->max_seq = max_seq;
4216 walk->can_swap = can_swap;
Yu Zhao4983c522022-09-18 02:00:09 -06004217 walk->force_scan = force_scan;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004218
4219 do {
4220 success = iterate_mm_list(lruvec, walk, &mm);
4221 if (mm)
4222 walk_mm(lruvec, mm, walk);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004223 } while (mm);
4224done:
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004225 if (success)
4226 inc_max_seq(lruvec, can_swap, force_scan);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004227
Kalesh Singhe4d3bd92023-04-13 14:43:26 -07004228 return success;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004229}
4230
Yu Zhaoa5998f92022-12-21 21:19:02 -07004231static bool lruvec_is_sizable(struct lruvec *lruvec, struct scan_control *sc)
Yu Zhao37397872022-09-18 02:00:03 -06004232{
Yu Zhaoa5998f92022-12-21 21:19:02 -07004233 int gen, type, zone;
4234 unsigned long total = 0;
4235 bool can_swap = get_swappiness(lruvec, sc);
4236 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004237 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4238 DEFINE_MAX_SEQ(lruvec);
4239 DEFINE_MIN_SEQ(lruvec);
4240
Yu Zhaoa5998f92022-12-21 21:19:02 -07004241 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4242 unsigned long seq;
4243
4244 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4245 gen = lru_gen_from_seq(seq);
4246
4247 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4248 total += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4249 }
4250 }
4251
4252 /* whether the size is big enough to be helpful */
4253 return mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4254}
4255
4256static bool lruvec_is_reclaimable(struct lruvec *lruvec, struct scan_control *sc,
4257 unsigned long min_ttl)
4258{
4259 int gen;
4260 unsigned long birth;
4261 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4262 DEFINE_MIN_SEQ(lruvec);
4263
Yu Zhaoa5998f92022-12-21 21:19:02 -07004264 /* see the comment on lru_gen_page */
4265 gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4266 birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4267
4268 if (time_is_after_jiffies(birth + min_ttl))
4269 return false;
4270
4271 if (!lruvec_is_sizable(lruvec, sc))
4272 return false;
4273
Yu Zhao37397872022-09-18 02:00:03 -06004274 mem_cgroup_calculate_protection(NULL, memcg);
4275
Yu Zhaoa5998f92022-12-21 21:19:02 -07004276 return !mem_cgroup_below_min(memcg);
Yu Zhao37397872022-09-18 02:00:03 -06004277}
4278
Yu Zhao430499c2022-09-18 02:00:08 -06004279/* to protect the working set of the last N jiffies */
4280static unsigned long lru_gen_min_ttl __read_mostly;
4281
Yu Zhao37397872022-09-18 02:00:03 -06004282static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4283{
4284 struct mem_cgroup *memcg;
Yu Zhao430499c2022-09-18 02:00:08 -06004285 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhao37397872022-09-18 02:00:03 -06004286
4287 VM_WARN_ON_ONCE(!current_is_kswapd());
4288
Yu Zhaoa5998f92022-12-21 21:19:02 -07004289 /* check the order to exclude compaction-induced reclaim */
4290 if (!min_ttl || sc->order || sc->priority == DEF_PRIORITY)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004291 return;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004292
Yu Zhao37397872022-09-18 02:00:03 -06004293 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4294 do {
4295 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4296
Yu Zhaoa5998f92022-12-21 21:19:02 -07004297 if (lruvec_is_reclaimable(lruvec, sc, min_ttl)) {
4298 mem_cgroup_iter_break(NULL, memcg);
4299 return;
4300 }
Yu Zhao37397872022-09-18 02:00:03 -06004301
4302 cond_resched();
4303 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004304
Yu Zhao430499c2022-09-18 02:00:08 -06004305 /*
4306 * The main goal is to OOM kill if every generation from all memcgs is
4307 * younger than min_ttl. However, another possibility is all memcgs are
Yu Zhaoa5998f92022-12-21 21:19:02 -07004308 * either too small or below min.
Yu Zhao430499c2022-09-18 02:00:08 -06004309 */
4310 if (mutex_trylock(&oom_lock)) {
4311 struct oom_control oc = {
4312 .gfp_mask = sc->gfp_mask,
4313 };
4314
4315 out_of_memory(&oc);
4316
4317 mutex_unlock(&oom_lock);
4318 }
Yu Zhao37397872022-09-18 02:00:03 -06004319}
4320
Yu Zhao0182f922022-09-18 02:00:04 -06004321/*
4322 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004323 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4324 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4325 * the PTE table to the Bloom filter. This forms a feedback loop between the
4326 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004327 */
4328void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4329{
4330 int i;
4331 pte_t *pte;
4332 unsigned long start;
4333 unsigned long end;
4334 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004335 struct lru_gen_mm_walk *walk;
4336 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004337 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4338 struct page *page = pvmw->page;
Kalesh Singh0f986fa2023-08-01 19:56:04 -07004339 bool can_swap = !page_is_file_lru(page);
Yu Zhao0182f922022-09-18 02:00:04 -06004340 struct mem_cgroup *memcg = page_memcg(page);
4341 struct pglist_data *pgdat = page_pgdat(page);
4342 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4343 DEFINE_MAX_SEQ(lruvec);
4344 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4345
4346 lockdep_assert_held(pvmw->ptl);
4347 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4348
4349 if (spin_is_contended(pvmw->ptl))
4350 return;
4351
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004352 /* avoid taking the LRU lock under the PTL when possible */
4353 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4354
Yu Zhao0182f922022-09-18 02:00:04 -06004355 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4356 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4357
4358 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4359 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4360 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4361 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4362 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4363 else {
4364 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4365 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4366 }
4367 }
4368
4369 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4370
4371 rcu_read_lock();
4372 arch_enter_lazy_mmu_mode();
4373
4374 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4375 unsigned long pfn;
4376
4377 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4378 if (pfn == -1)
4379 continue;
4380
4381 if (!pte_young(pte[i]))
4382 continue;
4383
Kalesh Singh0f986fa2023-08-01 19:56:04 -07004384 page = get_pfn_page(pfn, memcg, pgdat, can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004385 if (!page)
4386 continue;
4387
4388 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4389 VM_WARN_ON_ONCE(true);
4390
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004391 young++;
4392
Yu Zhao0182f922022-09-18 02:00:04 -06004393 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4394 !(PageAnon(page) && PageSwapBacked(page) &&
4395 !PageSwapCache(page)))
4396 set_page_dirty(page);
4397
4398 old_gen = page_lru_gen(page);
4399 if (old_gen < 0)
4400 SetPageReferenced(page);
4401 else if (old_gen != new_gen)
4402 __set_bit(i, bitmap);
4403 }
4404
4405 arch_leave_lazy_mmu_mode();
4406 rcu_read_unlock();
4407
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004408 /* feedback from rmap walkers to page table walkers */
4409 if (suitable_to_scan(i, young))
4410 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4411
4412 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004413 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4414 page = pte_page(pte[i]);
4415 activate_page(page);
4416 }
4417 return;
4418 }
4419
4420 /* page_update_gen() requires stable page_memcg() */
4421 if (!mem_cgroup_trylock_pages(memcg))
4422 return;
4423
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004424 if (!walk) {
4425 spin_lock_irq(&lruvec->lru_lock);
4426 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4427 }
Yu Zhao0182f922022-09-18 02:00:04 -06004428
4429 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4430 page = compound_head(pte_page(pte[i]));
4431 if (page_memcg_rcu(page) != memcg)
4432 continue;
4433
4434 old_gen = page_update_gen(page, new_gen);
4435 if (old_gen < 0 || old_gen == new_gen)
4436 continue;
4437
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004438 if (walk)
4439 update_batch_size(walk, page, old_gen, new_gen);
4440 else
4441 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004442 }
4443
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004444 if (!walk)
4445 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004446
4447 mem_cgroup_unlock_pages();
4448}
4449
Yu Zhao37397872022-09-18 02:00:03 -06004450/******************************************************************************
4451 * the eviction
4452 ******************************************************************************/
4453
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004454static bool sort_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc,
4455 int tier_idx)
Yu Zhao37397872022-09-18 02:00:03 -06004456{
4457 bool success;
4458 int gen = page_lru_gen(page);
4459 int type = page_is_file_lru(page);
4460 int zone = page_zonenum(page);
4461 int delta = thp_nr_pages(page);
4462 int refs = page_lru_refs(page);
4463 int tier = lru_tier_from_refs(refs);
Yu Zhao3c6c3592022-12-21 21:18:59 -07004464 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004465
4466 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4467
4468 /* unevictable */
4469 if (!page_evictable(page)) {
4470 success = lru_gen_del_page(lruvec, page, true);
4471 VM_WARN_ON_ONCE_PAGE(!success, page);
4472 SetPageUnevictable(page);
4473 add_page_to_lru_list(page, lruvec);
4474 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4475 return true;
4476 }
4477
4478 /* dirty lazyfree */
4479 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4480 success = lru_gen_del_page(lruvec, page, true);
4481 VM_WARN_ON_ONCE_PAGE(!success, page);
4482 SetPageSwapBacked(page);
4483 add_page_to_lru_list_tail(page, lruvec);
4484 return true;
4485 }
4486
Yu Zhao0182f922022-09-18 02:00:04 -06004487 /* promoted */
4488 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07004489 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao0182f922022-09-18 02:00:04 -06004490 return true;
4491 }
4492
Yu Zhao37397872022-09-18 02:00:03 -06004493 /* protected */
4494 if (tier > tier_idx) {
4495 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4496
4497 gen = page_inc_gen(lruvec, page, false);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004498 list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004499
4500 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4501 lrugen->protected[hist][type][tier - 1] + delta);
Yu Zhao37397872022-09-18 02:00:03 -06004502 return true;
4503 }
4504
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004505 /* ineligible */
4506 if (zone > sc->reclaim_idx) {
4507 gen = page_inc_gen(lruvec, page, false);
4508 list_move_tail(&page->lru, &lrugen->pages[gen][type][zone]);
4509 return true;
4510 }
4511
Yu Zhao37397872022-09-18 02:00:03 -06004512 /* waiting for writeback */
4513 if (PageLocked(page) || PageWriteback(page) ||
4514 (type == LRU_GEN_FILE && PageDirty(page))) {
4515 gen = page_inc_gen(lruvec, page, true);
Yu Zhaodf91dc92022-12-21 21:19:00 -07004516 list_move(&page->lru, &lrugen->pages[gen][type][zone]);
Yu Zhao37397872022-09-18 02:00:03 -06004517 return true;
4518 }
4519
4520 return false;
4521}
4522
4523static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4524{
4525 bool success;
4526
Yu Zhao37397872022-09-18 02:00:03 -06004527 /* swapping inhibited */
Yu Zhaof8b57162022-12-21 21:19:05 -07004528 if (!(sc->gfp_mask & __GFP_IO) &&
Yu Zhao37397872022-09-18 02:00:03 -06004529 (PageDirty(page) ||
4530 (PageAnon(page) && !PageSwapCache(page))))
4531 return false;
4532
4533 /* raced with release_pages() */
4534 if (!get_page_unless_zero(page))
4535 return false;
4536
4537 /* raced with another isolation */
4538 if (!TestClearPageLRU(page)) {
4539 put_page(page);
4540 return false;
4541 }
4542
4543 /* see the comment on MAX_NR_TIERS */
4544 if (!PageReferenced(page))
4545 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4546
4547 /* for shrink_page_list() */
4548 ClearPageReclaim(page);
4549 ClearPageReferenced(page);
4550
4551 success = lru_gen_del_page(lruvec, page, true);
4552 VM_WARN_ON_ONCE_PAGE(!success, page);
4553
4554 return true;
4555}
4556
4557static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4558 int type, int tier, struct list_head *list)
4559{
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004560 int i;
4561 int gen;
Yu Zhao37397872022-09-18 02:00:03 -06004562 enum vm_event_item item;
4563 int sorted = 0;
4564 int scanned = 0;
4565 int isolated = 0;
4566 int remaining = MAX_LRU_BATCH;
Yu Zhao3c6c3592022-12-21 21:18:59 -07004567 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao37397872022-09-18 02:00:03 -06004568 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4569
4570 VM_WARN_ON_ONCE(!list_empty(list));
4571
4572 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4573 return 0;
4574
4575 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4576
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004577 for (i = MAX_NR_ZONES; i > 0; i--) {
Yu Zhao37397872022-09-18 02:00:03 -06004578 LIST_HEAD(moved);
4579 int skipped = 0;
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004580 int zone = (sc->reclaim_idx + i) % MAX_NR_ZONES;
Yu Zhaodf91dc92022-12-21 21:19:00 -07004581 struct list_head *head = &lrugen->pages[gen][type][zone];
Yu Zhao37397872022-09-18 02:00:03 -06004582
4583 while (!list_empty(head)) {
4584 struct page *page = lru_to_page(head);
4585 int delta = thp_nr_pages(page);
4586
4587 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4588 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4589 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4590 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4591
4592 scanned += delta;
4593
Kalesh Singhbf03a7c2023-08-01 19:56:02 -07004594 if (sort_page(lruvec, page, sc, tier))
Yu Zhao37397872022-09-18 02:00:03 -06004595 sorted += delta;
4596 else if (isolate_page(lruvec, page, sc)) {
4597 list_add(&page->lru, list);
4598 isolated += delta;
4599 } else {
4600 list_move(&page->lru, &moved);
4601 skipped += delta;
4602 }
4603
4604 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4605 break;
4606 }
4607
4608 if (skipped) {
4609 list_splice(&moved, head);
4610 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4611 }
4612
4613 if (!remaining || isolated >= MIN_LRU_BATCH)
4614 break;
4615 }
4616
4617 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4618 if (!cgroup_reclaim(sc)) {
4619 __count_vm_events(item, isolated);
4620 __count_vm_events(PGREFILL, sorted);
4621 }
4622 __count_memcg_events(memcg, item, isolated);
4623 __count_memcg_events(memcg, PGREFILL, sorted);
4624 __count_vm_events(PGSCAN_ANON + type, isolated);
4625
4626 /*
Yu Zhaof8b57162022-12-21 21:19:05 -07004627 * There might not be eligible pages due to reclaim_idx. Check the
4628 * remaining to prevent livelock if it's not making progress.
Yu Zhao37397872022-09-18 02:00:03 -06004629 */
4630 return isolated || !remaining ? scanned : 0;
4631}
4632
4633static int get_tier_idx(struct lruvec *lruvec, int type)
4634{
4635 int tier;
4636 struct ctrl_pos sp, pv;
4637
4638 /*
4639 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4640 * This value is chosen because any other tier would have at least twice
4641 * as many refaults as the first tier.
4642 */
4643 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4644 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4645 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4646 if (!positive_ctrl_err(&sp, &pv))
4647 break;
4648 }
4649
4650 return tier - 1;
4651}
4652
4653static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4654{
4655 int type, tier;
4656 struct ctrl_pos sp, pv;
4657 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4658
4659 /*
4660 * Compare the first tier of anon with that of file to determine which
4661 * type to scan. Also need to compare other tiers of the selected type
4662 * with the first tier of the other type to determine the last tier (of
4663 * the selected type) to evict.
4664 */
4665 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4666 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4667 type = positive_ctrl_err(&sp, &pv);
4668
4669 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4670 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4671 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4672 if (!positive_ctrl_err(&sp, &pv))
4673 break;
4674 }
4675
4676 *tier_idx = tier - 1;
4677
4678 return type;
4679}
4680
4681static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4682 int *type_scanned, struct list_head *list)
4683{
4684 int i;
4685 int type;
4686 int scanned;
4687 int tier = -1;
4688 DEFINE_MIN_SEQ(lruvec);
4689
4690 /*
4691 * Try to make the obvious choice first. When anon and file are both
4692 * available from the same generation, interpret swappiness 1 as file
4693 * first and 200 as anon first.
4694 */
4695 if (!swappiness)
4696 type = LRU_GEN_FILE;
4697 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4698 type = LRU_GEN_ANON;
4699 else if (swappiness == 1)
4700 type = LRU_GEN_FILE;
4701 else if (swappiness == 200)
4702 type = LRU_GEN_ANON;
4703 else
4704 type = get_type_to_scan(lruvec, swappiness, &tier);
4705
4706 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4707 if (tier < 0)
4708 tier = get_tier_idx(lruvec, type);
4709
4710 scanned = scan_pages(lruvec, sc, type, tier, list);
4711 if (scanned)
4712 break;
4713
4714 type = !type;
4715 tier = -1;
4716 }
4717
4718 *type_scanned = type;
4719
4720 return scanned;
4721}
4722
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004723static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
Yu Zhao37397872022-09-18 02:00:03 -06004724{
4725 int type;
4726 int scanned;
4727 int reclaimed;
4728 LIST_HEAD(list);
Yu Zhao79e66ea2022-11-15 18:38:07 -07004729 LIST_HEAD(clean);
Yu Zhao37397872022-09-18 02:00:03 -06004730 struct page *page;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004731 struct page *next;
Yu Zhao37397872022-09-18 02:00:03 -06004732 enum vm_event_item item;
4733 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004734 struct lru_gen_mm_walk *walk;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004735 bool skip_retry = false;
Yu Zhao37397872022-09-18 02:00:03 -06004736 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4737 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4738
4739 spin_lock_irq(&lruvec->lru_lock);
4740
4741 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4742
4743 scanned += try_to_inc_min_seq(lruvec, swappiness);
4744
4745 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4746 scanned = 0;
4747
4748 spin_unlock_irq(&lruvec->lru_lock);
4749
4750 if (list_empty(&list))
4751 return scanned;
Yu Zhao79e66ea2022-11-15 18:38:07 -07004752retry:
Yu Zhao37397872022-09-18 02:00:03 -06004753 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
Yu Zhao79e66ea2022-11-15 18:38:07 -07004754 sc->nr_reclaimed += reclaimed;
Yu Zhao37397872022-09-18 02:00:03 -06004755
Yu Zhao79e66ea2022-11-15 18:38:07 -07004756 list_for_each_entry_safe_reverse(page, next, &list, lru) {
4757 if (!page_evictable(page)) {
4758 list_del(&page->lru);
4759 putback_lru_page(page);
4760 continue;
4761 }
Yu Zhao37397872022-09-18 02:00:03 -06004762
Yu Zhao37397872022-09-18 02:00:03 -06004763 if (PageReclaim(page) &&
Yu Zhao79e66ea2022-11-15 18:38:07 -07004764 (PageDirty(page) || PageWriteback(page))) {
4765 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4766 if (PageWorkingset(page))
4767 SetPageReferenced(page);
4768 continue;
4769 }
4770
4771 if (skip_retry || PageActive(page) || PageReferenced(page) ||
4772 page_mapped(page) || PageLocked(page) ||
4773 PageDirty(page) || PageWriteback(page)) {
4774 /* don't add rejected pages to the oldest generation */
4775 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS,
4776 BIT(PG_active));
4777 continue;
4778 }
4779
4780 /* retry pages that may have missed rotate_reclaimable_page() */
4781 list_move(&page->lru, &clean);
4782 sc->nr_scanned -= thp_nr_pages(page);
Yu Zhao37397872022-09-18 02:00:03 -06004783 }
4784
4785 spin_lock_irq(&lruvec->lru_lock);
4786
4787 move_pages_to_lru(lruvec, &list);
4788
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004789 walk = current->reclaim_state->mm_walk;
4790 if (walk && walk->batched)
4791 reset_batch_size(lruvec, walk);
4792
Yu Zhao37397872022-09-18 02:00:03 -06004793 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4794 if (!cgroup_reclaim(sc))
4795 __count_vm_events(item, reclaimed);
4796 __count_memcg_events(memcg, item, reclaimed);
4797 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4798
4799 spin_unlock_irq(&lruvec->lru_lock);
4800
4801 mem_cgroup_uncharge_list(&list);
4802 free_unref_page_list(&list);
4803
Yu Zhao79e66ea2022-11-15 18:38:07 -07004804 INIT_LIST_HEAD(&list);
4805 list_splice_init(&clean, &list);
4806
4807 if (!list_empty(&list)) {
4808 skip_retry = true;
4809 goto retry;
4810 }
Yu Zhao37397872022-09-18 02:00:03 -06004811
4812 return scanned;
4813}
4814
Yu Zhaocb3958d2022-12-21 21:19:03 -07004815static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq,
4816 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4817{
4818 int gen, type, zone;
4819 unsigned long old = 0;
4820 unsigned long young = 0;
4821 unsigned long total = 0;
4822 struct lru_gen_page *lrugen = &lruvec->lrugen;
4823 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4824 DEFINE_MIN_SEQ(lruvec);
4825
4826 /* whether this lruvec is completely out of cold pages */
4827 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq) {
4828 *nr_to_scan = 0;
4829 return true;
4830 }
4831
4832 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4833 unsigned long seq;
4834
4835 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4836 unsigned long size = 0;
4837
4838 gen = lru_gen_from_seq(seq);
4839
4840 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4841 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4842
4843 total += size;
4844 if (seq == max_seq)
4845 young += size;
4846 else if (seq + MIN_NR_GENS == max_seq)
4847 old += size;
4848 }
4849 }
4850
4851 /* try to scrape all its memory if this memcg was deleted */
4852 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4853
4854 /*
4855 * The aging tries to be lazy to reduce the overhead, while the eviction
4856 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4857 * ideal number of generations is MIN_NR_GENS+1.
4858 */
4859 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4860 return false;
4861
4862 /*
4863 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4864 * of the total number of pages for each generation. A reasonable range
4865 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4866 * aging cares about the upper bound of hot pages, while the eviction
4867 * cares about the lower bound of cold pages.
4868 */
4869 if (young * MIN_NR_GENS > total)
4870 return true;
4871 if (old * (MIN_NR_GENS + 2) < total)
4872 return true;
4873
4874 return false;
4875}
4876
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004877/*
4878 * For future optimizations:
4879 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4880 * reclaim.
4881 */
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004882static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004883{
Yu Zhao37397872022-09-18 02:00:03 -06004884 unsigned long nr_to_scan;
4885 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4886 DEFINE_MAX_SEQ(lruvec);
Yu Zhao37397872022-09-18 02:00:03 -06004887
Yu Zhaof8b57162022-12-21 21:19:05 -07004888 if (mem_cgroup_below_min(memcg))
Yu Zhao37397872022-09-18 02:00:03 -06004889 return 0;
4890
Yu Zhaoa5998f92022-12-21 21:19:02 -07004891 if (!should_run_aging(lruvec, max_seq, sc, can_swap, &nr_to_scan))
Yu Zhao37397872022-09-18 02:00:03 -06004892 return nr_to_scan;
4893
4894 /* skip the aging path at the default priority */
4895 if (sc->priority == DEF_PRIORITY)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004896 return nr_to_scan;
Yu Zhaoa5998f92022-12-21 21:19:02 -07004897
Yu Zhaoa5998f92022-12-21 21:19:02 -07004898 /* skip this lruvec as it's low on cold pages */
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004899 return try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false) ? -1 : 0;
Yu Zhao37397872022-09-18 02:00:03 -06004900}
4901
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004902static unsigned long get_nr_to_reclaim(struct scan_control *sc)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004903{
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004904 /* don't abort memcg reclaim to ensure fairness */
4905 if (!global_reclaim(sc))
4906 return -1;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004907
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004908 return max(sc->nr_to_reclaim, compact_gap(sc->order));
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004909}
4910
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004911static bool try_to_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Yu Zhao37397872022-09-18 02:00:03 -06004912{
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004913 long nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004914 unsigned long scanned = 0;
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004915 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
Yu Zhaof8b57162022-12-21 21:19:05 -07004916 int swappiness = get_swappiness(lruvec, sc);
4917
4918 /* clean file pages are more likely to exist */
4919 if (swappiness && !(sc->gfp_mask & __GFP_IO))
4920 swappiness = 1;
Yu Zhao37397872022-09-18 02:00:03 -06004921
Yu Zhao37397872022-09-18 02:00:03 -06004922 while (true) {
4923 int delta;
Yu Zhao37397872022-09-18 02:00:03 -06004924
Yu Zhaoa5998f92022-12-21 21:19:02 -07004925 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004926 if (nr_to_scan <= 0)
Yu Zhaoa5998f92022-12-21 21:19:02 -07004927 break;
Yu Zhao37397872022-09-18 02:00:03 -06004928
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004929 delta = evict_pages(lruvec, sc, swappiness);
Yu Zhao37397872022-09-18 02:00:03 -06004930 if (!delta)
Yu Zhaoa5998f92022-12-21 21:19:02 -07004931 break;
Yu Zhao37397872022-09-18 02:00:03 -06004932
4933 scanned += delta;
4934 if (scanned >= nr_to_scan)
4935 break;
4936
Yu Zhao4fc3ef42022-12-21 21:19:01 -07004937 if (sc->nr_reclaimed >= nr_to_reclaim)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004938 break;
4939
Yu Zhao37397872022-09-18 02:00:03 -06004940 cond_resched();
4941 }
4942
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004943 /* whether try_to_inc_max_seq() was successful */
4944 return nr_to_scan < 0;
4945}
4946
4947static int shrink_one(struct lruvec *lruvec, struct scan_control *sc)
4948{
4949 bool success;
4950 unsigned long scanned = sc->nr_scanned;
4951 unsigned long reclaimed = sc->nr_reclaimed;
4952 int seg = lru_gen_memcg_seg(lruvec);
4953 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4954 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4955
4956 /* see the comment on MEMCG_NR_GENS */
4957 if (!lruvec_is_sizable(lruvec, sc))
4958 return seg != MEMCG_LRU_TAIL ? MEMCG_LRU_TAIL : MEMCG_LRU_YOUNG;
4959
4960 mem_cgroup_calculate_protection(NULL, memcg);
4961
4962 if (mem_cgroup_below_min(memcg))
4963 return MEMCG_LRU_YOUNG;
4964
4965 if (mem_cgroup_below_low(memcg)) {
4966 /* see the comment on MEMCG_NR_GENS */
4967 if (seg != MEMCG_LRU_TAIL)
4968 return MEMCG_LRU_TAIL;
4969
4970 memcg_memory_event(memcg, MEMCG_LOW);
4971 }
4972
4973 success = try_to_shrink_lruvec(lruvec, sc);
4974
4975 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg, sc->priority);
4976
4977 vmpressure(sc->gfp_mask, memcg, false, sc->nr_scanned - scanned,
4978 sc->nr_reclaimed - reclaimed);
4979
4980 sc->nr_reclaimed += current->reclaim_state->reclaimed_slab;
4981 current->reclaim_state->reclaimed_slab = 0;
4982
4983 return success ? MEMCG_LRU_YOUNG : 0;
4984}
4985
4986#ifdef CONFIG_MEMCG
4987
4988static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
4989{
Yu Zhaof7909cb2023-02-13 00:53:22 -07004990 int op;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004991 int gen;
4992 int bin;
4993 int first_bin;
4994 struct lruvec *lruvec;
4995 struct lru_gen_page *lrugen;
Yu Zhaof7909cb2023-02-13 00:53:22 -07004996 struct mem_cgroup *memcg;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004997 const struct hlist_nulls_node *pos;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07004998 unsigned long nr_to_reclaim = get_nr_to_reclaim(sc);
4999
5000 bin = first_bin = prandom_u32_max(MEMCG_NR_BINS);
5001restart:
Yu Zhaof7909cb2023-02-13 00:53:22 -07005002 op = 0;
5003 memcg = NULL;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005004 gen = get_memcg_gen(READ_ONCE(pgdat->memcg_lru.seq));
5005
5006 rcu_read_lock();
5007
5008 hlist_nulls_for_each_entry_rcu(lrugen, pos, &pgdat->memcg_lru.fifo[gen][bin], list) {
5009 if (op)
5010 lru_gen_rotate_memcg(lruvec, op);
5011
5012 mem_cgroup_put(memcg);
5013
5014 lruvec = container_of(lrugen, struct lruvec, lrugen);
5015 memcg = lruvec_memcg(lruvec);
5016
5017 if (!mem_cgroup_tryget(memcg)) {
5018 op = 0;
5019 memcg = NULL;
5020 continue;
5021 }
5022
5023 rcu_read_unlock();
5024
5025 op = shrink_one(lruvec, sc);
5026
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005027 rcu_read_lock();
Yu Zhaof7909cb2023-02-13 00:53:22 -07005028
5029 if (sc->nr_reclaimed >= nr_to_reclaim)
5030 break;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005031 }
5032
5033 rcu_read_unlock();
5034
Yu Zhaof7909cb2023-02-13 00:53:22 -07005035 if (op)
5036 lru_gen_rotate_memcg(lruvec, op);
5037
5038 mem_cgroup_put(memcg);
5039
5040 if (sc->nr_reclaimed >= nr_to_reclaim)
5041 return;
5042
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005043 /* restart if raced with lru_gen_rotate_memcg() */
5044 if (gen != get_nulls_value(pos))
5045 goto restart;
5046
5047 /* try the rest of the bins of the current generation */
5048 bin = get_memcg_bin(bin + 1);
5049 if (bin != first_bin)
5050 goto restart;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005051}
5052
5053static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5054{
5055 struct blk_plug plug;
5056
5057 VM_WARN_ON_ONCE(global_reclaim(sc));
Yu Zhaof8b57162022-12-21 21:19:05 -07005058 VM_WARN_ON_ONCE(!sc->may_writepage || !sc->may_unmap);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005059
5060 lru_add_drain();
5061
5062 blk_start_plug(&plug);
5063
Yu Zhaof8b57162022-12-21 21:19:05 -07005064 set_mm_walk(NULL, false);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005065
5066 if (try_to_shrink_lruvec(lruvec, sc))
5067 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_YOUNG);
5068
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005069 clear_mm_walk();
5070
Yu Zhao37397872022-09-18 02:00:03 -06005071 blk_finish_plug(&plug);
5072}
5073
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005074#else /* !CONFIG_MEMCG */
5075
5076static void shrink_many(struct pglist_data *pgdat, struct scan_control *sc)
5077{
5078 BUILD_BUG();
5079}
5080
5081static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5082{
5083 BUILD_BUG();
5084}
5085
5086#endif
5087
5088static void set_initial_priority(struct pglist_data *pgdat, struct scan_control *sc)
5089{
5090 int priority;
5091 unsigned long reclaimable;
5092 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5093
5094 if (sc->priority != DEF_PRIORITY || sc->nr_to_reclaim < MIN_LRU_BATCH)
5095 return;
5096 /*
5097 * Determine the initial priority based on ((total / MEMCG_NR_GENS) >>
5098 * priority) * reclaimed_to_scanned_ratio = nr_to_reclaim, where the
5099 * estimated reclaimed_to_scanned_ratio = inactive / total.
5100 */
5101 reclaimable = node_page_state(pgdat, NR_INACTIVE_FILE);
5102 if (get_swappiness(lruvec, sc))
5103 reclaimable += node_page_state(pgdat, NR_INACTIVE_ANON);
5104
5105 reclaimable /= MEMCG_NR_GENS;
5106
5107 /* round down reclaimable and round up sc->nr_to_reclaim */
5108 priority = fls_long(reclaimable) - 1 - fls_long(sc->nr_to_reclaim - 1);
5109
5110 sc->priority = clamp(priority, 0, DEF_PRIORITY);
5111}
5112
5113static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5114{
5115 struct blk_plug plug;
5116 unsigned long reclaimed = sc->nr_reclaimed;
5117
5118 VM_WARN_ON_ONCE(!global_reclaim(sc));
5119
Yu Zhaof8b57162022-12-21 21:19:05 -07005120 /*
5121 * Unmapped clean pages are already prioritized. Scanning for more of
5122 * them is likely futile and can cause high reclaim latency when there
5123 * is a large number of memcgs.
5124 */
5125 if (!sc->may_writepage || !sc->may_unmap)
5126 goto done;
5127
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005128 lru_add_drain();
5129
5130 blk_start_plug(&plug);
5131
Yu Zhaof8b57162022-12-21 21:19:05 -07005132 set_mm_walk(pgdat, false);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005133
5134 set_initial_priority(pgdat, sc);
5135
5136 if (current_is_kswapd())
5137 sc->nr_reclaimed = 0;
5138
5139 if (mem_cgroup_disabled())
5140 shrink_one(&pgdat->__lruvec, sc);
5141 else
5142 shrink_many(pgdat, sc);
5143
5144 if (current_is_kswapd())
5145 sc->nr_reclaimed += reclaimed;
5146
5147 clear_mm_walk();
5148
5149 blk_finish_plug(&plug);
Yu Zhaof8b57162022-12-21 21:19:05 -07005150done:
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005151 /* kswapd should never fail */
5152 pgdat->kswapd_failures = 0;
5153}
5154
5155#ifdef CONFIG_MEMCG
5156void lru_gen_rotate_memcg(struct lruvec *lruvec, int op)
5157{
5158 int seg;
5159 int old, new;
5160 int bin = prandom_u32_max(MEMCG_NR_BINS);
5161 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
5162
5163 spin_lock(&pgdat->memcg_lru.lock);
5164
5165 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
5166
5167 seg = 0;
5168 new = old = lruvec->lrugen.gen;
5169
5170 /* see the comment on MEMCG_NR_GENS */
5171 if (op == MEMCG_LRU_HEAD)
5172 seg = MEMCG_LRU_HEAD;
5173 else if (op == MEMCG_LRU_TAIL)
5174 seg = MEMCG_LRU_TAIL;
5175 else if (op == MEMCG_LRU_OLD)
5176 new = get_memcg_gen(pgdat->memcg_lru.seq);
5177 else if (op == MEMCG_LRU_YOUNG)
5178 new = get_memcg_gen(pgdat->memcg_lru.seq + 1);
5179 else
5180 VM_WARN_ON_ONCE(true);
5181
5182 hlist_nulls_del_rcu(&lruvec->lrugen.list);
5183
5184 if (op == MEMCG_LRU_HEAD || op == MEMCG_LRU_OLD)
5185 hlist_nulls_add_head_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
5186 else
5187 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[new][bin]);
5188
5189 pgdat->memcg_lru.nr_memcgs[old]--;
5190 pgdat->memcg_lru.nr_memcgs[new]++;
5191
5192 lruvec->lrugen.gen = new;
5193 WRITE_ONCE(lruvec->lrugen.seg, seg);
5194
5195 if (!pgdat->memcg_lru.nr_memcgs[old] && old == get_memcg_gen(pgdat->memcg_lru.seq))
5196 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
5197
5198 spin_unlock(&pgdat->memcg_lru.lock);
5199}
5200#endif
5201
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005202/******************************************************************************
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005203 * state change
5204 ******************************************************************************/
5205
5206static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5207{
Yu Zhao3c6c3592022-12-21 21:18:59 -07005208 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005209
5210 if (lrugen->enabled) {
5211 enum lru_list lru;
5212
5213 for_each_evictable_lru(lru) {
5214 if (!list_empty(&lruvec->lists[lru]))
5215 return false;
5216 }
5217 } else {
5218 int gen, type, zone;
5219
5220 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005221 if (!list_empty(&lrugen->pages[gen][type][zone]))
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005222 return false;
5223 }
5224 }
5225
5226 return true;
5227}
5228
5229static bool fill_evictable(struct lruvec *lruvec)
5230{
5231 enum lru_list lru;
5232 int remaining = MAX_LRU_BATCH;
5233
5234 for_each_evictable_lru(lru) {
5235 int type = is_file_lru(lru);
5236 bool active = is_active_lru(lru);
5237 struct list_head *head = &lruvec->lists[lru];
5238
5239 while (!list_empty(head)) {
5240 bool success;
5241 struct page *page = lru_to_page(head);
5242
5243 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5244 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
5245 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5246 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
5247
5248 del_page_from_lru_list(page, lruvec);
5249 success = lru_gen_add_page(lruvec, page, false);
5250 VM_WARN_ON_ONCE(!success);
5251
5252 if (!--remaining)
5253 return false;
5254 }
5255 }
5256
5257 return true;
5258}
5259
5260static bool drain_evictable(struct lruvec *lruvec)
5261{
5262 int gen, type, zone;
5263 int remaining = MAX_LRU_BATCH;
5264
5265 for_each_gen_type_zone(gen, type, zone) {
Yu Zhaodf91dc92022-12-21 21:19:00 -07005266 struct list_head *head = &lruvec->lrugen.pages[gen][type][zone];
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005267
5268 while (!list_empty(head)) {
5269 bool success;
5270 struct page *page = lru_to_page(head);
5271
5272 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5273 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5274 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5275 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5276
5277 success = lru_gen_del_page(lruvec, page, false);
5278 VM_WARN_ON_ONCE(!success);
5279 add_page_to_lru_list(page, lruvec);
5280
5281 if (!--remaining)
5282 return false;
5283 }
5284 }
5285
5286 return true;
5287}
5288
5289static void lru_gen_change_state(bool enabled)
5290{
5291 static DEFINE_MUTEX(state_mutex);
5292
5293 struct mem_cgroup *memcg;
5294
5295 cgroup_lock();
5296 cpus_read_lock();
5297 get_online_mems();
5298 mutex_lock(&state_mutex);
5299
5300 if (enabled == lru_gen_enabled())
5301 goto unlock;
5302
5303 if (enabled)
5304 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5305 else
5306 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5307
5308 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5309 do {
5310 int nid;
5311
5312 for_each_node(nid) {
5313 struct lruvec *lruvec = get_lruvec(memcg, nid);
5314
5315 if (!lruvec)
5316 continue;
5317
5318 spin_lock_irq(&lruvec->lru_lock);
5319
5320 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5321 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5322
5323 lruvec->lrugen.enabled = enabled;
5324
5325 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5326 spin_unlock_irq(&lruvec->lru_lock);
5327 cond_resched();
5328 spin_lock_irq(&lruvec->lru_lock);
5329 }
5330
5331 spin_unlock_irq(&lruvec->lru_lock);
5332 }
5333
5334 cond_resched();
5335 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5336unlock:
5337 mutex_unlock(&state_mutex);
5338 put_online_mems();
5339 cpus_read_unlock();
5340 cgroup_unlock();
5341}
5342
5343/******************************************************************************
5344 * sysfs interface
5345 ******************************************************************************/
5346
Yu Zhao430499c2022-09-18 02:00:08 -06005347static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5348{
5349 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5350}
5351
Yu Zhao642d9862022-09-18 02:00:10 -06005352/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao430499c2022-09-18 02:00:08 -06005353static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5354 const char *buf, size_t len)
5355{
5356 unsigned int msecs;
5357
5358 if (kstrtouint(buf, 0, &msecs))
5359 return -EINVAL;
5360
5361 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5362
5363 return len;
5364}
5365
5366static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5367 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5368);
5369
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005370static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5371{
5372 unsigned int caps = 0;
5373
5374 if (get_cap(LRU_GEN_CORE))
5375 caps |= BIT(LRU_GEN_CORE);
5376
5377 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5378 caps |= BIT(LRU_GEN_MM_WALK);
5379
Juergen Gross23811792022-11-23 07:45:10 +01005380 if (arch_has_hw_nonleaf_pmd_young() && get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005381 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5382
5383 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5384}
5385
Yu Zhao642d9862022-09-18 02:00:10 -06005386/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005387static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5388 const char *buf, size_t len)
5389{
5390 int i;
5391 unsigned int caps;
5392
5393 if (tolower(*buf) == 'n')
5394 caps = 0;
5395 else if (tolower(*buf) == 'y')
5396 caps = -1;
5397 else if (kstrtouint(buf, 0, &caps))
5398 return -EINVAL;
5399
5400 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5401 bool enabled = caps & BIT(i);
5402
5403 if (i == LRU_GEN_CORE)
5404 lru_gen_change_state(enabled);
5405 else if (enabled)
5406 static_branch_enable(&lru_gen_caps[i]);
5407 else
5408 static_branch_disable(&lru_gen_caps[i]);
5409 }
5410
5411 return len;
5412}
5413
5414static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5415 enabled, 0644, show_enabled, store_enabled
5416);
5417
5418static struct attribute *lru_gen_attrs[] = {
Yu Zhao430499c2022-09-18 02:00:08 -06005419 &lru_gen_min_ttl_attr.attr,
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005420 &lru_gen_enabled_attr.attr,
5421 NULL
5422};
5423
5424static struct attribute_group lru_gen_attr_group = {
5425 .name = "lru_gen",
5426 .attrs = lru_gen_attrs,
5427};
5428
5429/******************************************************************************
Yu Zhao4983c522022-09-18 02:00:09 -06005430 * debugfs interface
5431 ******************************************************************************/
5432
5433static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5434{
5435 struct mem_cgroup *memcg;
5436 loff_t nr_to_skip = *pos;
5437
5438 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5439 if (!m->private)
5440 return ERR_PTR(-ENOMEM);
5441
5442 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5443 do {
5444 int nid;
5445
5446 for_each_node_state(nid, N_MEMORY) {
5447 if (!nr_to_skip--)
5448 return get_lruvec(memcg, nid);
5449 }
5450 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5451
5452 return NULL;
5453}
5454
5455static void lru_gen_seq_stop(struct seq_file *m, void *v)
5456{
5457 if (!IS_ERR_OR_NULL(v))
5458 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5459
5460 kvfree(m->private);
5461 m->private = NULL;
5462}
5463
5464static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5465{
5466 int nid = lruvec_pgdat(v)->node_id;
5467 struct mem_cgroup *memcg = lruvec_memcg(v);
5468
5469 ++*pos;
5470
5471 nid = next_memory_node(nid);
5472 if (nid == MAX_NUMNODES) {
5473 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5474 if (!memcg)
5475 return NULL;
5476
5477 nid = first_memory_node;
5478 }
5479
5480 return get_lruvec(memcg, nid);
5481}
5482
5483static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5484 unsigned long max_seq, unsigned long *min_seq,
5485 unsigned long seq)
5486{
5487 int i;
5488 int type, tier;
5489 int hist = lru_hist_from_seq(seq);
Yu Zhao3c6c3592022-12-21 21:18:59 -07005490 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005491
5492 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5493 seq_printf(m, " %10d", tier);
5494 for (type = 0; type < ANON_AND_FILE; type++) {
5495 const char *s = " ";
5496 unsigned long n[3] = {};
5497
5498 if (seq == max_seq) {
5499 s = "RT ";
5500 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5501 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5502 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5503 s = "rep";
5504 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5505 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5506 if (tier)
5507 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5508 }
5509
5510 for (i = 0; i < 3; i++)
5511 seq_printf(m, " %10lu%c", n[i], s[i]);
5512 }
5513 seq_putc(m, '\n');
5514 }
5515
5516 seq_puts(m, " ");
5517 for (i = 0; i < NR_MM_STATS; i++) {
5518 const char *s = " ";
5519 unsigned long n = 0;
5520
5521 if (seq == max_seq && NR_HIST_GENS == 1) {
5522 s = "LOYNFA";
5523 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5524 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5525 s = "loynfa";
5526 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5527 }
5528
5529 seq_printf(m, " %10lu%c", n, s[i]);
5530 }
5531 seq_putc(m, '\n');
5532}
5533
Yu Zhao642d9862022-09-18 02:00:10 -06005534/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005535static int lru_gen_seq_show(struct seq_file *m, void *v)
5536{
5537 unsigned long seq;
5538 bool full = !debugfs_real_fops(m->file)->write;
5539 struct lruvec *lruvec = v;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005540 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06005541 int nid = lruvec_pgdat(lruvec)->node_id;
5542 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5543 DEFINE_MAX_SEQ(lruvec);
5544 DEFINE_MIN_SEQ(lruvec);
5545
5546 if (nid == first_memory_node) {
5547 const char *path = memcg ? m->private : "";
5548
5549#ifdef CONFIG_MEMCG
5550 if (memcg)
5551 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5552#endif
5553 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5554 }
5555
5556 seq_printf(m, " node %5d\n", nid);
5557
5558 if (!full)
5559 seq = min_seq[LRU_GEN_ANON];
5560 else if (max_seq >= MAX_NR_GENS)
5561 seq = max_seq - MAX_NR_GENS + 1;
5562 else
5563 seq = 0;
5564
5565 for (; seq <= max_seq; seq++) {
5566 int type, zone;
5567 int gen = lru_gen_from_seq(seq);
5568 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5569
5570 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5571
5572 for (type = 0; type < ANON_AND_FILE; type++) {
5573 unsigned long size = 0;
5574 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5575
5576 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5577 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5578
5579 seq_printf(m, " %10lu%c", size, mark);
5580 }
5581
5582 seq_putc(m, '\n');
5583
5584 if (full)
5585 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5586 }
5587
5588 return 0;
5589}
5590
5591static const struct seq_operations lru_gen_seq_ops = {
5592 .start = lru_gen_seq_start,
5593 .stop = lru_gen_seq_stop,
5594 .next = lru_gen_seq_next,
5595 .show = lru_gen_seq_show,
5596};
5597
5598static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5599 bool can_swap, bool force_scan)
5600{
5601 DEFINE_MAX_SEQ(lruvec);
5602 DEFINE_MIN_SEQ(lruvec);
5603
5604 if (seq < max_seq)
5605 return 0;
5606
5607 if (seq > max_seq)
5608 return -EINVAL;
5609
5610 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5611 return -ERANGE;
5612
5613 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5614
5615 return 0;
5616}
5617
5618static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5619 int swappiness, unsigned long nr_to_reclaim)
5620{
5621 DEFINE_MAX_SEQ(lruvec);
5622
5623 if (seq + MIN_NR_GENS > max_seq)
5624 return -EINVAL;
5625
5626 sc->nr_reclaimed = 0;
5627
5628 while (!signal_pending(current)) {
5629 DEFINE_MIN_SEQ(lruvec);
5630
5631 if (seq < min_seq[!swappiness])
5632 return 0;
5633
5634 if (sc->nr_reclaimed >= nr_to_reclaim)
5635 return 0;
5636
Yu Zhao4fc3ef42022-12-21 21:19:01 -07005637 if (!evict_pages(lruvec, sc, swappiness))
Yu Zhao4983c522022-09-18 02:00:09 -06005638 return 0;
5639
5640 cond_resched();
5641 }
5642
5643 return -EINTR;
5644}
5645
5646static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5647 struct scan_control *sc, int swappiness, unsigned long opt)
5648{
5649 struct lruvec *lruvec;
5650 int err = -EINVAL;
5651 struct mem_cgroup *memcg = NULL;
5652
5653 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5654 return -EINVAL;
5655
5656 if (!mem_cgroup_disabled()) {
5657 rcu_read_lock();
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005658
Yu Zhao4983c522022-09-18 02:00:09 -06005659 memcg = mem_cgroup_from_id(memcg_id);
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005660 if (!mem_cgroup_tryget(memcg))
Yu Zhao4983c522022-09-18 02:00:09 -06005661 memcg = NULL;
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005662
Yu Zhao4983c522022-09-18 02:00:09 -06005663 rcu_read_unlock();
5664
5665 if (!memcg)
5666 return -EINVAL;
5667 }
5668
5669 if (memcg_id != mem_cgroup_id(memcg))
5670 goto done;
5671
5672 lruvec = get_lruvec(memcg, nid);
5673
5674 if (swappiness < 0)
5675 swappiness = get_swappiness(lruvec, sc);
5676 else if (swappiness > 200)
5677 goto done;
5678
5679 switch (cmd) {
5680 case '+':
5681 err = run_aging(lruvec, seq, sc, swappiness, opt);
5682 break;
5683 case '-':
5684 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5685 break;
5686 }
5687done:
5688 mem_cgroup_put(memcg);
5689
5690 return err;
5691}
5692
Yu Zhao642d9862022-09-18 02:00:10 -06005693/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005694static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5695 size_t len, loff_t *pos)
5696{
5697 void *buf;
5698 char *cur, *next;
5699 unsigned int flags;
5700 struct blk_plug plug;
5701 int err = -EINVAL;
5702 struct scan_control sc = {
5703 .may_writepage = true,
5704 .may_unmap = true,
5705 .may_swap = true,
5706 .reclaim_idx = MAX_NR_ZONES - 1,
5707 .gfp_mask = GFP_KERNEL,
5708 };
5709
5710 buf = kvmalloc(len + 1, GFP_KERNEL);
5711 if (!buf)
5712 return -ENOMEM;
5713
5714 if (copy_from_user(buf, src, len)) {
5715 kvfree(buf);
5716 return -EFAULT;
5717 }
5718
5719 set_task_reclaim_state(current, &sc.reclaim_state);
5720 flags = memalloc_noreclaim_save();
5721 blk_start_plug(&plug);
Yu Zhaof8b57162022-12-21 21:19:05 -07005722 if (!set_mm_walk(NULL, true)) {
Yu Zhao4983c522022-09-18 02:00:09 -06005723 err = -ENOMEM;
5724 goto done;
5725 }
5726
5727 next = buf;
5728 next[len] = '\0';
5729
5730 while ((cur = strsep(&next, ",;\n"))) {
5731 int n;
5732 int end;
5733 char cmd;
5734 unsigned int memcg_id;
5735 unsigned int nid;
5736 unsigned long seq;
5737 unsigned int swappiness = -1;
5738 unsigned long opt = -1;
5739
5740 cur = skip_spaces(cur);
5741 if (!*cur)
5742 continue;
5743
5744 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5745 &seq, &end, &swappiness, &end, &opt, &end);
5746 if (n < 4 || cur[end]) {
5747 err = -EINVAL;
5748 break;
5749 }
5750
5751 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5752 if (err)
5753 break;
5754 }
5755done:
5756 clear_mm_walk();
5757 blk_finish_plug(&plug);
5758 memalloc_noreclaim_restore(flags);
5759 set_task_reclaim_state(current, NULL);
5760
5761 kvfree(buf);
5762
5763 return err ? : len;
5764}
5765
5766static int lru_gen_seq_open(struct inode *inode, struct file *file)
5767{
5768 return seq_open(file, &lru_gen_seq_ops);
5769}
5770
5771static const struct file_operations lru_gen_rw_fops = {
5772 .open = lru_gen_seq_open,
5773 .read = seq_read,
5774 .write = lru_gen_seq_write,
5775 .llseek = seq_lseek,
5776 .release = seq_release,
5777};
5778
5779static const struct file_operations lru_gen_ro_fops = {
5780 .open = lru_gen_seq_open,
5781 .read = seq_read,
5782 .llseek = seq_lseek,
5783 .release = seq_release,
5784};
5785
5786/******************************************************************************
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005787 * initialization
5788 ******************************************************************************/
5789
5790void lru_gen_init_lruvec(struct lruvec *lruvec)
5791{
Yu Zhao430499c2022-09-18 02:00:08 -06005792 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005793 int gen, type, zone;
Yu Zhao3c6c3592022-12-21 21:18:59 -07005794 struct lru_gen_page *lrugen = &lruvec->lrugen;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005795
5796 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005797 lrugen->enabled = lru_gen_enabled();
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005798
Yu Zhao430499c2022-09-18 02:00:08 -06005799 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5800 lrugen->timestamps[i] = jiffies;
5801
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005802 for_each_gen_type_zone(gen, type, zone)
Yu Zhaodf91dc92022-12-21 21:19:00 -07005803 INIT_LIST_HEAD(&lrugen->pages[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005804
5805 lruvec->mm_state.seq = MIN_NR_GENS;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005806}
5807
5808#ifdef CONFIG_MEMCG
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005809
5810void lru_gen_init_pgdat(struct pglist_data *pgdat)
5811{
5812 int i, j;
5813
5814 spin_lock_init(&pgdat->memcg_lru.lock);
5815
5816 for (i = 0; i < MEMCG_NR_GENS; i++) {
5817 for (j = 0; j < MEMCG_NR_BINS; j++)
5818 INIT_HLIST_NULLS_HEAD(&pgdat->memcg_lru.fifo[i][j], i);
5819 }
5820}
5821
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005822void lru_gen_init_memcg(struct mem_cgroup *memcg)
5823{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005824 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5825 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005826}
5827
5828void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5829{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005830 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005831 int nid;
5832
5833 for_each_node(nid) {
5834 struct lruvec *lruvec = get_lruvec(memcg, nid);
5835
5836 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5837 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005838
5839 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5840 bitmap_free(lruvec->mm_state.filters[i]);
5841 lruvec->mm_state.filters[i] = NULL;
5842 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005843 }
5844}
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005845
5846void lru_gen_online_memcg(struct mem_cgroup *memcg)
5847{
5848 int gen;
5849 int nid;
5850 int bin = prandom_u32_max(MEMCG_NR_BINS);
5851
5852 for_each_node(nid) {
5853 struct pglist_data *pgdat = NODE_DATA(nid);
5854 struct lruvec *lruvec = get_lruvec(memcg, nid);
5855
5856 spin_lock(&pgdat->memcg_lru.lock);
5857
5858 VM_WARN_ON_ONCE(!hlist_nulls_unhashed(&lruvec->lrugen.list));
5859
5860 gen = get_memcg_gen(pgdat->memcg_lru.seq);
5861
5862 hlist_nulls_add_tail_rcu(&lruvec->lrugen.list, &pgdat->memcg_lru.fifo[gen][bin]);
5863 pgdat->memcg_lru.nr_memcgs[gen]++;
5864
5865 lruvec->lrugen.gen = gen;
5866
5867 spin_unlock(&pgdat->memcg_lru.lock);
5868 }
5869}
5870
5871void lru_gen_offline_memcg(struct mem_cgroup *memcg)
5872{
5873 int nid;
5874
5875 for_each_node(nid) {
5876 struct lruvec *lruvec = get_lruvec(memcg, nid);
5877
5878 lru_gen_rotate_memcg(lruvec, MEMCG_LRU_OLD);
5879 }
5880}
5881
5882void lru_gen_release_memcg(struct mem_cgroup *memcg)
5883{
5884 int gen;
5885 int nid;
5886
5887 for_each_node(nid) {
5888 struct pglist_data *pgdat = NODE_DATA(nid);
5889 struct lruvec *lruvec = get_lruvec(memcg, nid);
5890
5891 spin_lock(&pgdat->memcg_lru.lock);
5892
5893 VM_WARN_ON_ONCE(hlist_nulls_unhashed(&lruvec->lrugen.list));
5894
5895 gen = lruvec->lrugen.gen;
5896
5897 hlist_nulls_del_rcu(&lruvec->lrugen.list);
5898 pgdat->memcg_lru.nr_memcgs[gen]--;
5899
5900 if (!pgdat->memcg_lru.nr_memcgs[gen] && gen == get_memcg_gen(pgdat->memcg_lru.seq))
5901 WRITE_ONCE(pgdat->memcg_lru.seq, pgdat->memcg_lru.seq + 1);
5902
5903 spin_unlock(&pgdat->memcg_lru.lock);
5904 }
5905}
5906
5907#endif /* CONFIG_MEMCG */
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005908
5909static int __init init_lru_gen(void)
5910{
5911 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5912 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5913
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005914 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5915 pr_err("lru_gen: failed to create sysfs group\n");
5916
Yu Zhao4983c522022-09-18 02:00:09 -06005917 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5918 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5919
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005920 return 0;
5921};
5922late_initcall(init_lru_gen);
5923
Yu Zhao37397872022-09-18 02:00:03 -06005924#else /* !CONFIG_LRU_GEN */
5925
5926static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5927{
5928}
5929
5930static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5931{
5932}
5933
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005934static void lru_gen_shrink_node(struct pglist_data *pgdat, struct scan_control *sc)
5935{
5936}
5937
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005938#endif /* CONFIG_LRU_GEN */
5939
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005940static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005941{
5942 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005943 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005944 unsigned long nr_to_scan;
5945 enum lru_list lru;
5946 unsigned long nr_reclaimed = 0;
5947 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005948 bool proportional_reclaim;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005949 struct blk_plug plug;
Minchan Kima8962f62022-11-02 09:04:41 -07005950 bool do_plug = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005951
Yu Zhaoa3eb6512022-12-21 21:19:04 -07005952 if (lru_gen_enabled() && !global_reclaim(sc)) {
Yu Zhao37397872022-09-18 02:00:03 -06005953 lru_gen_shrink_lruvec(lruvec, sc);
5954 return;
5955 }
5956
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005957 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005958
Mel Gormane82e0562013-07-03 15:01:44 -07005959 /* Record the original scan target for proportional adjustments later */
5960 memcpy(targets, nr, sizeof(nr));
5961
Mel Gorman1a501902014-06-04 16:10:49 -07005962 /*
5963 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5964 * event that can occur when there is little memory pressure e.g.
5965 * multiple streaming readers/writers. Hence, we do not abort scanning
5966 * when the requested number of pages are reclaimed when scanning at
5967 * DEF_PRIORITY on the assumption that the fact we are direct
5968 * reclaiming implies that kswapd is not keeping up and it is best to
5969 * do a batch of work at once. For memcg reclaim one check is made to
5970 * abort proportional reclaim if either the file or anon lru has already
5971 * dropped to zero at the first pass.
5972 */
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005973 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5974 sc->priority == DEF_PRIORITY);
Mel Gorman1a501902014-06-04 16:10:49 -07005975
Minchan Kima8962f62022-11-02 09:04:41 -07005976 trace_android_vh_shrink_lruvec_blk_plug(&do_plug);
5977 if (do_plug)
5978 blk_start_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005979 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5980 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005981 unsigned long nr_anon, nr_file, percentage;
5982 unsigned long nr_scanned;
5983
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005984 for_each_evictable_lru(lru) {
5985 if (nr[lru]) {
5986 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5987 nr[lru] -= nr_to_scan;
5988
5989 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005990 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005991 }
5992 }
Mel Gormane82e0562013-07-03 15:01:44 -07005993
Michal Hockobd041732016-12-02 17:26:48 -08005994 cond_resched();
5995
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005996 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
Mel Gormane82e0562013-07-03 15:01:44 -07005997 continue;
5998
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005999 /*
Mel Gormane82e0562013-07-03 15:01:44 -07006000 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07006001 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07006002 * proportionally what was requested by get_scan_count(). We
6003 * stop reclaiming one LRU and reduce the amount scanning
6004 * proportional to the original scan target.
6005 */
6006 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
6007 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
6008
Mel Gorman1a501902014-06-04 16:10:49 -07006009 /*
6010 * It's just vindictive to attack the larger once the smaller
6011 * has gone to zero. And given the way we stop scanning the
6012 * smaller below, this makes sure that we only make one nudge
6013 * towards proportionality once we've got nr_to_reclaim.
6014 */
6015 if (!nr_file || !nr_anon)
6016 break;
6017
Mel Gormane82e0562013-07-03 15:01:44 -07006018 if (nr_file > nr_anon) {
6019 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
6020 targets[LRU_ACTIVE_ANON] + 1;
6021 lru = LRU_BASE;
6022 percentage = nr_anon * 100 / scan_target;
6023 } else {
6024 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
6025 targets[LRU_ACTIVE_FILE] + 1;
6026 lru = LRU_FILE;
6027 percentage = nr_file * 100 / scan_target;
6028 }
6029
6030 /* Stop scanning the smaller of the LRU */
6031 nr[lru] = 0;
6032 nr[lru + LRU_ACTIVE] = 0;
6033
6034 /*
6035 * Recalculate the other LRU scan count based on its original
6036 * scan target and the percentage scanning already complete
6037 */
6038 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
6039 nr_scanned = targets[lru] - nr[lru];
6040 nr[lru] = targets[lru] * (100 - percentage) / 100;
6041 nr[lru] -= min(nr[lru], nr_scanned);
6042
6043 lru += LRU_ACTIVE;
6044 nr_scanned = targets[lru] - nr[lru];
6045 nr[lru] = targets[lru] * (100 - percentage) / 100;
6046 nr[lru] -= min(nr[lru], nr_scanned);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006047 }
Minchan Kima8962f62022-11-02 09:04:41 -07006048 if (do_plug)
6049 blk_finish_plug(&plug);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006050 sc->nr_reclaimed += nr_reclaimed;
6051
6052 /*
6053 * Even if we did not try to evict anon pages at all, we want to
6054 * rebalance the anon lru active/inactive ratio.
6055 */
Dave Hansen2f368a92021-09-02 14:59:23 -07006056 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
6057 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006058 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6059 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08006060}
6061
Mel Gorman23b9da52012-05-29 15:06:20 -07006062/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006063static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07006064{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08006065 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07006066 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006067 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07006068 return true;
6069
6070 return false;
6071}
6072
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006073/*
Mel Gorman23b9da52012-05-29 15:06:20 -07006074 * Reclaim/compaction is used for high-order allocation requests. It reclaims
6075 * order-0 pages before compacting the zone. should_continue_reclaim() returns
6076 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07006077 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07006078 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08006079 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006080static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08006081 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08006082 struct scan_control *sc)
6083{
6084 unsigned long pages_for_compaction;
6085 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07006086 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006087
6088 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006089 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08006090 return false;
6091
Vlastimil Babka5ee04712019-09-23 15:37:29 -07006092 /*
6093 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
6094 * number of pages that were scanned. This will return to the caller
6095 * with the risk reclaim/compaction and the resulting allocation attempt
6096 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
6097 * allocations through requiring that the full LRU list has been scanned
6098 * first, by assuming that zero delta of sc->nr_scanned means full LRU
6099 * scan, but that approximation was wrong, and there were corner cases
6100 * where always a non-zero amount of pages were scanned.
6101 */
6102 if (!nr_reclaimed)
6103 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006104
Mel Gorman3e7d3442011-01-13 15:45:56 -08006105 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006106 for (z = 0; z <= sc->reclaim_idx; z++) {
6107 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07006108 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07006109 continue;
6110
6111 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07006112 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07006113 case COMPACT_CONTINUE:
6114 return false;
6115 default:
6116 /* check next zone */
6117 ;
6118 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08006119 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07006120
6121 /*
6122 * If we have not reclaimed enough pages for compaction and the
6123 * inactive lists are large enough, continue reclaiming
6124 */
6125 pages_for_compaction = compact_gap(sc->order);
6126 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07006127 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07006128 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
6129
Vlastimil Babka5ee04712019-09-23 15:37:29 -07006130 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08006131}
6132
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006133static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006134{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006135 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08006136 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006137
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006138 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08006139 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006140 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006141 unsigned long reclaimed;
6142 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08006143 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08006144
Xunlei Pange3336ca2020-09-04 16:35:27 -07006145 /*
6146 * This loop can become CPU-bound when target memcgs
6147 * aren't eligible for reclaim - either because they
6148 * don't have any reclaimable pages, or because their
6149 * memory is explicitly protected. Avoid soft lockups.
6150 */
6151 cond_resched();
6152
Liujie Xieb7ea1c42022-06-01 15:38:17 +08006153 trace_android_vh_shrink_node_memcgs(memcg, &skip);
6154 if (skip)
6155 continue;
6156
Chris Down45c7f7e2020-08-06 23:22:05 -07006157 mem_cgroup_calculate_protection(target_memcg, memcg);
6158
6159 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08006160 /*
6161 * Hard protection.
6162 * If there is no reclaimable memory, OOM.
6163 */
6164 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07006165 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08006166 /*
6167 * Soft protection.
6168 * Respect the protection only as long as
6169 * there is an unprotected supply
6170 * of reclaimable memory from other cgroups.
6171 */
6172 if (!sc->memcg_low_reclaim) {
6173 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07006174 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006175 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08006176 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08006177 }
6178
Johannes Weinerd2af3392019-11-30 17:55:43 -08006179 reclaimed = sc->nr_reclaimed;
6180 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006181
6182 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006183
Johannes Weinerd2af3392019-11-30 17:55:43 -08006184 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
6185 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07006186
Johannes Weinerd2af3392019-11-30 17:55:43 -08006187 /* Record the group's reclaim efficiency */
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006188 if (!sc->proactive)
6189 vmpressure(sc->gfp_mask, memcg, false,
6190 sc->nr_scanned - scanned,
6191 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006192
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006193 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
6194}
6195
Liu Song6c9e09072020-01-30 22:14:08 -08006196static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006197{
6198 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006199 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08006200 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006201 bool reclaimable = false;
6202
Yu Zhaoa3eb6512022-12-21 21:19:04 -07006203 if (lru_gen_enabled() && global_reclaim(sc)) {
6204 lru_gen_shrink_node(pgdat, sc);
6205 return;
6206 }
6207
Johannes Weiner1b051172019-11-30 17:55:52 -08006208 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
6209
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006210again:
6211 memset(&sc->nr, 0, sizeof(sc->nr));
6212
6213 nr_reclaimed = sc->nr_reclaimed;
6214 nr_scanned = sc->nr_scanned;
6215
Yu Zhao6d313442022-09-18 02:00:00 -06006216 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08006217
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08006218 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006219
Johannes Weinerd2af3392019-11-30 17:55:43 -08006220 if (reclaim_state) {
6221 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
6222 reclaim_state->reclaimed_slab = 0;
6223 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07006224
Johannes Weinerd2af3392019-11-30 17:55:43 -08006225 /* Record the subtree's reclaim efficiency */
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006226 if (!sc->proactive)
6227 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
6228 sc->nr_scanned - nr_scanned,
6229 sc->nr_reclaimed - nr_reclaimed);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006230
6231 if (sc->nr_reclaimed - nr_reclaimed)
6232 reclaimable = true;
6233
6234 if (current_is_kswapd()) {
6235 /*
6236 * If reclaim is isolating dirty pages under writeback,
6237 * it implies that the long-lived page allocation rate
6238 * is exceeding the page laundering rate. Either the
6239 * global limits are not being effective at throttling
6240 * processes due to the page distribution throughout
6241 * zones or there is heavy usage of a slow backing
6242 * device. The only option is to throttle from reclaim
6243 * context which is not ideal as there is no guarantee
6244 * the dirtying process is throttled in the same way
6245 * balance_dirty_pages() manages.
6246 *
6247 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
6248 * count the number of pages under pages flagged for
6249 * immediate reclaim and stall if any are encountered
6250 * in the nr_immediate check below.
6251 */
6252 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
6253 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07006254
Johannes Weinerd2af3392019-11-30 17:55:43 -08006255 /* Allow kswapd to start writing pages during reclaim.*/
6256 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
6257 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07006258
6259 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006260 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08006261 * reclaim and under writeback (nr_immediate), it
6262 * implies that pages are cycling through the LRU
6263 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07006264 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08006265 if (sc->nr.immediate)
6266 congestion_wait(BLK_RW_ASYNC, HZ/10);
6267 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07006268
Johannes Weinerd2af3392019-11-30 17:55:43 -08006269 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08006270 * Tag a node/memcg as congested if all the dirty pages
6271 * scanned were backed by a congested BDI and
6272 * wait_iff_congested will stall.
6273 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08006274 * Legacy memcg will stall in page writeback so avoid forcibly
6275 * stalling in wait_iff_congested().
6276 */
Johannes Weiner1b051172019-11-30 17:55:52 -08006277 if ((current_is_kswapd() ||
6278 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08006279 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08006280 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006281
6282 /*
6283 * Stall direct reclaim for IO completions if underlying BDIs
6284 * and node is congested. Allow kswapd to continue until it
6285 * starts encountering unqueued dirty pages or cycling through
6286 * the LRU too quickly.
6287 */
Johannes Weiner1b051172019-11-30 17:55:52 -08006288 if (!current_is_kswapd() && current_may_throttle() &&
6289 !sc->hibernation_mode &&
6290 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08006291 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
6292
6293 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
6294 sc))
6295 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07006296
Johannes Weinerc73322d2017-05-03 14:51:51 -07006297 /*
6298 * Kswapd gives up on balancing particular nodes after too
6299 * many failures to reclaim anything from them and goes to
6300 * sleep. On reclaim progress, reset the failure counter. A
6301 * successful direct reclaim run will revive a dormant kswapd.
6302 */
6303 if (reclaimable)
6304 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006305}
6306
Vlastimil Babka53853e22014-10-09 15:27:02 -07006307/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006308 * Returns true if compaction should go ahead for a costly-order request, or
6309 * the allocation would already succeed without compaction. Return false if we
6310 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07006311 */
Mel Gorman4f588332016-07-28 15:46:38 -07006312static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006313{
Mel Gorman31483b62016-07-28 15:45:46 -07006314 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006315 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006316
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006317 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6318 if (suitable == COMPACT_SUCCESS)
6319 /* Allocation should succeed already. Don't reclaim. */
6320 return true;
6321 if (suitable == COMPACT_SKIPPED)
6322 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006323 return false;
6324
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006325 /*
6326 * Compaction is already possible, but it takes time to run and there
6327 * are potentially other callers using the pages just freed. So proceed
6328 * with reclaim to make a buffer of free pages available to give
6329 * compaction a reasonable chance of completing and allocating the page.
6330 * Note that we won't actually reclaim the whole buffer in one attempt
6331 * as the target watermark in should_continue_reclaim() is lower. But if
6332 * we are already above the high+gap watermark, don't reclaim at all.
6333 */
6334 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6335
6336 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006337}
6338
Linus Torvalds1da177e2005-04-16 15:20:36 -07006339/*
6340 * This is the direct reclaim path, for page-allocating processes. We only
6341 * try to reclaim pages from zones which will satisfy the caller's allocation
6342 * request.
6343 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07006344 * If a zone is deemed to be full of pinned pages then just give it a light
6345 * scan then give up on it.
6346 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07006347static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006348{
Mel Gormandd1a2392008-04-28 02:12:17 -07006349 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07006350 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07006351 unsigned long nr_soft_reclaimed;
6352 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07006353 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07006354 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006355
Mel Gormancc715d92012-03-21 16:34:00 -07006356 /*
6357 * If the number of buffer_heads in the machine exceeds the maximum
6358 * allowed level, force direct reclaim to scan the highmem zone as
6359 * highmem pages could be pinning lowmem pages storing buffer_heads
6360 */
Weijie Yang619d0d762014-04-07 15:36:59 -07006361 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07006362 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07006363 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07006364 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07006365 }
Mel Gormancc715d92012-03-21 16:34:00 -07006366
Mel Gormand4debc62010-08-09 17:19:29 -07006367 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07006368 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07006369 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006370 * Take care memory controller reclaiming has small influence
6371 * to global LRU.
6372 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08006373 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04006374 if (!cpuset_zone_allowed(zone,
6375 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006376 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006377
Johannes Weiner0b064962014-08-06 16:06:12 -07006378 /*
6379 * If we already have plenty of memory free for
6380 * compaction in this zone, don't free any more.
6381 * Even though compaction is invoked for any
6382 * non-zero order, only frequent costly order
6383 * reclamation is disruptive enough to become a
6384 * noticeable problem, like transparent huge
6385 * page allocations.
6386 */
6387 if (IS_ENABLED(CONFIG_COMPACTION) &&
6388 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07006389 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07006390 sc->compaction_ready = true;
6391 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07006392 }
Johannes Weiner0b064962014-08-06 16:06:12 -07006393
Andrew Morton0608f432013-09-24 15:27:41 -07006394 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07006395 * Shrink each node in the zonelist once. If the
6396 * zonelist is ordered by zone (not the default) then a
6397 * node may be shrunk multiple times but in that case
6398 * the user prefers lower zones being preserved.
6399 */
6400 if (zone->zone_pgdat == last_pgdat)
6401 continue;
6402
6403 /*
Andrew Morton0608f432013-09-24 15:27:41 -07006404 * This steals pages from memory cgroups over softlimit
6405 * and returns the number of reclaimed pages and
6406 * scanned pages. This works for global memory pressure
6407 * and balancing, not for a memcg's limit.
6408 */
6409 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006410 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006411 sc->order, sc->gfp_mask,
6412 &nr_soft_scanned);
6413 sc->nr_reclaimed += nr_soft_reclaimed;
6414 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006415 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006416 }
Nick Piggin408d8542006-09-25 23:31:27 -07006417
Mel Gorman79dafcd2016-07-28 15:45:53 -07006418 /* See comment about same check for global reclaim above */
6419 if (zone->zone_pgdat == last_pgdat)
6420 continue;
6421 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006422 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006423 }
Mel Gormane0c23272011-10-31 17:09:33 -07006424
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006425 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006426 * Restore to original mask to avoid the impact on the caller if we
6427 * promoted it to __GFP_HIGHMEM.
6428 */
6429 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006430}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006431
Johannes Weinerb9107182019-11-30 17:55:59 -08006432static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006433{
Johannes Weinerb9107182019-11-30 17:55:59 -08006434 struct lruvec *target_lruvec;
6435 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006436
Yu Zhao37397872022-09-18 02:00:03 -06006437 if (lru_gen_enabled())
6438 return;
6439
Johannes Weinerb9107182019-11-30 17:55:59 -08006440 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006441 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6442 target_lruvec->refaults[0] = refaults;
6443 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6444 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006445}
6446
Linus Torvalds1da177e2005-04-16 15:20:36 -07006447/*
6448 * This is the main entry point to direct page reclaim.
6449 *
6450 * If a full scan of the inactive list fails to free enough memory then we
6451 * are "out of memory" and something needs to be killed.
6452 *
6453 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6454 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006455 * caller can't do much about. We kick the writeback threads and take explicit
6456 * naps in the hope that some of these pages can be written. But if the
6457 * allocating task holds filesystem locks which prevent writeout this might not
6458 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006459 *
6460 * returns: 0, if no pages reclaimed
6461 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006462 */
Mel Gormandac1d272008-04-28 02:12:12 -07006463static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006464 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006465{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006466 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006467 pg_data_t *last_pgdat;
6468 struct zoneref *z;
6469 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006470retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006471 delayacct_freepages_start();
6472
Johannes Weinerb5ead352019-11-30 17:55:40 -08006473 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006474 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006475
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006476 do {
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006477 if (!sc->proactive)
6478 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6479 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006480 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006481 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006482
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006483 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006484 break;
6485
6486 if (sc->compaction_ready)
6487 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006488
6489 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006490 * If we're getting trouble reclaiming, start doing
6491 * writepage even in laptop mode.
6492 */
6493 if (sc->priority < DEF_PRIORITY - 2)
6494 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006495 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006496
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006497 last_pgdat = NULL;
6498 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6499 sc->nodemask) {
6500 if (zone->zone_pgdat == last_pgdat)
6501 continue;
6502 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006503
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006504 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006505
6506 if (cgroup_reclaim(sc)) {
6507 struct lruvec *lruvec;
6508
6509 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6510 zone->zone_pgdat);
6511 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6512 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006513 }
6514
Keika Kobayashi873b4772008-07-25 01:48:52 -07006515 delayacct_freepages_end();
6516
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006517 if (sc->nr_reclaimed)
6518 return sc->nr_reclaimed;
6519
Mel Gorman0cee34f2012-01-12 17:19:49 -08006520 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006521 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006522 return 1;
6523
Johannes Weinerb91ac372019-11-30 17:56:02 -08006524 /*
6525 * We make inactive:active ratio decisions based on the node's
6526 * composition of memory, but a restrictive reclaim_idx or a
6527 * memory.low cgroup setting can exempt large amounts of
6528 * memory from reclaim. Neither of which are very common, so
6529 * instead of doing costly eligibility calculations of the
6530 * entire cgroup subtree up front, we assume the estimates are
6531 * good, and retry with forcible deactivation if that fails.
6532 */
6533 if (sc->skipped_deactivate) {
6534 sc->priority = initial_priority;
6535 sc->force_deactivate = 1;
6536 sc->skipped_deactivate = 0;
6537 goto retry;
6538 }
6539
Johannes Weiner241994ed2015-02-11 15:26:06 -08006540 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006541 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006542 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006543 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006544 sc->memcg_low_reclaim = 1;
6545 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006546 goto retry;
6547 }
6548
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006549 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006550}
6551
Johannes Weinerc73322d2017-05-03 14:51:51 -07006552static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006553{
6554 struct zone *zone;
6555 unsigned long pfmemalloc_reserve = 0;
6556 unsigned long free_pages = 0;
6557 int i;
6558 bool wmark_ok;
6559
Johannes Weinerc73322d2017-05-03 14:51:51 -07006560 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6561 return true;
6562
Mel Gorman55150612012-07-31 16:44:35 -07006563 for (i = 0; i <= ZONE_NORMAL; i++) {
6564 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006565 if (!managed_zone(zone))
6566 continue;
6567
6568 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006569 continue;
6570
Mel Gorman55150612012-07-31 16:44:35 -07006571 pfmemalloc_reserve += min_wmark_pages(zone);
6572 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6573 }
6574
Mel Gorman675becc2014-06-04 16:07:35 -07006575 /* If there are no reserves (unexpected config) then do not throttle */
6576 if (!pfmemalloc_reserve)
6577 return true;
6578
Mel Gorman55150612012-07-31 16:44:35 -07006579 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6580
6581 /* kswapd must be awake if processes are being throttled */
6582 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006583 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6584 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006585
Mel Gorman55150612012-07-31 16:44:35 -07006586 wake_up_interruptible(&pgdat->kswapd_wait);
6587 }
6588
6589 return wmark_ok;
6590}
6591
6592/*
6593 * Throttle direct reclaimers if backing storage is backed by the network
6594 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6595 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006596 * when the low watermark is reached.
6597 *
6598 * Returns true if a fatal signal was delivered during throttling. If this
6599 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006600 */
Mel Gorman50694c22012-11-26 16:29:48 -08006601static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006602 nodemask_t *nodemask)
6603{
Mel Gorman675becc2014-06-04 16:07:35 -07006604 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006605 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006606 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006607
6608 /*
6609 * Kernel threads should not be throttled as they may be indirectly
6610 * responsible for cleaning pages necessary for reclaim to make forward
6611 * progress. kjournald for example may enter direct reclaim while
6612 * committing a transaction where throttling it could forcing other
6613 * processes to block on log_wait_commit().
6614 */
6615 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006616 goto out;
6617
6618 /*
6619 * If a fatal signal is pending, this process should not throttle.
6620 * It should return quickly so it can exit and free its memory
6621 */
6622 if (fatal_signal_pending(current))
6623 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006624
Mel Gorman675becc2014-06-04 16:07:35 -07006625 /*
6626 * Check if the pfmemalloc reserves are ok by finding the first node
6627 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6628 * GFP_KERNEL will be required for allocating network buffers when
6629 * swapping over the network so ZONE_HIGHMEM is unusable.
6630 *
6631 * Throttling is based on the first usable node and throttled processes
6632 * wait on a queue until kswapd makes progress and wakes them. There
6633 * is an affinity then between processes waking up and where reclaim
6634 * progress has been made assuming the process wakes on the same node.
6635 * More importantly, processes running on remote nodes will not compete
6636 * for remote pfmemalloc reserves and processes on different nodes
6637 * should make reasonable progress.
6638 */
6639 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006640 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006641 if (zone_idx(zone) > ZONE_NORMAL)
6642 continue;
6643
6644 /* Throttle based on the first usable node */
6645 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006646 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006647 goto out;
6648 break;
6649 }
6650
6651 /* If no zone was usable by the allocation flags then do not throttle */
6652 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006653 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006654
Mel Gorman68243e72012-07-31 16:44:39 -07006655 /* Account for the throttling */
6656 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6657
Mel Gorman55150612012-07-31 16:44:35 -07006658 /*
6659 * If the caller cannot enter the filesystem, it's possible that it
6660 * is due to the caller holding an FS lock or performing a journal
6661 * transaction in the case of a filesystem like ext[3|4]. In this case,
6662 * it is not safe to block on pfmemalloc_wait as kswapd could be
6663 * blocked waiting on the same lock. Instead, throttle for up to a
6664 * second before continuing.
6665 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006666 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006667 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006668 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006669 else
6670 /* Throttle until kswapd wakes the process */
6671 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6672 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006673
Mel Gorman50694c22012-11-26 16:29:48 -08006674 if (fatal_signal_pending(current))
6675 return true;
6676
6677out:
6678 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006679}
6680
Mel Gormandac1d272008-04-28 02:12:12 -07006681unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006682 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006683{
Mel Gorman33906bc2010-08-09 17:19:16 -07006684 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006685 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006686 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006687 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006688 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006689 .order = order,
6690 .nodemask = nodemask,
6691 .priority = DEF_PRIORITY,
6692 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006693 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006694 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006695 };
6696
Mel Gorman55150612012-07-31 16:44:35 -07006697 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006698 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6699 * Confirm they are large enough for max values.
6700 */
6701 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6702 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6703 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6704
6705 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006706 * Do not enter reclaim if fatal signal was delivered while throttled.
6707 * 1 is returned so that the page allocator does not OOM kill at this
6708 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006709 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006710 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006711 return 1;
6712
Andrew Morton1732d2b012019-07-16 16:26:15 -07006713 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006714 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006715
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006716 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006717
6718 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006719 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006720
6721 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006722}
6723
Andrew Mortonc255a452012-07-31 16:43:02 -07006724#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006725
Michal Hockod2e5fb92019-08-30 16:04:50 -07006726/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006727unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006728 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006729 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006730 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006731{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006732 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006733 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006734 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006735 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006736 .may_writepage = !laptop_mode,
6737 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006738 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006739 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006740 };
Ying Han0ae5e892011-05-26 16:25:25 -07006741
Michal Hockod2e5fb92019-08-30 16:04:50 -07006742 WARN_ON_ONCE(!current->reclaim_state);
6743
Balbir Singh4e416952009-09-23 15:56:39 -07006744 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6745 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006746
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006747 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006748 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006749
Balbir Singh4e416952009-09-23 15:56:39 -07006750 /*
6751 * NOTE: Although we can get the priority field, using it
6752 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006753 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006754 * will pick up pages from other mem cgroup's as well. We hack
6755 * the priority and make it zero.
6756 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006757 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006758
6759 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6760
Ying Han0ae5e892011-05-26 16:25:25 -07006761 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006762
Balbir Singh4e416952009-09-23 15:56:39 -07006763 return sc.nr_reclaimed;
6764}
6765
Johannes Weiner72835c82012-01-12 17:18:32 -08006766unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006767 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006768 gfp_t gfp_mask,
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006769 unsigned int reclaim_options)
Balbir Singh66e17072008-02-07 00:13:56 -08006770{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006771 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006772 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006773 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006774 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006775 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006776 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006777 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006778 .target_mem_cgroup = memcg,
6779 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006780 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006781 .may_unmap = 1,
Yosry Ahmed17bdc392022-07-14 06:49:18 +00006782 .may_swap = !!(reclaim_options & MEMCG_RECLAIM_MAY_SWAP),
6783 .proactive = !!(reclaim_options & MEMCG_RECLAIM_PROACTIVE),
Ying Hana09ed5e2011-05-24 17:12:26 -07006784 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006785 /*
6786 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6787 * equal pressure on all the nodes. This is based on the assumption that
6788 * the reclaim does not bail out early.
6789 */
6790 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006791
Andrew Morton1732d2b012019-07-16 16:26:15 -07006792 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006793 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006794 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006795
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006796 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006797
Vlastimil Babka499118e2017-05-08 15:59:50 -07006798 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006799 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006800 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006801
6802 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006803}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006804EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006805#endif
6806
Yu Zhao37397872022-09-18 02:00:03 -06006807static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006808{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006809 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006810 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006811
Yu Zhao37397872022-09-18 02:00:03 -06006812 if (lru_gen_enabled()) {
6813 lru_gen_age_node(pgdat, sc);
6814 return;
6815 }
6816
Dave Hansen2f368a92021-09-02 14:59:23 -07006817 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006818 return;
6819
Johannes Weinerb91ac372019-11-30 17:56:02 -08006820 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6821 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6822 return;
6823
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006824 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6825 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006826 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6827 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6828 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006829 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6830 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006831}
6832
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006833static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006834{
6835 int i;
6836 struct zone *zone;
6837
6838 /*
6839 * Check for watermark boosts top-down as the higher zones
6840 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006841 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006842 * start prematurely when there is no boosting and a lower
6843 * zone is balanced.
6844 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006845 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006846 zone = pgdat->node_zones + i;
6847 if (!managed_zone(zone))
6848 continue;
6849
6850 if (zone->watermark_boost)
6851 return true;
6852 }
6853
6854 return false;
6855}
6856
Mel Gormane716f2e2017-05-03 14:53:45 -07006857/*
6858 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006859 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006860 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006861static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006862{
Mel Gormane716f2e2017-05-03 14:53:45 -07006863 int i;
6864 unsigned long mark = -1;
6865 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006866
Mel Gorman1c308442018-12-28 00:35:52 -08006867 /*
6868 * Check watermarks bottom-up as lower zones are more likely to
6869 * meet watermarks.
6870 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006871 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006872 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006873
Mel Gormane716f2e2017-05-03 14:53:45 -07006874 if (!managed_zone(zone))
6875 continue;
6876
6877 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006878 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006879 return true;
6880 }
6881
6882 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006883 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006884 * need balancing by definition. This can happen if a zone-restricted
6885 * allocation tries to wake a remote kswapd.
6886 */
6887 if (mark == -1)
6888 return true;
6889
6890 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006891}
6892
Mel Gorman631b6e02017-05-03 14:53:41 -07006893/* Clear pgdat state for congested, dirty or under writeback. */
6894static void clear_pgdat_congested(pg_data_t *pgdat)
6895{
Johannes Weiner1b051172019-11-30 17:55:52 -08006896 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6897
6898 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006899 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6900 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6901}
6902
Mel Gorman1741c872011-01-13 15:46:21 -08006903/*
Mel Gorman55150612012-07-31 16:44:35 -07006904 * Prepare kswapd for sleeping. This verifies that there are no processes
6905 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6906 *
6907 * Returns true if kswapd is ready to sleep
6908 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006909static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6910 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006911{
Mel Gorman55150612012-07-31 16:44:35 -07006912 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006913 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006914 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006915 * race between when kswapd checks the watermarks and a process gets
6916 * throttled. There is also a potential race if processes get
6917 * throttled, kswapd wakes, a large process exits thereby balancing the
6918 * zones, which causes kswapd to exit balance_pgdat() before reaching
6919 * the wake up checks. If kswapd is going to sleep, no process should
6920 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6921 * the wake up is premature, processes will wake kswapd and get
6922 * throttled again. The difference from wake ups in balance_pgdat() is
6923 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006924 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006925 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6926 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006927
Johannes Weinerc73322d2017-05-03 14:51:51 -07006928 /* Hopeless node, leave it to direct reclaim */
6929 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6930 return true;
6931
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006932 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006933 clear_pgdat_congested(pgdat);
6934 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006935 }
6936
Shantanu Goel333b0a42017-05-03 14:53:38 -07006937 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006938}
6939
Linus Torvalds1da177e2005-04-16 15:20:36 -07006940/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006941 * kswapd shrinks a node of pages that are at or below the highest usable
6942 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006943 *
6944 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006945 * reclaim or if the lack of progress was due to pages under writeback.
6946 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006947 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006948static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006949 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006950{
Mel Gorman1d82de62016-07-28 15:45:43 -07006951 struct zone *zone;
6952 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006953
Mel Gorman1d82de62016-07-28 15:45:43 -07006954 /* Reclaim a number of pages proportional to the number of zones */
6955 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006956 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006957 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006958 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006959 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006960
Mel Gorman1d82de62016-07-28 15:45:43 -07006961 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006962 }
6963
Mel Gorman1d82de62016-07-28 15:45:43 -07006964 /*
6965 * Historically care was taken to put equal pressure on all zones but
6966 * now pressure is applied based on node LRU order.
6967 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006968 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006969
6970 /*
6971 * Fragmentation may mean that the system cannot be rebalanced for
6972 * high-order allocations. If twice the allocation size has been
6973 * reclaimed then recheck watermarks only at order-0 to prevent
6974 * excessive reclaim. Assume that a process requested a high-order
6975 * can direct reclaim/compact.
6976 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006977 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006978 sc->order = 0;
6979
Mel Gormanb8e83b92013-07-03 15:01:45 -07006980 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006981}
6982
Mel Gormanc49c2c42021-06-28 19:42:21 -07006983/* Page allocator PCP high watermark is lowered if reclaim is active. */
6984static inline void
6985update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6986{
6987 int i;
6988 struct zone *zone;
6989
6990 for (i = 0; i <= highest_zoneidx; i++) {
6991 zone = pgdat->node_zones + i;
6992
6993 if (!managed_zone(zone))
6994 continue;
6995
6996 if (active)
6997 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6998 else
6999 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
7000 }
7001}
7002
7003static inline void
7004set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7005{
7006 update_reclaim_active(pgdat, highest_zoneidx, true);
7007}
7008
7009static inline void
7010clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
7011{
7012 update_reclaim_active(pgdat, highest_zoneidx, false);
7013}
7014
Mel Gorman75485362013-07-03 15:01:42 -07007015/*
Mel Gorman1d82de62016-07-28 15:45:43 -07007016 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
7017 * that are eligible for use by the caller until at least one zone is
7018 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007019 *
Mel Gorman1d82de62016-07-28 15:45:43 -07007020 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007021 *
7022 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07007023 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08007024 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07007025 * or lower is eligible for reclaim until at least one usable zone is
7026 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007027 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007028static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007029{
Linus Torvalds1da177e2005-04-16 15:20:36 -07007030 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07007031 unsigned long nr_soft_reclaimed;
7032 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07007033 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08007034 unsigned long nr_boost_reclaim;
7035 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
7036 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07007037 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08007038 struct scan_control sc = {
7039 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07007040 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07007041 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08007042 };
Omar Sandoval93781322018-06-07 17:07:02 -07007043
Andrew Morton1732d2b012019-07-16 16:26:15 -07007044 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07007045 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007046 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007047
Christoph Lameterf8891e52006-06-30 01:55:45 -07007048 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007049
Mel Gorman1c308442018-12-28 00:35:52 -08007050 /*
7051 * Account for the reclaim boost. Note that the zone boost is left in
7052 * place so that parallel allocations that are near the watermark will
7053 * stall or direct reclaim until kswapd is finished.
7054 */
7055 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007056 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08007057 zone = pgdat->node_zones + i;
7058 if (!managed_zone(zone))
7059 continue;
7060
7061 nr_boost_reclaim += zone->watermark_boost;
7062 zone_boosts[i] = zone->watermark_boost;
7063 }
7064 boosted = nr_boost_reclaim;
7065
7066restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07007067 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007068 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007069 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07007070 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07007071 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08007072 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07007073 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07007074
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007075 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007076
Mel Gorman86c79f62016-07-28 15:45:59 -07007077 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07007078 * If the number of buffer_heads exceeds the maximum allowed
7079 * then consider reclaiming from all zones. This has a dual
7080 * purpose -- on 64-bit systems it is expected that
7081 * buffer_heads are stripped during active rotation. On 32-bit
7082 * systems, highmem pages can pin lowmem memory and shrinking
7083 * buffers can relieve lowmem pressure. Reclaim may still not
7084 * go ahead if all eligible zones for the original allocation
7085 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07007086 */
7087 if (buffer_heads_over_limit) {
7088 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
7089 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07007090 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07007091 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007092
Mel Gorman970a39a2016-07-28 15:46:35 -07007093 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08007094 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007095 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07007096 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08007097
Mel Gorman86c79f62016-07-28 15:45:59 -07007098 /*
Mel Gorman1c308442018-12-28 00:35:52 -08007099 * If the pgdat is imbalanced then ignore boosting and preserve
7100 * the watermarks for a later time and restart. Note that the
7101 * zone watermarks will be still reset at the end of balancing
7102 * on the grounds that the normal reclaim should be enough to
7103 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07007104 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007105 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007106 if (!balanced && nr_boost_reclaim) {
7107 nr_boost_reclaim = 0;
7108 goto restart;
7109 }
7110
7111 /*
7112 * If boosting is not active then only reclaim if there are no
7113 * eligible zones. Note that sc.reclaim_idx is not used as
7114 * buffer_heads_over_limit may have adjusted it.
7115 */
7116 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07007117 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08007118
Mel Gorman1c308442018-12-28 00:35:52 -08007119 /* Limit the priority of boosting to avoid reclaim writeback */
7120 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
7121 raise_priority = false;
7122
7123 /*
7124 * Do not writeback or swap pages for boosted reclaim. The
7125 * intent is to relieve pressure not issue sub-optimal IO
7126 * from reclaim context. If no pages are reclaimed, the
7127 * reclaim will be aborted.
7128 */
7129 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
7130 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08007131
Linus Torvalds1da177e2005-04-16 15:20:36 -07007132 /*
Yu Zhao37397872022-09-18 02:00:03 -06007133 * Do some background aging, to give pages a chance to be
7134 * referenced before reclaiming. All pages are rotated
7135 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07007136 */
Yu Zhao37397872022-09-18 02:00:03 -06007137 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07007138
7139 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007140 * If we're getting trouble reclaiming, start doing writepage
7141 * even in laptop mode.
7142 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07007143 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007144 sc.may_writepage = 1;
7145
Mel Gorman1d82de62016-07-28 15:45:43 -07007146 /* Call soft limit reclaim before calling shrink_node. */
7147 sc.nr_scanned = 0;
7148 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07007149 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07007150 sc.gfp_mask, &nr_soft_scanned);
7151 sc.nr_reclaimed += nr_soft_reclaimed;
7152
Mel Gormanb7ea3c42013-07-03 15:01:53 -07007153 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07007154 * There should be no need to raise the scanning priority if
7155 * enough pages are already being scanned that that high
7156 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007157 */
Mel Gorman970a39a2016-07-28 15:46:35 -07007158 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07007159 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07007160
7161 /*
7162 * If the low watermark is met there is no need for processes
7163 * to be throttled on pfmemalloc_wait as they should not be
7164 * able to safely make forward progress. Wake them
7165 */
7166 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07007167 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08007168 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07007169
Mel Gormanb8e83b92013-07-03 15:01:45 -07007170 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007171 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007172 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007173 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07007174 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07007175 break;
7176
7177 /*
7178 * Raise priority if scanning rate is too low or there was no
7179 * progress in reclaiming pages
7180 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07007181 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08007182 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
7183
7184 /*
7185 * If reclaim made no progress for a boost, stop reclaim as
7186 * IO cannot be queued and it could be an infinite loop in
7187 * extreme circumstances.
7188 */
7189 if (nr_boost_reclaim && !nr_reclaimed)
7190 break;
7191
Johannes Weinerc73322d2017-05-03 14:51:51 -07007192 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07007193 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07007194 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007195
Johannes Weinerc73322d2017-05-03 14:51:51 -07007196 if (!sc.nr_reclaimed)
7197 pgdat->kswapd_failures++;
7198
Mel Gormanb8e83b92013-07-03 15:01:45 -07007199out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07007200 clear_reclaim_active(pgdat, highest_zoneidx);
7201
Mel Gorman1c308442018-12-28 00:35:52 -08007202 /* If reclaim was boosted, account for the reclaim done in this pass */
7203 if (boosted) {
7204 unsigned long flags;
7205
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007206 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08007207 if (!zone_boosts[i])
7208 continue;
7209
7210 /* Increments are under the zone lock */
7211 zone = pgdat->node_zones + i;
7212 spin_lock_irqsave(&zone->lock, flags);
7213 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
7214 spin_unlock_irqrestore(&zone->lock, flags);
7215 }
7216
7217 /*
7218 * As there is now likely space, wakeup kcompact to defragment
7219 * pageblocks.
7220 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007221 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08007222 }
7223
Johannes Weiner2a2e4882017-05-03 14:55:03 -07007224 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07007225 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07007226 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07007227 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07007228
Mel Gorman0abdee22011-01-13 15:46:22 -08007229 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07007230 * Return the order kswapd stopped reclaiming at as
7231 * prepare_kswapd_sleep() takes it into account. If another caller
7232 * entered the allocator slow path while kswapd was awake, order will
7233 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08007234 */
Mel Gorman1d82de62016-07-28 15:45:43 -07007235 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007236}
7237
Mel Gormane716f2e2017-05-03 14:53:45 -07007238/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007239 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
7240 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
7241 * not a valid index then either kswapd runs for first time or kswapd couldn't
7242 * sleep after previous reclaim attempt (node is still unbalanced). In that
7243 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07007244 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007245static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
7246 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07007247{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007248 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007249
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007250 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07007251}
7252
Mel Gorman38087d92016-07-28 15:45:49 -07007253static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007254 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007255{
7256 long remaining = 0;
7257 DEFINE_WAIT(wait);
7258
7259 if (freezing(current) || kthread_should_stop())
7260 return;
7261
7262 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7263
Shantanu Goel333b0a42017-05-03 14:53:38 -07007264 /*
7265 * Try to sleep for a short interval. Note that kcompactd will only be
7266 * woken if it is possible to sleep for a short interval. This is
7267 * deliberate on the assumption that if reclaim cannot keep an
7268 * eligible zone balanced that it's also unlikely that compaction will
7269 * succeed.
7270 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007271 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07007272 /*
7273 * Compaction records what page blocks it recently failed to
7274 * isolate pages from and skips them in the future scanning.
7275 * When kswapd is going to sleep, it is reasonable to assume
7276 * that pages and compaction may succeed so reset the cache.
7277 */
7278 reset_isolation_suitable(pgdat);
7279
7280 /*
7281 * We have freed the memory, now we should compact it to make
7282 * allocation of the requested order possible.
7283 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007284 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07007285
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007286 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07007287
7288 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007289 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07007290 * order. The values will either be from a wakeup request or
7291 * the previous request that slept prematurely.
7292 */
7293 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007294 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7295 kswapd_highest_zoneidx(pgdat,
7296 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07007297
7298 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7299 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07007300 }
7301
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007302 finish_wait(&pgdat->kswapd_wait, &wait);
7303 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7304 }
7305
7306 /*
7307 * After a short sleep, check if it was a premature sleep. If not, then
7308 * go fully to sleep until explicitly woken up.
7309 */
Mel Gormand9f21d42016-07-28 15:46:41 -07007310 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007311 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007312 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7313
7314 /*
7315 * vmstat counters are not perfectly accurate and the estimated
7316 * value for counters such as NR_FREE_PAGES can deviate from the
7317 * true value by nr_online_cpus * threshold. To avoid the zone
7318 * watermarks being breached while under pressure, we reduce the
7319 * per-cpu vmstat threshold while kswapd is awake and restore
7320 * them before going back to sleep.
7321 */
7322 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07007323
7324 if (!kthread_should_stop())
7325 schedule();
7326
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007327 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7328 } else {
7329 if (remaining)
7330 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7331 else
7332 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7333 }
7334 finish_wait(&pgdat->kswapd_wait, &wait);
7335}
7336
Linus Torvalds1da177e2005-04-16 15:20:36 -07007337/*
7338 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07007339 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007340 *
7341 * This basically trickles out pages so that we have _some_
7342 * free memory available even if there is no other activity
7343 * that frees anything up. This is needed for things like routing
7344 * etc, where we otherwise might have all activity going on in
7345 * asynchronous contexts that cannot page things out.
7346 *
7347 * If there are applications that are active memory-allocators
7348 * (most normal use), this basically shouldn't matter.
7349 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307350int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007351{
Mel Gormane716f2e2017-05-03 14:53:45 -07007352 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007353 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07007354 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007355 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10307356 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007357
Rusty Russell174596a2009-01-01 10:12:29 +10307358 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07007359 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007360
7361 /*
7362 * Tell the memory management that we're a "memory allocator",
7363 * and that if we need more memory we should get access to it
7364 * regardless (see "__alloc_pages()"). "kswapd" should
7365 * never get caught in the normal page freeing logic.
7366 *
7367 * (Kswapd normally doesn't need memory anyway, but sometimes
7368 * you need a small amount of memory in order to be able to
7369 * page out something else, and this flag essentially protects
7370 * us from recursively trying to free more memory as we're
7371 * trying to free the first piece of memory in the first place).
7372 */
Christoph Lameter930d9152006-01-08 01:00:47 -08007373 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07007374 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07007375
Qian Cai5644e1fb2020-04-01 21:10:12 -07007376 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007377 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007378 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08007379 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07007380
Qian Cai5644e1fb2020-04-01 21:10:12 -07007381 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007382 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7383 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07007384
Mel Gorman38087d92016-07-28 15:45:49 -07007385kswapd_try_sleep:
7386 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007387 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07007388
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007389 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08007390 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007391 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7392 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007393 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007394 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007395
David Rientjes8fe23e02009-12-14 17:58:33 -08007396 ret = try_to_freeze();
7397 if (kthread_should_stop())
7398 break;
7399
7400 /*
7401 * We can speed up thawing tasks if we don't call balance_pgdat
7402 * after returning from the refrigerator
7403 */
Mel Gorman38087d92016-07-28 15:45:49 -07007404 if (ret)
7405 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07007406
Mel Gorman38087d92016-07-28 15:45:49 -07007407 /*
7408 * Reclaim begins at the requested order but if a high-order
7409 * reclaim fails then kswapd falls back to reclaiming for
7410 * order-0. If that happens, kswapd will consider sleeping
7411 * for the order it finished reclaiming at (reclaim_order)
7412 * but kcompactd is woken to compact for the original
7413 * request (alloc_order).
7414 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007415 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007416 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007417 reclaim_order = balance_pgdat(pgdat, alloc_order,
7418 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007419 if (reclaim_order < alloc_order)
7420 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007421 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007422
Johannes Weiner71abdc12014-06-06 14:35:35 -07007423 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007424
Linus Torvalds1da177e2005-04-16 15:20:36 -07007425 return 0;
7426}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307427EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007428
7429/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007430 * A zone is low on free memory or too fragmented for high-order memory. If
7431 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7432 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7433 * has failed or is not needed, still wake up kcompactd if only compaction is
7434 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007435 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007436void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007437 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007438{
7439 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007440 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007441
Mel Gorman6aa303d2016-09-01 16:14:55 -07007442 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007443 return;
7444
David Rientjes5ecd9d42018-04-05 16:25:16 -07007445 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007446 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007447
Qian Cai5644e1fb2020-04-01 21:10:12 -07007448 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007449 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007450
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007451 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7452 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007453
7454 if (READ_ONCE(pgdat->kswapd_order) < order)
7455 WRITE_ONCE(pgdat->kswapd_order, order);
7456
Con Kolivas8d0986e2005-09-13 01:25:07 -07007457 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007458 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007459
David Rientjes5ecd9d42018-04-05 16:25:16 -07007460 /* Hopeless node, leave it to direct reclaim if possible */
7461 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007462 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7463 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007464 /*
7465 * There may be plenty of free memory available, but it's too
7466 * fragmented for high-order allocations. Wake up kcompactd
7467 * and rely on compaction_suitable() to determine if it's
7468 * needed. If it fails, it will defer subsequent attempts to
7469 * ratelimit its work.
7470 */
7471 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007472 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007473 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007474 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007475
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007476 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007477 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007478 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007479}
7480
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007481#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007482/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007483 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007484 * freed pages.
7485 *
7486 * Rather than trying to age LRUs the aim is to preserve the overall
7487 * LRU order by reclaiming preferentially
7488 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007489 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007490unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007491{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007492 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007493 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007494 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007495 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007496 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007497 .may_writepage = 1,
7498 .may_unmap = 1,
7499 .may_swap = 1,
7500 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007501 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007502 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007503 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007504 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007505
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007506 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007507 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007508 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007509
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007510 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007511
Andrew Morton1732d2b012019-07-16 16:26:15 -07007512 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007513 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007514 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007515
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007516 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007517}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007518#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007519
Yasunori Goto3218ae12006-06-27 02:53:33 -07007520/*
7521 * This kswapd start function will be called by init and node-hot-add.
7522 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7523 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007524void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007525{
7526 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307527 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007528
7529 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007530 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007531
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307532 trace_android_vh_kswapd_per_node(nid, &skip, true);
7533 if (skip)
7534 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007535 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7536 if (IS_ERR(pgdat->kswapd)) {
7537 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007538 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007539 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007540 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007541 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007542}
7543
David Rientjes8fe23e02009-12-14 17:58:33 -08007544/*
Jiang Liud8adde12012-07-11 14:01:52 -07007545 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007546 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007547 */
7548void kswapd_stop(int nid)
7549{
7550 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307551 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007552
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307553 trace_android_vh_kswapd_per_node(nid, &skip, false);
7554 if (skip)
7555 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007556 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007557 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007558 NODE_DATA(nid)->kswapd = NULL;
7559 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007560}
7561
Linus Torvalds1da177e2005-04-16 15:20:36 -07007562static int __init kswapd_init(void)
7563{
Wei Yang6b700b52020-04-01 21:10:09 -07007564 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007565
Linus Torvalds1da177e2005-04-16 15:20:36 -07007566 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007567 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007568 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007569 return 0;
7570}
7571
7572module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007573
7574#ifdef CONFIG_NUMA
7575/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007576 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007577 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007578 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007579 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007580 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007581int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007582
Dave Hansen51998362021-02-24 12:09:15 -08007583/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007584 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007585 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7586 * a zone.
7587 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007588#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007589
Christoph Lameter9eeff232006-01-18 17:42:31 -08007590/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007591 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007592 * occur.
7593 */
7594int sysctl_min_unmapped_ratio = 1;
7595
7596/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007597 * If the number of slab pages in a zone grows beyond this percentage then
7598 * slab reclaim needs to occur.
7599 */
7600int sysctl_min_slab_ratio = 5;
7601
Mel Gorman11fb9982016-07-28 15:46:20 -07007602static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007603{
Mel Gorman11fb9982016-07-28 15:46:20 -07007604 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7605 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7606 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007607
7608 /*
7609 * It's possible for there to be more file mapped pages than
7610 * accounted for by the pages on the file LRU lists because
7611 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7612 */
7613 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7614}
7615
7616/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007617static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007618{
Alexandru Moised031a152015-11-05 18:48:08 -08007619 unsigned long nr_pagecache_reclaimable;
7620 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007621
7622 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007623 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007624 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007625 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007626 * a better estimate
7627 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007628 if (node_reclaim_mode & RECLAIM_UNMAP)
7629 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007630 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007631 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007632
7633 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007634 if (!(node_reclaim_mode & RECLAIM_WRITE))
7635 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007636
7637 /* Watch for any possible underflows due to delta */
7638 if (unlikely(delta > nr_pagecache_reclaimable))
7639 delta = nr_pagecache_reclaimable;
7640
7641 return nr_pagecache_reclaimable - delta;
7642}
7643
Christoph Lameter0ff38492006-09-25 23:31:52 -07007644/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007645 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007646 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007647static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007648{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007649 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007650 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007651 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007652 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007653 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007654 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007655 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007656 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007657 .priority = NODE_RECLAIM_PRIORITY,
7658 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7659 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007660 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007661 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007662 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007663 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007664
Yafang Shao132bb8c2019-05-13 17:17:53 -07007665 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7666 sc.gfp_mask);
7667
Christoph Lameter9eeff232006-01-18 17:42:31 -08007668 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007669 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007670 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007671 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007672 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007673 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007674 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007675 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007676 noreclaim_flag = memalloc_noreclaim_save();
7677 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007678 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007679
Mel Gormana5f5f912016-07-28 15:46:32 -07007680 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007681 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007682 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007683 * priorities until we have enough memory freed.
7684 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007685 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007686 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007687 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007688 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007689
Andrew Morton1732d2b012019-07-16 16:26:15 -07007690 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007691 current->flags &= ~PF_SWAPWRITE;
7692 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007693 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007694 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007695
7696 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7697
Rik van Riela79311c2009-01-06 14:40:01 -08007698 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007699}
Andrew Morton179e9632006-03-22 00:08:18 -08007700
Mel Gormana5f5f912016-07-28 15:46:32 -07007701int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007702{
David Rientjesd773ed62007-10-16 23:26:01 -07007703 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007704
7705 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007706 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007707 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007708 *
Christoph Lameter96146342006-07-03 00:24:13 -07007709 * A small portion of unmapped file backed pages is needed for
7710 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007711 * thrown out if the node is overallocated. So we do not reclaim
7712 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007713 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007714 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007715 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007716 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7717 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007718 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007719
7720 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007721 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007722 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007723 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007724 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007725
7726 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007727 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007728 * have associated processors. This will favor the local processor
7729 * over remote processors and spread off node memory allocations
7730 * as wide as possible.
7731 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007732 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7733 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007734
Mel Gormana5f5f912016-07-28 15:46:32 -07007735 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7736 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007737
Mel Gormana5f5f912016-07-28 15:46:32 -07007738 ret = __node_reclaim(pgdat, gfp_mask, order);
7739 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007740
Mel Gorman24cf725182009-06-16 15:33:23 -07007741 if (!ret)
7742 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7743
David Rientjesd773ed62007-10-16 23:26:01 -07007744 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007745}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007746#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007747
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007748/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007749 * check_move_unevictable_pages - check pages for evictability and move to
7750 * appropriate zone lru list
7751 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007752 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007753 * Checks pages for evictability, if an evictable page is in the unevictable
7754 * lru list, moves it to the appropriate evictable lru list. This function
7755 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007756 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007757void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007758{
Alex Shi6168d0d2020-12-15 12:34:29 -08007759 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007760 int pgscanned = 0;
7761 int pgrescued = 0;
7762 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007763
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007764 for (i = 0; i < pvec->nr; i++) {
7765 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007766 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007767
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007768 if (PageTransTail(page))
7769 continue;
7770
7771 nr_pages = thp_nr_pages(page);
7772 pgscanned += nr_pages;
7773
Alex Shid25b5bd2020-12-15 12:34:16 -08007774 /* block memcg migration during page moving between lru */
7775 if (!TestClearPageLRU(page))
7776 continue;
7777
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007778 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007779 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007780 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007781 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007782 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007783 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007784 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007785 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007786 }
Hugh Dickins24513262012-01-20 14:34:21 -08007787
Alex Shi6168d0d2020-12-15 12:34:29 -08007788 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007789 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7790 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007791 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007792 } else if (pgscanned) {
7793 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007794 }
Hugh Dickins850465792012-01-20 14:34:19 -08007795}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007796EXPORT_SYMBOL_GPL(check_move_unevictable_pages);