blob: 67e229e2833aeccb11f5b3a46958560621101b6e [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>
Linus Torvalds1da177e2005-04-16 15:20:36 -070056
57#include <asm/tlbflush.h>
58#include <asm/div64.h>
59
60#include <linux/swapops.h>
Rafael Aquini117aad12013-09-30 13:45:16 -070061#include <linux/balloon_compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070062
Nick Piggin0f8053a2006-03-22 00:08:33 -080063#include "internal.h"
64
Mel Gorman33906bc2010-08-09 17:19:16 -070065#define CREATE_TRACE_POINTS
66#include <trace/events/vmscan.h>
67
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -070068#undef CREATE_TRACE_POINTS
69#include <trace/hooks/vmscan.h>
70
Linus Torvalds1da177e2005-04-16 15:20:36 -070071struct scan_control {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -080072 /* How many pages shrink_list() should reclaim */
73 unsigned long nr_to_reclaim;
74
Johannes Weineree814fe2014-08-06 16:06:19 -070075 /*
76 * Nodemask of nodes allowed by the caller. If NULL, all nodes
77 * are scanned.
78 */
79 nodemask_t *nodemask;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -070080
KOSAKI Motohiro5f53e762010-05-24 14:32:37 -070081 /*
Johannes Weinerf16015f2012-01-12 17:17:52 -080082 * The memory cgroup that hit its limit and as a result is the
83 * primary target of this reclaim invocation.
84 */
85 struct mem_cgroup *target_mem_cgroup;
Balbir Singh66e17072008-02-07 00:13:56 -080086
Johannes Weiner7cf111b2020-06-03 16:03:06 -070087 /*
88 * Scan pressure balancing between anon and file LRUs
89 */
90 unsigned long anon_cost;
91 unsigned long file_cost;
92
Johannes Weinerb91ac372019-11-30 17:56:02 -080093 /* Can active pages be deactivated as part of reclaim? */
94#define DEACTIVATE_ANON 1
95#define DEACTIVATE_FILE 2
96 unsigned int may_deactivate:2;
97 unsigned int force_deactivate:1;
98 unsigned int skipped_deactivate:1;
99
Johannes Weiner1276ad62017-02-24 14:56:11 -0800100 /* Writepage batching in laptop mode; RECLAIM_WRITE */
Johannes Weineree814fe2014-08-06 16:06:19 -0700101 unsigned int may_writepage:1;
102
103 /* Can mapped pages be reclaimed? */
104 unsigned int may_unmap:1;
105
106 /* Can pages be swapped as part of reclaim? */
107 unsigned int may_swap:1;
108
Yisheng Xied6622f62017-05-03 14:53:57 -0700109 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700110 * Cgroup memory below memory.low is protected as long as we
111 * don't threaten to OOM. If any cgroup is reclaimed at
112 * reduced force or passed over entirely due to its memory.low
113 * setting (memcg_low_skipped), and nothing is reclaimed as a
114 * result, then go back for one more cycle that reclaims the protected
115 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700116 */
117 unsigned int memcg_low_reclaim:1;
118 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800119
Johannes Weineree814fe2014-08-06 16:06:19 -0700120 unsigned int hibernation_mode:1;
121
122 /* One of the zones is ready for compaction */
123 unsigned int compaction_ready:1;
124
Johannes Weinerb91ac372019-11-30 17:56:02 -0800125 /* There is easily reclaimable cold cache in the current node */
126 unsigned int cache_trim_mode:1;
127
Johannes Weiner53138ce2019-11-30 17:55:56 -0800128 /* The file pages on the current node are dangerously low */
129 unsigned int file_is_tiny:1;
130
Dave Hansen26aa2d12021-09-02 14:59:16 -0700131 /* Always discard instead of demoting to lower tier memory */
132 unsigned int no_demotion:1;
133
Yu Zhaoa8a158a2022-09-18 02:00:06 -0600134#ifdef CONFIG_LRU_GEN
135 /* help kswapd make better choices among multiple memcgs */
136 unsigned int memcgs_need_aging:1;
137 unsigned long last_reclaimed;
138#endif
139
Greg Thelenbb451fd2018-08-17 15:45:19 -0700140 /* Allocation order */
141 s8 order;
142
143 /* Scan (total_size >> priority) pages at once */
144 s8 priority;
145
146 /* The highest zone to isolate pages for reclaim from */
147 s8 reclaim_idx;
148
149 /* This context's GFP mask */
150 gfp_t gfp_mask;
151
Johannes Weineree814fe2014-08-06 16:06:19 -0700152 /* Incremented by the number of inactive pages that were scanned */
153 unsigned long nr_scanned;
154
155 /* Number of pages freed so far during a call to shrink_zones() */
156 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700157
158 struct {
159 unsigned int dirty;
160 unsigned int unqueued_dirty;
161 unsigned int congested;
162 unsigned int writeback;
163 unsigned int immediate;
164 unsigned int file_taken;
165 unsigned int taken;
166 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700167
168 /* for recording the reclaimed slab by now */
169 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700170};
171
Linus Torvalds1da177e2005-04-16 15:20:36 -0700172#ifdef ARCH_HAS_PREFETCHW
173#define prefetchw_prev_lru_page(_page, _base, _field) \
174 do { \
175 if ((_page)->lru.prev != _base) { \
176 struct page *prev; \
177 \
178 prev = lru_to_page(&(_page->lru)); \
179 prefetchw(&prev->_field); \
180 } \
181 } while (0)
182#else
183#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
184#endif
185
186/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700187 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700188 */
189int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700190
Yang Shi0a432dc2019-09-23 15:38:12 -0700191static void set_task_reclaim_state(struct task_struct *task,
192 struct reclaim_state *rs)
193{
194 /* Check for an overwrite */
195 WARN_ON_ONCE(rs && task->reclaim_state);
196
197 /* Check for the nulling of an already-nulled member */
198 WARN_ON_ONCE(!rs && !task->reclaim_state);
199
200 task->reclaim_state = rs;
201}
202
Linus Torvalds1da177e2005-04-16 15:20:36 -0700203static LIST_HEAD(shrinker_list);
204static DECLARE_RWSEM(shrinker_rwsem);
205
Yang Shi0a432dc2019-09-23 15:38:12 -0700206#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700207static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700208
Yang Shi3c6f17e2021-05-04 18:36:33 -0700209/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700210static inline int shrinker_map_size(int nr_items)
211{
212 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
213}
Yang Shi2bfd3632021-05-04 18:36:11 -0700214
Yang Shi3c6f17e2021-05-04 18:36:33 -0700215static inline int shrinker_defer_size(int nr_items)
216{
217 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
218}
219
Yang Shi468ab842021-05-04 18:36:26 -0700220static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
221 int nid)
222{
223 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
224 lockdep_is_held(&shrinker_rwsem));
225}
226
Yang Shie4262c42021-05-04 18:36:23 -0700227static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700228 int map_size, int defer_size,
229 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700230{
Yang Shie4262c42021-05-04 18:36:23 -0700231 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700232 struct mem_cgroup_per_node *pn;
233 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700234 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700235
Yang Shi2bfd3632021-05-04 18:36:11 -0700236 for_each_node(nid) {
237 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700238 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700239 /* Not yet online memcg */
240 if (!old)
241 return 0;
242
243 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
244 if (!new)
245 return -ENOMEM;
246
Yang Shi3c6f17e2021-05-04 18:36:33 -0700247 new->nr_deferred = (atomic_long_t *)(new + 1);
248 new->map = (void *)new->nr_deferred + defer_size;
249
250 /* map: set all old bits, clear all new bits */
251 memset(new->map, (int)0xff, old_map_size);
252 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
253 /* nr_deferred: copy old values, clear all new values */
254 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
255 memset((void *)new->nr_deferred + old_defer_size, 0,
256 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700257
Yang Shie4262c42021-05-04 18:36:23 -0700258 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700259 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700260 }
261
262 return 0;
263}
264
Yang Shie4262c42021-05-04 18:36:23 -0700265void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700266{
267 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700268 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700269 int nid;
270
Yang Shi2bfd3632021-05-04 18:36:11 -0700271 for_each_node(nid) {
272 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700273 info = rcu_dereference_protected(pn->shrinker_info, true);
274 kvfree(info);
275 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700276 }
277}
278
Yang Shie4262c42021-05-04 18:36:23 -0700279int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700280{
Yang Shie4262c42021-05-04 18:36:23 -0700281 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700282 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700283 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700284
Yang Shid27cf2a2021-05-04 18:36:14 -0700285 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700286 map_size = shrinker_map_size(shrinker_nr_max);
287 defer_size = shrinker_defer_size(shrinker_nr_max);
288 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700289 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700290 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
291 if (!info) {
292 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700293 ret = -ENOMEM;
294 break;
295 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700296 info->nr_deferred = (atomic_long_t *)(info + 1);
297 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700298 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700299 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700300 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700301
302 return ret;
303}
304
Yang Shi3c6f17e2021-05-04 18:36:33 -0700305static inline bool need_expand(int nr_max)
306{
307 return round_up(nr_max, BITS_PER_LONG) >
308 round_up(shrinker_nr_max, BITS_PER_LONG);
309}
310
Yang Shie4262c42021-05-04 18:36:23 -0700311static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700312{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700313 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700314 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700315 int map_size, defer_size = 0;
316 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700317 struct mem_cgroup *memcg;
318
Yang Shi3c6f17e2021-05-04 18:36:33 -0700319 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700320 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700321
Yang Shi2bfd3632021-05-04 18:36:11 -0700322 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700323 goto out;
324
325 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700326
Yang Shi3c6f17e2021-05-04 18:36:33 -0700327 map_size = shrinker_map_size(new_nr_max);
328 defer_size = shrinker_defer_size(new_nr_max);
329 old_map_size = shrinker_map_size(shrinker_nr_max);
330 old_defer_size = shrinker_defer_size(shrinker_nr_max);
331
Yang Shi2bfd3632021-05-04 18:36:11 -0700332 memcg = mem_cgroup_iter(NULL, NULL, NULL);
333 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700334 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
335 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700336 if (ret) {
337 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700338 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700339 }
340 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700341out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700342 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700343 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700344
Yang Shi2bfd3632021-05-04 18:36:11 -0700345 return ret;
346}
347
348void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
349{
350 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700351 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700352
353 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700354 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700355 /* Pairs with smp mb in shrink_slab() */
356 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700357 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700358 rcu_read_unlock();
359 }
360}
361
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700362static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700363
364static int prealloc_memcg_shrinker(struct shrinker *shrinker)
365{
366 int id, ret = -ENOMEM;
367
Yang Shi476b30a2021-05-04 18:36:39 -0700368 if (mem_cgroup_disabled())
369 return -ENOSYS;
370
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700371 down_write(&shrinker_rwsem);
372 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700373 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700374 if (id < 0)
375 goto unlock;
376
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700377 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700378 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700379 idr_remove(&shrinker_idr, id);
380 goto unlock;
381 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700382 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700383 shrinker->id = id;
384 ret = 0;
385unlock:
386 up_write(&shrinker_rwsem);
387 return ret;
388}
389
390static void unregister_memcg_shrinker(struct shrinker *shrinker)
391{
392 int id = shrinker->id;
393
394 BUG_ON(id < 0);
395
Yang Shi41ca6682021-05-04 18:36:29 -0700396 lockdep_assert_held(&shrinker_rwsem);
397
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700398 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700399}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700400
Yang Shi86750832021-05-04 18:36:36 -0700401static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
402 struct mem_cgroup *memcg)
403{
404 struct shrinker_info *info;
405
406 info = shrinker_info_protected(memcg, nid);
407 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
408}
409
410static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
411 struct mem_cgroup *memcg)
412{
413 struct shrinker_info *info;
414
415 info = shrinker_info_protected(memcg, nid);
416 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
417}
418
Yang Shia1780152021-05-04 18:36:42 -0700419void reparent_shrinker_deferred(struct mem_cgroup *memcg)
420{
421 int i, nid;
422 long nr;
423 struct mem_cgroup *parent;
424 struct shrinker_info *child_info, *parent_info;
425
426 parent = parent_mem_cgroup(memcg);
427 if (!parent)
428 parent = root_mem_cgroup;
429
430 /* Prevent from concurrent shrinker_info expand */
431 down_read(&shrinker_rwsem);
432 for_each_node(nid) {
433 child_info = shrinker_info_protected(memcg, nid);
434 parent_info = shrinker_info_protected(parent, nid);
435 for (i = 0; i < shrinker_nr_max; i++) {
436 nr = atomic_long_read(&child_info->nr_deferred[i]);
437 atomic_long_add(nr, &parent_info->nr_deferred[i]);
438 }
439 }
440 up_read(&shrinker_rwsem);
441}
442
Johannes Weinerb5ead352019-11-30 17:55:40 -0800443static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800444{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800445 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800446}
Tejun Heo97c93412015-05-22 18:23:36 -0400447
448/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800449 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400450 * @sc: scan_control in question
451 *
452 * The normal page dirty throttling mechanism in balance_dirty_pages() is
453 * completely broken with the legacy memcg and direct stalling in
454 * shrink_page_list() is used for throttling instead, which lacks all the
455 * niceties such as fairness, adaptive pausing, bandwidth proportional
456 * allocation and configurability.
457 *
458 * This function tests whether the vmscan currently in progress can assume
459 * that the normal dirty throttling mechanism is operational.
460 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800461static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400462{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800463 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400464 return true;
465#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800466 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400467 return true;
468#endif
469 return false;
470}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800471#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700472static int prealloc_memcg_shrinker(struct shrinker *shrinker)
473{
Yang Shi476b30a2021-05-04 18:36:39 -0700474 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700475}
476
477static void unregister_memcg_shrinker(struct shrinker *shrinker)
478{
479}
480
Yang Shi86750832021-05-04 18:36:36 -0700481static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
482 struct mem_cgroup *memcg)
483{
484 return 0;
485}
486
487static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
488 struct mem_cgroup *memcg)
489{
490 return 0;
491}
492
Johannes Weinerb5ead352019-11-30 17:55:40 -0800493static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800494{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800495 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800496}
Tejun Heo97c93412015-05-22 18:23:36 -0400497
Johannes Weinerb5ead352019-11-30 17:55:40 -0800498static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400499{
500 return true;
501}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800502#endif
503
Yang Shi86750832021-05-04 18:36:36 -0700504static long xchg_nr_deferred(struct shrinker *shrinker,
505 struct shrink_control *sc)
506{
507 int nid = sc->nid;
508
509 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
510 nid = 0;
511
512 if (sc->memcg &&
513 (shrinker->flags & SHRINKER_MEMCG_AWARE))
514 return xchg_nr_deferred_memcg(nid, shrinker,
515 sc->memcg);
516
517 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
518}
519
520
521static long add_nr_deferred(long nr, struct shrinker *shrinker,
522 struct shrink_control *sc)
523{
524 int nid = sc->nid;
525
526 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
527 nid = 0;
528
529 if (sc->memcg &&
530 (shrinker->flags & SHRINKER_MEMCG_AWARE))
531 return add_nr_deferred_memcg(nr, nid, shrinker,
532 sc->memcg);
533
534 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
535}
536
Dave Hansen26aa2d12021-09-02 14:59:16 -0700537static bool can_demote(int nid, struct scan_control *sc)
538{
Huang Ying20b51af12021-09-02 14:59:33 -0700539 if (!numa_demotion_enabled)
540 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700541 if (sc) {
542 if (sc->no_demotion)
543 return false;
544 /* It is pointless to do demotion in memcg reclaim */
545 if (cgroup_reclaim(sc))
546 return false;
547 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700548 if (next_demotion_node(nid) == NUMA_NO_NODE)
549 return false;
550
Huang Ying20b51af12021-09-02 14:59:33 -0700551 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700552}
553
Keith Buscha2a36482021-09-02 14:59:26 -0700554static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
555 int nid,
556 struct scan_control *sc)
557{
558 if (memcg == NULL) {
559 /*
560 * For non-memcg reclaim, is there
561 * space in any swap device?
562 */
563 if (get_nr_swap_pages() > 0)
564 return true;
565 } else {
566 /* Is the memcg below its swap limit? */
567 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
568 return true;
569 }
570
571 /*
572 * The page can not be swapped.
573 *
574 * Can it be reclaimed from this node via demotion?
575 */
576 return can_demote(nid, sc);
577}
578
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700579/*
580 * This misses isolated pages which are not accounted for to save counters.
581 * As the data only determines if reclaim or compaction continues, it is
582 * not expected that isolated pages will be a dominating factor.
583 */
584unsigned long zone_reclaimable_pages(struct zone *zone)
585{
586 unsigned long nr;
587
588 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
589 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700590 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700591 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
592 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
593
594 return nr;
595}
596
Michal Hockofd538802017-02-22 15:45:58 -0800597/**
598 * lruvec_lru_size - Returns the number of pages on the given LRU list.
599 * @lruvec: lru vector
600 * @lru: lru to use
601 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
602 */
Yu Zhao20913392021-02-24 12:08:44 -0800603static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
604 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800605{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800606 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800607 int zid;
608
Johannes Weinerde3b0152019-11-30 17:55:31 -0800609 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800610 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800611
Michal Hockofd538802017-02-22 15:45:58 -0800612 if (!managed_zone(zone))
613 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800614
Michal Hockofd538802017-02-22 15:45:58 -0800615 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800616 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800617 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800618 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800619 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800620 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800621}
622
Linus Torvalds1da177e2005-04-16 15:20:36 -0700623/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000624 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700625 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900626int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700627{
Yang Shi476b30a2021-05-04 18:36:39 -0700628 unsigned int size;
629 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000630
Yang Shi476b30a2021-05-04 18:36:39 -0700631 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
632 err = prealloc_memcg_shrinker(shrinker);
633 if (err != -ENOSYS)
634 return err;
635
636 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
637 }
638
639 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000640 if (shrinker->flags & SHRINKER_NUMA_AWARE)
641 size *= nr_node_ids;
642
643 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
644 if (!shrinker->nr_deferred)
645 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700646
Tetsuo Handa8e049442018-04-04 19:53:07 +0900647 return 0;
648}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000649
Tetsuo Handa8e049442018-04-04 19:53:07 +0900650void free_prealloced_shrinker(struct shrinker *shrinker)
651{
Yang Shi41ca6682021-05-04 18:36:29 -0700652 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
653 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700654 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700655 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700656 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700657 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700658
Tetsuo Handa8e049442018-04-04 19:53:07 +0900659 kfree(shrinker->nr_deferred);
660 shrinker->nr_deferred = NULL;
661}
662
663void register_shrinker_prepared(struct shrinker *shrinker)
664{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700665 down_write(&shrinker_rwsem);
666 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700667 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700668 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900669}
670
671int register_shrinker(struct shrinker *shrinker)
672{
673 int err = prealloc_shrinker(shrinker);
674
675 if (err)
676 return err;
677 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000678 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700679}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700680EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700681
682/*
683 * Remove one
684 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700685void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700686{
Yang Shi41ca6682021-05-04 18:36:29 -0700687 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900688 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700689
Linus Torvalds1da177e2005-04-16 15:20:36 -0700690 down_write(&shrinker_rwsem);
691 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700692 shrinker->flags &= ~SHRINKER_REGISTERED;
693 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
694 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700695 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700696
Andrew Vaginae393322013-10-16 13:46:46 -0700697 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900698 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700699}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700700EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700701
702#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000703
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800704static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800705 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700706{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000707 unsigned long freed = 0;
708 unsigned long long delta;
709 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700710 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000711 long nr;
712 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000713 long batch_size = shrinker->batch ? shrinker->batch
714 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800715 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000716
rongqianfeng8da6ee32021-05-21 10:30:14 +0800717 trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
718
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700719 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700720 if (freeable == 0 || freeable == SHRINK_EMPTY)
721 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000722
723 /*
724 * copy the current shrinker scan count into a local variable
725 * and zero it so that other concurrent shrinker invocations
726 * don't also do this scanning work.
727 */
Yang Shi86750832021-05-04 18:36:36 -0700728 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000729
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700730 if (shrinker->seeks) {
731 delta = freeable >> priority;
732 delta *= 4;
733 do_div(delta, shrinker->seeks);
734 } else {
735 /*
736 * These objects don't require any IO to create. Trim
737 * them aggressively under memory pressure to keep
738 * them from causing refetches in the IO caches.
739 */
740 delta = freeable / 2;
741 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700742
Yang Shi18bb4732021-05-04 18:36:45 -0700743 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000744 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700745 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000746
747 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800748 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000749
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800750 /*
751 * Normally, we should not scan less than batch_size objects in one
752 * pass to avoid too frequent shrinker calls, but if the slab has less
753 * than batch_size objects in total and we are really tight on memory,
754 * we will try to reclaim all available objects, otherwise we can end
755 * up failing allocations although there are plenty of reclaimable
756 * objects spread over several slabs with usage less than the
757 * batch_size.
758 *
759 * We detect the "tight on memory" situations by looking at the total
760 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700761 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800762 * scanning at high prio and therefore should try to reclaim as much as
763 * possible.
764 */
765 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700766 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000767 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800768 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000769
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800770 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700771 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000772 ret = shrinker->scan_objects(shrinker, shrinkctl);
773 if (ret == SHRINK_STOP)
774 break;
775 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000776
Chris Wilsond460acb2017-09-06 16:19:26 -0700777 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
778 total_scan -= shrinkctl->nr_scanned;
779 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000780
781 cond_resched();
782 }
783
Yang Shi18bb4732021-05-04 18:36:45 -0700784 /*
785 * The deferred work is increased by any new work (delta) that wasn't
786 * done, decreased by old deferred work that was done now.
787 *
788 * And it is capped to two times of the freeable items.
789 */
790 next_deferred = max_t(long, (nr + delta - scanned), 0);
791 next_deferred = min(next_deferred, (2 * freeable));
792
Glauber Costa1d3d4432013-08-28 10:18:04 +1000793 /*
794 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700795 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000796 */
Yang Shi86750832021-05-04 18:36:36 -0700797 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000798
Yang Shi8efb4b52021-05-04 18:36:08 -0700799 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000800 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700801}
802
Yang Shi0a432dc2019-09-23 15:38:12 -0700803#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700804static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
805 struct mem_cgroup *memcg, int priority)
806{
Yang Shie4262c42021-05-04 18:36:23 -0700807 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700808 unsigned long ret, freed = 0;
809 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700810
Yang Shi0a432dc2019-09-23 15:38:12 -0700811 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700812 return 0;
813
814 if (!down_read_trylock(&shrinker_rwsem))
815 return 0;
816
Yang Shi468ab842021-05-04 18:36:26 -0700817 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700818 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700819 goto unlock;
820
Yang Shie4262c42021-05-04 18:36:23 -0700821 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700822 struct shrink_control sc = {
823 .gfp_mask = gfp_mask,
824 .nid = nid,
825 .memcg = memcg,
826 };
827 struct shrinker *shrinker;
828
829 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700830 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700831 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700832 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700833 continue;
834 }
835
Yang Shi0a432dc2019-09-23 15:38:12 -0700836 /* Call non-slab shrinkers even though kmem is disabled */
837 if (!memcg_kmem_enabled() &&
838 !(shrinker->flags & SHRINKER_NONSLAB))
839 continue;
840
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700841 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700842 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700843 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700844 /*
845 * After the shrinker reported that it had no objects to
846 * free, but before we cleared the corresponding bit in
847 * the memcg shrinker map, a new object might have been
848 * added. To make sure, we have the bit set in this
849 * case, we invoke the shrinker one more time and reset
850 * the bit if it reports that it is not empty anymore.
851 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700852 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700853 *
854 * list_lru_add() shrink_slab_memcg()
855 * list_add_tail() clear_bit()
856 * <MB> <MB>
857 * set_bit() do_shrink_slab()
858 */
859 smp_mb__after_atomic();
860 ret = do_shrink_slab(&sc, shrinker, priority);
861 if (ret == SHRINK_EMPTY)
862 ret = 0;
863 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700864 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700865 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700866 freed += ret;
867
868 if (rwsem_is_contended(&shrinker_rwsem)) {
869 freed = freed ? : 1;
870 break;
871 }
872 }
873unlock:
874 up_read(&shrinker_rwsem);
875 return freed;
876}
Yang Shi0a432dc2019-09-23 15:38:12 -0700877#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700878static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
879 struct mem_cgroup *memcg, int priority)
880{
881 return 0;
882}
Yang Shi0a432dc2019-09-23 15:38:12 -0700883#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700884
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800885/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800886 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800887 * @gfp_mask: allocation context
888 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800889 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800890 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700891 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800892 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700893 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800894 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
895 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700896 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700897 * @memcg specifies the memory cgroup to target. Unaware shrinkers
898 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800899 *
Josef Bacik9092c712018-01-31 16:16:26 -0800900 * @priority is sc->priority, we take the number of objects and >> by priority
901 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700902 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800903 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700904 */
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800905unsigned long shrink_slab(gfp_t gfp_mask, int nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800906 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800907 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700908{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700909 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700910 struct shrinker *shrinker;
wudean842c68a2021-04-27 17:40:41 +0800911 bool bypass = false;
912
913 trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
914 if (bypass)
915 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700916
Yang Shifa1e5122019-08-02 21:48:44 -0700917 /*
918 * The root memcg might be allocated even though memcg is disabled
919 * via "cgroup_disable=memory" boot parameter. This could make
920 * mem_cgroup_is_root() return false, then just run memcg slab
921 * shrink, but skip global shrink. This may result in premature
922 * oom.
923 */
924 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700925 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800926
Tetsuo Handae830c632018-04-05 16:23:35 -0700927 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700928 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700929
930 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800931 struct shrink_control sc = {
932 .gfp_mask = gfp_mask,
933 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800934 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800935 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800936
Kirill Tkhai9b996462018-08-17 15:48:21 -0700937 ret = do_shrink_slab(&sc, shrinker, priority);
938 if (ret == SHRINK_EMPTY)
939 ret = 0;
940 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800941 /*
942 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700943 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800944 * by parallel ongoing shrinking.
945 */
946 if (rwsem_is_contended(&shrinker_rwsem)) {
947 freed = freed ? : 1;
948 break;
949 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700950 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800951
Linus Torvalds1da177e2005-04-16 15:20:36 -0700952 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700953out:
954 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000955 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700956}
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800957EXPORT_SYMBOL_GPL(shrink_slab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700958
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800959void drop_slab_node(int nid)
960{
961 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700962 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800963
964 do {
965 struct mem_cgroup *memcg = NULL;
966
Chunxin Zang069c4112020-10-13 16:56:46 -0700967 if (fatal_signal_pending(current))
968 return;
969
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800970 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700971 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800972 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800973 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800974 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700975 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800976}
977
978void drop_slab(void)
979{
980 int nid;
981
982 for_each_online_node(nid)
983 drop_slab_node(nid);
984}
985
Linus Torvalds1da177e2005-04-16 15:20:36 -0700986static inline int is_page_cache_freeable(struct page *page)
987{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700988 /*
989 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400990 * that isolated the page, the page cache and optional buffer
991 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700992 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -0700993 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400994 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700995}
996
Yang Shicb165562019-11-30 17:55:28 -0800997static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700998{
Christoph Lameter930d9152006-01-08 01:00:47 -0800999 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001000 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001001 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001002 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001003 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001004 return 1;
1005 return 0;
1006}
1007
1008/*
1009 * We detected a synchronous write error writing a page out. Probably
1010 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1011 * fsync(), msync() or close().
1012 *
1013 * The tricky part is that after writepage we cannot touch the mapping: nothing
1014 * prevents it from being freed up. But we have a ref on the page and once
1015 * that page is locked, the mapping is pinned.
1016 *
1017 * We're allowed to run sleeping lock_page() here because we know the caller has
1018 * __GFP_FS.
1019 */
1020static void handle_write_error(struct address_space *mapping,
1021 struct page *page, int error)
1022{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001023 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001024 if (page_mapping(page) == mapping)
1025 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001026 unlock_page(page);
1027}
1028
Christoph Lameter04e62a22006-06-23 02:03:38 -07001029/* possible outcome of pageout() */
1030typedef enum {
1031 /* failed to write page out, page is locked */
1032 PAGE_KEEP,
1033 /* move page to the active list, page is locked */
1034 PAGE_ACTIVATE,
1035 /* page has been sent to the disk successfully, page is unlocked */
1036 PAGE_SUCCESS,
1037 /* page is clean and locked */
1038 PAGE_CLEAN,
1039} pageout_t;
1040
Linus Torvalds1da177e2005-04-16 15:20:36 -07001041/*
Andrew Morton1742f192006-03-22 00:08:21 -08001042 * pageout is called by shrink_page_list() for each dirty page.
1043 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001044 */
Yang Shicb165562019-11-30 17:55:28 -08001045static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001046{
1047 /*
1048 * If the page is dirty, only perform writeback if that write
1049 * will be non-blocking. To prevent this allocation from being
1050 * stalled by pagecache activity. But note that there may be
1051 * stalls if we need to run get_block(). We could test
1052 * PagePrivate for that.
1053 *
Al Viro81742022014-04-03 03:17:43 -04001054 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001055 * this page's queue, we can perform writeback even if that
1056 * will block.
1057 *
1058 * If the page is swapcache, write it back even if that would
1059 * block, for some throttling. This happens by accident, because
1060 * swap_backing_dev_info is bust: it doesn't reflect the
1061 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001062 */
1063 if (!is_page_cache_freeable(page))
1064 return PAGE_KEEP;
1065 if (!mapping) {
1066 /*
1067 * Some data journaling orphaned pages can have
1068 * page->mapping == NULL while being dirty with clean buffers.
1069 */
David Howells266cf652009-04-03 16:42:36 +01001070 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001071 if (try_to_free_buffers(page)) {
1072 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001073 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001074 return PAGE_CLEAN;
1075 }
1076 }
1077 return PAGE_KEEP;
1078 }
1079 if (mapping->a_ops->writepage == NULL)
1080 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001081 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001082 return PAGE_KEEP;
1083
1084 if (clear_page_dirty_for_io(page)) {
1085 int res;
1086 struct writeback_control wbc = {
1087 .sync_mode = WB_SYNC_NONE,
1088 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001089 .range_start = 0,
1090 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001091 .for_reclaim = 1,
1092 };
1093
1094 SetPageReclaim(page);
1095 res = mapping->a_ops->writepage(page, &wbc);
1096 if (res < 0)
1097 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001098 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001099 ClearPageReclaim(page);
1100 return PAGE_ACTIVATE;
1101 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001102
Linus Torvalds1da177e2005-04-16 15:20:36 -07001103 if (!PageWriteback(page)) {
1104 /* synchronous write or broken a_ops? */
1105 ClearPageReclaim(page);
1106 }
yalin wang3aa23852016-01-14 15:18:30 -08001107 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001108 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001109 return PAGE_SUCCESS;
1110 }
1111
1112 return PAGE_CLEAN;
1113}
1114
Andrew Mortona649fd92006-10-17 00:09:36 -07001115/*
Nick Piggine2867812008-07-25 19:45:30 -07001116 * Same as remove_mapping, but if the page is removed from the mapping, it
1117 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001118 */
Johannes Weinera5289102014-04-03 14:47:51 -07001119static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001120 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001121{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001122 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001123 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001124
Nick Piggin28e4d962006-09-25 23:31:23 -07001125 BUG_ON(!PageLocked(page));
1126 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001127
Johannes Weiner30472502021-09-02 14:53:18 -07001128 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001129 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001130 * The non racy check for a busy page.
1131 *
1132 * Must be careful with the order of the tests. When someone has
1133 * a ref to the page, it may be possible that they dirty it then
1134 * drop the reference. So if PageDirty is tested before page_count
1135 * here, then the following race may occur:
1136 *
1137 * get_user_pages(&page);
1138 * [user mapping goes away]
1139 * write_to(page);
1140 * !PageDirty(page) [good]
1141 * SetPageDirty(page);
1142 * put_page(page);
1143 * !page_count(page) [good, discard it]
1144 *
1145 * [oops, our write_to data is lost]
1146 *
1147 * Reversing the order of the tests ensures such a situation cannot
1148 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001149 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001150 *
1151 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001152 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001153 */
William Kucharski906d2782019-10-18 20:20:33 -07001154 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001155 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001156 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001157 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001158 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001159 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001160 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001161 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001162
1163 if (PageSwapCache(page)) {
1164 swp_entry_t swap = { .val = page_private(page) };
Yu Zhao37397872022-09-18 02:00:03 -06001165
1166 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001167 if (reclaimed && !mapping_exiting(mapping))
1168 shadow = workingset_eviction(page, target_memcg);
Yu Zhao37397872022-09-18 02:00:03 -06001169 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001170 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001171 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001172 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001173 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001174 void (*freepage)(struct page *);
1175
1176 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001177 /*
1178 * Remember a shadow entry for reclaimed file cache in
1179 * order to detect refaults, thus thrashing, later on.
1180 *
1181 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001182 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001183 * inode reclaim needs to empty out the radix tree or
1184 * the nodes are lost. Don't plant shadows behind its
1185 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001186 *
1187 * We also don't store shadows for DAX mappings because the
1188 * only page cache pages found in these are zero pages
1189 * covering holes, and because we don't want to mix DAX
1190 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001191 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001192 */
Huang Ying9de4f222020-04-06 20:04:41 -07001193 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001194 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001195 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001196 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001197 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001198
1199 if (freepage != NULL)
1200 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001201 }
1202
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001203 return 1;
1204
1205cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001206 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001207 return 0;
1208}
1209
Linus Torvalds1da177e2005-04-16 15:20:36 -07001210/*
Nick Piggine2867812008-07-25 19:45:30 -07001211 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1212 * someone else has a ref on the page, abort and return 0. If it was
1213 * successfully detached, return 1. Assumes the caller has a single ref on
1214 * this page.
1215 */
1216int remove_mapping(struct address_space *mapping, struct page *page)
1217{
Johannes Weinerb9107182019-11-30 17:55:59 -08001218 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001219 /*
1220 * Unfreezing the refcount with 1 rather than 2 effectively
1221 * drops the pagecache ref for us without requiring another
1222 * atomic operation.
1223 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001224 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001225 return 1;
1226 }
1227 return 0;
1228}
1229
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001230/**
1231 * putback_lru_page - put previously isolated page onto appropriate LRU list
1232 * @page: page to be put back to appropriate lru list
1233 *
1234 * Add previously isolated @page to appropriate LRU list.
1235 * Page may still be unevictable for other reasons.
1236 *
1237 * lru_lock must not be held, interrupts must be enabled.
1238 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001239void putback_lru_page(struct page *page)
1240{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001241 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001242 put_page(page); /* drop ref from isolate */
1243}
1244
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001245enum page_references {
1246 PAGEREF_RECLAIM,
1247 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001248 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001249 PAGEREF_ACTIVATE,
1250};
1251
1252static enum page_references page_check_references(struct page *page,
1253 struct scan_control *sc)
1254{
Johannes Weiner645747462010-03-05 13:42:22 -08001255 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001256 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001257
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001258 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1259 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001260 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001261
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001262 /*
1263 * Mlock lost the isolation race with us. Let try_to_unmap()
1264 * move the page to the unevictable list.
1265 */
1266 if (vm_flags & VM_LOCKED)
1267 return PAGEREF_RECLAIM;
1268
Johannes Weiner645747462010-03-05 13:42:22 -08001269 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001270 /*
1271 * All mapped pages start out with page table
1272 * references from the instantiating fault, so we need
1273 * to look twice if a mapped file page is used more
1274 * than once.
1275 *
1276 * Mark it and spare it for another trip around the
1277 * inactive list. Another page table reference will
1278 * lead to its activation.
1279 *
1280 * Note: the mark is set for activated pages as well
1281 * so that recently deactivated but used pages are
1282 * quickly recovered.
1283 */
1284 SetPageReferenced(page);
1285
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001286 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001287 return PAGEREF_ACTIVATE;
1288
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001289 /*
1290 * Activate file-backed executable pages after first usage.
1291 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001292 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001293 return PAGEREF_ACTIVATE;
1294
Johannes Weiner645747462010-03-05 13:42:22 -08001295 return PAGEREF_KEEP;
1296 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001297
1298 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001299 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001300 return PAGEREF_RECLAIM_CLEAN;
1301
1302 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001303}
1304
Mel Gormane2be15f2013-07-03 15:01:57 -07001305/* Check if a page is dirty or under writeback */
1306static void page_check_dirty_writeback(struct page *page,
1307 bool *dirty, bool *writeback)
1308{
Mel Gormanb4597222013-07-03 15:02:05 -07001309 struct address_space *mapping;
1310
Mel Gormane2be15f2013-07-03 15:01:57 -07001311 /*
1312 * Anonymous pages are not handled by flushers and must be written
1313 * from reclaim context. Do not stall reclaim based on them
1314 */
Huang Ying9de4f222020-04-06 20:04:41 -07001315 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001316 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001317 *dirty = false;
1318 *writeback = false;
1319 return;
1320 }
1321
1322 /* By default assume that the page flags are accurate */
1323 *dirty = PageDirty(page);
1324 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001325
1326 /* Verify dirty/writeback state if the filesystem supports it */
1327 if (!page_has_private(page))
1328 return;
1329
1330 mapping = page_mapping(page);
1331 if (mapping && mapping->a_ops->is_dirty_writeback)
1332 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001333}
1334
Dave Hansen26aa2d12021-09-02 14:59:16 -07001335static struct page *alloc_demote_page(struct page *page, unsigned long node)
1336{
1337 struct migration_target_control mtc = {
1338 /*
1339 * Allocate from 'node', or fail quickly and quietly.
1340 * When this happens, 'page' will likely just be discarded
1341 * instead of migrated.
1342 */
1343 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1344 __GFP_THISNODE | __GFP_NOWARN |
1345 __GFP_NOMEMALLOC | GFP_NOWAIT,
1346 .nid = node
1347 };
1348
1349 return alloc_migration_target(page, (unsigned long)&mtc);
1350}
1351
1352/*
1353 * Take pages on @demote_list and attempt to demote them to
1354 * another node. Pages which are not demoted are left on
1355 * @demote_pages.
1356 */
1357static unsigned int demote_page_list(struct list_head *demote_pages,
1358 struct pglist_data *pgdat)
1359{
1360 int target_nid = next_demotion_node(pgdat->node_id);
1361 unsigned int nr_succeeded;
1362 int err;
1363
1364 if (list_empty(demote_pages))
1365 return 0;
1366
1367 if (target_nid == NUMA_NO_NODE)
1368 return 0;
1369
1370 /* Demotion ignores all cpuset and mempolicy settings */
1371 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1372 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1373 &nr_succeeded);
1374
Yang Shi668e4142021-09-02 14:59:19 -07001375 if (current_is_kswapd())
1376 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1377 else
1378 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1379
Dave Hansen26aa2d12021-09-02 14:59:16 -07001380 return nr_succeeded;
1381}
1382
Nick Piggine2867812008-07-25 19:45:30 -07001383/*
Andrew Morton1742f192006-03-22 00:08:21 -08001384 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001385 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001386static unsigned int shrink_page_list(struct list_head *page_list,
1387 struct pglist_data *pgdat,
1388 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001389 struct reclaim_stat *stat,
1390 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001391{
1392 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001393 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001394 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001395 unsigned int nr_reclaimed = 0;
1396 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001397 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001398
Kirill Tkhai060f0052019-03-05 15:48:15 -08001399 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001400 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001401 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001402
Dave Hansen26aa2d12021-09-02 14:59:16 -07001403retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001404 while (!list_empty(page_list)) {
1405 struct address_space *mapping;
1406 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001407 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001408 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001409 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001410
1411 cond_resched();
1412
1413 page = lru_to_page(page_list);
1414 list_del(&page->lru);
1415
Nick Piggin529ae9a2008-08-02 12:01:03 +02001416 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001417 goto keep;
1418
Sasha Levin309381fea2014-01-23 15:52:54 -08001419 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001420
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001421 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001422
1423 /* Account the number of base pages even though THP */
1424 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001425
Hugh Dickins39b5f292012-10-08 16:33:18 -07001426 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001427 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001428
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001429 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001430 goto keep_locked;
1431
Yu Zhao0182f922022-09-18 02:00:04 -06001432 /* page_update_gen() tried to promote this page? */
1433 if (lru_gen_enabled() && !ignore_references &&
1434 page_mapped(page) && PageReferenced(page))
1435 goto keep_locked;
1436
Andy Whitcroftc661b072007-08-22 14:01:26 -07001437 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1438 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1439
Mel Gorman283aba92013-07-03 15:01:51 -07001440 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001441 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001442 * reclaim_congested which affects wait_iff_congested. kswapd
1443 * will stall and start writing pages if the tail of the LRU
1444 * is all dirty unqueued pages.
1445 */
1446 page_check_dirty_writeback(page, &dirty, &writeback);
1447 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001448 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001449
1450 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001451 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001452
Mel Gormand04e8ac2013-07-03 15:02:03 -07001453 /*
1454 * Treat this page as congested if the underlying BDI is or if
1455 * pages are cycling through the LRU so quickly that the
1456 * pages marked for immediate reclaim are making it to the
1457 * end of the LRU a second time.
1458 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001459 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001460 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001461 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001462 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001463 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001464
1465 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001466 * If a page at the tail of the LRU is under writeback, there
1467 * are three cases to consider.
1468 *
1469 * 1) If reclaim is encountering an excessive number of pages
1470 * under writeback and this page is both under writeback and
1471 * PageReclaim then it indicates that pages are being queued
1472 * for IO but are being recycled through the LRU before the
1473 * IO can complete. Waiting on the page itself risks an
1474 * indefinite stall if it is impossible to writeback the
1475 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001476 * note that the LRU is being scanned too quickly and the
1477 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001478 *
Tejun Heo97c93412015-05-22 18:23:36 -04001479 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001480 * not marked for immediate reclaim, or the caller does not
1481 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1482 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001483 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001484 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001485 * Require may_enter_fs because we would wait on fs, which
1486 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001487 * enter reclaim, and deadlock if it waits on a page for
1488 * which it is needed to do the write (loop masks off
1489 * __GFP_IO|__GFP_FS for this reason); but more thought
1490 * would probably show more reasons.
1491 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001492 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001493 * PageReclaim. memcg does not have any dirty pages
1494 * throttling so we could easily OOM just because too many
1495 * pages are in writeback and there is nothing else to
1496 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001497 *
1498 * In cases 1) and 2) we activate the pages to get them out of
1499 * the way while we continue scanning for clean pages on the
1500 * inactive list and refilling from the active list. The
1501 * observation here is that waiting for disk writes is more
1502 * expensive than potentially causing reloads down the line.
1503 * Since they're marked for immediate reclaim, they won't put
1504 * memory pressure on the cache working set any longer than it
1505 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001506 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001507 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001508 /* Case 1 above */
1509 if (current_is_kswapd() &&
1510 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001511 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001512 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001513 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001514
1515 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001516 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001517 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001518 /*
1519 * This is slightly racy - end_page_writeback()
1520 * might have just cleared PageReclaim, then
1521 * setting PageReclaim here end up interpreted
1522 * as PageReadahead - but that does not matter
1523 * enough to care. What we do want is for this
1524 * page to have PageReclaim set next time memcg
1525 * reclaim reaches the tests above, so it will
1526 * then wait_on_page_writeback() to avoid OOM;
1527 * and it's also appropriate in global reclaim.
1528 */
1529 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001530 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001531 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001532
1533 /* Case 3 above */
1534 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001535 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001536 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001537 /* then go back and try same page again */
1538 list_add_tail(&page->lru, page_list);
1539 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001540 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001541 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001542
Minchan Kim8940b342019-09-25 16:49:11 -07001543 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001544 references = page_check_references(page, sc);
1545
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001546 switch (references) {
1547 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001548 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001549 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001550 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001551 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001552 case PAGEREF_RECLAIM:
1553 case PAGEREF_RECLAIM_CLEAN:
1554 ; /* try to reclaim the page below */
1555 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001556
Linus Torvalds1da177e2005-04-16 15:20:36 -07001557 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001558 * Before reclaiming the page, try to relocate
1559 * its contents to another node.
1560 */
1561 if (do_demote_pass &&
1562 (thp_migration_supported() || !PageTransHuge(page))) {
1563 list_add(&page->lru, &demote_pages);
1564 unlock_page(page);
1565 continue;
1566 }
1567
1568 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001569 * Anonymous process memory has backing store?
1570 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001571 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001572 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001573 if (PageAnon(page) && PageSwapBacked(page)) {
1574 if (!PageSwapCache(page)) {
1575 if (!(sc->gfp_mask & __GFP_IO))
1576 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001577 if (page_maybe_dma_pinned(page))
1578 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001579 if (PageTransHuge(page)) {
1580 /* cannot split THP, skip it */
1581 if (!can_split_huge_page(page, NULL))
1582 goto activate_locked;
1583 /*
1584 * Split pages without a PMD map right
1585 * away. Chances are some or all of the
1586 * tail pages can be freed without IO.
1587 */
1588 if (!compound_mapcount(page) &&
1589 split_huge_page_to_list(page,
1590 page_list))
1591 goto activate_locked;
1592 }
1593 if (!add_to_swap(page)) {
1594 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001595 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001596 /* Fallback to swap normal pages */
1597 if (split_huge_page_to_list(page,
1598 page_list))
1599 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001600#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1601 count_vm_event(THP_SWPOUT_FALLBACK);
1602#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001603 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001604 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001605 }
Minchan Kim0f074652017-07-06 15:37:24 -07001606
Kirill Tkhai4b793062020-04-01 21:10:18 -07001607 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001608
1609 /* Adding to swap updated mapping */
1610 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001611 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001612 } else if (unlikely(PageTransHuge(page))) {
1613 /* Split file THP */
1614 if (split_huge_page_to_list(page, page_list))
1615 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001616 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001617
1618 /*
Yang Shi98879b32019-07-11 20:59:30 -07001619 * THP may get split above, need minus tail pages and update
1620 * nr_pages to avoid accounting tail pages twice.
1621 *
1622 * The tail pages that are added into swap cache successfully
1623 * reach here.
1624 */
1625 if ((nr_pages > 1) && !PageTransHuge(page)) {
1626 sc->nr_scanned -= (nr_pages - 1);
1627 nr_pages = 1;
1628 }
1629
1630 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001631 * The page is mapped into the page tables of one or more
1632 * processes. Try to unmap it here.
1633 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001634 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001635 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001636 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001637
1638 if (unlikely(PageTransHuge(page)))
1639 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001640
Yang Shi1fb08ac2021-06-30 18:52:01 -07001641 try_to_unmap(page, flags);
1642 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001643 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001644 if (!was_swapbacked && PageSwapBacked(page))
1645 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001646 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001647 }
1648 }
1649
1650 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001651 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001652 * Only kswapd can writeback filesystem pages
1653 * to avoid risk of stack overflow. But avoid
1654 * injecting inefficient single-page IO into
1655 * flusher writeback as much as possible: only
1656 * write pages when we've encountered many
1657 * dirty pages, and when we've already scanned
1658 * the rest of the LRU for clean pages and see
1659 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001660 */
Huang Ying9de4f222020-04-06 20:04:41 -07001661 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001662 (!current_is_kswapd() || !PageReclaim(page) ||
1663 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001664 /*
1665 * Immediately reclaim when written back.
1666 * Similar in principal to deactivate_page()
1667 * except we already have the page isolated
1668 * and know it's dirty
1669 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001670 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001671 SetPageReclaim(page);
1672
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001673 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001674 }
1675
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001676 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001677 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001678 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001679 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001680 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001681 goto keep_locked;
1682
Mel Gormand950c942015-09-04 15:47:35 -07001683 /*
1684 * Page is dirty. Flush the TLB if a writable entry
1685 * potentially exists to avoid CPU writes after IO
1686 * starts and then write it out here.
1687 */
1688 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001689 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001690 case PAGE_KEEP:
1691 goto keep_locked;
1692 case PAGE_ACTIVATE:
1693 goto activate_locked;
1694 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001695 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001696
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001697 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001698 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001699 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001700 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001701
Linus Torvalds1da177e2005-04-16 15:20:36 -07001702 /*
1703 * A synchronous write - probably a ramdisk. Go
1704 * ahead and try to reclaim the page.
1705 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001706 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001707 goto keep;
1708 if (PageDirty(page) || PageWriteback(page))
1709 goto keep_locked;
1710 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001711 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001712 case PAGE_CLEAN:
1713 ; /* try to free the page below */
1714 }
1715 }
1716
1717 /*
1718 * If the page has buffers, try to free the buffer mappings
1719 * associated with this page. If we succeed we try to free
1720 * the page as well.
1721 *
1722 * We do this even if the page is PageDirty().
1723 * try_to_release_page() does not perform I/O, but it is
1724 * possible for a page to have PageDirty set, but it is actually
1725 * clean (all its buffers are clean). This happens if the
1726 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001727 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001728 * try_to_release_page() will discover that cleanness and will
1729 * drop the buffers and mark the page clean - it can be freed.
1730 *
1731 * Rarely, pages can have buffers and no ->mapping. These are
1732 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001733 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001734 * and if that worked, and the page is no longer mapped into
1735 * process address space (page_count == 1) it can be freed.
1736 * Otherwise, leave the page on the LRU so it is swappable.
1737 */
David Howells266cf652009-04-03 16:42:36 +01001738 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001739 if (!try_to_release_page(page, sc->gfp_mask))
1740 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001741 if (!mapping && page_count(page) == 1) {
1742 unlock_page(page);
1743 if (put_page_testzero(page))
1744 goto free_it;
1745 else {
1746 /*
1747 * rare race with speculative reference.
1748 * the speculative reference will free
1749 * this page shortly, so we may
1750 * increment nr_reclaimed here (and
1751 * leave it off the LRU).
1752 */
1753 nr_reclaimed++;
1754 continue;
1755 }
1756 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001757 }
1758
Shaohua Li802a3a92017-05-03 14:52:32 -07001759 if (PageAnon(page) && !PageSwapBacked(page)) {
1760 /* follow __remove_mapping for reference */
1761 if (!page_ref_freeze(page, 1))
1762 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001763 /*
1764 * The page has only one reference left, which is
1765 * from the isolation. After the caller puts the
1766 * page back on lru and drops the reference, the
1767 * page will be freed anyway. It doesn't matter
1768 * which lru it goes. So we don't bother checking
1769 * PageDirty here.
1770 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001771 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001772 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001773 } else if (!mapping || !__remove_mapping(mapping, page, true,
1774 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001775 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001776
1777 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001778free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001779 /*
1780 * THP may get swapped out in a whole, need account
1781 * all base pages.
1782 */
1783 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001784
1785 /*
1786 * Is there need to periodically free_page_list? It would
1787 * appear not as the counts should be low
1788 */
Yang Shi7ae88532019-09-23 15:38:09 -07001789 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001790 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001791 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001792 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001793 continue;
1794
Yang Shi98879b32019-07-11 20:59:30 -07001795activate_locked_split:
1796 /*
1797 * The tail pages that are failed to add into swap cache
1798 * reach here. Fixup nr_scanned and nr_pages.
1799 */
1800 if (nr_pages > 1) {
1801 sc->nr_scanned -= (nr_pages - 1);
1802 nr_pages = 1;
1803 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001804activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001805 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001806 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1807 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001808 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001809 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001810 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001811 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001812 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001813 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001814 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001815 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001816keep_locked:
1817 unlock_page(page);
1818keep:
1819 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001820 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001821 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001822 /* 'page_list' is always empty here */
1823
1824 /* Migrate pages selected for demotion */
1825 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1826 /* Pages that could not be demoted are still in @demote_pages */
1827 if (!list_empty(&demote_pages)) {
1828 /* Pages which failed to demoted go back on @page_list for retry: */
1829 list_splice_init(&demote_pages, page_list);
1830 do_demote_pass = false;
1831 goto retry;
1832 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001833
Yang Shi98879b32019-07-11 20:59:30 -07001834 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1835
Johannes Weiner747db952014-08-08 14:19:24 -07001836 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001837 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001838 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001839
Linus Torvalds1da177e2005-04-16 15:20:36 -07001840 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001841 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001842
Andrew Morton05ff5132006-03-22 00:08:20 -08001843 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001844}
1845
Maninder Singh730ec8c2020-06-03 16:01:18 -07001846unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001847 struct list_head *page_list)
1848{
1849 struct scan_control sc = {
1850 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001851 .may_unmap = 1,
1852 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001853 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001854 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001855 struct page *page, *next;
1856 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001857 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001858
1859 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001860 if (!PageHuge(page) && page_is_file_lru(page) &&
1861 !PageDirty(page) && !__PageMovable(page) &&
1862 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001863 ClearPageActive(page);
1864 list_move(&page->lru, &clean_pages);
1865 }
1866 }
1867
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001868 /*
1869 * We should be safe here since we are only dealing with file pages and
1870 * we are not kswapd and therefore cannot write dirty file pages. But
1871 * call memalloc_noreclaim_save() anyway, just in case these conditions
1872 * change in the future.
1873 */
1874 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001875 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001876 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001877 memalloc_noreclaim_restore(noreclaim_flag);
1878
Minchan Kim02c6de82012-10-08 16:31:55 -07001879 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001880 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1881 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001882 /*
1883 * Since lazyfree pages are isolated from file LRU from the beginning,
1884 * they will rotate back to anonymous LRU in the end if it failed to
1885 * discard so isolated count will be mismatched.
1886 * Compensate the isolated count for both LRU lists.
1887 */
1888 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1889 stat.nr_lazyfree_fail);
1890 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001891 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001892 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001893}
1894
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001895/*
1896 * Attempt to remove the specified page from its LRU. Only take this page
1897 * if it is of the appropriate PageActive status. Pages which are being
1898 * freed elsewhere are also ignored.
1899 *
1900 * page: page to consider
1901 * mode: one of the LRU isolation modes defined above
1902 *
Alex Shic2135f72021-02-24 12:08:01 -08001903 * returns true on success, false on failure.
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001904 */
Alex Shic2135f72021-02-24 12:08:01 -08001905bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001906{
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001907 /* Only take pages on the LRU. */
1908 if (!PageLRU(page))
Alex Shic2135f72021-02-24 12:08:01 -08001909 return false;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001910
Minchan Kime46a2872012-10-08 16:33:48 -07001911 /* Compaction should not handle unevictable pages but CMA can do so */
1912 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
Alex Shic2135f72021-02-24 12:08:01 -08001913 return false;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001914
Mel Gormanc8244932012-01-12 17:19:38 -08001915 /*
1916 * To minimise LRU disruption, the caller can indicate that it only
1917 * wants to isolate pages it will be able to operate on without
1918 * blocking - clean pages for the most part.
1919 *
Mel Gormanc8244932012-01-12 17:19:38 -08001920 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1921 * that it is possible to migrate without blocking
1922 */
Johannes Weiner1276ad62017-02-24 14:56:11 -08001923 if (mode & ISOLATE_ASYNC_MIGRATE) {
Mel Gormanc8244932012-01-12 17:19:38 -08001924 /* All the caller can do on PageWriteback is block */
1925 if (PageWriteback(page))
Alex Shic2135f72021-02-24 12:08:01 -08001926 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001927
1928 if (PageDirty(page)) {
1929 struct address_space *mapping;
Mel Gorman69d763f2018-01-31 16:19:52 -08001930 bool migrate_dirty;
Mel Gormanc8244932012-01-12 17:19:38 -08001931
Mel Gormanc8244932012-01-12 17:19:38 -08001932 /*
1933 * Only pages without mappings or that have a
1934 * ->migratepage callback are possible to migrate
Mel Gorman69d763f2018-01-31 16:19:52 -08001935 * without blocking. However, we can be racing with
1936 * truncation so it's necessary to lock the page
1937 * to stabilise the mapping as truncation holds
1938 * the page lock until after the page is removed
1939 * from the page cache.
Mel Gormanc8244932012-01-12 17:19:38 -08001940 */
Mel Gorman69d763f2018-01-31 16:19:52 -08001941 if (!trylock_page(page))
Alex Shic2135f72021-02-24 12:08:01 -08001942 return false;
Mel Gorman69d763f2018-01-31 16:19:52 -08001943
Mel Gormanc8244932012-01-12 17:19:38 -08001944 mapping = page_mapping(page);
Hugh Dickins145e1a72018-06-01 16:50:50 -07001945 migrate_dirty = !mapping || mapping->a_ops->migratepage;
Mel Gorman69d763f2018-01-31 16:19:52 -08001946 unlock_page(page);
1947 if (!migrate_dirty)
Alex Shic2135f72021-02-24 12:08:01 -08001948 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001949 }
1950 }
Minchan Kim39deaf82011-10-31 17:06:51 -07001951
Minchan Kimf80c0672011-10-31 17:06:55 -07001952 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
Alex Shic2135f72021-02-24 12:08:01 -08001953 return false;
Minchan Kimf80c0672011-10-31 17:06:55 -07001954
Alex Shic2135f72021-02-24 12:08:01 -08001955 return true;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001956}
1957
Mel Gorman7ee36a12016-07-28 15:47:17 -07001958/*
1959 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001960 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001961 */
1962static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001963 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001964{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001965 int zid;
1966
Mel Gorman7ee36a12016-07-28 15:47:17 -07001967 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1968 if (!nr_zone_taken[zid])
1969 continue;
1970
Wei Yanga892cb62020-06-03 16:01:12 -07001971 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001972 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001973
Mel Gorman7ee36a12016-07-28 15:47:17 -07001974}
1975
Mel Gormanf611fab2021-06-30 18:53:19 -07001976/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001977 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1978 *
1979 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001980 * shrink the lists perform better by taking out a batch of pages
1981 * and working on them outside the LRU lock.
1982 *
1983 * For pagecache intensive workloads, this function is the hottest
1984 * spot in the kernel (apart from copy_*_user functions).
1985 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001986 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001987 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001988 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001989 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001990 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001991 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001992 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001993 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001994 *
1995 * returns how many pages were moved onto *@dst.
1996 */
Andrew Morton69e05942006-03-22 00:08:19 -08001997static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001998 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001999 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002000 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002001{
Hugh Dickins75b00af2012-05-29 15:07:09 -07002002 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08002003 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07002004 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002005 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07002006 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002007 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002008 LIST_HEAD(pages_skipped);
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002009 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002010
Yang Shi98879b32019-07-11 20:59:30 -07002011 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002012 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07002013 while (scan < nr_to_scan && !list_empty(src)) {
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002014 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002015
Linus Torvalds1da177e2005-04-16 15:20:36 -07002016 page = lru_to_page(src);
2017 prefetchw_prev_lru_page(page, src, flags);
2018
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002019 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002020 total_scan += nr_pages;
2021
Mel Gormanb2e18752016-07-28 15:45:37 -07002022 if (page_zonenum(page) > sc->reclaim_idx) {
2023 list_move(&page->lru, &pages_skipped);
Yang Shi98879b32019-07-11 20:59:30 -07002024 nr_skipped[page_zonenum(page)] += nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002025 continue;
2026 }
2027
Minchan Kim791b48b2017-05-12 15:47:06 -07002028 /*
2029 * Do not count skipped pages because that makes the function
2030 * return with no isolated pages if the LRU mostly contains
2031 * ineligible pages. This causes the VM to not reclaim any
2032 * pages, triggering a premature OOM.
Yang Shi98879b32019-07-11 20:59:30 -07002033 *
2034 * Account all tail pages of THP. This would not cause
2035 * premature OOM since __isolate_lru_page() returns -EBUSY
2036 * only when the page is being freed somewhere else.
Minchan Kim791b48b2017-05-12 15:47:06 -07002037 */
Yang Shi98879b32019-07-11 20:59:30 -07002038 scan += nr_pages;
Alex Shic2135f72021-02-24 12:08:01 -08002039 if (!__isolate_lru_page_prepare(page, mode)) {
2040 /* It is being freed elsewhere */
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002041 list_move(&page->lru, src);
Alex Shic2135f72021-02-24 12:08:01 -08002042 continue;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002043 }
Alex Shic2135f72021-02-24 12:08:01 -08002044 /*
2045 * Be careful not to clear PageLRU until after we're
2046 * sure the page is not being freed elsewhere -- the
2047 * page release code relies on it.
2048 */
2049 if (unlikely(!get_page_unless_zero(page))) {
2050 list_move(&page->lru, src);
2051 continue;
2052 }
2053
2054 if (!TestClearPageLRU(page)) {
2055 /* Another thread is already isolating this page */
2056 put_page(page);
2057 list_move(&page->lru, src);
2058 continue;
2059 }
2060
2061 nr_taken += nr_pages;
2062 nr_zone_taken[page_zonenum(page)] += nr_pages;
2063 list_move(&page->lru, dst);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002064 }
2065
Mel Gormanb2e18752016-07-28 15:45:37 -07002066 /*
2067 * Splice any skipped pages to the start of the LRU list. Note that
2068 * this disrupts the LRU order when reclaiming for lower zones but
2069 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2070 * scanning would soon rescan the same pages to skip and put the
2071 * system at risk of premature OOM.
2072 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002073 if (!list_empty(&pages_skipped)) {
2074 int zid;
2075
Johannes Weiner3db65812017-05-03 14:52:13 -07002076 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002077 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2078 if (!nr_skipped[zid])
2079 continue;
2080
2081 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002082 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002083 }
2084 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002085 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002086 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Minchan Kim791b48b2017-05-12 15:47:06 -07002087 total_scan, skipped, nr_taken, mode, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002088 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002089 return nr_taken;
2090}
2091
Nick Piggin62695a82008-10-18 20:26:09 -07002092/**
2093 * isolate_lru_page - tries to isolate a page from its LRU list
2094 * @page: page to isolate from its LRU list
2095 *
2096 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2097 * vmstat statistic corresponding to whatever LRU list the page was on.
2098 *
2099 * Returns 0 if the page was removed from an LRU list.
2100 * Returns -EBUSY if the page was not on an LRU list.
2101 *
2102 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002103 * the active list, it will have PageActive set. If it was found on
2104 * the unevictable list, it will have the PageUnevictable bit set. That flag
2105 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002106 *
2107 * The vmstat statistic corresponding to the list on which the page was
2108 * found will be decremented.
2109 *
2110 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002111 *
Nick Piggin62695a82008-10-18 20:26:09 -07002112 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002113 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002114 * without a stable reference).
2115 * (2) the lru_lock must not be held.
2116 * (3) interrupts must be enabled.
2117 */
2118int isolate_lru_page(struct page *page)
2119{
2120 int ret = -EBUSY;
2121
Sasha Levin309381fea2014-01-23 15:52:54 -08002122 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002123 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002124
Alex Shid25b5bd2020-12-15 12:34:16 -08002125 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002126 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002127
Alex Shid25b5bd2020-12-15 12:34:16 -08002128 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002129 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002130 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002131 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002132 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002133 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002134
Nick Piggin62695a82008-10-18 20:26:09 -07002135 return ret;
2136}
2137
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002138/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002139 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002140 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002141 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2142 * the LRU list will go small and be scanned faster than necessary, leading to
2143 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002144 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002145static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002146 struct scan_control *sc)
2147{
2148 unsigned long inactive, isolated;
2149
2150 if (current_is_kswapd())
2151 return 0;
2152
Johannes Weinerb5ead352019-11-30 17:55:40 -08002153 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002154 return 0;
2155
2156 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002157 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2158 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002159 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002160 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2161 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002162 }
2163
Fengguang Wu3cf23842012-12-18 14:23:31 -08002164 /*
2165 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2166 * won't get blocked by normal direct-reclaimers, forming a circular
2167 * deadlock.
2168 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002169 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002170 inactive >>= 3;
2171
Rik van Riel35cd7812009-09-21 17:01:38 -07002172 return isolated > inactive;
2173}
2174
Kirill Tkhaia222f342019-05-13 17:17:00 -07002175/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002176 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2177 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002178 *
2179 * Returns the number of pages moved to the given lruvec.
2180 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002181static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2182 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002183{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002184 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002185 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002186 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002187
Kirill Tkhaia222f342019-05-13 17:17:00 -07002188 while (!list_empty(list)) {
2189 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002190 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002191 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002192 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002193 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002194 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002195 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002196 continue;
2197 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002198
Alex Shi3d06afa2020-12-15 12:33:37 -08002199 /*
2200 * The SetPageLRU needs to be kept here for list integrity.
2201 * Otherwise:
2202 * #0 move_pages_to_lru #1 release_pages
2203 * if !put_page_testzero
2204 * if (put_page_testzero())
2205 * !PageLRU //skip lru_lock
2206 * SetPageLRU()
2207 * list_add(&page->lru,)
2208 * list_add(&page->lru,)
2209 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002210 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002211
Alex Shi3d06afa2020-12-15 12:33:37 -08002212 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002213 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002214
2215 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002216 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002217 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002218 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002219 } else
2220 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002221
2222 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002223 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002224
Alex Shiafca9152020-12-15 12:34:02 -08002225 /*
2226 * All pages were isolated from the same lruvec (and isolation
2227 * inhibits memcg migration).
2228 */
Muchun Song7467c392021-06-28 19:37:59 -07002229 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002230 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002231 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002232 nr_moved += nr_pages;
2233 if (PageActive(page))
2234 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002235 }
Mel Gorman66635622010-08-09 17:19:30 -07002236
Hugh Dickins3f797682012-01-12 17:20:07 -08002237 /*
2238 * To save our caller's stack, now use input list for pages to free.
2239 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002240 list_splice(&pages_to_free, list);
2241
2242 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002243}
2244
2245/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002246 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002247 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002248 * In that case we should only throttle if the backing device it is
2249 * writing to is congested. In other cases it is safe to throttle.
2250 */
2251static int current_may_throttle(void)
2252{
NeilBrowna37b0712020-06-01 21:48:18 -07002253 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002254 current->backing_dev_info == NULL ||
2255 bdi_write_congested(current->backing_dev_info);
2256}
2257
2258/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002259 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002260 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002261 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002262static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002263shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002264 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002265{
2266 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002267 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002268 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002269 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002270 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002271 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002272 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002273 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002274 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002275
Mel Gorman599d0c92016-07-28 15:45:31 -07002276 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002277 if (stalled)
2278 return 0;
2279
2280 /* wait a bit for the reclaimer. */
2281 msleep(100);
2282 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002283
2284 /* We are about to die and free our memory. Return now. */
2285 if (fatal_signal_pending(current))
2286 return SWAP_CLUSTER_MAX;
2287 }
2288
Linus Torvalds1da177e2005-04-16 15:20:36 -07002289 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002290
Alex Shi6168d0d2020-12-15 12:34:29 -08002291 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002292
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002293 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002294 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002295
Mel Gorman599d0c92016-07-28 15:45:31 -07002296 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002297 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002298 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002299 __count_vm_events(item, nr_scanned);
2300 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002301 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2302
Alex Shi6168d0d2020-12-15 12:34:29 -08002303 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002304
Hillf Dantond563c052012-03-21 16:34:02 -07002305 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002306 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002307
Shakeel Butt013339d2020-12-14 19:06:39 -08002308 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002309
Alex Shi6168d0d2020-12-15 12:34:29 -08002310 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002311 move_pages_to_lru(lruvec, &page_list);
2312
2313 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002314 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002315 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002316 __count_vm_events(item, nr_reclaimed);
2317 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002318 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002319 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002320
Alex Shi75cc3c92020-12-15 14:20:50 -08002321 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002322 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002323 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002324
Mel Gorman92df3a72011-10-31 17:07:56 -07002325 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002326 * If dirty pages are scanned that are not queued for IO, it
2327 * implies that flushers are not doing their job. This can
2328 * happen when memory pressure pushes dirty pages to the end of
2329 * the LRU before the dirty limits are breached and the dirty
2330 * data has expired. It can also happen when the proportion of
2331 * dirty pages grows not through writes but through memory
2332 * pressure reclaiming all the clean cache. And in some cases,
2333 * the flushers simply cannot keep up with the allocation
2334 * rate. Nudge the flusher threads in case they are asleep.
2335 */
2336 if (stat.nr_unqueued_dirty == nr_taken)
2337 wakeup_flusher_threads(WB_REASON_VMSCAN);
2338
Andrey Ryabinind108c772018-04-10 16:27:59 -07002339 sc->nr.dirty += stat.nr_dirty;
2340 sc->nr.congested += stat.nr_congested;
2341 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2342 sc->nr.writeback += stat.nr_writeback;
2343 sc->nr.immediate += stat.nr_immediate;
2344 sc->nr.taken += nr_taken;
2345 if (file)
2346 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002347
Mel Gorman599d0c92016-07-28 15:45:31 -07002348 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002349 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002350 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002351}
2352
Hugh Dickins15b44732020-12-15 14:21:31 -08002353/*
2354 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2355 *
2356 * We move them the other way if the page is referenced by one or more
2357 * processes.
2358 *
2359 * If the pages are mostly unmapped, the processing is fast and it is
2360 * appropriate to hold lru_lock across the whole operation. But if
2361 * the pages are mapped, the processing is slow (page_referenced()), so
2362 * we should drop lru_lock around each page. It's impossible to balance
2363 * this, so instead we remove the pages from the LRU while processing them.
2364 * It is safe to rely on PG_active against the non-LRU pages in here because
2365 * nobody will play with that bit on a non-LRU page.
2366 *
2367 * The downside is that we have to touch page->_refcount against each page.
2368 * But we had to alter page->flags anyway.
2369 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002370static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002371 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002372 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002373 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002374{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002375 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002376 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002377 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002378 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002379 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002380 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002381 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002382 unsigned nr_deactivate, nr_activate;
2383 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002384 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002385 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002386 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002387
2388 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002389
Alex Shi6168d0d2020-12-15 12:34:29 -08002390 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002391
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002392 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002393 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002394
Mel Gorman599d0c92016-07-28 15:45:31 -07002395 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002396
Shakeel Butt912c0572020-08-06 23:26:32 -07002397 if (!cgroup_reclaim(sc))
2398 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002399 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002400
Alex Shi6168d0d2020-12-15 12:34:29 -08002401 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002402
Linus Torvalds1da177e2005-04-16 15:20:36 -07002403 while (!list_empty(&l_hold)) {
2404 cond_resched();
2405 page = lru_to_page(&l_hold);
2406 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002407
Hugh Dickins39b5f292012-10-08 16:33:18 -07002408 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002409 putback_lru_page(page);
2410 continue;
2411 }
2412
Mel Gormancc715d92012-03-21 16:34:00 -07002413 if (unlikely(buffer_heads_over_limit)) {
2414 if (page_has_private(page) && trylock_page(page)) {
2415 if (page_has_private(page))
2416 try_to_release_page(page, 0);
2417 unlock_page(page);
2418 }
2419 }
2420
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002421 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2422 if (bypass)
2423 goto skip_page_referenced;
2424
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002425 if (page_referenced(page, 0, sc->target_mem_cgroup,
2426 &vm_flags)) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002427 /*
2428 * Identify referenced, file-backed active pages and
2429 * give them one more trip around the active list. So
2430 * that executable code get better chances to stay in
2431 * memory under moderate memory pressure. Anon pages
2432 * are not likely to be evicted by use-once streaming
2433 * IO, plus JVM can create lots of anon VM_EXEC pages,
2434 * so we ignore them here.
2435 */
Huang Ying9de4f222020-04-06 20:04:41 -07002436 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002437 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002438 list_add(&page->lru, &l_active);
2439 continue;
2440 }
2441 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002442skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002443 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002444 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002445 list_add(&page->lru, &l_inactive);
2446 }
2447
Andrew Mortonb5557492009-01-06 14:40:13 -08002448 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002449 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002450 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002451 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002452
Kirill Tkhaia222f342019-05-13 17:17:00 -07002453 nr_activate = move_pages_to_lru(lruvec, &l_active);
2454 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002455 /* Keep all free pages in l_active list */
2456 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002457
2458 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2459 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2460
Mel Gorman599d0c92016-07-28 15:45:31 -07002461 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002462 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002463
Kirill Tkhaif372d892019-05-13 17:16:57 -07002464 mem_cgroup_uncharge_list(&l_active);
2465 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002466 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2467 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002468}
2469
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002470unsigned long reclaim_pages(struct list_head *page_list)
2471{
Yang Shif661d002020-04-01 21:10:05 -07002472 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002473 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002474 LIST_HEAD(node_page_list);
2475 struct reclaim_stat dummy_stat;
2476 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002477 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002478 struct scan_control sc = {
2479 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002480 .may_writepage = 1,
2481 .may_unmap = 1,
2482 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002483 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002484 };
2485
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002486 noreclaim_flag = memalloc_noreclaim_save();
2487
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002488 while (!list_empty(page_list)) {
2489 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002490 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002491 nid = page_to_nid(page);
2492 INIT_LIST_HEAD(&node_page_list);
2493 }
2494
2495 if (nid == page_to_nid(page)) {
2496 ClearPageActive(page);
2497 list_move(&page->lru, &node_page_list);
2498 continue;
2499 }
2500
2501 nr_reclaimed += shrink_page_list(&node_page_list,
2502 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002503 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002504 while (!list_empty(&node_page_list)) {
2505 page = lru_to_page(&node_page_list);
2506 list_del(&page->lru);
2507 putback_lru_page(page);
2508 }
2509
Yang Shif661d002020-04-01 21:10:05 -07002510 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002511 }
2512
2513 if (!list_empty(&node_page_list)) {
2514 nr_reclaimed += shrink_page_list(&node_page_list,
2515 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002516 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002517 while (!list_empty(&node_page_list)) {
2518 page = lru_to_page(&node_page_list);
2519 list_del(&page->lru);
2520 putback_lru_page(page);
2521 }
2522 }
2523
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002524 memalloc_noreclaim_restore(noreclaim_flag);
2525
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002526 return nr_reclaimed;
2527}
2528
Johannes Weinerb91ac372019-11-30 17:56:02 -08002529static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2530 struct lruvec *lruvec, struct scan_control *sc)
2531{
2532 if (is_active_lru(lru)) {
2533 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2534 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2535 else
2536 sc->skipped_deactivate = 1;
2537 return 0;
2538 }
2539
2540 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2541}
2542
Rik van Riel59dc76b2016-05-20 16:56:31 -07002543/*
2544 * The inactive anon list should be small enough that the VM never has
2545 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002546 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002547 * The inactive file list should be small enough to leave most memory
2548 * to the established workingset on the scan-resistant active list,
2549 * but large enough to avoid thrashing the aggregate readahead window.
2550 *
2551 * Both inactive lists should also be large enough that each inactive
2552 * page has a chance to be referenced again before it is reclaimed.
2553 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002554 * If that fails and refaulting is observed, the inactive list grows.
2555 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002556 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002557 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002558 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2559 *
2560 * total target max
2561 * memory ratio inactive
2562 * -------------------------------------
2563 * 10MB 1 5MB
2564 * 100MB 1 50MB
2565 * 1GB 3 250MB
2566 * 10GB 10 0.9GB
2567 * 100GB 31 3GB
2568 * 1TB 101 10GB
2569 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002570 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002571static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002572{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002573 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002574 unsigned long inactive, active;
2575 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002576 unsigned long gb;
2577
Johannes Weinerb91ac372019-11-30 17:56:02 -08002578 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2579 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002580
Johannes Weinerb91ac372019-11-30 17:56:02 -08002581 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002582 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002583 inactive_ratio = int_sqrt(10 * gb);
2584 else
2585 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002586
Rik van Riel59dc76b2016-05-20 16:56:31 -07002587 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002588}
2589
Johannes Weiner9a265112013-02-22 16:32:17 -08002590enum scan_balance {
2591 SCAN_EQUAL,
2592 SCAN_FRACT,
2593 SCAN_ANON,
2594 SCAN_FILE,
2595};
2596
Yu Zhao6d313442022-09-18 02:00:00 -06002597static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2598{
2599 unsigned long file;
2600 struct lruvec *target_lruvec;
2601
Yu Zhao37397872022-09-18 02:00:03 -06002602 if (lru_gen_enabled())
2603 return;
2604
Yu Zhao6d313442022-09-18 02:00:00 -06002605 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2606
2607 /*
2608 * Flush the memory cgroup stats, so that we read accurate per-memcg
2609 * lruvec stats for heuristics.
2610 */
2611 mem_cgroup_flush_stats();
2612
2613 /*
2614 * Determine the scan balance between anon and file LRUs.
2615 */
2616 spin_lock_irq(&target_lruvec->lru_lock);
2617 sc->anon_cost = target_lruvec->anon_cost;
2618 sc->file_cost = target_lruvec->file_cost;
2619 spin_unlock_irq(&target_lruvec->lru_lock);
2620
2621 /*
2622 * Target desirable inactive:active list ratios for the anon
2623 * and file LRU lists.
2624 */
2625 if (!sc->force_deactivate) {
2626 unsigned long refaults;
2627
2628 refaults = lruvec_page_state(target_lruvec,
2629 WORKINGSET_ACTIVATE_ANON);
2630 if (refaults != target_lruvec->refaults[0] ||
2631 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2632 sc->may_deactivate |= DEACTIVATE_ANON;
2633 else
2634 sc->may_deactivate &= ~DEACTIVATE_ANON;
2635
2636 /*
2637 * When refaults are being observed, it means a new
2638 * workingset is being established. Deactivate to get
2639 * rid of any stale active pages quickly.
2640 */
2641 refaults = lruvec_page_state(target_lruvec,
2642 WORKINGSET_ACTIVATE_FILE);
2643 if (refaults != target_lruvec->refaults[1] ||
2644 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2645 sc->may_deactivate |= DEACTIVATE_FILE;
2646 else
2647 sc->may_deactivate &= ~DEACTIVATE_FILE;
2648 } else
2649 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2650
2651 /*
2652 * If we have plenty of inactive file pages that aren't
2653 * thrashing, try to reclaim those first before touching
2654 * anonymous pages.
2655 */
2656 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2657 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2658 sc->cache_trim_mode = 1;
2659 else
2660 sc->cache_trim_mode = 0;
2661
2662 /*
2663 * Prevent the reclaimer from falling into the cache trap: as
2664 * cache pages start out inactive, every cache fault will tip
2665 * the scan balance towards the file LRU. And as the file LRU
2666 * shrinks, so does the window for rotation from references.
2667 * This means we have a runaway feedback loop where a tiny
2668 * thrashing file LRU becomes infinitely more attractive than
2669 * anon pages. Try to detect this based on file LRU size.
2670 */
2671 if (!cgroup_reclaim(sc)) {
2672 unsigned long total_high_wmark = 0;
2673 unsigned long free, anon;
2674 int z;
2675
2676 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2677 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2678 node_page_state(pgdat, NR_INACTIVE_FILE);
2679
2680 for (z = 0; z < MAX_NR_ZONES; z++) {
2681 struct zone *zone = &pgdat->node_zones[z];
2682
2683 if (!managed_zone(zone))
2684 continue;
2685
2686 total_high_wmark += high_wmark_pages(zone);
2687 }
2688
2689 /*
2690 * Consider anon: if that's low too, this isn't a
2691 * runaway file reclaim problem, but rather just
2692 * extreme pressure. Reclaim as per usual then.
2693 */
2694 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2695
2696 sc->file_is_tiny =
2697 file + free <= total_high_wmark &&
2698 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2699 anon >> sc->priority;
2700 }
2701}
2702
Linus Torvalds1da177e2005-04-16 15:20:36 -07002703/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002704 * Determine how aggressively the anon and file LRU lists should be
2705 * scanned. The relative value of each set of LRU lists is determined
2706 * by looking at the fraction of the pages scanned we did rotate back
2707 * onto the active list instead of evict.
2708 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002709 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2710 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002711 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002712static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2713 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002714{
Keith Buscha2a36482021-09-02 14:59:26 -07002715 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002716 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002717 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002718 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002719 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002720 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002721 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002722 unsigned long ap, fp;
2723 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002724 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002725
2726 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002727 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002728 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002729 goto out;
2730 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002731
Johannes Weiner10316b32013-02-22 16:32:14 -08002732 /*
2733 * Global reclaim will swap to prevent OOM even with no
2734 * swappiness, but memcg users want to use this knob to
2735 * disable swapping for individual groups completely when
2736 * using the memory controller's swap limit feature would be
2737 * too expensive.
2738 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002739 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002740 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002741 goto out;
2742 }
2743
2744 /*
2745 * Do not apply any pressure balancing cleverness when the
2746 * system is close to OOM, scan both anon and file equally
2747 * (unless the swappiness setting disagrees with swapping).
2748 */
Johannes Weiner02695172014-08-06 16:06:17 -07002749 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002750 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002751 goto out;
2752 }
2753
Johannes Weiner11d16c22013-02-22 16:32:15 -08002754 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002755 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002756 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002757 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002758 scan_balance = SCAN_ANON;
2759 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002760 }
2761
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002762 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2763
Johannes Weiner62376252014-05-06 12:50:07 -07002764 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002765 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002766 * anything from the anonymous working right now. But when balancing
2767 * anon and page cache files for reclaim, allow swapping of anon pages
2768 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002769 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002770 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002771 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002772 goto out;
2773 }
2774
Johannes Weiner9a265112013-02-22 16:32:17 -08002775 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002776 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002777 * Calculate the pressure balance between anon and file pages.
2778 *
2779 * The amount of pressure we put on each LRU is inversely
2780 * proportional to the cost of reclaiming each list, as
2781 * determined by the share of pages that are refaulting, times
2782 * the relative IO cost of bringing back a swapped out
2783 * anonymous page vs reloading a filesystem page (swappiness).
2784 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002785 * Although we limit that influence to ensure no list gets
2786 * left behind completely: at least a third of the pressure is
2787 * applied, before swappiness.
2788 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002789 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002790 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002791 total_cost = sc->anon_cost + sc->file_cost;
2792 anon_cost = total_cost + sc->anon_cost;
2793 file_cost = total_cost + sc->file_cost;
2794 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002795
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002796 ap = swappiness * (total_cost + 1);
2797 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002798
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002799 fp = (200 - swappiness) * (total_cost + 1);
2800 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002801
Shaohua Li76a33fc2010-05-24 14:32:36 -07002802 fraction[0] = ap;
2803 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002804 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002805out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002806 for_each_evictable_lru(lru) {
2807 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002808 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002809 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002810 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002811
Chris Down9783aa92019-10-06 17:58:32 -07002812 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002813 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2814 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002815
Johannes Weinerf56ce412021-08-19 19:04:21 -07002816 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002817 /*
2818 * Scale a cgroup's reclaim pressure by proportioning
2819 * its current usage to its memory.low or memory.min
2820 * setting.
2821 *
2822 * This is important, as otherwise scanning aggression
2823 * becomes extremely binary -- from nothing as we
2824 * approach the memory protection threshold, to totally
2825 * nominal as we exceed it. This results in requiring
2826 * setting extremely liberal protection thresholds. It
2827 * also means we simply get no protection at all if we
2828 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002829 *
2830 * If there is any protection in place, we reduce scan
2831 * pressure by how much of the total memory used is
2832 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002833 *
Chris Down9de7ca42019-10-06 17:58:35 -07002834 * There is one special case: in the first reclaim pass,
2835 * we skip over all groups that are within their low
2836 * protection. If that fails to reclaim enough pages to
2837 * satisfy the reclaim goal, we come back and override
2838 * the best-effort low protection. However, we still
2839 * ideally want to honor how well-behaved groups are in
2840 * that case instead of simply punishing them all
2841 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002842 * memory they are using, reducing the scan pressure
2843 * again by how much of the total memory used is under
2844 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002845 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002846 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002847 unsigned long protection;
2848
2849 /* memory.low scaling, make sure we retry before OOM */
2850 if (!sc->memcg_low_reclaim && low > min) {
2851 protection = low;
2852 sc->memcg_low_skipped = 1;
2853 } else {
2854 protection = min;
2855 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002856
2857 /* Avoid TOCTOU with earlier protection check */
2858 cgroup_size = max(cgroup_size, protection);
2859
2860 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002861 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002862
2863 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002864 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002865 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002866 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002867 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002868 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002869 } else {
2870 scan = lruvec_size;
2871 }
2872
2873 scan >>= sc->priority;
2874
Johannes Weiner688035f2017-05-03 14:52:07 -07002875 /*
2876 * If the cgroup's already been deleted, make sure to
2877 * scrape out the remaining cache.
2878 */
2879 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002880 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002881
Johannes Weiner688035f2017-05-03 14:52:07 -07002882 switch (scan_balance) {
2883 case SCAN_EQUAL:
2884 /* Scan lists relative to size */
2885 break;
2886 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002887 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002888 * Scan types proportional to swappiness and
2889 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002890 * Make sure we don't miss the last page on
2891 * the offlined memory cgroups because of a
2892 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002893 */
Gavin Shan76073c62020-02-20 20:04:24 -08002894 scan = mem_cgroup_online(memcg) ?
2895 div64_u64(scan * fraction[file], denominator) :
2896 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002897 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002898 break;
2899 case SCAN_FILE:
2900 case SCAN_ANON:
2901 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002902 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002903 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002904 break;
2905 default:
2906 /* Look ma, no brain */
2907 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002908 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002909
Johannes Weiner688035f2017-05-03 14:52:07 -07002910 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002911 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002912}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002913
Dave Hansen2f368a92021-09-02 14:59:23 -07002914/*
2915 * Anonymous LRU management is a waste if there is
2916 * ultimately no way to reclaim the memory.
2917 */
2918static bool can_age_anon_pages(struct pglist_data *pgdat,
2919 struct scan_control *sc)
2920{
2921 /* Aging the anon LRU is valuable if swap is present: */
2922 if (total_swap_pages > 0)
2923 return true;
2924
2925 /* Also valuable if anon pages can be demoted: */
2926 return can_demote(pgdat->node_id, sc);
2927}
2928
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002929#ifdef CONFIG_LRU_GEN
2930
Yu Zhaobaeb9a02022-09-18 02:00:07 -06002931#ifdef CONFIG_LRU_GEN_ENABLED
2932DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2933#define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2934#else
2935DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2936#define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2937#endif
2938
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002939/******************************************************************************
2940 * shorthand helpers
2941 ******************************************************************************/
2942
Yu Zhao37397872022-09-18 02:00:03 -06002943#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2944
2945#define DEFINE_MAX_SEQ(lruvec) \
2946 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2947
2948#define DEFINE_MIN_SEQ(lruvec) \
2949 unsigned long min_seq[ANON_AND_FILE] = { \
2950 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2951 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2952 }
2953
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002954#define for_each_gen_type_zone(gen, type, zone) \
2955 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2956 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2957 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2958
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002959static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002960{
2961 struct pglist_data *pgdat = NODE_DATA(nid);
2962
2963#ifdef CONFIG_MEMCG
2964 if (memcg) {
2965 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2966
2967 /* for hotadd_new_pgdat() */
2968 if (!lruvec->pgdat)
2969 lruvec->pgdat = pgdat;
2970
2971 return lruvec;
2972 }
2973#endif
2974 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2975
2976 return pgdat ? &pgdat->__lruvec : NULL;
2977}
2978
Yu Zhao37397872022-09-18 02:00:03 -06002979static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2980{
2981 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2982 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2983
2984 if (!can_demote(pgdat->node_id, sc) &&
2985 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2986 return 0;
2987
2988 return mem_cgroup_swappiness(memcg);
2989}
2990
2991static int get_nr_gens(struct lruvec *lruvec, int type)
2992{
2993 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2994}
2995
2996static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2997{
2998 /* see the comment on lru_gen_struct */
2999 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3000 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3001 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3002}
3003
3004/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003005 * mm_struct list
3006 ******************************************************************************/
3007
3008static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3009{
3010 static struct lru_gen_mm_list mm_list = {
3011 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3012 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3013 };
3014
3015#ifdef CONFIG_MEMCG
3016 if (memcg)
3017 return &memcg->mm_list;
3018#endif
3019 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3020
3021 return &mm_list;
3022}
3023
3024void lru_gen_add_mm(struct mm_struct *mm)
3025{
3026 int nid;
3027 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3028 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3029
3030 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3031#ifdef CONFIG_MEMCG
3032 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3033 mm->lru_gen.memcg = memcg;
3034#endif
3035 spin_lock(&mm_list->lock);
3036
3037 for_each_node_state(nid, N_MEMORY) {
3038 struct lruvec *lruvec = get_lruvec(memcg, nid);
3039
3040 if (!lruvec)
3041 continue;
3042
3043 /* the first addition since the last iteration */
3044 if (lruvec->mm_state.tail == &mm_list->fifo)
3045 lruvec->mm_state.tail = &mm->lru_gen.list;
3046 }
3047
3048 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3049
3050 spin_unlock(&mm_list->lock);
3051}
3052
3053void lru_gen_del_mm(struct mm_struct *mm)
3054{
3055 int nid;
3056 struct lru_gen_mm_list *mm_list;
3057 struct mem_cgroup *memcg = NULL;
3058
3059 if (list_empty(&mm->lru_gen.list))
3060 return;
3061
3062#ifdef CONFIG_MEMCG
3063 memcg = mm->lru_gen.memcg;
3064#endif
3065 mm_list = get_mm_list(memcg);
3066
3067 spin_lock(&mm_list->lock);
3068
3069 for_each_node(nid) {
3070 struct lruvec *lruvec = get_lruvec(memcg, nid);
3071
3072 if (!lruvec)
3073 continue;
3074
3075 /* where the last iteration ended (exclusive) */
3076 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3077 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3078
3079 /* where the current iteration continues (inclusive) */
3080 if (lruvec->mm_state.head != &mm->lru_gen.list)
3081 continue;
3082
3083 lruvec->mm_state.head = lruvec->mm_state.head->next;
3084 /* the deletion ends the current iteration */
3085 if (lruvec->mm_state.head == &mm_list->fifo)
3086 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3087 }
3088
3089 list_del_init(&mm->lru_gen.list);
3090
3091 spin_unlock(&mm_list->lock);
3092
3093#ifdef CONFIG_MEMCG
3094 mem_cgroup_put(mm->lru_gen.memcg);
3095 mm->lru_gen.memcg = NULL;
3096#endif
3097}
3098
3099#ifdef CONFIG_MEMCG
3100void lru_gen_migrate_mm(struct mm_struct *mm)
3101{
3102 struct mem_cgroup *memcg;
3103 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3104
3105 VM_WARN_ON_ONCE(task->mm != mm);
3106 lockdep_assert_held(&task->alloc_lock);
3107
3108 /* for mm_update_next_owner() */
3109 if (mem_cgroup_disabled())
3110 return;
3111
3112 rcu_read_lock();
3113 memcg = mem_cgroup_from_task(task);
3114 rcu_read_unlock();
3115 if (memcg == mm->lru_gen.memcg)
3116 return;
3117
3118 VM_WARN_ON_ONCE(!mm->lru_gen.memcg);
3119 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3120
3121 lru_gen_del_mm(mm);
3122 lru_gen_add_mm(mm);
3123}
3124#endif
3125
3126/*
3127 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3128 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3129 * bits in a bitmap, k is the number of hash functions and n is the number of
3130 * inserted items.
3131 *
3132 * Page table walkers use one of the two filters to reduce their search space.
3133 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3134 * aging uses the double-buffering technique to flip to the other filter each
3135 * time it produces a new generation. For non-leaf entries that have enough
3136 * leaf entries, the aging carries them over to the next generation in
3137 * walk_pmd_range(); the eviction also report them when walking the rmap
3138 * in lru_gen_look_around().
3139 *
3140 * For future optimizations:
3141 * 1. It's not necessary to keep both filters all the time. The spare one can be
3142 * freed after the RCU grace period and reallocated if needed again.
3143 * 2. And when reallocating, it's worth scaling its size according to the number
3144 * of inserted entries in the other filter, to reduce the memory overhead on
3145 * small systems and false positives on large systems.
3146 * 3. Jenkins' hash function is an alternative to Knuth's.
3147 */
3148#define BLOOM_FILTER_SHIFT 15
3149
3150static inline int filter_gen_from_seq(unsigned long seq)
3151{
3152 return seq % NR_BLOOM_FILTERS;
3153}
3154
3155static void get_item_key(void *item, int *key)
3156{
3157 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3158
3159 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3160
3161 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3162 key[1] = hash >> BLOOM_FILTER_SHIFT;
3163}
3164
3165static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3166{
3167 unsigned long *filter;
3168 int gen = filter_gen_from_seq(seq);
3169
3170 filter = lruvec->mm_state.filters[gen];
3171 if (filter) {
3172 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3173 return;
3174 }
3175
3176 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3177 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3178 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3179}
3180
3181static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3182{
3183 int key[2];
3184 unsigned long *filter;
3185 int gen = filter_gen_from_seq(seq);
3186
3187 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3188 if (!filter)
3189 return;
3190
3191 get_item_key(item, key);
3192
3193 if (!test_bit(key[0], filter))
3194 set_bit(key[0], filter);
3195 if (!test_bit(key[1], filter))
3196 set_bit(key[1], filter);
3197}
3198
3199static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3200{
3201 int key[2];
3202 unsigned long *filter;
3203 int gen = filter_gen_from_seq(seq);
3204
3205 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3206 if (!filter)
3207 return true;
3208
3209 get_item_key(item, key);
3210
3211 return test_bit(key[0], filter) && test_bit(key[1], filter);
3212}
3213
3214static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3215{
3216 int i;
3217 int hist;
3218
3219 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3220
3221 if (walk) {
3222 hist = lru_hist_from_seq(walk->max_seq);
3223
3224 for (i = 0; i < NR_MM_STATS; i++) {
3225 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3226 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3227 walk->mm_stats[i] = 0;
3228 }
3229 }
3230
3231 if (NR_HIST_GENS > 1 && last) {
3232 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3233
3234 for (i = 0; i < NR_MM_STATS; i++)
3235 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3236 }
3237}
3238
3239static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3240{
3241 int type;
3242 unsigned long size = 0;
3243 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3244 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3245
3246 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3247 return true;
3248
3249 clear_bit(key, &mm->lru_gen.bitmap);
3250
3251 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3252 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3253 get_mm_counter(mm, MM_ANONPAGES) +
3254 get_mm_counter(mm, MM_SHMEMPAGES);
3255 }
3256
3257 if (size < MIN_LRU_BATCH)
3258 return true;
3259
3260 return !mmget_not_zero(mm);
3261}
3262
3263static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3264 struct mm_struct **iter)
3265{
3266 bool first = false;
3267 bool last = true;
3268 struct mm_struct *mm = NULL;
3269 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3270 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3271 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3272
3273 /*
3274 * There are four interesting cases for this page table walker:
3275 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3276 * there is nothing left to do.
3277 * 2. It's the first of the current generation, and it needs to reset
3278 * the Bloom filter for the next generation.
3279 * 3. It reaches the end of mm_list, and it needs to increment
3280 * mm_state->seq; the iteration is done.
3281 * 4. It's the last of the current generation, and it needs to reset the
3282 * mm stats counters for the next generation.
3283 */
3284 spin_lock(&mm_list->lock);
3285
3286 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3287 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3288 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3289
3290 if (walk->max_seq <= mm_state->seq) {
3291 if (!*iter)
3292 last = false;
3293 goto done;
3294 }
3295
3296 if (!mm_state->nr_walkers) {
3297 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3298
3299 mm_state->head = mm_list->fifo.next;
3300 first = true;
3301 }
3302
3303 while (!mm && mm_state->head != &mm_list->fifo) {
3304 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3305
3306 mm_state->head = mm_state->head->next;
3307
3308 /* force scan for those added after the last iteration */
3309 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3310 mm_state->tail = mm_state->head;
3311 walk->force_scan = true;
3312 }
3313
3314 if (should_skip_mm(mm, walk))
3315 mm = NULL;
3316 }
3317
3318 if (mm_state->head == &mm_list->fifo)
3319 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3320done:
3321 if (*iter && !mm)
3322 mm_state->nr_walkers--;
3323 if (!*iter && mm)
3324 mm_state->nr_walkers++;
3325
3326 if (mm_state->nr_walkers)
3327 last = false;
3328
3329 if (*iter || last)
3330 reset_mm_stats(lruvec, walk, last);
3331
3332 spin_unlock(&mm_list->lock);
3333
3334 if (mm && first)
3335 reset_bloom_filter(lruvec, walk->max_seq + 1);
3336
3337 if (*iter)
3338 mmput_async(*iter);
3339
3340 *iter = mm;
3341
3342 return last;
3343}
3344
3345static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3346{
3347 bool success = false;
3348 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3349 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3350 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3351
3352 spin_lock(&mm_list->lock);
3353
3354 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3355
3356 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3357 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3358
3359 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3360 reset_mm_stats(lruvec, NULL, true);
3361 success = true;
3362 }
3363
3364 spin_unlock(&mm_list->lock);
3365
3366 return success;
3367}
3368
3369/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003370 * refault feedback loop
3371 ******************************************************************************/
3372
3373/*
3374 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3375 *
3376 * The P term is refaulted/(evicted+protected) from a tier in the generation
3377 * currently being evicted; the I term is the exponential moving average of the
3378 * P term over the generations previously evicted, using the smoothing factor
3379 * 1/2; the D term isn't supported.
3380 *
3381 * The setpoint (SP) is always the first tier of one type; the process variable
3382 * (PV) is either any tier of the other type or any other tier of the same
3383 * type.
3384 *
3385 * The error is the difference between the SP and the PV; the correction is to
3386 * turn off protection when SP>PV or turn on protection when SP<PV.
3387 *
3388 * For future optimizations:
3389 * 1. The D term may discount the other two terms over time so that long-lived
3390 * generations can resist stale information.
3391 */
3392struct ctrl_pos {
3393 unsigned long refaulted;
3394 unsigned long total;
3395 int gain;
3396};
3397
3398static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3399 struct ctrl_pos *pos)
3400{
3401 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3402 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3403
3404 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3405 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3406 pos->total = lrugen->avg_total[type][tier] +
3407 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3408 if (tier)
3409 pos->total += lrugen->protected[hist][type][tier - 1];
3410 pos->gain = gain;
3411}
3412
3413static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3414{
3415 int hist, tier;
3416 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3417 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3418 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3419
3420 lockdep_assert_held(&lruvec->lru_lock);
3421
3422 if (!carryover && !clear)
3423 return;
3424
3425 hist = lru_hist_from_seq(seq);
3426
3427 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3428 if (carryover) {
3429 unsigned long sum;
3430
3431 sum = lrugen->avg_refaulted[type][tier] +
3432 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3433 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3434
3435 sum = lrugen->avg_total[type][tier] +
3436 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3437 if (tier)
3438 sum += lrugen->protected[hist][type][tier - 1];
3439 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3440 }
3441
3442 if (clear) {
3443 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3444 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3445 if (tier)
3446 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3447 }
3448 }
3449}
3450
3451static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3452{
3453 /*
3454 * Return true if the PV has a limited number of refaults or a lower
3455 * refaulted/total than the SP.
3456 */
3457 return pv->refaulted < MIN_LRU_BATCH ||
3458 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3459 (sp->refaulted + 1) * pv->total * pv->gain;
3460}
3461
3462/******************************************************************************
3463 * the aging
3464 ******************************************************************************/
3465
Yu Zhao0182f922022-09-18 02:00:04 -06003466/* promote pages accessed through page tables */
3467static int page_update_gen(struct page *page, int gen)
3468{
3469 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3470
3471 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3472 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3473
3474 do {
3475 /* lru_gen_del_page() has isolated this page? */
3476 if (!(old_flags & LRU_GEN_MASK)) {
3477 /* for shrink_page_list() */
3478 new_flags = old_flags | BIT(PG_referenced);
3479 continue;
3480 }
3481
3482 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3483 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3484 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3485
3486 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3487}
3488
Yu Zhao37397872022-09-18 02:00:03 -06003489/* protect pages accessed multiple times through file descriptors */
3490static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3491{
3492 int type = page_is_file_lru(page);
3493 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3494 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3495 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3496
3497 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3498
3499 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003500 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3501 /* page_update_gen() has promoted this page? */
3502 if (new_gen >= 0 && new_gen != old_gen)
3503 return new_gen;
3504
Yu Zhao37397872022-09-18 02:00:03 -06003505 new_gen = (old_gen + 1) % MAX_NR_GENS;
3506
3507 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3508 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3509 /* for end_page_writeback() */
3510 if (reclaiming)
3511 new_flags |= BIT(PG_reclaim);
3512 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3513
3514 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3515
3516 return new_gen;
3517}
3518
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003519static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3520 int old_gen, int new_gen)
3521{
3522 int type = page_is_file_lru(page);
3523 int zone = page_zonenum(page);
3524 int delta = thp_nr_pages(page);
3525
3526 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3527 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3528
3529 walk->batched++;
3530
3531 walk->nr_pages[old_gen][type][zone] -= delta;
3532 walk->nr_pages[new_gen][type][zone] += delta;
3533}
3534
3535static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3536{
3537 int gen, type, zone;
3538 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3539
3540 walk->batched = 0;
3541
3542 for_each_gen_type_zone(gen, type, zone) {
3543 enum lru_list lru = type * LRU_INACTIVE_FILE;
3544 int delta = walk->nr_pages[gen][type][zone];
3545
3546 if (!delta)
3547 continue;
3548
3549 walk->nr_pages[gen][type][zone] = 0;
3550 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3551 lrugen->nr_pages[gen][type][zone] + delta);
3552
3553 if (lru_gen_is_active(lruvec, gen))
3554 lru += LRU_ACTIVE;
3555 __update_lru_size(lruvec, lru, zone, delta);
3556 }
3557}
3558
3559static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3560{
3561 struct address_space *mapping;
3562 struct vm_area_struct *vma = args->vma;
3563 struct lru_gen_mm_walk *walk = args->private;
3564
3565 if (!vma_is_accessible(vma))
3566 return true;
3567
3568 if (is_vm_hugetlb_page(vma))
3569 return true;
3570
3571 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3572 return true;
3573
3574 if (vma == get_gate_vma(vma->vm_mm))
3575 return true;
3576
3577 if (vma_is_anonymous(vma))
3578 return !walk->can_swap;
3579
3580 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3581 return true;
3582
3583 mapping = vma->vm_file->f_mapping;
3584 if (mapping_unevictable(mapping))
3585 return true;
3586
3587 if (shmem_mapping(mapping))
3588 return !walk->can_swap;
3589
3590 /* to exclude special mappings like dax, etc. */
3591 return !mapping->a_ops->readpage;
3592}
3593
3594/*
3595 * Some userspace memory allocators map many single-page VMAs. Instead of
3596 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3597 * table to reduce zigzags and improve cache performance.
3598 */
3599static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3600 unsigned long *vm_start, unsigned long *vm_end)
3601{
3602 unsigned long start = round_up(*vm_end, size);
3603 unsigned long end = (start | ~mask) + 1;
3604
3605 VM_WARN_ON_ONCE(mask & size);
3606 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3607
3608 while (args->vma) {
3609 if (start >= args->vma->vm_end) {
3610 args->vma = args->vma->vm_next;
3611 continue;
3612 }
3613
3614 if (end && end <= args->vma->vm_start)
3615 return false;
3616
3617 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3618 args->vma = args->vma->vm_next;
3619 continue;
3620 }
3621
3622 *vm_start = max(start, args->vma->vm_start);
3623 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3624
3625 return true;
3626 }
3627
3628 return false;
3629}
3630
Yu Zhao0182f922022-09-18 02:00:04 -06003631static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3632{
3633 unsigned long pfn = pte_pfn(pte);
3634
3635 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3636
3637 if (!pte_present(pte) || is_zero_pfn(pfn))
3638 return -1;
3639
3640 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3641 return -1;
3642
3643 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3644 return -1;
3645
3646 return pfn;
3647}
3648
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003649#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3650static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3651{
3652 unsigned long pfn = pmd_pfn(pmd);
3653
3654 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3655
3656 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3657 return -1;
3658
3659 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3660 return -1;
3661
3662 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3663 return -1;
3664
3665 return pfn;
3666}
3667#endif
3668
Yu Zhao0182f922022-09-18 02:00:04 -06003669static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003670 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003671{
3672 struct page *page;
3673
3674 /* try to avoid unnecessary memory loads */
3675 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3676 return NULL;
3677
3678 page = compound_head(pfn_to_page(pfn));
3679 if (page_to_nid(page) != pgdat->node_id)
3680 return NULL;
3681
3682 if (page_memcg_rcu(page) != memcg)
3683 return NULL;
3684
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003685 /* file VMAs can contain anon pages from COW */
3686 if (!page_is_file_lru(page) && !can_swap)
3687 return NULL;
3688
Yu Zhao0182f922022-09-18 02:00:04 -06003689 return page;
3690}
3691
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003692static bool suitable_to_scan(int total, int young)
3693{
3694 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3695
3696 /* suitable if the average number of young PTEs per cacheline is >=1 */
3697 return young * n >= total;
3698}
3699
3700static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3701 struct mm_walk *args)
3702{
3703 int i;
3704 pte_t *pte;
3705 spinlock_t *ptl;
3706 unsigned long addr;
3707 int total = 0;
3708 int young = 0;
3709 struct lru_gen_mm_walk *walk = args->private;
3710 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3711 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3712 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3713
3714 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3715
3716 ptl = pte_lockptr(args->mm, pmd);
3717 if (!spin_trylock(ptl))
3718 return false;
3719
3720 arch_enter_lazy_mmu_mode();
3721
3722 pte = pte_offset_map(pmd, start & PMD_MASK);
3723restart:
3724 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3725 unsigned long pfn;
3726 struct page *page;
3727
3728 total++;
3729 walk->mm_stats[MM_LEAF_TOTAL]++;
3730
3731 pfn = get_pte_pfn(pte[i], args->vma, addr);
3732 if (pfn == -1)
3733 continue;
3734
3735 if (!pte_young(pte[i])) {
3736 walk->mm_stats[MM_LEAF_OLD]++;
3737 continue;
3738 }
3739
3740 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3741 if (!page)
3742 continue;
3743
3744 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3745 VM_WARN_ON_ONCE(true);
3746
3747 young++;
3748 walk->mm_stats[MM_LEAF_YOUNG]++;
3749
3750 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3751 !(PageAnon(page) && PageSwapBacked(page) &&
3752 !PageSwapCache(page)))
3753 set_page_dirty(page);
3754
3755 old_gen = page_update_gen(page, new_gen);
3756 if (old_gen >= 0 && old_gen != new_gen)
3757 update_batch_size(walk, page, old_gen, new_gen);
3758 }
3759
3760 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3761 goto restart;
3762
3763 pte_unmap(pte);
3764
3765 arch_leave_lazy_mmu_mode();
3766 spin_unlock(ptl);
3767
3768 return suitable_to_scan(total, young);
3769}
3770
3771#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3772static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3773 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3774{
3775 int i;
3776 pmd_t *pmd;
3777 spinlock_t *ptl;
3778 struct lru_gen_mm_walk *walk = args->private;
3779 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3780 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3781 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3782
3783 VM_WARN_ON_ONCE(pud_leaf(*pud));
3784
3785 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3786 if (*start == -1) {
3787 *start = next;
3788 return;
3789 }
3790
3791 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3792 if (i && i <= MIN_LRU_BATCH) {
3793 __set_bit(i - 1, bitmap);
3794 return;
3795 }
3796
3797 pmd = pmd_offset(pud, *start);
3798
3799 ptl = pmd_lockptr(args->mm, pmd);
3800 if (!spin_trylock(ptl))
3801 goto done;
3802
3803 arch_enter_lazy_mmu_mode();
3804
3805 do {
3806 unsigned long pfn;
3807 struct page *page;
3808 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3809
3810 pfn = get_pmd_pfn(pmd[i], vma, addr);
3811 if (pfn == -1)
3812 goto next;
3813
3814 if (!pmd_trans_huge(pmd[i])) {
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003815 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3816 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003817 pmdp_test_and_clear_young(vma, addr, pmd + i);
3818 goto next;
3819 }
3820
3821 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3822 if (!page)
3823 goto next;
3824
3825 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3826 goto next;
3827
3828 walk->mm_stats[MM_LEAF_YOUNG]++;
3829
3830 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3831 !(PageAnon(page) && PageSwapBacked(page) &&
3832 !PageSwapCache(page)))
3833 set_page_dirty(page);
3834
3835 old_gen = page_update_gen(page, new_gen);
3836 if (old_gen >= 0 && old_gen != new_gen)
3837 update_batch_size(walk, page, old_gen, new_gen);
3838next:
3839 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3840 } while (i <= MIN_LRU_BATCH);
3841
3842 arch_leave_lazy_mmu_mode();
3843 spin_unlock(ptl);
3844done:
3845 *start = -1;
3846 bitmap_zero(bitmap, MIN_LRU_BATCH);
3847}
3848#else
3849static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3850 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3851{
3852}
3853#endif
3854
3855static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3856 struct mm_walk *args)
3857{
3858 int i;
3859 pmd_t *pmd;
3860 unsigned long next;
3861 unsigned long addr;
3862 struct vm_area_struct *vma;
3863 unsigned long pos = -1;
3864 struct lru_gen_mm_walk *walk = args->private;
3865 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3866
3867 VM_WARN_ON_ONCE(pud_leaf(*pud));
3868
3869 /*
3870 * Finish an entire PMD in two passes: the first only reaches to PTE
3871 * tables to avoid taking the PMD lock; the second, if necessary, takes
3872 * the PMD lock to clear the accessed bit in PMD entries.
3873 */
3874 pmd = pmd_offset(pud, start & PUD_MASK);
3875restart:
3876 /* walk_pte_range() may call get_next_vma() */
3877 vma = args->vma;
3878 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3879 pmd_t val = pmd_read_atomic(pmd + i);
3880
3881 /* for pmd_read_atomic() */
3882 barrier();
3883
3884 next = pmd_addr_end(addr, end);
3885
3886 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3887 walk->mm_stats[MM_LEAF_TOTAL]++;
3888 continue;
3889 }
3890
3891#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3892 if (pmd_trans_huge(val)) {
3893 unsigned long pfn = pmd_pfn(val);
3894 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3895
3896 walk->mm_stats[MM_LEAF_TOTAL]++;
3897
3898 if (!pmd_young(val)) {
3899 walk->mm_stats[MM_LEAF_OLD]++;
3900 continue;
3901 }
3902
3903 /* try to avoid unnecessary memory loads */
3904 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3905 continue;
3906
3907 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3908 continue;
3909 }
3910#endif
3911 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3912
3913#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003914 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3915 if (!pmd_young(val))
3916 continue;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003917
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003918 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3919 }
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003920#endif
3921 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3922 continue;
3923
3924 walk->mm_stats[MM_NONLEAF_FOUND]++;
3925
3926 if (!walk_pte_range(&val, addr, next, args))
3927 continue;
3928
3929 walk->mm_stats[MM_NONLEAF_ADDED]++;
3930
3931 /* carry over to the next generation */
3932 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3933 }
3934
3935 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3936
3937 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3938 goto restart;
3939}
3940
3941static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3942 struct mm_walk *args)
3943{
3944 int i;
3945 pud_t *pud;
3946 unsigned long addr;
3947 unsigned long next;
3948 struct lru_gen_mm_walk *walk = args->private;
3949
3950 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3951
3952 pud = pud_offset(p4d, start & P4D_MASK);
3953restart:
3954 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3955 pud_t val = READ_ONCE(pud[i]);
3956
3957 next = pud_addr_end(addr, end);
3958
3959 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3960 continue;
3961
3962 walk_pmd_range(&val, addr, next, args);
3963
3964 /* a racy check to curtail the waiting time */
3965 if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
3966 return 1;
3967
3968 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3969 end = (addr | ~PUD_MASK) + 1;
3970 goto done;
3971 }
3972 }
3973
3974 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3975 goto restart;
3976
3977 end = round_up(end, P4D_SIZE);
3978done:
3979 if (!end || !args->vma)
3980 return 1;
3981
3982 walk->next_addr = max(end, args->vma->vm_start);
3983
3984 return -EAGAIN;
3985}
3986
3987static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3988{
3989 static const struct mm_walk_ops mm_walk_ops = {
3990 .test_walk = should_skip_vma,
3991 .p4d_entry = walk_pud_range,
3992 };
3993
3994 int err;
3995 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3996
3997 walk->next_addr = FIRST_USER_ADDRESS;
3998
3999 do {
4000 err = -EBUSY;
4001
4002 /* page_update_gen() requires stable page_memcg() */
4003 if (!mem_cgroup_trylock_pages(memcg))
4004 break;
4005
4006 /* the caller might be holding the lock for write */
4007 if (mmap_read_trylock(mm)) {
4008 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
4009
4010 mmap_read_unlock(mm);
4011 }
4012
4013 mem_cgroup_unlock_pages();
4014
4015 if (walk->batched) {
4016 spin_lock_irq(&lruvec->lru_lock);
4017 reset_batch_size(lruvec, walk);
4018 spin_unlock_irq(&lruvec->lru_lock);
4019 }
4020
4021 cond_resched();
4022 } while (err == -EAGAIN);
4023}
4024
4025static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
4026{
4027 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4028
4029 if (pgdat && current_is_kswapd()) {
4030 VM_WARN_ON_ONCE(walk);
4031
4032 walk = &pgdat->mm_walk;
4033 } else if (!pgdat && !walk) {
4034 VM_WARN_ON_ONCE(current_is_kswapd());
4035
4036 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4037 }
4038
4039 current->reclaim_state->mm_walk = walk;
4040
4041 return walk;
4042}
4043
4044static void clear_mm_walk(void)
4045{
4046 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4047
4048 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4049 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4050
4051 current->reclaim_state->mm_walk = NULL;
4052
4053 if (!current_is_kswapd())
4054 kfree(walk);
4055}
4056
Yu Zhao37397872022-09-18 02:00:03 -06004057static void inc_min_seq(struct lruvec *lruvec, int type)
4058{
4059 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4060
4061 reset_ctrl_pos(lruvec, type, true);
4062 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4063}
4064
4065static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4066{
4067 int gen, type, zone;
4068 bool success = false;
4069 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4070 DEFINE_MIN_SEQ(lruvec);
4071
4072 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4073
4074 /* find the oldest populated generation */
4075 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4076 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4077 gen = lru_gen_from_seq(min_seq[type]);
4078
4079 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4080 if (!list_empty(&lrugen->lists[gen][type][zone]))
4081 goto next;
4082 }
4083
4084 min_seq[type]++;
4085 }
4086next:
4087 ;
4088 }
4089
4090 /* see the comment on lru_gen_struct */
4091 if (can_swap) {
4092 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4093 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4094 }
4095
4096 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4097 if (min_seq[type] == lrugen->min_seq[type])
4098 continue;
4099
4100 reset_ctrl_pos(lruvec, type, true);
4101 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4102 success = true;
4103 }
4104
4105 return success;
4106}
4107
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004108static void inc_max_seq(struct lruvec *lruvec, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004109{
4110 int prev, next;
4111 int type, zone;
4112 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4113
4114 spin_lock_irq(&lruvec->lru_lock);
4115
4116 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4117
Yu Zhao37397872022-09-18 02:00:03 -06004118 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4119 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4120 continue;
4121
4122 VM_WARN_ON_ONCE(type == LRU_GEN_FILE || can_swap);
4123
4124 inc_min_seq(lruvec, type);
4125 }
4126
4127 /*
4128 * Update the active/inactive LRU sizes for compatibility. Both sides of
4129 * the current max_seq need to be covered, since max_seq+1 can overlap
4130 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4131 * overlap, cold/hot inversion happens.
4132 */
4133 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4134 next = lru_gen_from_seq(lrugen->max_seq + 1);
4135
4136 for (type = 0; type < ANON_AND_FILE; type++) {
4137 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4138 enum lru_list lru = type * LRU_INACTIVE_FILE;
4139 long delta = lrugen->nr_pages[prev][type][zone] -
4140 lrugen->nr_pages[next][type][zone];
4141
4142 if (!delta)
4143 continue;
4144
4145 __update_lru_size(lruvec, lru, zone, delta);
4146 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4147 }
4148 }
4149
4150 for (type = 0; type < ANON_AND_FILE; type++)
4151 reset_ctrl_pos(lruvec, type, false);
4152
4153 /* make sure preceding modifications appear */
4154 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004155
Yu Zhao37397872022-09-18 02:00:03 -06004156 spin_unlock_irq(&lruvec->lru_lock);
4157}
4158
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004159static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4160 struct scan_control *sc, bool can_swap)
4161{
4162 bool success;
4163 struct lru_gen_mm_walk *walk;
4164 struct mm_struct *mm = NULL;
4165 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4166
4167 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4168
4169 /* see the comment in iterate_mm_list() */
4170 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4171 success = false;
4172 goto done;
4173 }
4174
4175 /*
4176 * If the hardware doesn't automatically set the accessed bit, fallback
4177 * to lru_gen_look_around(), which only clears the accessed bit in a
4178 * handful of PTEs. Spreading the work out over a period of time usually
4179 * is less efficient, but it avoids bursty page faults.
4180 */
Yu Zhaobaeb9a02022-09-18 02:00:07 -06004181 if (!(arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004182 success = iterate_mm_list_nowalk(lruvec, max_seq);
4183 goto done;
4184 }
4185
4186 walk = set_mm_walk(NULL);
4187 if (!walk) {
4188 success = iterate_mm_list_nowalk(lruvec, max_seq);
4189 goto done;
4190 }
4191
4192 walk->lruvec = lruvec;
4193 walk->max_seq = max_seq;
4194 walk->can_swap = can_swap;
4195 walk->force_scan = false;
4196
4197 do {
4198 success = iterate_mm_list(lruvec, walk, &mm);
4199 if (mm)
4200 walk_mm(lruvec, mm, walk);
4201
4202 cond_resched();
4203 } while (mm);
4204done:
4205 if (!success) {
4206 if (sc->priority <= DEF_PRIORITY - 2)
4207 wait_event_killable(lruvec->mm_state.wait,
4208 max_seq < READ_ONCE(lrugen->max_seq));
4209
4210 return max_seq < READ_ONCE(lrugen->max_seq);
4211 }
4212
4213 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4214
4215 inc_max_seq(lruvec, can_swap);
4216 /* either this sees any waiters or they will see updated max_seq */
4217 if (wq_has_sleeper(&lruvec->mm_state.wait))
4218 wake_up_all(&lruvec->mm_state.wait);
4219
4220 return true;
4221}
4222
Yu Zhao37397872022-09-18 02:00:03 -06004223static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
4224 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4225{
4226 int gen, type, zone;
4227 unsigned long old = 0;
4228 unsigned long young = 0;
4229 unsigned long total = 0;
4230 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4231 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4232
4233 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4234 unsigned long seq;
4235
4236 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4237 unsigned long size = 0;
4238
4239 gen = lru_gen_from_seq(seq);
4240
4241 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4242 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4243
4244 total += size;
4245 if (seq == max_seq)
4246 young += size;
4247 else if (seq + MIN_NR_GENS == max_seq)
4248 old += size;
4249 }
4250 }
4251
4252 /* try to scrape all its memory if this memcg was deleted */
4253 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4254
4255 /*
4256 * The aging tries to be lazy to reduce the overhead, while the eviction
4257 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4258 * ideal number of generations is MIN_NR_GENS+1.
4259 */
4260 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
4261 return true;
4262 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4263 return false;
4264
4265 /*
4266 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4267 * of the total number of pages for each generation. A reasonable range
4268 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4269 * aging cares about the upper bound of hot pages, while the eviction
4270 * cares about the lower bound of cold pages.
4271 */
4272 if (young * MIN_NR_GENS > total)
4273 return true;
4274 if (old * (MIN_NR_GENS + 2) < total)
4275 return true;
4276
4277 return false;
4278}
4279
4280static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4281{
4282 bool need_aging;
4283 unsigned long nr_to_scan;
4284 int swappiness = get_swappiness(lruvec, sc);
4285 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4286 DEFINE_MAX_SEQ(lruvec);
4287 DEFINE_MIN_SEQ(lruvec);
4288
4289 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
4290
4291 mem_cgroup_calculate_protection(NULL, memcg);
4292
4293 if (mem_cgroup_below_min(memcg))
4294 return;
4295
4296 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
4297 if (need_aging)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004298 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness);
Yu Zhao37397872022-09-18 02:00:03 -06004299}
4300
4301static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4302{
4303 struct mem_cgroup *memcg;
4304
4305 VM_WARN_ON_ONCE(!current_is_kswapd());
4306
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004307 sc->last_reclaimed = sc->nr_reclaimed;
4308
4309 /*
4310 * To reduce the chance of going into the aging path, which can be
4311 * costly, optimistically skip it if the flag below was cleared in the
4312 * eviction path. This improves the overall performance when multiple
4313 * memcgs are available.
4314 */
4315 if (!sc->memcgs_need_aging) {
4316 sc->memcgs_need_aging = true;
4317 return;
4318 }
4319
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004320 set_mm_walk(pgdat);
4321
Yu Zhao37397872022-09-18 02:00:03 -06004322 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4323 do {
4324 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4325
4326 age_lruvec(lruvec, sc);
4327
4328 cond_resched();
4329 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004330
4331 clear_mm_walk();
Yu Zhao37397872022-09-18 02:00:03 -06004332}
4333
Yu Zhao0182f922022-09-18 02:00:04 -06004334/*
4335 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004336 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4337 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4338 * the PTE table to the Bloom filter. This forms a feedback loop between the
4339 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004340 */
4341void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4342{
4343 int i;
4344 pte_t *pte;
4345 unsigned long start;
4346 unsigned long end;
4347 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004348 struct lru_gen_mm_walk *walk;
4349 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004350 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4351 struct page *page = pvmw->page;
4352 struct mem_cgroup *memcg = page_memcg(page);
4353 struct pglist_data *pgdat = page_pgdat(page);
4354 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4355 DEFINE_MAX_SEQ(lruvec);
4356 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4357
4358 lockdep_assert_held(pvmw->ptl);
4359 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4360
4361 if (spin_is_contended(pvmw->ptl))
4362 return;
4363
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004364 /* avoid taking the LRU lock under the PTL when possible */
4365 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4366
Yu Zhao0182f922022-09-18 02:00:04 -06004367 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4368 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4369
4370 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4371 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4372 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4373 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4374 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4375 else {
4376 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4377 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4378 }
4379 }
4380
4381 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4382
4383 rcu_read_lock();
4384 arch_enter_lazy_mmu_mode();
4385
4386 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4387 unsigned long pfn;
4388
4389 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4390 if (pfn == -1)
4391 continue;
4392
4393 if (!pte_young(pte[i]))
4394 continue;
4395
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004396 page = get_pfn_page(pfn, memcg, pgdat, !walk || walk->can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004397 if (!page)
4398 continue;
4399
4400 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4401 VM_WARN_ON_ONCE(true);
4402
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004403 young++;
4404
Yu Zhao0182f922022-09-18 02:00:04 -06004405 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4406 !(PageAnon(page) && PageSwapBacked(page) &&
4407 !PageSwapCache(page)))
4408 set_page_dirty(page);
4409
4410 old_gen = page_lru_gen(page);
4411 if (old_gen < 0)
4412 SetPageReferenced(page);
4413 else if (old_gen != new_gen)
4414 __set_bit(i, bitmap);
4415 }
4416
4417 arch_leave_lazy_mmu_mode();
4418 rcu_read_unlock();
4419
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004420 /* feedback from rmap walkers to page table walkers */
4421 if (suitable_to_scan(i, young))
4422 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4423
4424 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004425 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4426 page = pte_page(pte[i]);
4427 activate_page(page);
4428 }
4429 return;
4430 }
4431
4432 /* page_update_gen() requires stable page_memcg() */
4433 if (!mem_cgroup_trylock_pages(memcg))
4434 return;
4435
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004436 if (!walk) {
4437 spin_lock_irq(&lruvec->lru_lock);
4438 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4439 }
Yu Zhao0182f922022-09-18 02:00:04 -06004440
4441 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4442 page = compound_head(pte_page(pte[i]));
4443 if (page_memcg_rcu(page) != memcg)
4444 continue;
4445
4446 old_gen = page_update_gen(page, new_gen);
4447 if (old_gen < 0 || old_gen == new_gen)
4448 continue;
4449
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004450 if (walk)
4451 update_batch_size(walk, page, old_gen, new_gen);
4452 else
4453 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004454 }
4455
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004456 if (!walk)
4457 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004458
4459 mem_cgroup_unlock_pages();
4460}
4461
Yu Zhao37397872022-09-18 02:00:03 -06004462/******************************************************************************
4463 * the eviction
4464 ******************************************************************************/
4465
4466static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4467{
4468 bool success;
4469 int gen = page_lru_gen(page);
4470 int type = page_is_file_lru(page);
4471 int zone = page_zonenum(page);
4472 int delta = thp_nr_pages(page);
4473 int refs = page_lru_refs(page);
4474 int tier = lru_tier_from_refs(refs);
4475 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4476
4477 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4478
4479 /* unevictable */
4480 if (!page_evictable(page)) {
4481 success = lru_gen_del_page(lruvec, page, true);
4482 VM_WARN_ON_ONCE_PAGE(!success, page);
4483 SetPageUnevictable(page);
4484 add_page_to_lru_list(page, lruvec);
4485 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4486 return true;
4487 }
4488
4489 /* dirty lazyfree */
4490 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4491 success = lru_gen_del_page(lruvec, page, true);
4492 VM_WARN_ON_ONCE_PAGE(!success, page);
4493 SetPageSwapBacked(page);
4494 add_page_to_lru_list_tail(page, lruvec);
4495 return true;
4496 }
4497
Yu Zhao0182f922022-09-18 02:00:04 -06004498 /* promoted */
4499 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4500 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4501 return true;
4502 }
4503
Yu Zhao37397872022-09-18 02:00:03 -06004504 /* protected */
4505 if (tier > tier_idx) {
4506 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4507
4508 gen = page_inc_gen(lruvec, page, false);
4509 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4510
4511 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4512 lrugen->protected[hist][type][tier - 1] + delta);
4513 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4514 return true;
4515 }
4516
4517 /* waiting for writeback */
4518 if (PageLocked(page) || PageWriteback(page) ||
4519 (type == LRU_GEN_FILE && PageDirty(page))) {
4520 gen = page_inc_gen(lruvec, page, true);
4521 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4522 return true;
4523 }
4524
4525 return false;
4526}
4527
4528static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4529{
4530 bool success;
4531
4532 /* unmapping inhibited */
4533 if (!sc->may_unmap && page_mapped(page))
4534 return false;
4535
4536 /* swapping inhibited */
4537 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4538 (PageDirty(page) ||
4539 (PageAnon(page) && !PageSwapCache(page))))
4540 return false;
4541
4542 /* raced with release_pages() */
4543 if (!get_page_unless_zero(page))
4544 return false;
4545
4546 /* raced with another isolation */
4547 if (!TestClearPageLRU(page)) {
4548 put_page(page);
4549 return false;
4550 }
4551
4552 /* see the comment on MAX_NR_TIERS */
4553 if (!PageReferenced(page))
4554 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4555
4556 /* for shrink_page_list() */
4557 ClearPageReclaim(page);
4558 ClearPageReferenced(page);
4559
4560 success = lru_gen_del_page(lruvec, page, true);
4561 VM_WARN_ON_ONCE_PAGE(!success, page);
4562
4563 return true;
4564}
4565
4566static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4567 int type, int tier, struct list_head *list)
4568{
4569 int gen, zone;
4570 enum vm_event_item item;
4571 int sorted = 0;
4572 int scanned = 0;
4573 int isolated = 0;
4574 int remaining = MAX_LRU_BATCH;
4575 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4576 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4577
4578 VM_WARN_ON_ONCE(!list_empty(list));
4579
4580 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4581 return 0;
4582
4583 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4584
4585 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4586 LIST_HEAD(moved);
4587 int skipped = 0;
4588 struct list_head *head = &lrugen->lists[gen][type][zone];
4589
4590 while (!list_empty(head)) {
4591 struct page *page = lru_to_page(head);
4592 int delta = thp_nr_pages(page);
4593
4594 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4595 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4596 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4597 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4598
4599 scanned += delta;
4600
4601 if (sort_page(lruvec, page, tier))
4602 sorted += delta;
4603 else if (isolate_page(lruvec, page, sc)) {
4604 list_add(&page->lru, list);
4605 isolated += delta;
4606 } else {
4607 list_move(&page->lru, &moved);
4608 skipped += delta;
4609 }
4610
4611 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4612 break;
4613 }
4614
4615 if (skipped) {
4616 list_splice(&moved, head);
4617 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4618 }
4619
4620 if (!remaining || isolated >= MIN_LRU_BATCH)
4621 break;
4622 }
4623
4624 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4625 if (!cgroup_reclaim(sc)) {
4626 __count_vm_events(item, isolated);
4627 __count_vm_events(PGREFILL, sorted);
4628 }
4629 __count_memcg_events(memcg, item, isolated);
4630 __count_memcg_events(memcg, PGREFILL, sorted);
4631 __count_vm_events(PGSCAN_ANON + type, isolated);
4632
4633 /*
4634 * There might not be eligible pages due to reclaim_idx, may_unmap and
4635 * may_writepage. Check the remaining to prevent livelock if it's not
4636 * making progress.
4637 */
4638 return isolated || !remaining ? scanned : 0;
4639}
4640
4641static int get_tier_idx(struct lruvec *lruvec, int type)
4642{
4643 int tier;
4644 struct ctrl_pos sp, pv;
4645
4646 /*
4647 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4648 * This value is chosen because any other tier would have at least twice
4649 * as many refaults as the first tier.
4650 */
4651 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4652 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4653 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4654 if (!positive_ctrl_err(&sp, &pv))
4655 break;
4656 }
4657
4658 return tier - 1;
4659}
4660
4661static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4662{
4663 int type, tier;
4664 struct ctrl_pos sp, pv;
4665 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4666
4667 /*
4668 * Compare the first tier of anon with that of file to determine which
4669 * type to scan. Also need to compare other tiers of the selected type
4670 * with the first tier of the other type to determine the last tier (of
4671 * the selected type) to evict.
4672 */
4673 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4674 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4675 type = positive_ctrl_err(&sp, &pv);
4676
4677 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4678 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4679 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4680 if (!positive_ctrl_err(&sp, &pv))
4681 break;
4682 }
4683
4684 *tier_idx = tier - 1;
4685
4686 return type;
4687}
4688
4689static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4690 int *type_scanned, struct list_head *list)
4691{
4692 int i;
4693 int type;
4694 int scanned;
4695 int tier = -1;
4696 DEFINE_MIN_SEQ(lruvec);
4697
4698 /*
4699 * Try to make the obvious choice first. When anon and file are both
4700 * available from the same generation, interpret swappiness 1 as file
4701 * first and 200 as anon first.
4702 */
4703 if (!swappiness)
4704 type = LRU_GEN_FILE;
4705 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4706 type = LRU_GEN_ANON;
4707 else if (swappiness == 1)
4708 type = LRU_GEN_FILE;
4709 else if (swappiness == 200)
4710 type = LRU_GEN_ANON;
4711 else
4712 type = get_type_to_scan(lruvec, swappiness, &tier);
4713
4714 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4715 if (tier < 0)
4716 tier = get_tier_idx(lruvec, type);
4717
4718 scanned = scan_pages(lruvec, sc, type, tier, list);
4719 if (scanned)
4720 break;
4721
4722 type = !type;
4723 tier = -1;
4724 }
4725
4726 *type_scanned = type;
4727
4728 return scanned;
4729}
4730
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004731static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4732 bool *need_swapping)
Yu Zhao37397872022-09-18 02:00:03 -06004733{
4734 int type;
4735 int scanned;
4736 int reclaimed;
4737 LIST_HEAD(list);
4738 struct page *page;
4739 enum vm_event_item item;
4740 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004741 struct lru_gen_mm_walk *walk;
Yu Zhao37397872022-09-18 02:00:03 -06004742 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4743 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4744
4745 spin_lock_irq(&lruvec->lru_lock);
4746
4747 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4748
4749 scanned += try_to_inc_min_seq(lruvec, swappiness);
4750
4751 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4752 scanned = 0;
4753
4754 spin_unlock_irq(&lruvec->lru_lock);
4755
4756 if (list_empty(&list))
4757 return scanned;
4758
4759 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4760
4761 list_for_each_entry(page, &list, lru) {
4762 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4763 if (PageWorkingset(page))
4764 SetPageReferenced(page);
4765
4766 /* don't add rejected pages to the oldest generation */
4767 if (PageReclaim(page) &&
4768 (PageDirty(page) || PageWriteback(page)))
4769 ClearPageActive(page);
4770 else
4771 SetPageActive(page);
4772 }
4773
4774 spin_lock_irq(&lruvec->lru_lock);
4775
4776 move_pages_to_lru(lruvec, &list);
4777
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004778 walk = current->reclaim_state->mm_walk;
4779 if (walk && walk->batched)
4780 reset_batch_size(lruvec, walk);
4781
Yu Zhao37397872022-09-18 02:00:03 -06004782 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4783 if (!cgroup_reclaim(sc))
4784 __count_vm_events(item, reclaimed);
4785 __count_memcg_events(memcg, item, reclaimed);
4786 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4787
4788 spin_unlock_irq(&lruvec->lru_lock);
4789
4790 mem_cgroup_uncharge_list(&list);
4791 free_unref_page_list(&list);
4792
4793 sc->nr_reclaimed += reclaimed;
4794
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004795 if (need_swapping && type == LRU_GEN_ANON)
4796 *need_swapping = true;
4797
Yu Zhao37397872022-09-18 02:00:03 -06004798 return scanned;
4799}
4800
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004801/*
4802 * For future optimizations:
4803 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4804 * reclaim.
4805 */
Yu Zhao37397872022-09-18 02:00:03 -06004806static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004807 bool can_swap, bool *need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004808{
Yu Zhao37397872022-09-18 02:00:03 -06004809 unsigned long nr_to_scan;
4810 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4811 DEFINE_MAX_SEQ(lruvec);
4812 DEFINE_MIN_SEQ(lruvec);
4813
4814 if (mem_cgroup_below_min(memcg) ||
4815 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4816 return 0;
4817
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004818 *need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
4819 if (!*need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004820 return nr_to_scan;
4821
4822 /* skip the aging path at the default priority */
4823 if (sc->priority == DEF_PRIORITY)
4824 goto done;
4825
4826 /* leave the work to lru_gen_age_node() */
4827 if (current_is_kswapd())
4828 return 0;
4829
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004830 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap))
4831 return nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004832done:
4833 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
4834}
4835
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004836static bool should_abort_scan(struct lruvec *lruvec, unsigned long seq,
4837 struct scan_control *sc, bool need_swapping)
4838{
4839 int i;
4840 DEFINE_MAX_SEQ(lruvec);
4841
4842 if (!current_is_kswapd()) {
4843 /* age each memcg at most once to ensure fairness */
4844 if (max_seq - seq > 1)
4845 return true;
4846
4847 /* over-swapping can increase allocation latency */
4848 if (sc->nr_reclaimed >= sc->nr_to_reclaim && need_swapping)
4849 return true;
4850
4851 /* give this thread a chance to exit and free its memory */
4852 if (fatal_signal_pending(current)) {
4853 sc->nr_reclaimed += MIN_LRU_BATCH;
4854 return true;
4855 }
4856
4857 if (cgroup_reclaim(sc))
4858 return false;
4859 } else if (sc->nr_reclaimed - sc->last_reclaimed < sc->nr_to_reclaim)
4860 return false;
4861
4862 /* keep scanning at low priorities to ensure fairness */
4863 if (sc->priority > DEF_PRIORITY - 2)
4864 return false;
4865
4866 /*
4867 * A minimum amount of work was done under global memory pressure. For
4868 * kswapd, it may be overshooting. For direct reclaim, the allocation
4869 * may succeed if all suitable zones are somewhat safe. In either case,
4870 * it's better to stop now, and restart later if necessary.
4871 */
4872 for (i = 0; i <= sc->reclaim_idx; i++) {
4873 unsigned long wmark;
4874 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
4875
4876 if (!managed_zone(zone))
4877 continue;
4878
4879 wmark = current_is_kswapd() ? high_wmark_pages(zone) : low_wmark_pages(zone);
4880 if (wmark > zone_page_state(zone, NR_FREE_PAGES))
4881 return false;
4882 }
4883
4884 sc->nr_reclaimed += MIN_LRU_BATCH;
4885
4886 return true;
4887}
4888
Yu Zhao37397872022-09-18 02:00:03 -06004889static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4890{
4891 struct blk_plug plug;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004892 bool need_aging = false;
4893 bool need_swapping = false;
Yu Zhao37397872022-09-18 02:00:03 -06004894 unsigned long scanned = 0;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004895 unsigned long reclaimed = sc->nr_reclaimed;
4896 DEFINE_MAX_SEQ(lruvec);
Yu Zhao37397872022-09-18 02:00:03 -06004897
4898 lru_add_drain();
4899
4900 blk_start_plug(&plug);
4901
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004902 set_mm_walk(lruvec_pgdat(lruvec));
4903
Yu Zhao37397872022-09-18 02:00:03 -06004904 while (true) {
4905 int delta;
4906 int swappiness;
4907 unsigned long nr_to_scan;
4908
4909 if (sc->may_swap)
4910 swappiness = get_swappiness(lruvec, sc);
4911 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4912 swappiness = 1;
4913 else
4914 swappiness = 0;
4915
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004916 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, &need_aging);
Yu Zhao37397872022-09-18 02:00:03 -06004917 if (!nr_to_scan)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004918 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004919
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004920 delta = evict_pages(lruvec, sc, swappiness, &need_swapping);
Yu Zhao37397872022-09-18 02:00:03 -06004921 if (!delta)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004922 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004923
4924 scanned += delta;
4925 if (scanned >= nr_to_scan)
4926 break;
4927
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004928 if (should_abort_scan(lruvec, max_seq, sc, need_swapping))
4929 break;
4930
Yu Zhao37397872022-09-18 02:00:03 -06004931 cond_resched();
4932 }
4933
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004934 /* see the comment in lru_gen_age_node() */
4935 if (sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH && !need_aging)
4936 sc->memcgs_need_aging = false;
4937done:
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004938 clear_mm_walk();
4939
Yu Zhao37397872022-09-18 02:00:03 -06004940 blk_finish_plug(&plug);
4941}
4942
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004943/******************************************************************************
Yu Zhaobaeb9a02022-09-18 02:00:07 -06004944 * state change
4945 ******************************************************************************/
4946
4947static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
4948{
4949 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4950
4951 if (lrugen->enabled) {
4952 enum lru_list lru;
4953
4954 for_each_evictable_lru(lru) {
4955 if (!list_empty(&lruvec->lists[lru]))
4956 return false;
4957 }
4958 } else {
4959 int gen, type, zone;
4960
4961 for_each_gen_type_zone(gen, type, zone) {
4962 if (!list_empty(&lrugen->lists[gen][type][zone]))
4963 return false;
4964 }
4965 }
4966
4967 return true;
4968}
4969
4970static bool fill_evictable(struct lruvec *lruvec)
4971{
4972 enum lru_list lru;
4973 int remaining = MAX_LRU_BATCH;
4974
4975 for_each_evictable_lru(lru) {
4976 int type = is_file_lru(lru);
4977 bool active = is_active_lru(lru);
4978 struct list_head *head = &lruvec->lists[lru];
4979
4980 while (!list_empty(head)) {
4981 bool success;
4982 struct page *page = lru_to_page(head);
4983
4984 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4985 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
4986 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4987 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
4988
4989 del_page_from_lru_list(page, lruvec);
4990 success = lru_gen_add_page(lruvec, page, false);
4991 VM_WARN_ON_ONCE(!success);
4992
4993 if (!--remaining)
4994 return false;
4995 }
4996 }
4997
4998 return true;
4999}
5000
5001static bool drain_evictable(struct lruvec *lruvec)
5002{
5003 int gen, type, zone;
5004 int remaining = MAX_LRU_BATCH;
5005
5006 for_each_gen_type_zone(gen, type, zone) {
5007 struct list_head *head = &lruvec->lrugen.lists[gen][type][zone];
5008
5009 while (!list_empty(head)) {
5010 bool success;
5011 struct page *page = lru_to_page(head);
5012
5013 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5014 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5015 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5016 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5017
5018 success = lru_gen_del_page(lruvec, page, false);
5019 VM_WARN_ON_ONCE(!success);
5020 add_page_to_lru_list(page, lruvec);
5021
5022 if (!--remaining)
5023 return false;
5024 }
5025 }
5026
5027 return true;
5028}
5029
5030static void lru_gen_change_state(bool enabled)
5031{
5032 static DEFINE_MUTEX(state_mutex);
5033
5034 struct mem_cgroup *memcg;
5035
5036 cgroup_lock();
5037 cpus_read_lock();
5038 get_online_mems();
5039 mutex_lock(&state_mutex);
5040
5041 if (enabled == lru_gen_enabled())
5042 goto unlock;
5043
5044 if (enabled)
5045 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5046 else
5047 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5048
5049 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5050 do {
5051 int nid;
5052
5053 for_each_node(nid) {
5054 struct lruvec *lruvec = get_lruvec(memcg, nid);
5055
5056 if (!lruvec)
5057 continue;
5058
5059 spin_lock_irq(&lruvec->lru_lock);
5060
5061 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5062 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5063
5064 lruvec->lrugen.enabled = enabled;
5065
5066 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5067 spin_unlock_irq(&lruvec->lru_lock);
5068 cond_resched();
5069 spin_lock_irq(&lruvec->lru_lock);
5070 }
5071
5072 spin_unlock_irq(&lruvec->lru_lock);
5073 }
5074
5075 cond_resched();
5076 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5077unlock:
5078 mutex_unlock(&state_mutex);
5079 put_online_mems();
5080 cpus_read_unlock();
5081 cgroup_unlock();
5082}
5083
5084/******************************************************************************
5085 * sysfs interface
5086 ******************************************************************************/
5087
5088static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5089{
5090 unsigned int caps = 0;
5091
5092 if (get_cap(LRU_GEN_CORE))
5093 caps |= BIT(LRU_GEN_CORE);
5094
5095 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5096 caps |= BIT(LRU_GEN_MM_WALK);
5097
5098 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
5099 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5100
5101 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5102}
5103
5104static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5105 const char *buf, size_t len)
5106{
5107 int i;
5108 unsigned int caps;
5109
5110 if (tolower(*buf) == 'n')
5111 caps = 0;
5112 else if (tolower(*buf) == 'y')
5113 caps = -1;
5114 else if (kstrtouint(buf, 0, &caps))
5115 return -EINVAL;
5116
5117 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5118 bool enabled = caps & BIT(i);
5119
5120 if (i == LRU_GEN_CORE)
5121 lru_gen_change_state(enabled);
5122 else if (enabled)
5123 static_branch_enable(&lru_gen_caps[i]);
5124 else
5125 static_branch_disable(&lru_gen_caps[i]);
5126 }
5127
5128 return len;
5129}
5130
5131static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5132 enabled, 0644, show_enabled, store_enabled
5133);
5134
5135static struct attribute *lru_gen_attrs[] = {
5136 &lru_gen_enabled_attr.attr,
5137 NULL
5138};
5139
5140static struct attribute_group lru_gen_attr_group = {
5141 .name = "lru_gen",
5142 .attrs = lru_gen_attrs,
5143};
5144
5145/******************************************************************************
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005146 * initialization
5147 ******************************************************************************/
5148
5149void lru_gen_init_lruvec(struct lruvec *lruvec)
5150{
5151 int gen, type, zone;
5152 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5153
5154 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005155 lrugen->enabled = lru_gen_enabled();
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005156
5157 for_each_gen_type_zone(gen, type, zone)
5158 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005159
5160 lruvec->mm_state.seq = MIN_NR_GENS;
5161 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005162}
5163
5164#ifdef CONFIG_MEMCG
5165void lru_gen_init_memcg(struct mem_cgroup *memcg)
5166{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005167 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5168 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005169}
5170
5171void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5172{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005173 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005174 int nid;
5175
5176 for_each_node(nid) {
5177 struct lruvec *lruvec = get_lruvec(memcg, nid);
5178
5179 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5180 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005181
5182 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5183 bitmap_free(lruvec->mm_state.filters[i]);
5184 lruvec->mm_state.filters[i] = NULL;
5185 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005186 }
5187}
5188#endif
5189
5190static int __init init_lru_gen(void)
5191{
5192 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5193 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5194
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005195 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5196 pr_err("lru_gen: failed to create sysfs group\n");
5197
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005198 return 0;
5199};
5200late_initcall(init_lru_gen);
5201
Yu Zhao37397872022-09-18 02:00:03 -06005202#else /* !CONFIG_LRU_GEN */
5203
5204static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5205{
5206}
5207
5208static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5209{
5210}
5211
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005212#endif /* CONFIG_LRU_GEN */
5213
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005214static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005215{
5216 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005217 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005218 unsigned long nr_to_scan;
5219 enum lru_list lru;
5220 unsigned long nr_reclaimed = 0;
5221 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5222 struct blk_plug plug;
Mel Gorman1a501902014-06-04 16:10:49 -07005223 bool scan_adjusted;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005224
Yu Zhao37397872022-09-18 02:00:03 -06005225 if (lru_gen_enabled()) {
5226 lru_gen_shrink_lruvec(lruvec, sc);
5227 return;
5228 }
5229
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005230 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005231
Mel Gormane82e0562013-07-03 15:01:44 -07005232 /* Record the original scan target for proportional adjustments later */
5233 memcpy(targets, nr, sizeof(nr));
5234
Mel Gorman1a501902014-06-04 16:10:49 -07005235 /*
5236 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5237 * event that can occur when there is little memory pressure e.g.
5238 * multiple streaming readers/writers. Hence, we do not abort scanning
5239 * when the requested number of pages are reclaimed when scanning at
5240 * DEF_PRIORITY on the assumption that the fact we are direct
5241 * reclaiming implies that kswapd is not keeping up and it is best to
5242 * do a batch of work at once. For memcg reclaim one check is made to
5243 * abort proportional reclaim if either the file or anon lru has already
5244 * dropped to zero at the first pass.
5245 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005246 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
Mel Gorman1a501902014-06-04 16:10:49 -07005247 sc->priority == DEF_PRIORITY);
5248
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005249 blk_start_plug(&plug);
5250 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5251 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005252 unsigned long nr_anon, nr_file, percentage;
5253 unsigned long nr_scanned;
5254
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005255 for_each_evictable_lru(lru) {
5256 if (nr[lru]) {
5257 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5258 nr[lru] -= nr_to_scan;
5259
5260 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005261 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005262 }
5263 }
Mel Gormane82e0562013-07-03 15:01:44 -07005264
Michal Hockobd041732016-12-02 17:26:48 -08005265 cond_resched();
5266
Mel Gormane82e0562013-07-03 15:01:44 -07005267 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
5268 continue;
5269
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005270 /*
Mel Gormane82e0562013-07-03 15:01:44 -07005271 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07005272 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07005273 * proportionally what was requested by get_scan_count(). We
5274 * stop reclaiming one LRU and reduce the amount scanning
5275 * proportional to the original scan target.
5276 */
5277 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5278 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5279
Mel Gorman1a501902014-06-04 16:10:49 -07005280 /*
5281 * It's just vindictive to attack the larger once the smaller
5282 * has gone to zero. And given the way we stop scanning the
5283 * smaller below, this makes sure that we only make one nudge
5284 * towards proportionality once we've got nr_to_reclaim.
5285 */
5286 if (!nr_file || !nr_anon)
5287 break;
5288
Mel Gormane82e0562013-07-03 15:01:44 -07005289 if (nr_file > nr_anon) {
5290 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5291 targets[LRU_ACTIVE_ANON] + 1;
5292 lru = LRU_BASE;
5293 percentage = nr_anon * 100 / scan_target;
5294 } else {
5295 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5296 targets[LRU_ACTIVE_FILE] + 1;
5297 lru = LRU_FILE;
5298 percentage = nr_file * 100 / scan_target;
5299 }
5300
5301 /* Stop scanning the smaller of the LRU */
5302 nr[lru] = 0;
5303 nr[lru + LRU_ACTIVE] = 0;
5304
5305 /*
5306 * Recalculate the other LRU scan count based on its original
5307 * scan target and the percentage scanning already complete
5308 */
5309 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5310 nr_scanned = targets[lru] - nr[lru];
5311 nr[lru] = targets[lru] * (100 - percentage) / 100;
5312 nr[lru] -= min(nr[lru], nr_scanned);
5313
5314 lru += LRU_ACTIVE;
5315 nr_scanned = targets[lru] - nr[lru];
5316 nr[lru] = targets[lru] * (100 - percentage) / 100;
5317 nr[lru] -= min(nr[lru], nr_scanned);
5318
5319 scan_adjusted = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005320 }
5321 blk_finish_plug(&plug);
5322 sc->nr_reclaimed += nr_reclaimed;
5323
5324 /*
5325 * Even if we did not try to evict anon pages at all, we want to
5326 * rebalance the anon lru active/inactive ratio.
5327 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005328 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5329 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005330 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5331 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005332}
5333
Mel Gorman23b9da52012-05-29 15:06:20 -07005334/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005335static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005336{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005337 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005338 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005339 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005340 return true;
5341
5342 return false;
5343}
5344
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005345/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005346 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5347 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5348 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005349 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005350 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005351 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005352static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005353 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005354 struct scan_control *sc)
5355{
5356 unsigned long pages_for_compaction;
5357 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005358 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005359
5360 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005361 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005362 return false;
5363
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005364 /*
5365 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5366 * number of pages that were scanned. This will return to the caller
5367 * with the risk reclaim/compaction and the resulting allocation attempt
5368 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5369 * allocations through requiring that the full LRU list has been scanned
5370 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5371 * scan, but that approximation was wrong, and there were corner cases
5372 * where always a non-zero amount of pages were scanned.
5373 */
5374 if (!nr_reclaimed)
5375 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005376
Mel Gorman3e7d3442011-01-13 15:45:56 -08005377 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005378 for (z = 0; z <= sc->reclaim_idx; z++) {
5379 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005380 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005381 continue;
5382
5383 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005384 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005385 case COMPACT_CONTINUE:
5386 return false;
5387 default:
5388 /* check next zone */
5389 ;
5390 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005391 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005392
5393 /*
5394 * If we have not reclaimed enough pages for compaction and the
5395 * inactive lists are large enough, continue reclaiming
5396 */
5397 pages_for_compaction = compact_gap(sc->order);
5398 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005399 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005400 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5401
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005402 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005403}
5404
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005405static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005406{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005407 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005408 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005409
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005410 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005411 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005412 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005413 unsigned long reclaimed;
5414 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005415 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08005416
Xunlei Pange3336ca2020-09-04 16:35:27 -07005417 /*
5418 * This loop can become CPU-bound when target memcgs
5419 * aren't eligible for reclaim - either because they
5420 * don't have any reclaimable pages, or because their
5421 * memory is explicitly protected. Avoid soft lockups.
5422 */
5423 cond_resched();
5424
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005425 trace_android_vh_shrink_node_memcgs(memcg, &skip);
5426 if (skip)
5427 continue;
5428
Chris Down45c7f7e2020-08-06 23:22:05 -07005429 mem_cgroup_calculate_protection(target_memcg, memcg);
5430
5431 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005432 /*
5433 * Hard protection.
5434 * If there is no reclaimable memory, OOM.
5435 */
5436 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005437 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005438 /*
5439 * Soft protection.
5440 * Respect the protection only as long as
5441 * there is an unprotected supply
5442 * of reclaimable memory from other cgroups.
5443 */
5444 if (!sc->memcg_low_reclaim) {
5445 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005446 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005447 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005448 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005449 }
5450
Johannes Weinerd2af3392019-11-30 17:55:43 -08005451 reclaimed = sc->nr_reclaimed;
5452 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005453
5454 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005455
Johannes Weinerd2af3392019-11-30 17:55:43 -08005456 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5457 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005458
Johannes Weinerd2af3392019-11-30 17:55:43 -08005459 /* Record the group's reclaim efficiency */
5460 vmpressure(sc->gfp_mask, memcg, false,
5461 sc->nr_scanned - scanned,
5462 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005463
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005464 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5465}
5466
Liu Song6c9e09072020-01-30 22:14:08 -08005467static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005468{
5469 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005470 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005471 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005472 bool reclaimable = false;
5473
Johannes Weiner1b051172019-11-30 17:55:52 -08005474 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5475
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005476again:
5477 memset(&sc->nr, 0, sizeof(sc->nr));
5478
5479 nr_reclaimed = sc->nr_reclaimed;
5480 nr_scanned = sc->nr_scanned;
5481
Yu Zhao6d313442022-09-18 02:00:00 -06005482 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005483
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005484 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005485
Johannes Weinerd2af3392019-11-30 17:55:43 -08005486 if (reclaim_state) {
5487 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5488 reclaim_state->reclaimed_slab = 0;
5489 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005490
Johannes Weinerd2af3392019-11-30 17:55:43 -08005491 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005492 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005493 sc->nr_scanned - nr_scanned,
5494 sc->nr_reclaimed - nr_reclaimed);
5495
5496 if (sc->nr_reclaimed - nr_reclaimed)
5497 reclaimable = true;
5498
5499 if (current_is_kswapd()) {
5500 /*
5501 * If reclaim is isolating dirty pages under writeback,
5502 * it implies that the long-lived page allocation rate
5503 * is exceeding the page laundering rate. Either the
5504 * global limits are not being effective at throttling
5505 * processes due to the page distribution throughout
5506 * zones or there is heavy usage of a slow backing
5507 * device. The only option is to throttle from reclaim
5508 * context which is not ideal as there is no guarantee
5509 * the dirtying process is throttled in the same way
5510 * balance_dirty_pages() manages.
5511 *
5512 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5513 * count the number of pages under pages flagged for
5514 * immediate reclaim and stall if any are encountered
5515 * in the nr_immediate check below.
5516 */
5517 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5518 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005519
Johannes Weinerd2af3392019-11-30 17:55:43 -08005520 /* Allow kswapd to start writing pages during reclaim.*/
5521 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5522 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005523
5524 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005525 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005526 * reclaim and under writeback (nr_immediate), it
5527 * implies that pages are cycling through the LRU
5528 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005529 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005530 if (sc->nr.immediate)
5531 congestion_wait(BLK_RW_ASYNC, HZ/10);
5532 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005533
Johannes Weinerd2af3392019-11-30 17:55:43 -08005534 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005535 * Tag a node/memcg as congested if all the dirty pages
5536 * scanned were backed by a congested BDI and
5537 * wait_iff_congested will stall.
5538 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005539 * Legacy memcg will stall in page writeback so avoid forcibly
5540 * stalling in wait_iff_congested().
5541 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005542 if ((current_is_kswapd() ||
5543 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005544 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005545 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005546
5547 /*
5548 * Stall direct reclaim for IO completions if underlying BDIs
5549 * and node is congested. Allow kswapd to continue until it
5550 * starts encountering unqueued dirty pages or cycling through
5551 * the LRU too quickly.
5552 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005553 if (!current_is_kswapd() && current_may_throttle() &&
5554 !sc->hibernation_mode &&
5555 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005556 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5557
5558 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5559 sc))
5560 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005561
Johannes Weinerc73322d2017-05-03 14:51:51 -07005562 /*
5563 * Kswapd gives up on balancing particular nodes after too
5564 * many failures to reclaim anything from them and goes to
5565 * sleep. On reclaim progress, reset the failure counter. A
5566 * successful direct reclaim run will revive a dormant kswapd.
5567 */
5568 if (reclaimable)
5569 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005570}
5571
Vlastimil Babka53853e22014-10-09 15:27:02 -07005572/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005573 * Returns true if compaction should go ahead for a costly-order request, or
5574 * the allocation would already succeed without compaction. Return false if we
5575 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07005576 */
Mel Gorman4f588332016-07-28 15:46:38 -07005577static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005578{
Mel Gorman31483b62016-07-28 15:45:46 -07005579 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005580 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005581
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005582 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
5583 if (suitable == COMPACT_SUCCESS)
5584 /* Allocation should succeed already. Don't reclaim. */
5585 return true;
5586 if (suitable == COMPACT_SKIPPED)
5587 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005588 return false;
5589
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005590 /*
5591 * Compaction is already possible, but it takes time to run and there
5592 * are potentially other callers using the pages just freed. So proceed
5593 * with reclaim to make a buffer of free pages available to give
5594 * compaction a reasonable chance of completing and allocating the page.
5595 * Note that we won't actually reclaim the whole buffer in one attempt
5596 * as the target watermark in should_continue_reclaim() is lower. But if
5597 * we are already above the high+gap watermark, don't reclaim at all.
5598 */
5599 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
5600
5601 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005602}
5603
Linus Torvalds1da177e2005-04-16 15:20:36 -07005604/*
5605 * This is the direct reclaim path, for page-allocating processes. We only
5606 * try to reclaim pages from zones which will satisfy the caller's allocation
5607 * request.
5608 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07005609 * If a zone is deemed to be full of pinned pages then just give it a light
5610 * scan then give up on it.
5611 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07005612static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005613{
Mel Gormandd1a2392008-04-28 02:12:17 -07005614 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07005615 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07005616 unsigned long nr_soft_reclaimed;
5617 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07005618 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07005619 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005620
Mel Gormancc715d92012-03-21 16:34:00 -07005621 /*
5622 * If the number of buffer_heads in the machine exceeds the maximum
5623 * allowed level, force direct reclaim to scan the highmem zone as
5624 * highmem pages could be pinning lowmem pages storing buffer_heads
5625 */
Weijie Yang619d0d762014-04-07 15:36:59 -07005626 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07005627 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07005628 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07005629 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07005630 }
Mel Gormancc715d92012-03-21 16:34:00 -07005631
Mel Gormand4debc62010-08-09 17:19:29 -07005632 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07005633 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07005634 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005635 * Take care memory controller reclaiming has small influence
5636 * to global LRU.
5637 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005638 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04005639 if (!cpuset_zone_allowed(zone,
5640 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005641 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005642
Johannes Weiner0b064962014-08-06 16:06:12 -07005643 /*
5644 * If we already have plenty of memory free for
5645 * compaction in this zone, don't free any more.
5646 * Even though compaction is invoked for any
5647 * non-zero order, only frequent costly order
5648 * reclamation is disruptive enough to become a
5649 * noticeable problem, like transparent huge
5650 * page allocations.
5651 */
5652 if (IS_ENABLED(CONFIG_COMPACTION) &&
5653 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07005654 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07005655 sc->compaction_ready = true;
5656 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07005657 }
Johannes Weiner0b064962014-08-06 16:06:12 -07005658
Andrew Morton0608f432013-09-24 15:27:41 -07005659 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07005660 * Shrink each node in the zonelist once. If the
5661 * zonelist is ordered by zone (not the default) then a
5662 * node may be shrunk multiple times but in that case
5663 * the user prefers lower zones being preserved.
5664 */
5665 if (zone->zone_pgdat == last_pgdat)
5666 continue;
5667
5668 /*
Andrew Morton0608f432013-09-24 15:27:41 -07005669 * This steals pages from memory cgroups over softlimit
5670 * and returns the number of reclaimed pages and
5671 * scanned pages. This works for global memory pressure
5672 * and balancing, not for a memcg's limit.
5673 */
5674 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07005675 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07005676 sc->order, sc->gfp_mask,
5677 &nr_soft_scanned);
5678 sc->nr_reclaimed += nr_soft_reclaimed;
5679 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07005680 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005681 }
Nick Piggin408d8542006-09-25 23:31:27 -07005682
Mel Gorman79dafcd2016-07-28 15:45:53 -07005683 /* See comment about same check for global reclaim above */
5684 if (zone->zone_pgdat == last_pgdat)
5685 continue;
5686 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07005687 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005688 }
Mel Gormane0c23272011-10-31 17:09:33 -07005689
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005690 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07005691 * Restore to original mask to avoid the impact on the caller if we
5692 * promoted it to __GFP_HIGHMEM.
5693 */
5694 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005695}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005696
Johannes Weinerb9107182019-11-30 17:55:59 -08005697static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005698{
Johannes Weinerb9107182019-11-30 17:55:59 -08005699 struct lruvec *target_lruvec;
5700 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005701
Yu Zhao37397872022-09-18 02:00:03 -06005702 if (lru_gen_enabled())
5703 return;
5704
Johannes Weinerb9107182019-11-30 17:55:59 -08005705 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07005706 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
5707 target_lruvec->refaults[0] = refaults;
5708 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
5709 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005710}
5711
Linus Torvalds1da177e2005-04-16 15:20:36 -07005712/*
5713 * This is the main entry point to direct page reclaim.
5714 *
5715 * If a full scan of the inactive list fails to free enough memory then we
5716 * are "out of memory" and something needs to be killed.
5717 *
5718 * If the caller is !__GFP_FS then the probability of a failure is reasonably
5719 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02005720 * caller can't do much about. We kick the writeback threads and take explicit
5721 * naps in the hope that some of these pages can be written. But if the
5722 * allocating task holds filesystem locks which prevent writeout this might not
5723 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07005724 *
5725 * returns: 0, if no pages reclaimed
5726 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07005727 */
Mel Gormandac1d272008-04-28 02:12:12 -07005728static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005729 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005730{
Johannes Weiner241994ed2015-02-11 15:26:06 -08005731 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005732 pg_data_t *last_pgdat;
5733 struct zoneref *z;
5734 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005735retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07005736 delayacct_freepages_start();
5737
Johannes Weinerb5ead352019-11-30 17:55:40 -08005738 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07005739 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005740
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005741 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005742 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
5743 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08005744 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07005745 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07005746
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005747 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07005748 break;
5749
5750 if (sc->compaction_ready)
5751 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005752
5753 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08005754 * If we're getting trouble reclaiming, start doing
5755 * writepage even in laptop mode.
5756 */
5757 if (sc->priority < DEF_PRIORITY - 2)
5758 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07005759 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005760
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005761 last_pgdat = NULL;
5762 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
5763 sc->nodemask) {
5764 if (zone->zone_pgdat == last_pgdat)
5765 continue;
5766 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08005767
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005768 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08005769
5770 if (cgroup_reclaim(sc)) {
5771 struct lruvec *lruvec;
5772
5773 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
5774 zone->zone_pgdat);
5775 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
5776 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005777 }
5778
Keika Kobayashi873b4772008-07-25 01:48:52 -07005779 delayacct_freepages_end();
5780
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005781 if (sc->nr_reclaimed)
5782 return sc->nr_reclaimed;
5783
Mel Gorman0cee34f2012-01-12 17:19:49 -08005784 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07005785 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08005786 return 1;
5787
Johannes Weinerb91ac372019-11-30 17:56:02 -08005788 /*
5789 * We make inactive:active ratio decisions based on the node's
5790 * composition of memory, but a restrictive reclaim_idx or a
5791 * memory.low cgroup setting can exempt large amounts of
5792 * memory from reclaim. Neither of which are very common, so
5793 * instead of doing costly eligibility calculations of the
5794 * entire cgroup subtree up front, we assume the estimates are
5795 * good, and retry with forcible deactivation if that fails.
5796 */
5797 if (sc->skipped_deactivate) {
5798 sc->priority = initial_priority;
5799 sc->force_deactivate = 1;
5800 sc->skipped_deactivate = 0;
5801 goto retry;
5802 }
5803
Johannes Weiner241994ed2015-02-11 15:26:06 -08005804 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07005805 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08005806 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08005807 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07005808 sc->memcg_low_reclaim = 1;
5809 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005810 goto retry;
5811 }
5812
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005813 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005814}
5815
Johannes Weinerc73322d2017-05-03 14:51:51 -07005816static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07005817{
5818 struct zone *zone;
5819 unsigned long pfmemalloc_reserve = 0;
5820 unsigned long free_pages = 0;
5821 int i;
5822 bool wmark_ok;
5823
Johannes Weinerc73322d2017-05-03 14:51:51 -07005824 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
5825 return true;
5826
Mel Gorman55150612012-07-31 16:44:35 -07005827 for (i = 0; i <= ZONE_NORMAL; i++) {
5828 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07005829 if (!managed_zone(zone))
5830 continue;
5831
5832 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07005833 continue;
5834
Mel Gorman55150612012-07-31 16:44:35 -07005835 pfmemalloc_reserve += min_wmark_pages(zone);
5836 free_pages += zone_page_state(zone, NR_FREE_PAGES);
5837 }
5838
Mel Gorman675becc2014-06-04 16:07:35 -07005839 /* If there are no reserves (unexpected config) then do not throttle */
5840 if (!pfmemalloc_reserve)
5841 return true;
5842
Mel Gorman55150612012-07-31 16:44:35 -07005843 wmark_ok = free_pages > pfmemalloc_reserve / 2;
5844
5845 /* kswapd must be awake if processes are being throttled */
5846 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005847 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
5848 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005849
Mel Gorman55150612012-07-31 16:44:35 -07005850 wake_up_interruptible(&pgdat->kswapd_wait);
5851 }
5852
5853 return wmark_ok;
5854}
5855
5856/*
5857 * Throttle direct reclaimers if backing storage is backed by the network
5858 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
5859 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08005860 * when the low watermark is reached.
5861 *
5862 * Returns true if a fatal signal was delivered during throttling. If this
5863 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07005864 */
Mel Gorman50694c22012-11-26 16:29:48 -08005865static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07005866 nodemask_t *nodemask)
5867{
Mel Gorman675becc2014-06-04 16:07:35 -07005868 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07005869 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07005870 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07005871
5872 /*
5873 * Kernel threads should not be throttled as they may be indirectly
5874 * responsible for cleaning pages necessary for reclaim to make forward
5875 * progress. kjournald for example may enter direct reclaim while
5876 * committing a transaction where throttling it could forcing other
5877 * processes to block on log_wait_commit().
5878 */
5879 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08005880 goto out;
5881
5882 /*
5883 * If a fatal signal is pending, this process should not throttle.
5884 * It should return quickly so it can exit and free its memory
5885 */
5886 if (fatal_signal_pending(current))
5887 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005888
Mel Gorman675becc2014-06-04 16:07:35 -07005889 /*
5890 * Check if the pfmemalloc reserves are ok by finding the first node
5891 * with a usable ZONE_NORMAL or lower zone. The expectation is that
5892 * GFP_KERNEL will be required for allocating network buffers when
5893 * swapping over the network so ZONE_HIGHMEM is unusable.
5894 *
5895 * Throttling is based on the first usable node and throttled processes
5896 * wait on a queue until kswapd makes progress and wakes them. There
5897 * is an affinity then between processes waking up and where reclaim
5898 * progress has been made assuming the process wakes on the same node.
5899 * More importantly, processes running on remote nodes will not compete
5900 * for remote pfmemalloc reserves and processes on different nodes
5901 * should make reasonable progress.
5902 */
5903 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08005904 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07005905 if (zone_idx(zone) > ZONE_NORMAL)
5906 continue;
5907
5908 /* Throttle based on the first usable node */
5909 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07005910 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07005911 goto out;
5912 break;
5913 }
5914
5915 /* If no zone was usable by the allocation flags then do not throttle */
5916 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08005917 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005918
Mel Gorman68243e72012-07-31 16:44:39 -07005919 /* Account for the throttling */
5920 count_vm_event(PGSCAN_DIRECT_THROTTLE);
5921
Mel Gorman55150612012-07-31 16:44:35 -07005922 /*
5923 * If the caller cannot enter the filesystem, it's possible that it
5924 * is due to the caller holding an FS lock or performing a journal
5925 * transaction in the case of a filesystem like ext[3|4]. In this case,
5926 * it is not safe to block on pfmemalloc_wait as kswapd could be
5927 * blocked waiting on the same lock. Instead, throttle for up to a
5928 * second before continuing.
5929 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07005930 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07005931 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07005932 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07005933 else
5934 /* Throttle until kswapd wakes the process */
5935 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
5936 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08005937
Mel Gorman50694c22012-11-26 16:29:48 -08005938 if (fatal_signal_pending(current))
5939 return true;
5940
5941out:
5942 return false;
Mel Gorman55150612012-07-31 16:44:35 -07005943}
5944
Mel Gormandac1d272008-04-28 02:12:12 -07005945unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07005946 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08005947{
Mel Gorman33906bc2010-08-09 17:19:16 -07005948 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005949 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08005950 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005951 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07005952 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07005953 .order = order,
5954 .nodemask = nodemask,
5955 .priority = DEF_PRIORITY,
5956 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005957 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07005958 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08005959 };
5960
Mel Gorman55150612012-07-31 16:44:35 -07005961 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07005962 * scan_control uses s8 fields for order, priority, and reclaim_idx.
5963 * Confirm they are large enough for max values.
5964 */
5965 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
5966 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
5967 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
5968
5969 /*
Mel Gorman50694c22012-11-26 16:29:48 -08005970 * Do not enter reclaim if fatal signal was delivered while throttled.
5971 * 1 is returned so that the page allocator does not OOM kill at this
5972 * point.
Mel Gorman55150612012-07-31 16:44:35 -07005973 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005974 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07005975 return 1;
5976
Andrew Morton1732d2b012019-07-16 16:26:15 -07005977 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005978 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07005979
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005980 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07005981
5982 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005983 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07005984
5985 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005986}
5987
Andrew Mortonc255a452012-07-31 16:43:02 -07005988#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08005989
Michal Hockod2e5fb92019-08-30 16:04:50 -07005990/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005991unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005992 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07005993 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07005994 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07005995{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005996 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07005997 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07005998 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07005999 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006000 .may_writepage = !laptop_mode,
6001 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006002 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006003 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006004 };
Ying Han0ae5e892011-05-26 16:25:25 -07006005
Michal Hockod2e5fb92019-08-30 16:04:50 -07006006 WARN_ON_ONCE(!current->reclaim_state);
6007
Balbir Singh4e416952009-09-23 15:56:39 -07006008 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6009 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006010
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006011 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006012 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006013
Balbir Singh4e416952009-09-23 15:56:39 -07006014 /*
6015 * NOTE: Although we can get the priority field, using it
6016 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006017 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006018 * will pick up pages from other mem cgroup's as well. We hack
6019 * the priority and make it zero.
6020 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006021 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006022
6023 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6024
Ying Han0ae5e892011-05-26 16:25:25 -07006025 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006026
Balbir Singh4e416952009-09-23 15:56:39 -07006027 return sc.nr_reclaimed;
6028}
6029
Johannes Weiner72835c82012-01-12 17:18:32 -08006030unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006031 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006032 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006033 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08006034{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006035 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006036 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006037 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006038 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006039 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006040 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006041 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006042 .target_mem_cgroup = memcg,
6043 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006044 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006045 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006046 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07006047 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006048 /*
6049 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6050 * equal pressure on all the nodes. This is based on the assumption that
6051 * the reclaim does not bail out early.
6052 */
6053 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006054
Andrew Morton1732d2b012019-07-16 16:26:15 -07006055 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006056 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006057 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006058
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006059 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006060
Vlastimil Babka499118e2017-05-08 15:59:50 -07006061 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006062 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006063 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006064
6065 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006066}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006067EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006068#endif
6069
Yu Zhao37397872022-09-18 02:00:03 -06006070static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006071{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006072 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006073 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006074
Yu Zhao37397872022-09-18 02:00:03 -06006075 if (lru_gen_enabled()) {
6076 lru_gen_age_node(pgdat, sc);
6077 return;
6078 }
6079
Dave Hansen2f368a92021-09-02 14:59:23 -07006080 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006081 return;
6082
Johannes Weinerb91ac372019-11-30 17:56:02 -08006083 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6084 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6085 return;
6086
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006087 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6088 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006089 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6090 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6091 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006092 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6093 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006094}
6095
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006096static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006097{
6098 int i;
6099 struct zone *zone;
6100
6101 /*
6102 * Check for watermark boosts top-down as the higher zones
6103 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006104 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006105 * start prematurely when there is no boosting and a lower
6106 * zone is balanced.
6107 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006108 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006109 zone = pgdat->node_zones + i;
6110 if (!managed_zone(zone))
6111 continue;
6112
6113 if (zone->watermark_boost)
6114 return true;
6115 }
6116
6117 return false;
6118}
6119
Mel Gormane716f2e2017-05-03 14:53:45 -07006120/*
6121 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006122 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006123 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006124static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006125{
Mel Gormane716f2e2017-05-03 14:53:45 -07006126 int i;
6127 unsigned long mark = -1;
6128 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006129
Mel Gorman1c308442018-12-28 00:35:52 -08006130 /*
6131 * Check watermarks bottom-up as lower zones are more likely to
6132 * meet watermarks.
6133 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006134 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006135 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006136
Mel Gormane716f2e2017-05-03 14:53:45 -07006137 if (!managed_zone(zone))
6138 continue;
6139
6140 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006141 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006142 return true;
6143 }
6144
6145 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006146 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006147 * need balancing by definition. This can happen if a zone-restricted
6148 * allocation tries to wake a remote kswapd.
6149 */
6150 if (mark == -1)
6151 return true;
6152
6153 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006154}
6155
Mel Gorman631b6e02017-05-03 14:53:41 -07006156/* Clear pgdat state for congested, dirty or under writeback. */
6157static void clear_pgdat_congested(pg_data_t *pgdat)
6158{
Johannes Weiner1b051172019-11-30 17:55:52 -08006159 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6160
6161 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006162 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6163 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6164}
6165
Mel Gorman1741c872011-01-13 15:46:21 -08006166/*
Mel Gorman55150612012-07-31 16:44:35 -07006167 * Prepare kswapd for sleeping. This verifies that there are no processes
6168 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6169 *
6170 * Returns true if kswapd is ready to sleep
6171 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006172static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6173 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006174{
Mel Gorman55150612012-07-31 16:44:35 -07006175 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006176 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006177 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006178 * race between when kswapd checks the watermarks and a process gets
6179 * throttled. There is also a potential race if processes get
6180 * throttled, kswapd wakes, a large process exits thereby balancing the
6181 * zones, which causes kswapd to exit balance_pgdat() before reaching
6182 * the wake up checks. If kswapd is going to sleep, no process should
6183 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6184 * the wake up is premature, processes will wake kswapd and get
6185 * throttled again. The difference from wake ups in balance_pgdat() is
6186 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006187 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006188 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6189 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006190
Johannes Weinerc73322d2017-05-03 14:51:51 -07006191 /* Hopeless node, leave it to direct reclaim */
6192 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6193 return true;
6194
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006195 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006196 clear_pgdat_congested(pgdat);
6197 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006198 }
6199
Shantanu Goel333b0a42017-05-03 14:53:38 -07006200 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006201}
6202
Linus Torvalds1da177e2005-04-16 15:20:36 -07006203/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006204 * kswapd shrinks a node of pages that are at or below the highest usable
6205 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006206 *
6207 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006208 * reclaim or if the lack of progress was due to pages under writeback.
6209 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006210 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006211static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006212 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006213{
Mel Gorman1d82de62016-07-28 15:45:43 -07006214 struct zone *zone;
6215 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006216
Mel Gorman1d82de62016-07-28 15:45:43 -07006217 /* Reclaim a number of pages proportional to the number of zones */
6218 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006219 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006220 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006221 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006222 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006223
Mel Gorman1d82de62016-07-28 15:45:43 -07006224 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006225 }
6226
Mel Gorman1d82de62016-07-28 15:45:43 -07006227 /*
6228 * Historically care was taken to put equal pressure on all zones but
6229 * now pressure is applied based on node LRU order.
6230 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006231 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006232
6233 /*
6234 * Fragmentation may mean that the system cannot be rebalanced for
6235 * high-order allocations. If twice the allocation size has been
6236 * reclaimed then recheck watermarks only at order-0 to prevent
6237 * excessive reclaim. Assume that a process requested a high-order
6238 * can direct reclaim/compact.
6239 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006240 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006241 sc->order = 0;
6242
Mel Gormanb8e83b92013-07-03 15:01:45 -07006243 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006244}
6245
Mel Gormanc49c2c42021-06-28 19:42:21 -07006246/* Page allocator PCP high watermark is lowered if reclaim is active. */
6247static inline void
6248update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6249{
6250 int i;
6251 struct zone *zone;
6252
6253 for (i = 0; i <= highest_zoneidx; i++) {
6254 zone = pgdat->node_zones + i;
6255
6256 if (!managed_zone(zone))
6257 continue;
6258
6259 if (active)
6260 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6261 else
6262 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6263 }
6264}
6265
6266static inline void
6267set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6268{
6269 update_reclaim_active(pgdat, highest_zoneidx, true);
6270}
6271
6272static inline void
6273clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6274{
6275 update_reclaim_active(pgdat, highest_zoneidx, false);
6276}
6277
Mel Gorman75485362013-07-03 15:01:42 -07006278/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006279 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6280 * that are eligible for use by the caller until at least one zone is
6281 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006282 *
Mel Gorman1d82de62016-07-28 15:45:43 -07006283 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006284 *
6285 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07006286 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08006287 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07006288 * or lower is eligible for reclaim until at least one usable zone is
6289 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006290 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006291static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006292{
Linus Torvalds1da177e2005-04-16 15:20:36 -07006293 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07006294 unsigned long nr_soft_reclaimed;
6295 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07006296 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08006297 unsigned long nr_boost_reclaim;
6298 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6299 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07006300 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08006301 struct scan_control sc = {
6302 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07006303 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006304 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08006305 };
Omar Sandoval93781322018-06-07 17:07:02 -07006306
Andrew Morton1732d2b012019-07-16 16:26:15 -07006307 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07006308 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006309 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006310
Christoph Lameterf8891e52006-06-30 01:55:45 -07006311 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006312
Mel Gorman1c308442018-12-28 00:35:52 -08006313 /*
6314 * Account for the reclaim boost. Note that the zone boost is left in
6315 * place so that parallel allocations that are near the watermark will
6316 * stall or direct reclaim until kswapd is finished.
6317 */
6318 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006319 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006320 zone = pgdat->node_zones + i;
6321 if (!managed_zone(zone))
6322 continue;
6323
6324 nr_boost_reclaim += zone->watermark_boost;
6325 zone_boosts[i] = zone->watermark_boost;
6326 }
6327 boosted = nr_boost_reclaim;
6328
6329restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006330 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006331 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006332 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006333 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006334 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006335 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006336 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006337
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006338 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006339
Mel Gorman86c79f62016-07-28 15:45:59 -07006340 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006341 * If the number of buffer_heads exceeds the maximum allowed
6342 * then consider reclaiming from all zones. This has a dual
6343 * purpose -- on 64-bit systems it is expected that
6344 * buffer_heads are stripped during active rotation. On 32-bit
6345 * systems, highmem pages can pin lowmem memory and shrinking
6346 * buffers can relieve lowmem pressure. Reclaim may still not
6347 * go ahead if all eligible zones for the original allocation
6348 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006349 */
6350 if (buffer_heads_over_limit) {
6351 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6352 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006353 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006354 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006355
Mel Gorman970a39a2016-07-28 15:46:35 -07006356 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006357 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006358 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006359 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006360
Mel Gorman86c79f62016-07-28 15:45:59 -07006361 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006362 * If the pgdat is imbalanced then ignore boosting and preserve
6363 * the watermarks for a later time and restart. Note that the
6364 * zone watermarks will be still reset at the end of balancing
6365 * on the grounds that the normal reclaim should be enough to
6366 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006367 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006368 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006369 if (!balanced && nr_boost_reclaim) {
6370 nr_boost_reclaim = 0;
6371 goto restart;
6372 }
6373
6374 /*
6375 * If boosting is not active then only reclaim if there are no
6376 * eligible zones. Note that sc.reclaim_idx is not used as
6377 * buffer_heads_over_limit may have adjusted it.
6378 */
6379 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006380 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006381
Mel Gorman1c308442018-12-28 00:35:52 -08006382 /* Limit the priority of boosting to avoid reclaim writeback */
6383 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6384 raise_priority = false;
6385
6386 /*
6387 * Do not writeback or swap pages for boosted reclaim. The
6388 * intent is to relieve pressure not issue sub-optimal IO
6389 * from reclaim context. If no pages are reclaimed, the
6390 * reclaim will be aborted.
6391 */
6392 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6393 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006394
Linus Torvalds1da177e2005-04-16 15:20:36 -07006395 /*
Yu Zhao37397872022-09-18 02:00:03 -06006396 * Do some background aging, to give pages a chance to be
6397 * referenced before reclaiming. All pages are rotated
6398 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07006399 */
Yu Zhao37397872022-09-18 02:00:03 -06006400 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006401
6402 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006403 * If we're getting trouble reclaiming, start doing writepage
6404 * even in laptop mode.
6405 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006406 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006407 sc.may_writepage = 1;
6408
Mel Gorman1d82de62016-07-28 15:45:43 -07006409 /* Call soft limit reclaim before calling shrink_node. */
6410 sc.nr_scanned = 0;
6411 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006412 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006413 sc.gfp_mask, &nr_soft_scanned);
6414 sc.nr_reclaimed += nr_soft_reclaimed;
6415
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006416 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006417 * There should be no need to raise the scanning priority if
6418 * enough pages are already being scanned that that high
6419 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006420 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006421 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006422 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006423
6424 /*
6425 * If the low watermark is met there is no need for processes
6426 * to be throttled on pfmemalloc_wait as they should not be
6427 * able to safely make forward progress. Wake them
6428 */
6429 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006430 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006431 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006432
Mel Gormanb8e83b92013-07-03 15:01:45 -07006433 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006434 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006435 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006436 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006437 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006438 break;
6439
6440 /*
6441 * Raise priority if scanning rate is too low or there was no
6442 * progress in reclaiming pages
6443 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006444 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006445 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6446
6447 /*
6448 * If reclaim made no progress for a boost, stop reclaim as
6449 * IO cannot be queued and it could be an infinite loop in
6450 * extreme circumstances.
6451 */
6452 if (nr_boost_reclaim && !nr_reclaimed)
6453 break;
6454
Johannes Weinerc73322d2017-05-03 14:51:51 -07006455 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006456 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006457 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006458
Johannes Weinerc73322d2017-05-03 14:51:51 -07006459 if (!sc.nr_reclaimed)
6460 pgdat->kswapd_failures++;
6461
Mel Gormanb8e83b92013-07-03 15:01:45 -07006462out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006463 clear_reclaim_active(pgdat, highest_zoneidx);
6464
Mel Gorman1c308442018-12-28 00:35:52 -08006465 /* If reclaim was boosted, account for the reclaim done in this pass */
6466 if (boosted) {
6467 unsigned long flags;
6468
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006469 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006470 if (!zone_boosts[i])
6471 continue;
6472
6473 /* Increments are under the zone lock */
6474 zone = pgdat->node_zones + i;
6475 spin_lock_irqsave(&zone->lock, flags);
6476 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6477 spin_unlock_irqrestore(&zone->lock, flags);
6478 }
6479
6480 /*
6481 * As there is now likely space, wakeup kcompact to defragment
6482 * pageblocks.
6483 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006484 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006485 }
6486
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006487 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006488 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006489 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006490 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006491
Mel Gorman0abdee22011-01-13 15:46:22 -08006492 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006493 * Return the order kswapd stopped reclaiming at as
6494 * prepare_kswapd_sleep() takes it into account. If another caller
6495 * entered the allocator slow path while kswapd was awake, order will
6496 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006497 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006498 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006499}
6500
Mel Gormane716f2e2017-05-03 14:53:45 -07006501/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006502 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6503 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6504 * not a valid index then either kswapd runs for first time or kswapd couldn't
6505 * sleep after previous reclaim attempt (node is still unbalanced). In that
6506 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006507 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006508static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6509 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006510{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006511 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006512
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006513 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006514}
6515
Mel Gorman38087d92016-07-28 15:45:49 -07006516static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006517 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006518{
6519 long remaining = 0;
6520 DEFINE_WAIT(wait);
6521
6522 if (freezing(current) || kthread_should_stop())
6523 return;
6524
6525 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6526
Shantanu Goel333b0a42017-05-03 14:53:38 -07006527 /*
6528 * Try to sleep for a short interval. Note that kcompactd will only be
6529 * woken if it is possible to sleep for a short interval. This is
6530 * deliberate on the assumption that if reclaim cannot keep an
6531 * eligible zone balanced that it's also unlikely that compaction will
6532 * succeed.
6533 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006534 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006535 /*
6536 * Compaction records what page blocks it recently failed to
6537 * isolate pages from and skips them in the future scanning.
6538 * When kswapd is going to sleep, it is reasonable to assume
6539 * that pages and compaction may succeed so reset the cache.
6540 */
6541 reset_isolation_suitable(pgdat);
6542
6543 /*
6544 * We have freed the memory, now we should compact it to make
6545 * allocation of the requested order possible.
6546 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006547 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006548
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006549 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006550
6551 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006552 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006553 * order. The values will either be from a wakeup request or
6554 * the previous request that slept prematurely.
6555 */
6556 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006557 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6558 kswapd_highest_zoneidx(pgdat,
6559 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006560
6561 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6562 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006563 }
6564
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006565 finish_wait(&pgdat->kswapd_wait, &wait);
6566 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6567 }
6568
6569 /*
6570 * After a short sleep, check if it was a premature sleep. If not, then
6571 * go fully to sleep until explicitly woken up.
6572 */
Mel Gormand9f21d42016-07-28 15:46:41 -07006573 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006574 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006575 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6576
6577 /*
6578 * vmstat counters are not perfectly accurate and the estimated
6579 * value for counters such as NR_FREE_PAGES can deviate from the
6580 * true value by nr_online_cpus * threshold. To avoid the zone
6581 * watermarks being breached while under pressure, we reduce the
6582 * per-cpu vmstat threshold while kswapd is awake and restore
6583 * them before going back to sleep.
6584 */
6585 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07006586
6587 if (!kthread_should_stop())
6588 schedule();
6589
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006590 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
6591 } else {
6592 if (remaining)
6593 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
6594 else
6595 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
6596 }
6597 finish_wait(&pgdat->kswapd_wait, &wait);
6598}
6599
Linus Torvalds1da177e2005-04-16 15:20:36 -07006600/*
6601 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006602 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006603 *
6604 * This basically trickles out pages so that we have _some_
6605 * free memory available even if there is no other activity
6606 * that frees anything up. This is needed for things like routing
6607 * etc, where we otherwise might have all activity going on in
6608 * asynchronous contexts that cannot page things out.
6609 *
6610 * If there are applications that are active memory-allocators
6611 * (most normal use), this basically shouldn't matter.
6612 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306613int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006614{
Mel Gormane716f2e2017-05-03 14:53:45 -07006615 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006616 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07006617 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006618 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10306619 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006620
Rusty Russell174596a2009-01-01 10:12:29 +10306621 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07006622 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006623
6624 /*
6625 * Tell the memory management that we're a "memory allocator",
6626 * and that if we need more memory we should get access to it
6627 * regardless (see "__alloc_pages()"). "kswapd" should
6628 * never get caught in the normal page freeing logic.
6629 *
6630 * (Kswapd normally doesn't need memory anyway, but sometimes
6631 * you need a small amount of memory in order to be able to
6632 * page out something else, and this flag essentially protects
6633 * us from recursively trying to free more memory as we're
6634 * trying to free the first piece of memory in the first place).
6635 */
Christoph Lameter930d9152006-01-08 01:00:47 -08006636 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07006637 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07006638
Qian Cai5644e1fb2020-04-01 21:10:12 -07006639 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006640 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006641 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08006642 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07006643
Qian Cai5644e1fb2020-04-01 21:10:12 -07006644 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006645 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6646 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07006647
Mel Gorman38087d92016-07-28 15:45:49 -07006648kswapd_try_sleep:
6649 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006650 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07006651
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006652 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08006653 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006654 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6655 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006656 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006657 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006658
David Rientjes8fe23e02009-12-14 17:58:33 -08006659 ret = try_to_freeze();
6660 if (kthread_should_stop())
6661 break;
6662
6663 /*
6664 * We can speed up thawing tasks if we don't call balance_pgdat
6665 * after returning from the refrigerator
6666 */
Mel Gorman38087d92016-07-28 15:45:49 -07006667 if (ret)
6668 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07006669
Mel Gorman38087d92016-07-28 15:45:49 -07006670 /*
6671 * Reclaim begins at the requested order but if a high-order
6672 * reclaim fails then kswapd falls back to reclaiming for
6673 * order-0. If that happens, kswapd will consider sleeping
6674 * for the order it finished reclaiming at (reclaim_order)
6675 * but kcompactd is woken to compact for the original
6676 * request (alloc_order).
6677 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006678 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07006679 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006680 reclaim_order = balance_pgdat(pgdat, alloc_order,
6681 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07006682 if (reclaim_order < alloc_order)
6683 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006684 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08006685
Johannes Weiner71abdc12014-06-06 14:35:35 -07006686 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07006687
Linus Torvalds1da177e2005-04-16 15:20:36 -07006688 return 0;
6689}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306690EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006691
6692/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07006693 * A zone is low on free memory or too fragmented for high-order memory. If
6694 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
6695 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
6696 * has failed or is not needed, still wake up kcompactd if only compaction is
6697 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006698 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07006699void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006700 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006701{
6702 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07006703 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006704
Mel Gorman6aa303d2016-09-01 16:14:55 -07006705 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006706 return;
6707
David Rientjes5ecd9d42018-04-05 16:25:16 -07006708 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006709 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07006710
Qian Cai5644e1fb2020-04-01 21:10:12 -07006711 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006712 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006713
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006714 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
6715 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006716
6717 if (READ_ONCE(pgdat->kswapd_order) < order)
6718 WRITE_ONCE(pgdat->kswapd_order, order);
6719
Con Kolivas8d0986e2005-09-13 01:25:07 -07006720 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006721 return;
Mel Gormane1a55632016-07-28 15:46:26 -07006722
David Rientjes5ecd9d42018-04-05 16:25:16 -07006723 /* Hopeless node, leave it to direct reclaim if possible */
6724 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006725 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
6726 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07006727 /*
6728 * There may be plenty of free memory available, but it's too
6729 * fragmented for high-order allocations. Wake up kcompactd
6730 * and rely on compaction_suitable() to determine if it's
6731 * needed. If it fails, it will defer subsequent attempts to
6732 * ratelimit its work.
6733 */
6734 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006735 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07006736 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07006737 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07006738
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006739 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07006740 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07006741 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006742}
6743
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006744#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07006745/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006746 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006747 * freed pages.
6748 *
6749 * Rather than trying to age LRUs the aim is to preserve the overall
6750 * LRU order by reclaiming preferentially
6751 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07006752 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006753unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006754{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006755 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006756 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07006757 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07006758 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006759 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07006760 .may_writepage = 1,
6761 .may_unmap = 1,
6762 .may_swap = 1,
6763 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07006764 };
Ying Hana09ed5e2011-05-24 17:12:26 -07006765 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006766 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006767 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006768
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01006769 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07006770 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07006771 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08006772
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006773 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006774
Andrew Morton1732d2b012019-07-16 16:26:15 -07006775 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006776 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006777 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006778
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006779 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006780}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006781#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07006782
Yasunori Goto3218ae12006-06-27 02:53:33 -07006783/*
6784 * This kswapd start function will be called by init and node-hot-add.
6785 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
6786 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07006787void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006788{
6789 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306790 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006791
6792 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07006793 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006794
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306795 trace_android_vh_kswapd_per_node(nid, &skip, true);
6796 if (skip)
6797 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006798 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
6799 if (IS_ERR(pgdat->kswapd)) {
6800 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02006801 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07006802 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07006803 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006804 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07006805}
6806
David Rientjes8fe23e02009-12-14 17:58:33 -08006807/*
Jiang Liud8adde12012-07-11 14:01:52 -07006808 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07006809 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08006810 */
6811void kswapd_stop(int nid)
6812{
6813 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306814 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08006815
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306816 trace_android_vh_kswapd_per_node(nid, &skip, false);
6817 if (skip)
6818 return;
Jiang Liud8adde12012-07-11 14:01:52 -07006819 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08006820 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07006821 NODE_DATA(nid)->kswapd = NULL;
6822 }
David Rientjes8fe23e02009-12-14 17:58:33 -08006823}
6824
Linus Torvalds1da177e2005-04-16 15:20:36 -07006825static int __init kswapd_init(void)
6826{
Wei Yang6b700b52020-04-01 21:10:09 -07006827 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08006828
Linus Torvalds1da177e2005-04-16 15:20:36 -07006829 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08006830 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006831 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006832 return 0;
6833}
6834
6835module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006836
6837#ifdef CONFIG_NUMA
6838/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006839 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08006840 *
Mel Gormana5f5f912016-07-28 15:46:32 -07006841 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08006842 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006843 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006844int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006845
Dave Hansen51998362021-02-24 12:09:15 -08006846/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006847 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08006848 * of a node considered for each zone_reclaim. 4 scans 1/16th of
6849 * a zone.
6850 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006851#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08006852
Christoph Lameter9eeff232006-01-18 17:42:31 -08006853/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006854 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07006855 * occur.
6856 */
6857int sysctl_min_unmapped_ratio = 1;
6858
6859/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07006860 * If the number of slab pages in a zone grows beyond this percentage then
6861 * slab reclaim needs to occur.
6862 */
6863int sysctl_min_slab_ratio = 5;
6864
Mel Gorman11fb9982016-07-28 15:46:20 -07006865static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006866{
Mel Gorman11fb9982016-07-28 15:46:20 -07006867 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
6868 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
6869 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006870
6871 /*
6872 * It's possible for there to be more file mapped pages than
6873 * accounted for by the pages on the file LRU lists because
6874 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
6875 */
6876 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
6877}
6878
6879/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07006880static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006881{
Alexandru Moised031a152015-11-05 18:48:08 -08006882 unsigned long nr_pagecache_reclaimable;
6883 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07006884
6885 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006886 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07006887 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07006888 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07006889 * a better estimate
6890 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006891 if (node_reclaim_mode & RECLAIM_UNMAP)
6892 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006893 else
Mel Gormana5f5f912016-07-28 15:46:32 -07006894 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006895
6896 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07006897 if (!(node_reclaim_mode & RECLAIM_WRITE))
6898 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006899
6900 /* Watch for any possible underflows due to delta */
6901 if (unlikely(delta > nr_pagecache_reclaimable))
6902 delta = nr_pagecache_reclaimable;
6903
6904 return nr_pagecache_reclaimable - delta;
6905}
6906
Christoph Lameter0ff38492006-09-25 23:31:52 -07006907/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006908 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006909 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006910static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006911{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08006912 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08006913 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006914 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006915 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08006916 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08006917 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006918 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07006919 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07006920 .priority = NODE_RECLAIM_PRIORITY,
6921 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
6922 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07006923 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006924 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08006925 };
Johannes Weiner57f29762021-08-19 19:04:27 -07006926 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006927
Yafang Shao132bb8c2019-05-13 17:17:53 -07006928 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
6929 sc.gfp_mask);
6930
Christoph Lameter9eeff232006-01-18 17:42:31 -08006931 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07006932 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07006933 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08006934 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006935 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08006936 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006937 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08006938 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07006939 noreclaim_flag = memalloc_noreclaim_save();
6940 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07006941 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08006942
Mel Gormana5f5f912016-07-28 15:46:32 -07006943 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07006944 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07006945 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07006946 * priorities until we have enough memory freed.
6947 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07006948 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07006949 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006950 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07006951 }
Christoph Lameterc84db232006-02-01 03:05:29 -08006952
Andrew Morton1732d2b012019-07-16 16:26:15 -07006953 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006954 current->flags &= ~PF_SWAPWRITE;
6955 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006956 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07006957 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07006958
6959 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
6960
Rik van Riela79311c2009-01-06 14:40:01 -08006961 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006962}
Andrew Morton179e9632006-03-22 00:08:18 -08006963
Mel Gormana5f5f912016-07-28 15:46:32 -07006964int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08006965{
David Rientjesd773ed62007-10-16 23:26:01 -07006966 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006967
6968 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006969 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07006970 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07006971 *
Christoph Lameter96146342006-07-03 00:24:13 -07006972 * A small portion of unmapped file backed pages is needed for
6973 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07006974 * thrown out if the node is overallocated. So we do not reclaim
6975 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07006976 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08006977 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006978 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07006979 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
6980 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07006981 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08006982
6983 /*
David Rientjesd773ed62007-10-16 23:26:01 -07006984 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08006985 */
Mel Gormand0164ad2015-11-06 16:28:21 -08006986 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07006987 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08006988
6989 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006990 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08006991 * have associated processors. This will favor the local processor
6992 * over remote processors and spread off node memory allocations
6993 * as wide as possible.
6994 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006995 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
6996 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07006997
Mel Gormana5f5f912016-07-28 15:46:32 -07006998 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
6999 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007000
Mel Gormana5f5f912016-07-28 15:46:32 -07007001 ret = __node_reclaim(pgdat, gfp_mask, order);
7002 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007003
Mel Gorman24cf725182009-06-16 15:33:23 -07007004 if (!ret)
7005 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7006
David Rientjesd773ed62007-10-16 23:26:01 -07007007 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007008}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007009#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007010
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007011/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007012 * check_move_unevictable_pages - check pages for evictability and move to
7013 * appropriate zone lru list
7014 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007015 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007016 * Checks pages for evictability, if an evictable page is in the unevictable
7017 * lru list, moves it to the appropriate evictable lru list. This function
7018 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007019 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007020void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007021{
Alex Shi6168d0d2020-12-15 12:34:29 -08007022 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007023 int pgscanned = 0;
7024 int pgrescued = 0;
7025 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007026
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007027 for (i = 0; i < pvec->nr; i++) {
7028 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007029 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007030
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007031 if (PageTransTail(page))
7032 continue;
7033
7034 nr_pages = thp_nr_pages(page);
7035 pgscanned += nr_pages;
7036
Alex Shid25b5bd2020-12-15 12:34:16 -08007037 /* block memcg migration during page moving between lru */
7038 if (!TestClearPageLRU(page))
7039 continue;
7040
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007041 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007042 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007043 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007044 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007045 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007046 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007047 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007048 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007049 }
Hugh Dickins24513262012-01-20 14:34:21 -08007050
Alex Shi6168d0d2020-12-15 12:34:29 -08007051 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007052 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7053 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007054 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007055 } else if (pgscanned) {
7056 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007057 }
Hugh Dickins850465792012-01-20 14:34:19 -08007058}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007059EXPORT_SYMBOL_GPL(check_move_unevictable_pages);