blob: c6585720ca9d564b7508af56fa0e259bbd37fc34 [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 Zhao5280d762022-01-27 19:23:01 -070053#include <linux/pagewalk.h>
54#include <linux/shmem_fs.h>
Yu Zhao76f7f072022-01-27 19:52:09 -070055#include <linux/ctype.h>
Yu Zhao3d18c9e2022-01-27 20:12:41 -070056#include <linux/debugfs.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070057
58#include <asm/tlbflush.h>
59#include <asm/div64.h>
60
61#include <linux/swapops.h>
Rafael Aquini117aad12013-09-30 13:45:16 -070062#include <linux/balloon_compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070063
Nick Piggin0f8053a2006-03-22 00:08:33 -080064#include "internal.h"
65
Mel Gorman33906bc2010-08-09 17:19:16 -070066#define CREATE_TRACE_POINTS
67#include <trace/events/vmscan.h>
68
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -070069#undef CREATE_TRACE_POINTS
70#include <trace/hooks/vmscan.h>
71
Linus Torvalds1da177e2005-04-16 15:20:36 -070072struct scan_control {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -080073 /* How many pages shrink_list() should reclaim */
74 unsigned long nr_to_reclaim;
75
Johannes Weineree814fe2014-08-06 16:06:19 -070076 /*
77 * Nodemask of nodes allowed by the caller. If NULL, all nodes
78 * are scanned.
79 */
80 nodemask_t *nodemask;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -070081
KOSAKI Motohiro5f53e762010-05-24 14:32:37 -070082 /*
Johannes Weinerf16015f2012-01-12 17:17:52 -080083 * The memory cgroup that hit its limit and as a result is the
84 * primary target of this reclaim invocation.
85 */
86 struct mem_cgroup *target_mem_cgroup;
Balbir Singh66e17072008-02-07 00:13:56 -080087
Johannes Weiner7cf111b2020-06-03 16:03:06 -070088 /*
89 * Scan pressure balancing between anon and file LRUs
90 */
91 unsigned long anon_cost;
92 unsigned long file_cost;
93
Johannes Weinerb91ac372019-11-30 17:56:02 -080094 /* Can active pages be deactivated as part of reclaim? */
95#define DEACTIVATE_ANON 1
96#define DEACTIVATE_FILE 2
97 unsigned int may_deactivate:2;
98 unsigned int force_deactivate:1;
99 unsigned int skipped_deactivate:1;
100
Johannes Weiner1276ad62017-02-24 14:56:11 -0800101 /* Writepage batching in laptop mode; RECLAIM_WRITE */
Johannes Weineree814fe2014-08-06 16:06:19 -0700102 unsigned int may_writepage:1;
103
104 /* Can mapped pages be reclaimed? */
105 unsigned int may_unmap:1;
106
107 /* Can pages be swapped as part of reclaim? */
108 unsigned int may_swap:1;
109
Yisheng Xied6622f62017-05-03 14:53:57 -0700110 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700111 * Cgroup memory below memory.low is protected as long as we
112 * don't threaten to OOM. If any cgroup is reclaimed at
113 * reduced force or passed over entirely due to its memory.low
114 * setting (memcg_low_skipped), and nothing is reclaimed as a
115 * result, then go back for one more cycle that reclaims the protected
116 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700117 */
118 unsigned int memcg_low_reclaim:1;
119 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800120
Johannes Weineree814fe2014-08-06 16:06:19 -0700121 unsigned int hibernation_mode:1;
122
123 /* One of the zones is ready for compaction */
124 unsigned int compaction_ready:1;
125
Johannes Weinerb91ac372019-11-30 17:56:02 -0800126 /* There is easily reclaimable cold cache in the current node */
127 unsigned int cache_trim_mode:1;
128
Johannes Weiner53138ce2019-11-30 17:55:56 -0800129 /* The file pages on the current node are dangerously low */
130 unsigned int file_is_tiny:1;
131
Dave Hansen26aa2d12021-09-02 14:59:16 -0700132 /* Always discard instead of demoting to lower tier memory */
133 unsigned int no_demotion:1;
134
Yu Zhao4d905e92022-01-27 19:59:54 -0700135#ifdef CONFIG_LRU_GEN
136 /* help make better choices when multiple memcgs are available */
137 unsigned int memcgs_need_aging:1;
138 unsigned int memcgs_need_swapping:1;
139 unsigned int memcgs_avoid_swapping:1;
140#endif
141
Greg Thelenbb451fd2018-08-17 15:45:19 -0700142 /* Allocation order */
143 s8 order;
144
145 /* Scan (total_size >> priority) pages at once */
146 s8 priority;
147
148 /* The highest zone to isolate pages for reclaim from */
149 s8 reclaim_idx;
150
151 /* This context's GFP mask */
152 gfp_t gfp_mask;
153
Johannes Weineree814fe2014-08-06 16:06:19 -0700154 /* Incremented by the number of inactive pages that were scanned */
155 unsigned long nr_scanned;
156
157 /* Number of pages freed so far during a call to shrink_zones() */
158 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700159
160 struct {
161 unsigned int dirty;
162 unsigned int unqueued_dirty;
163 unsigned int congested;
164 unsigned int writeback;
165 unsigned int immediate;
166 unsigned int file_taken;
167 unsigned int taken;
168 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700169
170 /* for recording the reclaimed slab by now */
171 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700172};
173
Linus Torvalds1da177e2005-04-16 15:20:36 -0700174#ifdef ARCH_HAS_PREFETCHW
175#define prefetchw_prev_lru_page(_page, _base, _field) \
176 do { \
177 if ((_page)->lru.prev != _base) { \
178 struct page *prev; \
179 \
180 prev = lru_to_page(&(_page->lru)); \
181 prefetchw(&prev->_field); \
182 } \
183 } while (0)
184#else
185#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
186#endif
187
188/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700189 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700190 */
191int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700192
Yang Shi0a432dc2019-09-23 15:38:12 -0700193static void set_task_reclaim_state(struct task_struct *task,
194 struct reclaim_state *rs)
195{
196 /* Check for an overwrite */
197 WARN_ON_ONCE(rs && task->reclaim_state);
198
199 /* Check for the nulling of an already-nulled member */
200 WARN_ON_ONCE(!rs && !task->reclaim_state);
201
202 task->reclaim_state = rs;
203}
204
Linus Torvalds1da177e2005-04-16 15:20:36 -0700205static LIST_HEAD(shrinker_list);
206static DECLARE_RWSEM(shrinker_rwsem);
207
Yang Shi0a432dc2019-09-23 15:38:12 -0700208#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700209static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700210
Yang Shi3c6f17e2021-05-04 18:36:33 -0700211/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700212static inline int shrinker_map_size(int nr_items)
213{
214 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
215}
Yang Shi2bfd3632021-05-04 18:36:11 -0700216
Yang Shi3c6f17e2021-05-04 18:36:33 -0700217static inline int shrinker_defer_size(int nr_items)
218{
219 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
220}
221
Yang Shi468ab842021-05-04 18:36:26 -0700222static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
223 int nid)
224{
225 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
226 lockdep_is_held(&shrinker_rwsem));
227}
228
Yang Shie4262c42021-05-04 18:36:23 -0700229static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700230 int map_size, int defer_size,
231 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700232{
Yang Shie4262c42021-05-04 18:36:23 -0700233 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700234 struct mem_cgroup_per_node *pn;
235 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700236 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700237
Yang Shi2bfd3632021-05-04 18:36:11 -0700238 for_each_node(nid) {
239 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700240 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700241 /* Not yet online memcg */
242 if (!old)
243 return 0;
244
245 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
246 if (!new)
247 return -ENOMEM;
248
Yang Shi3c6f17e2021-05-04 18:36:33 -0700249 new->nr_deferred = (atomic_long_t *)(new + 1);
250 new->map = (void *)new->nr_deferred + defer_size;
251
252 /* map: set all old bits, clear all new bits */
253 memset(new->map, (int)0xff, old_map_size);
254 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
255 /* nr_deferred: copy old values, clear all new values */
256 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
257 memset((void *)new->nr_deferred + old_defer_size, 0,
258 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700259
Yang Shie4262c42021-05-04 18:36:23 -0700260 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700261 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700262 }
263
264 return 0;
265}
266
Yang Shie4262c42021-05-04 18:36:23 -0700267void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700268{
269 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700270 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700271 int nid;
272
Yang Shi2bfd3632021-05-04 18:36:11 -0700273 for_each_node(nid) {
274 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700275 info = rcu_dereference_protected(pn->shrinker_info, true);
276 kvfree(info);
277 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700278 }
279}
280
Yang Shie4262c42021-05-04 18:36:23 -0700281int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700282{
Yang Shie4262c42021-05-04 18:36:23 -0700283 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700284 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700285 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700286
Yang Shid27cf2a2021-05-04 18:36:14 -0700287 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700288 map_size = shrinker_map_size(shrinker_nr_max);
289 defer_size = shrinker_defer_size(shrinker_nr_max);
290 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700291 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700292 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
293 if (!info) {
294 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700295 ret = -ENOMEM;
296 break;
297 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700298 info->nr_deferred = (atomic_long_t *)(info + 1);
299 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700300 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700301 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700302 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700303
304 return ret;
305}
306
Yang Shi3c6f17e2021-05-04 18:36:33 -0700307static inline bool need_expand(int nr_max)
308{
309 return round_up(nr_max, BITS_PER_LONG) >
310 round_up(shrinker_nr_max, BITS_PER_LONG);
311}
312
Yang Shie4262c42021-05-04 18:36:23 -0700313static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700314{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700315 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700316 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700317 int map_size, defer_size = 0;
318 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700319 struct mem_cgroup *memcg;
320
Yang Shi3c6f17e2021-05-04 18:36:33 -0700321 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700322 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700323
Yang Shi2bfd3632021-05-04 18:36:11 -0700324 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700325 goto out;
326
327 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700328
Yang Shi3c6f17e2021-05-04 18:36:33 -0700329 map_size = shrinker_map_size(new_nr_max);
330 defer_size = shrinker_defer_size(new_nr_max);
331 old_map_size = shrinker_map_size(shrinker_nr_max);
332 old_defer_size = shrinker_defer_size(shrinker_nr_max);
333
Yang Shi2bfd3632021-05-04 18:36:11 -0700334 memcg = mem_cgroup_iter(NULL, NULL, NULL);
335 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700336 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
337 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700338 if (ret) {
339 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700340 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700341 }
342 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700343out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700344 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700345 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700346
Yang Shi2bfd3632021-05-04 18:36:11 -0700347 return ret;
348}
349
350void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
351{
352 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700353 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700354
355 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700356 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700357 /* Pairs with smp mb in shrink_slab() */
358 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700359 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700360 rcu_read_unlock();
361 }
362}
363
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700364static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700365
366static int prealloc_memcg_shrinker(struct shrinker *shrinker)
367{
368 int id, ret = -ENOMEM;
369
Yang Shi476b30a2021-05-04 18:36:39 -0700370 if (mem_cgroup_disabled())
371 return -ENOSYS;
372
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700373 down_write(&shrinker_rwsem);
374 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700375 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700376 if (id < 0)
377 goto unlock;
378
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700379 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700380 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700381 idr_remove(&shrinker_idr, id);
382 goto unlock;
383 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700384 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700385 shrinker->id = id;
386 ret = 0;
387unlock:
388 up_write(&shrinker_rwsem);
389 return ret;
390}
391
392static void unregister_memcg_shrinker(struct shrinker *shrinker)
393{
394 int id = shrinker->id;
395
396 BUG_ON(id < 0);
397
Yang Shi41ca6682021-05-04 18:36:29 -0700398 lockdep_assert_held(&shrinker_rwsem);
399
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700400 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700401}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700402
Yang Shi86750832021-05-04 18:36:36 -0700403static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
404 struct mem_cgroup *memcg)
405{
406 struct shrinker_info *info;
407
408 info = shrinker_info_protected(memcg, nid);
409 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
410}
411
412static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
413 struct mem_cgroup *memcg)
414{
415 struct shrinker_info *info;
416
417 info = shrinker_info_protected(memcg, nid);
418 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
419}
420
Yang Shia1780152021-05-04 18:36:42 -0700421void reparent_shrinker_deferred(struct mem_cgroup *memcg)
422{
423 int i, nid;
424 long nr;
425 struct mem_cgroup *parent;
426 struct shrinker_info *child_info, *parent_info;
427
428 parent = parent_mem_cgroup(memcg);
429 if (!parent)
430 parent = root_mem_cgroup;
431
432 /* Prevent from concurrent shrinker_info expand */
433 down_read(&shrinker_rwsem);
434 for_each_node(nid) {
435 child_info = shrinker_info_protected(memcg, nid);
436 parent_info = shrinker_info_protected(parent, nid);
437 for (i = 0; i < shrinker_nr_max; i++) {
438 nr = atomic_long_read(&child_info->nr_deferred[i]);
439 atomic_long_add(nr, &parent_info->nr_deferred[i]);
440 }
441 }
442 up_read(&shrinker_rwsem);
443}
444
Johannes Weinerb5ead352019-11-30 17:55:40 -0800445static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800446{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800447 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800448}
Tejun Heo97c93412015-05-22 18:23:36 -0400449
450/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800451 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400452 * @sc: scan_control in question
453 *
454 * The normal page dirty throttling mechanism in balance_dirty_pages() is
455 * completely broken with the legacy memcg and direct stalling in
456 * shrink_page_list() is used for throttling instead, which lacks all the
457 * niceties such as fairness, adaptive pausing, bandwidth proportional
458 * allocation and configurability.
459 *
460 * This function tests whether the vmscan currently in progress can assume
461 * that the normal dirty throttling mechanism is operational.
462 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800463static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400464{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800465 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400466 return true;
467#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800468 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400469 return true;
470#endif
471 return false;
472}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800473#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700474static int prealloc_memcg_shrinker(struct shrinker *shrinker)
475{
Yang Shi476b30a2021-05-04 18:36:39 -0700476 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700477}
478
479static void unregister_memcg_shrinker(struct shrinker *shrinker)
480{
481}
482
Yang Shi86750832021-05-04 18:36:36 -0700483static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
484 struct mem_cgroup *memcg)
485{
486 return 0;
487}
488
489static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
490 struct mem_cgroup *memcg)
491{
492 return 0;
493}
494
Johannes Weinerb5ead352019-11-30 17:55:40 -0800495static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800496{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800497 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800498}
Tejun Heo97c93412015-05-22 18:23:36 -0400499
Johannes Weinerb5ead352019-11-30 17:55:40 -0800500static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400501{
502 return true;
503}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800504#endif
505
Yang Shi86750832021-05-04 18:36:36 -0700506static long xchg_nr_deferred(struct shrinker *shrinker,
507 struct shrink_control *sc)
508{
509 int nid = sc->nid;
510
511 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
512 nid = 0;
513
514 if (sc->memcg &&
515 (shrinker->flags & SHRINKER_MEMCG_AWARE))
516 return xchg_nr_deferred_memcg(nid, shrinker,
517 sc->memcg);
518
519 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
520}
521
522
523static long add_nr_deferred(long nr, struct shrinker *shrinker,
524 struct shrink_control *sc)
525{
526 int nid = sc->nid;
527
528 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
529 nid = 0;
530
531 if (sc->memcg &&
532 (shrinker->flags & SHRINKER_MEMCG_AWARE))
533 return add_nr_deferred_memcg(nr, nid, shrinker,
534 sc->memcg);
535
536 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
537}
538
Dave Hansen26aa2d12021-09-02 14:59:16 -0700539static bool can_demote(int nid, struct scan_control *sc)
540{
Huang Ying20b51af12021-09-02 14:59:33 -0700541 if (!numa_demotion_enabled)
542 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700543 if (sc) {
544 if (sc->no_demotion)
545 return false;
546 /* It is pointless to do demotion in memcg reclaim */
547 if (cgroup_reclaim(sc))
548 return false;
549 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700550 if (next_demotion_node(nid) == NUMA_NO_NODE)
551 return false;
552
Huang Ying20b51af12021-09-02 14:59:33 -0700553 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700554}
555
Keith Buscha2a36482021-09-02 14:59:26 -0700556static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
557 int nid,
558 struct scan_control *sc)
559{
560 if (memcg == NULL) {
561 /*
562 * For non-memcg reclaim, is there
563 * space in any swap device?
564 */
565 if (get_nr_swap_pages() > 0)
566 return true;
567 } else {
568 /* Is the memcg below its swap limit? */
569 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
570 return true;
571 }
572
573 /*
574 * The page can not be swapped.
575 *
576 * Can it be reclaimed from this node via demotion?
577 */
578 return can_demote(nid, sc);
579}
580
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700581/*
582 * This misses isolated pages which are not accounted for to save counters.
583 * As the data only determines if reclaim or compaction continues, it is
584 * not expected that isolated pages will be a dominating factor.
585 */
586unsigned long zone_reclaimable_pages(struct zone *zone)
587{
588 unsigned long nr;
589
590 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
591 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700592 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700593 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
594 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
595
596 return nr;
597}
598
Michal Hockofd538802017-02-22 15:45:58 -0800599/**
600 * lruvec_lru_size - Returns the number of pages on the given LRU list.
601 * @lruvec: lru vector
602 * @lru: lru to use
603 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
604 */
Yu Zhao20913392021-02-24 12:08:44 -0800605static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
606 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800607{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800608 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800609 int zid;
610
Johannes Weinerde3b0152019-11-30 17:55:31 -0800611 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800612 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800613
Michal Hockofd538802017-02-22 15:45:58 -0800614 if (!managed_zone(zone))
615 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800616
Michal Hockofd538802017-02-22 15:45:58 -0800617 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800618 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800619 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800620 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800621 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800622 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800623}
624
Linus Torvalds1da177e2005-04-16 15:20:36 -0700625/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000626 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700627 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900628int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700629{
Yang Shi476b30a2021-05-04 18:36:39 -0700630 unsigned int size;
631 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000632
Yang Shi476b30a2021-05-04 18:36:39 -0700633 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
634 err = prealloc_memcg_shrinker(shrinker);
635 if (err != -ENOSYS)
636 return err;
637
638 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
639 }
640
641 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000642 if (shrinker->flags & SHRINKER_NUMA_AWARE)
643 size *= nr_node_ids;
644
645 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
646 if (!shrinker->nr_deferred)
647 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700648
Tetsuo Handa8e049442018-04-04 19:53:07 +0900649 return 0;
650}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000651
Tetsuo Handa8e049442018-04-04 19:53:07 +0900652void free_prealloced_shrinker(struct shrinker *shrinker)
653{
Yang Shi41ca6682021-05-04 18:36:29 -0700654 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
655 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700656 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700657 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700658 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700659 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700660
Tetsuo Handa8e049442018-04-04 19:53:07 +0900661 kfree(shrinker->nr_deferred);
662 shrinker->nr_deferred = NULL;
663}
664
665void register_shrinker_prepared(struct shrinker *shrinker)
666{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700667 down_write(&shrinker_rwsem);
668 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700669 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700670 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900671}
672
673int register_shrinker(struct shrinker *shrinker)
674{
675 int err = prealloc_shrinker(shrinker);
676
677 if (err)
678 return err;
679 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000680 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700681}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700682EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700683
684/*
685 * Remove one
686 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700687void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700688{
Yang Shi41ca6682021-05-04 18:36:29 -0700689 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900690 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700691
Linus Torvalds1da177e2005-04-16 15:20:36 -0700692 down_write(&shrinker_rwsem);
693 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700694 shrinker->flags &= ~SHRINKER_REGISTERED;
695 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
696 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700697 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700698
Andrew Vaginae393322013-10-16 13:46:46 -0700699 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900700 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700701}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700702EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700703
704#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000705
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800706static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800707 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700708{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000709 unsigned long freed = 0;
710 unsigned long long delta;
711 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700712 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000713 long nr;
714 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000715 long batch_size = shrinker->batch ? shrinker->batch
716 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800717 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000718
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 */
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800905static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
906 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;
911
Yang Shifa1e5122019-08-02 21:48:44 -0700912 /*
913 * The root memcg might be allocated even though memcg is disabled
914 * via "cgroup_disable=memory" boot parameter. This could make
915 * mem_cgroup_is_root() return false, then just run memcg slab
916 * shrink, but skip global shrink. This may result in premature
917 * oom.
918 */
919 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700920 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800921
Tetsuo Handae830c632018-04-05 16:23:35 -0700922 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700923 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700924
925 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800926 struct shrink_control sc = {
927 .gfp_mask = gfp_mask,
928 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800929 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800930 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800931
Kirill Tkhai9b996462018-08-17 15:48:21 -0700932 ret = do_shrink_slab(&sc, shrinker, priority);
933 if (ret == SHRINK_EMPTY)
934 ret = 0;
935 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800936 /*
937 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700938 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800939 * by parallel ongoing shrinking.
940 */
941 if (rwsem_is_contended(&shrinker_rwsem)) {
942 freed = freed ? : 1;
943 break;
944 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700945 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800946
Linus Torvalds1da177e2005-04-16 15:20:36 -0700947 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700948out:
949 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000950 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700951}
952
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800953void drop_slab_node(int nid)
954{
955 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700956 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800957
958 do {
959 struct mem_cgroup *memcg = NULL;
960
Chunxin Zang069c4112020-10-13 16:56:46 -0700961 if (fatal_signal_pending(current))
962 return;
963
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800964 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700965 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800966 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800967 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800968 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700969 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800970}
971
972void drop_slab(void)
973{
974 int nid;
975
976 for_each_online_node(nid)
977 drop_slab_node(nid);
978}
979
Linus Torvalds1da177e2005-04-16 15:20:36 -0700980static inline int is_page_cache_freeable(struct page *page)
981{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700982 /*
983 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400984 * that isolated the page, the page cache and optional buffer
985 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700986 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -0700987 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400988 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700989}
990
Yang Shicb165562019-11-30 17:55:28 -0800991static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700992{
Christoph Lameter930d9152006-01-08 01:00:47 -0800993 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700994 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400995 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700996 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400997 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700998 return 1;
999 return 0;
1000}
1001
1002/*
1003 * We detected a synchronous write error writing a page out. Probably
1004 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1005 * fsync(), msync() or close().
1006 *
1007 * The tricky part is that after writepage we cannot touch the mapping: nothing
1008 * prevents it from being freed up. But we have a ref on the page and once
1009 * that page is locked, the mapping is pinned.
1010 *
1011 * We're allowed to run sleeping lock_page() here because we know the caller has
1012 * __GFP_FS.
1013 */
1014static void handle_write_error(struct address_space *mapping,
1015 struct page *page, int error)
1016{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001017 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001018 if (page_mapping(page) == mapping)
1019 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001020 unlock_page(page);
1021}
1022
Christoph Lameter04e62a22006-06-23 02:03:38 -07001023/* possible outcome of pageout() */
1024typedef enum {
1025 /* failed to write page out, page is locked */
1026 PAGE_KEEP,
1027 /* move page to the active list, page is locked */
1028 PAGE_ACTIVATE,
1029 /* page has been sent to the disk successfully, page is unlocked */
1030 PAGE_SUCCESS,
1031 /* page is clean and locked */
1032 PAGE_CLEAN,
1033} pageout_t;
1034
Linus Torvalds1da177e2005-04-16 15:20:36 -07001035/*
Andrew Morton1742f192006-03-22 00:08:21 -08001036 * pageout is called by shrink_page_list() for each dirty page.
1037 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001038 */
Yang Shicb165562019-11-30 17:55:28 -08001039static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001040{
1041 /*
1042 * If the page is dirty, only perform writeback if that write
1043 * will be non-blocking. To prevent this allocation from being
1044 * stalled by pagecache activity. But note that there may be
1045 * stalls if we need to run get_block(). We could test
1046 * PagePrivate for that.
1047 *
Al Viro81742022014-04-03 03:17:43 -04001048 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001049 * this page's queue, we can perform writeback even if that
1050 * will block.
1051 *
1052 * If the page is swapcache, write it back even if that would
1053 * block, for some throttling. This happens by accident, because
1054 * swap_backing_dev_info is bust: it doesn't reflect the
1055 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001056 */
1057 if (!is_page_cache_freeable(page))
1058 return PAGE_KEEP;
1059 if (!mapping) {
1060 /*
1061 * Some data journaling orphaned pages can have
1062 * page->mapping == NULL while being dirty with clean buffers.
1063 */
David Howells266cf652009-04-03 16:42:36 +01001064 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001065 if (try_to_free_buffers(page)) {
1066 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001067 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001068 return PAGE_CLEAN;
1069 }
1070 }
1071 return PAGE_KEEP;
1072 }
1073 if (mapping->a_ops->writepage == NULL)
1074 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001075 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001076 return PAGE_KEEP;
1077
1078 if (clear_page_dirty_for_io(page)) {
1079 int res;
1080 struct writeback_control wbc = {
1081 .sync_mode = WB_SYNC_NONE,
1082 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001083 .range_start = 0,
1084 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001085 .for_reclaim = 1,
1086 };
1087
1088 SetPageReclaim(page);
1089 res = mapping->a_ops->writepage(page, &wbc);
1090 if (res < 0)
1091 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001092 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001093 ClearPageReclaim(page);
1094 return PAGE_ACTIVATE;
1095 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001096
Linus Torvalds1da177e2005-04-16 15:20:36 -07001097 if (!PageWriteback(page)) {
1098 /* synchronous write or broken a_ops? */
1099 ClearPageReclaim(page);
1100 }
yalin wang3aa23852016-01-14 15:18:30 -08001101 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001102 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001103 return PAGE_SUCCESS;
1104 }
1105
1106 return PAGE_CLEAN;
1107}
1108
Andrew Mortona649fd92006-10-17 00:09:36 -07001109/*
Nick Piggine2867812008-07-25 19:45:30 -07001110 * Same as remove_mapping, but if the page is removed from the mapping, it
1111 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001112 */
Johannes Weinera5289102014-04-03 14:47:51 -07001113static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001114 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001115{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001116 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001117 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001118
Nick Piggin28e4d962006-09-25 23:31:23 -07001119 BUG_ON(!PageLocked(page));
1120 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001121
Johannes Weiner30472502021-09-02 14:53:18 -07001122 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001123 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001124 * The non racy check for a busy page.
1125 *
1126 * Must be careful with the order of the tests. When someone has
1127 * a ref to the page, it may be possible that they dirty it then
1128 * drop the reference. So if PageDirty is tested before page_count
1129 * here, then the following race may occur:
1130 *
1131 * get_user_pages(&page);
1132 * [user mapping goes away]
1133 * write_to(page);
1134 * !PageDirty(page) [good]
1135 * SetPageDirty(page);
1136 * put_page(page);
1137 * !page_count(page) [good, discard it]
1138 *
1139 * [oops, our write_to data is lost]
1140 *
1141 * Reversing the order of the tests ensures such a situation cannot
1142 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001143 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001144 *
1145 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001146 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001147 */
William Kucharski906d2782019-10-18 20:20:33 -07001148 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001149 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001150 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001151 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001152 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001153 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001154 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001155 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001156
1157 if (PageSwapCache(page)) {
1158 swp_entry_t swap = { .val = page_private(page) };
Yu Zhaoa1537a62022-01-27 20:32:37 -07001159
1160 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001161 if (reclaimed && !mapping_exiting(mapping))
1162 shadow = workingset_eviction(page, target_memcg);
Yu Zhaoa1537a62022-01-27 20:32:37 -07001163 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001164 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001165 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001166 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001167 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001168 void (*freepage)(struct page *);
1169
1170 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001171 /*
1172 * Remember a shadow entry for reclaimed file cache in
1173 * order to detect refaults, thus thrashing, later on.
1174 *
1175 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001176 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001177 * inode reclaim needs to empty out the radix tree or
1178 * the nodes are lost. Don't plant shadows behind its
1179 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001180 *
1181 * We also don't store shadows for DAX mappings because the
1182 * only page cache pages found in these are zero pages
1183 * covering holes, and because we don't want to mix DAX
1184 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001185 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001186 */
Huang Ying9de4f222020-04-06 20:04:41 -07001187 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001188 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001189 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001190 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001191 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001192
1193 if (freepage != NULL)
1194 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001195 }
1196
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001197 return 1;
1198
1199cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001200 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001201 return 0;
1202}
1203
Linus Torvalds1da177e2005-04-16 15:20:36 -07001204/*
Nick Piggine2867812008-07-25 19:45:30 -07001205 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1206 * someone else has a ref on the page, abort and return 0. If it was
1207 * successfully detached, return 1. Assumes the caller has a single ref on
1208 * this page.
1209 */
1210int remove_mapping(struct address_space *mapping, struct page *page)
1211{
Johannes Weinerb9107182019-11-30 17:55:59 -08001212 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001213 /*
1214 * Unfreezing the refcount with 1 rather than 2 effectively
1215 * drops the pagecache ref for us without requiring another
1216 * atomic operation.
1217 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001218 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001219 return 1;
1220 }
1221 return 0;
1222}
1223
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001224/**
1225 * putback_lru_page - put previously isolated page onto appropriate LRU list
1226 * @page: page to be put back to appropriate lru list
1227 *
1228 * Add previously isolated @page to appropriate LRU list.
1229 * Page may still be unevictable for other reasons.
1230 *
1231 * lru_lock must not be held, interrupts must be enabled.
1232 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001233void putback_lru_page(struct page *page)
1234{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001235 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001236 put_page(page); /* drop ref from isolate */
1237}
1238
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001239enum page_references {
1240 PAGEREF_RECLAIM,
1241 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001242 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001243 PAGEREF_ACTIVATE,
1244};
1245
1246static enum page_references page_check_references(struct page *page,
1247 struct scan_control *sc)
1248{
Johannes Weiner645747462010-03-05 13:42:22 -08001249 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001250 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001251
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001252 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1253 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001254 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001255
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001256 /*
1257 * Mlock lost the isolation race with us. Let try_to_unmap()
1258 * move the page to the unevictable list.
1259 */
1260 if (vm_flags & VM_LOCKED)
1261 return PAGEREF_RECLAIM;
1262
Johannes Weiner645747462010-03-05 13:42:22 -08001263 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001264 /*
1265 * All mapped pages start out with page table
1266 * references from the instantiating fault, so we need
1267 * to look twice if a mapped file page is used more
1268 * than once.
1269 *
1270 * Mark it and spare it for another trip around the
1271 * inactive list. Another page table reference will
1272 * lead to its activation.
1273 *
1274 * Note: the mark is set for activated pages as well
1275 * so that recently deactivated but used pages are
1276 * quickly recovered.
1277 */
1278 SetPageReferenced(page);
1279
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001280 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001281 return PAGEREF_ACTIVATE;
1282
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001283 /*
1284 * Activate file-backed executable pages after first usage.
1285 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001286 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001287 return PAGEREF_ACTIVATE;
1288
Johannes Weiner645747462010-03-05 13:42:22 -08001289 return PAGEREF_KEEP;
1290 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001291
1292 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001293 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001294 return PAGEREF_RECLAIM_CLEAN;
1295
1296 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001297}
1298
Mel Gormane2be15f2013-07-03 15:01:57 -07001299/* Check if a page is dirty or under writeback */
1300static void page_check_dirty_writeback(struct page *page,
1301 bool *dirty, bool *writeback)
1302{
Mel Gormanb4597222013-07-03 15:02:05 -07001303 struct address_space *mapping;
1304
Mel Gormane2be15f2013-07-03 15:01:57 -07001305 /*
1306 * Anonymous pages are not handled by flushers and must be written
1307 * from reclaim context. Do not stall reclaim based on them
1308 */
Huang Ying9de4f222020-04-06 20:04:41 -07001309 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001310 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001311 *dirty = false;
1312 *writeback = false;
1313 return;
1314 }
1315
1316 /* By default assume that the page flags are accurate */
1317 *dirty = PageDirty(page);
1318 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001319
1320 /* Verify dirty/writeback state if the filesystem supports it */
1321 if (!page_has_private(page))
1322 return;
1323
1324 mapping = page_mapping(page);
1325 if (mapping && mapping->a_ops->is_dirty_writeback)
1326 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001327}
1328
Dave Hansen26aa2d12021-09-02 14:59:16 -07001329static struct page *alloc_demote_page(struct page *page, unsigned long node)
1330{
1331 struct migration_target_control mtc = {
1332 /*
1333 * Allocate from 'node', or fail quickly and quietly.
1334 * When this happens, 'page' will likely just be discarded
1335 * instead of migrated.
1336 */
1337 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1338 __GFP_THISNODE | __GFP_NOWARN |
1339 __GFP_NOMEMALLOC | GFP_NOWAIT,
1340 .nid = node
1341 };
1342
1343 return alloc_migration_target(page, (unsigned long)&mtc);
1344}
1345
1346/*
1347 * Take pages on @demote_list and attempt to demote them to
1348 * another node. Pages which are not demoted are left on
1349 * @demote_pages.
1350 */
1351static unsigned int demote_page_list(struct list_head *demote_pages,
1352 struct pglist_data *pgdat)
1353{
1354 int target_nid = next_demotion_node(pgdat->node_id);
1355 unsigned int nr_succeeded;
1356 int err;
1357
1358 if (list_empty(demote_pages))
1359 return 0;
1360
1361 if (target_nid == NUMA_NO_NODE)
1362 return 0;
1363
1364 /* Demotion ignores all cpuset and mempolicy settings */
1365 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1366 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1367 &nr_succeeded);
1368
Yang Shi668e4142021-09-02 14:59:19 -07001369 if (current_is_kswapd())
1370 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1371 else
1372 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1373
Dave Hansen26aa2d12021-09-02 14:59:16 -07001374 return nr_succeeded;
1375}
1376
Nick Piggine2867812008-07-25 19:45:30 -07001377/*
Andrew Morton1742f192006-03-22 00:08:21 -08001378 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001379 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001380static unsigned int shrink_page_list(struct list_head *page_list,
1381 struct pglist_data *pgdat,
1382 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001383 struct reclaim_stat *stat,
1384 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001385{
1386 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001387 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001388 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001389 unsigned int nr_reclaimed = 0;
1390 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001391 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001392
Kirill Tkhai060f0052019-03-05 15:48:15 -08001393 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001394 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001395 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001396
Dave Hansen26aa2d12021-09-02 14:59:16 -07001397retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001398 while (!list_empty(page_list)) {
1399 struct address_space *mapping;
1400 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001401 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001402 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001403 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001404
1405 cond_resched();
1406
1407 page = lru_to_page(page_list);
1408 list_del(&page->lru);
1409
Nick Piggin529ae9a2008-08-02 12:01:03 +02001410 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001411 goto keep;
1412
Sasha Levin309381fea2014-01-23 15:52:54 -08001413 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001414
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001415 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001416
1417 /* Account the number of base pages even though THP */
1418 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001419
Hugh Dickins39b5f292012-10-08 16:33:18 -07001420 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001421 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001422
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001423 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001424 goto keep_locked;
1425
Yu Zhaoafd94c92022-01-27 20:43:22 -07001426 /* page_update_gen() tried to promote this page? */
1427 if (lru_gen_enabled() && !ignore_references &&
1428 page_mapped(page) && PageReferenced(page))
1429 goto keep_locked;
1430
Andy Whitcroftc661b072007-08-22 14:01:26 -07001431 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1432 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1433
Mel Gorman283aba92013-07-03 15:01:51 -07001434 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001435 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001436 * reclaim_congested which affects wait_iff_congested. kswapd
1437 * will stall and start writing pages if the tail of the LRU
1438 * is all dirty unqueued pages.
1439 */
1440 page_check_dirty_writeback(page, &dirty, &writeback);
1441 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001442 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001443
1444 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001445 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001446
Mel Gormand04e8ac2013-07-03 15:02:03 -07001447 /*
1448 * Treat this page as congested if the underlying BDI is or if
1449 * pages are cycling through the LRU so quickly that the
1450 * pages marked for immediate reclaim are making it to the
1451 * end of the LRU a second time.
1452 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001453 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001454 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001455 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001456 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001457 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001458
1459 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001460 * If a page at the tail of the LRU is under writeback, there
1461 * are three cases to consider.
1462 *
1463 * 1) If reclaim is encountering an excessive number of pages
1464 * under writeback and this page is both under writeback and
1465 * PageReclaim then it indicates that pages are being queued
1466 * for IO but are being recycled through the LRU before the
1467 * IO can complete. Waiting on the page itself risks an
1468 * indefinite stall if it is impossible to writeback the
1469 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001470 * note that the LRU is being scanned too quickly and the
1471 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001472 *
Tejun Heo97c93412015-05-22 18:23:36 -04001473 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001474 * not marked for immediate reclaim, or the caller does not
1475 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1476 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001477 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001478 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001479 * Require may_enter_fs because we would wait on fs, which
1480 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001481 * enter reclaim, and deadlock if it waits on a page for
1482 * which it is needed to do the write (loop masks off
1483 * __GFP_IO|__GFP_FS for this reason); but more thought
1484 * would probably show more reasons.
1485 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001486 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001487 * PageReclaim. memcg does not have any dirty pages
1488 * throttling so we could easily OOM just because too many
1489 * pages are in writeback and there is nothing else to
1490 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001491 *
1492 * In cases 1) and 2) we activate the pages to get them out of
1493 * the way while we continue scanning for clean pages on the
1494 * inactive list and refilling from the active list. The
1495 * observation here is that waiting for disk writes is more
1496 * expensive than potentially causing reloads down the line.
1497 * Since they're marked for immediate reclaim, they won't put
1498 * memory pressure on the cache working set any longer than it
1499 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001500 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001501 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001502 /* Case 1 above */
1503 if (current_is_kswapd() &&
1504 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001505 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001506 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001507 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001508
1509 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001510 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001511 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001512 /*
1513 * This is slightly racy - end_page_writeback()
1514 * might have just cleared PageReclaim, then
1515 * setting PageReclaim here end up interpreted
1516 * as PageReadahead - but that does not matter
1517 * enough to care. What we do want is for this
1518 * page to have PageReclaim set next time memcg
1519 * reclaim reaches the tests above, so it will
1520 * then wait_on_page_writeback() to avoid OOM;
1521 * and it's also appropriate in global reclaim.
1522 */
1523 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001524 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001525 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001526
1527 /* Case 3 above */
1528 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001529 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001530 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001531 /* then go back and try same page again */
1532 list_add_tail(&page->lru, page_list);
1533 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001534 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001535 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001536
Minchan Kim8940b342019-09-25 16:49:11 -07001537 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001538 references = page_check_references(page, sc);
1539
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001540 switch (references) {
1541 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001542 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001543 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001544 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001545 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001546 case PAGEREF_RECLAIM:
1547 case PAGEREF_RECLAIM_CLEAN:
1548 ; /* try to reclaim the page below */
1549 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001550
Linus Torvalds1da177e2005-04-16 15:20:36 -07001551 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001552 * Before reclaiming the page, try to relocate
1553 * its contents to another node.
1554 */
1555 if (do_demote_pass &&
1556 (thp_migration_supported() || !PageTransHuge(page))) {
1557 list_add(&page->lru, &demote_pages);
1558 unlock_page(page);
1559 continue;
1560 }
1561
1562 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001563 * Anonymous process memory has backing store?
1564 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001565 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001566 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001567 if (PageAnon(page) && PageSwapBacked(page)) {
1568 if (!PageSwapCache(page)) {
1569 if (!(sc->gfp_mask & __GFP_IO))
1570 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001571 if (page_maybe_dma_pinned(page))
1572 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001573 if (PageTransHuge(page)) {
1574 /* cannot split THP, skip it */
1575 if (!can_split_huge_page(page, NULL))
1576 goto activate_locked;
1577 /*
1578 * Split pages without a PMD map right
1579 * away. Chances are some or all of the
1580 * tail pages can be freed without IO.
1581 */
1582 if (!compound_mapcount(page) &&
1583 split_huge_page_to_list(page,
1584 page_list))
1585 goto activate_locked;
1586 }
1587 if (!add_to_swap(page)) {
1588 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001589 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001590 /* Fallback to swap normal pages */
1591 if (split_huge_page_to_list(page,
1592 page_list))
1593 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001594#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1595 count_vm_event(THP_SWPOUT_FALLBACK);
1596#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001597 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001598 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001599 }
Minchan Kim0f074652017-07-06 15:37:24 -07001600
Kirill Tkhai4b793062020-04-01 21:10:18 -07001601 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001602
1603 /* Adding to swap updated mapping */
1604 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001605 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001606 } else if (unlikely(PageTransHuge(page))) {
1607 /* Split file THP */
1608 if (split_huge_page_to_list(page, page_list))
1609 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001610 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001611
1612 /*
Yang Shi98879b32019-07-11 20:59:30 -07001613 * THP may get split above, need minus tail pages and update
1614 * nr_pages to avoid accounting tail pages twice.
1615 *
1616 * The tail pages that are added into swap cache successfully
1617 * reach here.
1618 */
1619 if ((nr_pages > 1) && !PageTransHuge(page)) {
1620 sc->nr_scanned -= (nr_pages - 1);
1621 nr_pages = 1;
1622 }
1623
1624 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001625 * The page is mapped into the page tables of one or more
1626 * processes. Try to unmap it here.
1627 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001628 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001629 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001630 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001631
1632 if (unlikely(PageTransHuge(page)))
1633 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001634
Yang Shi1fb08ac2021-06-30 18:52:01 -07001635 try_to_unmap(page, flags);
1636 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001637 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001638 if (!was_swapbacked && PageSwapBacked(page))
1639 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001640 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001641 }
1642 }
1643
1644 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001645 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001646 * Only kswapd can writeback filesystem pages
1647 * to avoid risk of stack overflow. But avoid
1648 * injecting inefficient single-page IO into
1649 * flusher writeback as much as possible: only
1650 * write pages when we've encountered many
1651 * dirty pages, and when we've already scanned
1652 * the rest of the LRU for clean pages and see
1653 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001654 */
Huang Ying9de4f222020-04-06 20:04:41 -07001655 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001656 (!current_is_kswapd() || !PageReclaim(page) ||
1657 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001658 /*
1659 * Immediately reclaim when written back.
1660 * Similar in principal to deactivate_page()
1661 * except we already have the page isolated
1662 * and know it's dirty
1663 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001664 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001665 SetPageReclaim(page);
1666
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001667 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001668 }
1669
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001670 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001671 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001672 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001673 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001674 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001675 goto keep_locked;
1676
Mel Gormand950c942015-09-04 15:47:35 -07001677 /*
1678 * Page is dirty. Flush the TLB if a writable entry
1679 * potentially exists to avoid CPU writes after IO
1680 * starts and then write it out here.
1681 */
1682 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001683 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001684 case PAGE_KEEP:
1685 goto keep_locked;
1686 case PAGE_ACTIVATE:
1687 goto activate_locked;
1688 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001689 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001690
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001691 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001692 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001693 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001694 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001695
Linus Torvalds1da177e2005-04-16 15:20:36 -07001696 /*
1697 * A synchronous write - probably a ramdisk. Go
1698 * ahead and try to reclaim the page.
1699 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001700 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001701 goto keep;
1702 if (PageDirty(page) || PageWriteback(page))
1703 goto keep_locked;
1704 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001705 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001706 case PAGE_CLEAN:
1707 ; /* try to free the page below */
1708 }
1709 }
1710
1711 /*
1712 * If the page has buffers, try to free the buffer mappings
1713 * associated with this page. If we succeed we try to free
1714 * the page as well.
1715 *
1716 * We do this even if the page is PageDirty().
1717 * try_to_release_page() does not perform I/O, but it is
1718 * possible for a page to have PageDirty set, but it is actually
1719 * clean (all its buffers are clean). This happens if the
1720 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001721 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001722 * try_to_release_page() will discover that cleanness and will
1723 * drop the buffers and mark the page clean - it can be freed.
1724 *
1725 * Rarely, pages can have buffers and no ->mapping. These are
1726 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001727 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001728 * and if that worked, and the page is no longer mapped into
1729 * process address space (page_count == 1) it can be freed.
1730 * Otherwise, leave the page on the LRU so it is swappable.
1731 */
David Howells266cf652009-04-03 16:42:36 +01001732 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001733 if (!try_to_release_page(page, sc->gfp_mask))
1734 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001735 if (!mapping && page_count(page) == 1) {
1736 unlock_page(page);
1737 if (put_page_testzero(page))
1738 goto free_it;
1739 else {
1740 /*
1741 * rare race with speculative reference.
1742 * the speculative reference will free
1743 * this page shortly, so we may
1744 * increment nr_reclaimed here (and
1745 * leave it off the LRU).
1746 */
1747 nr_reclaimed++;
1748 continue;
1749 }
1750 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001751 }
1752
Shaohua Li802a3a92017-05-03 14:52:32 -07001753 if (PageAnon(page) && !PageSwapBacked(page)) {
1754 /* follow __remove_mapping for reference */
1755 if (!page_ref_freeze(page, 1))
1756 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001757 /*
1758 * The page has only one reference left, which is
1759 * from the isolation. After the caller puts the
1760 * page back on lru and drops the reference, the
1761 * page will be freed anyway. It doesn't matter
1762 * which lru it goes. So we don't bother checking
1763 * PageDirty here.
1764 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001765 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001766 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001767 } else if (!mapping || !__remove_mapping(mapping, page, true,
1768 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001769 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001770
1771 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001772free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001773 /*
1774 * THP may get swapped out in a whole, need account
1775 * all base pages.
1776 */
1777 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001778
1779 /*
1780 * Is there need to periodically free_page_list? It would
1781 * appear not as the counts should be low
1782 */
Yang Shi7ae88532019-09-23 15:38:09 -07001783 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001784 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001785 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001786 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001787 continue;
1788
Yang Shi98879b32019-07-11 20:59:30 -07001789activate_locked_split:
1790 /*
1791 * The tail pages that are failed to add into swap cache
1792 * reach here. Fixup nr_scanned and nr_pages.
1793 */
1794 if (nr_pages > 1) {
1795 sc->nr_scanned -= (nr_pages - 1);
1796 nr_pages = 1;
1797 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001798activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001799 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001800 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1801 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001802 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001803 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001804 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001805 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001806 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001807 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001808 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001809 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001810keep_locked:
1811 unlock_page(page);
1812keep:
1813 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001814 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001815 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001816 /* 'page_list' is always empty here */
1817
1818 /* Migrate pages selected for demotion */
1819 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1820 /* Pages that could not be demoted are still in @demote_pages */
1821 if (!list_empty(&demote_pages)) {
1822 /* Pages which failed to demoted go back on @page_list for retry: */
1823 list_splice_init(&demote_pages, page_list);
1824 do_demote_pass = false;
1825 goto retry;
1826 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001827
Yang Shi98879b32019-07-11 20:59:30 -07001828 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1829
Johannes Weiner747db952014-08-08 14:19:24 -07001830 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001831 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001832 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001833
Linus Torvalds1da177e2005-04-16 15:20:36 -07001834 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001835 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001836
Andrew Morton05ff5132006-03-22 00:08:20 -08001837 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001838}
1839
Maninder Singh730ec8c2020-06-03 16:01:18 -07001840unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001841 struct list_head *page_list)
1842{
1843 struct scan_control sc = {
1844 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001845 .may_unmap = 1,
1846 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001847 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001848 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001849 struct page *page, *next;
1850 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001851 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001852
1853 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001854 if (!PageHuge(page) && page_is_file_lru(page) &&
1855 !PageDirty(page) && !__PageMovable(page) &&
1856 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001857 ClearPageActive(page);
1858 list_move(&page->lru, &clean_pages);
1859 }
1860 }
1861
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001862 /*
1863 * We should be safe here since we are only dealing with file pages and
1864 * we are not kswapd and therefore cannot write dirty file pages. But
1865 * call memalloc_noreclaim_save() anyway, just in case these conditions
1866 * change in the future.
1867 */
1868 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001869 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001870 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001871 memalloc_noreclaim_restore(noreclaim_flag);
1872
Minchan Kim02c6de82012-10-08 16:31:55 -07001873 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001874 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1875 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001876 /*
1877 * Since lazyfree pages are isolated from file LRU from the beginning,
1878 * they will rotate back to anonymous LRU in the end if it failed to
1879 * discard so isolated count will be mismatched.
1880 * Compensate the isolated count for both LRU lists.
1881 */
1882 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1883 stat.nr_lazyfree_fail);
1884 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001885 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001886 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001887}
1888
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001889/*
1890 * Attempt to remove the specified page from its LRU. Only take this page
1891 * if it is of the appropriate PageActive status. Pages which are being
1892 * freed elsewhere are also ignored.
1893 *
1894 * page: page to consider
1895 * mode: one of the LRU isolation modes defined above
1896 *
Alex Shic2135f72021-02-24 12:08:01 -08001897 * returns true on success, false on failure.
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001898 */
Alex Shic2135f72021-02-24 12:08:01 -08001899bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001900{
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001901 /* Only take pages on the LRU. */
1902 if (!PageLRU(page))
Alex Shic2135f72021-02-24 12:08:01 -08001903 return false;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001904
Minchan Kime46a2872012-10-08 16:33:48 -07001905 /* Compaction should not handle unevictable pages but CMA can do so */
1906 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
Alex Shic2135f72021-02-24 12:08:01 -08001907 return false;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001908
Mel Gormanc8244932012-01-12 17:19:38 -08001909 /*
1910 * To minimise LRU disruption, the caller can indicate that it only
1911 * wants to isolate pages it will be able to operate on without
1912 * blocking - clean pages for the most part.
1913 *
Mel Gormanc8244932012-01-12 17:19:38 -08001914 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1915 * that it is possible to migrate without blocking
1916 */
Johannes Weiner1276ad62017-02-24 14:56:11 -08001917 if (mode & ISOLATE_ASYNC_MIGRATE) {
Mel Gormanc8244932012-01-12 17:19:38 -08001918 /* All the caller can do on PageWriteback is block */
1919 if (PageWriteback(page))
Alex Shic2135f72021-02-24 12:08:01 -08001920 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001921
1922 if (PageDirty(page)) {
1923 struct address_space *mapping;
Mel Gorman69d763f2018-01-31 16:19:52 -08001924 bool migrate_dirty;
Mel Gormanc8244932012-01-12 17:19:38 -08001925
Mel Gormanc8244932012-01-12 17:19:38 -08001926 /*
1927 * Only pages without mappings or that have a
1928 * ->migratepage callback are possible to migrate
Mel Gorman69d763f2018-01-31 16:19:52 -08001929 * without blocking. However, we can be racing with
1930 * truncation so it's necessary to lock the page
1931 * to stabilise the mapping as truncation holds
1932 * the page lock until after the page is removed
1933 * from the page cache.
Mel Gormanc8244932012-01-12 17:19:38 -08001934 */
Mel Gorman69d763f2018-01-31 16:19:52 -08001935 if (!trylock_page(page))
Alex Shic2135f72021-02-24 12:08:01 -08001936 return false;
Mel Gorman69d763f2018-01-31 16:19:52 -08001937
Mel Gormanc8244932012-01-12 17:19:38 -08001938 mapping = page_mapping(page);
Hugh Dickins145e1a72018-06-01 16:50:50 -07001939 migrate_dirty = !mapping || mapping->a_ops->migratepage;
Mel Gorman69d763f2018-01-31 16:19:52 -08001940 unlock_page(page);
1941 if (!migrate_dirty)
Alex Shic2135f72021-02-24 12:08:01 -08001942 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001943 }
1944 }
Minchan Kim39deaf82011-10-31 17:06:51 -07001945
Minchan Kimf80c0672011-10-31 17:06:55 -07001946 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
Alex Shic2135f72021-02-24 12:08:01 -08001947 return false;
Minchan Kimf80c0672011-10-31 17:06:55 -07001948
Alex Shic2135f72021-02-24 12:08:01 -08001949 return true;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001950}
1951
Mel Gorman7ee36a12016-07-28 15:47:17 -07001952/*
1953 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001954 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001955 */
1956static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001957 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001958{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001959 int zid;
1960
Mel Gorman7ee36a12016-07-28 15:47:17 -07001961 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1962 if (!nr_zone_taken[zid])
1963 continue;
1964
Wei Yanga892cb62020-06-03 16:01:12 -07001965 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001966 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001967
Mel Gorman7ee36a12016-07-28 15:47:17 -07001968}
1969
Mel Gormanf611fab2021-06-30 18:53:19 -07001970/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001971 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1972 *
1973 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001974 * shrink the lists perform better by taking out a batch of pages
1975 * and working on them outside the LRU lock.
1976 *
1977 * For pagecache intensive workloads, this function is the hottest
1978 * spot in the kernel (apart from copy_*_user functions).
1979 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001980 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001981 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001982 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001983 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001984 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001985 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001986 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001987 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001988 *
1989 * returns how many pages were moved onto *@dst.
1990 */
Andrew Morton69e05942006-03-22 00:08:19 -08001991static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001992 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001993 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001994 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001995{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001996 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001997 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001998 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001999 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07002000 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002001 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002002 LIST_HEAD(pages_skipped);
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002003 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002004
Yang Shi98879b32019-07-11 20:59:30 -07002005 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002006 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07002007 while (scan < nr_to_scan && !list_empty(src)) {
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002008 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002009
Linus Torvalds1da177e2005-04-16 15:20:36 -07002010 page = lru_to_page(src);
2011 prefetchw_prev_lru_page(page, src, flags);
2012
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002013 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002014 total_scan += nr_pages;
2015
Mel Gormanb2e18752016-07-28 15:45:37 -07002016 if (page_zonenum(page) > sc->reclaim_idx) {
2017 list_move(&page->lru, &pages_skipped);
Yang Shi98879b32019-07-11 20:59:30 -07002018 nr_skipped[page_zonenum(page)] += nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002019 continue;
2020 }
2021
Minchan Kim791b48b2017-05-12 15:47:06 -07002022 /*
2023 * Do not count skipped pages because that makes the function
2024 * return with no isolated pages if the LRU mostly contains
2025 * ineligible pages. This causes the VM to not reclaim any
2026 * pages, triggering a premature OOM.
Yang Shi98879b32019-07-11 20:59:30 -07002027 *
2028 * Account all tail pages of THP. This would not cause
2029 * premature OOM since __isolate_lru_page() returns -EBUSY
2030 * only when the page is being freed somewhere else.
Minchan Kim791b48b2017-05-12 15:47:06 -07002031 */
Yang Shi98879b32019-07-11 20:59:30 -07002032 scan += nr_pages;
Alex Shic2135f72021-02-24 12:08:01 -08002033 if (!__isolate_lru_page_prepare(page, mode)) {
2034 /* It is being freed elsewhere */
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002035 list_move(&page->lru, src);
Alex Shic2135f72021-02-24 12:08:01 -08002036 continue;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002037 }
Alex Shic2135f72021-02-24 12:08:01 -08002038 /*
2039 * Be careful not to clear PageLRU until after we're
2040 * sure the page is not being freed elsewhere -- the
2041 * page release code relies on it.
2042 */
2043 if (unlikely(!get_page_unless_zero(page))) {
2044 list_move(&page->lru, src);
2045 continue;
2046 }
2047
2048 if (!TestClearPageLRU(page)) {
2049 /* Another thread is already isolating this page */
2050 put_page(page);
2051 list_move(&page->lru, src);
2052 continue;
2053 }
2054
2055 nr_taken += nr_pages;
2056 nr_zone_taken[page_zonenum(page)] += nr_pages;
2057 list_move(&page->lru, dst);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002058 }
2059
Mel Gormanb2e18752016-07-28 15:45:37 -07002060 /*
2061 * Splice any skipped pages to the start of the LRU list. Note that
2062 * this disrupts the LRU order when reclaiming for lower zones but
2063 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2064 * scanning would soon rescan the same pages to skip and put the
2065 * system at risk of premature OOM.
2066 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002067 if (!list_empty(&pages_skipped)) {
2068 int zid;
2069
Johannes Weiner3db65812017-05-03 14:52:13 -07002070 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002071 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2072 if (!nr_skipped[zid])
2073 continue;
2074
2075 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002076 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002077 }
2078 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002079 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002080 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Minchan Kim791b48b2017-05-12 15:47:06 -07002081 total_scan, skipped, nr_taken, mode, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002082 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002083 return nr_taken;
2084}
2085
Nick Piggin62695a82008-10-18 20:26:09 -07002086/**
2087 * isolate_lru_page - tries to isolate a page from its LRU list
2088 * @page: page to isolate from its LRU list
2089 *
2090 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2091 * vmstat statistic corresponding to whatever LRU list the page was on.
2092 *
2093 * Returns 0 if the page was removed from an LRU list.
2094 * Returns -EBUSY if the page was not on an LRU list.
2095 *
2096 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002097 * the active list, it will have PageActive set. If it was found on
2098 * the unevictable list, it will have the PageUnevictable bit set. That flag
2099 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002100 *
2101 * The vmstat statistic corresponding to the list on which the page was
2102 * found will be decremented.
2103 *
2104 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002105 *
Nick Piggin62695a82008-10-18 20:26:09 -07002106 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002107 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002108 * without a stable reference).
2109 * (2) the lru_lock must not be held.
2110 * (3) interrupts must be enabled.
2111 */
2112int isolate_lru_page(struct page *page)
2113{
2114 int ret = -EBUSY;
2115
Sasha Levin309381fea2014-01-23 15:52:54 -08002116 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002117 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002118
Alex Shid25b5bd2020-12-15 12:34:16 -08002119 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002120 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002121
Alex Shid25b5bd2020-12-15 12:34:16 -08002122 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002123 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002124 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002125 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002126 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002127 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002128
Nick Piggin62695a82008-10-18 20:26:09 -07002129 return ret;
2130}
2131
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002132/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002133 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002134 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002135 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2136 * the LRU list will go small and be scanned faster than necessary, leading to
2137 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002138 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002139static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002140 struct scan_control *sc)
2141{
2142 unsigned long inactive, isolated;
2143
2144 if (current_is_kswapd())
2145 return 0;
2146
Johannes Weinerb5ead352019-11-30 17:55:40 -08002147 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002148 return 0;
2149
2150 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002151 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2152 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002153 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002154 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2155 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002156 }
2157
Fengguang Wu3cf23842012-12-18 14:23:31 -08002158 /*
2159 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2160 * won't get blocked by normal direct-reclaimers, forming a circular
2161 * deadlock.
2162 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002163 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002164 inactive >>= 3;
2165
Rik van Riel35cd7812009-09-21 17:01:38 -07002166 return isolated > inactive;
2167}
2168
Kirill Tkhaia222f342019-05-13 17:17:00 -07002169/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002170 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2171 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002172 *
2173 * Returns the number of pages moved to the given lruvec.
2174 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002175static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2176 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002177{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002178 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002179 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002180 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002181
Kirill Tkhaia222f342019-05-13 17:17:00 -07002182 while (!list_empty(list)) {
2183 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002184 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002185 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002186 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002187 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002188 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002189 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002190 continue;
2191 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002192
Alex Shi3d06afa2020-12-15 12:33:37 -08002193 /*
2194 * The SetPageLRU needs to be kept here for list integrity.
2195 * Otherwise:
2196 * #0 move_pages_to_lru #1 release_pages
2197 * if !put_page_testzero
2198 * if (put_page_testzero())
2199 * !PageLRU //skip lru_lock
2200 * SetPageLRU()
2201 * list_add(&page->lru,)
2202 * list_add(&page->lru,)
2203 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002204 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002205
Alex Shi3d06afa2020-12-15 12:33:37 -08002206 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002207 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002208
2209 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002210 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002211 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002212 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002213 } else
2214 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002215
2216 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002217 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002218
Alex Shiafca9152020-12-15 12:34:02 -08002219 /*
2220 * All pages were isolated from the same lruvec (and isolation
2221 * inhibits memcg migration).
2222 */
Muchun Song7467c392021-06-28 19:37:59 -07002223 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002224 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002225 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002226 nr_moved += nr_pages;
2227 if (PageActive(page))
2228 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002229 }
Mel Gorman66635622010-08-09 17:19:30 -07002230
Hugh Dickins3f797682012-01-12 17:20:07 -08002231 /*
2232 * To save our caller's stack, now use input list for pages to free.
2233 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002234 list_splice(&pages_to_free, list);
2235
2236 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002237}
2238
2239/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002240 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002241 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002242 * In that case we should only throttle if the backing device it is
2243 * writing to is congested. In other cases it is safe to throttle.
2244 */
2245static int current_may_throttle(void)
2246{
NeilBrowna37b0712020-06-01 21:48:18 -07002247 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002248 current->backing_dev_info == NULL ||
2249 bdi_write_congested(current->backing_dev_info);
2250}
2251
2252/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002253 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002254 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002255 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002256static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002257shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002258 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002259{
2260 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002261 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002262 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002263 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002264 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002265 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002266 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002267 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002268 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002269
Mel Gorman599d0c92016-07-28 15:45:31 -07002270 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002271 if (stalled)
2272 return 0;
2273
2274 /* wait a bit for the reclaimer. */
2275 msleep(100);
2276 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002277
2278 /* We are about to die and free our memory. Return now. */
2279 if (fatal_signal_pending(current))
2280 return SWAP_CLUSTER_MAX;
2281 }
2282
Linus Torvalds1da177e2005-04-16 15:20:36 -07002283 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002284
Alex Shi6168d0d2020-12-15 12:34:29 -08002285 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002286
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002287 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002288 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002289
Mel Gorman599d0c92016-07-28 15:45:31 -07002290 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002291 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002292 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002293 __count_vm_events(item, nr_scanned);
2294 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002295 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2296
Alex Shi6168d0d2020-12-15 12:34:29 -08002297 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002298
Hillf Dantond563c052012-03-21 16:34:02 -07002299 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002300 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002301
Shakeel Butt013339d2020-12-14 19:06:39 -08002302 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002303
Alex Shi6168d0d2020-12-15 12:34:29 -08002304 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002305 move_pages_to_lru(lruvec, &page_list);
2306
2307 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002308 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002309 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002310 __count_vm_events(item, nr_reclaimed);
2311 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002312 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002313 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002314
Alex Shi75cc3c92020-12-15 14:20:50 -08002315 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002316 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002317 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002318
Mel Gorman92df3a72011-10-31 17:07:56 -07002319 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002320 * If dirty pages are scanned that are not queued for IO, it
2321 * implies that flushers are not doing their job. This can
2322 * happen when memory pressure pushes dirty pages to the end of
2323 * the LRU before the dirty limits are breached and the dirty
2324 * data has expired. It can also happen when the proportion of
2325 * dirty pages grows not through writes but through memory
2326 * pressure reclaiming all the clean cache. And in some cases,
2327 * the flushers simply cannot keep up with the allocation
2328 * rate. Nudge the flusher threads in case they are asleep.
2329 */
2330 if (stat.nr_unqueued_dirty == nr_taken)
2331 wakeup_flusher_threads(WB_REASON_VMSCAN);
2332
Andrey Ryabinind108c772018-04-10 16:27:59 -07002333 sc->nr.dirty += stat.nr_dirty;
2334 sc->nr.congested += stat.nr_congested;
2335 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2336 sc->nr.writeback += stat.nr_writeback;
2337 sc->nr.immediate += stat.nr_immediate;
2338 sc->nr.taken += nr_taken;
2339 if (file)
2340 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002341
Mel Gorman599d0c92016-07-28 15:45:31 -07002342 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002343 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002344 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002345}
2346
Hugh Dickins15b44732020-12-15 14:21:31 -08002347/*
2348 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2349 *
2350 * We move them the other way if the page is referenced by one or more
2351 * processes.
2352 *
2353 * If the pages are mostly unmapped, the processing is fast and it is
2354 * appropriate to hold lru_lock across the whole operation. But if
2355 * the pages are mapped, the processing is slow (page_referenced()), so
2356 * we should drop lru_lock around each page. It's impossible to balance
2357 * this, so instead we remove the pages from the LRU while processing them.
2358 * It is safe to rely on PG_active against the non-LRU pages in here because
2359 * nobody will play with that bit on a non-LRU page.
2360 *
2361 * The downside is that we have to touch page->_refcount against each page.
2362 * But we had to alter page->flags anyway.
2363 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002364static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002365 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002366 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002367 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002368{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002369 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002370 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002371 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002372 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002373 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002374 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002375 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002376 unsigned nr_deactivate, nr_activate;
2377 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002378 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002379 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002380
2381 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002382
Alex Shi6168d0d2020-12-15 12:34:29 -08002383 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002384
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002385 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002386 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002387
Mel Gorman599d0c92016-07-28 15:45:31 -07002388 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002389
Shakeel Butt912c0572020-08-06 23:26:32 -07002390 if (!cgroup_reclaim(sc))
2391 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002392 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002393
Alex Shi6168d0d2020-12-15 12:34:29 -08002394 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002395
Linus Torvalds1da177e2005-04-16 15:20:36 -07002396 while (!list_empty(&l_hold)) {
2397 cond_resched();
2398 page = lru_to_page(&l_hold);
2399 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002400
Hugh Dickins39b5f292012-10-08 16:33:18 -07002401 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002402 putback_lru_page(page);
2403 continue;
2404 }
2405
Mel Gormancc715d92012-03-21 16:34:00 -07002406 if (unlikely(buffer_heads_over_limit)) {
2407 if (page_has_private(page) && trylock_page(page)) {
2408 if (page_has_private(page))
2409 try_to_release_page(page, 0);
2410 unlock_page(page);
2411 }
2412 }
2413
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002414 if (page_referenced(page, 0, sc->target_mem_cgroup,
2415 &vm_flags)) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002416 /*
2417 * Identify referenced, file-backed active pages and
2418 * give them one more trip around the active list. So
2419 * that executable code get better chances to stay in
2420 * memory under moderate memory pressure. Anon pages
2421 * are not likely to be evicted by use-once streaming
2422 * IO, plus JVM can create lots of anon VM_EXEC pages,
2423 * so we ignore them here.
2424 */
Huang Ying9de4f222020-04-06 20:04:41 -07002425 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002426 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002427 list_add(&page->lru, &l_active);
2428 continue;
2429 }
2430 }
Rik van Riel7e9cd482008-10-18 20:26:35 -07002431
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002432 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002433 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002434 list_add(&page->lru, &l_inactive);
2435 }
2436
Andrew Mortonb5557492009-01-06 14:40:13 -08002437 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002438 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002439 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002440 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002441
Kirill Tkhaia222f342019-05-13 17:17:00 -07002442 nr_activate = move_pages_to_lru(lruvec, &l_active);
2443 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002444 /* Keep all free pages in l_active list */
2445 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002446
2447 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2448 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2449
Mel Gorman599d0c92016-07-28 15:45:31 -07002450 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002451 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002452
Kirill Tkhaif372d892019-05-13 17:16:57 -07002453 mem_cgroup_uncharge_list(&l_active);
2454 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002455 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2456 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002457}
2458
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002459unsigned long reclaim_pages(struct list_head *page_list)
2460{
Yang Shif661d002020-04-01 21:10:05 -07002461 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002462 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002463 LIST_HEAD(node_page_list);
2464 struct reclaim_stat dummy_stat;
2465 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002466 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002467 struct scan_control sc = {
2468 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002469 .may_writepage = 1,
2470 .may_unmap = 1,
2471 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002472 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002473 };
2474
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002475 noreclaim_flag = memalloc_noreclaim_save();
2476
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002477 while (!list_empty(page_list)) {
2478 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002479 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002480 nid = page_to_nid(page);
2481 INIT_LIST_HEAD(&node_page_list);
2482 }
2483
2484 if (nid == page_to_nid(page)) {
2485 ClearPageActive(page);
2486 list_move(&page->lru, &node_page_list);
2487 continue;
2488 }
2489
2490 nr_reclaimed += shrink_page_list(&node_page_list,
2491 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002492 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002493 while (!list_empty(&node_page_list)) {
2494 page = lru_to_page(&node_page_list);
2495 list_del(&page->lru);
2496 putback_lru_page(page);
2497 }
2498
Yang Shif661d002020-04-01 21:10:05 -07002499 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002500 }
2501
2502 if (!list_empty(&node_page_list)) {
2503 nr_reclaimed += shrink_page_list(&node_page_list,
2504 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002505 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002506 while (!list_empty(&node_page_list)) {
2507 page = lru_to_page(&node_page_list);
2508 list_del(&page->lru);
2509 putback_lru_page(page);
2510 }
2511 }
2512
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002513 memalloc_noreclaim_restore(noreclaim_flag);
2514
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002515 return nr_reclaimed;
2516}
2517
Johannes Weinerb91ac372019-11-30 17:56:02 -08002518static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2519 struct lruvec *lruvec, struct scan_control *sc)
2520{
2521 if (is_active_lru(lru)) {
2522 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2523 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2524 else
2525 sc->skipped_deactivate = 1;
2526 return 0;
2527 }
2528
2529 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2530}
2531
Rik van Riel59dc76b2016-05-20 16:56:31 -07002532/*
2533 * The inactive anon list should be small enough that the VM never has
2534 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002535 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002536 * The inactive file list should be small enough to leave most memory
2537 * to the established workingset on the scan-resistant active list,
2538 * but large enough to avoid thrashing the aggregate readahead window.
2539 *
2540 * Both inactive lists should also be large enough that each inactive
2541 * page has a chance to be referenced again before it is reclaimed.
2542 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002543 * If that fails and refaulting is observed, the inactive list grows.
2544 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002545 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002546 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002547 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2548 *
2549 * total target max
2550 * memory ratio inactive
2551 * -------------------------------------
2552 * 10MB 1 5MB
2553 * 100MB 1 50MB
2554 * 1GB 3 250MB
2555 * 10GB 10 0.9GB
2556 * 100GB 31 3GB
2557 * 1TB 101 10GB
2558 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002559 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002560static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002561{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002562 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002563 unsigned long inactive, active;
2564 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002565 unsigned long gb;
2566
Johannes Weinerb91ac372019-11-30 17:56:02 -08002567 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2568 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002569
Johannes Weinerb91ac372019-11-30 17:56:02 -08002570 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002571 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002572 inactive_ratio = int_sqrt(10 * gb);
2573 else
2574 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002575
Rik van Riel59dc76b2016-05-20 16:56:31 -07002576 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002577}
2578
Johannes Weiner9a265112013-02-22 16:32:17 -08002579enum scan_balance {
2580 SCAN_EQUAL,
2581 SCAN_FRACT,
2582 SCAN_ANON,
2583 SCAN_FILE,
2584};
2585
Yu Zhao3eb07702020-09-27 20:49:08 -06002586static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2587{
2588 unsigned long file;
2589 struct lruvec *target_lruvec;
2590
Yu Zhaoa1537a62022-01-27 20:32:37 -07002591 if (lru_gen_enabled())
2592 return;
2593
Yu Zhao3eb07702020-09-27 20:49:08 -06002594 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2595
2596 /*
2597 * Flush the memory cgroup stats, so that we read accurate per-memcg
2598 * lruvec stats for heuristics.
2599 */
2600 mem_cgroup_flush_stats();
2601
2602 /*
2603 * Determine the scan balance between anon and file LRUs.
2604 */
2605 spin_lock_irq(&target_lruvec->lru_lock);
2606 sc->anon_cost = target_lruvec->anon_cost;
2607 sc->file_cost = target_lruvec->file_cost;
2608 spin_unlock_irq(&target_lruvec->lru_lock);
2609
2610 /*
2611 * Target desirable inactive:active list ratios for the anon
2612 * and file LRU lists.
2613 */
2614 if (!sc->force_deactivate) {
2615 unsigned long refaults;
2616
2617 refaults = lruvec_page_state(target_lruvec,
2618 WORKINGSET_ACTIVATE_ANON);
2619 if (refaults != target_lruvec->refaults[0] ||
2620 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2621 sc->may_deactivate |= DEACTIVATE_ANON;
2622 else
2623 sc->may_deactivate &= ~DEACTIVATE_ANON;
2624
2625 /*
2626 * When refaults are being observed, it means a new
2627 * workingset is being established. Deactivate to get
2628 * rid of any stale active pages quickly.
2629 */
2630 refaults = lruvec_page_state(target_lruvec,
2631 WORKINGSET_ACTIVATE_FILE);
2632 if (refaults != target_lruvec->refaults[1] ||
2633 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2634 sc->may_deactivate |= DEACTIVATE_FILE;
2635 else
2636 sc->may_deactivate &= ~DEACTIVATE_FILE;
2637 } else
2638 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2639
2640 /*
2641 * If we have plenty of inactive file pages that aren't
2642 * thrashing, try to reclaim those first before touching
2643 * anonymous pages.
2644 */
2645 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2646 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2647 sc->cache_trim_mode = 1;
2648 else
2649 sc->cache_trim_mode = 0;
2650
2651 /*
2652 * Prevent the reclaimer from falling into the cache trap: as
2653 * cache pages start out inactive, every cache fault will tip
2654 * the scan balance towards the file LRU. And as the file LRU
2655 * shrinks, so does the window for rotation from references.
2656 * This means we have a runaway feedback loop where a tiny
2657 * thrashing file LRU becomes infinitely more attractive than
2658 * anon pages. Try to detect this based on file LRU size.
2659 */
2660 if (!cgroup_reclaim(sc)) {
2661 unsigned long total_high_wmark = 0;
2662 unsigned long free, anon;
2663 int z;
2664
2665 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2666 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2667 node_page_state(pgdat, NR_INACTIVE_FILE);
2668
2669 for (z = 0; z < MAX_NR_ZONES; z++) {
2670 struct zone *zone = &pgdat->node_zones[z];
2671
2672 if (!managed_zone(zone))
2673 continue;
2674
2675 total_high_wmark += high_wmark_pages(zone);
2676 }
2677
2678 /*
2679 * Consider anon: if that's low too, this isn't a
2680 * runaway file reclaim problem, but rather just
2681 * extreme pressure. Reclaim as per usual then.
2682 */
2683 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2684
2685 sc->file_is_tiny =
2686 file + free <= total_high_wmark &&
2687 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2688 anon >> sc->priority;
2689 }
2690}
2691
Linus Torvalds1da177e2005-04-16 15:20:36 -07002692/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002693 * Determine how aggressively the anon and file LRU lists should be
2694 * scanned. The relative value of each set of LRU lists is determined
2695 * by looking at the fraction of the pages scanned we did rotate back
2696 * onto the active list instead of evict.
2697 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002698 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2699 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002700 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002701static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2702 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002703{
Keith Buscha2a36482021-09-02 14:59:26 -07002704 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002705 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002706 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002707 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002708 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002709 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002710 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002711 unsigned long ap, fp;
2712 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002713 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002714
2715 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002716 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002717 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002718 goto out;
2719 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002720
Johannes Weiner10316b32013-02-22 16:32:14 -08002721 /*
2722 * Global reclaim will swap to prevent OOM even with no
2723 * swappiness, but memcg users want to use this knob to
2724 * disable swapping for individual groups completely when
2725 * using the memory controller's swap limit feature would be
2726 * too expensive.
2727 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002728 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002729 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002730 goto out;
2731 }
2732
2733 /*
2734 * Do not apply any pressure balancing cleverness when the
2735 * system is close to OOM, scan both anon and file equally
2736 * (unless the swappiness setting disagrees with swapping).
2737 */
Johannes Weiner02695172014-08-06 16:06:17 -07002738 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002739 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002740 goto out;
2741 }
2742
Johannes Weiner11d16c22013-02-22 16:32:15 -08002743 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002744 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002745 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002746 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002747 scan_balance = SCAN_ANON;
2748 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002749 }
2750
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002751 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2752
Johannes Weiner62376252014-05-06 12:50:07 -07002753 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002754 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002755 * anything from the anonymous working right now. But when balancing
2756 * anon and page cache files for reclaim, allow swapping of anon pages
2757 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002758 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002759 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002760 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002761 goto out;
2762 }
2763
Johannes Weiner9a265112013-02-22 16:32:17 -08002764 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002765 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002766 * Calculate the pressure balance between anon and file pages.
2767 *
2768 * The amount of pressure we put on each LRU is inversely
2769 * proportional to the cost of reclaiming each list, as
2770 * determined by the share of pages that are refaulting, times
2771 * the relative IO cost of bringing back a swapped out
2772 * anonymous page vs reloading a filesystem page (swappiness).
2773 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002774 * Although we limit that influence to ensure no list gets
2775 * left behind completely: at least a third of the pressure is
2776 * applied, before swappiness.
2777 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002778 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002779 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002780 total_cost = sc->anon_cost + sc->file_cost;
2781 anon_cost = total_cost + sc->anon_cost;
2782 file_cost = total_cost + sc->file_cost;
2783 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002784
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002785 ap = swappiness * (total_cost + 1);
2786 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002787
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002788 fp = (200 - swappiness) * (total_cost + 1);
2789 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002790
Shaohua Li76a33fc2010-05-24 14:32:36 -07002791 fraction[0] = ap;
2792 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002793 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002794out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002795 for_each_evictable_lru(lru) {
2796 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002797 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002798 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002799 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002800
Chris Down9783aa92019-10-06 17:58:32 -07002801 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002802 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2803 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002804
Johannes Weinerf56ce412021-08-19 19:04:21 -07002805 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002806 /*
2807 * Scale a cgroup's reclaim pressure by proportioning
2808 * its current usage to its memory.low or memory.min
2809 * setting.
2810 *
2811 * This is important, as otherwise scanning aggression
2812 * becomes extremely binary -- from nothing as we
2813 * approach the memory protection threshold, to totally
2814 * nominal as we exceed it. This results in requiring
2815 * setting extremely liberal protection thresholds. It
2816 * also means we simply get no protection at all if we
2817 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002818 *
2819 * If there is any protection in place, we reduce scan
2820 * pressure by how much of the total memory used is
2821 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002822 *
Chris Down9de7ca42019-10-06 17:58:35 -07002823 * There is one special case: in the first reclaim pass,
2824 * we skip over all groups that are within their low
2825 * protection. If that fails to reclaim enough pages to
2826 * satisfy the reclaim goal, we come back and override
2827 * the best-effort low protection. However, we still
2828 * ideally want to honor how well-behaved groups are in
2829 * that case instead of simply punishing them all
2830 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002831 * memory they are using, reducing the scan pressure
2832 * again by how much of the total memory used is under
2833 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002834 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002835 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002836 unsigned long protection;
2837
2838 /* memory.low scaling, make sure we retry before OOM */
2839 if (!sc->memcg_low_reclaim && low > min) {
2840 protection = low;
2841 sc->memcg_low_skipped = 1;
2842 } else {
2843 protection = min;
2844 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002845
2846 /* Avoid TOCTOU with earlier protection check */
2847 cgroup_size = max(cgroup_size, protection);
2848
2849 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002850 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002851
2852 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002853 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002854 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002855 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002856 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002857 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002858 } else {
2859 scan = lruvec_size;
2860 }
2861
2862 scan >>= sc->priority;
2863
Johannes Weiner688035f2017-05-03 14:52:07 -07002864 /*
2865 * If the cgroup's already been deleted, make sure to
2866 * scrape out the remaining cache.
2867 */
2868 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002869 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002870
Johannes Weiner688035f2017-05-03 14:52:07 -07002871 switch (scan_balance) {
2872 case SCAN_EQUAL:
2873 /* Scan lists relative to size */
2874 break;
2875 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002876 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002877 * Scan types proportional to swappiness and
2878 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002879 * Make sure we don't miss the last page on
2880 * the offlined memory cgroups because of a
2881 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002882 */
Gavin Shan76073c62020-02-20 20:04:24 -08002883 scan = mem_cgroup_online(memcg) ?
2884 div64_u64(scan * fraction[file], denominator) :
2885 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002886 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002887 break;
2888 case SCAN_FILE:
2889 case SCAN_ANON:
2890 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002891 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002892 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002893 break;
2894 default:
2895 /* Look ma, no brain */
2896 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002897 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002898
Johannes Weiner688035f2017-05-03 14:52:07 -07002899 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002900 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002901}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002902
Dave Hansen2f368a92021-09-02 14:59:23 -07002903/*
2904 * Anonymous LRU management is a waste if there is
2905 * ultimately no way to reclaim the memory.
2906 */
2907static bool can_age_anon_pages(struct pglist_data *pgdat,
2908 struct scan_control *sc)
2909{
2910 /* Aging the anon LRU is valuable if swap is present: */
2911 if (total_swap_pages > 0)
2912 return true;
2913
2914 /* Also valuable if anon pages can be demoted: */
2915 return can_demote(pgdat->node_id, sc);
2916}
2917
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002918#ifdef CONFIG_LRU_GEN
2919
Yu Zhao76f7f072022-01-27 19:52:09 -07002920#ifdef CONFIG_LRU_GEN_ENABLED
2921DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2922#else
2923DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2924#endif
2925
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002926/******************************************************************************
2927 * shorthand helpers
2928 ******************************************************************************/
2929
Yu Zhaoa1537a62022-01-27 20:32:37 -07002930#define DEFINE_MAX_SEQ(lruvec) \
2931 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2932
2933#define DEFINE_MIN_SEQ(lruvec) \
2934 unsigned long min_seq[ANON_AND_FILE] = { \
2935 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2936 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2937 }
2938
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002939#define for_each_gen_type_zone(gen, type, zone) \
2940 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2941 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2942 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2943
Yu Zhaoa1537a62022-01-27 20:32:37 -07002944static int page_lru_gen(struct page *page)
2945{
2946 unsigned long flags = READ_ONCE(page->flags);
2947
2948 return ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
2949}
2950
2951static int page_lru_tier(struct page *page)
2952{
2953 int refs;
2954 unsigned long flags = READ_ONCE(page->flags);
2955
2956 refs = (flags & LRU_REFS_FLAGS) == LRU_REFS_FLAGS ?
2957 ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) + 1 : 0;
2958
2959 return lru_tier_from_refs(refs);
2960}
2961
Yu Zhao76f7f072022-01-27 19:52:09 -07002962static bool get_cap(int cap)
2963{
2964#ifdef CONFIG_LRU_GEN_ENABLED
2965 return static_branch_likely(&lru_gen_caps[cap]);
2966#else
2967 return static_branch_unlikely(&lru_gen_caps[cap]);
2968#endif
2969}
2970
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002971static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
2972{
2973 struct pglist_data *pgdat = NODE_DATA(nid);
2974
2975#ifdef CONFIG_MEMCG
2976 if (memcg) {
2977 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2978
2979 /* for hotadd_new_pgdat() */
2980 if (!lruvec->pgdat)
2981 lruvec->pgdat = pgdat;
2982
2983 return lruvec;
2984 }
2985#endif
2986 VM_BUG_ON(!mem_cgroup_disabled());
2987
2988 return pgdat ? &pgdat->__lruvec : NULL;
2989}
2990
Yu Zhaoa1537a62022-01-27 20:32:37 -07002991static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2992{
2993 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2994 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2995
2996 if (!can_demote(pgdat->node_id, sc) &&
2997 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2998 return 0;
2999
3000 return mem_cgroup_swappiness(memcg);
3001}
3002
3003static int get_nr_gens(struct lruvec *lruvec, int type)
3004{
3005 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3006}
3007
3008static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3009{
3010 /* see the comment on lru_gen_struct */
3011 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3012 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3013 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3014}
3015
3016/******************************************************************************
Yu Zhao5280d762022-01-27 19:23:01 -07003017 * mm_struct list
3018 ******************************************************************************/
3019
3020static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3021{
3022 static struct lru_gen_mm_list mm_list = {
3023 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3024 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3025 };
3026
3027#ifdef CONFIG_MEMCG
3028 if (memcg)
3029 return &memcg->mm_list;
3030#endif
3031 VM_BUG_ON(!mem_cgroup_disabled());
3032
3033 return &mm_list;
3034}
3035
3036void lru_gen_add_mm(struct mm_struct *mm)
3037{
3038 int nid;
3039 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3040 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3041
3042 VM_BUG_ON_MM(!list_empty(&mm->lru_gen.list), mm);
3043#ifdef CONFIG_MEMCG
3044 VM_BUG_ON_MM(mm->lru_gen.memcg, mm);
3045 mm->lru_gen.memcg = memcg;
3046#endif
3047 spin_lock(&mm_list->lock);
3048
3049 for_each_node_state(nid, N_MEMORY) {
3050 struct lruvec *lruvec = get_lruvec(memcg, nid);
3051
3052 if (!lruvec)
3053 continue;
3054
3055 if (lruvec->mm_state.tail == &mm_list->fifo)
3056 lruvec->mm_state.tail = &mm->lru_gen.list;
3057 }
3058
3059 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3060
3061 spin_unlock(&mm_list->lock);
3062}
3063
3064void lru_gen_del_mm(struct mm_struct *mm)
3065{
3066 int nid;
3067 struct lru_gen_mm_list *mm_list;
3068 struct mem_cgroup *memcg = NULL;
3069
3070 if (list_empty(&mm->lru_gen.list))
3071 return;
3072
3073#ifdef CONFIG_MEMCG
3074 memcg = mm->lru_gen.memcg;
3075#endif
3076 mm_list = get_mm_list(memcg);
3077
3078 spin_lock(&mm_list->lock);
3079
3080 for_each_node(nid) {
3081 struct lruvec *lruvec = get_lruvec(memcg, nid);
3082
3083 if (!lruvec)
3084 continue;
3085
3086 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3087 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3088
3089 if (lruvec->mm_state.head != &mm->lru_gen.list)
3090 continue;
3091
3092 lruvec->mm_state.head = lruvec->mm_state.head->next;
3093 if (lruvec->mm_state.head == &mm_list->fifo)
3094 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3095 }
3096
3097 list_del_init(&mm->lru_gen.list);
3098
3099 spin_unlock(&mm_list->lock);
3100
3101#ifdef CONFIG_MEMCG
3102 mem_cgroup_put(mm->lru_gen.memcg);
3103 mm->lru_gen.memcg = NULL;
3104#endif
3105}
3106
3107#ifdef CONFIG_MEMCG
3108void lru_gen_migrate_mm(struct mm_struct *mm)
3109{
3110 struct mem_cgroup *memcg;
3111
3112 lockdep_assert_held(&mm->owner->alloc_lock);
3113
3114 /* for mm_update_next_owner() */
3115 if (mem_cgroup_disabled())
3116 return;
3117
3118 rcu_read_lock();
3119 memcg = mem_cgroup_from_task(mm->owner);
3120 rcu_read_unlock();
3121 if (memcg == mm->lru_gen.memcg)
3122 return;
3123
3124 VM_BUG_ON_MM(!mm->lru_gen.memcg, mm);
3125 VM_BUG_ON_MM(list_empty(&mm->lru_gen.list), mm);
3126
3127 lru_gen_del_mm(mm);
3128 lru_gen_add_mm(mm);
3129}
3130#endif
3131
3132/*
3133 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3134 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3135 * bits in a bitmap, k is the number of hash functions and n is the number of
3136 * inserted items.
3137 *
3138 * Page table walkers use one of the two filters to reduce their search space.
3139 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3140 * aging uses the double-buffering technique to flip to the other filter each
3141 * time it produces a new generation. For non-leaf entries that have enough
3142 * leaf entries, the aging carries them over to the next generation in
3143 * walk_pmd_range(); the eviction also report them when walking the rmap
3144 * in lru_gen_look_around().
3145 *
3146 * For future optimizations:
3147 * 1. It's not necessary to keep both filters all the time. The spare one can be
3148 * freed after the RCU grace period and reallocated if needed again.
3149 * 2. And when reallocating, it's worth scaling its size according to the number
3150 * of inserted entries in the other filter, to reduce the memory overhead on
3151 * small systems and false positives on large systems.
3152 * 3. Jenkins' hash function is an alternative to Knuth's.
3153 */
3154#define BLOOM_FILTER_SHIFT 15
3155
3156static inline int filter_gen_from_seq(unsigned long seq)
3157{
3158 return seq % NR_BLOOM_FILTERS;
3159}
3160
3161static void get_item_key(void *item, int *key)
3162{
3163 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3164
3165 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3166
3167 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3168 key[1] = hash >> BLOOM_FILTER_SHIFT;
3169}
3170
3171static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3172{
3173 unsigned long *filter;
3174 int gen = filter_gen_from_seq(seq);
3175
3176 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3177
3178 filter = lruvec->mm_state.filters[gen];
3179 if (filter) {
3180 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3181 return;
3182 }
3183
3184 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT), GFP_ATOMIC);
3185 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3186}
3187
3188static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3189{
3190 int key[2];
3191 unsigned long *filter;
3192 int gen = filter_gen_from_seq(seq);
3193
3194 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3195 if (!filter)
3196 return;
3197
3198 get_item_key(item, key);
3199
3200 if (!test_bit(key[0], filter))
3201 set_bit(key[0], filter);
3202 if (!test_bit(key[1], filter))
3203 set_bit(key[1], filter);
3204}
3205
3206static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3207{
3208 int key[2];
3209 unsigned long *filter;
3210 int gen = filter_gen_from_seq(seq);
3211
3212 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3213 if (!filter)
3214 return true;
3215
3216 get_item_key(item, key);
3217
3218 return test_bit(key[0], filter) && test_bit(key[1], filter);
3219}
3220
3221static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3222{
3223 int i;
3224 int hist;
3225
3226 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3227
3228 if (walk) {
3229 hist = lru_hist_from_seq(walk->max_seq);
3230
3231 for (i = 0; i < NR_MM_STATS; i++) {
3232 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3233 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3234 walk->mm_stats[i] = 0;
3235 }
3236 }
3237
3238 if (NR_HIST_GENS > 1 && last) {
3239 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3240
3241 for (i = 0; i < NR_MM_STATS; i++)
3242 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3243 }
3244}
3245
3246static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3247{
3248 int type;
3249 unsigned long size = 0;
3250 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3251
3252 if (!walk->full_scan && cpumask_empty(mm_cpumask(mm)) &&
3253 !node_isset(pgdat->node_id, mm->lru_gen.nodes))
3254 return true;
3255
3256 node_clear(pgdat->node_id, mm->lru_gen.nodes);
3257
3258 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3259 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3260 get_mm_counter(mm, MM_ANONPAGES) +
3261 get_mm_counter(mm, MM_SHMEMPAGES);
3262 }
3263
3264 if (size < MIN_LRU_BATCH)
3265 return true;
3266
3267 if (mm_is_oom_victim(mm))
3268 return true;
3269
3270 return !mmget_not_zero(mm);
3271}
3272
3273static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3274 struct mm_struct **iter)
3275{
3276 bool first = false;
3277 bool last = true;
3278 struct mm_struct *mm = NULL;
3279 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3280 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3281 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3282
3283 /*
3284 * There are four interesting cases for this page table walker:
3285 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3286 * there is nothing to be done.
3287 * 2. It's the first of the current generation, and it needs to reset
3288 * the Bloom filter for the next generation.
3289 * 3. It reaches the end of mm_list, and it needs to increment
3290 * mm_state->seq; the iteration is done.
3291 * 4. It's the last of the current generation, and it needs to reset the
3292 * mm stats counters for the next generation.
3293 */
3294 if (*iter)
3295 mmput_async(*iter);
3296 else if (walk->max_seq <= READ_ONCE(mm_state->seq))
3297 return false;
3298
3299 spin_lock(&mm_list->lock);
3300
3301 VM_BUG_ON(mm_state->seq + 1 < walk->max_seq);
3302 VM_BUG_ON(*iter && mm_state->seq > walk->max_seq);
3303 VM_BUG_ON(*iter && !mm_state->nr_walkers);
3304
3305 if (walk->max_seq <= mm_state->seq) {
3306 if (!*iter)
3307 last = false;
3308 goto done;
3309 }
3310
3311 if (!mm_state->nr_walkers) {
3312 VM_BUG_ON(mm_state->head && mm_state->head != &mm_list->fifo);
3313
3314 mm_state->head = mm_list->fifo.next;
3315 first = true;
3316 }
3317
3318 while (!mm && mm_state->head != &mm_list->fifo) {
3319 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3320
3321 mm_state->head = mm_state->head->next;
3322
3323 /* full scan for those added after the last iteration */
3324 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3325 mm_state->tail = mm_state->head;
3326 walk->full_scan = true;
3327 }
3328
3329 if (should_skip_mm(mm, walk))
3330 mm = NULL;
3331 }
3332
3333 if (mm_state->head == &mm_list->fifo)
3334 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3335done:
3336 if (*iter && !mm)
3337 mm_state->nr_walkers--;
3338 if (!*iter && mm)
3339 mm_state->nr_walkers++;
3340
3341 if (mm_state->nr_walkers)
3342 last = false;
3343
3344 if (mm && first)
3345 reset_bloom_filter(lruvec, walk->max_seq + 1);
3346
3347 if (*iter || last)
3348 reset_mm_stats(lruvec, walk, last);
3349
3350 spin_unlock(&mm_list->lock);
3351
3352 *iter = mm;
3353
3354 return last;
3355}
3356
3357static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3358{
3359 bool success = false;
3360 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3361 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3362 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3363
3364 if (max_seq <= READ_ONCE(mm_state->seq))
3365 return false;
3366
3367 spin_lock(&mm_list->lock);
3368
3369 VM_BUG_ON(mm_state->seq + 1 < max_seq);
3370
3371 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3372 VM_BUG_ON(mm_state->head && mm_state->head != &mm_list->fifo);
3373
3374 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3375 reset_mm_stats(lruvec, NULL, true);
3376 success = true;
3377 }
3378
3379 spin_unlock(&mm_list->lock);
3380
3381 return success;
3382}
3383
3384/******************************************************************************
Yu Zhaoa1537a62022-01-27 20:32:37 -07003385 * refault feedback loop
3386 ******************************************************************************/
3387
3388/*
3389 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3390 *
3391 * The P term is refaulted/(evicted+protected) from a tier in the generation
3392 * currently being evicted; the I term is the exponential moving average of the
3393 * P term over the generations previously evicted, using the smoothing factor
3394 * 1/2; the D term isn't supported.
3395 *
3396 * The setpoint (SP) is always the first tier of one type; the process variable
3397 * (PV) is either any tier of the other type or any other tier of the same
3398 * type.
3399 *
3400 * The error is the difference between the SP and the PV; the correction is
3401 * turn off protection when SP>PV or turn on protection when SP<PV.
3402 *
3403 * For future optimizations:
3404 * 1. The D term may discount the other two terms over time so that long-lived
3405 * generations can resist stale information.
3406 */
3407struct ctrl_pos {
3408 unsigned long refaulted;
3409 unsigned long total;
3410 int gain;
3411};
3412
3413static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3414 struct ctrl_pos *pos)
3415{
3416 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3417 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3418
3419 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3420 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3421 pos->total = lrugen->avg_total[type][tier] +
3422 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3423 if (tier)
3424 pos->total += lrugen->protected[hist][type][tier - 1];
3425 pos->gain = gain;
3426}
3427
3428static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3429{
3430 int hist, tier;
3431 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3432 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3433 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3434
3435 lockdep_assert_held(&lruvec->lru_lock);
3436
3437 if (!carryover && !clear)
3438 return;
3439
3440 hist = lru_hist_from_seq(seq);
3441
3442 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3443 if (carryover) {
3444 unsigned long sum;
3445
3446 sum = lrugen->avg_refaulted[type][tier] +
3447 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3448 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3449
3450 sum = lrugen->avg_total[type][tier] +
3451 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3452 if (tier)
3453 sum += lrugen->protected[hist][type][tier - 1];
3454 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3455 }
3456
3457 if (clear) {
3458 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3459 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3460 if (tier)
3461 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3462 }
3463 }
3464}
3465
3466static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3467{
3468 /*
3469 * Return true if the PV has a limited number of refaults or a lower
3470 * refaulted/total than the SP.
3471 */
3472 return pv->refaulted < MIN_LRU_BATCH ||
3473 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3474 (sp->refaulted + 1) * pv->total * pv->gain;
3475}
3476
3477/******************************************************************************
3478 * the aging
3479 ******************************************************************************/
3480
Yu Zhaoafd94c92022-01-27 20:43:22 -07003481static int page_update_gen(struct page *page, int gen)
3482{
3483 unsigned long old_flags, new_flags;
3484
3485 VM_BUG_ON(gen >= MAX_NR_GENS);
3486 VM_BUG_ON(!rcu_read_lock_held());
3487
3488 do {
3489 new_flags = old_flags = READ_ONCE(page->flags);
3490
3491 /* for shrink_page_list() */
3492 if (!(new_flags & LRU_GEN_MASK)) {
3493 new_flags |= BIT(PG_referenced);
3494 continue;
3495 }
3496
3497 new_flags &= ~LRU_GEN_MASK;
3498 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3499 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3500 } while (new_flags != old_flags &&
3501 cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3502
3503 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3504}
3505
Yu Zhaoa1537a62022-01-27 20:32:37 -07003506static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3507{
3508 unsigned long old_flags, new_flags;
3509 int type = page_is_file_lru(page);
3510 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3511 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3512
3513 do {
3514 new_flags = old_flags = READ_ONCE(page->flags);
3515 VM_BUG_ON_PAGE(!(new_flags & LRU_GEN_MASK), page);
3516
Yu Zhaoafd94c92022-01-27 20:43:22 -07003517 new_gen = ((new_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3518 /* page_update_gen() has promoted this page? */
3519 if (new_gen >= 0 && new_gen != old_gen)
3520 return new_gen;
3521
Yu Zhaoa1537a62022-01-27 20:32:37 -07003522 new_gen = (old_gen + 1) % MAX_NR_GENS;
3523
3524 new_flags &= ~LRU_GEN_MASK;
3525 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3526 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3527 /* for end_page_writeback() */
3528 if (reclaiming)
3529 new_flags |= BIT(PG_reclaim);
3530 } while (cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3531
3532 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3533
3534 return new_gen;
3535}
3536
Yu Zhao5280d762022-01-27 19:23:01 -07003537static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3538 int old_gen, int new_gen)
3539{
3540 int type = page_is_file_lru(page);
3541 int zone = page_zonenum(page);
3542 int delta = thp_nr_pages(page);
3543
3544 VM_BUG_ON(old_gen >= MAX_NR_GENS);
3545 VM_BUG_ON(new_gen >= MAX_NR_GENS);
3546
3547 walk->batched++;
3548
3549 walk->nr_pages[old_gen][type][zone] -= delta;
3550 walk->nr_pages[new_gen][type][zone] += delta;
3551}
3552
3553static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3554{
3555 int gen, type, zone;
3556 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3557
3558 walk->batched = 0;
3559
3560 for_each_gen_type_zone(gen, type, zone) {
3561 enum lru_list lru = type * LRU_INACTIVE_FILE;
3562 int delta = walk->nr_pages[gen][type][zone];
3563
3564 if (!delta)
3565 continue;
3566
3567 walk->nr_pages[gen][type][zone] = 0;
3568 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3569 lrugen->nr_pages[gen][type][zone] + delta);
3570
3571 if (lru_gen_is_active(lruvec, gen))
3572 lru += LRU_ACTIVE;
3573 __update_lru_size(lruvec, lru, zone, delta);
3574 }
3575}
3576
3577static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *walk)
3578{
3579 struct address_space *mapping;
3580 struct vm_area_struct *vma = walk->vma;
3581 struct lru_gen_mm_walk *priv = walk->private;
3582
3583 if (!vma_is_accessible(vma) || is_vm_hugetlb_page(vma) ||
3584 (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ)) ||
3585 vma == get_gate_vma(vma->vm_mm))
3586 return true;
3587
3588 if (vma_is_anonymous(vma))
3589 return !priv->can_swap;
3590
3591 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3592 return true;
3593
3594 mapping = vma->vm_file->f_mapping;
3595 if (mapping_unevictable(mapping))
3596 return true;
3597
3598 /* check readpage to exclude special mappings like dax, etc. */
3599 return shmem_mapping(mapping) ? !priv->can_swap : !mapping->a_ops->readpage;
3600}
3601
3602/*
3603 * Some userspace memory allocators map many single-page VMAs. Instead of
3604 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3605 * table to reduce zigzags and improve cache performance.
3606 */
3607static bool get_next_vma(struct mm_walk *walk, unsigned long mask, unsigned long size,
3608 unsigned long *start, unsigned long *end)
3609{
3610 unsigned long next = round_up(*end, size);
3611
3612 VM_BUG_ON(mask & size);
3613 VM_BUG_ON(*start >= *end);
3614 VM_BUG_ON((next & mask) != (*start & mask));
3615
3616 while (walk->vma) {
3617 if (next >= walk->vma->vm_end) {
3618 walk->vma = walk->vma->vm_next;
3619 continue;
3620 }
3621
3622 if ((next & mask) != (walk->vma->vm_start & mask))
3623 return false;
3624
3625 if (should_skip_vma(walk->vma->vm_start, walk->vma->vm_end, walk)) {
3626 walk->vma = walk->vma->vm_next;
3627 continue;
3628 }
3629
3630 *start = max(next, walk->vma->vm_start);
3631 next = (next | ~mask) + 1;
3632 /* rounded-up boundaries can wrap to 0 */
3633 *end = next && next < walk->vma->vm_end ? next : walk->vma->vm_end;
3634
3635 return true;
3636 }
3637
3638 return false;
3639}
3640
3641static bool suitable_to_scan(int total, int young)
3642{
3643 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3644
3645 /* suitable if the average number of young PTEs per cacheline is >=1 */
3646 return young * n >= total;
3647}
3648
3649static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3650 struct mm_walk *walk)
3651{
3652 int i;
3653 pte_t *pte;
3654 spinlock_t *ptl;
3655 unsigned long addr;
3656 int total = 0;
3657 int young = 0;
3658 struct lru_gen_mm_walk *priv = walk->private;
3659 struct mem_cgroup *memcg = lruvec_memcg(priv->lruvec);
3660 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3661 int old_gen, new_gen = lru_gen_from_seq(priv->max_seq);
3662
3663 VM_BUG_ON(pmd_leaf(*pmd));
3664
3665 ptl = pte_lockptr(walk->mm, pmd);
3666 if (!spin_trylock(ptl))
3667 return false;
3668
3669 arch_enter_lazy_mmu_mode();
3670
3671 pte = pte_offset_map(pmd, start & PMD_MASK);
3672restart:
3673 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3674 struct page *page;
3675 unsigned long pfn = pte_pfn(pte[i]);
3676
3677 VM_BUG_ON(addr < walk->vma->vm_start || addr >= walk->vma->vm_end);
3678
3679 total++;
3680 priv->mm_stats[MM_PTE_TOTAL]++;
3681
3682 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
3683 continue;
3684
3685 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
3686 continue;
3687
3688 if (!pte_young(pte[i])) {
3689 priv->mm_stats[MM_PTE_OLD]++;
3690 continue;
3691 }
3692
3693 VM_BUG_ON(!pfn_valid(pfn));
3694 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3695 continue;
3696
3697 page = compound_head(pfn_to_page(pfn));
3698 if (page_to_nid(page) != pgdat->node_id)
3699 continue;
3700
3701 if (page_memcg_rcu(page) != memcg)
3702 continue;
3703
3704 if (!ptep_test_and_clear_young(walk->vma, addr, pte + i))
3705 continue;
3706
3707 young++;
3708 priv->mm_stats[MM_PTE_YOUNG]++;
3709
3710 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3711 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3712 set_page_dirty(page);
3713
3714 old_gen = page_update_gen(page, new_gen);
3715 if (old_gen >= 0 && old_gen != new_gen)
3716 update_batch_size(priv, page, old_gen, new_gen);
3717 }
3718
3719 if (i < PTRS_PER_PTE && get_next_vma(walk, PMD_MASK, PAGE_SIZE, &start, &end))
3720 goto restart;
3721
3722 pte_unmap(pte);
3723
3724 arch_leave_lazy_mmu_mode();
3725 spin_unlock(ptl);
3726
3727 return suitable_to_scan(total, young);
3728}
3729
3730#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3731static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3732 struct mm_walk *walk, unsigned long *start)
3733{
3734 int i;
3735 pmd_t *pmd;
3736 spinlock_t *ptl;
3737 struct lru_gen_mm_walk *priv = walk->private;
3738 struct mem_cgroup *memcg = lruvec_memcg(priv->lruvec);
3739 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3740 int old_gen, new_gen = lru_gen_from_seq(priv->max_seq);
3741
3742 VM_BUG_ON(pud_leaf(*pud));
3743
3744 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3745 if (*start == -1) {
3746 *start = next;
3747 return;
3748 }
3749
3750 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3751 if (i && i <= MIN_LRU_BATCH) {
3752 __set_bit(i - 1, priv->bitmap);
3753 return;
3754 }
3755
3756 pmd = pmd_offset(pud, *start);
3757
3758 ptl = pmd_lockptr(walk->mm, pmd);
3759 if (!spin_trylock(ptl))
3760 goto done;
3761
3762 arch_enter_lazy_mmu_mode();
3763
3764 do {
3765 struct page *page;
3766 unsigned long pfn = pmd_pfn(pmd[i]);
3767 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3768
3769 VM_BUG_ON(addr < vma->vm_start || addr >= vma->vm_end);
3770
3771 if (!pmd_present(pmd[i]) || is_huge_zero_pmd(pmd[i]))
3772 goto next;
3773
3774 if (WARN_ON_ONCE(pmd_devmap(pmd[i])))
3775 goto next;
3776
3777 if (!pmd_trans_huge(pmd[i])) {
Yu Zhao76f7f072022-01-27 19:52:09 -07003778 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3779 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao5280d762022-01-27 19:23:01 -07003780 pmdp_test_and_clear_young(vma, addr, pmd + i);
3781 goto next;
3782 }
3783
3784 VM_BUG_ON(!pfn_valid(pfn));
3785 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3786 goto next;
3787
3788 page = pfn_to_page(pfn);
3789 VM_BUG_ON_PAGE(PageTail(page), page);
3790 if (page_to_nid(page) != pgdat->node_id)
3791 goto next;
3792
3793 if (page_memcg_rcu(page) != memcg)
3794 goto next;
3795
3796 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3797 goto next;
3798
3799 priv->mm_stats[MM_PTE_YOUNG]++;
3800
3801 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3802 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3803 set_page_dirty(page);
3804
3805 old_gen = page_update_gen(page, new_gen);
3806 if (old_gen >= 0 && old_gen != new_gen)
3807 update_batch_size(priv, page, old_gen, new_gen);
3808next:
3809 i = i > MIN_LRU_BATCH ? 0 :
3810 find_next_bit(priv->bitmap, MIN_LRU_BATCH, i) + 1;
3811 } while (i <= MIN_LRU_BATCH);
3812
3813 arch_leave_lazy_mmu_mode();
3814 spin_unlock(ptl);
3815done:
3816 *start = -1;
3817 bitmap_zero(priv->bitmap, MIN_LRU_BATCH);
3818}
3819#else
3820static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3821 struct mm_walk *walk, unsigned long *start)
3822{
3823}
3824#endif
3825
3826static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3827 struct mm_walk *walk)
3828{
3829 int i;
3830 pmd_t *pmd;
3831 unsigned long next;
3832 unsigned long addr;
3833 struct vm_area_struct *vma;
3834 unsigned long pos = -1;
3835 struct lru_gen_mm_walk *priv = walk->private;
3836
3837 VM_BUG_ON(pud_leaf(*pud));
3838
3839 /*
3840 * Finish an entire PMD in two passes: the first only reaches to PTE
3841 * tables to avoid taking the PMD lock; the second, if necessary, takes
3842 * the PMD lock to clear the accessed bit in PMD entries.
3843 */
3844 pmd = pmd_offset(pud, start & PUD_MASK);
3845restart:
3846 /* walk_pte_range() may call get_next_vma() */
3847 vma = walk->vma;
3848 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3849 pmd_t val = pmd_read_atomic(pmd + i);
3850
3851 /* for pmd_read_atomic() */
3852 barrier();
3853
3854 next = pmd_addr_end(addr, end);
3855
3856 if (!pmd_present(val)) {
3857 priv->mm_stats[MM_PTE_TOTAL]++;
3858 continue;
3859 }
3860
3861#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3862 if (pmd_trans_huge(val)) {
3863 unsigned long pfn = pmd_pfn(val);
3864 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3865
3866 priv->mm_stats[MM_PTE_TOTAL]++;
3867
3868 if (is_huge_zero_pmd(val))
3869 continue;
3870
3871 if (!pmd_young(val)) {
3872 priv->mm_stats[MM_PTE_OLD]++;
3873 continue;
3874 }
3875
3876 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3877 continue;
3878
3879 walk_pmd_range_locked(pud, addr, vma, walk, &pos);
3880 continue;
3881 }
3882#endif
3883 priv->mm_stats[MM_PMD_TOTAL]++;
3884
3885#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
Yu Zhao76f7f072022-01-27 19:52:09 -07003886 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3887 if (!pmd_young(val))
3888 continue;
Yu Zhao5280d762022-01-27 19:23:01 -07003889
Yu Zhao76f7f072022-01-27 19:52:09 -07003890 walk_pmd_range_locked(pud, addr, vma, walk, &pos);
3891 }
Yu Zhao5280d762022-01-27 19:23:01 -07003892#endif
3893 if (!priv->full_scan && !test_bloom_filter(priv->lruvec, priv->max_seq, pmd + i))
3894 continue;
3895
3896 priv->mm_stats[MM_PMD_FOUND]++;
3897
3898 if (!walk_pte_range(&val, addr, next, walk))
3899 continue;
3900
3901 priv->mm_stats[MM_PMD_ADDED]++;
3902
3903 /* carry over to the next generation */
3904 update_bloom_filter(priv->lruvec, priv->max_seq + 1, pmd + i);
3905 }
3906
3907 walk_pmd_range_locked(pud, -1, vma, walk, &pos);
3908
3909 if (i < PTRS_PER_PMD && get_next_vma(walk, PUD_MASK, PMD_SIZE, &start, &end))
3910 goto restart;
3911}
3912
3913static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3914 struct mm_walk *walk)
3915{
3916 int i;
3917 pud_t *pud;
3918 unsigned long addr;
3919 unsigned long next;
3920 struct lru_gen_mm_walk *priv = walk->private;
3921
3922 VM_BUG_ON(p4d_leaf(*p4d));
3923
3924 pud = pud_offset(p4d, start & P4D_MASK);
3925restart:
3926 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3927 pud_t val = READ_ONCE(pud[i]);
3928
3929 next = pud_addr_end(addr, end);
3930
3931 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3932 continue;
3933
3934 walk_pmd_range(&val, addr, next, walk);
3935
3936 if (priv->batched >= MAX_LRU_BATCH) {
3937 end = (addr | ~PUD_MASK) + 1;
3938 goto done;
3939 }
3940 }
3941
3942 if (i < PTRS_PER_PUD && get_next_vma(walk, P4D_MASK, PUD_SIZE, &start, &end))
3943 goto restart;
3944
3945 end = round_up(end, P4D_SIZE);
3946done:
3947 /* rounded-up boundaries can wrap to 0 */
3948 priv->next_addr = end && walk->vma ? max(end, walk->vma->vm_start) : 0;
3949
3950 return -EAGAIN;
3951}
3952
3953static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3954{
3955 static const struct mm_walk_ops mm_walk_ops = {
3956 .test_walk = should_skip_vma,
3957 .p4d_entry = walk_pud_range,
3958 };
3959
3960 int err;
3961 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3962
3963 walk->next_addr = FIRST_USER_ADDRESS;
3964
3965 do {
3966 err = -EBUSY;
3967
3968 /* page_update_gen() requires stable page_memcg() */
3969 if (!mem_cgroup_trylock_pages(memcg))
3970 break;
3971
3972 /* the caller might be holding the lock for write */
3973 if (mmap_read_trylock(mm)) {
3974 unsigned long start = walk->next_addr;
3975 unsigned long end = mm->highest_vm_end;
3976
3977 err = walk_page_range(mm, start, end, &mm_walk_ops, walk);
3978
3979 mmap_read_unlock(mm);
3980
3981 if (walk->batched) {
3982 spin_lock_irq(&lruvec->lru_lock);
3983 reset_batch_size(lruvec, walk);
3984 spin_unlock_irq(&lruvec->lru_lock);
3985 }
3986 }
3987
3988 mem_cgroup_unlock_pages();
3989
3990 cond_resched();
3991 } while (err == -EAGAIN && walk->next_addr && !mm_is_oom_victim(mm));
3992}
3993
3994static struct lru_gen_mm_walk *alloc_mm_walk(void)
3995{
3996 if (current->reclaim_state && current->reclaim_state->mm_walk)
3997 return current->reclaim_state->mm_walk;
3998
3999 return kzalloc(sizeof(struct lru_gen_mm_walk),
4000 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4001}
4002
4003static void free_mm_walk(struct lru_gen_mm_walk *walk)
4004{
4005 if (!current->reclaim_state || !current->reclaim_state->mm_walk)
4006 kfree(walk);
4007}
4008
Yu Zhaoa1537a62022-01-27 20:32:37 -07004009static void inc_min_seq(struct lruvec *lruvec)
4010{
4011 int type;
4012 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4013
4014 VM_BUG_ON(!seq_is_valid(lruvec));
4015
4016 for (type = 0; type < ANON_AND_FILE; type++) {
4017 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4018 continue;
4019
4020 reset_ctrl_pos(lruvec, type, true);
4021 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4022 }
4023}
4024
4025static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4026{
4027 int gen, type, zone;
4028 bool success = false;
4029 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4030 DEFINE_MIN_SEQ(lruvec);
4031
4032 VM_BUG_ON(!seq_is_valid(lruvec));
4033
4034 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4035 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4036 gen = lru_gen_from_seq(min_seq[type]);
4037
4038 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4039 if (!list_empty(&lrugen->lists[gen][type][zone]))
4040 goto next;
4041 }
4042
4043 min_seq[type]++;
4044 }
4045next:
4046 ;
4047 }
4048
4049 /* see the comment on lru_gen_struct */
4050 if (can_swap) {
4051 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4052 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4053 }
4054
4055 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4056 if (min_seq[type] == lrugen->min_seq[type])
4057 continue;
4058
4059 reset_ctrl_pos(lruvec, type, true);
4060 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4061 success = true;
4062 }
4063
4064 return success;
4065}
4066
Yu Zhao5280d762022-01-27 19:23:01 -07004067static void inc_max_seq(struct lruvec *lruvec)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004068{
4069 int prev, next;
4070 int type, zone;
4071 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4072
4073 spin_lock_irq(&lruvec->lru_lock);
4074
4075 VM_BUG_ON(!seq_is_valid(lruvec));
4076
Yu Zhaoa1537a62022-01-27 20:32:37 -07004077 inc_min_seq(lruvec);
4078
4079 /*
4080 * Update the active/inactive LRU sizes for compatibility. Both sides of
4081 * the current max_seq need to be covered, since max_seq+1 can overlap
4082 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4083 * overlap, cold/hot inversion happens. This can be solved by moving
4084 * pages from min_seq to min_seq+1 but is omitted for simplicity.
4085 */
4086 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4087 next = lru_gen_from_seq(lrugen->max_seq + 1);
4088
4089 for (type = 0; type < ANON_AND_FILE; type++) {
4090 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4091 enum lru_list lru = type * LRU_INACTIVE_FILE;
4092 long delta = lrugen->nr_pages[prev][type][zone] -
4093 lrugen->nr_pages[next][type][zone];
4094
4095 if (!delta)
4096 continue;
4097
4098 __update_lru_size(lruvec, lru, zone, delta);
4099 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4100 }
4101 }
4102
4103 for (type = 0; type < ANON_AND_FILE; type++)
4104 reset_ctrl_pos(lruvec, type, false);
4105
Yu Zhaoe8507812022-01-27 20:08:50 -07004106 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004107 /* make sure preceding modifications appear */
4108 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao5280d762022-01-27 19:23:01 -07004109
Yu Zhaoa1537a62022-01-27 20:32:37 -07004110 spin_unlock_irq(&lruvec->lru_lock);
4111}
4112
Yu Zhao5280d762022-01-27 19:23:01 -07004113static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4114 struct scan_control *sc, bool can_swap, bool full_scan)
4115{
4116 bool success;
4117 struct lru_gen_mm_walk *walk;
4118 struct mm_struct *mm = NULL;
4119 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4120
4121 VM_BUG_ON(max_seq > READ_ONCE(lrugen->max_seq));
4122
4123 /*
4124 * If the hardware doesn't automatically set the accessed bit, fallback
4125 * to lru_gen_look_around(), which only clears the accessed bit in a
4126 * handful of PTEs. Spreading the work out over a period of time usually
4127 * is less efficient, but it avoids bursty page faults.
4128 */
Yu Zhao76f7f072022-01-27 19:52:09 -07004129 if (!full_scan && (!arch_has_hw_pte_young() || !get_cap(LRU_GEN_MM_WALK))) {
Yu Zhao5280d762022-01-27 19:23:01 -07004130 success = iterate_mm_list_nowalk(lruvec, max_seq);
4131 goto done;
4132 }
4133
4134 walk = alloc_mm_walk();
4135 if (!walk) {
4136 success = iterate_mm_list_nowalk(lruvec, max_seq);
4137 goto done;
4138 }
4139
4140 walk->lruvec = lruvec;
4141 walk->max_seq = max_seq;
4142 walk->can_swap = can_swap;
4143 walk->full_scan = full_scan;
4144
4145 do {
4146 success = iterate_mm_list(lruvec, walk, &mm);
4147 if (mm)
4148 walk_mm(lruvec, mm, walk);
4149
4150 cond_resched();
4151 } while (mm);
4152
4153 free_mm_walk(walk);
4154done:
4155 if (!success) {
4156 if (!current_is_kswapd() && !sc->priority)
4157 wait_event_killable(lruvec->mm_state.wait,
4158 max_seq < READ_ONCE(lrugen->max_seq));
4159
4160 return max_seq < READ_ONCE(lrugen->max_seq);
4161 }
4162
4163 VM_BUG_ON(max_seq != READ_ONCE(lrugen->max_seq));
4164
4165 inc_max_seq(lruvec);
4166 /* either this sees any waiters or they will see updated max_seq */
4167 if (wq_has_sleeper(&lruvec->mm_state.wait))
4168 wake_up_all(&lruvec->mm_state.wait);
4169
4170 wakeup_flusher_threads(WB_REASON_VMSCAN);
4171
4172 return true;
4173}
4174
Yu Zhaoa1537a62022-01-27 20:32:37 -07004175static long get_nr_evictable(struct lruvec *lruvec, unsigned long max_seq,
4176 unsigned long *min_seq, bool can_swap, bool *need_aging)
4177{
4178 int gen, type, zone;
4179 long old = 0;
4180 long young = 0;
4181 long total = 0;
4182 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4183
4184 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4185 unsigned long seq;
4186
4187 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4188 long size = 0;
4189
4190 gen = lru_gen_from_seq(seq);
4191
4192 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4193 size += READ_ONCE(lrugen->nr_pages[gen][type][zone]);
4194
4195 total += size;
4196 if (seq == max_seq)
4197 young += size;
4198 if (seq + MIN_NR_GENS == max_seq)
4199 old += size;
4200 }
4201 }
4202
4203 /*
4204 * The aging and the eviction is a typical producer-consumer model. The
4205 * aging tries to be lazy to reduce the unnecessary overhead. On the
4206 * other hand, the eviction stalls when the number of generations
4207 * reaches MIN_NR_GENS. So ideally, there should be MIN_NR_GENS+1
4208 * generations, hence the first two if's.
4209 *
4210 * In addition, it's ideal to spread pages out evenly, meaning
4211 * 1/(MIN_NR_GENS+1) of the total number of pages for each generation. A
4212 * reasonable range for this average portion would [1/MIN_NR_GENS,
4213 * 1/(MIN_NR_GENS+2)]. From the consumer's POV, the eviction only cares
4214 * about the lower bound of cold pages, i.e., 1/(MIN_NR_GENS+2), whereas
4215 * from the producer's POV, the aging only cares about the upper bound
4216 * of hot pages, i.e., 1/MIN_NR_GENS.
4217 */
4218 if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS > max_seq)
4219 *need_aging = true;
4220 else if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS < max_seq)
4221 *need_aging = false;
4222 else if (young * MIN_NR_GENS > total)
4223 *need_aging = true;
4224 else if (old * (MIN_NR_GENS + 2) < total)
4225 *need_aging = true;
4226 else
4227 *need_aging = false;
4228
4229 return total > 0 ? total : 0;
4230}
4231
Yu Zhaoe8507812022-01-27 20:08:50 -07004232static bool age_lruvec(struct lruvec *lruvec, struct scan_control *sc,
4233 unsigned long min_ttl)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004234{
4235 bool need_aging;
4236 long nr_to_scan;
4237 int swappiness = get_swappiness(lruvec, sc);
4238 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4239 DEFINE_MAX_SEQ(lruvec);
4240 DEFINE_MIN_SEQ(lruvec);
4241
Yu Zhaoe8507812022-01-27 20:08:50 -07004242 if (min_ttl) {
4243 int gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4244 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4245
4246 if (time_is_after_jiffies(birth + min_ttl))
4247 return false;
4248 }
4249
Yu Zhaoa1537a62022-01-27 20:32:37 -07004250 mem_cgroup_calculate_protection(NULL, memcg);
4251
4252 if (mem_cgroup_below_min(memcg))
Yu Zhaoe8507812022-01-27 20:08:50 -07004253 return false;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004254
4255 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, swappiness, &need_aging);
4256 if (!nr_to_scan)
Yu Zhaoe8507812022-01-27 20:08:50 -07004257 return false;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004258
4259 nr_to_scan >>= sc->priority;
4260
4261 if (!mem_cgroup_online(memcg))
4262 nr_to_scan++;
4263
4264 if (nr_to_scan && need_aging && (!mem_cgroup_below_low(memcg) || sc->memcg_low_reclaim))
Yu Zhao5280d762022-01-27 19:23:01 -07004265 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
Yu Zhaoe8507812022-01-27 20:08:50 -07004266
4267 return true;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004268}
4269
Yu Zhaoe8507812022-01-27 20:08:50 -07004270/* to protect the working set of the last N jiffies */
4271static unsigned long lru_gen_min_ttl __read_mostly;
4272
Yu Zhaoa1537a62022-01-27 20:32:37 -07004273static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4274{
4275 struct mem_cgroup *memcg;
Yu Zhaoe8507812022-01-27 20:08:50 -07004276 bool success = false;
4277 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004278
4279 VM_BUG_ON(!current_is_kswapd());
4280
Yu Zhao4d905e92022-01-27 19:59:54 -07004281 /*
4282 * To reduce the chance of going into the aging path or swapping, which
4283 * can be costly, optimistically skip them unless their corresponding
4284 * flags were cleared in the eviction path. This improves the overall
4285 * performance when multiple memcgs are available.
4286 */
4287 if (!sc->memcgs_need_aging) {
4288 sc->memcgs_need_aging = true;
4289 sc->memcgs_avoid_swapping = !sc->memcgs_need_swapping;
4290 sc->memcgs_need_swapping = true;
4291 return;
4292 }
4293
4294 sc->memcgs_need_swapping = true;
4295 sc->memcgs_avoid_swapping = true;
4296
Yu Zhao5280d762022-01-27 19:23:01 -07004297 current->reclaim_state->mm_walk = &pgdat->mm_walk;
4298
Yu Zhaoa1537a62022-01-27 20:32:37 -07004299 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4300 do {
4301 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4302
Yu Zhaoe8507812022-01-27 20:08:50 -07004303 if (age_lruvec(lruvec, sc, min_ttl))
4304 success = true;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004305
4306 cond_resched();
4307 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao5280d762022-01-27 19:23:01 -07004308
4309 current->reclaim_state->mm_walk = NULL;
Yu Zhaoe8507812022-01-27 20:08:50 -07004310
4311 /*
4312 * The main goal is to OOM kill if every generation from all memcgs is
4313 * younger than min_ttl. However, another theoretical possibility is all
4314 * memcgs are either below min or empty.
4315 */
4316 if (!success && mutex_trylock(&oom_lock)) {
4317 struct oom_control oc = {
4318 .gfp_mask = sc->gfp_mask,
4319 .order = sc->order,
4320 };
4321
4322 out_of_memory(&oc);
4323
4324 mutex_unlock(&oom_lock);
4325 }
Yu Zhaoa1537a62022-01-27 20:32:37 -07004326}
4327
Yu Zhaoafd94c92022-01-27 20:43:22 -07004328/*
4329 * This function exploits spatial locality when shrink_page_list() walks the
4330 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages.
Yu Zhao5280d762022-01-27 19:23:01 -07004331 * If the scan was done cacheline efficiently, it adds the PMD entry pointing
4332 * to the PTE table to the Bloom filter. This process is a feedback loop from
4333 * the eviction to the aging.
Yu Zhaoafd94c92022-01-27 20:43:22 -07004334 */
4335void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4336{
4337 int i;
4338 pte_t *pte;
4339 unsigned long start;
4340 unsigned long end;
4341 unsigned long addr;
4342 struct page *page;
Yu Zhao5280d762022-01-27 19:23:01 -07004343 struct lru_gen_mm_walk *walk;
4344 int young = 0;
Yu Zhaoafd94c92022-01-27 20:43:22 -07004345 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4346 struct mem_cgroup *memcg = page_memcg(pvmw->page);
4347 struct pglist_data *pgdat = page_pgdat(pvmw->page);
4348 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4349 DEFINE_MAX_SEQ(lruvec);
4350 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4351
4352 lockdep_assert_held(pvmw->ptl);
4353 VM_BUG_ON_PAGE(PageLRU(pvmw->page), pvmw->page);
4354
4355 if (spin_is_contended(pvmw->ptl))
4356 return;
4357
4358 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4359 end = pmd_addr_end(pvmw->address, pvmw->vma->vm_end);
4360
4361 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4362 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4363 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4364 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4365 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4366 else {
4367 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4368 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4369 }
4370 }
4371
4372 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4373
4374 rcu_read_lock();
4375 arch_enter_lazy_mmu_mode();
4376
4377 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4378 unsigned long pfn = pte_pfn(pte[i]);
4379
4380 VM_BUG_ON(addr < pvmw->vma->vm_start || addr >= pvmw->vma->vm_end);
4381
4382 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
4383 continue;
4384
4385 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
4386 continue;
4387
4388 if (!pte_young(pte[i]))
4389 continue;
4390
4391 VM_BUG_ON(!pfn_valid(pfn));
4392 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
4393 continue;
4394
4395 page = compound_head(pfn_to_page(pfn));
4396 if (page_to_nid(page) != pgdat->node_id)
4397 continue;
4398
4399 if (page_memcg_rcu(page) != memcg)
4400 continue;
4401
4402 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4403 continue;
4404
Yu Zhao5280d762022-01-27 19:23:01 -07004405 young++;
4406
Yu Zhaoafd94c92022-01-27 20:43:22 -07004407 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4408 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
4409 set_page_dirty(page);
4410
4411 old_gen = page_lru_gen(page);
4412 if (old_gen < 0)
4413 SetPageReferenced(page);
4414 else if (old_gen != new_gen)
4415 __set_bit(i, bitmap);
4416 }
4417
4418 arch_leave_lazy_mmu_mode();
4419 rcu_read_unlock();
4420
Yu Zhao5280d762022-01-27 19:23:01 -07004421 /* feedback from rmap walkers to page table walkers */
4422 if (suitable_to_scan(i, young))
4423 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4424
4425 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4426
4427 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhaoafd94c92022-01-27 20:43:22 -07004428 for_each_set_bit(i, bitmap, MIN_LRU_BATCH)
4429 activate_page(pte_page(pte[i]));
4430 return;
4431 }
4432
4433 /* page_update_gen() requires stable page_memcg() */
4434 if (!mem_cgroup_trylock_pages(memcg))
4435 return;
4436
Yu Zhao5280d762022-01-27 19:23:01 -07004437 if (!walk) {
4438 spin_lock_irq(&lruvec->lru_lock);
4439 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4440 }
Yu Zhaoafd94c92022-01-27 20:43:22 -07004441
4442 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4443 page = compound_head(pte_page(pte[i]));
4444 if (page_memcg_rcu(page) != memcg)
4445 continue;
4446
4447 old_gen = page_update_gen(page, new_gen);
4448 if (old_gen < 0 || old_gen == new_gen)
4449 continue;
4450
Yu Zhao5280d762022-01-27 19:23:01 -07004451 if (walk)
4452 update_batch_size(walk, page, old_gen, new_gen);
4453 else
4454 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhaoafd94c92022-01-27 20:43:22 -07004455 }
4456
Yu Zhao5280d762022-01-27 19:23:01 -07004457 if (!walk)
4458 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhaoafd94c92022-01-27 20:43:22 -07004459
4460 mem_cgroup_unlock_pages();
4461}
4462
Yu Zhaoa1537a62022-01-27 20:32:37 -07004463/******************************************************************************
4464 * the eviction
4465 ******************************************************************************/
4466
4467static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4468{
4469 bool success;
4470 int gen = page_lru_gen(page);
4471 int type = page_is_file_lru(page);
4472 int zone = page_zonenum(page);
4473 int tier = page_lru_tier(page);
4474 int delta = thp_nr_pages(page);
4475 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4476
4477 VM_BUG_ON_PAGE(gen >= MAX_NR_GENS, page);
4478
4479 if (!page_evictable(page)) {
4480 success = lru_gen_del_page(lruvec, page, true);
4481 VM_BUG_ON_PAGE(!success, page);
4482 SetPageUnevictable(page);
4483 add_page_to_lru_list(page, lruvec);
4484 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4485 return true;
4486 }
4487
4488 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4489 success = lru_gen_del_page(lruvec, page, true);
4490 VM_BUG_ON_PAGE(!success, page);
4491 SetPageSwapBacked(page);
4492 add_page_to_lru_list_tail(page, lruvec);
4493 return true;
4494 }
4495
Yu Zhaoafd94c92022-01-27 20:43:22 -07004496 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4497 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4498 return true;
4499 }
4500
Yu Zhaoa1537a62022-01-27 20:32:37 -07004501 if (tier > tier_idx) {
4502 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4503
4504 gen = page_inc_gen(lruvec, page, false);
4505 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4506
4507 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4508 lrugen->protected[hist][type][tier - 1] + delta);
4509 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4510 return true;
4511 }
4512
4513 if (PageLocked(page) || PageWriteback(page) ||
4514 (type == LRU_GEN_FILE && PageDirty(page))) {
4515 gen = page_inc_gen(lruvec, page, true);
4516 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4517 return true;
4518 }
4519
4520 return false;
4521}
4522
4523static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4524{
4525 bool success;
4526
4527 if (!sc->may_unmap && page_mapped(page))
4528 return false;
4529
4530 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4531 (PageDirty(page) || (PageAnon(page) && !PageSwapCache(page))))
4532 return false;
4533
4534 if (!get_page_unless_zero(page))
4535 return false;
4536
4537 if (!TestClearPageLRU(page)) {
4538 put_page(page);
4539 return false;
4540 }
4541
4542 success = lru_gen_del_page(lruvec, page, true);
4543 VM_BUG_ON_PAGE(!success, page);
4544
4545 return true;
4546}
4547
4548static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4549 int type, int tier, struct list_head *list)
4550{
4551 int gen, zone;
4552 enum vm_event_item item;
4553 int sorted = 0;
4554 int scanned = 0;
4555 int isolated = 0;
4556 int remaining = MAX_LRU_BATCH;
4557 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4558 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4559
4560 VM_BUG_ON(!list_empty(list));
4561
4562 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4563 return 0;
4564
4565 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4566
4567 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4568 LIST_HEAD(moved);
4569 int skipped = 0;
4570 struct list_head *head = &lrugen->lists[gen][type][zone];
4571
4572 while (!list_empty(head)) {
4573 struct page *page = lru_to_page(head);
4574 int delta = thp_nr_pages(page);
4575
4576 VM_BUG_ON_PAGE(PageTail(page), page);
4577 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4578 VM_BUG_ON_PAGE(PageActive(page), page);
4579 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4580 VM_BUG_ON_PAGE(page_zonenum(page) != zone, page);
4581
4582 prefetchw_prev_lru_page(page, head, flags);
4583
4584 scanned += delta;
4585
4586 if (sort_page(lruvec, page, tier))
4587 sorted += delta;
4588 else if (isolate_page(lruvec, page, sc)) {
4589 list_add(&page->lru, list);
4590 isolated += delta;
4591 } else {
4592 list_move(&page->lru, &moved);
4593 skipped += delta;
4594 }
4595
4596 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4597 break;
4598 }
4599
4600 if (skipped) {
4601 list_splice(&moved, head);
4602 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4603 }
4604
4605 if (!remaining || isolated >= MIN_LRU_BATCH)
4606 break;
4607 }
4608
4609 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4610 if (!cgroup_reclaim(sc)) {
4611 __count_vm_events(item, isolated);
4612 __count_vm_events(PGREFILL, sorted);
4613 }
4614 __count_memcg_events(memcg, item, isolated);
4615 __count_memcg_events(memcg, PGREFILL, sorted);
4616 __count_vm_events(PGSCAN_ANON + type, isolated);
4617
4618 /*
4619 * There might not be eligible pages due to reclaim_idx, may_unmap and
4620 * may_writepage. Check the remaining to prevent livelock if there is no
4621 * progress.
4622 */
4623 return isolated || !remaining ? scanned : 0;
4624}
4625
4626static int get_tier_idx(struct lruvec *lruvec, int type)
4627{
4628 int tier;
4629 struct ctrl_pos sp, pv;
4630
4631 /*
4632 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4633 * This value is chosen because any other tier would have at least twice
4634 * as many refaults as the first tier.
4635 */
4636 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4637 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4638 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4639 if (!positive_ctrl_err(&sp, &pv))
4640 break;
4641 }
4642
4643 return tier - 1;
4644}
4645
4646static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4647{
4648 int type, tier;
4649 struct ctrl_pos sp, pv;
4650 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4651
4652 /*
4653 * Compare the first tier of anon with that of file to determine which
4654 * type to scan. Also need to compare other tiers of the selected type
4655 * with the first tier of the other type to determine the last tier (of
4656 * the selected type) to evict.
4657 */
4658 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4659 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4660 type = positive_ctrl_err(&sp, &pv);
4661
4662 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4663 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4664 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4665 if (!positive_ctrl_err(&sp, &pv))
4666 break;
4667 }
4668
4669 *tier_idx = tier - 1;
4670
4671 return type;
4672}
4673
4674static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4675 int *type_scanned, struct list_head *list)
4676{
4677 int i;
4678 int type;
4679 int scanned;
4680 int tier = -1;
4681 DEFINE_MIN_SEQ(lruvec);
4682
4683 VM_BUG_ON(!seq_is_valid(lruvec));
4684
4685 /*
4686 * Try to make the obvious choice first. When anon and file are both
4687 * available from the same generation, interpret swappiness 1 as file
4688 * first and 200 as anon first.
4689 */
4690 if (!swappiness)
4691 type = LRU_GEN_FILE;
4692 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4693 type = LRU_GEN_ANON;
4694 else if (swappiness == 1)
4695 type = LRU_GEN_FILE;
4696 else if (swappiness == 200)
4697 type = LRU_GEN_ANON;
4698 else
4699 type = get_type_to_scan(lruvec, swappiness, &tier);
4700
4701 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4702 if (tier < 0)
4703 tier = get_tier_idx(lruvec, type);
4704
4705 scanned = scan_pages(lruvec, sc, type, tier, list);
4706 if (scanned)
4707 break;
4708
4709 type = !type;
4710 tier = -1;
4711 }
4712
4713 *type_scanned = type;
4714
4715 return scanned;
4716}
4717
Yu Zhao4d905e92022-01-27 19:59:54 -07004718static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4719 bool *swapped)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004720{
4721 int type;
4722 int scanned;
4723 int reclaimed;
4724 LIST_HEAD(list);
4725 struct page *page;
4726 enum vm_event_item item;
4727 struct reclaim_stat stat;
Yu Zhao5280d762022-01-27 19:23:01 -07004728 struct lru_gen_mm_walk *walk;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004729 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4730 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4731
4732 spin_lock_irq(&lruvec->lru_lock);
4733
4734 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4735
4736 if (try_to_inc_min_seq(lruvec, swappiness))
4737 scanned++;
4738
4739 if (get_nr_gens(lruvec, LRU_GEN_FILE) == MIN_NR_GENS)
4740 scanned = 0;
4741
4742 spin_unlock_irq(&lruvec->lru_lock);
4743
4744 if (list_empty(&list))
4745 return scanned;
4746
4747 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4748
4749 /*
4750 * To avoid livelock, don't add rejected pages back to the same lists
4751 * they were isolated from. See lru_gen_add_page().
4752 */
4753 list_for_each_entry(page, &list, lru) {
4754 ClearPageReferenced(page);
4755 ClearPageWorkingset(page);
4756
4757 if (PageReclaim(page) && (PageDirty(page) || PageWriteback(page)))
4758 ClearPageActive(page);
4759 else if (page_is_file_lru(page) || PageSwapCache(page))
4760 SetPageActive(page);
4761 }
4762
4763 spin_lock_irq(&lruvec->lru_lock);
4764
4765 move_pages_to_lru(lruvec, &list);
4766
Yu Zhao5280d762022-01-27 19:23:01 -07004767 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4768 if (walk && walk->batched)
4769 reset_batch_size(lruvec, walk);
4770
Yu Zhaoa1537a62022-01-27 20:32:37 -07004771 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4772 if (!cgroup_reclaim(sc))
4773 __count_vm_events(item, reclaimed);
4774 __count_memcg_events(memcg, item, reclaimed);
4775 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4776
4777 spin_unlock_irq(&lruvec->lru_lock);
4778
4779 mem_cgroup_uncharge_list(&list);
4780 free_unref_page_list(&list);
4781
4782 sc->nr_reclaimed += reclaimed;
4783
Yu Zhao4d905e92022-01-27 19:59:54 -07004784 if (type == LRU_GEN_ANON && swapped)
4785 *swapped = true;
4786
Yu Zhaoa1537a62022-01-27 20:32:37 -07004787 return scanned;
4788}
4789
4790static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
4791{
4792 bool need_aging;
4793 long nr_to_scan;
4794 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4795 DEFINE_MAX_SEQ(lruvec);
4796 DEFINE_MIN_SEQ(lruvec);
4797
4798 if (mem_cgroup_below_min(memcg) ||
4799 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4800 return 0;
4801
4802 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, can_swap, &need_aging);
4803 if (!nr_to_scan)
4804 return 0;
4805
4806 /* reset the priority if the target has been met */
4807 nr_to_scan >>= sc->nr_reclaimed < sc->nr_to_reclaim ? sc->priority : DEF_PRIORITY;
4808
4809 if (!mem_cgroup_online(memcg))
4810 nr_to_scan++;
4811
4812 if (!nr_to_scan)
4813 return 0;
4814
Yu Zhao4d905e92022-01-27 19:59:54 -07004815 if (!need_aging) {
4816 sc->memcgs_need_aging = false;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004817 return nr_to_scan;
Yu Zhao4d905e92022-01-27 19:59:54 -07004818 }
Yu Zhaoa1537a62022-01-27 20:32:37 -07004819
4820 /* leave the work to lru_gen_age_node() */
4821 if (current_is_kswapd())
4822 return 0;
4823
4824 /* try other memcgs before going to the aging path */
4825 if (!cgroup_reclaim(sc) && !sc->force_deactivate) {
4826 sc->skipped_deactivate = true;
4827 return 0;
4828 }
4829
Yu Zhao5280d762022-01-27 19:23:01 -07004830 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
4831 return nr_to_scan;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004832
Yu Zhao5280d762022-01-27 19:23:01 -07004833 return min_seq[LRU_GEN_FILE] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004834}
4835
4836static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4837{
4838 struct blk_plug plug;
4839 long scanned = 0;
Yu Zhao4d905e92022-01-27 19:59:54 -07004840 bool swapped = false;
4841 unsigned long reclaimed = sc->nr_reclaimed;
Yu Zhao5280d762022-01-27 19:23:01 -07004842 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004843
4844 lru_add_drain();
4845
4846 blk_start_plug(&plug);
4847
Yu Zhao5280d762022-01-27 19:23:01 -07004848 if (current_is_kswapd())
4849 current->reclaim_state->mm_walk = &pgdat->mm_walk;
4850
Yu Zhaoa1537a62022-01-27 20:32:37 -07004851 while (true) {
4852 int delta;
4853 int swappiness;
4854 long nr_to_scan;
4855
4856 if (sc->may_swap)
4857 swappiness = get_swappiness(lruvec, sc);
4858 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4859 swappiness = 1;
4860 else
4861 swappiness = 0;
4862
4863 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
4864 if (!nr_to_scan)
4865 break;
4866
Yu Zhao4d905e92022-01-27 19:59:54 -07004867 delta = evict_pages(lruvec, sc, swappiness, &swapped);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004868 if (!delta)
4869 break;
4870
Yu Zhao4d905e92022-01-27 19:59:54 -07004871 if (sc->memcgs_avoid_swapping && swappiness < 200 && swapped)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004872 break;
4873
Yu Zhao4d905e92022-01-27 19:59:54 -07004874 scanned += delta;
4875 if (scanned >= nr_to_scan) {
4876 if (!swapped && sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH)
4877 sc->memcgs_need_swapping = false;
4878 break;
4879 }
4880
Yu Zhaoa1537a62022-01-27 20:32:37 -07004881 cond_resched();
4882 }
4883
Yu Zhao5280d762022-01-27 19:23:01 -07004884 if (current_is_kswapd())
4885 current->reclaim_state->mm_walk = NULL;
4886
Yu Zhaoa1537a62022-01-27 20:32:37 -07004887 blk_finish_plug(&plug);
4888}
4889
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004890/******************************************************************************
Yu Zhao76f7f072022-01-27 19:52:09 -07004891 * state change
4892 ******************************************************************************/
4893
4894static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
4895{
4896 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4897
4898 if (lrugen->enabled) {
4899 enum lru_list lru;
4900
4901 for_each_evictable_lru(lru) {
4902 if (!list_empty(&lruvec->lists[lru]))
4903 return false;
4904 }
4905 } else {
4906 int gen, type, zone;
4907
4908 for_each_gen_type_zone(gen, type, zone) {
4909 if (!list_empty(&lrugen->lists[gen][type][zone]))
4910 return false;
4911
4912 /* unlikely but not a bug when reset_batch_size() is pending */
4913 VM_WARN_ON(lrugen->nr_pages[gen][type][zone]);
4914 }
4915 }
4916
4917 return true;
4918}
4919
4920static bool fill_evictable(struct lruvec *lruvec)
4921{
4922 enum lru_list lru;
4923 int remaining = MAX_LRU_BATCH;
4924
4925 for_each_evictable_lru(lru) {
4926 int type = is_file_lru(lru);
4927 bool active = is_active_lru(lru);
4928 struct list_head *head = &lruvec->lists[lru];
4929
4930 while (!list_empty(head)) {
4931 bool success;
4932 struct page *page = lru_to_page(head);
4933
4934 VM_BUG_ON_PAGE(PageTail(page), page);
4935 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4936 VM_BUG_ON_PAGE(PageActive(page) != active, page);
4937 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4938 VM_BUG_ON_PAGE(page_lru_gen(page) < MAX_NR_GENS, page);
4939
4940 prefetchw_prev_lru_page(page, head, flags);
4941
4942 del_page_from_lru_list(page, lruvec);
4943 success = lru_gen_add_page(lruvec, page, false);
4944 VM_BUG_ON(!success);
4945
4946 if (!--remaining)
4947 return false;
4948 }
4949 }
4950
4951 return true;
4952}
4953
4954static bool drain_evictable(struct lruvec *lruvec)
4955{
4956 int gen, type, zone;
4957 int remaining = MAX_LRU_BATCH;
4958
4959 for_each_gen_type_zone(gen, type, zone) {
4960 struct list_head *head = &lruvec->lrugen.lists[gen][type][zone];
4961
4962 while (!list_empty(head)) {
4963 bool success;
4964 struct page *page = lru_to_page(head);
4965
4966 VM_BUG_ON_PAGE(PageTail(page), page);
4967 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4968 VM_BUG_ON_PAGE(PageActive(page), page);
4969 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4970 VM_BUG_ON_PAGE(page_zonenum(page) != zone, page);
4971
4972 prefetchw_prev_lru_page(page, head, flags);
4973
4974 success = lru_gen_del_page(lruvec, page, false);
4975 VM_BUG_ON(!success);
4976 add_page_to_lru_list(page, lruvec);
4977
4978 if (!--remaining)
4979 return false;
4980 }
4981 }
4982
4983 return true;
4984}
4985
4986static void lru_gen_change_state(bool enable)
4987{
4988 static DEFINE_MUTEX(state_mutex);
4989
4990 struct mem_cgroup *memcg;
4991
4992 cgroup_lock();
4993 cpus_read_lock();
4994 get_online_mems();
4995 mutex_lock(&state_mutex);
4996
4997 if (enable == lru_gen_enabled())
4998 goto unlock;
4999
5000 if (enable)
5001 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5002 else
5003 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5004
5005 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5006 do {
5007 int nid;
5008
5009 for_each_node(nid) {
5010 struct lruvec *lruvec = get_lruvec(memcg, nid);
5011
5012 if (!lruvec)
5013 continue;
5014
5015 spin_lock_irq(&lruvec->lru_lock);
5016
5017 VM_BUG_ON(!seq_is_valid(lruvec));
5018 VM_BUG_ON(!state_is_valid(lruvec));
5019
5020 lruvec->lrugen.enabled = enable;
5021
5022 while (!(enable ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5023 spin_unlock_irq(&lruvec->lru_lock);
5024 cond_resched();
5025 spin_lock_irq(&lruvec->lru_lock);
5026 }
5027
5028 spin_unlock_irq(&lruvec->lru_lock);
5029 }
5030
5031 cond_resched();
5032 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5033unlock:
5034 mutex_unlock(&state_mutex);
5035 put_online_mems();
5036 cpus_read_unlock();
5037 cgroup_unlock();
5038}
5039
5040/******************************************************************************
5041 * sysfs interface
5042 ******************************************************************************/
5043
Yu Zhaoe8507812022-01-27 20:08:50 -07005044static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5045{
5046 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5047}
5048
5049static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5050 const char *buf, size_t len)
5051{
5052 unsigned int msecs;
5053
5054 if (kstrtouint(buf, 0, &msecs))
5055 return -EINVAL;
5056
5057 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5058
5059 return len;
5060}
5061
5062static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5063 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5064);
5065
Yu Zhao76f7f072022-01-27 19:52:09 -07005066static ssize_t show_enable(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5067{
5068 unsigned int caps = 0;
5069
5070 if (get_cap(LRU_GEN_CORE))
5071 caps |= BIT(LRU_GEN_CORE);
5072
5073 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5074 caps |= BIT(LRU_GEN_MM_WALK);
5075
5076 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
5077 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5078
5079 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5080}
5081
5082static ssize_t store_enable(struct kobject *kobj, struct kobj_attribute *attr,
5083 const char *buf, size_t len)
5084{
5085 int i;
5086 unsigned int caps;
5087
5088 if (tolower(*buf) == 'n')
5089 caps = 0;
5090 else if (tolower(*buf) == 'y')
5091 caps = -1;
5092 else if (kstrtouint(buf, 0, &caps))
5093 return -EINVAL;
5094
5095 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5096 bool enable = caps & BIT(i);
5097
5098 if (i == LRU_GEN_CORE)
5099 lru_gen_change_state(enable);
5100 else if (enable)
5101 static_branch_enable(&lru_gen_caps[i]);
5102 else
5103 static_branch_disable(&lru_gen_caps[i]);
5104 }
5105
5106 return len;
5107}
5108
5109static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5110 enabled, 0644, show_enable, store_enable
5111);
5112
5113static struct attribute *lru_gen_attrs[] = {
Yu Zhaoe8507812022-01-27 20:08:50 -07005114 &lru_gen_min_ttl_attr.attr,
Yu Zhao76f7f072022-01-27 19:52:09 -07005115 &lru_gen_enabled_attr.attr,
5116 NULL
5117};
5118
5119static struct attribute_group lru_gen_attr_group = {
5120 .name = "lru_gen",
5121 .attrs = lru_gen_attrs,
5122};
5123
5124/******************************************************************************
Yu Zhao3d18c9e2022-01-27 20:12:41 -07005125 * debugfs interface
5126 ******************************************************************************/
5127
5128static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5129{
5130 struct mem_cgroup *memcg;
5131 loff_t nr_to_skip = *pos;
5132
5133 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5134 if (!m->private)
5135 return ERR_PTR(-ENOMEM);
5136
5137 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5138 do {
5139 int nid;
5140
5141 for_each_node_state(nid, N_MEMORY) {
5142 if (!nr_to_skip--)
5143 return get_lruvec(memcg, nid);
5144 }
5145 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5146
5147 return NULL;
5148}
5149
5150static void lru_gen_seq_stop(struct seq_file *m, void *v)
5151{
5152 if (!IS_ERR_OR_NULL(v))
5153 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5154
5155 kvfree(m->private);
5156 m->private = NULL;
5157}
5158
5159static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5160{
5161 int nid = lruvec_pgdat(v)->node_id;
5162 struct mem_cgroup *memcg = lruvec_memcg(v);
5163
5164 ++*pos;
5165
5166 nid = next_memory_node(nid);
5167 if (nid == MAX_NUMNODES) {
5168 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5169 if (!memcg)
5170 return NULL;
5171
5172 nid = first_memory_node;
5173 }
5174
5175 return get_lruvec(memcg, nid);
5176}
5177
5178static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5179 unsigned long max_seq, unsigned long *min_seq,
5180 unsigned long seq)
5181{
5182 int i;
5183 int type, tier;
5184 int hist = lru_hist_from_seq(seq);
5185 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5186
5187 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5188 seq_printf(m, " %10d", tier);
5189 for (type = 0; type < ANON_AND_FILE; type++) {
5190 unsigned long n[3] = {};
5191
5192 if (seq == max_seq) {
5193 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5194 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5195
5196 seq_printf(m, " %10luR %10luT %10lu ", n[0], n[1], n[2]);
5197 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5198 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5199 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5200 if (tier)
5201 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5202
5203 seq_printf(m, " %10lur %10lue %10lup", n[0], n[1], n[2]);
5204 } else
5205 seq_puts(m, " 0 0 0 ");
5206 }
5207 seq_putc(m, '\n');
5208 }
5209
5210 seq_puts(m, " ");
5211 for (i = 0; i < NR_MM_STATS; i++) {
5212 if (seq == max_seq && NR_HIST_GENS == 1)
5213 seq_printf(m, " %10lu%c", READ_ONCE(lruvec->mm_state.stats[hist][i]),
5214 toupper(MM_STAT_CODES[i]));
5215 else if (seq != max_seq && NR_HIST_GENS > 1)
5216 seq_printf(m, " %10lu%c", READ_ONCE(lruvec->mm_state.stats[hist][i]),
5217 MM_STAT_CODES[i]);
5218 else
5219 seq_puts(m, " 0 ");
5220 }
5221 seq_putc(m, '\n');
5222}
5223
5224static int lru_gen_seq_show(struct seq_file *m, void *v)
5225{
5226 unsigned long seq;
5227 bool full = !debugfs_real_fops(m->file)->write;
5228 struct lruvec *lruvec = v;
5229 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5230 int nid = lruvec_pgdat(lruvec)->node_id;
5231 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5232 DEFINE_MAX_SEQ(lruvec);
5233 DEFINE_MIN_SEQ(lruvec);
5234
5235 if (nid == first_memory_node) {
5236 const char *path = memcg ? m->private : "";
5237
5238#ifdef CONFIG_MEMCG
5239 if (memcg)
5240 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5241#endif
5242 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5243 }
5244
5245 seq_printf(m, " node %5d\n", nid);
5246
5247 if (!full)
5248 seq = min_seq[LRU_GEN_ANON];
5249 else if (max_seq >= MAX_NR_GENS)
5250 seq = max_seq - MAX_NR_GENS + 1;
5251 else
5252 seq = 0;
5253
5254 for (; seq <= max_seq; seq++) {
5255 int type, zone;
5256 int gen = lru_gen_from_seq(seq);
5257 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5258
5259 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5260
5261 for (type = 0; type < ANON_AND_FILE; type++) {
5262 long size = 0;
5263 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5264
5265 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5266 size += READ_ONCE(lrugen->nr_pages[gen][type][zone]);
5267
5268 seq_printf(m, " %10lu%c", max(size, 0L), mark);
5269 }
5270
5271 seq_putc(m, '\n');
5272
5273 if (full)
5274 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5275 }
5276
5277 return 0;
5278}
5279
5280static const struct seq_operations lru_gen_seq_ops = {
5281 .start = lru_gen_seq_start,
5282 .stop = lru_gen_seq_stop,
5283 .next = lru_gen_seq_next,
5284 .show = lru_gen_seq_show,
5285};
5286
5287static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5288 bool can_swap, bool full_scan)
5289{
5290 DEFINE_MAX_SEQ(lruvec);
5291
5292 if (seq == max_seq)
5293 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, full_scan);
5294
5295 return seq > max_seq ? -EINVAL : 0;
5296}
5297
5298static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5299 int swappiness, unsigned long nr_to_reclaim)
5300{
5301 struct blk_plug plug;
5302 int err = -EINTR;
5303 DEFINE_MAX_SEQ(lruvec);
5304
5305 if (seq + MIN_NR_GENS > max_seq)
5306 return -EINVAL;
5307
5308 sc->nr_reclaimed = 0;
5309
5310 blk_start_plug(&plug);
5311
5312 while (!signal_pending(current)) {
5313 DEFINE_MIN_SEQ(lruvec);
5314
5315 if (seq < min_seq[!swappiness] || sc->nr_reclaimed >= nr_to_reclaim ||
5316 !evict_pages(lruvec, sc, swappiness, NULL)) {
5317 err = 0;
5318 break;
5319 }
5320
5321 cond_resched();
5322 }
5323
5324 blk_finish_plug(&plug);
5325
5326 return err;
5327}
5328
5329static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5330 struct scan_control *sc, int swappiness, unsigned long opt)
5331{
5332 struct lruvec *lruvec;
5333 int err = -EINVAL;
5334 struct mem_cgroup *memcg = NULL;
5335
5336 if (!mem_cgroup_disabled()) {
5337 rcu_read_lock();
5338 memcg = mem_cgroup_from_id(memcg_id);
5339#ifdef CONFIG_MEMCG
5340 if (memcg && !css_tryget(&memcg->css))
5341 memcg = NULL;
5342#endif
5343 rcu_read_unlock();
5344
5345 if (!memcg)
5346 goto done;
5347 }
5348 if (memcg_id != mem_cgroup_id(memcg))
5349 goto done;
5350
5351 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5352 goto done;
5353
5354 lruvec = get_lruvec(memcg, nid);
5355
5356 if (swappiness < 0)
5357 swappiness = get_swappiness(lruvec, sc);
5358 else if (swappiness > 200)
5359 goto done;
5360
5361 switch (cmd) {
5362 case '+':
5363 err = run_aging(lruvec, seq, sc, swappiness, opt);
5364 break;
5365 case '-':
5366 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5367 break;
5368 }
5369done:
5370 mem_cgroup_put(memcg);
5371
5372 return err;
5373}
5374
5375static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5376 size_t len, loff_t *pos)
5377{
5378 void *buf;
5379 char *cur, *next;
5380 unsigned int flags;
5381 int err = 0;
5382 struct scan_control sc = {
5383 .may_writepage = true,
5384 .may_unmap = true,
5385 .may_swap = true,
5386 .reclaim_idx = MAX_NR_ZONES - 1,
5387 .gfp_mask = GFP_KERNEL,
5388 };
5389
5390 buf = kvmalloc(len + 1, GFP_KERNEL);
5391 if (!buf)
5392 return -ENOMEM;
5393
5394 if (copy_from_user(buf, src, len)) {
5395 kvfree(buf);
5396 return -EFAULT;
5397 }
5398
5399 next = buf;
5400 next[len] = '\0';
5401
5402 sc.reclaim_state.mm_walk = alloc_mm_walk();
5403 if (!sc.reclaim_state.mm_walk) {
5404 kvfree(buf);
5405 return -ENOMEM;
5406 }
5407
5408 set_task_reclaim_state(current, &sc.reclaim_state);
5409 flags = memalloc_noreclaim_save();
5410
5411 while ((cur = strsep(&next, ",;\n"))) {
5412 int n;
5413 int end;
5414 char cmd;
5415 unsigned int memcg_id;
5416 unsigned int nid;
5417 unsigned long seq;
5418 unsigned int swappiness = -1;
5419 unsigned long opt = -1;
5420
5421 cur = skip_spaces(cur);
5422 if (!*cur)
5423 continue;
5424
5425 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5426 &seq, &end, &swappiness, &end, &opt, &end);
5427 if (n < 4 || cur[end]) {
5428 err = -EINVAL;
5429 break;
5430 }
5431
5432 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5433 if (err)
5434 break;
5435 }
5436
5437 memalloc_noreclaim_restore(flags);
5438 set_task_reclaim_state(current, NULL);
5439
5440 free_mm_walk(sc.reclaim_state.mm_walk);
5441 kvfree(buf);
5442
5443 return err ? : len;
5444}
5445
5446static int lru_gen_seq_open(struct inode *inode, struct file *file)
5447{
5448 return seq_open(file, &lru_gen_seq_ops);
5449}
5450
5451static const struct file_operations lru_gen_rw_fops = {
5452 .open = lru_gen_seq_open,
5453 .read = seq_read,
5454 .write = lru_gen_seq_write,
5455 .llseek = seq_lseek,
5456 .release = seq_release,
5457};
5458
5459static const struct file_operations lru_gen_ro_fops = {
5460 .open = lru_gen_seq_open,
5461 .read = seq_read,
5462 .llseek = seq_lseek,
5463 .release = seq_release,
5464};
5465
5466/******************************************************************************
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005467 * initialization
5468 ******************************************************************************/
5469
5470void lru_gen_init_lruvec(struct lruvec *lruvec)
5471{
Yu Zhaoe8507812022-01-27 20:08:50 -07005472 int i;
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005473 int gen, type, zone;
5474 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5475
5476 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhao76f7f072022-01-27 19:52:09 -07005477 lrugen->enabled = lru_gen_enabled();
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005478
Yu Zhaoe8507812022-01-27 20:08:50 -07005479 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5480 lrugen->timestamps[i] = jiffies;
5481
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005482 for_each_gen_type_zone(gen, type, zone)
5483 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao5280d762022-01-27 19:23:01 -07005484
5485 lruvec->mm_state.seq = MIN_NR_GENS;
5486 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005487}
5488
5489#ifdef CONFIG_MEMCG
5490void lru_gen_init_memcg(struct mem_cgroup *memcg)
5491{
Yu Zhao5280d762022-01-27 19:23:01 -07005492 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5493 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005494}
5495
5496void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5497{
Yu Zhao5280d762022-01-27 19:23:01 -07005498 int i;
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005499 int nid;
5500
5501 for_each_node(nid) {
5502 struct lruvec *lruvec = get_lruvec(memcg, nid);
5503
5504 VM_BUG_ON(memchr_inv(lruvec->lrugen.nr_pages, 0,
5505 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao5280d762022-01-27 19:23:01 -07005506
5507 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5508 bitmap_free(lruvec->mm_state.filters[i]);
5509 lruvec->mm_state.filters[i] = NULL;
5510 }
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005511 }
5512}
5513#endif
5514
5515static int __init init_lru_gen(void)
5516{
5517 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5518 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
Yu Zhao5280d762022-01-27 19:23:01 -07005519 BUILD_BUG_ON(sizeof(MM_STAT_CODES) != NR_MM_STATS + 1);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005520
Yu Zhao76f7f072022-01-27 19:52:09 -07005521 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5522 pr_err("lru_gen: failed to create sysfs group\n");
5523
Yu Zhao3d18c9e2022-01-27 20:12:41 -07005524 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5525 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5526
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005527 return 0;
5528};
5529late_initcall(init_lru_gen);
5530
Yu Zhaoa1537a62022-01-27 20:32:37 -07005531#else
5532
5533static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5534{
5535}
5536
5537static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5538{
5539}
5540
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005541#endif /* CONFIG_LRU_GEN */
5542
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005543static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005544{
5545 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005546 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005547 unsigned long nr_to_scan;
5548 enum lru_list lru;
5549 unsigned long nr_reclaimed = 0;
5550 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5551 struct blk_plug plug;
Mel Gorman1a501902014-06-04 16:10:49 -07005552 bool scan_adjusted;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005553
Yu Zhaoa1537a62022-01-27 20:32:37 -07005554 if (lru_gen_enabled()) {
5555 lru_gen_shrink_lruvec(lruvec, sc);
5556 return;
5557 }
5558
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005559 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005560
Mel Gormane82e0562013-07-03 15:01:44 -07005561 /* Record the original scan target for proportional adjustments later */
5562 memcpy(targets, nr, sizeof(nr));
5563
Mel Gorman1a501902014-06-04 16:10:49 -07005564 /*
5565 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5566 * event that can occur when there is little memory pressure e.g.
5567 * multiple streaming readers/writers. Hence, we do not abort scanning
5568 * when the requested number of pages are reclaimed when scanning at
5569 * DEF_PRIORITY on the assumption that the fact we are direct
5570 * reclaiming implies that kswapd is not keeping up and it is best to
5571 * do a batch of work at once. For memcg reclaim one check is made to
5572 * abort proportional reclaim if either the file or anon lru has already
5573 * dropped to zero at the first pass.
5574 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005575 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
Mel Gorman1a501902014-06-04 16:10:49 -07005576 sc->priority == DEF_PRIORITY);
5577
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005578 blk_start_plug(&plug);
5579 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5580 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005581 unsigned long nr_anon, nr_file, percentage;
5582 unsigned long nr_scanned;
5583
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005584 for_each_evictable_lru(lru) {
5585 if (nr[lru]) {
5586 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5587 nr[lru] -= nr_to_scan;
5588
5589 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005590 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005591 }
5592 }
Mel Gormane82e0562013-07-03 15:01:44 -07005593
Michal Hockobd041732016-12-02 17:26:48 -08005594 cond_resched();
5595
Mel Gormane82e0562013-07-03 15:01:44 -07005596 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
5597 continue;
5598
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005599 /*
Mel Gormane82e0562013-07-03 15:01:44 -07005600 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07005601 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07005602 * proportionally what was requested by get_scan_count(). We
5603 * stop reclaiming one LRU and reduce the amount scanning
5604 * proportional to the original scan target.
5605 */
5606 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5607 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5608
Mel Gorman1a501902014-06-04 16:10:49 -07005609 /*
5610 * It's just vindictive to attack the larger once the smaller
5611 * has gone to zero. And given the way we stop scanning the
5612 * smaller below, this makes sure that we only make one nudge
5613 * towards proportionality once we've got nr_to_reclaim.
5614 */
5615 if (!nr_file || !nr_anon)
5616 break;
5617
Mel Gormane82e0562013-07-03 15:01:44 -07005618 if (nr_file > nr_anon) {
5619 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5620 targets[LRU_ACTIVE_ANON] + 1;
5621 lru = LRU_BASE;
5622 percentage = nr_anon * 100 / scan_target;
5623 } else {
5624 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5625 targets[LRU_ACTIVE_FILE] + 1;
5626 lru = LRU_FILE;
5627 percentage = nr_file * 100 / scan_target;
5628 }
5629
5630 /* Stop scanning the smaller of the LRU */
5631 nr[lru] = 0;
5632 nr[lru + LRU_ACTIVE] = 0;
5633
5634 /*
5635 * Recalculate the other LRU scan count based on its original
5636 * scan target and the percentage scanning already complete
5637 */
5638 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5639 nr_scanned = targets[lru] - nr[lru];
5640 nr[lru] = targets[lru] * (100 - percentage) / 100;
5641 nr[lru] -= min(nr[lru], nr_scanned);
5642
5643 lru += LRU_ACTIVE;
5644 nr_scanned = targets[lru] - nr[lru];
5645 nr[lru] = targets[lru] * (100 - percentage) / 100;
5646 nr[lru] -= min(nr[lru], nr_scanned);
5647
5648 scan_adjusted = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005649 }
5650 blk_finish_plug(&plug);
5651 sc->nr_reclaimed += nr_reclaimed;
5652
5653 /*
5654 * Even if we did not try to evict anon pages at all, we want to
5655 * rebalance the anon lru active/inactive ratio.
5656 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005657 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5658 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005659 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5660 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005661}
5662
Mel Gorman23b9da52012-05-29 15:06:20 -07005663/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005664static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005665{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005666 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005667 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005668 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005669 return true;
5670
5671 return false;
5672}
5673
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005674/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005675 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5676 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5677 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005678 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005679 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005680 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005681static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005682 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005683 struct scan_control *sc)
5684{
5685 unsigned long pages_for_compaction;
5686 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005687 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005688
5689 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005690 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005691 return false;
5692
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005693 /*
5694 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5695 * number of pages that were scanned. This will return to the caller
5696 * with the risk reclaim/compaction and the resulting allocation attempt
5697 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5698 * allocations through requiring that the full LRU list has been scanned
5699 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5700 * scan, but that approximation was wrong, and there were corner cases
5701 * where always a non-zero amount of pages were scanned.
5702 */
5703 if (!nr_reclaimed)
5704 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005705
Mel Gorman3e7d3442011-01-13 15:45:56 -08005706 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005707 for (z = 0; z <= sc->reclaim_idx; z++) {
5708 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005709 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005710 continue;
5711
5712 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005713 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005714 case COMPACT_CONTINUE:
5715 return false;
5716 default:
5717 /* check next zone */
5718 ;
5719 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005720 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005721
5722 /*
5723 * If we have not reclaimed enough pages for compaction and the
5724 * inactive lists are large enough, continue reclaiming
5725 */
5726 pages_for_compaction = compact_gap(sc->order);
5727 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005728 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005729 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5730
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005731 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005732}
5733
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005734static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005735{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005736 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005737 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005738
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005739 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005740 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005741 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005742 unsigned long reclaimed;
5743 unsigned long scanned;
Johannes Weiner56600482012-01-12 17:17:59 -08005744
Xunlei Pange3336ca2020-09-04 16:35:27 -07005745 /*
5746 * This loop can become CPU-bound when target memcgs
5747 * aren't eligible for reclaim - either because they
5748 * don't have any reclaimable pages, or because their
5749 * memory is explicitly protected. Avoid soft lockups.
5750 */
5751 cond_resched();
5752
Chris Down45c7f7e2020-08-06 23:22:05 -07005753 mem_cgroup_calculate_protection(target_memcg, memcg);
5754
5755 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005756 /*
5757 * Hard protection.
5758 * If there is no reclaimable memory, OOM.
5759 */
5760 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005761 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005762 /*
5763 * Soft protection.
5764 * Respect the protection only as long as
5765 * there is an unprotected supply
5766 * of reclaimable memory from other cgroups.
5767 */
5768 if (!sc->memcg_low_reclaim) {
5769 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005770 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005771 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005772 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005773 }
5774
Johannes Weinerd2af3392019-11-30 17:55:43 -08005775 reclaimed = sc->nr_reclaimed;
5776 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005777
5778 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005779
Johannes Weinerd2af3392019-11-30 17:55:43 -08005780 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5781 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005782
Johannes Weinerd2af3392019-11-30 17:55:43 -08005783 /* Record the group's reclaim efficiency */
5784 vmpressure(sc->gfp_mask, memcg, false,
5785 sc->nr_scanned - scanned,
5786 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005787
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005788 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5789}
5790
Liu Song6c9e09072020-01-30 22:14:08 -08005791static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005792{
5793 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005794 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005795 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005796 bool reclaimable = false;
5797
Johannes Weiner1b051172019-11-30 17:55:52 -08005798 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5799
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005800again:
5801 memset(&sc->nr, 0, sizeof(sc->nr));
5802
5803 nr_reclaimed = sc->nr_reclaimed;
5804 nr_scanned = sc->nr_scanned;
5805
Yu Zhao3eb07702020-09-27 20:49:08 -06005806 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005807
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005808 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005809
Johannes Weinerd2af3392019-11-30 17:55:43 -08005810 if (reclaim_state) {
5811 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5812 reclaim_state->reclaimed_slab = 0;
5813 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005814
Johannes Weinerd2af3392019-11-30 17:55:43 -08005815 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005816 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005817 sc->nr_scanned - nr_scanned,
5818 sc->nr_reclaimed - nr_reclaimed);
5819
5820 if (sc->nr_reclaimed - nr_reclaimed)
5821 reclaimable = true;
5822
5823 if (current_is_kswapd()) {
5824 /*
5825 * If reclaim is isolating dirty pages under writeback,
5826 * it implies that the long-lived page allocation rate
5827 * is exceeding the page laundering rate. Either the
5828 * global limits are not being effective at throttling
5829 * processes due to the page distribution throughout
5830 * zones or there is heavy usage of a slow backing
5831 * device. The only option is to throttle from reclaim
5832 * context which is not ideal as there is no guarantee
5833 * the dirtying process is throttled in the same way
5834 * balance_dirty_pages() manages.
5835 *
5836 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5837 * count the number of pages under pages flagged for
5838 * immediate reclaim and stall if any are encountered
5839 * in the nr_immediate check below.
5840 */
5841 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5842 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005843
Johannes Weinerd2af3392019-11-30 17:55:43 -08005844 /* Allow kswapd to start writing pages during reclaim.*/
5845 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5846 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005847
5848 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005849 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005850 * reclaim and under writeback (nr_immediate), it
5851 * implies that pages are cycling through the LRU
5852 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005853 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005854 if (sc->nr.immediate)
5855 congestion_wait(BLK_RW_ASYNC, HZ/10);
5856 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005857
Johannes Weinerd2af3392019-11-30 17:55:43 -08005858 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005859 * Tag a node/memcg as congested if all the dirty pages
5860 * scanned were backed by a congested BDI and
5861 * wait_iff_congested will stall.
5862 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005863 * Legacy memcg will stall in page writeback so avoid forcibly
5864 * stalling in wait_iff_congested().
5865 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005866 if ((current_is_kswapd() ||
5867 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005868 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005869 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005870
5871 /*
5872 * Stall direct reclaim for IO completions if underlying BDIs
5873 * and node is congested. Allow kswapd to continue until it
5874 * starts encountering unqueued dirty pages or cycling through
5875 * the LRU too quickly.
5876 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005877 if (!current_is_kswapd() && current_may_throttle() &&
5878 !sc->hibernation_mode &&
5879 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005880 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5881
5882 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5883 sc))
5884 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005885
Johannes Weinerc73322d2017-05-03 14:51:51 -07005886 /*
5887 * Kswapd gives up on balancing particular nodes after too
5888 * many failures to reclaim anything from them and goes to
5889 * sleep. On reclaim progress, reset the failure counter. A
5890 * successful direct reclaim run will revive a dormant kswapd.
5891 */
5892 if (reclaimable)
5893 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005894}
5895
Vlastimil Babka53853e22014-10-09 15:27:02 -07005896/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005897 * Returns true if compaction should go ahead for a costly-order request, or
5898 * the allocation would already succeed without compaction. Return false if we
5899 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07005900 */
Mel Gorman4f588332016-07-28 15:46:38 -07005901static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005902{
Mel Gorman31483b62016-07-28 15:45:46 -07005903 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005904 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005905
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005906 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
5907 if (suitable == COMPACT_SUCCESS)
5908 /* Allocation should succeed already. Don't reclaim. */
5909 return true;
5910 if (suitable == COMPACT_SKIPPED)
5911 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005912 return false;
5913
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005914 /*
5915 * Compaction is already possible, but it takes time to run and there
5916 * are potentially other callers using the pages just freed. So proceed
5917 * with reclaim to make a buffer of free pages available to give
5918 * compaction a reasonable chance of completing and allocating the page.
5919 * Note that we won't actually reclaim the whole buffer in one attempt
5920 * as the target watermark in should_continue_reclaim() is lower. But if
5921 * we are already above the high+gap watermark, don't reclaim at all.
5922 */
5923 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
5924
5925 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005926}
5927
Linus Torvalds1da177e2005-04-16 15:20:36 -07005928/*
5929 * This is the direct reclaim path, for page-allocating processes. We only
5930 * try to reclaim pages from zones which will satisfy the caller's allocation
5931 * request.
5932 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07005933 * If a zone is deemed to be full of pinned pages then just give it a light
5934 * scan then give up on it.
5935 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07005936static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005937{
Mel Gormandd1a2392008-04-28 02:12:17 -07005938 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07005939 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07005940 unsigned long nr_soft_reclaimed;
5941 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07005942 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07005943 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005944
Mel Gormancc715d92012-03-21 16:34:00 -07005945 /*
5946 * If the number of buffer_heads in the machine exceeds the maximum
5947 * allowed level, force direct reclaim to scan the highmem zone as
5948 * highmem pages could be pinning lowmem pages storing buffer_heads
5949 */
Weijie Yang619d0d762014-04-07 15:36:59 -07005950 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07005951 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07005952 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07005953 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07005954 }
Mel Gormancc715d92012-03-21 16:34:00 -07005955
Mel Gormand4debc62010-08-09 17:19:29 -07005956 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07005957 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07005958 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005959 * Take care memory controller reclaiming has small influence
5960 * to global LRU.
5961 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005962 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04005963 if (!cpuset_zone_allowed(zone,
5964 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005965 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005966
Johannes Weiner0b064962014-08-06 16:06:12 -07005967 /*
5968 * If we already have plenty of memory free for
5969 * compaction in this zone, don't free any more.
5970 * Even though compaction is invoked for any
5971 * non-zero order, only frequent costly order
5972 * reclamation is disruptive enough to become a
5973 * noticeable problem, like transparent huge
5974 * page allocations.
5975 */
5976 if (IS_ENABLED(CONFIG_COMPACTION) &&
5977 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07005978 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07005979 sc->compaction_ready = true;
5980 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07005981 }
Johannes Weiner0b064962014-08-06 16:06:12 -07005982
Andrew Morton0608f432013-09-24 15:27:41 -07005983 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07005984 * Shrink each node in the zonelist once. If the
5985 * zonelist is ordered by zone (not the default) then a
5986 * node may be shrunk multiple times but in that case
5987 * the user prefers lower zones being preserved.
5988 */
5989 if (zone->zone_pgdat == last_pgdat)
5990 continue;
5991
5992 /*
Andrew Morton0608f432013-09-24 15:27:41 -07005993 * This steals pages from memory cgroups over softlimit
5994 * and returns the number of reclaimed pages and
5995 * scanned pages. This works for global memory pressure
5996 * and balancing, not for a memcg's limit.
5997 */
5998 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07005999 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006000 sc->order, sc->gfp_mask,
6001 &nr_soft_scanned);
6002 sc->nr_reclaimed += nr_soft_reclaimed;
6003 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006004 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006005 }
Nick Piggin408d8542006-09-25 23:31:27 -07006006
Mel Gorman79dafcd2016-07-28 15:45:53 -07006007 /* See comment about same check for global reclaim above */
6008 if (zone->zone_pgdat == last_pgdat)
6009 continue;
6010 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006011 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006012 }
Mel Gormane0c23272011-10-31 17:09:33 -07006013
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006014 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006015 * Restore to original mask to avoid the impact on the caller if we
6016 * promoted it to __GFP_HIGHMEM.
6017 */
6018 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006019}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006020
Johannes Weinerb9107182019-11-30 17:55:59 -08006021static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006022{
Johannes Weinerb9107182019-11-30 17:55:59 -08006023 struct lruvec *target_lruvec;
6024 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006025
Yu Zhaoa1537a62022-01-27 20:32:37 -07006026 if (lru_gen_enabled())
6027 return;
6028
Johannes Weinerb9107182019-11-30 17:55:59 -08006029 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006030 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6031 target_lruvec->refaults[0] = refaults;
6032 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6033 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006034}
6035
Linus Torvalds1da177e2005-04-16 15:20:36 -07006036/*
6037 * This is the main entry point to direct page reclaim.
6038 *
6039 * If a full scan of the inactive list fails to free enough memory then we
6040 * are "out of memory" and something needs to be killed.
6041 *
6042 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6043 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006044 * caller can't do much about. We kick the writeback threads and take explicit
6045 * naps in the hope that some of these pages can be written. But if the
6046 * allocating task holds filesystem locks which prevent writeout this might not
6047 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006048 *
6049 * returns: 0, if no pages reclaimed
6050 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006051 */
Mel Gormandac1d272008-04-28 02:12:12 -07006052static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006053 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006054{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006055 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006056 pg_data_t *last_pgdat;
6057 struct zoneref *z;
6058 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006059retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006060 delayacct_freepages_start();
6061
Johannes Weinerb5ead352019-11-30 17:55:40 -08006062 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006063 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006064
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006065 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006066 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6067 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006068 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006069 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006070
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006071 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006072 break;
6073
6074 if (sc->compaction_ready)
6075 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006076
6077 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006078 * If we're getting trouble reclaiming, start doing
6079 * writepage even in laptop mode.
6080 */
6081 if (sc->priority < DEF_PRIORITY - 2)
6082 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006083 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006084
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006085 last_pgdat = NULL;
6086 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6087 sc->nodemask) {
6088 if (zone->zone_pgdat == last_pgdat)
6089 continue;
6090 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006091
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006092 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006093
6094 if (cgroup_reclaim(sc)) {
6095 struct lruvec *lruvec;
6096
6097 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6098 zone->zone_pgdat);
6099 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6100 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006101 }
6102
Keika Kobayashi873b4772008-07-25 01:48:52 -07006103 delayacct_freepages_end();
6104
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006105 if (sc->nr_reclaimed)
6106 return sc->nr_reclaimed;
6107
Mel Gorman0cee34f2012-01-12 17:19:49 -08006108 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006109 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006110 return 1;
6111
Johannes Weinerb91ac372019-11-30 17:56:02 -08006112 /*
6113 * We make inactive:active ratio decisions based on the node's
6114 * composition of memory, but a restrictive reclaim_idx or a
6115 * memory.low cgroup setting can exempt large amounts of
6116 * memory from reclaim. Neither of which are very common, so
6117 * instead of doing costly eligibility calculations of the
6118 * entire cgroup subtree up front, we assume the estimates are
6119 * good, and retry with forcible deactivation if that fails.
6120 */
6121 if (sc->skipped_deactivate) {
6122 sc->priority = initial_priority;
6123 sc->force_deactivate = 1;
6124 sc->skipped_deactivate = 0;
6125 goto retry;
6126 }
6127
Johannes Weiner241994ed2015-02-11 15:26:06 -08006128 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006129 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006130 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006131 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006132 sc->memcg_low_reclaim = 1;
6133 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006134 goto retry;
6135 }
6136
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006137 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006138}
6139
Johannes Weinerc73322d2017-05-03 14:51:51 -07006140static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006141{
6142 struct zone *zone;
6143 unsigned long pfmemalloc_reserve = 0;
6144 unsigned long free_pages = 0;
6145 int i;
6146 bool wmark_ok;
6147
Johannes Weinerc73322d2017-05-03 14:51:51 -07006148 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6149 return true;
6150
Mel Gorman55150612012-07-31 16:44:35 -07006151 for (i = 0; i <= ZONE_NORMAL; i++) {
6152 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006153 if (!managed_zone(zone))
6154 continue;
6155
6156 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006157 continue;
6158
Mel Gorman55150612012-07-31 16:44:35 -07006159 pfmemalloc_reserve += min_wmark_pages(zone);
6160 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6161 }
6162
Mel Gorman675becc2014-06-04 16:07:35 -07006163 /* If there are no reserves (unexpected config) then do not throttle */
6164 if (!pfmemalloc_reserve)
6165 return true;
6166
Mel Gorman55150612012-07-31 16:44:35 -07006167 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6168
6169 /* kswapd must be awake if processes are being throttled */
6170 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006171 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6172 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006173
Mel Gorman55150612012-07-31 16:44:35 -07006174 wake_up_interruptible(&pgdat->kswapd_wait);
6175 }
6176
6177 return wmark_ok;
6178}
6179
6180/*
6181 * Throttle direct reclaimers if backing storage is backed by the network
6182 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6183 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006184 * when the low watermark is reached.
6185 *
6186 * Returns true if a fatal signal was delivered during throttling. If this
6187 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006188 */
Mel Gorman50694c22012-11-26 16:29:48 -08006189static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006190 nodemask_t *nodemask)
6191{
Mel Gorman675becc2014-06-04 16:07:35 -07006192 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006193 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006194 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006195
6196 /*
6197 * Kernel threads should not be throttled as they may be indirectly
6198 * responsible for cleaning pages necessary for reclaim to make forward
6199 * progress. kjournald for example may enter direct reclaim while
6200 * committing a transaction where throttling it could forcing other
6201 * processes to block on log_wait_commit().
6202 */
6203 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006204 goto out;
6205
6206 /*
6207 * If a fatal signal is pending, this process should not throttle.
6208 * It should return quickly so it can exit and free its memory
6209 */
6210 if (fatal_signal_pending(current))
6211 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006212
Mel Gorman675becc2014-06-04 16:07:35 -07006213 /*
6214 * Check if the pfmemalloc reserves are ok by finding the first node
6215 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6216 * GFP_KERNEL will be required for allocating network buffers when
6217 * swapping over the network so ZONE_HIGHMEM is unusable.
6218 *
6219 * Throttling is based on the first usable node and throttled processes
6220 * wait on a queue until kswapd makes progress and wakes them. There
6221 * is an affinity then between processes waking up and where reclaim
6222 * progress has been made assuming the process wakes on the same node.
6223 * More importantly, processes running on remote nodes will not compete
6224 * for remote pfmemalloc reserves and processes on different nodes
6225 * should make reasonable progress.
6226 */
6227 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006228 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006229 if (zone_idx(zone) > ZONE_NORMAL)
6230 continue;
6231
6232 /* Throttle based on the first usable node */
6233 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006234 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006235 goto out;
6236 break;
6237 }
6238
6239 /* If no zone was usable by the allocation flags then do not throttle */
6240 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006241 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006242
Mel Gorman68243e72012-07-31 16:44:39 -07006243 /* Account for the throttling */
6244 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6245
Mel Gorman55150612012-07-31 16:44:35 -07006246 /*
6247 * If the caller cannot enter the filesystem, it's possible that it
6248 * is due to the caller holding an FS lock or performing a journal
6249 * transaction in the case of a filesystem like ext[3|4]. In this case,
6250 * it is not safe to block on pfmemalloc_wait as kswapd could be
6251 * blocked waiting on the same lock. Instead, throttle for up to a
6252 * second before continuing.
6253 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006254 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006255 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006256 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006257 else
6258 /* Throttle until kswapd wakes the process */
6259 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6260 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006261
Mel Gorman50694c22012-11-26 16:29:48 -08006262 if (fatal_signal_pending(current))
6263 return true;
6264
6265out:
6266 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006267}
6268
Mel Gormandac1d272008-04-28 02:12:12 -07006269unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006270 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006271{
Mel Gorman33906bc2010-08-09 17:19:16 -07006272 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006273 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006274 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006275 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006276 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006277 .order = order,
6278 .nodemask = nodemask,
6279 .priority = DEF_PRIORITY,
6280 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006281 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006282 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006283 };
6284
Mel Gorman55150612012-07-31 16:44:35 -07006285 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006286 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6287 * Confirm they are large enough for max values.
6288 */
6289 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6290 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6291 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6292
6293 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006294 * Do not enter reclaim if fatal signal was delivered while throttled.
6295 * 1 is returned so that the page allocator does not OOM kill at this
6296 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006297 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006298 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006299 return 1;
6300
Andrew Morton1732d2b012019-07-16 16:26:15 -07006301 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006302 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006303
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006304 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006305
6306 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006307 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006308
6309 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006310}
6311
Andrew Mortonc255a452012-07-31 16:43:02 -07006312#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006313
Michal Hockod2e5fb92019-08-30 16:04:50 -07006314/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006315unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006316 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006317 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006318 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006319{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006320 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006321 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006322 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006323 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006324 .may_writepage = !laptop_mode,
6325 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006326 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006327 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006328 };
Ying Han0ae5e892011-05-26 16:25:25 -07006329
Michal Hockod2e5fb92019-08-30 16:04:50 -07006330 WARN_ON_ONCE(!current->reclaim_state);
6331
Balbir Singh4e416952009-09-23 15:56:39 -07006332 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6333 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006334
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006335 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006336 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006337
Balbir Singh4e416952009-09-23 15:56:39 -07006338 /*
6339 * NOTE: Although we can get the priority field, using it
6340 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006341 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006342 * will pick up pages from other mem cgroup's as well. We hack
6343 * the priority and make it zero.
6344 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006345 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006346
6347 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6348
Ying Han0ae5e892011-05-26 16:25:25 -07006349 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006350
Balbir Singh4e416952009-09-23 15:56:39 -07006351 return sc.nr_reclaimed;
6352}
6353
Johannes Weiner72835c82012-01-12 17:18:32 -08006354unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006355 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006356 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006357 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08006358{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006359 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006360 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006361 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006362 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006363 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006364 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006365 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006366 .target_mem_cgroup = memcg,
6367 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006368 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006369 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006370 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07006371 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006372 /*
6373 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6374 * equal pressure on all the nodes. This is based on the assumption that
6375 * the reclaim does not bail out early.
6376 */
6377 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006378
Andrew Morton1732d2b012019-07-16 16:26:15 -07006379 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006380 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006381 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006382
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006383 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006384
Vlastimil Babka499118e2017-05-08 15:59:50 -07006385 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006386 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006387 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006388
6389 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006390}
6391#endif
6392
Mel Gorman1d82de62016-07-28 15:45:43 -07006393static void age_active_anon(struct pglist_data *pgdat,
Mel Gormanef8f2322016-07-28 15:46:05 -07006394 struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006395{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006396 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006397 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006398
Yu Zhaoa1537a62022-01-27 20:32:37 -07006399 if (lru_gen_enabled()) {
6400 lru_gen_age_node(pgdat, sc);
6401 return;
6402 }
6403
Dave Hansen2f368a92021-09-02 14:59:23 -07006404 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006405 return;
6406
Johannes Weinerb91ac372019-11-30 17:56:02 -08006407 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6408 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6409 return;
6410
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006411 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6412 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006413 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6414 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6415 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006416 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6417 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006418}
6419
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006420static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006421{
6422 int i;
6423 struct zone *zone;
6424
6425 /*
6426 * Check for watermark boosts top-down as the higher zones
6427 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006428 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006429 * start prematurely when there is no boosting and a lower
6430 * zone is balanced.
6431 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006432 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006433 zone = pgdat->node_zones + i;
6434 if (!managed_zone(zone))
6435 continue;
6436
6437 if (zone->watermark_boost)
6438 return true;
6439 }
6440
6441 return false;
6442}
6443
Mel Gormane716f2e2017-05-03 14:53:45 -07006444/*
6445 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006446 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006447 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006448static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006449{
Mel Gormane716f2e2017-05-03 14:53:45 -07006450 int i;
6451 unsigned long mark = -1;
6452 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006453
Mel Gorman1c308442018-12-28 00:35:52 -08006454 /*
6455 * Check watermarks bottom-up as lower zones are more likely to
6456 * meet watermarks.
6457 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006458 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006459 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006460
Mel Gormane716f2e2017-05-03 14:53:45 -07006461 if (!managed_zone(zone))
6462 continue;
6463
6464 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006465 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006466 return true;
6467 }
6468
6469 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006470 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006471 * need balancing by definition. This can happen if a zone-restricted
6472 * allocation tries to wake a remote kswapd.
6473 */
6474 if (mark == -1)
6475 return true;
6476
6477 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006478}
6479
Mel Gorman631b6e02017-05-03 14:53:41 -07006480/* Clear pgdat state for congested, dirty or under writeback. */
6481static void clear_pgdat_congested(pg_data_t *pgdat)
6482{
Johannes Weiner1b051172019-11-30 17:55:52 -08006483 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6484
6485 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006486 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6487 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6488}
6489
Mel Gorman1741c872011-01-13 15:46:21 -08006490/*
Mel Gorman55150612012-07-31 16:44:35 -07006491 * Prepare kswapd for sleeping. This verifies that there are no processes
6492 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6493 *
6494 * Returns true if kswapd is ready to sleep
6495 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006496static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6497 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006498{
Mel Gorman55150612012-07-31 16:44:35 -07006499 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006500 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006501 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006502 * race between when kswapd checks the watermarks and a process gets
6503 * throttled. There is also a potential race if processes get
6504 * throttled, kswapd wakes, a large process exits thereby balancing the
6505 * zones, which causes kswapd to exit balance_pgdat() before reaching
6506 * the wake up checks. If kswapd is going to sleep, no process should
6507 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6508 * the wake up is premature, processes will wake kswapd and get
6509 * throttled again. The difference from wake ups in balance_pgdat() is
6510 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006511 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006512 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6513 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006514
Johannes Weinerc73322d2017-05-03 14:51:51 -07006515 /* Hopeless node, leave it to direct reclaim */
6516 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6517 return true;
6518
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006519 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006520 clear_pgdat_congested(pgdat);
6521 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006522 }
6523
Shantanu Goel333b0a42017-05-03 14:53:38 -07006524 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006525}
6526
Linus Torvalds1da177e2005-04-16 15:20:36 -07006527/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006528 * kswapd shrinks a node of pages that are at or below the highest usable
6529 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006530 *
6531 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006532 * reclaim or if the lack of progress was due to pages under writeback.
6533 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006534 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006535static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006536 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006537{
Mel Gorman1d82de62016-07-28 15:45:43 -07006538 struct zone *zone;
6539 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006540
Mel Gorman1d82de62016-07-28 15:45:43 -07006541 /* Reclaim a number of pages proportional to the number of zones */
6542 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006543 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006544 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006545 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006546 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006547
Mel Gorman1d82de62016-07-28 15:45:43 -07006548 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006549 }
6550
Mel Gorman1d82de62016-07-28 15:45:43 -07006551 /*
6552 * Historically care was taken to put equal pressure on all zones but
6553 * now pressure is applied based on node LRU order.
6554 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006555 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006556
6557 /*
6558 * Fragmentation may mean that the system cannot be rebalanced for
6559 * high-order allocations. If twice the allocation size has been
6560 * reclaimed then recheck watermarks only at order-0 to prevent
6561 * excessive reclaim. Assume that a process requested a high-order
6562 * can direct reclaim/compact.
6563 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006564 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006565 sc->order = 0;
6566
Mel Gormanb8e83b92013-07-03 15:01:45 -07006567 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006568}
6569
Mel Gormanc49c2c42021-06-28 19:42:21 -07006570/* Page allocator PCP high watermark is lowered if reclaim is active. */
6571static inline void
6572update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6573{
6574 int i;
6575 struct zone *zone;
6576
6577 for (i = 0; i <= highest_zoneidx; i++) {
6578 zone = pgdat->node_zones + i;
6579
6580 if (!managed_zone(zone))
6581 continue;
6582
6583 if (active)
6584 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6585 else
6586 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6587 }
6588}
6589
6590static inline void
6591set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6592{
6593 update_reclaim_active(pgdat, highest_zoneidx, true);
6594}
6595
6596static inline void
6597clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6598{
6599 update_reclaim_active(pgdat, highest_zoneidx, false);
6600}
6601
Mel Gorman75485362013-07-03 15:01:42 -07006602/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006603 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6604 * that are eligible for use by the caller until at least one zone is
6605 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006606 *
Mel Gorman1d82de62016-07-28 15:45:43 -07006607 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006608 *
6609 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07006610 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08006611 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07006612 * or lower is eligible for reclaim until at least one usable zone is
6613 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006614 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006615static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006616{
Linus Torvalds1da177e2005-04-16 15:20:36 -07006617 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07006618 unsigned long nr_soft_reclaimed;
6619 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07006620 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08006621 unsigned long nr_boost_reclaim;
6622 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6623 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07006624 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08006625 struct scan_control sc = {
6626 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07006627 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006628 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08006629 };
Omar Sandoval93781322018-06-07 17:07:02 -07006630
Andrew Morton1732d2b012019-07-16 16:26:15 -07006631 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07006632 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006633 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006634
Christoph Lameterf8891e52006-06-30 01:55:45 -07006635 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006636
Mel Gorman1c308442018-12-28 00:35:52 -08006637 /*
6638 * Account for the reclaim boost. Note that the zone boost is left in
6639 * place so that parallel allocations that are near the watermark will
6640 * stall or direct reclaim until kswapd is finished.
6641 */
6642 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006643 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006644 zone = pgdat->node_zones + i;
6645 if (!managed_zone(zone))
6646 continue;
6647
6648 nr_boost_reclaim += zone->watermark_boost;
6649 zone_boosts[i] = zone->watermark_boost;
6650 }
6651 boosted = nr_boost_reclaim;
6652
6653restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006654 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006655 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006656 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006657 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006658 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006659 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006660 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006661
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006662 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006663
Mel Gorman86c79f62016-07-28 15:45:59 -07006664 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006665 * If the number of buffer_heads exceeds the maximum allowed
6666 * then consider reclaiming from all zones. This has a dual
6667 * purpose -- on 64-bit systems it is expected that
6668 * buffer_heads are stripped during active rotation. On 32-bit
6669 * systems, highmem pages can pin lowmem memory and shrinking
6670 * buffers can relieve lowmem pressure. Reclaim may still not
6671 * go ahead if all eligible zones for the original allocation
6672 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006673 */
6674 if (buffer_heads_over_limit) {
6675 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6676 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006677 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006678 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006679
Mel Gorman970a39a2016-07-28 15:46:35 -07006680 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006681 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006682 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006683 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006684
Mel Gorman86c79f62016-07-28 15:45:59 -07006685 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006686 * If the pgdat is imbalanced then ignore boosting and preserve
6687 * the watermarks for a later time and restart. Note that the
6688 * zone watermarks will be still reset at the end of balancing
6689 * on the grounds that the normal reclaim should be enough to
6690 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006691 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006692 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006693 if (!balanced && nr_boost_reclaim) {
6694 nr_boost_reclaim = 0;
6695 goto restart;
6696 }
6697
6698 /*
6699 * If boosting is not active then only reclaim if there are no
6700 * eligible zones. Note that sc.reclaim_idx is not used as
6701 * buffer_heads_over_limit may have adjusted it.
6702 */
6703 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006704 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006705
Mel Gorman1c308442018-12-28 00:35:52 -08006706 /* Limit the priority of boosting to avoid reclaim writeback */
6707 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6708 raise_priority = false;
6709
6710 /*
6711 * Do not writeback or swap pages for boosted reclaim. The
6712 * intent is to relieve pressure not issue sub-optimal IO
6713 * from reclaim context. If no pages are reclaimed, the
6714 * reclaim will be aborted.
6715 */
6716 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6717 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006718
Linus Torvalds1da177e2005-04-16 15:20:36 -07006719 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006720 * Do some background aging of the anon list, to give
6721 * pages a chance to be referenced before reclaiming. All
6722 * pages are rotated regardless of classzone as this is
6723 * about consistent aging.
6724 */
Mel Gormanef8f2322016-07-28 15:46:05 -07006725 age_active_anon(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006726
6727 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006728 * If we're getting trouble reclaiming, start doing writepage
6729 * even in laptop mode.
6730 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006731 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006732 sc.may_writepage = 1;
6733
Mel Gorman1d82de62016-07-28 15:45:43 -07006734 /* Call soft limit reclaim before calling shrink_node. */
6735 sc.nr_scanned = 0;
6736 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006737 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006738 sc.gfp_mask, &nr_soft_scanned);
6739 sc.nr_reclaimed += nr_soft_reclaimed;
6740
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006741 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006742 * There should be no need to raise the scanning priority if
6743 * enough pages are already being scanned that that high
6744 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006745 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006746 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006747 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006748
6749 /*
6750 * If the low watermark is met there is no need for processes
6751 * to be throttled on pfmemalloc_wait as they should not be
6752 * able to safely make forward progress. Wake them
6753 */
6754 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006755 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006756 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006757
Mel Gormanb8e83b92013-07-03 15:01:45 -07006758 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006759 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006760 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006761 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006762 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006763 break;
6764
6765 /*
6766 * Raise priority if scanning rate is too low or there was no
6767 * progress in reclaiming pages
6768 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006769 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006770 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6771
6772 /*
6773 * If reclaim made no progress for a boost, stop reclaim as
6774 * IO cannot be queued and it could be an infinite loop in
6775 * extreme circumstances.
6776 */
6777 if (nr_boost_reclaim && !nr_reclaimed)
6778 break;
6779
Johannes Weinerc73322d2017-05-03 14:51:51 -07006780 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006781 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006782 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006783
Johannes Weinerc73322d2017-05-03 14:51:51 -07006784 if (!sc.nr_reclaimed)
6785 pgdat->kswapd_failures++;
6786
Mel Gormanb8e83b92013-07-03 15:01:45 -07006787out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006788 clear_reclaim_active(pgdat, highest_zoneidx);
6789
Mel Gorman1c308442018-12-28 00:35:52 -08006790 /* If reclaim was boosted, account for the reclaim done in this pass */
6791 if (boosted) {
6792 unsigned long flags;
6793
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006794 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006795 if (!zone_boosts[i])
6796 continue;
6797
6798 /* Increments are under the zone lock */
6799 zone = pgdat->node_zones + i;
6800 spin_lock_irqsave(&zone->lock, flags);
6801 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6802 spin_unlock_irqrestore(&zone->lock, flags);
6803 }
6804
6805 /*
6806 * As there is now likely space, wakeup kcompact to defragment
6807 * pageblocks.
6808 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006809 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006810 }
6811
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006812 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006813 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006814 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006815 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006816
Mel Gorman0abdee22011-01-13 15:46:22 -08006817 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006818 * Return the order kswapd stopped reclaiming at as
6819 * prepare_kswapd_sleep() takes it into account. If another caller
6820 * entered the allocator slow path while kswapd was awake, order will
6821 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006822 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006823 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006824}
6825
Mel Gormane716f2e2017-05-03 14:53:45 -07006826/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006827 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6828 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6829 * not a valid index then either kswapd runs for first time or kswapd couldn't
6830 * sleep after previous reclaim attempt (node is still unbalanced). In that
6831 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006832 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006833static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6834 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006835{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006836 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006837
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006838 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006839}
6840
Mel Gorman38087d92016-07-28 15:45:49 -07006841static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006842 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006843{
6844 long remaining = 0;
6845 DEFINE_WAIT(wait);
6846
6847 if (freezing(current) || kthread_should_stop())
6848 return;
6849
6850 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6851
Shantanu Goel333b0a42017-05-03 14:53:38 -07006852 /*
6853 * Try to sleep for a short interval. Note that kcompactd will only be
6854 * woken if it is possible to sleep for a short interval. This is
6855 * deliberate on the assumption that if reclaim cannot keep an
6856 * eligible zone balanced that it's also unlikely that compaction will
6857 * succeed.
6858 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006859 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006860 /*
6861 * Compaction records what page blocks it recently failed to
6862 * isolate pages from and skips them in the future scanning.
6863 * When kswapd is going to sleep, it is reasonable to assume
6864 * that pages and compaction may succeed so reset the cache.
6865 */
6866 reset_isolation_suitable(pgdat);
6867
6868 /*
6869 * We have freed the memory, now we should compact it to make
6870 * allocation of the requested order possible.
6871 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006872 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006873
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006874 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006875
6876 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006877 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006878 * order. The values will either be from a wakeup request or
6879 * the previous request that slept prematurely.
6880 */
6881 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006882 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6883 kswapd_highest_zoneidx(pgdat,
6884 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006885
6886 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6887 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006888 }
6889
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006890 finish_wait(&pgdat->kswapd_wait, &wait);
6891 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6892 }
6893
6894 /*
6895 * After a short sleep, check if it was a premature sleep. If not, then
6896 * go fully to sleep until explicitly woken up.
6897 */
Mel Gormand9f21d42016-07-28 15:46:41 -07006898 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006899 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006900 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6901
6902 /*
6903 * vmstat counters are not perfectly accurate and the estimated
6904 * value for counters such as NR_FREE_PAGES can deviate from the
6905 * true value by nr_online_cpus * threshold. To avoid the zone
6906 * watermarks being breached while under pressure, we reduce the
6907 * per-cpu vmstat threshold while kswapd is awake and restore
6908 * them before going back to sleep.
6909 */
6910 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07006911
6912 if (!kthread_should_stop())
6913 schedule();
6914
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006915 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
6916 } else {
6917 if (remaining)
6918 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
6919 else
6920 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
6921 }
6922 finish_wait(&pgdat->kswapd_wait, &wait);
6923}
6924
Linus Torvalds1da177e2005-04-16 15:20:36 -07006925/*
6926 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006927 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006928 *
6929 * This basically trickles out pages so that we have _some_
6930 * free memory available even if there is no other activity
6931 * that frees anything up. This is needed for things like routing
6932 * etc, where we otherwise might have all activity going on in
6933 * asynchronous contexts that cannot page things out.
6934 *
6935 * If there are applications that are active memory-allocators
6936 * (most normal use), this basically shouldn't matter.
6937 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306938int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006939{
Mel Gormane716f2e2017-05-03 14:53:45 -07006940 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006941 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07006942 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006943 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10306944 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006945
Rusty Russell174596a2009-01-01 10:12:29 +10306946 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07006947 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006948
6949 /*
6950 * Tell the memory management that we're a "memory allocator",
6951 * and that if we need more memory we should get access to it
6952 * regardless (see "__alloc_pages()"). "kswapd" should
6953 * never get caught in the normal page freeing logic.
6954 *
6955 * (Kswapd normally doesn't need memory anyway, but sometimes
6956 * you need a small amount of memory in order to be able to
6957 * page out something else, and this flag essentially protects
6958 * us from recursively trying to free more memory as we're
6959 * trying to free the first piece of memory in the first place).
6960 */
Christoph Lameter930d9152006-01-08 01:00:47 -08006961 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07006962 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07006963
Qian Cai5644e1fb2020-04-01 21:10:12 -07006964 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006965 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006966 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08006967 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07006968
Qian Cai5644e1fb2020-04-01 21:10:12 -07006969 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006970 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6971 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07006972
Mel Gorman38087d92016-07-28 15:45:49 -07006973kswapd_try_sleep:
6974 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006975 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07006976
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006977 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08006978 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006979 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6980 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006981 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006982 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006983
David Rientjes8fe23e02009-12-14 17:58:33 -08006984 ret = try_to_freeze();
6985 if (kthread_should_stop())
6986 break;
6987
6988 /*
6989 * We can speed up thawing tasks if we don't call balance_pgdat
6990 * after returning from the refrigerator
6991 */
Mel Gorman38087d92016-07-28 15:45:49 -07006992 if (ret)
6993 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07006994
Mel Gorman38087d92016-07-28 15:45:49 -07006995 /*
6996 * Reclaim begins at the requested order but if a high-order
6997 * reclaim fails then kswapd falls back to reclaiming for
6998 * order-0. If that happens, kswapd will consider sleeping
6999 * for the order it finished reclaiming at (reclaim_order)
7000 * but kcompactd is woken to compact for the original
7001 * request (alloc_order).
7002 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007003 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007004 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007005 reclaim_order = balance_pgdat(pgdat, alloc_order,
7006 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007007 if (reclaim_order < alloc_order)
7008 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007009 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007010
Johannes Weiner71abdc12014-06-06 14:35:35 -07007011 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007012
Linus Torvalds1da177e2005-04-16 15:20:36 -07007013 return 0;
7014}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307015EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007016
7017/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007018 * A zone is low on free memory or too fragmented for high-order memory. If
7019 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7020 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7021 * has failed or is not needed, still wake up kcompactd if only compaction is
7022 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007023 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007024void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007025 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007026{
7027 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007028 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007029
Mel Gorman6aa303d2016-09-01 16:14:55 -07007030 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007031 return;
7032
David Rientjes5ecd9d42018-04-05 16:25:16 -07007033 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007034 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007035
Qian Cai5644e1fb2020-04-01 21:10:12 -07007036 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007037 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007038
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007039 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7040 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007041
7042 if (READ_ONCE(pgdat->kswapd_order) < order)
7043 WRITE_ONCE(pgdat->kswapd_order, order);
7044
Con Kolivas8d0986e2005-09-13 01:25:07 -07007045 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007046 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007047
David Rientjes5ecd9d42018-04-05 16:25:16 -07007048 /* Hopeless node, leave it to direct reclaim if possible */
7049 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007050 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7051 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007052 /*
7053 * There may be plenty of free memory available, but it's too
7054 * fragmented for high-order allocations. Wake up kcompactd
7055 * and rely on compaction_suitable() to determine if it's
7056 * needed. If it fails, it will defer subsequent attempts to
7057 * ratelimit its work.
7058 */
7059 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007060 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007061 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007062 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007063
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007064 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007065 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007066 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007067}
7068
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007069#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007070/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007071 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007072 * freed pages.
7073 *
7074 * Rather than trying to age LRUs the aim is to preserve the overall
7075 * LRU order by reclaiming preferentially
7076 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007077 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007078unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007079{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007080 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007081 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007082 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007083 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007084 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007085 .may_writepage = 1,
7086 .may_unmap = 1,
7087 .may_swap = 1,
7088 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007089 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007090 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007091 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007092 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007093
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007094 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007095 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007096 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007097
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007098 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007099
Andrew Morton1732d2b012019-07-16 16:26:15 -07007100 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007101 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007102 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007103
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007104 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007105}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007106#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007107
Yasunori Goto3218ae12006-06-27 02:53:33 -07007108/*
7109 * This kswapd start function will be called by init and node-hot-add.
7110 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7111 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007112void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007113{
7114 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307115 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007116
7117 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007118 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007119
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307120 trace_android_vh_kswapd_per_node(nid, &skip, true);
7121 if (skip)
7122 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007123 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7124 if (IS_ERR(pgdat->kswapd)) {
7125 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007126 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007127 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007128 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007129 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007130}
7131
David Rientjes8fe23e02009-12-14 17:58:33 -08007132/*
Jiang Liud8adde12012-07-11 14:01:52 -07007133 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007134 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007135 */
7136void kswapd_stop(int nid)
7137{
7138 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307139 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007140
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307141 trace_android_vh_kswapd_per_node(nid, &skip, false);
7142 if (skip)
7143 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007144 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007145 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007146 NODE_DATA(nid)->kswapd = NULL;
7147 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007148}
7149
Linus Torvalds1da177e2005-04-16 15:20:36 -07007150static int __init kswapd_init(void)
7151{
Wei Yang6b700b52020-04-01 21:10:09 -07007152 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007153
Linus Torvalds1da177e2005-04-16 15:20:36 -07007154 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007155 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007156 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007157 return 0;
7158}
7159
7160module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007161
7162#ifdef CONFIG_NUMA
7163/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007164 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007165 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007166 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007167 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007168 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007169int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007170
Dave Hansen51998362021-02-24 12:09:15 -08007171/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007172 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007173 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7174 * a zone.
7175 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007176#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007177
Christoph Lameter9eeff232006-01-18 17:42:31 -08007178/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007179 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007180 * occur.
7181 */
7182int sysctl_min_unmapped_ratio = 1;
7183
7184/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007185 * If the number of slab pages in a zone grows beyond this percentage then
7186 * slab reclaim needs to occur.
7187 */
7188int sysctl_min_slab_ratio = 5;
7189
Mel Gorman11fb9982016-07-28 15:46:20 -07007190static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007191{
Mel Gorman11fb9982016-07-28 15:46:20 -07007192 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7193 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7194 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007195
7196 /*
7197 * It's possible for there to be more file mapped pages than
7198 * accounted for by the pages on the file LRU lists because
7199 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7200 */
7201 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7202}
7203
7204/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007205static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007206{
Alexandru Moised031a152015-11-05 18:48:08 -08007207 unsigned long nr_pagecache_reclaimable;
7208 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007209
7210 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007211 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007212 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007213 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007214 * a better estimate
7215 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007216 if (node_reclaim_mode & RECLAIM_UNMAP)
7217 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007218 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007219 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007220
7221 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007222 if (!(node_reclaim_mode & RECLAIM_WRITE))
7223 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007224
7225 /* Watch for any possible underflows due to delta */
7226 if (unlikely(delta > nr_pagecache_reclaimable))
7227 delta = nr_pagecache_reclaimable;
7228
7229 return nr_pagecache_reclaimable - delta;
7230}
7231
Christoph Lameter0ff38492006-09-25 23:31:52 -07007232/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007233 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007234 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007235static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007236{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007237 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007238 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007239 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007240 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007241 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007242 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007243 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007244 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007245 .priority = NODE_RECLAIM_PRIORITY,
7246 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7247 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007248 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007249 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007250 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007251 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007252
Yafang Shao132bb8c2019-05-13 17:17:53 -07007253 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7254 sc.gfp_mask);
7255
Christoph Lameter9eeff232006-01-18 17:42:31 -08007256 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007257 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007258 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007259 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007260 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007261 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007262 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007263 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007264 noreclaim_flag = memalloc_noreclaim_save();
7265 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007266 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007267
Mel Gormana5f5f912016-07-28 15:46:32 -07007268 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007269 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007270 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007271 * priorities until we have enough memory freed.
7272 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007273 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007274 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007275 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007276 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007277
Andrew Morton1732d2b012019-07-16 16:26:15 -07007278 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007279 current->flags &= ~PF_SWAPWRITE;
7280 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007281 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007282 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007283
7284 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7285
Rik van Riela79311c2009-01-06 14:40:01 -08007286 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007287}
Andrew Morton179e9632006-03-22 00:08:18 -08007288
Mel Gormana5f5f912016-07-28 15:46:32 -07007289int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007290{
David Rientjesd773ed62007-10-16 23:26:01 -07007291 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007292
7293 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007294 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007295 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007296 *
Christoph Lameter96146342006-07-03 00:24:13 -07007297 * A small portion of unmapped file backed pages is needed for
7298 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007299 * thrown out if the node is overallocated. So we do not reclaim
7300 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007301 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007302 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007303 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007304 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7305 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007306 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007307
7308 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007309 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007310 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007311 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007312 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007313
7314 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007315 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007316 * have associated processors. This will favor the local processor
7317 * over remote processors and spread off node memory allocations
7318 * as wide as possible.
7319 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007320 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7321 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007322
Mel Gormana5f5f912016-07-28 15:46:32 -07007323 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7324 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007325
Mel Gormana5f5f912016-07-28 15:46:32 -07007326 ret = __node_reclaim(pgdat, gfp_mask, order);
7327 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007328
Mel Gorman24cf725182009-06-16 15:33:23 -07007329 if (!ret)
7330 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7331
David Rientjesd773ed62007-10-16 23:26:01 -07007332 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007333}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007334#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007335
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007336/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007337 * check_move_unevictable_pages - check pages for evictability and move to
7338 * appropriate zone lru list
7339 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007340 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007341 * Checks pages for evictability, if an evictable page is in the unevictable
7342 * lru list, moves it to the appropriate evictable lru list. This function
7343 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007344 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007345void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007346{
Alex Shi6168d0d2020-12-15 12:34:29 -08007347 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007348 int pgscanned = 0;
7349 int pgrescued = 0;
7350 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007351
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007352 for (i = 0; i < pvec->nr; i++) {
7353 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007354 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007355
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007356 if (PageTransTail(page))
7357 continue;
7358
7359 nr_pages = thp_nr_pages(page);
7360 pgscanned += nr_pages;
7361
Alex Shid25b5bd2020-12-15 12:34:16 -08007362 /* block memcg migration during page moving between lru */
7363 if (!TestClearPageLRU(page))
7364 continue;
7365
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007366 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007367 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007368 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007369 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007370 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007371 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007372 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007373 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007374 }
Hugh Dickins24513262012-01-20 14:34:21 -08007375
Alex Shi6168d0d2020-12-15 12:34:29 -08007376 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007377 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7378 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007379 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007380 } else if (pgscanned) {
7381 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007382 }
Hugh Dickins850465792012-01-20 14:34:19 -08007383}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007384EXPORT_SYMBOL_GPL(check_move_unevictable_pages);