blob: dc193025ac21342cd2403de381cdc8d2eb1b9d01 [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
rongqianfeng8da6ee32021-05-21 10:30:14 +0800719 trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
720
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700721 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700722 if (freeable == 0 || freeable == SHRINK_EMPTY)
723 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000724
725 /*
726 * copy the current shrinker scan count into a local variable
727 * and zero it so that other concurrent shrinker invocations
728 * don't also do this scanning work.
729 */
Yang Shi86750832021-05-04 18:36:36 -0700730 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000731
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700732 if (shrinker->seeks) {
733 delta = freeable >> priority;
734 delta *= 4;
735 do_div(delta, shrinker->seeks);
736 } else {
737 /*
738 * These objects don't require any IO to create. Trim
739 * them aggressively under memory pressure to keep
740 * them from causing refetches in the IO caches.
741 */
742 delta = freeable / 2;
743 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700744
Yang Shi18bb4732021-05-04 18:36:45 -0700745 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000746 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700747 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000748
749 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800750 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000751
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800752 /*
753 * Normally, we should not scan less than batch_size objects in one
754 * pass to avoid too frequent shrinker calls, but if the slab has less
755 * than batch_size objects in total and we are really tight on memory,
756 * we will try to reclaim all available objects, otherwise we can end
757 * up failing allocations although there are plenty of reclaimable
758 * objects spread over several slabs with usage less than the
759 * batch_size.
760 *
761 * We detect the "tight on memory" situations by looking at the total
762 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700763 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800764 * scanning at high prio and therefore should try to reclaim as much as
765 * possible.
766 */
767 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700768 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000769 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800770 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000771
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800772 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700773 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000774 ret = shrinker->scan_objects(shrinker, shrinkctl);
775 if (ret == SHRINK_STOP)
776 break;
777 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000778
Chris Wilsond460acb2017-09-06 16:19:26 -0700779 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
780 total_scan -= shrinkctl->nr_scanned;
781 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000782
783 cond_resched();
784 }
785
Yang Shi18bb4732021-05-04 18:36:45 -0700786 /*
787 * The deferred work is increased by any new work (delta) that wasn't
788 * done, decreased by old deferred work that was done now.
789 *
790 * And it is capped to two times of the freeable items.
791 */
792 next_deferred = max_t(long, (nr + delta - scanned), 0);
793 next_deferred = min(next_deferred, (2 * freeable));
794
Glauber Costa1d3d4432013-08-28 10:18:04 +1000795 /*
796 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700797 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000798 */
Yang Shi86750832021-05-04 18:36:36 -0700799 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000800
Yang Shi8efb4b52021-05-04 18:36:08 -0700801 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000802 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700803}
804
Yang Shi0a432dc2019-09-23 15:38:12 -0700805#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700806static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
807 struct mem_cgroup *memcg, int priority)
808{
Yang Shie4262c42021-05-04 18:36:23 -0700809 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700810 unsigned long ret, freed = 0;
811 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700812
Yang Shi0a432dc2019-09-23 15:38:12 -0700813 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700814 return 0;
815
816 if (!down_read_trylock(&shrinker_rwsem))
817 return 0;
818
Yang Shi468ab842021-05-04 18:36:26 -0700819 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700820 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700821 goto unlock;
822
Yang Shie4262c42021-05-04 18:36:23 -0700823 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700824 struct shrink_control sc = {
825 .gfp_mask = gfp_mask,
826 .nid = nid,
827 .memcg = memcg,
828 };
829 struct shrinker *shrinker;
830
831 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700832 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700833 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700834 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700835 continue;
836 }
837
Yang Shi0a432dc2019-09-23 15:38:12 -0700838 /* Call non-slab shrinkers even though kmem is disabled */
839 if (!memcg_kmem_enabled() &&
840 !(shrinker->flags & SHRINKER_NONSLAB))
841 continue;
842
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700843 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700844 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700845 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700846 /*
847 * After the shrinker reported that it had no objects to
848 * free, but before we cleared the corresponding bit in
849 * the memcg shrinker map, a new object might have been
850 * added. To make sure, we have the bit set in this
851 * case, we invoke the shrinker one more time and reset
852 * the bit if it reports that it is not empty anymore.
853 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700854 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700855 *
856 * list_lru_add() shrink_slab_memcg()
857 * list_add_tail() clear_bit()
858 * <MB> <MB>
859 * set_bit() do_shrink_slab()
860 */
861 smp_mb__after_atomic();
862 ret = do_shrink_slab(&sc, shrinker, priority);
863 if (ret == SHRINK_EMPTY)
864 ret = 0;
865 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700866 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700867 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700868 freed += ret;
869
870 if (rwsem_is_contended(&shrinker_rwsem)) {
871 freed = freed ? : 1;
872 break;
873 }
874 }
875unlock:
876 up_read(&shrinker_rwsem);
877 return freed;
878}
Yang Shi0a432dc2019-09-23 15:38:12 -0700879#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700880static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
881 struct mem_cgroup *memcg, int priority)
882{
883 return 0;
884}
Yang Shi0a432dc2019-09-23 15:38:12 -0700885#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700886
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800887/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800888 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800889 * @gfp_mask: allocation context
890 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800891 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800892 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700893 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800894 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700895 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800896 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
897 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700898 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700899 * @memcg specifies the memory cgroup to target. Unaware shrinkers
900 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800901 *
Josef Bacik9092c712018-01-31 16:16:26 -0800902 * @priority is sc->priority, we take the number of objects and >> by priority
903 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700904 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800905 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700906 */
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800907unsigned long shrink_slab(gfp_t gfp_mask, int nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800908 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800909 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700910{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700911 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700912 struct shrinker *shrinker;
wudean842c68a2021-04-27 17:40:41 +0800913 bool bypass = false;
914
915 trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
916 if (bypass)
917 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700918
Yang Shifa1e5122019-08-02 21:48:44 -0700919 /*
920 * The root memcg might be allocated even though memcg is disabled
921 * via "cgroup_disable=memory" boot parameter. This could make
922 * mem_cgroup_is_root() return false, then just run memcg slab
923 * shrink, but skip global shrink. This may result in premature
924 * oom.
925 */
926 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700927 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800928
Tetsuo Handae830c632018-04-05 16:23:35 -0700929 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700930 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700931
932 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800933 struct shrink_control sc = {
934 .gfp_mask = gfp_mask,
935 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800936 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800937 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800938
Kirill Tkhai9b996462018-08-17 15:48:21 -0700939 ret = do_shrink_slab(&sc, shrinker, priority);
940 if (ret == SHRINK_EMPTY)
941 ret = 0;
942 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800943 /*
944 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700945 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800946 * by parallel ongoing shrinking.
947 */
948 if (rwsem_is_contended(&shrinker_rwsem)) {
949 freed = freed ? : 1;
950 break;
951 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700952 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800953
Linus Torvalds1da177e2005-04-16 15:20:36 -0700954 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700955out:
956 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000957 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700958}
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800959EXPORT_SYMBOL_GPL(shrink_slab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700960
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800961void drop_slab_node(int nid)
962{
963 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700964 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800965
966 do {
967 struct mem_cgroup *memcg = NULL;
968
Chunxin Zang069c4112020-10-13 16:56:46 -0700969 if (fatal_signal_pending(current))
970 return;
971
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800972 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700973 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800974 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800975 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800976 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700977 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800978}
979
980void drop_slab(void)
981{
982 int nid;
983
984 for_each_online_node(nid)
985 drop_slab_node(nid);
986}
987
Linus Torvalds1da177e2005-04-16 15:20:36 -0700988static inline int is_page_cache_freeable(struct page *page)
989{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700990 /*
991 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400992 * that isolated the page, the page cache and optional buffer
993 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700994 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -0700995 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400996 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700997}
998
Yang Shicb165562019-11-30 17:55:28 -0800999static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001000{
Christoph Lameter930d9152006-01-08 01:00:47 -08001001 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001002 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001003 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001004 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001005 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001006 return 1;
1007 return 0;
1008}
1009
1010/*
1011 * We detected a synchronous write error writing a page out. Probably
1012 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1013 * fsync(), msync() or close().
1014 *
1015 * The tricky part is that after writepage we cannot touch the mapping: nothing
1016 * prevents it from being freed up. But we have a ref on the page and once
1017 * that page is locked, the mapping is pinned.
1018 *
1019 * We're allowed to run sleeping lock_page() here because we know the caller has
1020 * __GFP_FS.
1021 */
1022static void handle_write_error(struct address_space *mapping,
1023 struct page *page, int error)
1024{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001025 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001026 if (page_mapping(page) == mapping)
1027 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001028 unlock_page(page);
1029}
1030
Christoph Lameter04e62a22006-06-23 02:03:38 -07001031/* possible outcome of pageout() */
1032typedef enum {
1033 /* failed to write page out, page is locked */
1034 PAGE_KEEP,
1035 /* move page to the active list, page is locked */
1036 PAGE_ACTIVATE,
1037 /* page has been sent to the disk successfully, page is unlocked */
1038 PAGE_SUCCESS,
1039 /* page is clean and locked */
1040 PAGE_CLEAN,
1041} pageout_t;
1042
Linus Torvalds1da177e2005-04-16 15:20:36 -07001043/*
Andrew Morton1742f192006-03-22 00:08:21 -08001044 * pageout is called by shrink_page_list() for each dirty page.
1045 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001046 */
Yang Shicb165562019-11-30 17:55:28 -08001047static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001048{
1049 /*
1050 * If the page is dirty, only perform writeback if that write
1051 * will be non-blocking. To prevent this allocation from being
1052 * stalled by pagecache activity. But note that there may be
1053 * stalls if we need to run get_block(). We could test
1054 * PagePrivate for that.
1055 *
Al Viro81742022014-04-03 03:17:43 -04001056 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001057 * this page's queue, we can perform writeback even if that
1058 * will block.
1059 *
1060 * If the page is swapcache, write it back even if that would
1061 * block, for some throttling. This happens by accident, because
1062 * swap_backing_dev_info is bust: it doesn't reflect the
1063 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001064 */
1065 if (!is_page_cache_freeable(page))
1066 return PAGE_KEEP;
1067 if (!mapping) {
1068 /*
1069 * Some data journaling orphaned pages can have
1070 * page->mapping == NULL while being dirty with clean buffers.
1071 */
David Howells266cf652009-04-03 16:42:36 +01001072 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001073 if (try_to_free_buffers(page)) {
1074 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001075 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001076 return PAGE_CLEAN;
1077 }
1078 }
1079 return PAGE_KEEP;
1080 }
1081 if (mapping->a_ops->writepage == NULL)
1082 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001083 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001084 return PAGE_KEEP;
1085
1086 if (clear_page_dirty_for_io(page)) {
1087 int res;
1088 struct writeback_control wbc = {
1089 .sync_mode = WB_SYNC_NONE,
1090 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001091 .range_start = 0,
1092 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001093 .for_reclaim = 1,
1094 };
1095
1096 SetPageReclaim(page);
1097 res = mapping->a_ops->writepage(page, &wbc);
1098 if (res < 0)
1099 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001100 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001101 ClearPageReclaim(page);
1102 return PAGE_ACTIVATE;
1103 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001104
Linus Torvalds1da177e2005-04-16 15:20:36 -07001105 if (!PageWriteback(page)) {
1106 /* synchronous write or broken a_ops? */
1107 ClearPageReclaim(page);
1108 }
yalin wang3aa23852016-01-14 15:18:30 -08001109 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001110 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001111 return PAGE_SUCCESS;
1112 }
1113
1114 return PAGE_CLEAN;
1115}
1116
Andrew Mortona649fd92006-10-17 00:09:36 -07001117/*
Nick Piggine2867812008-07-25 19:45:30 -07001118 * Same as remove_mapping, but if the page is removed from the mapping, it
1119 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001120 */
Johannes Weinera5289102014-04-03 14:47:51 -07001121static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001122 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001123{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001124 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001125 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001126
Nick Piggin28e4d962006-09-25 23:31:23 -07001127 BUG_ON(!PageLocked(page));
1128 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001129
Johannes Weiner30472502021-09-02 14:53:18 -07001130 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001131 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001132 * The non racy check for a busy page.
1133 *
1134 * Must be careful with the order of the tests. When someone has
1135 * a ref to the page, it may be possible that they dirty it then
1136 * drop the reference. So if PageDirty is tested before page_count
1137 * here, then the following race may occur:
1138 *
1139 * get_user_pages(&page);
1140 * [user mapping goes away]
1141 * write_to(page);
1142 * !PageDirty(page) [good]
1143 * SetPageDirty(page);
1144 * put_page(page);
1145 * !page_count(page) [good, discard it]
1146 *
1147 * [oops, our write_to data is lost]
1148 *
1149 * Reversing the order of the tests ensures such a situation cannot
1150 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001151 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001152 *
1153 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001154 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001155 */
William Kucharski906d2782019-10-18 20:20:33 -07001156 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001157 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001158 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001159 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001160 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001161 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001162 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001163 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001164
1165 if (PageSwapCache(page)) {
1166 swp_entry_t swap = { .val = page_private(page) };
Yu Zhaoa1537a62022-01-27 20:32:37 -07001167
1168 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001169 if (reclaimed && !mapping_exiting(mapping))
1170 shadow = workingset_eviction(page, target_memcg);
Yu Zhaoa1537a62022-01-27 20:32:37 -07001171 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001172 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001173 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001174 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001175 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001176 void (*freepage)(struct page *);
1177
1178 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001179 /*
1180 * Remember a shadow entry for reclaimed file cache in
1181 * order to detect refaults, thus thrashing, later on.
1182 *
1183 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001184 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001185 * inode reclaim needs to empty out the radix tree or
1186 * the nodes are lost. Don't plant shadows behind its
1187 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001188 *
1189 * We also don't store shadows for DAX mappings because the
1190 * only page cache pages found in these are zero pages
1191 * covering holes, and because we don't want to mix DAX
1192 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001193 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001194 */
Huang Ying9de4f222020-04-06 20:04:41 -07001195 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001196 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001197 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001198 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001199 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001200
1201 if (freepage != NULL)
1202 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001203 }
1204
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001205 return 1;
1206
1207cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001208 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001209 return 0;
1210}
1211
Linus Torvalds1da177e2005-04-16 15:20:36 -07001212/*
Nick Piggine2867812008-07-25 19:45:30 -07001213 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1214 * someone else has a ref on the page, abort and return 0. If it was
1215 * successfully detached, return 1. Assumes the caller has a single ref on
1216 * this page.
1217 */
1218int remove_mapping(struct address_space *mapping, struct page *page)
1219{
Johannes Weinerb9107182019-11-30 17:55:59 -08001220 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001221 /*
1222 * Unfreezing the refcount with 1 rather than 2 effectively
1223 * drops the pagecache ref for us without requiring another
1224 * atomic operation.
1225 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001226 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001227 return 1;
1228 }
1229 return 0;
1230}
1231
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001232/**
1233 * putback_lru_page - put previously isolated page onto appropriate LRU list
1234 * @page: page to be put back to appropriate lru list
1235 *
1236 * Add previously isolated @page to appropriate LRU list.
1237 * Page may still be unevictable for other reasons.
1238 *
1239 * lru_lock must not be held, interrupts must be enabled.
1240 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001241void putback_lru_page(struct page *page)
1242{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001243 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001244 put_page(page); /* drop ref from isolate */
1245}
1246
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001247enum page_references {
1248 PAGEREF_RECLAIM,
1249 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001250 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001251 PAGEREF_ACTIVATE,
1252};
1253
1254static enum page_references page_check_references(struct page *page,
1255 struct scan_control *sc)
1256{
Johannes Weiner645747462010-03-05 13:42:22 -08001257 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001258 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001259
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001260 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1261 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001262 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001263
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001264 /*
1265 * Mlock lost the isolation race with us. Let try_to_unmap()
1266 * move the page to the unevictable list.
1267 */
1268 if (vm_flags & VM_LOCKED)
1269 return PAGEREF_RECLAIM;
1270
Johannes Weiner645747462010-03-05 13:42:22 -08001271 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001272 /*
1273 * All mapped pages start out with page table
1274 * references from the instantiating fault, so we need
1275 * to look twice if a mapped file page is used more
1276 * than once.
1277 *
1278 * Mark it and spare it for another trip around the
1279 * inactive list. Another page table reference will
1280 * lead to its activation.
1281 *
1282 * Note: the mark is set for activated pages as well
1283 * so that recently deactivated but used pages are
1284 * quickly recovered.
1285 */
1286 SetPageReferenced(page);
1287
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001288 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001289 return PAGEREF_ACTIVATE;
1290
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001291 /*
1292 * Activate file-backed executable pages after first usage.
1293 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001294 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001295 return PAGEREF_ACTIVATE;
1296
Johannes Weiner645747462010-03-05 13:42:22 -08001297 return PAGEREF_KEEP;
1298 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001299
1300 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001301 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001302 return PAGEREF_RECLAIM_CLEAN;
1303
1304 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001305}
1306
Mel Gormane2be15f2013-07-03 15:01:57 -07001307/* Check if a page is dirty or under writeback */
1308static void page_check_dirty_writeback(struct page *page,
1309 bool *dirty, bool *writeback)
1310{
Mel Gormanb4597222013-07-03 15:02:05 -07001311 struct address_space *mapping;
1312
Mel Gormane2be15f2013-07-03 15:01:57 -07001313 /*
1314 * Anonymous pages are not handled by flushers and must be written
1315 * from reclaim context. Do not stall reclaim based on them
1316 */
Huang Ying9de4f222020-04-06 20:04:41 -07001317 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001318 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001319 *dirty = false;
1320 *writeback = false;
1321 return;
1322 }
1323
1324 /* By default assume that the page flags are accurate */
1325 *dirty = PageDirty(page);
1326 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001327
1328 /* Verify dirty/writeback state if the filesystem supports it */
1329 if (!page_has_private(page))
1330 return;
1331
1332 mapping = page_mapping(page);
1333 if (mapping && mapping->a_ops->is_dirty_writeback)
1334 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001335}
1336
Dave Hansen26aa2d12021-09-02 14:59:16 -07001337static struct page *alloc_demote_page(struct page *page, unsigned long node)
1338{
1339 struct migration_target_control mtc = {
1340 /*
1341 * Allocate from 'node', or fail quickly and quietly.
1342 * When this happens, 'page' will likely just be discarded
1343 * instead of migrated.
1344 */
1345 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1346 __GFP_THISNODE | __GFP_NOWARN |
1347 __GFP_NOMEMALLOC | GFP_NOWAIT,
1348 .nid = node
1349 };
1350
1351 return alloc_migration_target(page, (unsigned long)&mtc);
1352}
1353
1354/*
1355 * Take pages on @demote_list and attempt to demote them to
1356 * another node. Pages which are not demoted are left on
1357 * @demote_pages.
1358 */
1359static unsigned int demote_page_list(struct list_head *demote_pages,
1360 struct pglist_data *pgdat)
1361{
1362 int target_nid = next_demotion_node(pgdat->node_id);
1363 unsigned int nr_succeeded;
1364 int err;
1365
1366 if (list_empty(demote_pages))
1367 return 0;
1368
1369 if (target_nid == NUMA_NO_NODE)
1370 return 0;
1371
1372 /* Demotion ignores all cpuset and mempolicy settings */
1373 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1374 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1375 &nr_succeeded);
1376
Yang Shi668e4142021-09-02 14:59:19 -07001377 if (current_is_kswapd())
1378 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1379 else
1380 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1381
Dave Hansen26aa2d12021-09-02 14:59:16 -07001382 return nr_succeeded;
1383}
1384
Nick Piggine2867812008-07-25 19:45:30 -07001385/*
Andrew Morton1742f192006-03-22 00:08:21 -08001386 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001387 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001388static unsigned int shrink_page_list(struct list_head *page_list,
1389 struct pglist_data *pgdat,
1390 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001391 struct reclaim_stat *stat,
1392 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001393{
1394 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001395 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001396 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001397 unsigned int nr_reclaimed = 0;
1398 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001399 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001400
Kirill Tkhai060f0052019-03-05 15:48:15 -08001401 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001402 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001403 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001404
Dave Hansen26aa2d12021-09-02 14:59:16 -07001405retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001406 while (!list_empty(page_list)) {
1407 struct address_space *mapping;
1408 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001409 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001410 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001411 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001412
1413 cond_resched();
1414
1415 page = lru_to_page(page_list);
1416 list_del(&page->lru);
1417
Nick Piggin529ae9a2008-08-02 12:01:03 +02001418 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001419 goto keep;
1420
Sasha Levin309381fea2014-01-23 15:52:54 -08001421 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001422
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001423 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001424
1425 /* Account the number of base pages even though THP */
1426 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001427
Hugh Dickins39b5f292012-10-08 16:33:18 -07001428 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001429 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001430
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001431 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001432 goto keep_locked;
1433
Yu Zhaoafd94c92022-01-27 20:43:22 -07001434 /* page_update_gen() tried to promote this page? */
1435 if (lru_gen_enabled() && !ignore_references &&
1436 page_mapped(page) && PageReferenced(page))
1437 goto keep_locked;
1438
Andy Whitcroftc661b072007-08-22 14:01:26 -07001439 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1440 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1441
Mel Gorman283aba92013-07-03 15:01:51 -07001442 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001443 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001444 * reclaim_congested which affects wait_iff_congested. kswapd
1445 * will stall and start writing pages if the tail of the LRU
1446 * is all dirty unqueued pages.
1447 */
1448 page_check_dirty_writeback(page, &dirty, &writeback);
1449 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001450 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001451
1452 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001453 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001454
Mel Gormand04e8ac2013-07-03 15:02:03 -07001455 /*
1456 * Treat this page as congested if the underlying BDI is or if
1457 * pages are cycling through the LRU so quickly that the
1458 * pages marked for immediate reclaim are making it to the
1459 * end of the LRU a second time.
1460 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001461 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001462 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001463 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001464 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001465 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001466
1467 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001468 * If a page at the tail of the LRU is under writeback, there
1469 * are three cases to consider.
1470 *
1471 * 1) If reclaim is encountering an excessive number of pages
1472 * under writeback and this page is both under writeback and
1473 * PageReclaim then it indicates that pages are being queued
1474 * for IO but are being recycled through the LRU before the
1475 * IO can complete. Waiting on the page itself risks an
1476 * indefinite stall if it is impossible to writeback the
1477 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001478 * note that the LRU is being scanned too quickly and the
1479 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001480 *
Tejun Heo97c93412015-05-22 18:23:36 -04001481 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001482 * not marked for immediate reclaim, or the caller does not
1483 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1484 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001485 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001486 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001487 * Require may_enter_fs because we would wait on fs, which
1488 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001489 * enter reclaim, and deadlock if it waits on a page for
1490 * which it is needed to do the write (loop masks off
1491 * __GFP_IO|__GFP_FS for this reason); but more thought
1492 * would probably show more reasons.
1493 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001494 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001495 * PageReclaim. memcg does not have any dirty pages
1496 * throttling so we could easily OOM just because too many
1497 * pages are in writeback and there is nothing else to
1498 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001499 *
1500 * In cases 1) and 2) we activate the pages to get them out of
1501 * the way while we continue scanning for clean pages on the
1502 * inactive list and refilling from the active list. The
1503 * observation here is that waiting for disk writes is more
1504 * expensive than potentially causing reloads down the line.
1505 * Since they're marked for immediate reclaim, they won't put
1506 * memory pressure on the cache working set any longer than it
1507 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001508 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001509 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001510 /* Case 1 above */
1511 if (current_is_kswapd() &&
1512 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001513 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001514 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001515 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001516
1517 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001518 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001519 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001520 /*
1521 * This is slightly racy - end_page_writeback()
1522 * might have just cleared PageReclaim, then
1523 * setting PageReclaim here end up interpreted
1524 * as PageReadahead - but that does not matter
1525 * enough to care. What we do want is for this
1526 * page to have PageReclaim set next time memcg
1527 * reclaim reaches the tests above, so it will
1528 * then wait_on_page_writeback() to avoid OOM;
1529 * and it's also appropriate in global reclaim.
1530 */
1531 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001532 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001533 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001534
1535 /* Case 3 above */
1536 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001537 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001538 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001539 /* then go back and try same page again */
1540 list_add_tail(&page->lru, page_list);
1541 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001542 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001543 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001544
Minchan Kim8940b342019-09-25 16:49:11 -07001545 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001546 references = page_check_references(page, sc);
1547
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001548 switch (references) {
1549 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001550 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001551 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001552 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001553 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001554 case PAGEREF_RECLAIM:
1555 case PAGEREF_RECLAIM_CLEAN:
1556 ; /* try to reclaim the page below */
1557 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001558
Linus Torvalds1da177e2005-04-16 15:20:36 -07001559 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001560 * Before reclaiming the page, try to relocate
1561 * its contents to another node.
1562 */
1563 if (do_demote_pass &&
1564 (thp_migration_supported() || !PageTransHuge(page))) {
1565 list_add(&page->lru, &demote_pages);
1566 unlock_page(page);
1567 continue;
1568 }
1569
1570 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001571 * Anonymous process memory has backing store?
1572 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001573 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001574 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001575 if (PageAnon(page) && PageSwapBacked(page)) {
1576 if (!PageSwapCache(page)) {
1577 if (!(sc->gfp_mask & __GFP_IO))
1578 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001579 if (page_maybe_dma_pinned(page))
1580 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001581 if (PageTransHuge(page)) {
1582 /* cannot split THP, skip it */
1583 if (!can_split_huge_page(page, NULL))
1584 goto activate_locked;
1585 /*
1586 * Split pages without a PMD map right
1587 * away. Chances are some or all of the
1588 * tail pages can be freed without IO.
1589 */
1590 if (!compound_mapcount(page) &&
1591 split_huge_page_to_list(page,
1592 page_list))
1593 goto activate_locked;
1594 }
1595 if (!add_to_swap(page)) {
1596 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001597 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001598 /* Fallback to swap normal pages */
1599 if (split_huge_page_to_list(page,
1600 page_list))
1601 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001602#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1603 count_vm_event(THP_SWPOUT_FALLBACK);
1604#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001605 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001606 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001607 }
Minchan Kim0f074652017-07-06 15:37:24 -07001608
Kirill Tkhai4b793062020-04-01 21:10:18 -07001609 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001610
1611 /* Adding to swap updated mapping */
1612 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001613 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001614 } else if (unlikely(PageTransHuge(page))) {
1615 /* Split file THP */
1616 if (split_huge_page_to_list(page, page_list))
1617 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001618 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001619
1620 /*
Yang Shi98879b32019-07-11 20:59:30 -07001621 * THP may get split above, need minus tail pages and update
1622 * nr_pages to avoid accounting tail pages twice.
1623 *
1624 * The tail pages that are added into swap cache successfully
1625 * reach here.
1626 */
1627 if ((nr_pages > 1) && !PageTransHuge(page)) {
1628 sc->nr_scanned -= (nr_pages - 1);
1629 nr_pages = 1;
1630 }
1631
1632 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001633 * The page is mapped into the page tables of one or more
1634 * processes. Try to unmap it here.
1635 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001636 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001637 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001638 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001639
1640 if (unlikely(PageTransHuge(page)))
1641 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001642
Yang Shi1fb08ac2021-06-30 18:52:01 -07001643 try_to_unmap(page, flags);
1644 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001645 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001646 if (!was_swapbacked && PageSwapBacked(page))
1647 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001648 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001649 }
1650 }
1651
1652 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001653 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001654 * Only kswapd can writeback filesystem pages
1655 * to avoid risk of stack overflow. But avoid
1656 * injecting inefficient single-page IO into
1657 * flusher writeback as much as possible: only
1658 * write pages when we've encountered many
1659 * dirty pages, and when we've already scanned
1660 * the rest of the LRU for clean pages and see
1661 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001662 */
Huang Ying9de4f222020-04-06 20:04:41 -07001663 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001664 (!current_is_kswapd() || !PageReclaim(page) ||
1665 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001666 /*
1667 * Immediately reclaim when written back.
1668 * Similar in principal to deactivate_page()
1669 * except we already have the page isolated
1670 * and know it's dirty
1671 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001672 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001673 SetPageReclaim(page);
1674
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001675 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001676 }
1677
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001678 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001679 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001680 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001681 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001682 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001683 goto keep_locked;
1684
Mel Gormand950c942015-09-04 15:47:35 -07001685 /*
1686 * Page is dirty. Flush the TLB if a writable entry
1687 * potentially exists to avoid CPU writes after IO
1688 * starts and then write it out here.
1689 */
1690 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001691 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001692 case PAGE_KEEP:
1693 goto keep_locked;
1694 case PAGE_ACTIVATE:
1695 goto activate_locked;
1696 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001697 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001698
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001699 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001700 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001701 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001702 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001703
Linus Torvalds1da177e2005-04-16 15:20:36 -07001704 /*
1705 * A synchronous write - probably a ramdisk. Go
1706 * ahead and try to reclaim the page.
1707 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001708 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001709 goto keep;
1710 if (PageDirty(page) || PageWriteback(page))
1711 goto keep_locked;
1712 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001713 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001714 case PAGE_CLEAN:
1715 ; /* try to free the page below */
1716 }
1717 }
1718
1719 /*
1720 * If the page has buffers, try to free the buffer mappings
1721 * associated with this page. If we succeed we try to free
1722 * the page as well.
1723 *
1724 * We do this even if the page is PageDirty().
1725 * try_to_release_page() does not perform I/O, but it is
1726 * possible for a page to have PageDirty set, but it is actually
1727 * clean (all its buffers are clean). This happens if the
1728 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001729 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001730 * try_to_release_page() will discover that cleanness and will
1731 * drop the buffers and mark the page clean - it can be freed.
1732 *
1733 * Rarely, pages can have buffers and no ->mapping. These are
1734 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001735 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001736 * and if that worked, and the page is no longer mapped into
1737 * process address space (page_count == 1) it can be freed.
1738 * Otherwise, leave the page on the LRU so it is swappable.
1739 */
David Howells266cf652009-04-03 16:42:36 +01001740 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001741 if (!try_to_release_page(page, sc->gfp_mask))
1742 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001743 if (!mapping && page_count(page) == 1) {
1744 unlock_page(page);
1745 if (put_page_testzero(page))
1746 goto free_it;
1747 else {
1748 /*
1749 * rare race with speculative reference.
1750 * the speculative reference will free
1751 * this page shortly, so we may
1752 * increment nr_reclaimed here (and
1753 * leave it off the LRU).
1754 */
1755 nr_reclaimed++;
1756 continue;
1757 }
1758 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001759 }
1760
Shaohua Li802a3a92017-05-03 14:52:32 -07001761 if (PageAnon(page) && !PageSwapBacked(page)) {
1762 /* follow __remove_mapping for reference */
1763 if (!page_ref_freeze(page, 1))
1764 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001765 /*
1766 * The page has only one reference left, which is
1767 * from the isolation. After the caller puts the
1768 * page back on lru and drops the reference, the
1769 * page will be freed anyway. It doesn't matter
1770 * which lru it goes. So we don't bother checking
1771 * PageDirty here.
1772 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001773 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001774 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001775 } else if (!mapping || !__remove_mapping(mapping, page, true,
1776 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001777 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001778
1779 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001780free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001781 /*
1782 * THP may get swapped out in a whole, need account
1783 * all base pages.
1784 */
1785 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001786
1787 /*
1788 * Is there need to periodically free_page_list? It would
1789 * appear not as the counts should be low
1790 */
Yang Shi7ae88532019-09-23 15:38:09 -07001791 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001792 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001793 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001794 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001795 continue;
1796
Yang Shi98879b32019-07-11 20:59:30 -07001797activate_locked_split:
1798 /*
1799 * The tail pages that are failed to add into swap cache
1800 * reach here. Fixup nr_scanned and nr_pages.
1801 */
1802 if (nr_pages > 1) {
1803 sc->nr_scanned -= (nr_pages - 1);
1804 nr_pages = 1;
1805 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001806activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001807 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001808 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1809 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001810 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001811 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001812 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001813 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001814 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001815 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001816 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001817 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001818keep_locked:
1819 unlock_page(page);
1820keep:
1821 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001822 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001823 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001824 /* 'page_list' is always empty here */
1825
1826 /* Migrate pages selected for demotion */
1827 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1828 /* Pages that could not be demoted are still in @demote_pages */
1829 if (!list_empty(&demote_pages)) {
1830 /* Pages which failed to demoted go back on @page_list for retry: */
1831 list_splice_init(&demote_pages, page_list);
1832 do_demote_pass = false;
1833 goto retry;
1834 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001835
Yang Shi98879b32019-07-11 20:59:30 -07001836 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1837
Johannes Weiner747db952014-08-08 14:19:24 -07001838 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001839 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001840 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001841
Linus Torvalds1da177e2005-04-16 15:20:36 -07001842 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001843 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001844
Andrew Morton05ff5132006-03-22 00:08:20 -08001845 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001846}
1847
Maninder Singh730ec8c2020-06-03 16:01:18 -07001848unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001849 struct list_head *page_list)
1850{
1851 struct scan_control sc = {
1852 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001853 .may_unmap = 1,
1854 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001855 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001856 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001857 struct page *page, *next;
1858 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001859 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001860
1861 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001862 if (!PageHuge(page) && page_is_file_lru(page) &&
1863 !PageDirty(page) && !__PageMovable(page) &&
1864 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001865 ClearPageActive(page);
1866 list_move(&page->lru, &clean_pages);
1867 }
1868 }
1869
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001870 /*
1871 * We should be safe here since we are only dealing with file pages and
1872 * we are not kswapd and therefore cannot write dirty file pages. But
1873 * call memalloc_noreclaim_save() anyway, just in case these conditions
1874 * change in the future.
1875 */
1876 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001877 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001878 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001879 memalloc_noreclaim_restore(noreclaim_flag);
1880
Minchan Kim02c6de82012-10-08 16:31:55 -07001881 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001882 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1883 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001884 /*
1885 * Since lazyfree pages are isolated from file LRU from the beginning,
1886 * they will rotate back to anonymous LRU in the end if it failed to
1887 * discard so isolated count will be mismatched.
1888 * Compensate the isolated count for both LRU lists.
1889 */
1890 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1891 stat.nr_lazyfree_fail);
1892 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001893 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001894 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001895}
1896
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001897/*
1898 * Attempt to remove the specified page from its LRU. Only take this page
1899 * if it is of the appropriate PageActive status. Pages which are being
1900 * freed elsewhere are also ignored.
1901 *
1902 * page: page to consider
1903 * mode: one of the LRU isolation modes defined above
1904 *
Alex Shic2135f72021-02-24 12:08:01 -08001905 * returns true on success, false on failure.
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001906 */
Alex Shic2135f72021-02-24 12:08:01 -08001907bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001908{
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001909 /* Only take pages on the LRU. */
1910 if (!PageLRU(page))
Alex Shic2135f72021-02-24 12:08:01 -08001911 return false;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001912
Minchan Kime46a2872012-10-08 16:33:48 -07001913 /* Compaction should not handle unevictable pages but CMA can do so */
1914 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
Alex Shic2135f72021-02-24 12:08:01 -08001915 return false;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001916
Mel Gormanc8244932012-01-12 17:19:38 -08001917 /*
1918 * To minimise LRU disruption, the caller can indicate that it only
1919 * wants to isolate pages it will be able to operate on without
1920 * blocking - clean pages for the most part.
1921 *
Mel Gormanc8244932012-01-12 17:19:38 -08001922 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1923 * that it is possible to migrate without blocking
1924 */
Johannes Weiner1276ad62017-02-24 14:56:11 -08001925 if (mode & ISOLATE_ASYNC_MIGRATE) {
Mel Gormanc8244932012-01-12 17:19:38 -08001926 /* All the caller can do on PageWriteback is block */
1927 if (PageWriteback(page))
Alex Shic2135f72021-02-24 12:08:01 -08001928 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001929
1930 if (PageDirty(page)) {
1931 struct address_space *mapping;
Mel Gorman69d763f2018-01-31 16:19:52 -08001932 bool migrate_dirty;
Mel Gormanc8244932012-01-12 17:19:38 -08001933
Mel Gormanc8244932012-01-12 17:19:38 -08001934 /*
1935 * Only pages without mappings or that have a
1936 * ->migratepage callback are possible to migrate
Mel Gorman69d763f2018-01-31 16:19:52 -08001937 * without blocking. However, we can be racing with
1938 * truncation so it's necessary to lock the page
1939 * to stabilise the mapping as truncation holds
1940 * the page lock until after the page is removed
1941 * from the page cache.
Mel Gormanc8244932012-01-12 17:19:38 -08001942 */
Mel Gorman69d763f2018-01-31 16:19:52 -08001943 if (!trylock_page(page))
Alex Shic2135f72021-02-24 12:08:01 -08001944 return false;
Mel Gorman69d763f2018-01-31 16:19:52 -08001945
Mel Gormanc8244932012-01-12 17:19:38 -08001946 mapping = page_mapping(page);
Hugh Dickins145e1a72018-06-01 16:50:50 -07001947 migrate_dirty = !mapping || mapping->a_ops->migratepage;
Mel Gorman69d763f2018-01-31 16:19:52 -08001948 unlock_page(page);
1949 if (!migrate_dirty)
Alex Shic2135f72021-02-24 12:08:01 -08001950 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001951 }
1952 }
Minchan Kim39deaf82011-10-31 17:06:51 -07001953
Minchan Kimf80c0672011-10-31 17:06:55 -07001954 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
Alex Shic2135f72021-02-24 12:08:01 -08001955 return false;
Minchan Kimf80c0672011-10-31 17:06:55 -07001956
Alex Shic2135f72021-02-24 12:08:01 -08001957 return true;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001958}
1959
Mel Gorman7ee36a12016-07-28 15:47:17 -07001960/*
1961 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001962 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001963 */
1964static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001965 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001966{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001967 int zid;
1968
Mel Gorman7ee36a12016-07-28 15:47:17 -07001969 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1970 if (!nr_zone_taken[zid])
1971 continue;
1972
Wei Yanga892cb62020-06-03 16:01:12 -07001973 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001974 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001975
Mel Gorman7ee36a12016-07-28 15:47:17 -07001976}
1977
Mel Gormanf611fab2021-06-30 18:53:19 -07001978/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001979 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1980 *
1981 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001982 * shrink the lists perform better by taking out a batch of pages
1983 * and working on them outside the LRU lock.
1984 *
1985 * For pagecache intensive workloads, this function is the hottest
1986 * spot in the kernel (apart from copy_*_user functions).
1987 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001988 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001989 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001990 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001991 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001992 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001993 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001994 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001995 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001996 *
1997 * returns how many pages were moved onto *@dst.
1998 */
Andrew Morton69e05942006-03-22 00:08:19 -08001999static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002000 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07002001 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002002 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002003{
Hugh Dickins75b00af2012-05-29 15:07:09 -07002004 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08002005 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07002006 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002007 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07002008 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002009 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002010 LIST_HEAD(pages_skipped);
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002011 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002012
Yang Shi98879b32019-07-11 20:59:30 -07002013 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002014 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07002015 while (scan < nr_to_scan && !list_empty(src)) {
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002016 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002017
Linus Torvalds1da177e2005-04-16 15:20:36 -07002018 page = lru_to_page(src);
2019 prefetchw_prev_lru_page(page, src, flags);
2020
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002021 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002022 total_scan += nr_pages;
2023
Mel Gormanb2e18752016-07-28 15:45:37 -07002024 if (page_zonenum(page) > sc->reclaim_idx) {
2025 list_move(&page->lru, &pages_skipped);
Yang Shi98879b32019-07-11 20:59:30 -07002026 nr_skipped[page_zonenum(page)] += nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002027 continue;
2028 }
2029
Minchan Kim791b48b2017-05-12 15:47:06 -07002030 /*
2031 * Do not count skipped pages because that makes the function
2032 * return with no isolated pages if the LRU mostly contains
2033 * ineligible pages. This causes the VM to not reclaim any
2034 * pages, triggering a premature OOM.
Yang Shi98879b32019-07-11 20:59:30 -07002035 *
2036 * Account all tail pages of THP. This would not cause
2037 * premature OOM since __isolate_lru_page() returns -EBUSY
2038 * only when the page is being freed somewhere else.
Minchan Kim791b48b2017-05-12 15:47:06 -07002039 */
Yang Shi98879b32019-07-11 20:59:30 -07002040 scan += nr_pages;
Alex Shic2135f72021-02-24 12:08:01 -08002041 if (!__isolate_lru_page_prepare(page, mode)) {
2042 /* It is being freed elsewhere */
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002043 list_move(&page->lru, src);
Alex Shic2135f72021-02-24 12:08:01 -08002044 continue;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002045 }
Alex Shic2135f72021-02-24 12:08:01 -08002046 /*
2047 * Be careful not to clear PageLRU until after we're
2048 * sure the page is not being freed elsewhere -- the
2049 * page release code relies on it.
2050 */
2051 if (unlikely(!get_page_unless_zero(page))) {
2052 list_move(&page->lru, src);
2053 continue;
2054 }
2055
2056 if (!TestClearPageLRU(page)) {
2057 /* Another thread is already isolating this page */
2058 put_page(page);
2059 list_move(&page->lru, src);
2060 continue;
2061 }
2062
2063 nr_taken += nr_pages;
2064 nr_zone_taken[page_zonenum(page)] += nr_pages;
2065 list_move(&page->lru, dst);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002066 }
2067
Mel Gormanb2e18752016-07-28 15:45:37 -07002068 /*
2069 * Splice any skipped pages to the start of the LRU list. Note that
2070 * this disrupts the LRU order when reclaiming for lower zones but
2071 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2072 * scanning would soon rescan the same pages to skip and put the
2073 * system at risk of premature OOM.
2074 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002075 if (!list_empty(&pages_skipped)) {
2076 int zid;
2077
Johannes Weiner3db65812017-05-03 14:52:13 -07002078 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002079 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2080 if (!nr_skipped[zid])
2081 continue;
2082
2083 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002084 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002085 }
2086 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002087 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002088 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Minchan Kim791b48b2017-05-12 15:47:06 -07002089 total_scan, skipped, nr_taken, mode, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002090 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002091 return nr_taken;
2092}
2093
Nick Piggin62695a82008-10-18 20:26:09 -07002094/**
2095 * isolate_lru_page - tries to isolate a page from its LRU list
2096 * @page: page to isolate from its LRU list
2097 *
2098 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2099 * vmstat statistic corresponding to whatever LRU list the page was on.
2100 *
2101 * Returns 0 if the page was removed from an LRU list.
2102 * Returns -EBUSY if the page was not on an LRU list.
2103 *
2104 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002105 * the active list, it will have PageActive set. If it was found on
2106 * the unevictable list, it will have the PageUnevictable bit set. That flag
2107 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002108 *
2109 * The vmstat statistic corresponding to the list on which the page was
2110 * found will be decremented.
2111 *
2112 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002113 *
Nick Piggin62695a82008-10-18 20:26:09 -07002114 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002115 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002116 * without a stable reference).
2117 * (2) the lru_lock must not be held.
2118 * (3) interrupts must be enabled.
2119 */
2120int isolate_lru_page(struct page *page)
2121{
2122 int ret = -EBUSY;
2123
Sasha Levin309381fea2014-01-23 15:52:54 -08002124 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002125 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002126
Alex Shid25b5bd2020-12-15 12:34:16 -08002127 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002128 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002129
Alex Shid25b5bd2020-12-15 12:34:16 -08002130 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002131 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002132 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002133 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002134 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002135 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002136
Nick Piggin62695a82008-10-18 20:26:09 -07002137 return ret;
2138}
2139
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002140/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002141 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002142 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002143 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2144 * the LRU list will go small and be scanned faster than necessary, leading to
2145 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002146 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002147static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002148 struct scan_control *sc)
2149{
2150 unsigned long inactive, isolated;
2151
2152 if (current_is_kswapd())
2153 return 0;
2154
Johannes Weinerb5ead352019-11-30 17:55:40 -08002155 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002156 return 0;
2157
2158 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002159 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2160 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002161 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002162 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2163 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002164 }
2165
Fengguang Wu3cf23842012-12-18 14:23:31 -08002166 /*
2167 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2168 * won't get blocked by normal direct-reclaimers, forming a circular
2169 * deadlock.
2170 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002171 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002172 inactive >>= 3;
2173
Rik van Riel35cd7812009-09-21 17:01:38 -07002174 return isolated > inactive;
2175}
2176
Kirill Tkhaia222f342019-05-13 17:17:00 -07002177/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002178 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2179 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002180 *
2181 * Returns the number of pages moved to the given lruvec.
2182 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002183static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2184 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002185{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002186 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002187 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002188 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002189
Kirill Tkhaia222f342019-05-13 17:17:00 -07002190 while (!list_empty(list)) {
2191 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002192 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002193 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002194 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002195 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002196 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002197 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002198 continue;
2199 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002200
Alex Shi3d06afa2020-12-15 12:33:37 -08002201 /*
2202 * The SetPageLRU needs to be kept here for list integrity.
2203 * Otherwise:
2204 * #0 move_pages_to_lru #1 release_pages
2205 * if !put_page_testzero
2206 * if (put_page_testzero())
2207 * !PageLRU //skip lru_lock
2208 * SetPageLRU()
2209 * list_add(&page->lru,)
2210 * list_add(&page->lru,)
2211 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002212 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002213
Alex Shi3d06afa2020-12-15 12:33:37 -08002214 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002215 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002216
2217 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002218 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002219 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002220 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002221 } else
2222 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002223
2224 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002225 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002226
Alex Shiafca9152020-12-15 12:34:02 -08002227 /*
2228 * All pages were isolated from the same lruvec (and isolation
2229 * inhibits memcg migration).
2230 */
Muchun Song7467c392021-06-28 19:37:59 -07002231 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002232 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002233 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002234 nr_moved += nr_pages;
2235 if (PageActive(page))
2236 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002237 }
Mel Gorman66635622010-08-09 17:19:30 -07002238
Hugh Dickins3f797682012-01-12 17:20:07 -08002239 /*
2240 * To save our caller's stack, now use input list for pages to free.
2241 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002242 list_splice(&pages_to_free, list);
2243
2244 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002245}
2246
2247/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002248 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002249 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002250 * In that case we should only throttle if the backing device it is
2251 * writing to is congested. In other cases it is safe to throttle.
2252 */
2253static int current_may_throttle(void)
2254{
NeilBrowna37b0712020-06-01 21:48:18 -07002255 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002256 current->backing_dev_info == NULL ||
2257 bdi_write_congested(current->backing_dev_info);
2258}
2259
2260/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002261 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002262 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002263 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002264static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002265shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002266 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002267{
2268 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002269 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002270 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002271 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002272 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002273 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002274 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002275 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002276 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002277
Mel Gorman599d0c92016-07-28 15:45:31 -07002278 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002279 if (stalled)
2280 return 0;
2281
2282 /* wait a bit for the reclaimer. */
2283 msleep(100);
2284 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002285
2286 /* We are about to die and free our memory. Return now. */
2287 if (fatal_signal_pending(current))
2288 return SWAP_CLUSTER_MAX;
2289 }
2290
Linus Torvalds1da177e2005-04-16 15:20:36 -07002291 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002292
Alex Shi6168d0d2020-12-15 12:34:29 -08002293 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002294
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002295 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002296 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002297
Mel Gorman599d0c92016-07-28 15:45:31 -07002298 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002299 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002300 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002301 __count_vm_events(item, nr_scanned);
2302 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002303 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2304
Alex Shi6168d0d2020-12-15 12:34:29 -08002305 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002306
Hillf Dantond563c052012-03-21 16:34:02 -07002307 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002308 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002309
Shakeel Butt013339d2020-12-14 19:06:39 -08002310 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002311
Alex Shi6168d0d2020-12-15 12:34:29 -08002312 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002313 move_pages_to_lru(lruvec, &page_list);
2314
2315 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002316 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002317 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002318 __count_vm_events(item, nr_reclaimed);
2319 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002320 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002321 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002322
Alex Shi75cc3c92020-12-15 14:20:50 -08002323 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002324 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002325 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002326
Mel Gorman92df3a72011-10-31 17:07:56 -07002327 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002328 * If dirty pages are scanned that are not queued for IO, it
2329 * implies that flushers are not doing their job. This can
2330 * happen when memory pressure pushes dirty pages to the end of
2331 * the LRU before the dirty limits are breached and the dirty
2332 * data has expired. It can also happen when the proportion of
2333 * dirty pages grows not through writes but through memory
2334 * pressure reclaiming all the clean cache. And in some cases,
2335 * the flushers simply cannot keep up with the allocation
2336 * rate. Nudge the flusher threads in case they are asleep.
2337 */
2338 if (stat.nr_unqueued_dirty == nr_taken)
2339 wakeup_flusher_threads(WB_REASON_VMSCAN);
2340
Andrey Ryabinind108c772018-04-10 16:27:59 -07002341 sc->nr.dirty += stat.nr_dirty;
2342 sc->nr.congested += stat.nr_congested;
2343 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2344 sc->nr.writeback += stat.nr_writeback;
2345 sc->nr.immediate += stat.nr_immediate;
2346 sc->nr.taken += nr_taken;
2347 if (file)
2348 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002349
Mel Gorman599d0c92016-07-28 15:45:31 -07002350 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002351 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002352 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002353}
2354
Hugh Dickins15b44732020-12-15 14:21:31 -08002355/*
2356 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2357 *
2358 * We move them the other way if the page is referenced by one or more
2359 * processes.
2360 *
2361 * If the pages are mostly unmapped, the processing is fast and it is
2362 * appropriate to hold lru_lock across the whole operation. But if
2363 * the pages are mapped, the processing is slow (page_referenced()), so
2364 * we should drop lru_lock around each page. It's impossible to balance
2365 * this, so instead we remove the pages from the LRU while processing them.
2366 * It is safe to rely on PG_active against the non-LRU pages in here because
2367 * nobody will play with that bit on a non-LRU page.
2368 *
2369 * The downside is that we have to touch page->_refcount against each page.
2370 * But we had to alter page->flags anyway.
2371 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002372static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002373 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002374 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002375 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002376{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002377 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002378 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002379 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002380 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002381 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002382 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002383 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002384 unsigned nr_deactivate, nr_activate;
2385 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002386 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002387 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002388 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002389
2390 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002391
Alex Shi6168d0d2020-12-15 12:34:29 -08002392 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002393
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002394 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002395 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002396
Mel Gorman599d0c92016-07-28 15:45:31 -07002397 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002398
Shakeel Butt912c0572020-08-06 23:26:32 -07002399 if (!cgroup_reclaim(sc))
2400 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002401 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002402
Alex Shi6168d0d2020-12-15 12:34:29 -08002403 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002404
Linus Torvalds1da177e2005-04-16 15:20:36 -07002405 while (!list_empty(&l_hold)) {
2406 cond_resched();
2407 page = lru_to_page(&l_hold);
2408 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002409
Hugh Dickins39b5f292012-10-08 16:33:18 -07002410 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002411 putback_lru_page(page);
2412 continue;
2413 }
2414
Mel Gormancc715d92012-03-21 16:34:00 -07002415 if (unlikely(buffer_heads_over_limit)) {
2416 if (page_has_private(page) && trylock_page(page)) {
2417 if (page_has_private(page))
2418 try_to_release_page(page, 0);
2419 unlock_page(page);
2420 }
2421 }
2422
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002423 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2424 if (bypass)
2425 goto skip_page_referenced;
2426
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002427 if (page_referenced(page, 0, sc->target_mem_cgroup,
2428 &vm_flags)) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002429 /*
2430 * Identify referenced, file-backed active pages and
2431 * give them one more trip around the active list. So
2432 * that executable code get better chances to stay in
2433 * memory under moderate memory pressure. Anon pages
2434 * are not likely to be evicted by use-once streaming
2435 * IO, plus JVM can create lots of anon VM_EXEC pages,
2436 * so we ignore them here.
2437 */
Huang Ying9de4f222020-04-06 20:04:41 -07002438 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002439 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002440 list_add(&page->lru, &l_active);
2441 continue;
2442 }
2443 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002444skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002445 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002446 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002447 list_add(&page->lru, &l_inactive);
2448 }
2449
Andrew Mortonb5557492009-01-06 14:40:13 -08002450 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002451 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002452 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002453 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002454
Kirill Tkhaia222f342019-05-13 17:17:00 -07002455 nr_activate = move_pages_to_lru(lruvec, &l_active);
2456 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002457 /* Keep all free pages in l_active list */
2458 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002459
2460 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2461 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2462
Mel Gorman599d0c92016-07-28 15:45:31 -07002463 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002464 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002465
Kirill Tkhaif372d892019-05-13 17:16:57 -07002466 mem_cgroup_uncharge_list(&l_active);
2467 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002468 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2469 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002470}
2471
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002472unsigned long reclaim_pages(struct list_head *page_list)
2473{
Yang Shif661d002020-04-01 21:10:05 -07002474 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002475 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002476 LIST_HEAD(node_page_list);
2477 struct reclaim_stat dummy_stat;
2478 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002479 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002480 struct scan_control sc = {
2481 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002482 .may_writepage = 1,
2483 .may_unmap = 1,
2484 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002485 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002486 };
2487
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002488 noreclaim_flag = memalloc_noreclaim_save();
2489
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002490 while (!list_empty(page_list)) {
2491 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002492 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002493 nid = page_to_nid(page);
2494 INIT_LIST_HEAD(&node_page_list);
2495 }
2496
2497 if (nid == page_to_nid(page)) {
2498 ClearPageActive(page);
2499 list_move(&page->lru, &node_page_list);
2500 continue;
2501 }
2502
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
Yang Shif661d002020-04-01 21:10:05 -07002512 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002513 }
2514
2515 if (!list_empty(&node_page_list)) {
2516 nr_reclaimed += shrink_page_list(&node_page_list,
2517 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002518 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002519 while (!list_empty(&node_page_list)) {
2520 page = lru_to_page(&node_page_list);
2521 list_del(&page->lru);
2522 putback_lru_page(page);
2523 }
2524 }
2525
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002526 memalloc_noreclaim_restore(noreclaim_flag);
2527
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002528 return nr_reclaimed;
2529}
2530
Johannes Weinerb91ac372019-11-30 17:56:02 -08002531static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2532 struct lruvec *lruvec, struct scan_control *sc)
2533{
2534 if (is_active_lru(lru)) {
2535 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2536 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2537 else
2538 sc->skipped_deactivate = 1;
2539 return 0;
2540 }
2541
2542 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2543}
2544
Rik van Riel59dc76b2016-05-20 16:56:31 -07002545/*
2546 * The inactive anon list should be small enough that the VM never has
2547 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002548 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002549 * The inactive file list should be small enough to leave most memory
2550 * to the established workingset on the scan-resistant active list,
2551 * but large enough to avoid thrashing the aggregate readahead window.
2552 *
2553 * Both inactive lists should also be large enough that each inactive
2554 * page has a chance to be referenced again before it is reclaimed.
2555 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002556 * If that fails and refaulting is observed, the inactive list grows.
2557 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002558 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002559 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002560 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2561 *
2562 * total target max
2563 * memory ratio inactive
2564 * -------------------------------------
2565 * 10MB 1 5MB
2566 * 100MB 1 50MB
2567 * 1GB 3 250MB
2568 * 10GB 10 0.9GB
2569 * 100GB 31 3GB
2570 * 1TB 101 10GB
2571 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002572 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002573static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002574{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002575 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002576 unsigned long inactive, active;
2577 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002578 unsigned long gb;
2579
Johannes Weinerb91ac372019-11-30 17:56:02 -08002580 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2581 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002582
Johannes Weinerb91ac372019-11-30 17:56:02 -08002583 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002584 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002585 inactive_ratio = int_sqrt(10 * gb);
2586 else
2587 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002588
Rik van Riel59dc76b2016-05-20 16:56:31 -07002589 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002590}
2591
Johannes Weiner9a265112013-02-22 16:32:17 -08002592enum scan_balance {
2593 SCAN_EQUAL,
2594 SCAN_FRACT,
2595 SCAN_ANON,
2596 SCAN_FILE,
2597};
2598
Yu Zhao3eb07702020-09-27 20:49:08 -06002599static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2600{
2601 unsigned long file;
2602 struct lruvec *target_lruvec;
2603
Yu Zhaoa1537a62022-01-27 20:32:37 -07002604 if (lru_gen_enabled())
2605 return;
2606
Yu Zhao3eb07702020-09-27 20:49:08 -06002607 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2608
2609 /*
2610 * Flush the memory cgroup stats, so that we read accurate per-memcg
2611 * lruvec stats for heuristics.
2612 */
2613 mem_cgroup_flush_stats();
2614
2615 /*
2616 * Determine the scan balance between anon and file LRUs.
2617 */
2618 spin_lock_irq(&target_lruvec->lru_lock);
2619 sc->anon_cost = target_lruvec->anon_cost;
2620 sc->file_cost = target_lruvec->file_cost;
2621 spin_unlock_irq(&target_lruvec->lru_lock);
2622
2623 /*
2624 * Target desirable inactive:active list ratios for the anon
2625 * and file LRU lists.
2626 */
2627 if (!sc->force_deactivate) {
2628 unsigned long refaults;
2629
2630 refaults = lruvec_page_state(target_lruvec,
2631 WORKINGSET_ACTIVATE_ANON);
2632 if (refaults != target_lruvec->refaults[0] ||
2633 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2634 sc->may_deactivate |= DEACTIVATE_ANON;
2635 else
2636 sc->may_deactivate &= ~DEACTIVATE_ANON;
2637
2638 /*
2639 * When refaults are being observed, it means a new
2640 * workingset is being established. Deactivate to get
2641 * rid of any stale active pages quickly.
2642 */
2643 refaults = lruvec_page_state(target_lruvec,
2644 WORKINGSET_ACTIVATE_FILE);
2645 if (refaults != target_lruvec->refaults[1] ||
2646 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2647 sc->may_deactivate |= DEACTIVATE_FILE;
2648 else
2649 sc->may_deactivate &= ~DEACTIVATE_FILE;
2650 } else
2651 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2652
2653 /*
2654 * If we have plenty of inactive file pages that aren't
2655 * thrashing, try to reclaim those first before touching
2656 * anonymous pages.
2657 */
2658 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2659 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2660 sc->cache_trim_mode = 1;
2661 else
2662 sc->cache_trim_mode = 0;
2663
2664 /*
2665 * Prevent the reclaimer from falling into the cache trap: as
2666 * cache pages start out inactive, every cache fault will tip
2667 * the scan balance towards the file LRU. And as the file LRU
2668 * shrinks, so does the window for rotation from references.
2669 * This means we have a runaway feedback loop where a tiny
2670 * thrashing file LRU becomes infinitely more attractive than
2671 * anon pages. Try to detect this based on file LRU size.
2672 */
2673 if (!cgroup_reclaim(sc)) {
2674 unsigned long total_high_wmark = 0;
2675 unsigned long free, anon;
2676 int z;
2677
2678 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2679 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2680 node_page_state(pgdat, NR_INACTIVE_FILE);
2681
2682 for (z = 0; z < MAX_NR_ZONES; z++) {
2683 struct zone *zone = &pgdat->node_zones[z];
2684
2685 if (!managed_zone(zone))
2686 continue;
2687
2688 total_high_wmark += high_wmark_pages(zone);
2689 }
2690
2691 /*
2692 * Consider anon: if that's low too, this isn't a
2693 * runaway file reclaim problem, but rather just
2694 * extreme pressure. Reclaim as per usual then.
2695 */
2696 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2697
2698 sc->file_is_tiny =
2699 file + free <= total_high_wmark &&
2700 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2701 anon >> sc->priority;
2702 }
2703}
2704
Linus Torvalds1da177e2005-04-16 15:20:36 -07002705/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002706 * Determine how aggressively the anon and file LRU lists should be
2707 * scanned. The relative value of each set of LRU lists is determined
2708 * by looking at the fraction of the pages scanned we did rotate back
2709 * onto the active list instead of evict.
2710 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002711 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2712 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002713 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002714static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2715 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002716{
Keith Buscha2a36482021-09-02 14:59:26 -07002717 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002718 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002719 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002720 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002721 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002722 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002723 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002724 unsigned long ap, fp;
2725 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002726 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002727
2728 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002729 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002730 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002731 goto out;
2732 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002733
Johannes Weiner10316b32013-02-22 16:32:14 -08002734 /*
2735 * Global reclaim will swap to prevent OOM even with no
2736 * swappiness, but memcg users want to use this knob to
2737 * disable swapping for individual groups completely when
2738 * using the memory controller's swap limit feature would be
2739 * too expensive.
2740 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002741 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002742 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002743 goto out;
2744 }
2745
2746 /*
2747 * Do not apply any pressure balancing cleverness when the
2748 * system is close to OOM, scan both anon and file equally
2749 * (unless the swappiness setting disagrees with swapping).
2750 */
Johannes Weiner02695172014-08-06 16:06:17 -07002751 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002752 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002753 goto out;
2754 }
2755
Johannes Weiner11d16c22013-02-22 16:32:15 -08002756 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002757 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002758 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002759 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002760 scan_balance = SCAN_ANON;
2761 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002762 }
2763
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002764 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2765
Johannes Weiner62376252014-05-06 12:50:07 -07002766 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002767 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002768 * anything from the anonymous working right now. But when balancing
2769 * anon and page cache files for reclaim, allow swapping of anon pages
2770 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002771 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002772 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002773 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002774 goto out;
2775 }
2776
Johannes Weiner9a265112013-02-22 16:32:17 -08002777 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002778 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002779 * Calculate the pressure balance between anon and file pages.
2780 *
2781 * The amount of pressure we put on each LRU is inversely
2782 * proportional to the cost of reclaiming each list, as
2783 * determined by the share of pages that are refaulting, times
2784 * the relative IO cost of bringing back a swapped out
2785 * anonymous page vs reloading a filesystem page (swappiness).
2786 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002787 * Although we limit that influence to ensure no list gets
2788 * left behind completely: at least a third of the pressure is
2789 * applied, before swappiness.
2790 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002791 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002792 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002793 total_cost = sc->anon_cost + sc->file_cost;
2794 anon_cost = total_cost + sc->anon_cost;
2795 file_cost = total_cost + sc->file_cost;
2796 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002797
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002798 ap = swappiness * (total_cost + 1);
2799 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002800
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002801 fp = (200 - swappiness) * (total_cost + 1);
2802 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002803
Shaohua Li76a33fc2010-05-24 14:32:36 -07002804 fraction[0] = ap;
2805 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002806 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002807out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002808 for_each_evictable_lru(lru) {
2809 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002810 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002811 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002812 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002813
Chris Down9783aa92019-10-06 17:58:32 -07002814 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002815 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2816 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002817
Johannes Weinerf56ce412021-08-19 19:04:21 -07002818 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002819 /*
2820 * Scale a cgroup's reclaim pressure by proportioning
2821 * its current usage to its memory.low or memory.min
2822 * setting.
2823 *
2824 * This is important, as otherwise scanning aggression
2825 * becomes extremely binary -- from nothing as we
2826 * approach the memory protection threshold, to totally
2827 * nominal as we exceed it. This results in requiring
2828 * setting extremely liberal protection thresholds. It
2829 * also means we simply get no protection at all if we
2830 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002831 *
2832 * If there is any protection in place, we reduce scan
2833 * pressure by how much of the total memory used is
2834 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002835 *
Chris Down9de7ca42019-10-06 17:58:35 -07002836 * There is one special case: in the first reclaim pass,
2837 * we skip over all groups that are within their low
2838 * protection. If that fails to reclaim enough pages to
2839 * satisfy the reclaim goal, we come back and override
2840 * the best-effort low protection. However, we still
2841 * ideally want to honor how well-behaved groups are in
2842 * that case instead of simply punishing them all
2843 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002844 * memory they are using, reducing the scan pressure
2845 * again by how much of the total memory used is under
2846 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002847 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002848 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002849 unsigned long protection;
2850
2851 /* memory.low scaling, make sure we retry before OOM */
2852 if (!sc->memcg_low_reclaim && low > min) {
2853 protection = low;
2854 sc->memcg_low_skipped = 1;
2855 } else {
2856 protection = min;
2857 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002858
2859 /* Avoid TOCTOU with earlier protection check */
2860 cgroup_size = max(cgroup_size, protection);
2861
2862 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002863 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002864
2865 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002866 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002867 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002868 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002869 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002870 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002871 } else {
2872 scan = lruvec_size;
2873 }
2874
2875 scan >>= sc->priority;
2876
Johannes Weiner688035f2017-05-03 14:52:07 -07002877 /*
2878 * If the cgroup's already been deleted, make sure to
2879 * scrape out the remaining cache.
2880 */
2881 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002882 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002883
Johannes Weiner688035f2017-05-03 14:52:07 -07002884 switch (scan_balance) {
2885 case SCAN_EQUAL:
2886 /* Scan lists relative to size */
2887 break;
2888 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002889 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002890 * Scan types proportional to swappiness and
2891 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002892 * Make sure we don't miss the last page on
2893 * the offlined memory cgroups because of a
2894 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002895 */
Gavin Shan76073c62020-02-20 20:04:24 -08002896 scan = mem_cgroup_online(memcg) ?
2897 div64_u64(scan * fraction[file], denominator) :
2898 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002899 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002900 break;
2901 case SCAN_FILE:
2902 case SCAN_ANON:
2903 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002904 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002905 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002906 break;
2907 default:
2908 /* Look ma, no brain */
2909 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002910 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002911
Johannes Weiner688035f2017-05-03 14:52:07 -07002912 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002913 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002914}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002915
Dave Hansen2f368a92021-09-02 14:59:23 -07002916/*
2917 * Anonymous LRU management is a waste if there is
2918 * ultimately no way to reclaim the memory.
2919 */
2920static bool can_age_anon_pages(struct pglist_data *pgdat,
2921 struct scan_control *sc)
2922{
2923 /* Aging the anon LRU is valuable if swap is present: */
2924 if (total_swap_pages > 0)
2925 return true;
2926
2927 /* Also valuable if anon pages can be demoted: */
2928 return can_demote(pgdat->node_id, sc);
2929}
2930
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002931#ifdef CONFIG_LRU_GEN
2932
Yu Zhao76f7f072022-01-27 19:52:09 -07002933#ifdef CONFIG_LRU_GEN_ENABLED
2934DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2935#else
2936DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2937#endif
2938
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002939/******************************************************************************
2940 * shorthand helpers
2941 ******************************************************************************/
2942
Yu Zhaoa1537a62022-01-27 20:32:37 -07002943#define DEFINE_MAX_SEQ(lruvec) \
2944 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2945
2946#define DEFINE_MIN_SEQ(lruvec) \
2947 unsigned long min_seq[ANON_AND_FILE] = { \
2948 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2949 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2950 }
2951
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002952#define for_each_gen_type_zone(gen, type, zone) \
2953 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2954 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2955 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2956
Yu Zhaoa1537a62022-01-27 20:32:37 -07002957static int page_lru_gen(struct page *page)
2958{
2959 unsigned long flags = READ_ONCE(page->flags);
2960
2961 return ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
2962}
2963
2964static int page_lru_tier(struct page *page)
2965{
2966 int refs;
2967 unsigned long flags = READ_ONCE(page->flags);
2968
2969 refs = (flags & LRU_REFS_FLAGS) == LRU_REFS_FLAGS ?
2970 ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) + 1 : 0;
2971
2972 return lru_tier_from_refs(refs);
2973}
2974
Yu Zhao76f7f072022-01-27 19:52:09 -07002975static bool get_cap(int cap)
2976{
2977#ifdef CONFIG_LRU_GEN_ENABLED
2978 return static_branch_likely(&lru_gen_caps[cap]);
2979#else
2980 return static_branch_unlikely(&lru_gen_caps[cap]);
2981#endif
2982}
2983
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002984static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
2985{
2986 struct pglist_data *pgdat = NODE_DATA(nid);
2987
2988#ifdef CONFIG_MEMCG
2989 if (memcg) {
2990 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2991
2992 /* for hotadd_new_pgdat() */
2993 if (!lruvec->pgdat)
2994 lruvec->pgdat = pgdat;
2995
2996 return lruvec;
2997 }
2998#endif
2999 VM_BUG_ON(!mem_cgroup_disabled());
3000
3001 return pgdat ? &pgdat->__lruvec : NULL;
3002}
3003
Yu Zhaoa1537a62022-01-27 20:32:37 -07003004static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
3005{
3006 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3007 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3008
3009 if (!can_demote(pgdat->node_id, sc) &&
3010 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
3011 return 0;
3012
3013 return mem_cgroup_swappiness(memcg);
3014}
3015
3016static int get_nr_gens(struct lruvec *lruvec, int type)
3017{
3018 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3019}
3020
3021static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3022{
3023 /* see the comment on lru_gen_struct */
3024 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3025 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3026 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3027}
3028
3029/******************************************************************************
Yu Zhao5280d762022-01-27 19:23:01 -07003030 * mm_struct list
3031 ******************************************************************************/
3032
3033static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3034{
3035 static struct lru_gen_mm_list mm_list = {
3036 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3037 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3038 };
3039
3040#ifdef CONFIG_MEMCG
3041 if (memcg)
3042 return &memcg->mm_list;
3043#endif
3044 VM_BUG_ON(!mem_cgroup_disabled());
3045
3046 return &mm_list;
3047}
3048
3049void lru_gen_add_mm(struct mm_struct *mm)
3050{
3051 int nid;
3052 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3053 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3054
3055 VM_BUG_ON_MM(!list_empty(&mm->lru_gen.list), mm);
3056#ifdef CONFIG_MEMCG
3057 VM_BUG_ON_MM(mm->lru_gen.memcg, mm);
3058 mm->lru_gen.memcg = memcg;
3059#endif
3060 spin_lock(&mm_list->lock);
3061
3062 for_each_node_state(nid, N_MEMORY) {
3063 struct lruvec *lruvec = get_lruvec(memcg, nid);
3064
3065 if (!lruvec)
3066 continue;
3067
3068 if (lruvec->mm_state.tail == &mm_list->fifo)
3069 lruvec->mm_state.tail = &mm->lru_gen.list;
3070 }
3071
3072 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3073
3074 spin_unlock(&mm_list->lock);
3075}
3076
3077void lru_gen_del_mm(struct mm_struct *mm)
3078{
3079 int nid;
3080 struct lru_gen_mm_list *mm_list;
3081 struct mem_cgroup *memcg = NULL;
3082
3083 if (list_empty(&mm->lru_gen.list))
3084 return;
3085
3086#ifdef CONFIG_MEMCG
3087 memcg = mm->lru_gen.memcg;
3088#endif
3089 mm_list = get_mm_list(memcg);
3090
3091 spin_lock(&mm_list->lock);
3092
3093 for_each_node(nid) {
3094 struct lruvec *lruvec = get_lruvec(memcg, nid);
3095
3096 if (!lruvec)
3097 continue;
3098
3099 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3100 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3101
3102 if (lruvec->mm_state.head != &mm->lru_gen.list)
3103 continue;
3104
3105 lruvec->mm_state.head = lruvec->mm_state.head->next;
3106 if (lruvec->mm_state.head == &mm_list->fifo)
3107 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3108 }
3109
3110 list_del_init(&mm->lru_gen.list);
3111
3112 spin_unlock(&mm_list->lock);
3113
3114#ifdef CONFIG_MEMCG
3115 mem_cgroup_put(mm->lru_gen.memcg);
3116 mm->lru_gen.memcg = NULL;
3117#endif
3118}
3119
3120#ifdef CONFIG_MEMCG
3121void lru_gen_migrate_mm(struct mm_struct *mm)
3122{
3123 struct mem_cgroup *memcg;
3124
3125 lockdep_assert_held(&mm->owner->alloc_lock);
3126
3127 /* for mm_update_next_owner() */
3128 if (mem_cgroup_disabled())
3129 return;
3130
3131 rcu_read_lock();
3132 memcg = mem_cgroup_from_task(mm->owner);
3133 rcu_read_unlock();
3134 if (memcg == mm->lru_gen.memcg)
3135 return;
3136
3137 VM_BUG_ON_MM(!mm->lru_gen.memcg, mm);
3138 VM_BUG_ON_MM(list_empty(&mm->lru_gen.list), mm);
3139
3140 lru_gen_del_mm(mm);
3141 lru_gen_add_mm(mm);
3142}
3143#endif
3144
3145/*
3146 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3147 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3148 * bits in a bitmap, k is the number of hash functions and n is the number of
3149 * inserted items.
3150 *
3151 * Page table walkers use one of the two filters to reduce their search space.
3152 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3153 * aging uses the double-buffering technique to flip to the other filter each
3154 * time it produces a new generation. For non-leaf entries that have enough
3155 * leaf entries, the aging carries them over to the next generation in
3156 * walk_pmd_range(); the eviction also report them when walking the rmap
3157 * in lru_gen_look_around().
3158 *
3159 * For future optimizations:
3160 * 1. It's not necessary to keep both filters all the time. The spare one can be
3161 * freed after the RCU grace period and reallocated if needed again.
3162 * 2. And when reallocating, it's worth scaling its size according to the number
3163 * of inserted entries in the other filter, to reduce the memory overhead on
3164 * small systems and false positives on large systems.
3165 * 3. Jenkins' hash function is an alternative to Knuth's.
3166 */
3167#define BLOOM_FILTER_SHIFT 15
3168
3169static inline int filter_gen_from_seq(unsigned long seq)
3170{
3171 return seq % NR_BLOOM_FILTERS;
3172}
3173
3174static void get_item_key(void *item, int *key)
3175{
3176 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3177
3178 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3179
3180 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3181 key[1] = hash >> BLOOM_FILTER_SHIFT;
3182}
3183
3184static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3185{
3186 unsigned long *filter;
3187 int gen = filter_gen_from_seq(seq);
3188
3189 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3190
3191 filter = lruvec->mm_state.filters[gen];
3192 if (filter) {
3193 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3194 return;
3195 }
3196
3197 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT), GFP_ATOMIC);
3198 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3199}
3200
3201static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3202{
3203 int key[2];
3204 unsigned long *filter;
3205 int gen = filter_gen_from_seq(seq);
3206
3207 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3208 if (!filter)
3209 return;
3210
3211 get_item_key(item, key);
3212
3213 if (!test_bit(key[0], filter))
3214 set_bit(key[0], filter);
3215 if (!test_bit(key[1], filter))
3216 set_bit(key[1], filter);
3217}
3218
3219static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3220{
3221 int key[2];
3222 unsigned long *filter;
3223 int gen = filter_gen_from_seq(seq);
3224
3225 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3226 if (!filter)
3227 return true;
3228
3229 get_item_key(item, key);
3230
3231 return test_bit(key[0], filter) && test_bit(key[1], filter);
3232}
3233
3234static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3235{
3236 int i;
3237 int hist;
3238
3239 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3240
3241 if (walk) {
3242 hist = lru_hist_from_seq(walk->max_seq);
3243
3244 for (i = 0; i < NR_MM_STATS; i++) {
3245 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3246 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3247 walk->mm_stats[i] = 0;
3248 }
3249 }
3250
3251 if (NR_HIST_GENS > 1 && last) {
3252 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3253
3254 for (i = 0; i < NR_MM_STATS; i++)
3255 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3256 }
3257}
3258
3259static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3260{
3261 int type;
3262 unsigned long size = 0;
3263 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3264
3265 if (!walk->full_scan && cpumask_empty(mm_cpumask(mm)) &&
3266 !node_isset(pgdat->node_id, mm->lru_gen.nodes))
3267 return true;
3268
3269 node_clear(pgdat->node_id, mm->lru_gen.nodes);
3270
3271 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3272 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3273 get_mm_counter(mm, MM_ANONPAGES) +
3274 get_mm_counter(mm, MM_SHMEMPAGES);
3275 }
3276
3277 if (size < MIN_LRU_BATCH)
3278 return true;
3279
3280 if (mm_is_oom_victim(mm))
3281 return true;
3282
3283 return !mmget_not_zero(mm);
3284}
3285
3286static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3287 struct mm_struct **iter)
3288{
3289 bool first = false;
3290 bool last = true;
3291 struct mm_struct *mm = NULL;
3292 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3293 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3294 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3295
3296 /*
3297 * There are four interesting cases for this page table walker:
3298 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3299 * there is nothing to be done.
3300 * 2. It's the first of the current generation, and it needs to reset
3301 * the Bloom filter for the next generation.
3302 * 3. It reaches the end of mm_list, and it needs to increment
3303 * mm_state->seq; the iteration is done.
3304 * 4. It's the last of the current generation, and it needs to reset the
3305 * mm stats counters for the next generation.
3306 */
3307 if (*iter)
3308 mmput_async(*iter);
3309 else if (walk->max_seq <= READ_ONCE(mm_state->seq))
3310 return false;
3311
3312 spin_lock(&mm_list->lock);
3313
3314 VM_BUG_ON(mm_state->seq + 1 < walk->max_seq);
3315 VM_BUG_ON(*iter && mm_state->seq > walk->max_seq);
3316 VM_BUG_ON(*iter && !mm_state->nr_walkers);
3317
3318 if (walk->max_seq <= mm_state->seq) {
3319 if (!*iter)
3320 last = false;
3321 goto done;
3322 }
3323
3324 if (!mm_state->nr_walkers) {
3325 VM_BUG_ON(mm_state->head && mm_state->head != &mm_list->fifo);
3326
3327 mm_state->head = mm_list->fifo.next;
3328 first = true;
3329 }
3330
3331 while (!mm && mm_state->head != &mm_list->fifo) {
3332 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3333
3334 mm_state->head = mm_state->head->next;
3335
3336 /* full scan for those added after the last iteration */
3337 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3338 mm_state->tail = mm_state->head;
3339 walk->full_scan = true;
3340 }
3341
3342 if (should_skip_mm(mm, walk))
3343 mm = NULL;
3344 }
3345
3346 if (mm_state->head == &mm_list->fifo)
3347 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3348done:
3349 if (*iter && !mm)
3350 mm_state->nr_walkers--;
3351 if (!*iter && mm)
3352 mm_state->nr_walkers++;
3353
3354 if (mm_state->nr_walkers)
3355 last = false;
3356
3357 if (mm && first)
3358 reset_bloom_filter(lruvec, walk->max_seq + 1);
3359
3360 if (*iter || last)
3361 reset_mm_stats(lruvec, walk, last);
3362
3363 spin_unlock(&mm_list->lock);
3364
3365 *iter = mm;
3366
3367 return last;
3368}
3369
3370static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3371{
3372 bool success = false;
3373 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3374 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3375 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3376
3377 if (max_seq <= READ_ONCE(mm_state->seq))
3378 return false;
3379
3380 spin_lock(&mm_list->lock);
3381
3382 VM_BUG_ON(mm_state->seq + 1 < max_seq);
3383
3384 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3385 VM_BUG_ON(mm_state->head && mm_state->head != &mm_list->fifo);
3386
3387 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3388 reset_mm_stats(lruvec, NULL, true);
3389 success = true;
3390 }
3391
3392 spin_unlock(&mm_list->lock);
3393
3394 return success;
3395}
3396
3397/******************************************************************************
Yu Zhaoa1537a62022-01-27 20:32:37 -07003398 * refault feedback loop
3399 ******************************************************************************/
3400
3401/*
3402 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3403 *
3404 * The P term is refaulted/(evicted+protected) from a tier in the generation
3405 * currently being evicted; the I term is the exponential moving average of the
3406 * P term over the generations previously evicted, using the smoothing factor
3407 * 1/2; the D term isn't supported.
3408 *
3409 * The setpoint (SP) is always the first tier of one type; the process variable
3410 * (PV) is either any tier of the other type or any other tier of the same
3411 * type.
3412 *
3413 * The error is the difference between the SP and the PV; the correction is
3414 * turn off protection when SP>PV or turn on protection when SP<PV.
3415 *
3416 * For future optimizations:
3417 * 1. The D term may discount the other two terms over time so that long-lived
3418 * generations can resist stale information.
3419 */
3420struct ctrl_pos {
3421 unsigned long refaulted;
3422 unsigned long total;
3423 int gain;
3424};
3425
3426static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3427 struct ctrl_pos *pos)
3428{
3429 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3430 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3431
3432 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3433 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3434 pos->total = lrugen->avg_total[type][tier] +
3435 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3436 if (tier)
3437 pos->total += lrugen->protected[hist][type][tier - 1];
3438 pos->gain = gain;
3439}
3440
3441static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3442{
3443 int hist, tier;
3444 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3445 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3446 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3447
3448 lockdep_assert_held(&lruvec->lru_lock);
3449
3450 if (!carryover && !clear)
3451 return;
3452
3453 hist = lru_hist_from_seq(seq);
3454
3455 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3456 if (carryover) {
3457 unsigned long sum;
3458
3459 sum = lrugen->avg_refaulted[type][tier] +
3460 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3461 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3462
3463 sum = lrugen->avg_total[type][tier] +
3464 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3465 if (tier)
3466 sum += lrugen->protected[hist][type][tier - 1];
3467 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3468 }
3469
3470 if (clear) {
3471 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3472 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3473 if (tier)
3474 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3475 }
3476 }
3477}
3478
3479static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3480{
3481 /*
3482 * Return true if the PV has a limited number of refaults or a lower
3483 * refaulted/total than the SP.
3484 */
3485 return pv->refaulted < MIN_LRU_BATCH ||
3486 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3487 (sp->refaulted + 1) * pv->total * pv->gain;
3488}
3489
3490/******************************************************************************
3491 * the aging
3492 ******************************************************************************/
3493
Yu Zhaoafd94c92022-01-27 20:43:22 -07003494static int page_update_gen(struct page *page, int gen)
3495{
3496 unsigned long old_flags, new_flags;
3497
3498 VM_BUG_ON(gen >= MAX_NR_GENS);
3499 VM_BUG_ON(!rcu_read_lock_held());
3500
3501 do {
3502 new_flags = old_flags = READ_ONCE(page->flags);
3503
3504 /* for shrink_page_list() */
3505 if (!(new_flags & LRU_GEN_MASK)) {
3506 new_flags |= BIT(PG_referenced);
3507 continue;
3508 }
3509
3510 new_flags &= ~LRU_GEN_MASK;
3511 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3512 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3513 } while (new_flags != old_flags &&
3514 cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3515
3516 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3517}
3518
Yu Zhaoa1537a62022-01-27 20:32:37 -07003519static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3520{
3521 unsigned long old_flags, new_flags;
3522 int type = page_is_file_lru(page);
3523 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3524 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3525
3526 do {
3527 new_flags = old_flags = READ_ONCE(page->flags);
3528 VM_BUG_ON_PAGE(!(new_flags & LRU_GEN_MASK), page);
3529
Yu Zhaoafd94c92022-01-27 20:43:22 -07003530 new_gen = ((new_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3531 /* page_update_gen() has promoted this page? */
3532 if (new_gen >= 0 && new_gen != old_gen)
3533 return new_gen;
3534
Yu Zhaoa1537a62022-01-27 20:32:37 -07003535 new_gen = (old_gen + 1) % MAX_NR_GENS;
3536
3537 new_flags &= ~LRU_GEN_MASK;
3538 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3539 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3540 /* for end_page_writeback() */
3541 if (reclaiming)
3542 new_flags |= BIT(PG_reclaim);
3543 } while (cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3544
3545 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3546
3547 return new_gen;
3548}
3549
Yu Zhao5280d762022-01-27 19:23:01 -07003550static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3551 int old_gen, int new_gen)
3552{
3553 int type = page_is_file_lru(page);
3554 int zone = page_zonenum(page);
3555 int delta = thp_nr_pages(page);
3556
3557 VM_BUG_ON(old_gen >= MAX_NR_GENS);
3558 VM_BUG_ON(new_gen >= MAX_NR_GENS);
3559
3560 walk->batched++;
3561
3562 walk->nr_pages[old_gen][type][zone] -= delta;
3563 walk->nr_pages[new_gen][type][zone] += delta;
3564}
3565
3566static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3567{
3568 int gen, type, zone;
3569 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3570
3571 walk->batched = 0;
3572
3573 for_each_gen_type_zone(gen, type, zone) {
3574 enum lru_list lru = type * LRU_INACTIVE_FILE;
3575 int delta = walk->nr_pages[gen][type][zone];
3576
3577 if (!delta)
3578 continue;
3579
3580 walk->nr_pages[gen][type][zone] = 0;
3581 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3582 lrugen->nr_pages[gen][type][zone] + delta);
3583
3584 if (lru_gen_is_active(lruvec, gen))
3585 lru += LRU_ACTIVE;
3586 __update_lru_size(lruvec, lru, zone, delta);
3587 }
3588}
3589
3590static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *walk)
3591{
3592 struct address_space *mapping;
3593 struct vm_area_struct *vma = walk->vma;
3594 struct lru_gen_mm_walk *priv = walk->private;
3595
3596 if (!vma_is_accessible(vma) || is_vm_hugetlb_page(vma) ||
3597 (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ)) ||
3598 vma == get_gate_vma(vma->vm_mm))
3599 return true;
3600
3601 if (vma_is_anonymous(vma))
3602 return !priv->can_swap;
3603
3604 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3605 return true;
3606
3607 mapping = vma->vm_file->f_mapping;
3608 if (mapping_unevictable(mapping))
3609 return true;
3610
3611 /* check readpage to exclude special mappings like dax, etc. */
3612 return shmem_mapping(mapping) ? !priv->can_swap : !mapping->a_ops->readpage;
3613}
3614
3615/*
3616 * Some userspace memory allocators map many single-page VMAs. Instead of
3617 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3618 * table to reduce zigzags and improve cache performance.
3619 */
3620static bool get_next_vma(struct mm_walk *walk, unsigned long mask, unsigned long size,
3621 unsigned long *start, unsigned long *end)
3622{
3623 unsigned long next = round_up(*end, size);
3624
3625 VM_BUG_ON(mask & size);
3626 VM_BUG_ON(*start >= *end);
3627 VM_BUG_ON((next & mask) != (*start & mask));
3628
3629 while (walk->vma) {
3630 if (next >= walk->vma->vm_end) {
3631 walk->vma = walk->vma->vm_next;
3632 continue;
3633 }
3634
3635 if ((next & mask) != (walk->vma->vm_start & mask))
3636 return false;
3637
3638 if (should_skip_vma(walk->vma->vm_start, walk->vma->vm_end, walk)) {
3639 walk->vma = walk->vma->vm_next;
3640 continue;
3641 }
3642
3643 *start = max(next, walk->vma->vm_start);
3644 next = (next | ~mask) + 1;
3645 /* rounded-up boundaries can wrap to 0 */
3646 *end = next && next < walk->vma->vm_end ? next : walk->vma->vm_end;
3647
3648 return true;
3649 }
3650
3651 return false;
3652}
3653
3654static bool suitable_to_scan(int total, int young)
3655{
3656 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3657
3658 /* suitable if the average number of young PTEs per cacheline is >=1 */
3659 return young * n >= total;
3660}
3661
3662static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3663 struct mm_walk *walk)
3664{
3665 int i;
3666 pte_t *pte;
3667 spinlock_t *ptl;
3668 unsigned long addr;
3669 int total = 0;
3670 int young = 0;
3671 struct lru_gen_mm_walk *priv = walk->private;
3672 struct mem_cgroup *memcg = lruvec_memcg(priv->lruvec);
3673 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3674 int old_gen, new_gen = lru_gen_from_seq(priv->max_seq);
3675
3676 VM_BUG_ON(pmd_leaf(*pmd));
3677
3678 ptl = pte_lockptr(walk->mm, pmd);
3679 if (!spin_trylock(ptl))
3680 return false;
3681
3682 arch_enter_lazy_mmu_mode();
3683
3684 pte = pte_offset_map(pmd, start & PMD_MASK);
3685restart:
3686 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3687 struct page *page;
3688 unsigned long pfn = pte_pfn(pte[i]);
3689
3690 VM_BUG_ON(addr < walk->vma->vm_start || addr >= walk->vma->vm_end);
3691
3692 total++;
3693 priv->mm_stats[MM_PTE_TOTAL]++;
3694
3695 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
3696 continue;
3697
3698 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
3699 continue;
3700
3701 if (!pte_young(pte[i])) {
3702 priv->mm_stats[MM_PTE_OLD]++;
3703 continue;
3704 }
3705
3706 VM_BUG_ON(!pfn_valid(pfn));
3707 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3708 continue;
3709
3710 page = compound_head(pfn_to_page(pfn));
3711 if (page_to_nid(page) != pgdat->node_id)
3712 continue;
3713
3714 if (page_memcg_rcu(page) != memcg)
3715 continue;
3716
3717 if (!ptep_test_and_clear_young(walk->vma, addr, pte + i))
3718 continue;
3719
3720 young++;
3721 priv->mm_stats[MM_PTE_YOUNG]++;
3722
3723 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3724 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3725 set_page_dirty(page);
3726
3727 old_gen = page_update_gen(page, new_gen);
3728 if (old_gen >= 0 && old_gen != new_gen)
3729 update_batch_size(priv, page, old_gen, new_gen);
3730 }
3731
3732 if (i < PTRS_PER_PTE && get_next_vma(walk, PMD_MASK, PAGE_SIZE, &start, &end))
3733 goto restart;
3734
3735 pte_unmap(pte);
3736
3737 arch_leave_lazy_mmu_mode();
3738 spin_unlock(ptl);
3739
3740 return suitable_to_scan(total, young);
3741}
3742
3743#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3744static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3745 struct mm_walk *walk, unsigned long *start)
3746{
3747 int i;
3748 pmd_t *pmd;
3749 spinlock_t *ptl;
3750 struct lru_gen_mm_walk *priv = walk->private;
3751 struct mem_cgroup *memcg = lruvec_memcg(priv->lruvec);
3752 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3753 int old_gen, new_gen = lru_gen_from_seq(priv->max_seq);
3754
3755 VM_BUG_ON(pud_leaf(*pud));
3756
3757 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3758 if (*start == -1) {
3759 *start = next;
3760 return;
3761 }
3762
3763 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3764 if (i && i <= MIN_LRU_BATCH) {
3765 __set_bit(i - 1, priv->bitmap);
3766 return;
3767 }
3768
3769 pmd = pmd_offset(pud, *start);
3770
3771 ptl = pmd_lockptr(walk->mm, pmd);
3772 if (!spin_trylock(ptl))
3773 goto done;
3774
3775 arch_enter_lazy_mmu_mode();
3776
3777 do {
3778 struct page *page;
3779 unsigned long pfn = pmd_pfn(pmd[i]);
3780 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3781
3782 VM_BUG_ON(addr < vma->vm_start || addr >= vma->vm_end);
3783
3784 if (!pmd_present(pmd[i]) || is_huge_zero_pmd(pmd[i]))
3785 goto next;
3786
3787 if (WARN_ON_ONCE(pmd_devmap(pmd[i])))
3788 goto next;
3789
3790 if (!pmd_trans_huge(pmd[i])) {
Yu Zhao76f7f072022-01-27 19:52:09 -07003791 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3792 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao5280d762022-01-27 19:23:01 -07003793 pmdp_test_and_clear_young(vma, addr, pmd + i);
3794 goto next;
3795 }
3796
3797 VM_BUG_ON(!pfn_valid(pfn));
3798 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3799 goto next;
3800
3801 page = pfn_to_page(pfn);
3802 VM_BUG_ON_PAGE(PageTail(page), page);
3803 if (page_to_nid(page) != pgdat->node_id)
3804 goto next;
3805
3806 if (page_memcg_rcu(page) != memcg)
3807 goto next;
3808
3809 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3810 goto next;
3811
3812 priv->mm_stats[MM_PTE_YOUNG]++;
3813
3814 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3815 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3816 set_page_dirty(page);
3817
3818 old_gen = page_update_gen(page, new_gen);
3819 if (old_gen >= 0 && old_gen != new_gen)
3820 update_batch_size(priv, page, old_gen, new_gen);
3821next:
3822 i = i > MIN_LRU_BATCH ? 0 :
3823 find_next_bit(priv->bitmap, MIN_LRU_BATCH, i) + 1;
3824 } while (i <= MIN_LRU_BATCH);
3825
3826 arch_leave_lazy_mmu_mode();
3827 spin_unlock(ptl);
3828done:
3829 *start = -1;
3830 bitmap_zero(priv->bitmap, MIN_LRU_BATCH);
3831}
3832#else
3833static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3834 struct mm_walk *walk, unsigned long *start)
3835{
3836}
3837#endif
3838
3839static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3840 struct mm_walk *walk)
3841{
3842 int i;
3843 pmd_t *pmd;
3844 unsigned long next;
3845 unsigned long addr;
3846 struct vm_area_struct *vma;
3847 unsigned long pos = -1;
3848 struct lru_gen_mm_walk *priv = walk->private;
3849
3850 VM_BUG_ON(pud_leaf(*pud));
3851
3852 /*
3853 * Finish an entire PMD in two passes: the first only reaches to PTE
3854 * tables to avoid taking the PMD lock; the second, if necessary, takes
3855 * the PMD lock to clear the accessed bit in PMD entries.
3856 */
3857 pmd = pmd_offset(pud, start & PUD_MASK);
3858restart:
3859 /* walk_pte_range() may call get_next_vma() */
3860 vma = walk->vma;
3861 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3862 pmd_t val = pmd_read_atomic(pmd + i);
3863
3864 /* for pmd_read_atomic() */
3865 barrier();
3866
3867 next = pmd_addr_end(addr, end);
3868
3869 if (!pmd_present(val)) {
3870 priv->mm_stats[MM_PTE_TOTAL]++;
3871 continue;
3872 }
3873
3874#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3875 if (pmd_trans_huge(val)) {
3876 unsigned long pfn = pmd_pfn(val);
3877 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3878
3879 priv->mm_stats[MM_PTE_TOTAL]++;
3880
3881 if (is_huge_zero_pmd(val))
3882 continue;
3883
3884 if (!pmd_young(val)) {
3885 priv->mm_stats[MM_PTE_OLD]++;
3886 continue;
3887 }
3888
3889 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3890 continue;
3891
3892 walk_pmd_range_locked(pud, addr, vma, walk, &pos);
3893 continue;
3894 }
3895#endif
3896 priv->mm_stats[MM_PMD_TOTAL]++;
3897
3898#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
Yu Zhao76f7f072022-01-27 19:52:09 -07003899 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3900 if (!pmd_young(val))
3901 continue;
Yu Zhao5280d762022-01-27 19:23:01 -07003902
Yu Zhao76f7f072022-01-27 19:52:09 -07003903 walk_pmd_range_locked(pud, addr, vma, walk, &pos);
3904 }
Yu Zhao5280d762022-01-27 19:23:01 -07003905#endif
3906 if (!priv->full_scan && !test_bloom_filter(priv->lruvec, priv->max_seq, pmd + i))
3907 continue;
3908
3909 priv->mm_stats[MM_PMD_FOUND]++;
3910
3911 if (!walk_pte_range(&val, addr, next, walk))
3912 continue;
3913
3914 priv->mm_stats[MM_PMD_ADDED]++;
3915
3916 /* carry over to the next generation */
3917 update_bloom_filter(priv->lruvec, priv->max_seq + 1, pmd + i);
3918 }
3919
3920 walk_pmd_range_locked(pud, -1, vma, walk, &pos);
3921
3922 if (i < PTRS_PER_PMD && get_next_vma(walk, PUD_MASK, PMD_SIZE, &start, &end))
3923 goto restart;
3924}
3925
3926static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3927 struct mm_walk *walk)
3928{
3929 int i;
3930 pud_t *pud;
3931 unsigned long addr;
3932 unsigned long next;
3933 struct lru_gen_mm_walk *priv = walk->private;
3934
3935 VM_BUG_ON(p4d_leaf(*p4d));
3936
3937 pud = pud_offset(p4d, start & P4D_MASK);
3938restart:
3939 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3940 pud_t val = READ_ONCE(pud[i]);
3941
3942 next = pud_addr_end(addr, end);
3943
3944 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3945 continue;
3946
3947 walk_pmd_range(&val, addr, next, walk);
3948
3949 if (priv->batched >= MAX_LRU_BATCH) {
3950 end = (addr | ~PUD_MASK) + 1;
3951 goto done;
3952 }
3953 }
3954
3955 if (i < PTRS_PER_PUD && get_next_vma(walk, P4D_MASK, PUD_SIZE, &start, &end))
3956 goto restart;
3957
3958 end = round_up(end, P4D_SIZE);
3959done:
3960 /* rounded-up boundaries can wrap to 0 */
3961 priv->next_addr = end && walk->vma ? max(end, walk->vma->vm_start) : 0;
3962
3963 return -EAGAIN;
3964}
3965
3966static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3967{
3968 static const struct mm_walk_ops mm_walk_ops = {
3969 .test_walk = should_skip_vma,
3970 .p4d_entry = walk_pud_range,
3971 };
3972
3973 int err;
3974 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3975
3976 walk->next_addr = FIRST_USER_ADDRESS;
3977
3978 do {
3979 err = -EBUSY;
3980
3981 /* page_update_gen() requires stable page_memcg() */
3982 if (!mem_cgroup_trylock_pages(memcg))
3983 break;
3984
3985 /* the caller might be holding the lock for write */
3986 if (mmap_read_trylock(mm)) {
3987 unsigned long start = walk->next_addr;
3988 unsigned long end = mm->highest_vm_end;
3989
3990 err = walk_page_range(mm, start, end, &mm_walk_ops, walk);
3991
3992 mmap_read_unlock(mm);
3993
3994 if (walk->batched) {
3995 spin_lock_irq(&lruvec->lru_lock);
3996 reset_batch_size(lruvec, walk);
3997 spin_unlock_irq(&lruvec->lru_lock);
3998 }
3999 }
4000
4001 mem_cgroup_unlock_pages();
4002
4003 cond_resched();
4004 } while (err == -EAGAIN && walk->next_addr && !mm_is_oom_victim(mm));
4005}
4006
4007static struct lru_gen_mm_walk *alloc_mm_walk(void)
4008{
4009 if (current->reclaim_state && current->reclaim_state->mm_walk)
4010 return current->reclaim_state->mm_walk;
4011
4012 return kzalloc(sizeof(struct lru_gen_mm_walk),
4013 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4014}
4015
4016static void free_mm_walk(struct lru_gen_mm_walk *walk)
4017{
4018 if (!current->reclaim_state || !current->reclaim_state->mm_walk)
4019 kfree(walk);
4020}
4021
Yu Zhaoa1537a62022-01-27 20:32:37 -07004022static void inc_min_seq(struct lruvec *lruvec)
4023{
4024 int type;
4025 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4026
4027 VM_BUG_ON(!seq_is_valid(lruvec));
4028
4029 for (type = 0; type < ANON_AND_FILE; type++) {
4030 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4031 continue;
4032
4033 reset_ctrl_pos(lruvec, type, true);
4034 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4035 }
4036}
4037
4038static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4039{
4040 int gen, type, zone;
4041 bool success = false;
4042 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4043 DEFINE_MIN_SEQ(lruvec);
4044
4045 VM_BUG_ON(!seq_is_valid(lruvec));
4046
4047 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4048 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4049 gen = lru_gen_from_seq(min_seq[type]);
4050
4051 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4052 if (!list_empty(&lrugen->lists[gen][type][zone]))
4053 goto next;
4054 }
4055
4056 min_seq[type]++;
4057 }
4058next:
4059 ;
4060 }
4061
4062 /* see the comment on lru_gen_struct */
4063 if (can_swap) {
4064 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4065 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4066 }
4067
4068 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4069 if (min_seq[type] == lrugen->min_seq[type])
4070 continue;
4071
4072 reset_ctrl_pos(lruvec, type, true);
4073 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4074 success = true;
4075 }
4076
4077 return success;
4078}
4079
Yu Zhao5280d762022-01-27 19:23:01 -07004080static void inc_max_seq(struct lruvec *lruvec)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004081{
4082 int prev, next;
4083 int type, zone;
4084 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4085
4086 spin_lock_irq(&lruvec->lru_lock);
4087
4088 VM_BUG_ON(!seq_is_valid(lruvec));
4089
Yu Zhaoa1537a62022-01-27 20:32:37 -07004090 inc_min_seq(lruvec);
4091
4092 /*
4093 * Update the active/inactive LRU sizes for compatibility. Both sides of
4094 * the current max_seq need to be covered, since max_seq+1 can overlap
4095 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4096 * overlap, cold/hot inversion happens. This can be solved by moving
4097 * pages from min_seq to min_seq+1 but is omitted for simplicity.
4098 */
4099 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4100 next = lru_gen_from_seq(lrugen->max_seq + 1);
4101
4102 for (type = 0; type < ANON_AND_FILE; type++) {
4103 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4104 enum lru_list lru = type * LRU_INACTIVE_FILE;
4105 long delta = lrugen->nr_pages[prev][type][zone] -
4106 lrugen->nr_pages[next][type][zone];
4107
4108 if (!delta)
4109 continue;
4110
4111 __update_lru_size(lruvec, lru, zone, delta);
4112 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4113 }
4114 }
4115
4116 for (type = 0; type < ANON_AND_FILE; type++)
4117 reset_ctrl_pos(lruvec, type, false);
4118
Yu Zhaoe8507812022-01-27 20:08:50 -07004119 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004120 /* make sure preceding modifications appear */
4121 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao5280d762022-01-27 19:23:01 -07004122
Yu Zhaoa1537a62022-01-27 20:32:37 -07004123 spin_unlock_irq(&lruvec->lru_lock);
4124}
4125
Yu Zhao5280d762022-01-27 19:23:01 -07004126static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4127 struct scan_control *sc, bool can_swap, bool full_scan)
4128{
4129 bool success;
4130 struct lru_gen_mm_walk *walk;
4131 struct mm_struct *mm = NULL;
4132 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4133
4134 VM_BUG_ON(max_seq > READ_ONCE(lrugen->max_seq));
4135
4136 /*
4137 * If the hardware doesn't automatically set the accessed bit, fallback
4138 * to lru_gen_look_around(), which only clears the accessed bit in a
4139 * handful of PTEs. Spreading the work out over a period of time usually
4140 * is less efficient, but it avoids bursty page faults.
4141 */
Yu Zhao76f7f072022-01-27 19:52:09 -07004142 if (!full_scan && (!arch_has_hw_pte_young() || !get_cap(LRU_GEN_MM_WALK))) {
Yu Zhao5280d762022-01-27 19:23:01 -07004143 success = iterate_mm_list_nowalk(lruvec, max_seq);
4144 goto done;
4145 }
4146
4147 walk = alloc_mm_walk();
4148 if (!walk) {
4149 success = iterate_mm_list_nowalk(lruvec, max_seq);
4150 goto done;
4151 }
4152
4153 walk->lruvec = lruvec;
4154 walk->max_seq = max_seq;
4155 walk->can_swap = can_swap;
4156 walk->full_scan = full_scan;
4157
4158 do {
4159 success = iterate_mm_list(lruvec, walk, &mm);
4160 if (mm)
4161 walk_mm(lruvec, mm, walk);
4162
4163 cond_resched();
4164 } while (mm);
4165
4166 free_mm_walk(walk);
4167done:
4168 if (!success) {
4169 if (!current_is_kswapd() && !sc->priority)
4170 wait_event_killable(lruvec->mm_state.wait,
4171 max_seq < READ_ONCE(lrugen->max_seq));
4172
4173 return max_seq < READ_ONCE(lrugen->max_seq);
4174 }
4175
4176 VM_BUG_ON(max_seq != READ_ONCE(lrugen->max_seq));
4177
4178 inc_max_seq(lruvec);
4179 /* either this sees any waiters or they will see updated max_seq */
4180 if (wq_has_sleeper(&lruvec->mm_state.wait))
4181 wake_up_all(&lruvec->mm_state.wait);
4182
4183 wakeup_flusher_threads(WB_REASON_VMSCAN);
4184
4185 return true;
4186}
4187
Yu Zhaoa1537a62022-01-27 20:32:37 -07004188static long get_nr_evictable(struct lruvec *lruvec, unsigned long max_seq,
4189 unsigned long *min_seq, bool can_swap, bool *need_aging)
4190{
4191 int gen, type, zone;
4192 long old = 0;
4193 long young = 0;
4194 long total = 0;
4195 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4196
4197 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4198 unsigned long seq;
4199
4200 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4201 long size = 0;
4202
4203 gen = lru_gen_from_seq(seq);
4204
4205 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4206 size += READ_ONCE(lrugen->nr_pages[gen][type][zone]);
4207
4208 total += size;
4209 if (seq == max_seq)
4210 young += size;
4211 if (seq + MIN_NR_GENS == max_seq)
4212 old += size;
4213 }
4214 }
4215
4216 /*
4217 * The aging and the eviction is a typical producer-consumer model. The
4218 * aging tries to be lazy to reduce the unnecessary overhead. On the
4219 * other hand, the eviction stalls when the number of generations
4220 * reaches MIN_NR_GENS. So ideally, there should be MIN_NR_GENS+1
4221 * generations, hence the first two if's.
4222 *
4223 * In addition, it's ideal to spread pages out evenly, meaning
4224 * 1/(MIN_NR_GENS+1) of the total number of pages for each generation. A
4225 * reasonable range for this average portion would [1/MIN_NR_GENS,
4226 * 1/(MIN_NR_GENS+2)]. From the consumer's POV, the eviction only cares
4227 * about the lower bound of cold pages, i.e., 1/(MIN_NR_GENS+2), whereas
4228 * from the producer's POV, the aging only cares about the upper bound
4229 * of hot pages, i.e., 1/MIN_NR_GENS.
4230 */
4231 if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS > max_seq)
4232 *need_aging = true;
4233 else if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS < max_seq)
4234 *need_aging = false;
4235 else if (young * MIN_NR_GENS > total)
4236 *need_aging = true;
4237 else if (old * (MIN_NR_GENS + 2) < total)
4238 *need_aging = true;
4239 else
4240 *need_aging = false;
4241
4242 return total > 0 ? total : 0;
4243}
4244
Yu Zhaoe8507812022-01-27 20:08:50 -07004245static bool age_lruvec(struct lruvec *lruvec, struct scan_control *sc,
4246 unsigned long min_ttl)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004247{
4248 bool need_aging;
4249 long nr_to_scan;
4250 int swappiness = get_swappiness(lruvec, sc);
4251 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4252 DEFINE_MAX_SEQ(lruvec);
4253 DEFINE_MIN_SEQ(lruvec);
4254
Yu Zhaoe8507812022-01-27 20:08:50 -07004255 if (min_ttl) {
4256 int gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4257 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4258
4259 if (time_is_after_jiffies(birth + min_ttl))
4260 return false;
4261 }
4262
Yu Zhaoa1537a62022-01-27 20:32:37 -07004263 mem_cgroup_calculate_protection(NULL, memcg);
4264
4265 if (mem_cgroup_below_min(memcg))
Yu Zhaoe8507812022-01-27 20:08:50 -07004266 return false;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004267
4268 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, swappiness, &need_aging);
4269 if (!nr_to_scan)
Yu Zhaoe8507812022-01-27 20:08:50 -07004270 return false;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004271
4272 nr_to_scan >>= sc->priority;
4273
4274 if (!mem_cgroup_online(memcg))
4275 nr_to_scan++;
4276
4277 if (nr_to_scan && need_aging && (!mem_cgroup_below_low(memcg) || sc->memcg_low_reclaim))
Yu Zhao5280d762022-01-27 19:23:01 -07004278 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
Yu Zhaoe8507812022-01-27 20:08:50 -07004279
4280 return true;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004281}
4282
Yu Zhaoe8507812022-01-27 20:08:50 -07004283/* to protect the working set of the last N jiffies */
4284static unsigned long lru_gen_min_ttl __read_mostly;
4285
Yu Zhaoa1537a62022-01-27 20:32:37 -07004286static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4287{
4288 struct mem_cgroup *memcg;
Yu Zhaoe8507812022-01-27 20:08:50 -07004289 bool success = false;
4290 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004291
4292 VM_BUG_ON(!current_is_kswapd());
4293
Yu Zhao4d905e92022-01-27 19:59:54 -07004294 /*
4295 * To reduce the chance of going into the aging path or swapping, which
4296 * can be costly, optimistically skip them unless their corresponding
4297 * flags were cleared in the eviction path. This improves the overall
4298 * performance when multiple memcgs are available.
4299 */
4300 if (!sc->memcgs_need_aging) {
4301 sc->memcgs_need_aging = true;
4302 sc->memcgs_avoid_swapping = !sc->memcgs_need_swapping;
4303 sc->memcgs_need_swapping = true;
4304 return;
4305 }
4306
4307 sc->memcgs_need_swapping = true;
4308 sc->memcgs_avoid_swapping = true;
4309
Yu Zhao5280d762022-01-27 19:23:01 -07004310 current->reclaim_state->mm_walk = &pgdat->mm_walk;
4311
Yu Zhaoa1537a62022-01-27 20:32:37 -07004312 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4313 do {
4314 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4315
Yu Zhaoe8507812022-01-27 20:08:50 -07004316 if (age_lruvec(lruvec, sc, min_ttl))
4317 success = true;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004318
4319 cond_resched();
4320 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao5280d762022-01-27 19:23:01 -07004321
4322 current->reclaim_state->mm_walk = NULL;
Yu Zhaoe8507812022-01-27 20:08:50 -07004323
4324 /*
4325 * The main goal is to OOM kill if every generation from all memcgs is
4326 * younger than min_ttl. However, another theoretical possibility is all
4327 * memcgs are either below min or empty.
4328 */
4329 if (!success && mutex_trylock(&oom_lock)) {
4330 struct oom_control oc = {
4331 .gfp_mask = sc->gfp_mask,
4332 .order = sc->order,
4333 };
4334
4335 out_of_memory(&oc);
4336
4337 mutex_unlock(&oom_lock);
4338 }
Yu Zhaoa1537a62022-01-27 20:32:37 -07004339}
4340
Yu Zhaoafd94c92022-01-27 20:43:22 -07004341/*
4342 * This function exploits spatial locality when shrink_page_list() walks the
4343 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages.
Yu Zhao5280d762022-01-27 19:23:01 -07004344 * If the scan was done cacheline efficiently, it adds the PMD entry pointing
4345 * to the PTE table to the Bloom filter. This process is a feedback loop from
4346 * the eviction to the aging.
Yu Zhaoafd94c92022-01-27 20:43:22 -07004347 */
4348void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4349{
4350 int i;
4351 pte_t *pte;
4352 unsigned long start;
4353 unsigned long end;
4354 unsigned long addr;
4355 struct page *page;
Yu Zhao5280d762022-01-27 19:23:01 -07004356 struct lru_gen_mm_walk *walk;
4357 int young = 0;
Yu Zhaoafd94c92022-01-27 20:43:22 -07004358 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4359 struct mem_cgroup *memcg = page_memcg(pvmw->page);
4360 struct pglist_data *pgdat = page_pgdat(pvmw->page);
4361 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4362 DEFINE_MAX_SEQ(lruvec);
4363 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4364
4365 lockdep_assert_held(pvmw->ptl);
4366 VM_BUG_ON_PAGE(PageLRU(pvmw->page), pvmw->page);
4367
4368 if (spin_is_contended(pvmw->ptl))
4369 return;
4370
4371 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4372 end = pmd_addr_end(pvmw->address, pvmw->vma->vm_end);
4373
4374 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4375 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4376 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4377 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4378 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4379 else {
4380 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4381 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4382 }
4383 }
4384
4385 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4386
4387 rcu_read_lock();
4388 arch_enter_lazy_mmu_mode();
4389
4390 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4391 unsigned long pfn = pte_pfn(pte[i]);
4392
4393 VM_BUG_ON(addr < pvmw->vma->vm_start || addr >= pvmw->vma->vm_end);
4394
4395 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
4396 continue;
4397
4398 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
4399 continue;
4400
4401 if (!pte_young(pte[i]))
4402 continue;
4403
4404 VM_BUG_ON(!pfn_valid(pfn));
4405 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
4406 continue;
4407
4408 page = compound_head(pfn_to_page(pfn));
4409 if (page_to_nid(page) != pgdat->node_id)
4410 continue;
4411
4412 if (page_memcg_rcu(page) != memcg)
4413 continue;
4414
4415 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4416 continue;
4417
Yu Zhao5280d762022-01-27 19:23:01 -07004418 young++;
4419
Yu Zhaoafd94c92022-01-27 20:43:22 -07004420 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4421 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
4422 set_page_dirty(page);
4423
4424 old_gen = page_lru_gen(page);
4425 if (old_gen < 0)
4426 SetPageReferenced(page);
4427 else if (old_gen != new_gen)
4428 __set_bit(i, bitmap);
4429 }
4430
4431 arch_leave_lazy_mmu_mode();
4432 rcu_read_unlock();
4433
Yu Zhao5280d762022-01-27 19:23:01 -07004434 /* feedback from rmap walkers to page table walkers */
4435 if (suitable_to_scan(i, young))
4436 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4437
4438 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4439
4440 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhaoafd94c92022-01-27 20:43:22 -07004441 for_each_set_bit(i, bitmap, MIN_LRU_BATCH)
4442 activate_page(pte_page(pte[i]));
4443 return;
4444 }
4445
4446 /* page_update_gen() requires stable page_memcg() */
4447 if (!mem_cgroup_trylock_pages(memcg))
4448 return;
4449
Yu Zhao5280d762022-01-27 19:23:01 -07004450 if (!walk) {
4451 spin_lock_irq(&lruvec->lru_lock);
4452 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4453 }
Yu Zhaoafd94c92022-01-27 20:43:22 -07004454
4455 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4456 page = compound_head(pte_page(pte[i]));
4457 if (page_memcg_rcu(page) != memcg)
4458 continue;
4459
4460 old_gen = page_update_gen(page, new_gen);
4461 if (old_gen < 0 || old_gen == new_gen)
4462 continue;
4463
Yu Zhao5280d762022-01-27 19:23:01 -07004464 if (walk)
4465 update_batch_size(walk, page, old_gen, new_gen);
4466 else
4467 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhaoafd94c92022-01-27 20:43:22 -07004468 }
4469
Yu Zhao5280d762022-01-27 19:23:01 -07004470 if (!walk)
4471 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhaoafd94c92022-01-27 20:43:22 -07004472
4473 mem_cgroup_unlock_pages();
4474}
4475
Yu Zhaoa1537a62022-01-27 20:32:37 -07004476/******************************************************************************
4477 * the eviction
4478 ******************************************************************************/
4479
4480static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4481{
4482 bool success;
4483 int gen = page_lru_gen(page);
4484 int type = page_is_file_lru(page);
4485 int zone = page_zonenum(page);
4486 int tier = page_lru_tier(page);
4487 int delta = thp_nr_pages(page);
4488 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4489
4490 VM_BUG_ON_PAGE(gen >= MAX_NR_GENS, page);
4491
4492 if (!page_evictable(page)) {
4493 success = lru_gen_del_page(lruvec, page, true);
4494 VM_BUG_ON_PAGE(!success, page);
4495 SetPageUnevictable(page);
4496 add_page_to_lru_list(page, lruvec);
4497 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4498 return true;
4499 }
4500
4501 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4502 success = lru_gen_del_page(lruvec, page, true);
4503 VM_BUG_ON_PAGE(!success, page);
4504 SetPageSwapBacked(page);
4505 add_page_to_lru_list_tail(page, lruvec);
4506 return true;
4507 }
4508
Yu Zhaoafd94c92022-01-27 20:43:22 -07004509 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4510 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4511 return true;
4512 }
4513
Yu Zhaoa1537a62022-01-27 20:32:37 -07004514 if (tier > tier_idx) {
4515 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4516
4517 gen = page_inc_gen(lruvec, page, false);
4518 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4519
4520 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4521 lrugen->protected[hist][type][tier - 1] + delta);
4522 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4523 return true;
4524 }
4525
4526 if (PageLocked(page) || PageWriteback(page) ||
4527 (type == LRU_GEN_FILE && PageDirty(page))) {
4528 gen = page_inc_gen(lruvec, page, true);
4529 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4530 return true;
4531 }
4532
4533 return false;
4534}
4535
4536static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4537{
4538 bool success;
4539
4540 if (!sc->may_unmap && page_mapped(page))
4541 return false;
4542
4543 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4544 (PageDirty(page) || (PageAnon(page) && !PageSwapCache(page))))
4545 return false;
4546
4547 if (!get_page_unless_zero(page))
4548 return false;
4549
4550 if (!TestClearPageLRU(page)) {
4551 put_page(page);
4552 return false;
4553 }
4554
4555 success = lru_gen_del_page(lruvec, page, true);
4556 VM_BUG_ON_PAGE(!success, page);
4557
4558 return true;
4559}
4560
4561static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4562 int type, int tier, struct list_head *list)
4563{
4564 int gen, zone;
4565 enum vm_event_item item;
4566 int sorted = 0;
4567 int scanned = 0;
4568 int isolated = 0;
4569 int remaining = MAX_LRU_BATCH;
4570 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4571 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4572
4573 VM_BUG_ON(!list_empty(list));
4574
4575 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4576 return 0;
4577
4578 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4579
4580 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4581 LIST_HEAD(moved);
4582 int skipped = 0;
4583 struct list_head *head = &lrugen->lists[gen][type][zone];
4584
4585 while (!list_empty(head)) {
4586 struct page *page = lru_to_page(head);
4587 int delta = thp_nr_pages(page);
4588
4589 VM_BUG_ON_PAGE(PageTail(page), page);
4590 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4591 VM_BUG_ON_PAGE(PageActive(page), page);
4592 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4593 VM_BUG_ON_PAGE(page_zonenum(page) != zone, page);
4594
4595 prefetchw_prev_lru_page(page, head, flags);
4596
4597 scanned += delta;
4598
4599 if (sort_page(lruvec, page, tier))
4600 sorted += delta;
4601 else if (isolate_page(lruvec, page, sc)) {
4602 list_add(&page->lru, list);
4603 isolated += delta;
4604 } else {
4605 list_move(&page->lru, &moved);
4606 skipped += delta;
4607 }
4608
4609 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4610 break;
4611 }
4612
4613 if (skipped) {
4614 list_splice(&moved, head);
4615 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4616 }
4617
4618 if (!remaining || isolated >= MIN_LRU_BATCH)
4619 break;
4620 }
4621
4622 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4623 if (!cgroup_reclaim(sc)) {
4624 __count_vm_events(item, isolated);
4625 __count_vm_events(PGREFILL, sorted);
4626 }
4627 __count_memcg_events(memcg, item, isolated);
4628 __count_memcg_events(memcg, PGREFILL, sorted);
4629 __count_vm_events(PGSCAN_ANON + type, isolated);
4630
4631 /*
4632 * There might not be eligible pages due to reclaim_idx, may_unmap and
4633 * may_writepage. Check the remaining to prevent livelock if there is no
4634 * progress.
4635 */
4636 return isolated || !remaining ? scanned : 0;
4637}
4638
4639static int get_tier_idx(struct lruvec *lruvec, int type)
4640{
4641 int tier;
4642 struct ctrl_pos sp, pv;
4643
4644 /*
4645 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4646 * This value is chosen because any other tier would have at least twice
4647 * as many refaults as the first tier.
4648 */
4649 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4650 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4651 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4652 if (!positive_ctrl_err(&sp, &pv))
4653 break;
4654 }
4655
4656 return tier - 1;
4657}
4658
4659static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4660{
4661 int type, tier;
4662 struct ctrl_pos sp, pv;
4663 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4664
4665 /*
4666 * Compare the first tier of anon with that of file to determine which
4667 * type to scan. Also need to compare other tiers of the selected type
4668 * with the first tier of the other type to determine the last tier (of
4669 * the selected type) to evict.
4670 */
4671 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4672 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4673 type = positive_ctrl_err(&sp, &pv);
4674
4675 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4676 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4677 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4678 if (!positive_ctrl_err(&sp, &pv))
4679 break;
4680 }
4681
4682 *tier_idx = tier - 1;
4683
4684 return type;
4685}
4686
4687static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4688 int *type_scanned, struct list_head *list)
4689{
4690 int i;
4691 int type;
4692 int scanned;
4693 int tier = -1;
4694 DEFINE_MIN_SEQ(lruvec);
4695
4696 VM_BUG_ON(!seq_is_valid(lruvec));
4697
4698 /*
4699 * Try to make the obvious choice first. When anon and file are both
4700 * available from the same generation, interpret swappiness 1 as file
4701 * first and 200 as anon first.
4702 */
4703 if (!swappiness)
4704 type = LRU_GEN_FILE;
4705 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4706 type = LRU_GEN_ANON;
4707 else if (swappiness == 1)
4708 type = LRU_GEN_FILE;
4709 else if (swappiness == 200)
4710 type = LRU_GEN_ANON;
4711 else
4712 type = get_type_to_scan(lruvec, swappiness, &tier);
4713
4714 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4715 if (tier < 0)
4716 tier = get_tier_idx(lruvec, type);
4717
4718 scanned = scan_pages(lruvec, sc, type, tier, list);
4719 if (scanned)
4720 break;
4721
4722 type = !type;
4723 tier = -1;
4724 }
4725
4726 *type_scanned = type;
4727
4728 return scanned;
4729}
4730
Yu Zhao4d905e92022-01-27 19:59:54 -07004731static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4732 bool *swapped)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004733{
4734 int type;
4735 int scanned;
4736 int reclaimed;
4737 LIST_HEAD(list);
4738 struct page *page;
4739 enum vm_event_item item;
4740 struct reclaim_stat stat;
Yu Zhao5280d762022-01-27 19:23:01 -07004741 struct lru_gen_mm_walk *walk;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004742 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4743 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4744
4745 spin_lock_irq(&lruvec->lru_lock);
4746
4747 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4748
4749 if (try_to_inc_min_seq(lruvec, swappiness))
4750 scanned++;
4751
4752 if (get_nr_gens(lruvec, LRU_GEN_FILE) == MIN_NR_GENS)
4753 scanned = 0;
4754
4755 spin_unlock_irq(&lruvec->lru_lock);
4756
4757 if (list_empty(&list))
4758 return scanned;
4759
4760 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4761
4762 /*
4763 * To avoid livelock, don't add rejected pages back to the same lists
4764 * they were isolated from. See lru_gen_add_page().
4765 */
4766 list_for_each_entry(page, &list, lru) {
4767 ClearPageReferenced(page);
4768 ClearPageWorkingset(page);
4769
4770 if (PageReclaim(page) && (PageDirty(page) || PageWriteback(page)))
4771 ClearPageActive(page);
4772 else if (page_is_file_lru(page) || PageSwapCache(page))
4773 SetPageActive(page);
4774 }
4775
4776 spin_lock_irq(&lruvec->lru_lock);
4777
4778 move_pages_to_lru(lruvec, &list);
4779
Yu Zhao5280d762022-01-27 19:23:01 -07004780 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4781 if (walk && walk->batched)
4782 reset_batch_size(lruvec, walk);
4783
Yu Zhaoa1537a62022-01-27 20:32:37 -07004784 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4785 if (!cgroup_reclaim(sc))
4786 __count_vm_events(item, reclaimed);
4787 __count_memcg_events(memcg, item, reclaimed);
4788 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4789
4790 spin_unlock_irq(&lruvec->lru_lock);
4791
4792 mem_cgroup_uncharge_list(&list);
4793 free_unref_page_list(&list);
4794
4795 sc->nr_reclaimed += reclaimed;
4796
Yu Zhao4d905e92022-01-27 19:59:54 -07004797 if (type == LRU_GEN_ANON && swapped)
4798 *swapped = true;
4799
Yu Zhaoa1537a62022-01-27 20:32:37 -07004800 return scanned;
4801}
4802
4803static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
4804{
4805 bool need_aging;
4806 long nr_to_scan;
4807 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4808 DEFINE_MAX_SEQ(lruvec);
4809 DEFINE_MIN_SEQ(lruvec);
4810
4811 if (mem_cgroup_below_min(memcg) ||
4812 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4813 return 0;
4814
4815 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, can_swap, &need_aging);
4816 if (!nr_to_scan)
4817 return 0;
4818
4819 /* reset the priority if the target has been met */
4820 nr_to_scan >>= sc->nr_reclaimed < sc->nr_to_reclaim ? sc->priority : DEF_PRIORITY;
4821
4822 if (!mem_cgroup_online(memcg))
4823 nr_to_scan++;
4824
4825 if (!nr_to_scan)
4826 return 0;
4827
Yu Zhao4d905e92022-01-27 19:59:54 -07004828 if (!need_aging) {
4829 sc->memcgs_need_aging = false;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004830 return nr_to_scan;
Yu Zhao4d905e92022-01-27 19:59:54 -07004831 }
Yu Zhaoa1537a62022-01-27 20:32:37 -07004832
4833 /* leave the work to lru_gen_age_node() */
4834 if (current_is_kswapd())
4835 return 0;
4836
4837 /* try other memcgs before going to the aging path */
4838 if (!cgroup_reclaim(sc) && !sc->force_deactivate) {
4839 sc->skipped_deactivate = true;
4840 return 0;
4841 }
4842
Yu Zhao5280d762022-01-27 19:23:01 -07004843 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
4844 return nr_to_scan;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004845
Yu Zhao5280d762022-01-27 19:23:01 -07004846 return min_seq[LRU_GEN_FILE] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004847}
4848
4849static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4850{
4851 struct blk_plug plug;
4852 long scanned = 0;
Yu Zhao4d905e92022-01-27 19:59:54 -07004853 bool swapped = false;
4854 unsigned long reclaimed = sc->nr_reclaimed;
Yu Zhao5280d762022-01-27 19:23:01 -07004855 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004856
4857 lru_add_drain();
4858
4859 blk_start_plug(&plug);
4860
Yu Zhao5280d762022-01-27 19:23:01 -07004861 if (current_is_kswapd())
4862 current->reclaim_state->mm_walk = &pgdat->mm_walk;
4863
Yu Zhaoa1537a62022-01-27 20:32:37 -07004864 while (true) {
4865 int delta;
4866 int swappiness;
4867 long nr_to_scan;
4868
4869 if (sc->may_swap)
4870 swappiness = get_swappiness(lruvec, sc);
4871 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4872 swappiness = 1;
4873 else
4874 swappiness = 0;
4875
4876 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
4877 if (!nr_to_scan)
4878 break;
4879
Yu Zhao4d905e92022-01-27 19:59:54 -07004880 delta = evict_pages(lruvec, sc, swappiness, &swapped);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004881 if (!delta)
4882 break;
4883
Yu Zhao4d905e92022-01-27 19:59:54 -07004884 if (sc->memcgs_avoid_swapping && swappiness < 200 && swapped)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004885 break;
4886
Yu Zhao4d905e92022-01-27 19:59:54 -07004887 scanned += delta;
4888 if (scanned >= nr_to_scan) {
4889 if (!swapped && sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH)
4890 sc->memcgs_need_swapping = false;
4891 break;
4892 }
4893
Yu Zhaoa1537a62022-01-27 20:32:37 -07004894 cond_resched();
4895 }
4896
Yu Zhao5280d762022-01-27 19:23:01 -07004897 if (current_is_kswapd())
4898 current->reclaim_state->mm_walk = NULL;
4899
Yu Zhaoa1537a62022-01-27 20:32:37 -07004900 blk_finish_plug(&plug);
4901}
4902
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004903/******************************************************************************
Yu Zhao76f7f072022-01-27 19:52:09 -07004904 * state change
4905 ******************************************************************************/
4906
4907static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
4908{
4909 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4910
4911 if (lrugen->enabled) {
4912 enum lru_list lru;
4913
4914 for_each_evictable_lru(lru) {
4915 if (!list_empty(&lruvec->lists[lru]))
4916 return false;
4917 }
4918 } else {
4919 int gen, type, zone;
4920
4921 for_each_gen_type_zone(gen, type, zone) {
4922 if (!list_empty(&lrugen->lists[gen][type][zone]))
4923 return false;
4924
4925 /* unlikely but not a bug when reset_batch_size() is pending */
4926 VM_WARN_ON(lrugen->nr_pages[gen][type][zone]);
4927 }
4928 }
4929
4930 return true;
4931}
4932
4933static bool fill_evictable(struct lruvec *lruvec)
4934{
4935 enum lru_list lru;
4936 int remaining = MAX_LRU_BATCH;
4937
4938 for_each_evictable_lru(lru) {
4939 int type = is_file_lru(lru);
4940 bool active = is_active_lru(lru);
4941 struct list_head *head = &lruvec->lists[lru];
4942
4943 while (!list_empty(head)) {
4944 bool success;
4945 struct page *page = lru_to_page(head);
4946
4947 VM_BUG_ON_PAGE(PageTail(page), page);
4948 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4949 VM_BUG_ON_PAGE(PageActive(page) != active, page);
4950 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4951 VM_BUG_ON_PAGE(page_lru_gen(page) < MAX_NR_GENS, page);
4952
4953 prefetchw_prev_lru_page(page, head, flags);
4954
4955 del_page_from_lru_list(page, lruvec);
4956 success = lru_gen_add_page(lruvec, page, false);
4957 VM_BUG_ON(!success);
4958
4959 if (!--remaining)
4960 return false;
4961 }
4962 }
4963
4964 return true;
4965}
4966
4967static bool drain_evictable(struct lruvec *lruvec)
4968{
4969 int gen, type, zone;
4970 int remaining = MAX_LRU_BATCH;
4971
4972 for_each_gen_type_zone(gen, type, zone) {
4973 struct list_head *head = &lruvec->lrugen.lists[gen][type][zone];
4974
4975 while (!list_empty(head)) {
4976 bool success;
4977 struct page *page = lru_to_page(head);
4978
4979 VM_BUG_ON_PAGE(PageTail(page), page);
4980 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4981 VM_BUG_ON_PAGE(PageActive(page), page);
4982 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4983 VM_BUG_ON_PAGE(page_zonenum(page) != zone, page);
4984
4985 prefetchw_prev_lru_page(page, head, flags);
4986
4987 success = lru_gen_del_page(lruvec, page, false);
4988 VM_BUG_ON(!success);
4989 add_page_to_lru_list(page, lruvec);
4990
4991 if (!--remaining)
4992 return false;
4993 }
4994 }
4995
4996 return true;
4997}
4998
4999static void lru_gen_change_state(bool enable)
5000{
5001 static DEFINE_MUTEX(state_mutex);
5002
5003 struct mem_cgroup *memcg;
5004
5005 cgroup_lock();
5006 cpus_read_lock();
5007 get_online_mems();
5008 mutex_lock(&state_mutex);
5009
5010 if (enable == lru_gen_enabled())
5011 goto unlock;
5012
5013 if (enable)
5014 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5015 else
5016 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5017
5018 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5019 do {
5020 int nid;
5021
5022 for_each_node(nid) {
5023 struct lruvec *lruvec = get_lruvec(memcg, nid);
5024
5025 if (!lruvec)
5026 continue;
5027
5028 spin_lock_irq(&lruvec->lru_lock);
5029
5030 VM_BUG_ON(!seq_is_valid(lruvec));
5031 VM_BUG_ON(!state_is_valid(lruvec));
5032
5033 lruvec->lrugen.enabled = enable;
5034
5035 while (!(enable ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5036 spin_unlock_irq(&lruvec->lru_lock);
5037 cond_resched();
5038 spin_lock_irq(&lruvec->lru_lock);
5039 }
5040
5041 spin_unlock_irq(&lruvec->lru_lock);
5042 }
5043
5044 cond_resched();
5045 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5046unlock:
5047 mutex_unlock(&state_mutex);
5048 put_online_mems();
5049 cpus_read_unlock();
5050 cgroup_unlock();
5051}
5052
5053/******************************************************************************
5054 * sysfs interface
5055 ******************************************************************************/
5056
Yu Zhaoe8507812022-01-27 20:08:50 -07005057static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5058{
5059 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5060}
5061
5062static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5063 const char *buf, size_t len)
5064{
5065 unsigned int msecs;
5066
5067 if (kstrtouint(buf, 0, &msecs))
5068 return -EINVAL;
5069
5070 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5071
5072 return len;
5073}
5074
5075static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5076 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5077);
5078
Yu Zhao76f7f072022-01-27 19:52:09 -07005079static ssize_t show_enable(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5080{
5081 unsigned int caps = 0;
5082
5083 if (get_cap(LRU_GEN_CORE))
5084 caps |= BIT(LRU_GEN_CORE);
5085
5086 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5087 caps |= BIT(LRU_GEN_MM_WALK);
5088
5089 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
5090 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5091
5092 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5093}
5094
5095static ssize_t store_enable(struct kobject *kobj, struct kobj_attribute *attr,
5096 const char *buf, size_t len)
5097{
5098 int i;
5099 unsigned int caps;
5100
5101 if (tolower(*buf) == 'n')
5102 caps = 0;
5103 else if (tolower(*buf) == 'y')
5104 caps = -1;
5105 else if (kstrtouint(buf, 0, &caps))
5106 return -EINVAL;
5107
5108 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5109 bool enable = caps & BIT(i);
5110
5111 if (i == LRU_GEN_CORE)
5112 lru_gen_change_state(enable);
5113 else if (enable)
5114 static_branch_enable(&lru_gen_caps[i]);
5115 else
5116 static_branch_disable(&lru_gen_caps[i]);
5117 }
5118
5119 return len;
5120}
5121
5122static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5123 enabled, 0644, show_enable, store_enable
5124);
5125
5126static struct attribute *lru_gen_attrs[] = {
Yu Zhaoe8507812022-01-27 20:08:50 -07005127 &lru_gen_min_ttl_attr.attr,
Yu Zhao76f7f072022-01-27 19:52:09 -07005128 &lru_gen_enabled_attr.attr,
5129 NULL
5130};
5131
5132static struct attribute_group lru_gen_attr_group = {
5133 .name = "lru_gen",
5134 .attrs = lru_gen_attrs,
5135};
5136
5137/******************************************************************************
Yu Zhao3d18c9e2022-01-27 20:12:41 -07005138 * debugfs interface
5139 ******************************************************************************/
5140
5141static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5142{
5143 struct mem_cgroup *memcg;
5144 loff_t nr_to_skip = *pos;
5145
5146 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5147 if (!m->private)
5148 return ERR_PTR(-ENOMEM);
5149
5150 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5151 do {
5152 int nid;
5153
5154 for_each_node_state(nid, N_MEMORY) {
5155 if (!nr_to_skip--)
5156 return get_lruvec(memcg, nid);
5157 }
5158 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5159
5160 return NULL;
5161}
5162
5163static void lru_gen_seq_stop(struct seq_file *m, void *v)
5164{
5165 if (!IS_ERR_OR_NULL(v))
5166 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5167
5168 kvfree(m->private);
5169 m->private = NULL;
5170}
5171
5172static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5173{
5174 int nid = lruvec_pgdat(v)->node_id;
5175 struct mem_cgroup *memcg = lruvec_memcg(v);
5176
5177 ++*pos;
5178
5179 nid = next_memory_node(nid);
5180 if (nid == MAX_NUMNODES) {
5181 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5182 if (!memcg)
5183 return NULL;
5184
5185 nid = first_memory_node;
5186 }
5187
5188 return get_lruvec(memcg, nid);
5189}
5190
5191static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5192 unsigned long max_seq, unsigned long *min_seq,
5193 unsigned long seq)
5194{
5195 int i;
5196 int type, tier;
5197 int hist = lru_hist_from_seq(seq);
5198 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5199
5200 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5201 seq_printf(m, " %10d", tier);
5202 for (type = 0; type < ANON_AND_FILE; type++) {
5203 unsigned long n[3] = {};
5204
5205 if (seq == max_seq) {
5206 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5207 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5208
5209 seq_printf(m, " %10luR %10luT %10lu ", n[0], n[1], n[2]);
5210 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5211 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5212 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5213 if (tier)
5214 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5215
5216 seq_printf(m, " %10lur %10lue %10lup", n[0], n[1], n[2]);
5217 } else
5218 seq_puts(m, " 0 0 0 ");
5219 }
5220 seq_putc(m, '\n');
5221 }
5222
5223 seq_puts(m, " ");
5224 for (i = 0; i < NR_MM_STATS; i++) {
5225 if (seq == max_seq && NR_HIST_GENS == 1)
5226 seq_printf(m, " %10lu%c", READ_ONCE(lruvec->mm_state.stats[hist][i]),
5227 toupper(MM_STAT_CODES[i]));
5228 else if (seq != max_seq && NR_HIST_GENS > 1)
5229 seq_printf(m, " %10lu%c", READ_ONCE(lruvec->mm_state.stats[hist][i]),
5230 MM_STAT_CODES[i]);
5231 else
5232 seq_puts(m, " 0 ");
5233 }
5234 seq_putc(m, '\n');
5235}
5236
5237static int lru_gen_seq_show(struct seq_file *m, void *v)
5238{
5239 unsigned long seq;
5240 bool full = !debugfs_real_fops(m->file)->write;
5241 struct lruvec *lruvec = v;
5242 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5243 int nid = lruvec_pgdat(lruvec)->node_id;
5244 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5245 DEFINE_MAX_SEQ(lruvec);
5246 DEFINE_MIN_SEQ(lruvec);
5247
5248 if (nid == first_memory_node) {
5249 const char *path = memcg ? m->private : "";
5250
5251#ifdef CONFIG_MEMCG
5252 if (memcg)
5253 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5254#endif
5255 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5256 }
5257
5258 seq_printf(m, " node %5d\n", nid);
5259
5260 if (!full)
5261 seq = min_seq[LRU_GEN_ANON];
5262 else if (max_seq >= MAX_NR_GENS)
5263 seq = max_seq - MAX_NR_GENS + 1;
5264 else
5265 seq = 0;
5266
5267 for (; seq <= max_seq; seq++) {
5268 int type, zone;
5269 int gen = lru_gen_from_seq(seq);
5270 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5271
5272 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5273
5274 for (type = 0; type < ANON_AND_FILE; type++) {
5275 long size = 0;
5276 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5277
5278 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5279 size += READ_ONCE(lrugen->nr_pages[gen][type][zone]);
5280
5281 seq_printf(m, " %10lu%c", max(size, 0L), mark);
5282 }
5283
5284 seq_putc(m, '\n');
5285
5286 if (full)
5287 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5288 }
5289
5290 return 0;
5291}
5292
5293static const struct seq_operations lru_gen_seq_ops = {
5294 .start = lru_gen_seq_start,
5295 .stop = lru_gen_seq_stop,
5296 .next = lru_gen_seq_next,
5297 .show = lru_gen_seq_show,
5298};
5299
5300static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5301 bool can_swap, bool full_scan)
5302{
5303 DEFINE_MAX_SEQ(lruvec);
5304
5305 if (seq == max_seq)
5306 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, full_scan);
5307
5308 return seq > max_seq ? -EINVAL : 0;
5309}
5310
5311static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5312 int swappiness, unsigned long nr_to_reclaim)
5313{
5314 struct blk_plug plug;
5315 int err = -EINTR;
5316 DEFINE_MAX_SEQ(lruvec);
5317
5318 if (seq + MIN_NR_GENS > max_seq)
5319 return -EINVAL;
5320
5321 sc->nr_reclaimed = 0;
5322
5323 blk_start_plug(&plug);
5324
5325 while (!signal_pending(current)) {
5326 DEFINE_MIN_SEQ(lruvec);
5327
5328 if (seq < min_seq[!swappiness] || sc->nr_reclaimed >= nr_to_reclaim ||
5329 !evict_pages(lruvec, sc, swappiness, NULL)) {
5330 err = 0;
5331 break;
5332 }
5333
5334 cond_resched();
5335 }
5336
5337 blk_finish_plug(&plug);
5338
5339 return err;
5340}
5341
5342static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5343 struct scan_control *sc, int swappiness, unsigned long opt)
5344{
5345 struct lruvec *lruvec;
5346 int err = -EINVAL;
5347 struct mem_cgroup *memcg = NULL;
5348
5349 if (!mem_cgroup_disabled()) {
5350 rcu_read_lock();
5351 memcg = mem_cgroup_from_id(memcg_id);
5352#ifdef CONFIG_MEMCG
5353 if (memcg && !css_tryget(&memcg->css))
5354 memcg = NULL;
5355#endif
5356 rcu_read_unlock();
5357
5358 if (!memcg)
5359 goto done;
5360 }
5361 if (memcg_id != mem_cgroup_id(memcg))
5362 goto done;
5363
5364 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5365 goto done;
5366
5367 lruvec = get_lruvec(memcg, nid);
5368
5369 if (swappiness < 0)
5370 swappiness = get_swappiness(lruvec, sc);
5371 else if (swappiness > 200)
5372 goto done;
5373
5374 switch (cmd) {
5375 case '+':
5376 err = run_aging(lruvec, seq, sc, swappiness, opt);
5377 break;
5378 case '-':
5379 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5380 break;
5381 }
5382done:
5383 mem_cgroup_put(memcg);
5384
5385 return err;
5386}
5387
5388static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5389 size_t len, loff_t *pos)
5390{
5391 void *buf;
5392 char *cur, *next;
5393 unsigned int flags;
5394 int err = 0;
5395 struct scan_control sc = {
5396 .may_writepage = true,
5397 .may_unmap = true,
5398 .may_swap = true,
5399 .reclaim_idx = MAX_NR_ZONES - 1,
5400 .gfp_mask = GFP_KERNEL,
5401 };
5402
5403 buf = kvmalloc(len + 1, GFP_KERNEL);
5404 if (!buf)
5405 return -ENOMEM;
5406
5407 if (copy_from_user(buf, src, len)) {
5408 kvfree(buf);
5409 return -EFAULT;
5410 }
5411
5412 next = buf;
5413 next[len] = '\0';
5414
5415 sc.reclaim_state.mm_walk = alloc_mm_walk();
5416 if (!sc.reclaim_state.mm_walk) {
5417 kvfree(buf);
5418 return -ENOMEM;
5419 }
5420
5421 set_task_reclaim_state(current, &sc.reclaim_state);
5422 flags = memalloc_noreclaim_save();
5423
5424 while ((cur = strsep(&next, ",;\n"))) {
5425 int n;
5426 int end;
5427 char cmd;
5428 unsigned int memcg_id;
5429 unsigned int nid;
5430 unsigned long seq;
5431 unsigned int swappiness = -1;
5432 unsigned long opt = -1;
5433
5434 cur = skip_spaces(cur);
5435 if (!*cur)
5436 continue;
5437
5438 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5439 &seq, &end, &swappiness, &end, &opt, &end);
5440 if (n < 4 || cur[end]) {
5441 err = -EINVAL;
5442 break;
5443 }
5444
5445 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5446 if (err)
5447 break;
5448 }
5449
5450 memalloc_noreclaim_restore(flags);
5451 set_task_reclaim_state(current, NULL);
5452
5453 free_mm_walk(sc.reclaim_state.mm_walk);
5454 kvfree(buf);
5455
5456 return err ? : len;
5457}
5458
5459static int lru_gen_seq_open(struct inode *inode, struct file *file)
5460{
5461 return seq_open(file, &lru_gen_seq_ops);
5462}
5463
5464static const struct file_operations lru_gen_rw_fops = {
5465 .open = lru_gen_seq_open,
5466 .read = seq_read,
5467 .write = lru_gen_seq_write,
5468 .llseek = seq_lseek,
5469 .release = seq_release,
5470};
5471
5472static const struct file_operations lru_gen_ro_fops = {
5473 .open = lru_gen_seq_open,
5474 .read = seq_read,
5475 .llseek = seq_lseek,
5476 .release = seq_release,
5477};
5478
5479/******************************************************************************
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005480 * initialization
5481 ******************************************************************************/
5482
5483void lru_gen_init_lruvec(struct lruvec *lruvec)
5484{
Yu Zhaoe8507812022-01-27 20:08:50 -07005485 int i;
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005486 int gen, type, zone;
5487 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5488
5489 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhao76f7f072022-01-27 19:52:09 -07005490 lrugen->enabled = lru_gen_enabled();
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005491
Yu Zhaoe8507812022-01-27 20:08:50 -07005492 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5493 lrugen->timestamps[i] = jiffies;
5494
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005495 for_each_gen_type_zone(gen, type, zone)
5496 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao5280d762022-01-27 19:23:01 -07005497
5498 lruvec->mm_state.seq = MIN_NR_GENS;
5499 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005500}
5501
5502#ifdef CONFIG_MEMCG
5503void lru_gen_init_memcg(struct mem_cgroup *memcg)
5504{
Yu Zhao5280d762022-01-27 19:23:01 -07005505 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5506 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005507}
5508
5509void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5510{
Yu Zhao5280d762022-01-27 19:23:01 -07005511 int i;
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005512 int nid;
5513
5514 for_each_node(nid) {
5515 struct lruvec *lruvec = get_lruvec(memcg, nid);
5516
5517 VM_BUG_ON(memchr_inv(lruvec->lrugen.nr_pages, 0,
5518 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao5280d762022-01-27 19:23:01 -07005519
5520 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5521 bitmap_free(lruvec->mm_state.filters[i]);
5522 lruvec->mm_state.filters[i] = NULL;
5523 }
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005524 }
5525}
5526#endif
5527
5528static int __init init_lru_gen(void)
5529{
5530 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5531 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
Yu Zhao5280d762022-01-27 19:23:01 -07005532 BUILD_BUG_ON(sizeof(MM_STAT_CODES) != NR_MM_STATS + 1);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005533
Yu Zhao76f7f072022-01-27 19:52:09 -07005534 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5535 pr_err("lru_gen: failed to create sysfs group\n");
5536
Yu Zhao3d18c9e2022-01-27 20:12:41 -07005537 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5538 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5539
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005540 return 0;
5541};
5542late_initcall(init_lru_gen);
5543
Yu Zhaoa1537a62022-01-27 20:32:37 -07005544#else
5545
5546static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5547{
5548}
5549
5550static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5551{
5552}
5553
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005554#endif /* CONFIG_LRU_GEN */
5555
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005556static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005557{
5558 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005559 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005560 unsigned long nr_to_scan;
5561 enum lru_list lru;
5562 unsigned long nr_reclaimed = 0;
5563 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5564 struct blk_plug plug;
Mel Gorman1a501902014-06-04 16:10:49 -07005565 bool scan_adjusted;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005566
Yu Zhaoa1537a62022-01-27 20:32:37 -07005567 if (lru_gen_enabled()) {
5568 lru_gen_shrink_lruvec(lruvec, sc);
5569 return;
5570 }
5571
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005572 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005573
Mel Gormane82e0562013-07-03 15:01:44 -07005574 /* Record the original scan target for proportional adjustments later */
5575 memcpy(targets, nr, sizeof(nr));
5576
Mel Gorman1a501902014-06-04 16:10:49 -07005577 /*
5578 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5579 * event that can occur when there is little memory pressure e.g.
5580 * multiple streaming readers/writers. Hence, we do not abort scanning
5581 * when the requested number of pages are reclaimed when scanning at
5582 * DEF_PRIORITY on the assumption that the fact we are direct
5583 * reclaiming implies that kswapd is not keeping up and it is best to
5584 * do a batch of work at once. For memcg reclaim one check is made to
5585 * abort proportional reclaim if either the file or anon lru has already
5586 * dropped to zero at the first pass.
5587 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005588 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
Mel Gorman1a501902014-06-04 16:10:49 -07005589 sc->priority == DEF_PRIORITY);
5590
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005591 blk_start_plug(&plug);
5592 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5593 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005594 unsigned long nr_anon, nr_file, percentage;
5595 unsigned long nr_scanned;
5596
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005597 for_each_evictable_lru(lru) {
5598 if (nr[lru]) {
5599 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5600 nr[lru] -= nr_to_scan;
5601
5602 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005603 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005604 }
5605 }
Mel Gormane82e0562013-07-03 15:01:44 -07005606
Michal Hockobd041732016-12-02 17:26:48 -08005607 cond_resched();
5608
Mel Gormane82e0562013-07-03 15:01:44 -07005609 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
5610 continue;
5611
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005612 /*
Mel Gormane82e0562013-07-03 15:01:44 -07005613 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07005614 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07005615 * proportionally what was requested by get_scan_count(). We
5616 * stop reclaiming one LRU and reduce the amount scanning
5617 * proportional to the original scan target.
5618 */
5619 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5620 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5621
Mel Gorman1a501902014-06-04 16:10:49 -07005622 /*
5623 * It's just vindictive to attack the larger once the smaller
5624 * has gone to zero. And given the way we stop scanning the
5625 * smaller below, this makes sure that we only make one nudge
5626 * towards proportionality once we've got nr_to_reclaim.
5627 */
5628 if (!nr_file || !nr_anon)
5629 break;
5630
Mel Gormane82e0562013-07-03 15:01:44 -07005631 if (nr_file > nr_anon) {
5632 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5633 targets[LRU_ACTIVE_ANON] + 1;
5634 lru = LRU_BASE;
5635 percentage = nr_anon * 100 / scan_target;
5636 } else {
5637 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5638 targets[LRU_ACTIVE_FILE] + 1;
5639 lru = LRU_FILE;
5640 percentage = nr_file * 100 / scan_target;
5641 }
5642
5643 /* Stop scanning the smaller of the LRU */
5644 nr[lru] = 0;
5645 nr[lru + LRU_ACTIVE] = 0;
5646
5647 /*
5648 * Recalculate the other LRU scan count based on its original
5649 * scan target and the percentage scanning already complete
5650 */
5651 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5652 nr_scanned = targets[lru] - nr[lru];
5653 nr[lru] = targets[lru] * (100 - percentage) / 100;
5654 nr[lru] -= min(nr[lru], nr_scanned);
5655
5656 lru += LRU_ACTIVE;
5657 nr_scanned = targets[lru] - nr[lru];
5658 nr[lru] = targets[lru] * (100 - percentage) / 100;
5659 nr[lru] -= min(nr[lru], nr_scanned);
5660
5661 scan_adjusted = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005662 }
5663 blk_finish_plug(&plug);
5664 sc->nr_reclaimed += nr_reclaimed;
5665
5666 /*
5667 * Even if we did not try to evict anon pages at all, we want to
5668 * rebalance the anon lru active/inactive ratio.
5669 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005670 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5671 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005672 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5673 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005674}
5675
Mel Gorman23b9da52012-05-29 15:06:20 -07005676/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005677static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005678{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005679 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005680 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005681 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005682 return true;
5683
5684 return false;
5685}
5686
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005687/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005688 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5689 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5690 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005691 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005692 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005693 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005694static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005695 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005696 struct scan_control *sc)
5697{
5698 unsigned long pages_for_compaction;
5699 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005700 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005701
5702 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005703 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005704 return false;
5705
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005706 /*
5707 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5708 * number of pages that were scanned. This will return to the caller
5709 * with the risk reclaim/compaction and the resulting allocation attempt
5710 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5711 * allocations through requiring that the full LRU list has been scanned
5712 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5713 * scan, but that approximation was wrong, and there were corner cases
5714 * where always a non-zero amount of pages were scanned.
5715 */
5716 if (!nr_reclaimed)
5717 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005718
Mel Gorman3e7d3442011-01-13 15:45:56 -08005719 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005720 for (z = 0; z <= sc->reclaim_idx; z++) {
5721 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005722 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005723 continue;
5724
5725 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005726 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005727 case COMPACT_CONTINUE:
5728 return false;
5729 default:
5730 /* check next zone */
5731 ;
5732 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005733 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005734
5735 /*
5736 * If we have not reclaimed enough pages for compaction and the
5737 * inactive lists are large enough, continue reclaiming
5738 */
5739 pages_for_compaction = compact_gap(sc->order);
5740 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005741 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005742 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5743
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005744 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005745}
5746
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005747static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005748{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005749 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005750 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005751
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005752 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005753 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005754 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005755 unsigned long reclaimed;
5756 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005757 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08005758
Xunlei Pange3336ca2020-09-04 16:35:27 -07005759 /*
5760 * This loop can become CPU-bound when target memcgs
5761 * aren't eligible for reclaim - either because they
5762 * don't have any reclaimable pages, or because their
5763 * memory is explicitly protected. Avoid soft lockups.
5764 */
5765 cond_resched();
5766
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005767 trace_android_vh_shrink_node_memcgs(memcg, &skip);
5768 if (skip)
5769 continue;
5770
Chris Down45c7f7e2020-08-06 23:22:05 -07005771 mem_cgroup_calculate_protection(target_memcg, memcg);
5772
5773 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005774 /*
5775 * Hard protection.
5776 * If there is no reclaimable memory, OOM.
5777 */
5778 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005779 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005780 /*
5781 * Soft protection.
5782 * Respect the protection only as long as
5783 * there is an unprotected supply
5784 * of reclaimable memory from other cgroups.
5785 */
5786 if (!sc->memcg_low_reclaim) {
5787 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005788 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005789 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005790 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005791 }
5792
Johannes Weinerd2af3392019-11-30 17:55:43 -08005793 reclaimed = sc->nr_reclaimed;
5794 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005795
5796 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005797
Johannes Weinerd2af3392019-11-30 17:55:43 -08005798 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5799 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005800
Johannes Weinerd2af3392019-11-30 17:55:43 -08005801 /* Record the group's reclaim efficiency */
5802 vmpressure(sc->gfp_mask, memcg, false,
5803 sc->nr_scanned - scanned,
5804 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005805
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005806 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5807}
5808
Liu Song6c9e09072020-01-30 22:14:08 -08005809static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005810{
5811 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005812 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005813 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005814 bool reclaimable = false;
5815
Johannes Weiner1b051172019-11-30 17:55:52 -08005816 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5817
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005818again:
5819 memset(&sc->nr, 0, sizeof(sc->nr));
5820
5821 nr_reclaimed = sc->nr_reclaimed;
5822 nr_scanned = sc->nr_scanned;
5823
Yu Zhao3eb07702020-09-27 20:49:08 -06005824 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005825
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005826 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005827
Johannes Weinerd2af3392019-11-30 17:55:43 -08005828 if (reclaim_state) {
5829 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5830 reclaim_state->reclaimed_slab = 0;
5831 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005832
Johannes Weinerd2af3392019-11-30 17:55:43 -08005833 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005834 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005835 sc->nr_scanned - nr_scanned,
5836 sc->nr_reclaimed - nr_reclaimed);
5837
5838 if (sc->nr_reclaimed - nr_reclaimed)
5839 reclaimable = true;
5840
5841 if (current_is_kswapd()) {
5842 /*
5843 * If reclaim is isolating dirty pages under writeback,
5844 * it implies that the long-lived page allocation rate
5845 * is exceeding the page laundering rate. Either the
5846 * global limits are not being effective at throttling
5847 * processes due to the page distribution throughout
5848 * zones or there is heavy usage of a slow backing
5849 * device. The only option is to throttle from reclaim
5850 * context which is not ideal as there is no guarantee
5851 * the dirtying process is throttled in the same way
5852 * balance_dirty_pages() manages.
5853 *
5854 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5855 * count the number of pages under pages flagged for
5856 * immediate reclaim and stall if any are encountered
5857 * in the nr_immediate check below.
5858 */
5859 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5860 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005861
Johannes Weinerd2af3392019-11-30 17:55:43 -08005862 /* Allow kswapd to start writing pages during reclaim.*/
5863 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5864 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005865
5866 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005867 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005868 * reclaim and under writeback (nr_immediate), it
5869 * implies that pages are cycling through the LRU
5870 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005871 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005872 if (sc->nr.immediate)
5873 congestion_wait(BLK_RW_ASYNC, HZ/10);
5874 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005875
Johannes Weinerd2af3392019-11-30 17:55:43 -08005876 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005877 * Tag a node/memcg as congested if all the dirty pages
5878 * scanned were backed by a congested BDI and
5879 * wait_iff_congested will stall.
5880 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005881 * Legacy memcg will stall in page writeback so avoid forcibly
5882 * stalling in wait_iff_congested().
5883 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005884 if ((current_is_kswapd() ||
5885 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005886 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005887 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005888
5889 /*
5890 * Stall direct reclaim for IO completions if underlying BDIs
5891 * and node is congested. Allow kswapd to continue until it
5892 * starts encountering unqueued dirty pages or cycling through
5893 * the LRU too quickly.
5894 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005895 if (!current_is_kswapd() && current_may_throttle() &&
5896 !sc->hibernation_mode &&
5897 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005898 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5899
5900 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5901 sc))
5902 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005903
Johannes Weinerc73322d2017-05-03 14:51:51 -07005904 /*
5905 * Kswapd gives up on balancing particular nodes after too
5906 * many failures to reclaim anything from them and goes to
5907 * sleep. On reclaim progress, reset the failure counter. A
5908 * successful direct reclaim run will revive a dormant kswapd.
5909 */
5910 if (reclaimable)
5911 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005912}
5913
Vlastimil Babka53853e22014-10-09 15:27:02 -07005914/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005915 * Returns true if compaction should go ahead for a costly-order request, or
5916 * the allocation would already succeed without compaction. Return false if we
5917 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07005918 */
Mel Gorman4f588332016-07-28 15:46:38 -07005919static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005920{
Mel Gorman31483b62016-07-28 15:45:46 -07005921 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005922 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005923
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005924 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
5925 if (suitable == COMPACT_SUCCESS)
5926 /* Allocation should succeed already. Don't reclaim. */
5927 return true;
5928 if (suitable == COMPACT_SKIPPED)
5929 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005930 return false;
5931
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005932 /*
5933 * Compaction is already possible, but it takes time to run and there
5934 * are potentially other callers using the pages just freed. So proceed
5935 * with reclaim to make a buffer of free pages available to give
5936 * compaction a reasonable chance of completing and allocating the page.
5937 * Note that we won't actually reclaim the whole buffer in one attempt
5938 * as the target watermark in should_continue_reclaim() is lower. But if
5939 * we are already above the high+gap watermark, don't reclaim at all.
5940 */
5941 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
5942
5943 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005944}
5945
Linus Torvalds1da177e2005-04-16 15:20:36 -07005946/*
5947 * This is the direct reclaim path, for page-allocating processes. We only
5948 * try to reclaim pages from zones which will satisfy the caller's allocation
5949 * request.
5950 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07005951 * If a zone is deemed to be full of pinned pages then just give it a light
5952 * scan then give up on it.
5953 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07005954static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005955{
Mel Gormandd1a2392008-04-28 02:12:17 -07005956 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07005957 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07005958 unsigned long nr_soft_reclaimed;
5959 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07005960 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07005961 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005962
Mel Gormancc715d92012-03-21 16:34:00 -07005963 /*
5964 * If the number of buffer_heads in the machine exceeds the maximum
5965 * allowed level, force direct reclaim to scan the highmem zone as
5966 * highmem pages could be pinning lowmem pages storing buffer_heads
5967 */
Weijie Yang619d0d762014-04-07 15:36:59 -07005968 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07005969 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07005970 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07005971 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07005972 }
Mel Gormancc715d92012-03-21 16:34:00 -07005973
Mel Gormand4debc62010-08-09 17:19:29 -07005974 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07005975 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07005976 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005977 * Take care memory controller reclaiming has small influence
5978 * to global LRU.
5979 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005980 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04005981 if (!cpuset_zone_allowed(zone,
5982 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005983 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005984
Johannes Weiner0b064962014-08-06 16:06:12 -07005985 /*
5986 * If we already have plenty of memory free for
5987 * compaction in this zone, don't free any more.
5988 * Even though compaction is invoked for any
5989 * non-zero order, only frequent costly order
5990 * reclamation is disruptive enough to become a
5991 * noticeable problem, like transparent huge
5992 * page allocations.
5993 */
5994 if (IS_ENABLED(CONFIG_COMPACTION) &&
5995 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07005996 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07005997 sc->compaction_ready = true;
5998 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07005999 }
Johannes Weiner0b064962014-08-06 16:06:12 -07006000
Andrew Morton0608f432013-09-24 15:27:41 -07006001 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07006002 * Shrink each node in the zonelist once. If the
6003 * zonelist is ordered by zone (not the default) then a
6004 * node may be shrunk multiple times but in that case
6005 * the user prefers lower zones being preserved.
6006 */
6007 if (zone->zone_pgdat == last_pgdat)
6008 continue;
6009
6010 /*
Andrew Morton0608f432013-09-24 15:27:41 -07006011 * This steals pages from memory cgroups over softlimit
6012 * and returns the number of reclaimed pages and
6013 * scanned pages. This works for global memory pressure
6014 * and balancing, not for a memcg's limit.
6015 */
6016 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006017 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006018 sc->order, sc->gfp_mask,
6019 &nr_soft_scanned);
6020 sc->nr_reclaimed += nr_soft_reclaimed;
6021 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006022 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006023 }
Nick Piggin408d8542006-09-25 23:31:27 -07006024
Mel Gorman79dafcd2016-07-28 15:45:53 -07006025 /* See comment about same check for global reclaim above */
6026 if (zone->zone_pgdat == last_pgdat)
6027 continue;
6028 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006029 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006030 }
Mel Gormane0c23272011-10-31 17:09:33 -07006031
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006032 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006033 * Restore to original mask to avoid the impact on the caller if we
6034 * promoted it to __GFP_HIGHMEM.
6035 */
6036 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006037}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006038
Johannes Weinerb9107182019-11-30 17:55:59 -08006039static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006040{
Johannes Weinerb9107182019-11-30 17:55:59 -08006041 struct lruvec *target_lruvec;
6042 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006043
Yu Zhaoa1537a62022-01-27 20:32:37 -07006044 if (lru_gen_enabled())
6045 return;
6046
Johannes Weinerb9107182019-11-30 17:55:59 -08006047 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006048 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6049 target_lruvec->refaults[0] = refaults;
6050 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6051 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006052}
6053
Linus Torvalds1da177e2005-04-16 15:20:36 -07006054/*
6055 * This is the main entry point to direct page reclaim.
6056 *
6057 * If a full scan of the inactive list fails to free enough memory then we
6058 * are "out of memory" and something needs to be killed.
6059 *
6060 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6061 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006062 * caller can't do much about. We kick the writeback threads and take explicit
6063 * naps in the hope that some of these pages can be written. But if the
6064 * allocating task holds filesystem locks which prevent writeout this might not
6065 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006066 *
6067 * returns: 0, if no pages reclaimed
6068 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006069 */
Mel Gormandac1d272008-04-28 02:12:12 -07006070static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006071 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006072{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006073 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006074 pg_data_t *last_pgdat;
6075 struct zoneref *z;
6076 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006077retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006078 delayacct_freepages_start();
6079
Johannes Weinerb5ead352019-11-30 17:55:40 -08006080 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006081 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006082
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006083 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006084 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6085 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006086 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006087 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006088
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006089 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006090 break;
6091
6092 if (sc->compaction_ready)
6093 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006094
6095 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006096 * If we're getting trouble reclaiming, start doing
6097 * writepage even in laptop mode.
6098 */
6099 if (sc->priority < DEF_PRIORITY - 2)
6100 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006101 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006102
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006103 last_pgdat = NULL;
6104 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6105 sc->nodemask) {
6106 if (zone->zone_pgdat == last_pgdat)
6107 continue;
6108 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006109
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006110 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006111
6112 if (cgroup_reclaim(sc)) {
6113 struct lruvec *lruvec;
6114
6115 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6116 zone->zone_pgdat);
6117 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6118 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006119 }
6120
Keika Kobayashi873b4772008-07-25 01:48:52 -07006121 delayacct_freepages_end();
6122
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006123 if (sc->nr_reclaimed)
6124 return sc->nr_reclaimed;
6125
Mel Gorman0cee34f2012-01-12 17:19:49 -08006126 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006127 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006128 return 1;
6129
Johannes Weinerb91ac372019-11-30 17:56:02 -08006130 /*
6131 * We make inactive:active ratio decisions based on the node's
6132 * composition of memory, but a restrictive reclaim_idx or a
6133 * memory.low cgroup setting can exempt large amounts of
6134 * memory from reclaim. Neither of which are very common, so
6135 * instead of doing costly eligibility calculations of the
6136 * entire cgroup subtree up front, we assume the estimates are
6137 * good, and retry with forcible deactivation if that fails.
6138 */
6139 if (sc->skipped_deactivate) {
6140 sc->priority = initial_priority;
6141 sc->force_deactivate = 1;
6142 sc->skipped_deactivate = 0;
6143 goto retry;
6144 }
6145
Johannes Weiner241994ed2015-02-11 15:26:06 -08006146 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006147 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006148 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006149 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006150 sc->memcg_low_reclaim = 1;
6151 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006152 goto retry;
6153 }
6154
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006155 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006156}
6157
Johannes Weinerc73322d2017-05-03 14:51:51 -07006158static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006159{
6160 struct zone *zone;
6161 unsigned long pfmemalloc_reserve = 0;
6162 unsigned long free_pages = 0;
6163 int i;
6164 bool wmark_ok;
6165
Johannes Weinerc73322d2017-05-03 14:51:51 -07006166 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6167 return true;
6168
Mel Gorman55150612012-07-31 16:44:35 -07006169 for (i = 0; i <= ZONE_NORMAL; i++) {
6170 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006171 if (!managed_zone(zone))
6172 continue;
6173
6174 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006175 continue;
6176
Mel Gorman55150612012-07-31 16:44:35 -07006177 pfmemalloc_reserve += min_wmark_pages(zone);
6178 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6179 }
6180
Mel Gorman675becc2014-06-04 16:07:35 -07006181 /* If there are no reserves (unexpected config) then do not throttle */
6182 if (!pfmemalloc_reserve)
6183 return true;
6184
Mel Gorman55150612012-07-31 16:44:35 -07006185 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6186
6187 /* kswapd must be awake if processes are being throttled */
6188 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006189 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6190 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006191
Mel Gorman55150612012-07-31 16:44:35 -07006192 wake_up_interruptible(&pgdat->kswapd_wait);
6193 }
6194
6195 return wmark_ok;
6196}
6197
6198/*
6199 * Throttle direct reclaimers if backing storage is backed by the network
6200 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6201 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006202 * when the low watermark is reached.
6203 *
6204 * Returns true if a fatal signal was delivered during throttling. If this
6205 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006206 */
Mel Gorman50694c22012-11-26 16:29:48 -08006207static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006208 nodemask_t *nodemask)
6209{
Mel Gorman675becc2014-06-04 16:07:35 -07006210 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006211 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006212 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006213
6214 /*
6215 * Kernel threads should not be throttled as they may be indirectly
6216 * responsible for cleaning pages necessary for reclaim to make forward
6217 * progress. kjournald for example may enter direct reclaim while
6218 * committing a transaction where throttling it could forcing other
6219 * processes to block on log_wait_commit().
6220 */
6221 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006222 goto out;
6223
6224 /*
6225 * If a fatal signal is pending, this process should not throttle.
6226 * It should return quickly so it can exit and free its memory
6227 */
6228 if (fatal_signal_pending(current))
6229 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006230
Mel Gorman675becc2014-06-04 16:07:35 -07006231 /*
6232 * Check if the pfmemalloc reserves are ok by finding the first node
6233 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6234 * GFP_KERNEL will be required for allocating network buffers when
6235 * swapping over the network so ZONE_HIGHMEM is unusable.
6236 *
6237 * Throttling is based on the first usable node and throttled processes
6238 * wait on a queue until kswapd makes progress and wakes them. There
6239 * is an affinity then between processes waking up and where reclaim
6240 * progress has been made assuming the process wakes on the same node.
6241 * More importantly, processes running on remote nodes will not compete
6242 * for remote pfmemalloc reserves and processes on different nodes
6243 * should make reasonable progress.
6244 */
6245 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006246 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006247 if (zone_idx(zone) > ZONE_NORMAL)
6248 continue;
6249
6250 /* Throttle based on the first usable node */
6251 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006252 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006253 goto out;
6254 break;
6255 }
6256
6257 /* If no zone was usable by the allocation flags then do not throttle */
6258 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006259 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006260
Mel Gorman68243e72012-07-31 16:44:39 -07006261 /* Account for the throttling */
6262 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6263
Mel Gorman55150612012-07-31 16:44:35 -07006264 /*
6265 * If the caller cannot enter the filesystem, it's possible that it
6266 * is due to the caller holding an FS lock or performing a journal
6267 * transaction in the case of a filesystem like ext[3|4]. In this case,
6268 * it is not safe to block on pfmemalloc_wait as kswapd could be
6269 * blocked waiting on the same lock. Instead, throttle for up to a
6270 * second before continuing.
6271 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006272 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006273 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006274 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006275 else
6276 /* Throttle until kswapd wakes the process */
6277 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6278 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006279
Mel Gorman50694c22012-11-26 16:29:48 -08006280 if (fatal_signal_pending(current))
6281 return true;
6282
6283out:
6284 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006285}
6286
Mel Gormandac1d272008-04-28 02:12:12 -07006287unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006288 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006289{
Mel Gorman33906bc2010-08-09 17:19:16 -07006290 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006291 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006292 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006293 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006294 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006295 .order = order,
6296 .nodemask = nodemask,
6297 .priority = DEF_PRIORITY,
6298 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006299 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006300 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006301 };
6302
Mel Gorman55150612012-07-31 16:44:35 -07006303 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006304 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6305 * Confirm they are large enough for max values.
6306 */
6307 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6308 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6309 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6310
6311 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006312 * Do not enter reclaim if fatal signal was delivered while throttled.
6313 * 1 is returned so that the page allocator does not OOM kill at this
6314 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006315 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006316 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006317 return 1;
6318
Andrew Morton1732d2b012019-07-16 16:26:15 -07006319 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006320 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006321
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006322 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006323
6324 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006325 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006326
6327 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006328}
6329
Andrew Mortonc255a452012-07-31 16:43:02 -07006330#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006331
Michal Hockod2e5fb92019-08-30 16:04:50 -07006332/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006333unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006334 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006335 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006336 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006337{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006338 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006339 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006340 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006341 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006342 .may_writepage = !laptop_mode,
6343 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006344 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006345 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006346 };
Ying Han0ae5e892011-05-26 16:25:25 -07006347
Michal Hockod2e5fb92019-08-30 16:04:50 -07006348 WARN_ON_ONCE(!current->reclaim_state);
6349
Balbir Singh4e416952009-09-23 15:56:39 -07006350 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6351 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006352
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006353 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006354 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006355
Balbir Singh4e416952009-09-23 15:56:39 -07006356 /*
6357 * NOTE: Although we can get the priority field, using it
6358 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006359 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006360 * will pick up pages from other mem cgroup's as well. We hack
6361 * the priority and make it zero.
6362 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006363 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006364
6365 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6366
Ying Han0ae5e892011-05-26 16:25:25 -07006367 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006368
Balbir Singh4e416952009-09-23 15:56:39 -07006369 return sc.nr_reclaimed;
6370}
6371
Johannes Weiner72835c82012-01-12 17:18:32 -08006372unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006373 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006374 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006375 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08006376{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006377 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006378 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006379 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006380 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006381 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006382 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006383 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006384 .target_mem_cgroup = memcg,
6385 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006386 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006387 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006388 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07006389 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006390 /*
6391 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6392 * equal pressure on all the nodes. This is based on the assumption that
6393 * the reclaim does not bail out early.
6394 */
6395 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006396
Andrew Morton1732d2b012019-07-16 16:26:15 -07006397 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006398 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006399 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006400
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006401 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006402
Vlastimil Babka499118e2017-05-08 15:59:50 -07006403 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006404 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006405 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006406
6407 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006408}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006409EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006410#endif
6411
Mel Gorman1d82de62016-07-28 15:45:43 -07006412static void age_active_anon(struct pglist_data *pgdat,
Mel Gormanef8f2322016-07-28 15:46:05 -07006413 struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006414{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006415 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006416 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006417
Yu Zhaoa1537a62022-01-27 20:32:37 -07006418 if (lru_gen_enabled()) {
6419 lru_gen_age_node(pgdat, sc);
6420 return;
6421 }
6422
Dave Hansen2f368a92021-09-02 14:59:23 -07006423 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006424 return;
6425
Johannes Weinerb91ac372019-11-30 17:56:02 -08006426 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6427 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6428 return;
6429
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006430 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6431 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006432 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6433 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6434 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006435 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6436 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006437}
6438
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006439static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006440{
6441 int i;
6442 struct zone *zone;
6443
6444 /*
6445 * Check for watermark boosts top-down as the higher zones
6446 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006447 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006448 * start prematurely when there is no boosting and a lower
6449 * zone is balanced.
6450 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006451 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006452 zone = pgdat->node_zones + i;
6453 if (!managed_zone(zone))
6454 continue;
6455
6456 if (zone->watermark_boost)
6457 return true;
6458 }
6459
6460 return false;
6461}
6462
Mel Gormane716f2e2017-05-03 14:53:45 -07006463/*
6464 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006465 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006466 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006467static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006468{
Mel Gormane716f2e2017-05-03 14:53:45 -07006469 int i;
6470 unsigned long mark = -1;
6471 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006472
Mel Gorman1c308442018-12-28 00:35:52 -08006473 /*
6474 * Check watermarks bottom-up as lower zones are more likely to
6475 * meet watermarks.
6476 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006477 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006478 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006479
Mel Gormane716f2e2017-05-03 14:53:45 -07006480 if (!managed_zone(zone))
6481 continue;
6482
6483 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006484 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006485 return true;
6486 }
6487
6488 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006489 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006490 * need balancing by definition. This can happen if a zone-restricted
6491 * allocation tries to wake a remote kswapd.
6492 */
6493 if (mark == -1)
6494 return true;
6495
6496 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006497}
6498
Mel Gorman631b6e02017-05-03 14:53:41 -07006499/* Clear pgdat state for congested, dirty or under writeback. */
6500static void clear_pgdat_congested(pg_data_t *pgdat)
6501{
Johannes Weiner1b051172019-11-30 17:55:52 -08006502 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6503
6504 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006505 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6506 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6507}
6508
Mel Gorman1741c872011-01-13 15:46:21 -08006509/*
Mel Gorman55150612012-07-31 16:44:35 -07006510 * Prepare kswapd for sleeping. This verifies that there are no processes
6511 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6512 *
6513 * Returns true if kswapd is ready to sleep
6514 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006515static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6516 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006517{
Mel Gorman55150612012-07-31 16:44:35 -07006518 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006519 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006520 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006521 * race between when kswapd checks the watermarks and a process gets
6522 * throttled. There is also a potential race if processes get
6523 * throttled, kswapd wakes, a large process exits thereby balancing the
6524 * zones, which causes kswapd to exit balance_pgdat() before reaching
6525 * the wake up checks. If kswapd is going to sleep, no process should
6526 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6527 * the wake up is premature, processes will wake kswapd and get
6528 * throttled again. The difference from wake ups in balance_pgdat() is
6529 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006530 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006531 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6532 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006533
Johannes Weinerc73322d2017-05-03 14:51:51 -07006534 /* Hopeless node, leave it to direct reclaim */
6535 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6536 return true;
6537
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006538 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006539 clear_pgdat_congested(pgdat);
6540 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006541 }
6542
Shantanu Goel333b0a42017-05-03 14:53:38 -07006543 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006544}
6545
Linus Torvalds1da177e2005-04-16 15:20:36 -07006546/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006547 * kswapd shrinks a node of pages that are at or below the highest usable
6548 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006549 *
6550 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006551 * reclaim or if the lack of progress was due to pages under writeback.
6552 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006553 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006554static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006555 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006556{
Mel Gorman1d82de62016-07-28 15:45:43 -07006557 struct zone *zone;
6558 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006559
Mel Gorman1d82de62016-07-28 15:45:43 -07006560 /* Reclaim a number of pages proportional to the number of zones */
6561 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006562 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006563 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006564 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006565 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006566
Mel Gorman1d82de62016-07-28 15:45:43 -07006567 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006568 }
6569
Mel Gorman1d82de62016-07-28 15:45:43 -07006570 /*
6571 * Historically care was taken to put equal pressure on all zones but
6572 * now pressure is applied based on node LRU order.
6573 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006574 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006575
6576 /*
6577 * Fragmentation may mean that the system cannot be rebalanced for
6578 * high-order allocations. If twice the allocation size has been
6579 * reclaimed then recheck watermarks only at order-0 to prevent
6580 * excessive reclaim. Assume that a process requested a high-order
6581 * can direct reclaim/compact.
6582 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006583 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006584 sc->order = 0;
6585
Mel Gormanb8e83b92013-07-03 15:01:45 -07006586 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006587}
6588
Mel Gormanc49c2c42021-06-28 19:42:21 -07006589/* Page allocator PCP high watermark is lowered if reclaim is active. */
6590static inline void
6591update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6592{
6593 int i;
6594 struct zone *zone;
6595
6596 for (i = 0; i <= highest_zoneidx; i++) {
6597 zone = pgdat->node_zones + i;
6598
6599 if (!managed_zone(zone))
6600 continue;
6601
6602 if (active)
6603 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6604 else
6605 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6606 }
6607}
6608
6609static inline void
6610set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6611{
6612 update_reclaim_active(pgdat, highest_zoneidx, true);
6613}
6614
6615static inline void
6616clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6617{
6618 update_reclaim_active(pgdat, highest_zoneidx, false);
6619}
6620
Mel Gorman75485362013-07-03 15:01:42 -07006621/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006622 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6623 * that are eligible for use by the caller until at least one zone is
6624 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006625 *
Mel Gorman1d82de62016-07-28 15:45:43 -07006626 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006627 *
6628 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07006629 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08006630 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07006631 * or lower is eligible for reclaim until at least one usable zone is
6632 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006633 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006634static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006635{
Linus Torvalds1da177e2005-04-16 15:20:36 -07006636 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07006637 unsigned long nr_soft_reclaimed;
6638 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07006639 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08006640 unsigned long nr_boost_reclaim;
6641 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6642 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07006643 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08006644 struct scan_control sc = {
6645 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07006646 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006647 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08006648 };
Omar Sandoval93781322018-06-07 17:07:02 -07006649
Andrew Morton1732d2b012019-07-16 16:26:15 -07006650 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07006651 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006652 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006653
Christoph Lameterf8891e52006-06-30 01:55:45 -07006654 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006655
Mel Gorman1c308442018-12-28 00:35:52 -08006656 /*
6657 * Account for the reclaim boost. Note that the zone boost is left in
6658 * place so that parallel allocations that are near the watermark will
6659 * stall or direct reclaim until kswapd is finished.
6660 */
6661 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006662 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006663 zone = pgdat->node_zones + i;
6664 if (!managed_zone(zone))
6665 continue;
6666
6667 nr_boost_reclaim += zone->watermark_boost;
6668 zone_boosts[i] = zone->watermark_boost;
6669 }
6670 boosted = nr_boost_reclaim;
6671
6672restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006673 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006674 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006675 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006676 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006677 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006678 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006679 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006680
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006681 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006682
Mel Gorman86c79f62016-07-28 15:45:59 -07006683 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006684 * If the number of buffer_heads exceeds the maximum allowed
6685 * then consider reclaiming from all zones. This has a dual
6686 * purpose -- on 64-bit systems it is expected that
6687 * buffer_heads are stripped during active rotation. On 32-bit
6688 * systems, highmem pages can pin lowmem memory and shrinking
6689 * buffers can relieve lowmem pressure. Reclaim may still not
6690 * go ahead if all eligible zones for the original allocation
6691 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006692 */
6693 if (buffer_heads_over_limit) {
6694 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6695 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006696 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006697 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006698
Mel Gorman970a39a2016-07-28 15:46:35 -07006699 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006700 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006701 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006702 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006703
Mel Gorman86c79f62016-07-28 15:45:59 -07006704 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006705 * If the pgdat is imbalanced then ignore boosting and preserve
6706 * the watermarks for a later time and restart. Note that the
6707 * zone watermarks will be still reset at the end of balancing
6708 * on the grounds that the normal reclaim should be enough to
6709 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006710 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006711 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006712 if (!balanced && nr_boost_reclaim) {
6713 nr_boost_reclaim = 0;
6714 goto restart;
6715 }
6716
6717 /*
6718 * If boosting is not active then only reclaim if there are no
6719 * eligible zones. Note that sc.reclaim_idx is not used as
6720 * buffer_heads_over_limit may have adjusted it.
6721 */
6722 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006723 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006724
Mel Gorman1c308442018-12-28 00:35:52 -08006725 /* Limit the priority of boosting to avoid reclaim writeback */
6726 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6727 raise_priority = false;
6728
6729 /*
6730 * Do not writeback or swap pages for boosted reclaim. The
6731 * intent is to relieve pressure not issue sub-optimal IO
6732 * from reclaim context. If no pages are reclaimed, the
6733 * reclaim will be aborted.
6734 */
6735 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6736 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006737
Linus Torvalds1da177e2005-04-16 15:20:36 -07006738 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006739 * Do some background aging of the anon list, to give
6740 * pages a chance to be referenced before reclaiming. All
6741 * pages are rotated regardless of classzone as this is
6742 * about consistent aging.
6743 */
Mel Gormanef8f2322016-07-28 15:46:05 -07006744 age_active_anon(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006745
6746 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006747 * If we're getting trouble reclaiming, start doing writepage
6748 * even in laptop mode.
6749 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006750 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006751 sc.may_writepage = 1;
6752
Mel Gorman1d82de62016-07-28 15:45:43 -07006753 /* Call soft limit reclaim before calling shrink_node. */
6754 sc.nr_scanned = 0;
6755 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006756 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006757 sc.gfp_mask, &nr_soft_scanned);
6758 sc.nr_reclaimed += nr_soft_reclaimed;
6759
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006760 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006761 * There should be no need to raise the scanning priority if
6762 * enough pages are already being scanned that that high
6763 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006764 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006765 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006766 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006767
6768 /*
6769 * If the low watermark is met there is no need for processes
6770 * to be throttled on pfmemalloc_wait as they should not be
6771 * able to safely make forward progress. Wake them
6772 */
6773 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006774 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006775 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006776
Mel Gormanb8e83b92013-07-03 15:01:45 -07006777 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006778 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006779 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006780 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006781 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006782 break;
6783
6784 /*
6785 * Raise priority if scanning rate is too low or there was no
6786 * progress in reclaiming pages
6787 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006788 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006789 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6790
6791 /*
6792 * If reclaim made no progress for a boost, stop reclaim as
6793 * IO cannot be queued and it could be an infinite loop in
6794 * extreme circumstances.
6795 */
6796 if (nr_boost_reclaim && !nr_reclaimed)
6797 break;
6798
Johannes Weinerc73322d2017-05-03 14:51:51 -07006799 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006800 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006801 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006802
Johannes Weinerc73322d2017-05-03 14:51:51 -07006803 if (!sc.nr_reclaimed)
6804 pgdat->kswapd_failures++;
6805
Mel Gormanb8e83b92013-07-03 15:01:45 -07006806out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006807 clear_reclaim_active(pgdat, highest_zoneidx);
6808
Mel Gorman1c308442018-12-28 00:35:52 -08006809 /* If reclaim was boosted, account for the reclaim done in this pass */
6810 if (boosted) {
6811 unsigned long flags;
6812
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006813 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006814 if (!zone_boosts[i])
6815 continue;
6816
6817 /* Increments are under the zone lock */
6818 zone = pgdat->node_zones + i;
6819 spin_lock_irqsave(&zone->lock, flags);
6820 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6821 spin_unlock_irqrestore(&zone->lock, flags);
6822 }
6823
6824 /*
6825 * As there is now likely space, wakeup kcompact to defragment
6826 * pageblocks.
6827 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006828 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006829 }
6830
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006831 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006832 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006833 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006834 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006835
Mel Gorman0abdee22011-01-13 15:46:22 -08006836 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006837 * Return the order kswapd stopped reclaiming at as
6838 * prepare_kswapd_sleep() takes it into account. If another caller
6839 * entered the allocator slow path while kswapd was awake, order will
6840 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006841 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006842 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006843}
6844
Mel Gormane716f2e2017-05-03 14:53:45 -07006845/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006846 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6847 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6848 * not a valid index then either kswapd runs for first time or kswapd couldn't
6849 * sleep after previous reclaim attempt (node is still unbalanced). In that
6850 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006851 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006852static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6853 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006854{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006855 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006856
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006857 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006858}
6859
Mel Gorman38087d92016-07-28 15:45:49 -07006860static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006861 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006862{
6863 long remaining = 0;
6864 DEFINE_WAIT(wait);
6865
6866 if (freezing(current) || kthread_should_stop())
6867 return;
6868
6869 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6870
Shantanu Goel333b0a42017-05-03 14:53:38 -07006871 /*
6872 * Try to sleep for a short interval. Note that kcompactd will only be
6873 * woken if it is possible to sleep for a short interval. This is
6874 * deliberate on the assumption that if reclaim cannot keep an
6875 * eligible zone balanced that it's also unlikely that compaction will
6876 * succeed.
6877 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006878 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006879 /*
6880 * Compaction records what page blocks it recently failed to
6881 * isolate pages from and skips them in the future scanning.
6882 * When kswapd is going to sleep, it is reasonable to assume
6883 * that pages and compaction may succeed so reset the cache.
6884 */
6885 reset_isolation_suitable(pgdat);
6886
6887 /*
6888 * We have freed the memory, now we should compact it to make
6889 * allocation of the requested order possible.
6890 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006891 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006892
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006893 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006894
6895 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006896 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006897 * order. The values will either be from a wakeup request or
6898 * the previous request that slept prematurely.
6899 */
6900 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006901 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6902 kswapd_highest_zoneidx(pgdat,
6903 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006904
6905 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6906 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006907 }
6908
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006909 finish_wait(&pgdat->kswapd_wait, &wait);
6910 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6911 }
6912
6913 /*
6914 * After a short sleep, check if it was a premature sleep. If not, then
6915 * go fully to sleep until explicitly woken up.
6916 */
Mel Gormand9f21d42016-07-28 15:46:41 -07006917 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006918 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006919 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6920
6921 /*
6922 * vmstat counters are not perfectly accurate and the estimated
6923 * value for counters such as NR_FREE_PAGES can deviate from the
6924 * true value by nr_online_cpus * threshold. To avoid the zone
6925 * watermarks being breached while under pressure, we reduce the
6926 * per-cpu vmstat threshold while kswapd is awake and restore
6927 * them before going back to sleep.
6928 */
6929 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07006930
6931 if (!kthread_should_stop())
6932 schedule();
6933
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006934 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
6935 } else {
6936 if (remaining)
6937 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
6938 else
6939 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
6940 }
6941 finish_wait(&pgdat->kswapd_wait, &wait);
6942}
6943
Linus Torvalds1da177e2005-04-16 15:20:36 -07006944/*
6945 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006946 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006947 *
6948 * This basically trickles out pages so that we have _some_
6949 * free memory available even if there is no other activity
6950 * that frees anything up. This is needed for things like routing
6951 * etc, where we otherwise might have all activity going on in
6952 * asynchronous contexts that cannot page things out.
6953 *
6954 * If there are applications that are active memory-allocators
6955 * (most normal use), this basically shouldn't matter.
6956 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306957int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006958{
Mel Gormane716f2e2017-05-03 14:53:45 -07006959 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006960 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07006961 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006962 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10306963 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006964
Rusty Russell174596a2009-01-01 10:12:29 +10306965 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07006966 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006967
6968 /*
6969 * Tell the memory management that we're a "memory allocator",
6970 * and that if we need more memory we should get access to it
6971 * regardless (see "__alloc_pages()"). "kswapd" should
6972 * never get caught in the normal page freeing logic.
6973 *
6974 * (Kswapd normally doesn't need memory anyway, but sometimes
6975 * you need a small amount of memory in order to be able to
6976 * page out something else, and this flag essentially protects
6977 * us from recursively trying to free more memory as we're
6978 * trying to free the first piece of memory in the first place).
6979 */
Christoph Lameter930d9152006-01-08 01:00:47 -08006980 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07006981 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07006982
Qian Cai5644e1fb2020-04-01 21:10:12 -07006983 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006984 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006985 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08006986 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07006987
Qian Cai5644e1fb2020-04-01 21:10:12 -07006988 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006989 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6990 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07006991
Mel Gorman38087d92016-07-28 15:45:49 -07006992kswapd_try_sleep:
6993 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006994 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07006995
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006996 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08006997 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006998 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6999 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007000 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007001 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007002
David Rientjes8fe23e02009-12-14 17:58:33 -08007003 ret = try_to_freeze();
7004 if (kthread_should_stop())
7005 break;
7006
7007 /*
7008 * We can speed up thawing tasks if we don't call balance_pgdat
7009 * after returning from the refrigerator
7010 */
Mel Gorman38087d92016-07-28 15:45:49 -07007011 if (ret)
7012 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07007013
Mel Gorman38087d92016-07-28 15:45:49 -07007014 /*
7015 * Reclaim begins at the requested order but if a high-order
7016 * reclaim fails then kswapd falls back to reclaiming for
7017 * order-0. If that happens, kswapd will consider sleeping
7018 * for the order it finished reclaiming at (reclaim_order)
7019 * but kcompactd is woken to compact for the original
7020 * request (alloc_order).
7021 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007022 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007023 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007024 reclaim_order = balance_pgdat(pgdat, alloc_order,
7025 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007026 if (reclaim_order < alloc_order)
7027 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007028 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007029
Johannes Weiner71abdc12014-06-06 14:35:35 -07007030 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007031
Linus Torvalds1da177e2005-04-16 15:20:36 -07007032 return 0;
7033}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307034EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007035
7036/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007037 * A zone is low on free memory or too fragmented for high-order memory. If
7038 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7039 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7040 * has failed or is not needed, still wake up kcompactd if only compaction is
7041 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007042 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007043void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007044 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007045{
7046 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007047 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007048
Mel Gorman6aa303d2016-09-01 16:14:55 -07007049 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007050 return;
7051
David Rientjes5ecd9d42018-04-05 16:25:16 -07007052 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007053 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007054
Qian Cai5644e1fb2020-04-01 21:10:12 -07007055 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007056 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007057
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007058 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7059 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007060
7061 if (READ_ONCE(pgdat->kswapd_order) < order)
7062 WRITE_ONCE(pgdat->kswapd_order, order);
7063
Con Kolivas8d0986e2005-09-13 01:25:07 -07007064 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007065 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007066
David Rientjes5ecd9d42018-04-05 16:25:16 -07007067 /* Hopeless node, leave it to direct reclaim if possible */
7068 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007069 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7070 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007071 /*
7072 * There may be plenty of free memory available, but it's too
7073 * fragmented for high-order allocations. Wake up kcompactd
7074 * and rely on compaction_suitable() to determine if it's
7075 * needed. If it fails, it will defer subsequent attempts to
7076 * ratelimit its work.
7077 */
7078 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007079 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007080 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007081 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007082
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007083 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007084 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007085 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007086}
7087
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007088#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007089/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007090 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007091 * freed pages.
7092 *
7093 * Rather than trying to age LRUs the aim is to preserve the overall
7094 * LRU order by reclaiming preferentially
7095 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007096 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007097unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007098{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007099 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007100 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007101 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007102 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007103 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007104 .may_writepage = 1,
7105 .may_unmap = 1,
7106 .may_swap = 1,
7107 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007108 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007109 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007110 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007111 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007112
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007113 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007114 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007115 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007116
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007117 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007118
Andrew Morton1732d2b012019-07-16 16:26:15 -07007119 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007120 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007121 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007122
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007123 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007124}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007125#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007126
Yasunori Goto3218ae12006-06-27 02:53:33 -07007127/*
7128 * This kswapd start function will be called by init and node-hot-add.
7129 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7130 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007131void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007132{
7133 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307134 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007135
7136 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007137 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007138
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307139 trace_android_vh_kswapd_per_node(nid, &skip, true);
7140 if (skip)
7141 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007142 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7143 if (IS_ERR(pgdat->kswapd)) {
7144 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007145 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007146 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007147 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007148 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007149}
7150
David Rientjes8fe23e02009-12-14 17:58:33 -08007151/*
Jiang Liud8adde12012-07-11 14:01:52 -07007152 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007153 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007154 */
7155void kswapd_stop(int nid)
7156{
7157 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307158 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007159
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307160 trace_android_vh_kswapd_per_node(nid, &skip, false);
7161 if (skip)
7162 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007163 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007164 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007165 NODE_DATA(nid)->kswapd = NULL;
7166 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007167}
7168
Linus Torvalds1da177e2005-04-16 15:20:36 -07007169static int __init kswapd_init(void)
7170{
Wei Yang6b700b52020-04-01 21:10:09 -07007171 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007172
Linus Torvalds1da177e2005-04-16 15:20:36 -07007173 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007174 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007175 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007176 return 0;
7177}
7178
7179module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007180
7181#ifdef CONFIG_NUMA
7182/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007183 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007184 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007185 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007186 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007187 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007188int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007189
Dave Hansen51998362021-02-24 12:09:15 -08007190/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007191 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007192 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7193 * a zone.
7194 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007195#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007196
Christoph Lameter9eeff232006-01-18 17:42:31 -08007197/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007198 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007199 * occur.
7200 */
7201int sysctl_min_unmapped_ratio = 1;
7202
7203/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007204 * If the number of slab pages in a zone grows beyond this percentage then
7205 * slab reclaim needs to occur.
7206 */
7207int sysctl_min_slab_ratio = 5;
7208
Mel Gorman11fb9982016-07-28 15:46:20 -07007209static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007210{
Mel Gorman11fb9982016-07-28 15:46:20 -07007211 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7212 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7213 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007214
7215 /*
7216 * It's possible for there to be more file mapped pages than
7217 * accounted for by the pages on the file LRU lists because
7218 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7219 */
7220 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7221}
7222
7223/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007224static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007225{
Alexandru Moised031a152015-11-05 18:48:08 -08007226 unsigned long nr_pagecache_reclaimable;
7227 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007228
7229 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007230 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007231 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007232 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007233 * a better estimate
7234 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007235 if (node_reclaim_mode & RECLAIM_UNMAP)
7236 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007237 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007238 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007239
7240 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007241 if (!(node_reclaim_mode & RECLAIM_WRITE))
7242 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007243
7244 /* Watch for any possible underflows due to delta */
7245 if (unlikely(delta > nr_pagecache_reclaimable))
7246 delta = nr_pagecache_reclaimable;
7247
7248 return nr_pagecache_reclaimable - delta;
7249}
7250
Christoph Lameter0ff38492006-09-25 23:31:52 -07007251/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007252 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007253 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007254static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007255{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007256 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007257 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007258 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007259 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007260 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007261 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007262 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007263 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007264 .priority = NODE_RECLAIM_PRIORITY,
7265 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7266 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007267 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007268 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007269 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007270 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007271
Yafang Shao132bb8c2019-05-13 17:17:53 -07007272 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7273 sc.gfp_mask);
7274
Christoph Lameter9eeff232006-01-18 17:42:31 -08007275 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007276 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007277 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007278 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007279 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007280 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007281 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007282 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007283 noreclaim_flag = memalloc_noreclaim_save();
7284 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007285 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007286
Mel Gormana5f5f912016-07-28 15:46:32 -07007287 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007288 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007289 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007290 * priorities until we have enough memory freed.
7291 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007292 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007293 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007294 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007295 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007296
Andrew Morton1732d2b012019-07-16 16:26:15 -07007297 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007298 current->flags &= ~PF_SWAPWRITE;
7299 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007300 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007301 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007302
7303 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7304
Rik van Riela79311c2009-01-06 14:40:01 -08007305 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007306}
Andrew Morton179e9632006-03-22 00:08:18 -08007307
Mel Gormana5f5f912016-07-28 15:46:32 -07007308int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007309{
David Rientjesd773ed62007-10-16 23:26:01 -07007310 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007311
7312 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007313 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007314 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007315 *
Christoph Lameter96146342006-07-03 00:24:13 -07007316 * A small portion of unmapped file backed pages is needed for
7317 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007318 * thrown out if the node is overallocated. So we do not reclaim
7319 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007320 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007321 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007322 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007323 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7324 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007325 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007326
7327 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007328 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007329 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007330 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007331 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007332
7333 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007334 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007335 * have associated processors. This will favor the local processor
7336 * over remote processors and spread off node memory allocations
7337 * as wide as possible.
7338 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007339 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7340 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007341
Mel Gormana5f5f912016-07-28 15:46:32 -07007342 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7343 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007344
Mel Gormana5f5f912016-07-28 15:46:32 -07007345 ret = __node_reclaim(pgdat, gfp_mask, order);
7346 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007347
Mel Gorman24cf725182009-06-16 15:33:23 -07007348 if (!ret)
7349 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7350
David Rientjesd773ed62007-10-16 23:26:01 -07007351 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007352}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007353#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007354
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007355/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007356 * check_move_unevictable_pages - check pages for evictability and move to
7357 * appropriate zone lru list
7358 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007359 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007360 * Checks pages for evictability, if an evictable page is in the unevictable
7361 * lru list, moves it to the appropriate evictable lru list. This function
7362 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007363 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007364void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007365{
Alex Shi6168d0d2020-12-15 12:34:29 -08007366 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007367 int pgscanned = 0;
7368 int pgrescued = 0;
7369 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007370
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007371 for (i = 0; i < pvec->nr; i++) {
7372 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007373 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007374
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007375 if (PageTransTail(page))
7376 continue;
7377
7378 nr_pages = thp_nr_pages(page);
7379 pgscanned += nr_pages;
7380
Alex Shid25b5bd2020-12-15 12:34:16 -08007381 /* block memcg migration during page moving between lru */
7382 if (!TestClearPageLRU(page))
7383 continue;
7384
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007385 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007386 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007387 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007388 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007389 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007390 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007391 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007392 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007393 }
Hugh Dickins24513262012-01-20 14:34:21 -08007394
Alex Shi6168d0d2020-12-15 12:34:29 -08007395 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007396 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7397 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007398 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007399 } else if (pgscanned) {
7400 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007401 }
Hugh Dickins850465792012-01-20 14:34:19 -08007402}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007403EXPORT_SYMBOL_GPL(check_move_unevictable_pages);