blob: 548662d7edb6b4ed1167633b004559e858bf017b [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001// SPDX-License-Identifier: GPL-2.0
Linus Torvalds1da177e2005-04-16 15:20:36 -07002/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07003 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
4 *
5 * Swap reorganised 29.12.95, Stephen Tweedie.
6 * kswapd added: 7.1.96 sct
7 * Removed kswapd_ctl limits, and swap out as many pages as needed
8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
10 * Multiqueue VM started 5.8.00, Rik van Riel.
11 */
12
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070013#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
Linus Torvalds1da177e2005-04-16 15:20:36 -070015#include <linux/mm.h>
Ingo Molnar5b3cc152017-02-02 20:43:54 +010016#include <linux/sched/mm.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070017#include <linux/module.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090018#include <linux/gfp.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070019#include <linux/kernel_stat.h>
20#include <linux/swap.h>
21#include <linux/pagemap.h>
22#include <linux/init.h>
23#include <linux/highmem.h>
Anton Vorontsov70ddf632013-04-29 15:08:31 -070024#include <linux/vmpressure.h>
Andrew Mortone129b5c2006-09-27 01:50:00 -070025#include <linux/vmstat.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070026#include <linux/file.h>
27#include <linux/writeback.h>
28#include <linux/blkdev.h>
29#include <linux/buffer_head.h> /* for try_to_release_page(),
30 buffer_heads_over_limit */
31#include <linux/mm_inline.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070032#include <linux/backing-dev.h>
33#include <linux/rmap.h>
34#include <linux/topology.h>
35#include <linux/cpu.h>
36#include <linux/cpuset.h>
Mel Gorman3e7d3442011-01-13 15:45:56 -080037#include <linux/compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070038#include <linux/notifier.h>
39#include <linux/rwsem.h>
Rafael J. Wysocki248a0302006-03-22 00:09:04 -080040#include <linux/delay.h>
Yasunori Goto3218ae12006-06-27 02:53:33 -070041#include <linux/kthread.h>
Nigel Cunningham7dfb7102006-12-06 20:34:23 -080042#include <linux/freezer.h>
Balbir Singh66e17072008-02-07 00:13:56 -080043#include <linux/memcontrol.h>
Dave Hansen26aa2d12021-09-02 14:59:16 -070044#include <linux/migrate.h>
Keika Kobayashi873b4772008-07-25 01:48:52 -070045#include <linux/delayacct.h>
Lee Schermerhornaf936a12008-10-18 20:26:53 -070046#include <linux/sysctl.h>
KOSAKI Motohiro929bea72011-04-14 15:22:12 -070047#include <linux/oom.h>
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +000048#include <linux/pagevec.h>
Linus Torvalds268bb0c2011-05-20 12:50:29 -070049#include <linux/prefetch.h>
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070050#include <linux/printk.h>
Ross Zwislerf9fe48b2016-01-22 15:10:40 -080051#include <linux/dax.h>
Johannes Weinereb414682018-10-26 15:06:27 -070052#include <linux/psi.h>
Yu Zhao7f53b0e2022-09-18 02:00:05 -060053#include <linux/pagewalk.h>
54#include <linux/shmem_fs.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070055
56#include <asm/tlbflush.h>
57#include <asm/div64.h>
58
59#include <linux/swapops.h>
Rafael Aquini117aad12013-09-30 13:45:16 -070060#include <linux/balloon_compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070061
Nick Piggin0f8053a2006-03-22 00:08:33 -080062#include "internal.h"
63
Mel Gorman33906bc2010-08-09 17:19:16 -070064#define CREATE_TRACE_POINTS
65#include <trace/events/vmscan.h>
66
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -070067#undef CREATE_TRACE_POINTS
68#include <trace/hooks/vmscan.h>
69
Linus Torvalds1da177e2005-04-16 15:20:36 -070070struct scan_control {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -080071 /* How many pages shrink_list() should reclaim */
72 unsigned long nr_to_reclaim;
73
Johannes Weineree814fe2014-08-06 16:06:19 -070074 /*
75 * Nodemask of nodes allowed by the caller. If NULL, all nodes
76 * are scanned.
77 */
78 nodemask_t *nodemask;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -070079
KOSAKI Motohiro5f53e762010-05-24 14:32:37 -070080 /*
Johannes Weinerf16015f2012-01-12 17:17:52 -080081 * The memory cgroup that hit its limit and as a result is the
82 * primary target of this reclaim invocation.
83 */
84 struct mem_cgroup *target_mem_cgroup;
Balbir Singh66e17072008-02-07 00:13:56 -080085
Johannes Weiner7cf111b2020-06-03 16:03:06 -070086 /*
87 * Scan pressure balancing between anon and file LRUs
88 */
89 unsigned long anon_cost;
90 unsigned long file_cost;
91
Johannes Weinerb91ac372019-11-30 17:56:02 -080092 /* Can active pages be deactivated as part of reclaim? */
93#define DEACTIVATE_ANON 1
94#define DEACTIVATE_FILE 2
95 unsigned int may_deactivate:2;
96 unsigned int force_deactivate:1;
97 unsigned int skipped_deactivate:1;
98
Johannes Weiner1276ad62017-02-24 14:56:11 -080099 /* Writepage batching in laptop mode; RECLAIM_WRITE */
Johannes Weineree814fe2014-08-06 16:06:19 -0700100 unsigned int may_writepage:1;
101
102 /* Can mapped pages be reclaimed? */
103 unsigned int may_unmap:1;
104
105 /* Can pages be swapped as part of reclaim? */
106 unsigned int may_swap:1;
107
Yisheng Xied6622f62017-05-03 14:53:57 -0700108 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700109 * Cgroup memory below memory.low is protected as long as we
110 * don't threaten to OOM. If any cgroup is reclaimed at
111 * reduced force or passed over entirely due to its memory.low
112 * setting (memcg_low_skipped), and nothing is reclaimed as a
113 * result, then go back for one more cycle that reclaims the protected
114 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700115 */
116 unsigned int memcg_low_reclaim:1;
117 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800118
Johannes Weineree814fe2014-08-06 16:06:19 -0700119 unsigned int hibernation_mode:1;
120
121 /* One of the zones is ready for compaction */
122 unsigned int compaction_ready:1;
123
Johannes Weinerb91ac372019-11-30 17:56:02 -0800124 /* There is easily reclaimable cold cache in the current node */
125 unsigned int cache_trim_mode:1;
126
Johannes Weiner53138ce2019-11-30 17:55:56 -0800127 /* The file pages on the current node are dangerously low */
128 unsigned int file_is_tiny:1;
129
Dave Hansen26aa2d12021-09-02 14:59:16 -0700130 /* Always discard instead of demoting to lower tier memory */
131 unsigned int no_demotion:1;
132
Greg Thelenbb451fd2018-08-17 15:45:19 -0700133 /* Allocation order */
134 s8 order;
135
136 /* Scan (total_size >> priority) pages at once */
137 s8 priority;
138
139 /* The highest zone to isolate pages for reclaim from */
140 s8 reclaim_idx;
141
142 /* This context's GFP mask */
143 gfp_t gfp_mask;
144
Johannes Weineree814fe2014-08-06 16:06:19 -0700145 /* Incremented by the number of inactive pages that were scanned */
146 unsigned long nr_scanned;
147
148 /* Number of pages freed so far during a call to shrink_zones() */
149 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700150
151 struct {
152 unsigned int dirty;
153 unsigned int unqueued_dirty;
154 unsigned int congested;
155 unsigned int writeback;
156 unsigned int immediate;
157 unsigned int file_taken;
158 unsigned int taken;
159 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700160
161 /* for recording the reclaimed slab by now */
162 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700163};
164
Linus Torvalds1da177e2005-04-16 15:20:36 -0700165#ifdef ARCH_HAS_PREFETCHW
166#define prefetchw_prev_lru_page(_page, _base, _field) \
167 do { \
168 if ((_page)->lru.prev != _base) { \
169 struct page *prev; \
170 \
171 prev = lru_to_page(&(_page->lru)); \
172 prefetchw(&prev->_field); \
173 } \
174 } while (0)
175#else
176#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
177#endif
178
179/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700180 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700181 */
182int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700183
Yang Shi0a432dc2019-09-23 15:38:12 -0700184static void set_task_reclaim_state(struct task_struct *task,
185 struct reclaim_state *rs)
186{
187 /* Check for an overwrite */
188 WARN_ON_ONCE(rs && task->reclaim_state);
189
190 /* Check for the nulling of an already-nulled member */
191 WARN_ON_ONCE(!rs && !task->reclaim_state);
192
193 task->reclaim_state = rs;
194}
195
Linus Torvalds1da177e2005-04-16 15:20:36 -0700196static LIST_HEAD(shrinker_list);
197static DECLARE_RWSEM(shrinker_rwsem);
198
Yang Shi0a432dc2019-09-23 15:38:12 -0700199#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700200static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700201
Yang Shi3c6f17e2021-05-04 18:36:33 -0700202/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700203static inline int shrinker_map_size(int nr_items)
204{
205 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
206}
Yang Shi2bfd3632021-05-04 18:36:11 -0700207
Yang Shi3c6f17e2021-05-04 18:36:33 -0700208static inline int shrinker_defer_size(int nr_items)
209{
210 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
211}
212
Yang Shi468ab842021-05-04 18:36:26 -0700213static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
214 int nid)
215{
216 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
217 lockdep_is_held(&shrinker_rwsem));
218}
219
Yang Shie4262c42021-05-04 18:36:23 -0700220static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700221 int map_size, int defer_size,
222 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700223{
Yang Shie4262c42021-05-04 18:36:23 -0700224 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700225 struct mem_cgroup_per_node *pn;
226 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700227 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700228
Yang Shi2bfd3632021-05-04 18:36:11 -0700229 for_each_node(nid) {
230 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700231 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700232 /* Not yet online memcg */
233 if (!old)
234 return 0;
235
236 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
237 if (!new)
238 return -ENOMEM;
239
Yang Shi3c6f17e2021-05-04 18:36:33 -0700240 new->nr_deferred = (atomic_long_t *)(new + 1);
241 new->map = (void *)new->nr_deferred + defer_size;
242
243 /* map: set all old bits, clear all new bits */
244 memset(new->map, (int)0xff, old_map_size);
245 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
246 /* nr_deferred: copy old values, clear all new values */
247 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
248 memset((void *)new->nr_deferred + old_defer_size, 0,
249 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700250
Yang Shie4262c42021-05-04 18:36:23 -0700251 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700252 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700253 }
254
255 return 0;
256}
257
Yang Shie4262c42021-05-04 18:36:23 -0700258void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700259{
260 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700261 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700262 int nid;
263
Yang Shi2bfd3632021-05-04 18:36:11 -0700264 for_each_node(nid) {
265 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700266 info = rcu_dereference_protected(pn->shrinker_info, true);
267 kvfree(info);
268 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700269 }
270}
271
Yang Shie4262c42021-05-04 18:36:23 -0700272int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700273{
Yang Shie4262c42021-05-04 18:36:23 -0700274 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700275 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700276 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700277
Yang Shid27cf2a2021-05-04 18:36:14 -0700278 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700279 map_size = shrinker_map_size(shrinker_nr_max);
280 defer_size = shrinker_defer_size(shrinker_nr_max);
281 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700282 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700283 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
284 if (!info) {
285 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700286 ret = -ENOMEM;
287 break;
288 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700289 info->nr_deferred = (atomic_long_t *)(info + 1);
290 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700291 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700292 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700293 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700294
295 return ret;
296}
297
Yang Shi3c6f17e2021-05-04 18:36:33 -0700298static inline bool need_expand(int nr_max)
299{
300 return round_up(nr_max, BITS_PER_LONG) >
301 round_up(shrinker_nr_max, BITS_PER_LONG);
302}
303
Yang Shie4262c42021-05-04 18:36:23 -0700304static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700305{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700306 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700307 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700308 int map_size, defer_size = 0;
309 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700310 struct mem_cgroup *memcg;
311
Yang Shi3c6f17e2021-05-04 18:36:33 -0700312 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700313 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700314
Yang Shi2bfd3632021-05-04 18:36:11 -0700315 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700316 goto out;
317
318 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700319
Yang Shi3c6f17e2021-05-04 18:36:33 -0700320 map_size = shrinker_map_size(new_nr_max);
321 defer_size = shrinker_defer_size(new_nr_max);
322 old_map_size = shrinker_map_size(shrinker_nr_max);
323 old_defer_size = shrinker_defer_size(shrinker_nr_max);
324
Yang Shi2bfd3632021-05-04 18:36:11 -0700325 memcg = mem_cgroup_iter(NULL, NULL, NULL);
326 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700327 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
328 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700329 if (ret) {
330 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700331 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700332 }
333 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700334out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700335 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700336 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700337
Yang Shi2bfd3632021-05-04 18:36:11 -0700338 return ret;
339}
340
341void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
342{
343 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700344 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700345
346 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700347 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700348 /* Pairs with smp mb in shrink_slab() */
349 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700350 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700351 rcu_read_unlock();
352 }
353}
354
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700355static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700356
357static int prealloc_memcg_shrinker(struct shrinker *shrinker)
358{
359 int id, ret = -ENOMEM;
360
Yang Shi476b30a2021-05-04 18:36:39 -0700361 if (mem_cgroup_disabled())
362 return -ENOSYS;
363
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700364 down_write(&shrinker_rwsem);
365 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700366 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700367 if (id < 0)
368 goto unlock;
369
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700370 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700371 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700372 idr_remove(&shrinker_idr, id);
373 goto unlock;
374 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700375 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700376 shrinker->id = id;
377 ret = 0;
378unlock:
379 up_write(&shrinker_rwsem);
380 return ret;
381}
382
383static void unregister_memcg_shrinker(struct shrinker *shrinker)
384{
385 int id = shrinker->id;
386
387 BUG_ON(id < 0);
388
Yang Shi41ca6682021-05-04 18:36:29 -0700389 lockdep_assert_held(&shrinker_rwsem);
390
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700391 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700392}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700393
Yang Shi86750832021-05-04 18:36:36 -0700394static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
395 struct mem_cgroup *memcg)
396{
397 struct shrinker_info *info;
398
399 info = shrinker_info_protected(memcg, nid);
400 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
401}
402
403static long add_nr_deferred_memcg(long nr, 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_add_return(nr, &info->nr_deferred[shrinker->id]);
410}
411
Yang Shia1780152021-05-04 18:36:42 -0700412void reparent_shrinker_deferred(struct mem_cgroup *memcg)
413{
414 int i, nid;
415 long nr;
416 struct mem_cgroup *parent;
417 struct shrinker_info *child_info, *parent_info;
418
419 parent = parent_mem_cgroup(memcg);
420 if (!parent)
421 parent = root_mem_cgroup;
422
423 /* Prevent from concurrent shrinker_info expand */
424 down_read(&shrinker_rwsem);
425 for_each_node(nid) {
426 child_info = shrinker_info_protected(memcg, nid);
427 parent_info = shrinker_info_protected(parent, nid);
428 for (i = 0; i < shrinker_nr_max; i++) {
429 nr = atomic_long_read(&child_info->nr_deferred[i]);
430 atomic_long_add(nr, &parent_info->nr_deferred[i]);
431 }
432 }
433 up_read(&shrinker_rwsem);
434}
435
Johannes Weinerb5ead352019-11-30 17:55:40 -0800436static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800437{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800438 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800439}
Tejun Heo97c93412015-05-22 18:23:36 -0400440
441/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800442 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400443 * @sc: scan_control in question
444 *
445 * The normal page dirty throttling mechanism in balance_dirty_pages() is
446 * completely broken with the legacy memcg and direct stalling in
447 * shrink_page_list() is used for throttling instead, which lacks all the
448 * niceties such as fairness, adaptive pausing, bandwidth proportional
449 * allocation and configurability.
450 *
451 * This function tests whether the vmscan currently in progress can assume
452 * that the normal dirty throttling mechanism is operational.
453 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800454static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400455{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800456 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400457 return true;
458#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800459 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400460 return true;
461#endif
462 return false;
463}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800464#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700465static int prealloc_memcg_shrinker(struct shrinker *shrinker)
466{
Yang Shi476b30a2021-05-04 18:36:39 -0700467 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700468}
469
470static void unregister_memcg_shrinker(struct shrinker *shrinker)
471{
472}
473
Yang Shi86750832021-05-04 18:36:36 -0700474static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
475 struct mem_cgroup *memcg)
476{
477 return 0;
478}
479
480static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
481 struct mem_cgroup *memcg)
482{
483 return 0;
484}
485
Johannes Weinerb5ead352019-11-30 17:55:40 -0800486static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800487{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800488 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800489}
Tejun Heo97c93412015-05-22 18:23:36 -0400490
Johannes Weinerb5ead352019-11-30 17:55:40 -0800491static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400492{
493 return true;
494}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800495#endif
496
Yang Shi86750832021-05-04 18:36:36 -0700497static long xchg_nr_deferred(struct shrinker *shrinker,
498 struct shrink_control *sc)
499{
500 int nid = sc->nid;
501
502 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
503 nid = 0;
504
505 if (sc->memcg &&
506 (shrinker->flags & SHRINKER_MEMCG_AWARE))
507 return xchg_nr_deferred_memcg(nid, shrinker,
508 sc->memcg);
509
510 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
511}
512
513
514static long add_nr_deferred(long nr, struct shrinker *shrinker,
515 struct shrink_control *sc)
516{
517 int nid = sc->nid;
518
519 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
520 nid = 0;
521
522 if (sc->memcg &&
523 (shrinker->flags & SHRINKER_MEMCG_AWARE))
524 return add_nr_deferred_memcg(nr, nid, shrinker,
525 sc->memcg);
526
527 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
528}
529
Dave Hansen26aa2d12021-09-02 14:59:16 -0700530static bool can_demote(int nid, struct scan_control *sc)
531{
Huang Ying20b51af12021-09-02 14:59:33 -0700532 if (!numa_demotion_enabled)
533 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700534 if (sc) {
535 if (sc->no_demotion)
536 return false;
537 /* It is pointless to do demotion in memcg reclaim */
538 if (cgroup_reclaim(sc))
539 return false;
540 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700541 if (next_demotion_node(nid) == NUMA_NO_NODE)
542 return false;
543
Huang Ying20b51af12021-09-02 14:59:33 -0700544 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700545}
546
Keith Buscha2a36482021-09-02 14:59:26 -0700547static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
548 int nid,
549 struct scan_control *sc)
550{
551 if (memcg == NULL) {
552 /*
553 * For non-memcg reclaim, is there
554 * space in any swap device?
555 */
556 if (get_nr_swap_pages() > 0)
557 return true;
558 } else {
559 /* Is the memcg below its swap limit? */
560 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
561 return true;
562 }
563
564 /*
565 * The page can not be swapped.
566 *
567 * Can it be reclaimed from this node via demotion?
568 */
569 return can_demote(nid, sc);
570}
571
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700572/*
573 * This misses isolated pages which are not accounted for to save counters.
574 * As the data only determines if reclaim or compaction continues, it is
575 * not expected that isolated pages will be a dominating factor.
576 */
577unsigned long zone_reclaimable_pages(struct zone *zone)
578{
579 unsigned long nr;
580
581 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
582 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700583 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700584 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
585 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
586
587 return nr;
588}
589
Michal Hockofd538802017-02-22 15:45:58 -0800590/**
591 * lruvec_lru_size - Returns the number of pages on the given LRU list.
592 * @lruvec: lru vector
593 * @lru: lru to use
594 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
595 */
Yu Zhao20913392021-02-24 12:08:44 -0800596static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
597 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800598{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800599 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800600 int zid;
601
Johannes Weinerde3b0152019-11-30 17:55:31 -0800602 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800603 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800604
Michal Hockofd538802017-02-22 15:45:58 -0800605 if (!managed_zone(zone))
606 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800607
Michal Hockofd538802017-02-22 15:45:58 -0800608 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800609 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800610 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800611 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800612 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800613 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800614}
615
Linus Torvalds1da177e2005-04-16 15:20:36 -0700616/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000617 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700618 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900619int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700620{
Yang Shi476b30a2021-05-04 18:36:39 -0700621 unsigned int size;
622 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000623
Yang Shi476b30a2021-05-04 18:36:39 -0700624 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
625 err = prealloc_memcg_shrinker(shrinker);
626 if (err != -ENOSYS)
627 return err;
628
629 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
630 }
631
632 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000633 if (shrinker->flags & SHRINKER_NUMA_AWARE)
634 size *= nr_node_ids;
635
636 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
637 if (!shrinker->nr_deferred)
638 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700639
Tetsuo Handa8e049442018-04-04 19:53:07 +0900640 return 0;
641}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000642
Tetsuo Handa8e049442018-04-04 19:53:07 +0900643void free_prealloced_shrinker(struct shrinker *shrinker)
644{
Yang Shi41ca6682021-05-04 18:36:29 -0700645 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
646 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700647 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700648 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700649 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700650 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700651
Tetsuo Handa8e049442018-04-04 19:53:07 +0900652 kfree(shrinker->nr_deferred);
653 shrinker->nr_deferred = NULL;
654}
655
656void register_shrinker_prepared(struct shrinker *shrinker)
657{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700658 down_write(&shrinker_rwsem);
659 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700660 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700661 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900662}
663
664int register_shrinker(struct shrinker *shrinker)
665{
666 int err = prealloc_shrinker(shrinker);
667
668 if (err)
669 return err;
670 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000671 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700672}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700673EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700674
675/*
676 * Remove one
677 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700678void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700679{
Yang Shi41ca6682021-05-04 18:36:29 -0700680 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900681 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700682
Linus Torvalds1da177e2005-04-16 15:20:36 -0700683 down_write(&shrinker_rwsem);
684 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700685 shrinker->flags &= ~SHRINKER_REGISTERED;
686 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
687 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700688 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700689
Andrew Vaginae393322013-10-16 13:46:46 -0700690 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900691 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700692}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700693EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700694
695#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000696
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800697static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800698 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700699{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000700 unsigned long freed = 0;
701 unsigned long long delta;
702 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700703 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000704 long nr;
705 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000706 long batch_size = shrinker->batch ? shrinker->batch
707 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800708 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000709
rongqianfeng8da6ee32021-05-21 10:30:14 +0800710 trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
711
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700712 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700713 if (freeable == 0 || freeable == SHRINK_EMPTY)
714 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000715
716 /*
717 * copy the current shrinker scan count into a local variable
718 * and zero it so that other concurrent shrinker invocations
719 * don't also do this scanning work.
720 */
Yang Shi86750832021-05-04 18:36:36 -0700721 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000722
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700723 if (shrinker->seeks) {
724 delta = freeable >> priority;
725 delta *= 4;
726 do_div(delta, shrinker->seeks);
727 } else {
728 /*
729 * These objects don't require any IO to create. Trim
730 * them aggressively under memory pressure to keep
731 * them from causing refetches in the IO caches.
732 */
733 delta = freeable / 2;
734 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700735
Yang Shi18bb4732021-05-04 18:36:45 -0700736 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000737 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700738 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000739
740 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800741 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000742
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800743 /*
744 * Normally, we should not scan less than batch_size objects in one
745 * pass to avoid too frequent shrinker calls, but if the slab has less
746 * than batch_size objects in total and we are really tight on memory,
747 * we will try to reclaim all available objects, otherwise we can end
748 * up failing allocations although there are plenty of reclaimable
749 * objects spread over several slabs with usage less than the
750 * batch_size.
751 *
752 * We detect the "tight on memory" situations by looking at the total
753 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700754 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800755 * scanning at high prio and therefore should try to reclaim as much as
756 * possible.
757 */
758 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700759 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000760 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800761 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000762
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800763 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700764 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000765 ret = shrinker->scan_objects(shrinker, shrinkctl);
766 if (ret == SHRINK_STOP)
767 break;
768 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000769
Chris Wilsond460acb2017-09-06 16:19:26 -0700770 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
771 total_scan -= shrinkctl->nr_scanned;
772 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000773
774 cond_resched();
775 }
776
Yang Shi18bb4732021-05-04 18:36:45 -0700777 /*
778 * The deferred work is increased by any new work (delta) that wasn't
779 * done, decreased by old deferred work that was done now.
780 *
781 * And it is capped to two times of the freeable items.
782 */
783 next_deferred = max_t(long, (nr + delta - scanned), 0);
784 next_deferred = min(next_deferred, (2 * freeable));
785
Glauber Costa1d3d4432013-08-28 10:18:04 +1000786 /*
787 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700788 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000789 */
Yang Shi86750832021-05-04 18:36:36 -0700790 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000791
Yang Shi8efb4b52021-05-04 18:36:08 -0700792 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000793 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700794}
795
Yang Shi0a432dc2019-09-23 15:38:12 -0700796#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700797static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
798 struct mem_cgroup *memcg, int priority)
799{
Yang Shie4262c42021-05-04 18:36:23 -0700800 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700801 unsigned long ret, freed = 0;
802 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700803
Yang Shi0a432dc2019-09-23 15:38:12 -0700804 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700805 return 0;
806
807 if (!down_read_trylock(&shrinker_rwsem))
808 return 0;
809
Yang Shi468ab842021-05-04 18:36:26 -0700810 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700811 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700812 goto unlock;
813
Yang Shie4262c42021-05-04 18:36:23 -0700814 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700815 struct shrink_control sc = {
816 .gfp_mask = gfp_mask,
817 .nid = nid,
818 .memcg = memcg,
819 };
820 struct shrinker *shrinker;
821
822 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700823 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700824 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700825 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700826 continue;
827 }
828
Yang Shi0a432dc2019-09-23 15:38:12 -0700829 /* Call non-slab shrinkers even though kmem is disabled */
830 if (!memcg_kmem_enabled() &&
831 !(shrinker->flags & SHRINKER_NONSLAB))
832 continue;
833
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700834 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700835 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700836 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700837 /*
838 * After the shrinker reported that it had no objects to
839 * free, but before we cleared the corresponding bit in
840 * the memcg shrinker map, a new object might have been
841 * added. To make sure, we have the bit set in this
842 * case, we invoke the shrinker one more time and reset
843 * the bit if it reports that it is not empty anymore.
844 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700845 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700846 *
847 * list_lru_add() shrink_slab_memcg()
848 * list_add_tail() clear_bit()
849 * <MB> <MB>
850 * set_bit() do_shrink_slab()
851 */
852 smp_mb__after_atomic();
853 ret = do_shrink_slab(&sc, shrinker, priority);
854 if (ret == SHRINK_EMPTY)
855 ret = 0;
856 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700857 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700858 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700859 freed += ret;
860
861 if (rwsem_is_contended(&shrinker_rwsem)) {
862 freed = freed ? : 1;
863 break;
864 }
865 }
866unlock:
867 up_read(&shrinker_rwsem);
868 return freed;
869}
Yang Shi0a432dc2019-09-23 15:38:12 -0700870#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700871static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
872 struct mem_cgroup *memcg, int priority)
873{
874 return 0;
875}
Yang Shi0a432dc2019-09-23 15:38:12 -0700876#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700877
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800878/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800879 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800880 * @gfp_mask: allocation context
881 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800882 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800883 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700884 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800885 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700886 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800887 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
888 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700889 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700890 * @memcg specifies the memory cgroup to target. Unaware shrinkers
891 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800892 *
Josef Bacik9092c712018-01-31 16:16:26 -0800893 * @priority is sc->priority, we take the number of objects and >> by priority
894 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700895 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800896 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700897 */
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800898unsigned long shrink_slab(gfp_t gfp_mask, int nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800899 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800900 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700901{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700902 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700903 struct shrinker *shrinker;
wudean842c68a2021-04-27 17:40:41 +0800904 bool bypass = false;
905
906 trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
907 if (bypass)
908 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700909
Yang Shifa1e5122019-08-02 21:48:44 -0700910 /*
911 * The root memcg might be allocated even though memcg is disabled
912 * via "cgroup_disable=memory" boot parameter. This could make
913 * mem_cgroup_is_root() return false, then just run memcg slab
914 * shrink, but skip global shrink. This may result in premature
915 * oom.
916 */
917 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700918 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800919
Tetsuo Handae830c632018-04-05 16:23:35 -0700920 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700921 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700922
923 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800924 struct shrink_control sc = {
925 .gfp_mask = gfp_mask,
926 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800927 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800928 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800929
Kirill Tkhai9b996462018-08-17 15:48:21 -0700930 ret = do_shrink_slab(&sc, shrinker, priority);
931 if (ret == SHRINK_EMPTY)
932 ret = 0;
933 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800934 /*
935 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700936 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800937 * by parallel ongoing shrinking.
938 */
939 if (rwsem_is_contended(&shrinker_rwsem)) {
940 freed = freed ? : 1;
941 break;
942 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700943 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800944
Linus Torvalds1da177e2005-04-16 15:20:36 -0700945 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700946out:
947 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000948 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700949}
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800950EXPORT_SYMBOL_GPL(shrink_slab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700951
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800952void drop_slab_node(int nid)
953{
954 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700955 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800956
957 do {
958 struct mem_cgroup *memcg = NULL;
959
Chunxin Zang069c4112020-10-13 16:56:46 -0700960 if (fatal_signal_pending(current))
961 return;
962
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800963 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700964 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800965 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800966 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800967 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700968 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800969}
970
971void drop_slab(void)
972{
973 int nid;
974
975 for_each_online_node(nid)
976 drop_slab_node(nid);
977}
978
Linus Torvalds1da177e2005-04-16 15:20:36 -0700979static inline int is_page_cache_freeable(struct page *page)
980{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700981 /*
982 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400983 * that isolated the page, the page cache and optional buffer
984 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700985 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -0700986 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400987 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700988}
989
Yang Shicb165562019-11-30 17:55:28 -0800990static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700991{
Christoph Lameter930d9152006-01-08 01:00:47 -0800992 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700993 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400994 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700995 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400996 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700997 return 1;
998 return 0;
999}
1000
1001/*
1002 * We detected a synchronous write error writing a page out. Probably
1003 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1004 * fsync(), msync() or close().
1005 *
1006 * The tricky part is that after writepage we cannot touch the mapping: nothing
1007 * prevents it from being freed up. But we have a ref on the page and once
1008 * that page is locked, the mapping is pinned.
1009 *
1010 * We're allowed to run sleeping lock_page() here because we know the caller has
1011 * __GFP_FS.
1012 */
1013static void handle_write_error(struct address_space *mapping,
1014 struct page *page, int error)
1015{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001016 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001017 if (page_mapping(page) == mapping)
1018 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001019 unlock_page(page);
1020}
1021
Christoph Lameter04e62a22006-06-23 02:03:38 -07001022/* possible outcome of pageout() */
1023typedef enum {
1024 /* failed to write page out, page is locked */
1025 PAGE_KEEP,
1026 /* move page to the active list, page is locked */
1027 PAGE_ACTIVATE,
1028 /* page has been sent to the disk successfully, page is unlocked */
1029 PAGE_SUCCESS,
1030 /* page is clean and locked */
1031 PAGE_CLEAN,
1032} pageout_t;
1033
Linus Torvalds1da177e2005-04-16 15:20:36 -07001034/*
Andrew Morton1742f192006-03-22 00:08:21 -08001035 * pageout is called by shrink_page_list() for each dirty page.
1036 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001037 */
Yang Shicb165562019-11-30 17:55:28 -08001038static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001039{
1040 /*
1041 * If the page is dirty, only perform writeback if that write
1042 * will be non-blocking. To prevent this allocation from being
1043 * stalled by pagecache activity. But note that there may be
1044 * stalls if we need to run get_block(). We could test
1045 * PagePrivate for that.
1046 *
Al Viro81742022014-04-03 03:17:43 -04001047 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001048 * this page's queue, we can perform writeback even if that
1049 * will block.
1050 *
1051 * If the page is swapcache, write it back even if that would
1052 * block, for some throttling. This happens by accident, because
1053 * swap_backing_dev_info is bust: it doesn't reflect the
1054 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001055 */
1056 if (!is_page_cache_freeable(page))
1057 return PAGE_KEEP;
1058 if (!mapping) {
1059 /*
1060 * Some data journaling orphaned pages can have
1061 * page->mapping == NULL while being dirty with clean buffers.
1062 */
David Howells266cf652009-04-03 16:42:36 +01001063 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001064 if (try_to_free_buffers(page)) {
1065 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001066 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001067 return PAGE_CLEAN;
1068 }
1069 }
1070 return PAGE_KEEP;
1071 }
1072 if (mapping->a_ops->writepage == NULL)
1073 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001074 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001075 return PAGE_KEEP;
1076
1077 if (clear_page_dirty_for_io(page)) {
1078 int res;
1079 struct writeback_control wbc = {
1080 .sync_mode = WB_SYNC_NONE,
1081 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001082 .range_start = 0,
1083 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001084 .for_reclaim = 1,
1085 };
1086
1087 SetPageReclaim(page);
1088 res = mapping->a_ops->writepage(page, &wbc);
1089 if (res < 0)
1090 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001091 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001092 ClearPageReclaim(page);
1093 return PAGE_ACTIVATE;
1094 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001095
Linus Torvalds1da177e2005-04-16 15:20:36 -07001096 if (!PageWriteback(page)) {
1097 /* synchronous write or broken a_ops? */
1098 ClearPageReclaim(page);
1099 }
yalin wang3aa23852016-01-14 15:18:30 -08001100 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001101 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001102 return PAGE_SUCCESS;
1103 }
1104
1105 return PAGE_CLEAN;
1106}
1107
Andrew Mortona649fd92006-10-17 00:09:36 -07001108/*
Nick Piggine2867812008-07-25 19:45:30 -07001109 * Same as remove_mapping, but if the page is removed from the mapping, it
1110 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001111 */
Johannes Weinera5289102014-04-03 14:47:51 -07001112static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001113 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001114{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001115 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001116 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001117
Nick Piggin28e4d962006-09-25 23:31:23 -07001118 BUG_ON(!PageLocked(page));
1119 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001120
Johannes Weiner30472502021-09-02 14:53:18 -07001121 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001122 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001123 * The non racy check for a busy page.
1124 *
1125 * Must be careful with the order of the tests. When someone has
1126 * a ref to the page, it may be possible that they dirty it then
1127 * drop the reference. So if PageDirty is tested before page_count
1128 * here, then the following race may occur:
1129 *
1130 * get_user_pages(&page);
1131 * [user mapping goes away]
1132 * write_to(page);
1133 * !PageDirty(page) [good]
1134 * SetPageDirty(page);
1135 * put_page(page);
1136 * !page_count(page) [good, discard it]
1137 *
1138 * [oops, our write_to data is lost]
1139 *
1140 * Reversing the order of the tests ensures such a situation cannot
1141 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001142 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001143 *
1144 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001145 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001146 */
William Kucharski906d2782019-10-18 20:20:33 -07001147 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001148 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001149 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001150 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001151 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001152 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001153 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001154 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001155
1156 if (PageSwapCache(page)) {
1157 swp_entry_t swap = { .val = page_private(page) };
Yu Zhao37397872022-09-18 02:00:03 -06001158
1159 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001160 if (reclaimed && !mapping_exiting(mapping))
1161 shadow = workingset_eviction(page, target_memcg);
Yu Zhao37397872022-09-18 02:00:03 -06001162 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001163 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001164 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001165 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001166 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001167 void (*freepage)(struct page *);
1168
1169 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001170 /*
1171 * Remember a shadow entry for reclaimed file cache in
1172 * order to detect refaults, thus thrashing, later on.
1173 *
1174 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001175 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001176 * inode reclaim needs to empty out the radix tree or
1177 * the nodes are lost. Don't plant shadows behind its
1178 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001179 *
1180 * We also don't store shadows for DAX mappings because the
1181 * only page cache pages found in these are zero pages
1182 * covering holes, and because we don't want to mix DAX
1183 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001184 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001185 */
Huang Ying9de4f222020-04-06 20:04:41 -07001186 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001187 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001188 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001189 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001190 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001191
1192 if (freepage != NULL)
1193 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001194 }
1195
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001196 return 1;
1197
1198cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001199 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001200 return 0;
1201}
1202
Linus Torvalds1da177e2005-04-16 15:20:36 -07001203/*
Nick Piggine2867812008-07-25 19:45:30 -07001204 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1205 * someone else has a ref on the page, abort and return 0. If it was
1206 * successfully detached, return 1. Assumes the caller has a single ref on
1207 * this page.
1208 */
1209int remove_mapping(struct address_space *mapping, struct page *page)
1210{
Johannes Weinerb9107182019-11-30 17:55:59 -08001211 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001212 /*
1213 * Unfreezing the refcount with 1 rather than 2 effectively
1214 * drops the pagecache ref for us without requiring another
1215 * atomic operation.
1216 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001217 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001218 return 1;
1219 }
1220 return 0;
1221}
1222
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001223/**
1224 * putback_lru_page - put previously isolated page onto appropriate LRU list
1225 * @page: page to be put back to appropriate lru list
1226 *
1227 * Add previously isolated @page to appropriate LRU list.
1228 * Page may still be unevictable for other reasons.
1229 *
1230 * lru_lock must not be held, interrupts must be enabled.
1231 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001232void putback_lru_page(struct page *page)
1233{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001234 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001235 put_page(page); /* drop ref from isolate */
1236}
1237
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001238enum page_references {
1239 PAGEREF_RECLAIM,
1240 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001241 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001242 PAGEREF_ACTIVATE,
1243};
1244
1245static enum page_references page_check_references(struct page *page,
1246 struct scan_control *sc)
1247{
Johannes Weiner645747462010-03-05 13:42:22 -08001248 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001249 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001250
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001251 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1252 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001253 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001254
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001255 /*
1256 * Mlock lost the isolation race with us. Let try_to_unmap()
1257 * move the page to the unevictable list.
1258 */
1259 if (vm_flags & VM_LOCKED)
1260 return PAGEREF_RECLAIM;
1261
Johannes Weiner645747462010-03-05 13:42:22 -08001262 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001263 /*
1264 * All mapped pages start out with page table
1265 * references from the instantiating fault, so we need
1266 * to look twice if a mapped file page is used more
1267 * than once.
1268 *
1269 * Mark it and spare it for another trip around the
1270 * inactive list. Another page table reference will
1271 * lead to its activation.
1272 *
1273 * Note: the mark is set for activated pages as well
1274 * so that recently deactivated but used pages are
1275 * quickly recovered.
1276 */
1277 SetPageReferenced(page);
1278
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001279 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001280 return PAGEREF_ACTIVATE;
1281
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001282 /*
1283 * Activate file-backed executable pages after first usage.
1284 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001285 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001286 return PAGEREF_ACTIVATE;
1287
Johannes Weiner645747462010-03-05 13:42:22 -08001288 return PAGEREF_KEEP;
1289 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001290
1291 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001292 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001293 return PAGEREF_RECLAIM_CLEAN;
1294
1295 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001296}
1297
Mel Gormane2be15f2013-07-03 15:01:57 -07001298/* Check if a page is dirty or under writeback */
1299static void page_check_dirty_writeback(struct page *page,
1300 bool *dirty, bool *writeback)
1301{
Mel Gormanb4597222013-07-03 15:02:05 -07001302 struct address_space *mapping;
1303
Mel Gormane2be15f2013-07-03 15:01:57 -07001304 /*
1305 * Anonymous pages are not handled by flushers and must be written
1306 * from reclaim context. Do not stall reclaim based on them
1307 */
Huang Ying9de4f222020-04-06 20:04:41 -07001308 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001309 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001310 *dirty = false;
1311 *writeback = false;
1312 return;
1313 }
1314
1315 /* By default assume that the page flags are accurate */
1316 *dirty = PageDirty(page);
1317 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001318
1319 /* Verify dirty/writeback state if the filesystem supports it */
1320 if (!page_has_private(page))
1321 return;
1322
1323 mapping = page_mapping(page);
1324 if (mapping && mapping->a_ops->is_dirty_writeback)
1325 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001326}
1327
Dave Hansen26aa2d12021-09-02 14:59:16 -07001328static struct page *alloc_demote_page(struct page *page, unsigned long node)
1329{
1330 struct migration_target_control mtc = {
1331 /*
1332 * Allocate from 'node', or fail quickly and quietly.
1333 * When this happens, 'page' will likely just be discarded
1334 * instead of migrated.
1335 */
1336 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1337 __GFP_THISNODE | __GFP_NOWARN |
1338 __GFP_NOMEMALLOC | GFP_NOWAIT,
1339 .nid = node
1340 };
1341
1342 return alloc_migration_target(page, (unsigned long)&mtc);
1343}
1344
1345/*
1346 * Take pages on @demote_list and attempt to demote them to
1347 * another node. Pages which are not demoted are left on
1348 * @demote_pages.
1349 */
1350static unsigned int demote_page_list(struct list_head *demote_pages,
1351 struct pglist_data *pgdat)
1352{
1353 int target_nid = next_demotion_node(pgdat->node_id);
1354 unsigned int nr_succeeded;
1355 int err;
1356
1357 if (list_empty(demote_pages))
1358 return 0;
1359
1360 if (target_nid == NUMA_NO_NODE)
1361 return 0;
1362
1363 /* Demotion ignores all cpuset and mempolicy settings */
1364 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1365 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1366 &nr_succeeded);
1367
Yang Shi668e4142021-09-02 14:59:19 -07001368 if (current_is_kswapd())
1369 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1370 else
1371 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1372
Dave Hansen26aa2d12021-09-02 14:59:16 -07001373 return nr_succeeded;
1374}
1375
Nick Piggine2867812008-07-25 19:45:30 -07001376/*
Andrew Morton1742f192006-03-22 00:08:21 -08001377 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001378 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001379static unsigned int shrink_page_list(struct list_head *page_list,
1380 struct pglist_data *pgdat,
1381 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001382 struct reclaim_stat *stat,
1383 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001384{
1385 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001386 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001387 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001388 unsigned int nr_reclaimed = 0;
1389 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001390 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001391
Kirill Tkhai060f0052019-03-05 15:48:15 -08001392 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001393 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001394 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001395
Dave Hansen26aa2d12021-09-02 14:59:16 -07001396retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001397 while (!list_empty(page_list)) {
1398 struct address_space *mapping;
1399 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001400 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001401 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001402 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001403
1404 cond_resched();
1405
1406 page = lru_to_page(page_list);
1407 list_del(&page->lru);
1408
Nick Piggin529ae9a2008-08-02 12:01:03 +02001409 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001410 goto keep;
1411
Sasha Levin309381fea2014-01-23 15:52:54 -08001412 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001413
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001414 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001415
1416 /* Account the number of base pages even though THP */
1417 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001418
Hugh Dickins39b5f292012-10-08 16:33:18 -07001419 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001420 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001421
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001422 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001423 goto keep_locked;
1424
Yu Zhao0182f922022-09-18 02:00:04 -06001425 /* page_update_gen() tried to promote this page? */
1426 if (lru_gen_enabled() && !ignore_references &&
1427 page_mapped(page) && PageReferenced(page))
1428 goto keep_locked;
1429
Andy Whitcroftc661b072007-08-22 14:01:26 -07001430 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1431 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1432
Mel Gorman283aba92013-07-03 15:01:51 -07001433 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001434 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001435 * reclaim_congested which affects wait_iff_congested. kswapd
1436 * will stall and start writing pages if the tail of the LRU
1437 * is all dirty unqueued pages.
1438 */
1439 page_check_dirty_writeback(page, &dirty, &writeback);
1440 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001441 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001442
1443 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001444 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001445
Mel Gormand04e8ac2013-07-03 15:02:03 -07001446 /*
1447 * Treat this page as congested if the underlying BDI is or if
1448 * pages are cycling through the LRU so quickly that the
1449 * pages marked for immediate reclaim are making it to the
1450 * end of the LRU a second time.
1451 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001452 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001453 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001454 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001455 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001456 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001457
1458 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001459 * If a page at the tail of the LRU is under writeback, there
1460 * are three cases to consider.
1461 *
1462 * 1) If reclaim is encountering an excessive number of pages
1463 * under writeback and this page is both under writeback and
1464 * PageReclaim then it indicates that pages are being queued
1465 * for IO but are being recycled through the LRU before the
1466 * IO can complete. Waiting on the page itself risks an
1467 * indefinite stall if it is impossible to writeback the
1468 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001469 * note that the LRU is being scanned too quickly and the
1470 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001471 *
Tejun Heo97c93412015-05-22 18:23:36 -04001472 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001473 * not marked for immediate reclaim, or the caller does not
1474 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1475 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001476 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001477 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001478 * Require may_enter_fs because we would wait on fs, which
1479 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001480 * enter reclaim, and deadlock if it waits on a page for
1481 * which it is needed to do the write (loop masks off
1482 * __GFP_IO|__GFP_FS for this reason); but more thought
1483 * would probably show more reasons.
1484 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001485 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001486 * PageReclaim. memcg does not have any dirty pages
1487 * throttling so we could easily OOM just because too many
1488 * pages are in writeback and there is nothing else to
1489 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001490 *
1491 * In cases 1) and 2) we activate the pages to get them out of
1492 * the way while we continue scanning for clean pages on the
1493 * inactive list and refilling from the active list. The
1494 * observation here is that waiting for disk writes is more
1495 * expensive than potentially causing reloads down the line.
1496 * Since they're marked for immediate reclaim, they won't put
1497 * memory pressure on the cache working set any longer than it
1498 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001499 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001500 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001501 /* Case 1 above */
1502 if (current_is_kswapd() &&
1503 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001504 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001505 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001506 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001507
1508 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001509 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001510 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001511 /*
1512 * This is slightly racy - end_page_writeback()
1513 * might have just cleared PageReclaim, then
1514 * setting PageReclaim here end up interpreted
1515 * as PageReadahead - but that does not matter
1516 * enough to care. What we do want is for this
1517 * page to have PageReclaim set next time memcg
1518 * reclaim reaches the tests above, so it will
1519 * then wait_on_page_writeback() to avoid OOM;
1520 * and it's also appropriate in global reclaim.
1521 */
1522 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001523 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001524 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001525
1526 /* Case 3 above */
1527 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001528 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001529 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001530 /* then go back and try same page again */
1531 list_add_tail(&page->lru, page_list);
1532 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001533 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001534 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001535
Minchan Kim8940b342019-09-25 16:49:11 -07001536 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001537 references = page_check_references(page, sc);
1538
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001539 switch (references) {
1540 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001541 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001542 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001543 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001544 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001545 case PAGEREF_RECLAIM:
1546 case PAGEREF_RECLAIM_CLEAN:
1547 ; /* try to reclaim the page below */
1548 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001549
Linus Torvalds1da177e2005-04-16 15:20:36 -07001550 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001551 * Before reclaiming the page, try to relocate
1552 * its contents to another node.
1553 */
1554 if (do_demote_pass &&
1555 (thp_migration_supported() || !PageTransHuge(page))) {
1556 list_add(&page->lru, &demote_pages);
1557 unlock_page(page);
1558 continue;
1559 }
1560
1561 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001562 * Anonymous process memory has backing store?
1563 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001564 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001565 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001566 if (PageAnon(page) && PageSwapBacked(page)) {
1567 if (!PageSwapCache(page)) {
1568 if (!(sc->gfp_mask & __GFP_IO))
1569 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001570 if (page_maybe_dma_pinned(page))
1571 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001572 if (PageTransHuge(page)) {
1573 /* cannot split THP, skip it */
1574 if (!can_split_huge_page(page, NULL))
1575 goto activate_locked;
1576 /*
1577 * Split pages without a PMD map right
1578 * away. Chances are some or all of the
1579 * tail pages can be freed without IO.
1580 */
1581 if (!compound_mapcount(page) &&
1582 split_huge_page_to_list(page,
1583 page_list))
1584 goto activate_locked;
1585 }
1586 if (!add_to_swap(page)) {
1587 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001588 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001589 /* Fallback to swap normal pages */
1590 if (split_huge_page_to_list(page,
1591 page_list))
1592 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001593#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1594 count_vm_event(THP_SWPOUT_FALLBACK);
1595#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001596 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001597 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001598 }
Minchan Kim0f074652017-07-06 15:37:24 -07001599
Kirill Tkhai4b793062020-04-01 21:10:18 -07001600 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001601
1602 /* Adding to swap updated mapping */
1603 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001604 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001605 } else if (unlikely(PageTransHuge(page))) {
1606 /* Split file THP */
1607 if (split_huge_page_to_list(page, page_list))
1608 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001609 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001610
1611 /*
Yang Shi98879b32019-07-11 20:59:30 -07001612 * THP may get split above, need minus tail pages and update
1613 * nr_pages to avoid accounting tail pages twice.
1614 *
1615 * The tail pages that are added into swap cache successfully
1616 * reach here.
1617 */
1618 if ((nr_pages > 1) && !PageTransHuge(page)) {
1619 sc->nr_scanned -= (nr_pages - 1);
1620 nr_pages = 1;
1621 }
1622
1623 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001624 * The page is mapped into the page tables of one or more
1625 * processes. Try to unmap it here.
1626 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001627 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001628 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001629 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001630
1631 if (unlikely(PageTransHuge(page)))
1632 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001633
Yang Shi1fb08ac2021-06-30 18:52:01 -07001634 try_to_unmap(page, flags);
1635 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001636 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001637 if (!was_swapbacked && PageSwapBacked(page))
1638 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001639 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001640 }
1641 }
1642
1643 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001644 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001645 * Only kswapd can writeback filesystem pages
1646 * to avoid risk of stack overflow. But avoid
1647 * injecting inefficient single-page IO into
1648 * flusher writeback as much as possible: only
1649 * write pages when we've encountered many
1650 * dirty pages, and when we've already scanned
1651 * the rest of the LRU for clean pages and see
1652 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001653 */
Huang Ying9de4f222020-04-06 20:04:41 -07001654 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001655 (!current_is_kswapd() || !PageReclaim(page) ||
1656 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001657 /*
1658 * Immediately reclaim when written back.
1659 * Similar in principal to deactivate_page()
1660 * except we already have the page isolated
1661 * and know it's dirty
1662 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001663 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001664 SetPageReclaim(page);
1665
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001666 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001667 }
1668
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001669 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001670 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001671 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001672 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001673 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001674 goto keep_locked;
1675
Mel Gormand950c942015-09-04 15:47:35 -07001676 /*
1677 * Page is dirty. Flush the TLB if a writable entry
1678 * potentially exists to avoid CPU writes after IO
1679 * starts and then write it out here.
1680 */
1681 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001682 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001683 case PAGE_KEEP:
1684 goto keep_locked;
1685 case PAGE_ACTIVATE:
1686 goto activate_locked;
1687 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001688 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001689
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001690 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001691 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001692 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001693 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001694
Linus Torvalds1da177e2005-04-16 15:20:36 -07001695 /*
1696 * A synchronous write - probably a ramdisk. Go
1697 * ahead and try to reclaim the page.
1698 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001699 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001700 goto keep;
1701 if (PageDirty(page) || PageWriteback(page))
1702 goto keep_locked;
1703 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001704 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001705 case PAGE_CLEAN:
1706 ; /* try to free the page below */
1707 }
1708 }
1709
1710 /*
1711 * If the page has buffers, try to free the buffer mappings
1712 * associated with this page. If we succeed we try to free
1713 * the page as well.
1714 *
1715 * We do this even if the page is PageDirty().
1716 * try_to_release_page() does not perform I/O, but it is
1717 * possible for a page to have PageDirty set, but it is actually
1718 * clean (all its buffers are clean). This happens if the
1719 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001720 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001721 * try_to_release_page() will discover that cleanness and will
1722 * drop the buffers and mark the page clean - it can be freed.
1723 *
1724 * Rarely, pages can have buffers and no ->mapping. These are
1725 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001726 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001727 * and if that worked, and the page is no longer mapped into
1728 * process address space (page_count == 1) it can be freed.
1729 * Otherwise, leave the page on the LRU so it is swappable.
1730 */
David Howells266cf652009-04-03 16:42:36 +01001731 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001732 if (!try_to_release_page(page, sc->gfp_mask))
1733 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001734 if (!mapping && page_count(page) == 1) {
1735 unlock_page(page);
1736 if (put_page_testzero(page))
1737 goto free_it;
1738 else {
1739 /*
1740 * rare race with speculative reference.
1741 * the speculative reference will free
1742 * this page shortly, so we may
1743 * increment nr_reclaimed here (and
1744 * leave it off the LRU).
1745 */
1746 nr_reclaimed++;
1747 continue;
1748 }
1749 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001750 }
1751
Shaohua Li802a3a92017-05-03 14:52:32 -07001752 if (PageAnon(page) && !PageSwapBacked(page)) {
1753 /* follow __remove_mapping for reference */
1754 if (!page_ref_freeze(page, 1))
1755 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001756 /*
1757 * The page has only one reference left, which is
1758 * from the isolation. After the caller puts the
1759 * page back on lru and drops the reference, the
1760 * page will be freed anyway. It doesn't matter
1761 * which lru it goes. So we don't bother checking
1762 * PageDirty here.
1763 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001764 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001765 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001766 } else if (!mapping || !__remove_mapping(mapping, page, true,
1767 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001768 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001769
1770 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001771free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001772 /*
1773 * THP may get swapped out in a whole, need account
1774 * all base pages.
1775 */
1776 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001777
1778 /*
1779 * Is there need to periodically free_page_list? It would
1780 * appear not as the counts should be low
1781 */
Yang Shi7ae88532019-09-23 15:38:09 -07001782 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001783 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001784 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001785 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001786 continue;
1787
Yang Shi98879b32019-07-11 20:59:30 -07001788activate_locked_split:
1789 /*
1790 * The tail pages that are failed to add into swap cache
1791 * reach here. Fixup nr_scanned and nr_pages.
1792 */
1793 if (nr_pages > 1) {
1794 sc->nr_scanned -= (nr_pages - 1);
1795 nr_pages = 1;
1796 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001797activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001798 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001799 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1800 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001801 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001802 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001803 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001804 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001805 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001806 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001807 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001808 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001809keep_locked:
1810 unlock_page(page);
1811keep:
1812 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001813 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001814 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001815 /* 'page_list' is always empty here */
1816
1817 /* Migrate pages selected for demotion */
1818 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1819 /* Pages that could not be demoted are still in @demote_pages */
1820 if (!list_empty(&demote_pages)) {
1821 /* Pages which failed to demoted go back on @page_list for retry: */
1822 list_splice_init(&demote_pages, page_list);
1823 do_demote_pass = false;
1824 goto retry;
1825 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001826
Yang Shi98879b32019-07-11 20:59:30 -07001827 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1828
Johannes Weiner747db952014-08-08 14:19:24 -07001829 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001830 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001831 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001832
Linus Torvalds1da177e2005-04-16 15:20:36 -07001833 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001834 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001835
Andrew Morton05ff5132006-03-22 00:08:20 -08001836 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001837}
1838
Maninder Singh730ec8c2020-06-03 16:01:18 -07001839unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001840 struct list_head *page_list)
1841{
1842 struct scan_control sc = {
1843 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001844 .may_unmap = 1,
1845 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001846 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001847 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001848 struct page *page, *next;
1849 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001850 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001851
1852 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001853 if (!PageHuge(page) && page_is_file_lru(page) &&
1854 !PageDirty(page) && !__PageMovable(page) &&
1855 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001856 ClearPageActive(page);
1857 list_move(&page->lru, &clean_pages);
1858 }
1859 }
1860
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001861 /*
1862 * We should be safe here since we are only dealing with file pages and
1863 * we are not kswapd and therefore cannot write dirty file pages. But
1864 * call memalloc_noreclaim_save() anyway, just in case these conditions
1865 * change in the future.
1866 */
1867 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001868 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001869 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001870 memalloc_noreclaim_restore(noreclaim_flag);
1871
Minchan Kim02c6de82012-10-08 16:31:55 -07001872 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001873 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1874 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001875 /*
1876 * Since lazyfree pages are isolated from file LRU from the beginning,
1877 * they will rotate back to anonymous LRU in the end if it failed to
1878 * discard so isolated count will be mismatched.
1879 * Compensate the isolated count for both LRU lists.
1880 */
1881 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1882 stat.nr_lazyfree_fail);
1883 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001884 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001885 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001886}
1887
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001888/*
1889 * Attempt to remove the specified page from its LRU. Only take this page
1890 * if it is of the appropriate PageActive status. Pages which are being
1891 * freed elsewhere are also ignored.
1892 *
1893 * page: page to consider
1894 * mode: one of the LRU isolation modes defined above
1895 *
Alex Shic2135f72021-02-24 12:08:01 -08001896 * returns true on success, false on failure.
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001897 */
Alex Shic2135f72021-02-24 12:08:01 -08001898bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001899{
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001900 /* Only take pages on the LRU. */
1901 if (!PageLRU(page))
Alex Shic2135f72021-02-24 12:08:01 -08001902 return false;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001903
Minchan Kime46a2872012-10-08 16:33:48 -07001904 /* Compaction should not handle unevictable pages but CMA can do so */
1905 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
Alex Shic2135f72021-02-24 12:08:01 -08001906 return false;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001907
Mel Gormanc8244932012-01-12 17:19:38 -08001908 /*
1909 * To minimise LRU disruption, the caller can indicate that it only
1910 * wants to isolate pages it will be able to operate on without
1911 * blocking - clean pages for the most part.
1912 *
Mel Gormanc8244932012-01-12 17:19:38 -08001913 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1914 * that it is possible to migrate without blocking
1915 */
Johannes Weiner1276ad62017-02-24 14:56:11 -08001916 if (mode & ISOLATE_ASYNC_MIGRATE) {
Mel Gormanc8244932012-01-12 17:19:38 -08001917 /* All the caller can do on PageWriteback is block */
1918 if (PageWriteback(page))
Alex Shic2135f72021-02-24 12:08:01 -08001919 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001920
1921 if (PageDirty(page)) {
1922 struct address_space *mapping;
Mel Gorman69d763f2018-01-31 16:19:52 -08001923 bool migrate_dirty;
Mel Gormanc8244932012-01-12 17:19:38 -08001924
Mel Gormanc8244932012-01-12 17:19:38 -08001925 /*
1926 * Only pages without mappings or that have a
1927 * ->migratepage callback are possible to migrate
Mel Gorman69d763f2018-01-31 16:19:52 -08001928 * without blocking. However, we can be racing with
1929 * truncation so it's necessary to lock the page
1930 * to stabilise the mapping as truncation holds
1931 * the page lock until after the page is removed
1932 * from the page cache.
Mel Gormanc8244932012-01-12 17:19:38 -08001933 */
Mel Gorman69d763f2018-01-31 16:19:52 -08001934 if (!trylock_page(page))
Alex Shic2135f72021-02-24 12:08:01 -08001935 return false;
Mel Gorman69d763f2018-01-31 16:19:52 -08001936
Mel Gormanc8244932012-01-12 17:19:38 -08001937 mapping = page_mapping(page);
Hugh Dickins145e1a72018-06-01 16:50:50 -07001938 migrate_dirty = !mapping || mapping->a_ops->migratepage;
Mel Gorman69d763f2018-01-31 16:19:52 -08001939 unlock_page(page);
1940 if (!migrate_dirty)
Alex Shic2135f72021-02-24 12:08:01 -08001941 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001942 }
1943 }
Minchan Kim39deaf82011-10-31 17:06:51 -07001944
Minchan Kimf80c0672011-10-31 17:06:55 -07001945 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
Alex Shic2135f72021-02-24 12:08:01 -08001946 return false;
Minchan Kimf80c0672011-10-31 17:06:55 -07001947
Alex Shic2135f72021-02-24 12:08:01 -08001948 return true;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001949}
1950
Mel Gorman7ee36a12016-07-28 15:47:17 -07001951/*
1952 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001953 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001954 */
1955static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001956 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001957{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001958 int zid;
1959
Mel Gorman7ee36a12016-07-28 15:47:17 -07001960 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1961 if (!nr_zone_taken[zid])
1962 continue;
1963
Wei Yanga892cb62020-06-03 16:01:12 -07001964 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001965 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001966
Mel Gorman7ee36a12016-07-28 15:47:17 -07001967}
1968
Mel Gormanf611fab2021-06-30 18:53:19 -07001969/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001970 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1971 *
1972 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001973 * shrink the lists perform better by taking out a batch of pages
1974 * and working on them outside the LRU lock.
1975 *
1976 * For pagecache intensive workloads, this function is the hottest
1977 * spot in the kernel (apart from copy_*_user functions).
1978 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001979 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001980 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001981 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001982 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001983 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001984 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001985 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001986 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001987 *
1988 * returns how many pages were moved onto *@dst.
1989 */
Andrew Morton69e05942006-03-22 00:08:19 -08001990static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001991 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001992 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001993 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001994{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001995 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001996 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001997 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001998 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07001999 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002000 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002001 LIST_HEAD(pages_skipped);
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002002 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002003
Yang Shi98879b32019-07-11 20:59:30 -07002004 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002005 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07002006 while (scan < nr_to_scan && !list_empty(src)) {
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002007 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002008
Linus Torvalds1da177e2005-04-16 15:20:36 -07002009 page = lru_to_page(src);
2010 prefetchw_prev_lru_page(page, src, flags);
2011
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002012 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002013 total_scan += nr_pages;
2014
Mel Gormanb2e18752016-07-28 15:45:37 -07002015 if (page_zonenum(page) > sc->reclaim_idx) {
2016 list_move(&page->lru, &pages_skipped);
Yang Shi98879b32019-07-11 20:59:30 -07002017 nr_skipped[page_zonenum(page)] += nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002018 continue;
2019 }
2020
Minchan Kim791b48b2017-05-12 15:47:06 -07002021 /*
2022 * Do not count skipped pages because that makes the function
2023 * return with no isolated pages if the LRU mostly contains
2024 * ineligible pages. This causes the VM to not reclaim any
2025 * pages, triggering a premature OOM.
Yang Shi98879b32019-07-11 20:59:30 -07002026 *
2027 * Account all tail pages of THP. This would not cause
2028 * premature OOM since __isolate_lru_page() returns -EBUSY
2029 * only when the page is being freed somewhere else.
Minchan Kim791b48b2017-05-12 15:47:06 -07002030 */
Yang Shi98879b32019-07-11 20:59:30 -07002031 scan += nr_pages;
Alex Shic2135f72021-02-24 12:08:01 -08002032 if (!__isolate_lru_page_prepare(page, mode)) {
2033 /* It is being freed elsewhere */
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002034 list_move(&page->lru, src);
Alex Shic2135f72021-02-24 12:08:01 -08002035 continue;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002036 }
Alex Shic2135f72021-02-24 12:08:01 -08002037 /*
2038 * Be careful not to clear PageLRU until after we're
2039 * sure the page is not being freed elsewhere -- the
2040 * page release code relies on it.
2041 */
2042 if (unlikely(!get_page_unless_zero(page))) {
2043 list_move(&page->lru, src);
2044 continue;
2045 }
2046
2047 if (!TestClearPageLRU(page)) {
2048 /* Another thread is already isolating this page */
2049 put_page(page);
2050 list_move(&page->lru, src);
2051 continue;
2052 }
2053
2054 nr_taken += nr_pages;
2055 nr_zone_taken[page_zonenum(page)] += nr_pages;
2056 list_move(&page->lru, dst);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002057 }
2058
Mel Gormanb2e18752016-07-28 15:45:37 -07002059 /*
2060 * Splice any skipped pages to the start of the LRU list. Note that
2061 * this disrupts the LRU order when reclaiming for lower zones but
2062 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2063 * scanning would soon rescan the same pages to skip and put the
2064 * system at risk of premature OOM.
2065 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002066 if (!list_empty(&pages_skipped)) {
2067 int zid;
2068
Johannes Weiner3db65812017-05-03 14:52:13 -07002069 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002070 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2071 if (!nr_skipped[zid])
2072 continue;
2073
2074 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002075 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002076 }
2077 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002078 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002079 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Minchan Kim791b48b2017-05-12 15:47:06 -07002080 total_scan, skipped, nr_taken, mode, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002081 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002082 return nr_taken;
2083}
2084
Nick Piggin62695a82008-10-18 20:26:09 -07002085/**
2086 * isolate_lru_page - tries to isolate a page from its LRU list
2087 * @page: page to isolate from its LRU list
2088 *
2089 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2090 * vmstat statistic corresponding to whatever LRU list the page was on.
2091 *
2092 * Returns 0 if the page was removed from an LRU list.
2093 * Returns -EBUSY if the page was not on an LRU list.
2094 *
2095 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002096 * the active list, it will have PageActive set. If it was found on
2097 * the unevictable list, it will have the PageUnevictable bit set. That flag
2098 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002099 *
2100 * The vmstat statistic corresponding to the list on which the page was
2101 * found will be decremented.
2102 *
2103 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002104 *
Nick Piggin62695a82008-10-18 20:26:09 -07002105 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002106 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002107 * without a stable reference).
2108 * (2) the lru_lock must not be held.
2109 * (3) interrupts must be enabled.
2110 */
2111int isolate_lru_page(struct page *page)
2112{
2113 int ret = -EBUSY;
2114
Sasha Levin309381fea2014-01-23 15:52:54 -08002115 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002116 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002117
Alex Shid25b5bd2020-12-15 12:34:16 -08002118 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002119 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002120
Alex Shid25b5bd2020-12-15 12:34:16 -08002121 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002122 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002123 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002124 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002125 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002126 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002127
Nick Piggin62695a82008-10-18 20:26:09 -07002128 return ret;
2129}
2130
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002131/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002132 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002133 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002134 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2135 * the LRU list will go small and be scanned faster than necessary, leading to
2136 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002137 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002138static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002139 struct scan_control *sc)
2140{
2141 unsigned long inactive, isolated;
2142
2143 if (current_is_kswapd())
2144 return 0;
2145
Johannes Weinerb5ead352019-11-30 17:55:40 -08002146 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002147 return 0;
2148
2149 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002150 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2151 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002152 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002153 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2154 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002155 }
2156
Fengguang Wu3cf23842012-12-18 14:23:31 -08002157 /*
2158 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2159 * won't get blocked by normal direct-reclaimers, forming a circular
2160 * deadlock.
2161 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002162 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002163 inactive >>= 3;
2164
Rik van Riel35cd7812009-09-21 17:01:38 -07002165 return isolated > inactive;
2166}
2167
Kirill Tkhaia222f342019-05-13 17:17:00 -07002168/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002169 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2170 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002171 *
2172 * Returns the number of pages moved to the given lruvec.
2173 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002174static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2175 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002176{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002177 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002178 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002179 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002180
Kirill Tkhaia222f342019-05-13 17:17:00 -07002181 while (!list_empty(list)) {
2182 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002183 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002184 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002185 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002186 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002187 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002188 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002189 continue;
2190 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002191
Alex Shi3d06afa2020-12-15 12:33:37 -08002192 /*
2193 * The SetPageLRU needs to be kept here for list integrity.
2194 * Otherwise:
2195 * #0 move_pages_to_lru #1 release_pages
2196 * if !put_page_testzero
2197 * if (put_page_testzero())
2198 * !PageLRU //skip lru_lock
2199 * SetPageLRU()
2200 * list_add(&page->lru,)
2201 * list_add(&page->lru,)
2202 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002203 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002204
Alex Shi3d06afa2020-12-15 12:33:37 -08002205 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002206 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002207
2208 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002209 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002210 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002211 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002212 } else
2213 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002214
2215 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002216 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002217
Alex Shiafca9152020-12-15 12:34:02 -08002218 /*
2219 * All pages were isolated from the same lruvec (and isolation
2220 * inhibits memcg migration).
2221 */
Muchun Song7467c392021-06-28 19:37:59 -07002222 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002223 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002224 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002225 nr_moved += nr_pages;
2226 if (PageActive(page))
2227 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002228 }
Mel Gorman66635622010-08-09 17:19:30 -07002229
Hugh Dickins3f797682012-01-12 17:20:07 -08002230 /*
2231 * To save our caller's stack, now use input list for pages to free.
2232 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002233 list_splice(&pages_to_free, list);
2234
2235 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002236}
2237
2238/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002239 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002240 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002241 * In that case we should only throttle if the backing device it is
2242 * writing to is congested. In other cases it is safe to throttle.
2243 */
2244static int current_may_throttle(void)
2245{
NeilBrowna37b0712020-06-01 21:48:18 -07002246 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002247 current->backing_dev_info == NULL ||
2248 bdi_write_congested(current->backing_dev_info);
2249}
2250
2251/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002252 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002253 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002254 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002255static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002256shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002257 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002258{
2259 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002260 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002261 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002262 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002263 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002264 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002265 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002266 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002267 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002268
Mel Gorman599d0c92016-07-28 15:45:31 -07002269 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002270 if (stalled)
2271 return 0;
2272
2273 /* wait a bit for the reclaimer. */
2274 msleep(100);
2275 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002276
2277 /* We are about to die and free our memory. Return now. */
2278 if (fatal_signal_pending(current))
2279 return SWAP_CLUSTER_MAX;
2280 }
2281
Linus Torvalds1da177e2005-04-16 15:20:36 -07002282 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002283
Alex Shi6168d0d2020-12-15 12:34:29 -08002284 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002285
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002286 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002287 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002288
Mel Gorman599d0c92016-07-28 15:45:31 -07002289 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002290 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002291 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002292 __count_vm_events(item, nr_scanned);
2293 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002294 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2295
Alex Shi6168d0d2020-12-15 12:34:29 -08002296 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002297
Hillf Dantond563c052012-03-21 16:34:02 -07002298 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002299 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002300
Shakeel Butt013339d2020-12-14 19:06:39 -08002301 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002302
Alex Shi6168d0d2020-12-15 12:34:29 -08002303 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002304 move_pages_to_lru(lruvec, &page_list);
2305
2306 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002307 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002308 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002309 __count_vm_events(item, nr_reclaimed);
2310 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002311 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002312 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002313
Alex Shi75cc3c92020-12-15 14:20:50 -08002314 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002315 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002316 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002317
Mel Gorman92df3a72011-10-31 17:07:56 -07002318 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002319 * If dirty pages are scanned that are not queued for IO, it
2320 * implies that flushers are not doing their job. This can
2321 * happen when memory pressure pushes dirty pages to the end of
2322 * the LRU before the dirty limits are breached and the dirty
2323 * data has expired. It can also happen when the proportion of
2324 * dirty pages grows not through writes but through memory
2325 * pressure reclaiming all the clean cache. And in some cases,
2326 * the flushers simply cannot keep up with the allocation
2327 * rate. Nudge the flusher threads in case they are asleep.
2328 */
2329 if (stat.nr_unqueued_dirty == nr_taken)
2330 wakeup_flusher_threads(WB_REASON_VMSCAN);
2331
Andrey Ryabinind108c772018-04-10 16:27:59 -07002332 sc->nr.dirty += stat.nr_dirty;
2333 sc->nr.congested += stat.nr_congested;
2334 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2335 sc->nr.writeback += stat.nr_writeback;
2336 sc->nr.immediate += stat.nr_immediate;
2337 sc->nr.taken += nr_taken;
2338 if (file)
2339 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002340
Mel Gorman599d0c92016-07-28 15:45:31 -07002341 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002342 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002343 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002344}
2345
Hugh Dickins15b44732020-12-15 14:21:31 -08002346/*
2347 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2348 *
2349 * We move them the other way if the page is referenced by one or more
2350 * processes.
2351 *
2352 * If the pages are mostly unmapped, the processing is fast and it is
2353 * appropriate to hold lru_lock across the whole operation. But if
2354 * the pages are mapped, the processing is slow (page_referenced()), so
2355 * we should drop lru_lock around each page. It's impossible to balance
2356 * this, so instead we remove the pages from the LRU while processing them.
2357 * It is safe to rely on PG_active against the non-LRU pages in here because
2358 * nobody will play with that bit on a non-LRU page.
2359 *
2360 * The downside is that we have to touch page->_refcount against each page.
2361 * But we had to alter page->flags anyway.
2362 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002363static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002364 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002365 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002366 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002367{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002368 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002369 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002370 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002371 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002372 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002373 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002374 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002375 unsigned nr_deactivate, nr_activate;
2376 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002377 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002378 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002379 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002380
2381 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002382
Alex Shi6168d0d2020-12-15 12:34:29 -08002383 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002384
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002385 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002386 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002387
Mel Gorman599d0c92016-07-28 15:45:31 -07002388 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002389
Shakeel Butt912c0572020-08-06 23:26:32 -07002390 if (!cgroup_reclaim(sc))
2391 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002392 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002393
Alex Shi6168d0d2020-12-15 12:34:29 -08002394 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002395
Linus Torvalds1da177e2005-04-16 15:20:36 -07002396 while (!list_empty(&l_hold)) {
2397 cond_resched();
2398 page = lru_to_page(&l_hold);
2399 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002400
Hugh Dickins39b5f292012-10-08 16:33:18 -07002401 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002402 putback_lru_page(page);
2403 continue;
2404 }
2405
Mel Gormancc715d92012-03-21 16:34:00 -07002406 if (unlikely(buffer_heads_over_limit)) {
2407 if (page_has_private(page) && trylock_page(page)) {
2408 if (page_has_private(page))
2409 try_to_release_page(page, 0);
2410 unlock_page(page);
2411 }
2412 }
2413
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002414 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2415 if (bypass)
2416 goto skip_page_referenced;
2417
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002418 if (page_referenced(page, 0, sc->target_mem_cgroup,
2419 &vm_flags)) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002420 /*
2421 * Identify referenced, file-backed active pages and
2422 * give them one more trip around the active list. So
2423 * that executable code get better chances to stay in
2424 * memory under moderate memory pressure. Anon pages
2425 * are not likely to be evicted by use-once streaming
2426 * IO, plus JVM can create lots of anon VM_EXEC pages,
2427 * so we ignore them here.
2428 */
Huang Ying9de4f222020-04-06 20:04:41 -07002429 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002430 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002431 list_add(&page->lru, &l_active);
2432 continue;
2433 }
2434 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002435skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002436 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002437 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002438 list_add(&page->lru, &l_inactive);
2439 }
2440
Andrew Mortonb5557492009-01-06 14:40:13 -08002441 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002442 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002443 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002444 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002445
Kirill Tkhaia222f342019-05-13 17:17:00 -07002446 nr_activate = move_pages_to_lru(lruvec, &l_active);
2447 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002448 /* Keep all free pages in l_active list */
2449 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002450
2451 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2452 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2453
Mel Gorman599d0c92016-07-28 15:45:31 -07002454 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002455 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002456
Kirill Tkhaif372d892019-05-13 17:16:57 -07002457 mem_cgroup_uncharge_list(&l_active);
2458 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002459 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2460 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002461}
2462
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002463unsigned long reclaim_pages(struct list_head *page_list)
2464{
Yang Shif661d002020-04-01 21:10:05 -07002465 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002466 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002467 LIST_HEAD(node_page_list);
2468 struct reclaim_stat dummy_stat;
2469 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002470 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002471 struct scan_control sc = {
2472 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002473 .may_writepage = 1,
2474 .may_unmap = 1,
2475 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002476 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002477 };
2478
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002479 noreclaim_flag = memalloc_noreclaim_save();
2480
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002481 while (!list_empty(page_list)) {
2482 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002483 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002484 nid = page_to_nid(page);
2485 INIT_LIST_HEAD(&node_page_list);
2486 }
2487
2488 if (nid == page_to_nid(page)) {
2489 ClearPageActive(page);
2490 list_move(&page->lru, &node_page_list);
2491 continue;
2492 }
2493
2494 nr_reclaimed += shrink_page_list(&node_page_list,
2495 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002496 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002497 while (!list_empty(&node_page_list)) {
2498 page = lru_to_page(&node_page_list);
2499 list_del(&page->lru);
2500 putback_lru_page(page);
2501 }
2502
Yang Shif661d002020-04-01 21:10:05 -07002503 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002504 }
2505
2506 if (!list_empty(&node_page_list)) {
2507 nr_reclaimed += shrink_page_list(&node_page_list,
2508 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002509 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002510 while (!list_empty(&node_page_list)) {
2511 page = lru_to_page(&node_page_list);
2512 list_del(&page->lru);
2513 putback_lru_page(page);
2514 }
2515 }
2516
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002517 memalloc_noreclaim_restore(noreclaim_flag);
2518
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002519 return nr_reclaimed;
2520}
2521
Johannes Weinerb91ac372019-11-30 17:56:02 -08002522static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2523 struct lruvec *lruvec, struct scan_control *sc)
2524{
2525 if (is_active_lru(lru)) {
2526 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2527 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2528 else
2529 sc->skipped_deactivate = 1;
2530 return 0;
2531 }
2532
2533 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2534}
2535
Rik van Riel59dc76b2016-05-20 16:56:31 -07002536/*
2537 * The inactive anon list should be small enough that the VM never has
2538 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002539 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002540 * The inactive file list should be small enough to leave most memory
2541 * to the established workingset on the scan-resistant active list,
2542 * but large enough to avoid thrashing the aggregate readahead window.
2543 *
2544 * Both inactive lists should also be large enough that each inactive
2545 * page has a chance to be referenced again before it is reclaimed.
2546 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002547 * If that fails and refaulting is observed, the inactive list grows.
2548 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002549 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002550 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002551 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2552 *
2553 * total target max
2554 * memory ratio inactive
2555 * -------------------------------------
2556 * 10MB 1 5MB
2557 * 100MB 1 50MB
2558 * 1GB 3 250MB
2559 * 10GB 10 0.9GB
2560 * 100GB 31 3GB
2561 * 1TB 101 10GB
2562 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002563 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002564static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002565{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002566 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002567 unsigned long inactive, active;
2568 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002569 unsigned long gb;
2570
Johannes Weinerb91ac372019-11-30 17:56:02 -08002571 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2572 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002573
Johannes Weinerb91ac372019-11-30 17:56:02 -08002574 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002575 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002576 inactive_ratio = int_sqrt(10 * gb);
2577 else
2578 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002579
Rik van Riel59dc76b2016-05-20 16:56:31 -07002580 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002581}
2582
Johannes Weiner9a265112013-02-22 16:32:17 -08002583enum scan_balance {
2584 SCAN_EQUAL,
2585 SCAN_FRACT,
2586 SCAN_ANON,
2587 SCAN_FILE,
2588};
2589
Yu Zhao6d313442022-09-18 02:00:00 -06002590static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2591{
2592 unsigned long file;
2593 struct lruvec *target_lruvec;
2594
Yu Zhao37397872022-09-18 02:00:03 -06002595 if (lru_gen_enabled())
2596 return;
2597
Yu Zhao6d313442022-09-18 02:00:00 -06002598 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2599
2600 /*
2601 * Flush the memory cgroup stats, so that we read accurate per-memcg
2602 * lruvec stats for heuristics.
2603 */
2604 mem_cgroup_flush_stats();
2605
2606 /*
2607 * Determine the scan balance between anon and file LRUs.
2608 */
2609 spin_lock_irq(&target_lruvec->lru_lock);
2610 sc->anon_cost = target_lruvec->anon_cost;
2611 sc->file_cost = target_lruvec->file_cost;
2612 spin_unlock_irq(&target_lruvec->lru_lock);
2613
2614 /*
2615 * Target desirable inactive:active list ratios for the anon
2616 * and file LRU lists.
2617 */
2618 if (!sc->force_deactivate) {
2619 unsigned long refaults;
2620
2621 refaults = lruvec_page_state(target_lruvec,
2622 WORKINGSET_ACTIVATE_ANON);
2623 if (refaults != target_lruvec->refaults[0] ||
2624 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2625 sc->may_deactivate |= DEACTIVATE_ANON;
2626 else
2627 sc->may_deactivate &= ~DEACTIVATE_ANON;
2628
2629 /*
2630 * When refaults are being observed, it means a new
2631 * workingset is being established. Deactivate to get
2632 * rid of any stale active pages quickly.
2633 */
2634 refaults = lruvec_page_state(target_lruvec,
2635 WORKINGSET_ACTIVATE_FILE);
2636 if (refaults != target_lruvec->refaults[1] ||
2637 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2638 sc->may_deactivate |= DEACTIVATE_FILE;
2639 else
2640 sc->may_deactivate &= ~DEACTIVATE_FILE;
2641 } else
2642 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2643
2644 /*
2645 * If we have plenty of inactive file pages that aren't
2646 * thrashing, try to reclaim those first before touching
2647 * anonymous pages.
2648 */
2649 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2650 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2651 sc->cache_trim_mode = 1;
2652 else
2653 sc->cache_trim_mode = 0;
2654
2655 /*
2656 * Prevent the reclaimer from falling into the cache trap: as
2657 * cache pages start out inactive, every cache fault will tip
2658 * the scan balance towards the file LRU. And as the file LRU
2659 * shrinks, so does the window for rotation from references.
2660 * This means we have a runaway feedback loop where a tiny
2661 * thrashing file LRU becomes infinitely more attractive than
2662 * anon pages. Try to detect this based on file LRU size.
2663 */
2664 if (!cgroup_reclaim(sc)) {
2665 unsigned long total_high_wmark = 0;
2666 unsigned long free, anon;
2667 int z;
2668
2669 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2670 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2671 node_page_state(pgdat, NR_INACTIVE_FILE);
2672
2673 for (z = 0; z < MAX_NR_ZONES; z++) {
2674 struct zone *zone = &pgdat->node_zones[z];
2675
2676 if (!managed_zone(zone))
2677 continue;
2678
2679 total_high_wmark += high_wmark_pages(zone);
2680 }
2681
2682 /*
2683 * Consider anon: if that's low too, this isn't a
2684 * runaway file reclaim problem, but rather just
2685 * extreme pressure. Reclaim as per usual then.
2686 */
2687 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2688
2689 sc->file_is_tiny =
2690 file + free <= total_high_wmark &&
2691 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2692 anon >> sc->priority;
2693 }
2694}
2695
Linus Torvalds1da177e2005-04-16 15:20:36 -07002696/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002697 * Determine how aggressively the anon and file LRU lists should be
2698 * scanned. The relative value of each set of LRU lists is determined
2699 * by looking at the fraction of the pages scanned we did rotate back
2700 * onto the active list instead of evict.
2701 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002702 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2703 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002704 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002705static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2706 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002707{
Keith Buscha2a36482021-09-02 14:59:26 -07002708 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002709 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002710 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002711 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002712 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002713 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002714 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002715 unsigned long ap, fp;
2716 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002717 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002718
2719 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002720 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002721 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002722 goto out;
2723 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002724
Johannes Weiner10316b32013-02-22 16:32:14 -08002725 /*
2726 * Global reclaim will swap to prevent OOM even with no
2727 * swappiness, but memcg users want to use this knob to
2728 * disable swapping for individual groups completely when
2729 * using the memory controller's swap limit feature would be
2730 * too expensive.
2731 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002732 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002733 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002734 goto out;
2735 }
2736
2737 /*
2738 * Do not apply any pressure balancing cleverness when the
2739 * system is close to OOM, scan both anon and file equally
2740 * (unless the swappiness setting disagrees with swapping).
2741 */
Johannes Weiner02695172014-08-06 16:06:17 -07002742 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002743 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002744 goto out;
2745 }
2746
Johannes Weiner11d16c22013-02-22 16:32:15 -08002747 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002748 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002749 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002750 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002751 scan_balance = SCAN_ANON;
2752 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002753 }
2754
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002755 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2756
Johannes Weiner62376252014-05-06 12:50:07 -07002757 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002758 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002759 * anything from the anonymous working right now. But when balancing
2760 * anon and page cache files for reclaim, allow swapping of anon pages
2761 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002762 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002763 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002764 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002765 goto out;
2766 }
2767
Johannes Weiner9a265112013-02-22 16:32:17 -08002768 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002769 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002770 * Calculate the pressure balance between anon and file pages.
2771 *
2772 * The amount of pressure we put on each LRU is inversely
2773 * proportional to the cost of reclaiming each list, as
2774 * determined by the share of pages that are refaulting, times
2775 * the relative IO cost of bringing back a swapped out
2776 * anonymous page vs reloading a filesystem page (swappiness).
2777 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002778 * Although we limit that influence to ensure no list gets
2779 * left behind completely: at least a third of the pressure is
2780 * applied, before swappiness.
2781 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002782 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002783 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002784 total_cost = sc->anon_cost + sc->file_cost;
2785 anon_cost = total_cost + sc->anon_cost;
2786 file_cost = total_cost + sc->file_cost;
2787 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002788
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002789 ap = swappiness * (total_cost + 1);
2790 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002791
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002792 fp = (200 - swappiness) * (total_cost + 1);
2793 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002794
Shaohua Li76a33fc2010-05-24 14:32:36 -07002795 fraction[0] = ap;
2796 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002797 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002798out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002799 for_each_evictable_lru(lru) {
2800 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002801 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002802 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002803 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002804
Chris Down9783aa92019-10-06 17:58:32 -07002805 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002806 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2807 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002808
Johannes Weinerf56ce412021-08-19 19:04:21 -07002809 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002810 /*
2811 * Scale a cgroup's reclaim pressure by proportioning
2812 * its current usage to its memory.low or memory.min
2813 * setting.
2814 *
2815 * This is important, as otherwise scanning aggression
2816 * becomes extremely binary -- from nothing as we
2817 * approach the memory protection threshold, to totally
2818 * nominal as we exceed it. This results in requiring
2819 * setting extremely liberal protection thresholds. It
2820 * also means we simply get no protection at all if we
2821 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002822 *
2823 * If there is any protection in place, we reduce scan
2824 * pressure by how much of the total memory used is
2825 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002826 *
Chris Down9de7ca42019-10-06 17:58:35 -07002827 * There is one special case: in the first reclaim pass,
2828 * we skip over all groups that are within their low
2829 * protection. If that fails to reclaim enough pages to
2830 * satisfy the reclaim goal, we come back and override
2831 * the best-effort low protection. However, we still
2832 * ideally want to honor how well-behaved groups are in
2833 * that case instead of simply punishing them all
2834 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002835 * memory they are using, reducing the scan pressure
2836 * again by how much of the total memory used is under
2837 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002838 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002839 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002840 unsigned long protection;
2841
2842 /* memory.low scaling, make sure we retry before OOM */
2843 if (!sc->memcg_low_reclaim && low > min) {
2844 protection = low;
2845 sc->memcg_low_skipped = 1;
2846 } else {
2847 protection = min;
2848 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002849
2850 /* Avoid TOCTOU with earlier protection check */
2851 cgroup_size = max(cgroup_size, protection);
2852
2853 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002854 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002855
2856 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002857 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002858 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002859 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002860 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002861 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002862 } else {
2863 scan = lruvec_size;
2864 }
2865
2866 scan >>= sc->priority;
2867
Johannes Weiner688035f2017-05-03 14:52:07 -07002868 /*
2869 * If the cgroup's already been deleted, make sure to
2870 * scrape out the remaining cache.
2871 */
2872 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002873 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002874
Johannes Weiner688035f2017-05-03 14:52:07 -07002875 switch (scan_balance) {
2876 case SCAN_EQUAL:
2877 /* Scan lists relative to size */
2878 break;
2879 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002880 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002881 * Scan types proportional to swappiness and
2882 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002883 * Make sure we don't miss the last page on
2884 * the offlined memory cgroups because of a
2885 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002886 */
Gavin Shan76073c62020-02-20 20:04:24 -08002887 scan = mem_cgroup_online(memcg) ?
2888 div64_u64(scan * fraction[file], denominator) :
2889 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002890 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002891 break;
2892 case SCAN_FILE:
2893 case SCAN_ANON:
2894 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002895 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002896 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002897 break;
2898 default:
2899 /* Look ma, no brain */
2900 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002901 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002902
Johannes Weiner688035f2017-05-03 14:52:07 -07002903 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002904 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002905}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002906
Dave Hansen2f368a92021-09-02 14:59:23 -07002907/*
2908 * Anonymous LRU management is a waste if there is
2909 * ultimately no way to reclaim the memory.
2910 */
2911static bool can_age_anon_pages(struct pglist_data *pgdat,
2912 struct scan_control *sc)
2913{
2914 /* Aging the anon LRU is valuable if swap is present: */
2915 if (total_swap_pages > 0)
2916 return true;
2917
2918 /* Also valuable if anon pages can be demoted: */
2919 return can_demote(pgdat->node_id, sc);
2920}
2921
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002922#ifdef CONFIG_LRU_GEN
2923
2924/******************************************************************************
2925 * shorthand helpers
2926 ******************************************************************************/
2927
Yu Zhao37397872022-09-18 02:00:03 -06002928#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2929
2930#define DEFINE_MAX_SEQ(lruvec) \
2931 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2932
2933#define DEFINE_MIN_SEQ(lruvec) \
2934 unsigned long min_seq[ANON_AND_FILE] = { \
2935 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2936 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2937 }
2938
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002939#define for_each_gen_type_zone(gen, type, zone) \
2940 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2941 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2942 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2943
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002944static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002945{
2946 struct pglist_data *pgdat = NODE_DATA(nid);
2947
2948#ifdef CONFIG_MEMCG
2949 if (memcg) {
2950 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2951
2952 /* for hotadd_new_pgdat() */
2953 if (!lruvec->pgdat)
2954 lruvec->pgdat = pgdat;
2955
2956 return lruvec;
2957 }
2958#endif
2959 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2960
2961 return pgdat ? &pgdat->__lruvec : NULL;
2962}
2963
Yu Zhao37397872022-09-18 02:00:03 -06002964static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2965{
2966 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2967 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2968
2969 if (!can_demote(pgdat->node_id, sc) &&
2970 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2971 return 0;
2972
2973 return mem_cgroup_swappiness(memcg);
2974}
2975
2976static int get_nr_gens(struct lruvec *lruvec, int type)
2977{
2978 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2979}
2980
2981static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2982{
2983 /* see the comment on lru_gen_struct */
2984 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2985 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2986 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2987}
2988
2989/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002990 * mm_struct list
2991 ******************************************************************************/
2992
2993static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
2994{
2995 static struct lru_gen_mm_list mm_list = {
2996 .fifo = LIST_HEAD_INIT(mm_list.fifo),
2997 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
2998 };
2999
3000#ifdef CONFIG_MEMCG
3001 if (memcg)
3002 return &memcg->mm_list;
3003#endif
3004 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3005
3006 return &mm_list;
3007}
3008
3009void lru_gen_add_mm(struct mm_struct *mm)
3010{
3011 int nid;
3012 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3013 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3014
3015 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3016#ifdef CONFIG_MEMCG
3017 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3018 mm->lru_gen.memcg = memcg;
3019#endif
3020 spin_lock(&mm_list->lock);
3021
3022 for_each_node_state(nid, N_MEMORY) {
3023 struct lruvec *lruvec = get_lruvec(memcg, nid);
3024
3025 if (!lruvec)
3026 continue;
3027
3028 /* the first addition since the last iteration */
3029 if (lruvec->mm_state.tail == &mm_list->fifo)
3030 lruvec->mm_state.tail = &mm->lru_gen.list;
3031 }
3032
3033 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3034
3035 spin_unlock(&mm_list->lock);
3036}
3037
3038void lru_gen_del_mm(struct mm_struct *mm)
3039{
3040 int nid;
3041 struct lru_gen_mm_list *mm_list;
3042 struct mem_cgroup *memcg = NULL;
3043
3044 if (list_empty(&mm->lru_gen.list))
3045 return;
3046
3047#ifdef CONFIG_MEMCG
3048 memcg = mm->lru_gen.memcg;
3049#endif
3050 mm_list = get_mm_list(memcg);
3051
3052 spin_lock(&mm_list->lock);
3053
3054 for_each_node(nid) {
3055 struct lruvec *lruvec = get_lruvec(memcg, nid);
3056
3057 if (!lruvec)
3058 continue;
3059
3060 /* where the last iteration ended (exclusive) */
3061 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3062 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3063
3064 /* where the current iteration continues (inclusive) */
3065 if (lruvec->mm_state.head != &mm->lru_gen.list)
3066 continue;
3067
3068 lruvec->mm_state.head = lruvec->mm_state.head->next;
3069 /* the deletion ends the current iteration */
3070 if (lruvec->mm_state.head == &mm_list->fifo)
3071 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3072 }
3073
3074 list_del_init(&mm->lru_gen.list);
3075
3076 spin_unlock(&mm_list->lock);
3077
3078#ifdef CONFIG_MEMCG
3079 mem_cgroup_put(mm->lru_gen.memcg);
3080 mm->lru_gen.memcg = NULL;
3081#endif
3082}
3083
3084#ifdef CONFIG_MEMCG
3085void lru_gen_migrate_mm(struct mm_struct *mm)
3086{
3087 struct mem_cgroup *memcg;
3088 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3089
3090 VM_WARN_ON_ONCE(task->mm != mm);
3091 lockdep_assert_held(&task->alloc_lock);
3092
3093 /* for mm_update_next_owner() */
3094 if (mem_cgroup_disabled())
3095 return;
3096
3097 rcu_read_lock();
3098 memcg = mem_cgroup_from_task(task);
3099 rcu_read_unlock();
3100 if (memcg == mm->lru_gen.memcg)
3101 return;
3102
3103 VM_WARN_ON_ONCE(!mm->lru_gen.memcg);
3104 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3105
3106 lru_gen_del_mm(mm);
3107 lru_gen_add_mm(mm);
3108}
3109#endif
3110
3111/*
3112 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3113 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3114 * bits in a bitmap, k is the number of hash functions and n is the number of
3115 * inserted items.
3116 *
3117 * Page table walkers use one of the two filters to reduce their search space.
3118 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3119 * aging uses the double-buffering technique to flip to the other filter each
3120 * time it produces a new generation. For non-leaf entries that have enough
3121 * leaf entries, the aging carries them over to the next generation in
3122 * walk_pmd_range(); the eviction also report them when walking the rmap
3123 * in lru_gen_look_around().
3124 *
3125 * For future optimizations:
3126 * 1. It's not necessary to keep both filters all the time. The spare one can be
3127 * freed after the RCU grace period and reallocated if needed again.
3128 * 2. And when reallocating, it's worth scaling its size according to the number
3129 * of inserted entries in the other filter, to reduce the memory overhead on
3130 * small systems and false positives on large systems.
3131 * 3. Jenkins' hash function is an alternative to Knuth's.
3132 */
3133#define BLOOM_FILTER_SHIFT 15
3134
3135static inline int filter_gen_from_seq(unsigned long seq)
3136{
3137 return seq % NR_BLOOM_FILTERS;
3138}
3139
3140static void get_item_key(void *item, int *key)
3141{
3142 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3143
3144 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3145
3146 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3147 key[1] = hash >> BLOOM_FILTER_SHIFT;
3148}
3149
3150static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3151{
3152 unsigned long *filter;
3153 int gen = filter_gen_from_seq(seq);
3154
3155 filter = lruvec->mm_state.filters[gen];
3156 if (filter) {
3157 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3158 return;
3159 }
3160
3161 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3162 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3163 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3164}
3165
3166static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3167{
3168 int key[2];
3169 unsigned long *filter;
3170 int gen = filter_gen_from_seq(seq);
3171
3172 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3173 if (!filter)
3174 return;
3175
3176 get_item_key(item, key);
3177
3178 if (!test_bit(key[0], filter))
3179 set_bit(key[0], filter);
3180 if (!test_bit(key[1], filter))
3181 set_bit(key[1], filter);
3182}
3183
3184static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3185{
3186 int key[2];
3187 unsigned long *filter;
3188 int gen = filter_gen_from_seq(seq);
3189
3190 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3191 if (!filter)
3192 return true;
3193
3194 get_item_key(item, key);
3195
3196 return test_bit(key[0], filter) && test_bit(key[1], filter);
3197}
3198
3199static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3200{
3201 int i;
3202 int hist;
3203
3204 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3205
3206 if (walk) {
3207 hist = lru_hist_from_seq(walk->max_seq);
3208
3209 for (i = 0; i < NR_MM_STATS; i++) {
3210 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3211 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3212 walk->mm_stats[i] = 0;
3213 }
3214 }
3215
3216 if (NR_HIST_GENS > 1 && last) {
3217 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3218
3219 for (i = 0; i < NR_MM_STATS; i++)
3220 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3221 }
3222}
3223
3224static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3225{
3226 int type;
3227 unsigned long size = 0;
3228 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3229 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3230
3231 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3232 return true;
3233
3234 clear_bit(key, &mm->lru_gen.bitmap);
3235
3236 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3237 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3238 get_mm_counter(mm, MM_ANONPAGES) +
3239 get_mm_counter(mm, MM_SHMEMPAGES);
3240 }
3241
3242 if (size < MIN_LRU_BATCH)
3243 return true;
3244
3245 return !mmget_not_zero(mm);
3246}
3247
3248static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3249 struct mm_struct **iter)
3250{
3251 bool first = false;
3252 bool last = true;
3253 struct mm_struct *mm = NULL;
3254 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3255 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3256 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3257
3258 /*
3259 * There are four interesting cases for this page table walker:
3260 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3261 * there is nothing left to do.
3262 * 2. It's the first of the current generation, and it needs to reset
3263 * the Bloom filter for the next generation.
3264 * 3. It reaches the end of mm_list, and it needs to increment
3265 * mm_state->seq; the iteration is done.
3266 * 4. It's the last of the current generation, and it needs to reset the
3267 * mm stats counters for the next generation.
3268 */
3269 spin_lock(&mm_list->lock);
3270
3271 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3272 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3273 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3274
3275 if (walk->max_seq <= mm_state->seq) {
3276 if (!*iter)
3277 last = false;
3278 goto done;
3279 }
3280
3281 if (!mm_state->nr_walkers) {
3282 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3283
3284 mm_state->head = mm_list->fifo.next;
3285 first = true;
3286 }
3287
3288 while (!mm && mm_state->head != &mm_list->fifo) {
3289 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3290
3291 mm_state->head = mm_state->head->next;
3292
3293 /* force scan for those added after the last iteration */
3294 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3295 mm_state->tail = mm_state->head;
3296 walk->force_scan = true;
3297 }
3298
3299 if (should_skip_mm(mm, walk))
3300 mm = NULL;
3301 }
3302
3303 if (mm_state->head == &mm_list->fifo)
3304 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3305done:
3306 if (*iter && !mm)
3307 mm_state->nr_walkers--;
3308 if (!*iter && mm)
3309 mm_state->nr_walkers++;
3310
3311 if (mm_state->nr_walkers)
3312 last = false;
3313
3314 if (*iter || last)
3315 reset_mm_stats(lruvec, walk, last);
3316
3317 spin_unlock(&mm_list->lock);
3318
3319 if (mm && first)
3320 reset_bloom_filter(lruvec, walk->max_seq + 1);
3321
3322 if (*iter)
3323 mmput_async(*iter);
3324
3325 *iter = mm;
3326
3327 return last;
3328}
3329
3330static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3331{
3332 bool success = false;
3333 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3334 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3335 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3336
3337 spin_lock(&mm_list->lock);
3338
3339 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3340
3341 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3342 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3343
3344 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3345 reset_mm_stats(lruvec, NULL, true);
3346 success = true;
3347 }
3348
3349 spin_unlock(&mm_list->lock);
3350
3351 return success;
3352}
3353
3354/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003355 * refault feedback loop
3356 ******************************************************************************/
3357
3358/*
3359 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3360 *
3361 * The P term is refaulted/(evicted+protected) from a tier in the generation
3362 * currently being evicted; the I term is the exponential moving average of the
3363 * P term over the generations previously evicted, using the smoothing factor
3364 * 1/2; the D term isn't supported.
3365 *
3366 * The setpoint (SP) is always the first tier of one type; the process variable
3367 * (PV) is either any tier of the other type or any other tier of the same
3368 * type.
3369 *
3370 * The error is the difference between the SP and the PV; the correction is to
3371 * turn off protection when SP>PV or turn on protection when SP<PV.
3372 *
3373 * For future optimizations:
3374 * 1. The D term may discount the other two terms over time so that long-lived
3375 * generations can resist stale information.
3376 */
3377struct ctrl_pos {
3378 unsigned long refaulted;
3379 unsigned long total;
3380 int gain;
3381};
3382
3383static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3384 struct ctrl_pos *pos)
3385{
3386 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3387 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3388
3389 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3390 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3391 pos->total = lrugen->avg_total[type][tier] +
3392 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3393 if (tier)
3394 pos->total += lrugen->protected[hist][type][tier - 1];
3395 pos->gain = gain;
3396}
3397
3398static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3399{
3400 int hist, tier;
3401 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3402 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3403 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3404
3405 lockdep_assert_held(&lruvec->lru_lock);
3406
3407 if (!carryover && !clear)
3408 return;
3409
3410 hist = lru_hist_from_seq(seq);
3411
3412 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3413 if (carryover) {
3414 unsigned long sum;
3415
3416 sum = lrugen->avg_refaulted[type][tier] +
3417 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3418 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3419
3420 sum = lrugen->avg_total[type][tier] +
3421 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3422 if (tier)
3423 sum += lrugen->protected[hist][type][tier - 1];
3424 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3425 }
3426
3427 if (clear) {
3428 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3429 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3430 if (tier)
3431 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3432 }
3433 }
3434}
3435
3436static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3437{
3438 /*
3439 * Return true if the PV has a limited number of refaults or a lower
3440 * refaulted/total than the SP.
3441 */
3442 return pv->refaulted < MIN_LRU_BATCH ||
3443 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3444 (sp->refaulted + 1) * pv->total * pv->gain;
3445}
3446
3447/******************************************************************************
3448 * the aging
3449 ******************************************************************************/
3450
Yu Zhao0182f922022-09-18 02:00:04 -06003451/* promote pages accessed through page tables */
3452static int page_update_gen(struct page *page, int gen)
3453{
3454 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3455
3456 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3457 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3458
3459 do {
3460 /* lru_gen_del_page() has isolated this page? */
3461 if (!(old_flags & LRU_GEN_MASK)) {
3462 /* for shrink_page_list() */
3463 new_flags = old_flags | BIT(PG_referenced);
3464 continue;
3465 }
3466
3467 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3468 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3469 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3470
3471 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3472}
3473
Yu Zhao37397872022-09-18 02:00:03 -06003474/* protect pages accessed multiple times through file descriptors */
3475static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3476{
3477 int type = page_is_file_lru(page);
3478 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3479 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3480 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3481
3482 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3483
3484 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003485 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3486 /* page_update_gen() has promoted this page? */
3487 if (new_gen >= 0 && new_gen != old_gen)
3488 return new_gen;
3489
Yu Zhao37397872022-09-18 02:00:03 -06003490 new_gen = (old_gen + 1) % MAX_NR_GENS;
3491
3492 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3493 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3494 /* for end_page_writeback() */
3495 if (reclaiming)
3496 new_flags |= BIT(PG_reclaim);
3497 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3498
3499 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3500
3501 return new_gen;
3502}
3503
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003504static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3505 int old_gen, int new_gen)
3506{
3507 int type = page_is_file_lru(page);
3508 int zone = page_zonenum(page);
3509 int delta = thp_nr_pages(page);
3510
3511 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3512 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3513
3514 walk->batched++;
3515
3516 walk->nr_pages[old_gen][type][zone] -= delta;
3517 walk->nr_pages[new_gen][type][zone] += delta;
3518}
3519
3520static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3521{
3522 int gen, type, zone;
3523 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3524
3525 walk->batched = 0;
3526
3527 for_each_gen_type_zone(gen, type, zone) {
3528 enum lru_list lru = type * LRU_INACTIVE_FILE;
3529 int delta = walk->nr_pages[gen][type][zone];
3530
3531 if (!delta)
3532 continue;
3533
3534 walk->nr_pages[gen][type][zone] = 0;
3535 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3536 lrugen->nr_pages[gen][type][zone] + delta);
3537
3538 if (lru_gen_is_active(lruvec, gen))
3539 lru += LRU_ACTIVE;
3540 __update_lru_size(lruvec, lru, zone, delta);
3541 }
3542}
3543
3544static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3545{
3546 struct address_space *mapping;
3547 struct vm_area_struct *vma = args->vma;
3548 struct lru_gen_mm_walk *walk = args->private;
3549
3550 if (!vma_is_accessible(vma))
3551 return true;
3552
3553 if (is_vm_hugetlb_page(vma))
3554 return true;
3555
3556 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3557 return true;
3558
3559 if (vma == get_gate_vma(vma->vm_mm))
3560 return true;
3561
3562 if (vma_is_anonymous(vma))
3563 return !walk->can_swap;
3564
3565 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3566 return true;
3567
3568 mapping = vma->vm_file->f_mapping;
3569 if (mapping_unevictable(mapping))
3570 return true;
3571
3572 if (shmem_mapping(mapping))
3573 return !walk->can_swap;
3574
3575 /* to exclude special mappings like dax, etc. */
3576 return !mapping->a_ops->readpage;
3577}
3578
3579/*
3580 * Some userspace memory allocators map many single-page VMAs. Instead of
3581 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3582 * table to reduce zigzags and improve cache performance.
3583 */
3584static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3585 unsigned long *vm_start, unsigned long *vm_end)
3586{
3587 unsigned long start = round_up(*vm_end, size);
3588 unsigned long end = (start | ~mask) + 1;
3589
3590 VM_WARN_ON_ONCE(mask & size);
3591 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3592
3593 while (args->vma) {
3594 if (start >= args->vma->vm_end) {
3595 args->vma = args->vma->vm_next;
3596 continue;
3597 }
3598
3599 if (end && end <= args->vma->vm_start)
3600 return false;
3601
3602 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3603 args->vma = args->vma->vm_next;
3604 continue;
3605 }
3606
3607 *vm_start = max(start, args->vma->vm_start);
3608 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3609
3610 return true;
3611 }
3612
3613 return false;
3614}
3615
Yu Zhao0182f922022-09-18 02:00:04 -06003616static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3617{
3618 unsigned long pfn = pte_pfn(pte);
3619
3620 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3621
3622 if (!pte_present(pte) || is_zero_pfn(pfn))
3623 return -1;
3624
3625 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3626 return -1;
3627
3628 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3629 return -1;
3630
3631 return pfn;
3632}
3633
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003634#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3635static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3636{
3637 unsigned long pfn = pmd_pfn(pmd);
3638
3639 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3640
3641 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3642 return -1;
3643
3644 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3645 return -1;
3646
3647 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3648 return -1;
3649
3650 return pfn;
3651}
3652#endif
3653
Yu Zhao0182f922022-09-18 02:00:04 -06003654static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003655 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003656{
3657 struct page *page;
3658
3659 /* try to avoid unnecessary memory loads */
3660 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3661 return NULL;
3662
3663 page = compound_head(pfn_to_page(pfn));
3664 if (page_to_nid(page) != pgdat->node_id)
3665 return NULL;
3666
3667 if (page_memcg_rcu(page) != memcg)
3668 return NULL;
3669
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003670 /* file VMAs can contain anon pages from COW */
3671 if (!page_is_file_lru(page) && !can_swap)
3672 return NULL;
3673
Yu Zhao0182f922022-09-18 02:00:04 -06003674 return page;
3675}
3676
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003677static bool suitable_to_scan(int total, int young)
3678{
3679 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3680
3681 /* suitable if the average number of young PTEs per cacheline is >=1 */
3682 return young * n >= total;
3683}
3684
3685static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3686 struct mm_walk *args)
3687{
3688 int i;
3689 pte_t *pte;
3690 spinlock_t *ptl;
3691 unsigned long addr;
3692 int total = 0;
3693 int young = 0;
3694 struct lru_gen_mm_walk *walk = args->private;
3695 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3696 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3697 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3698
3699 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3700
3701 ptl = pte_lockptr(args->mm, pmd);
3702 if (!spin_trylock(ptl))
3703 return false;
3704
3705 arch_enter_lazy_mmu_mode();
3706
3707 pte = pte_offset_map(pmd, start & PMD_MASK);
3708restart:
3709 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3710 unsigned long pfn;
3711 struct page *page;
3712
3713 total++;
3714 walk->mm_stats[MM_LEAF_TOTAL]++;
3715
3716 pfn = get_pte_pfn(pte[i], args->vma, addr);
3717 if (pfn == -1)
3718 continue;
3719
3720 if (!pte_young(pte[i])) {
3721 walk->mm_stats[MM_LEAF_OLD]++;
3722 continue;
3723 }
3724
3725 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3726 if (!page)
3727 continue;
3728
3729 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3730 VM_WARN_ON_ONCE(true);
3731
3732 young++;
3733 walk->mm_stats[MM_LEAF_YOUNG]++;
3734
3735 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3736 !(PageAnon(page) && PageSwapBacked(page) &&
3737 !PageSwapCache(page)))
3738 set_page_dirty(page);
3739
3740 old_gen = page_update_gen(page, new_gen);
3741 if (old_gen >= 0 && old_gen != new_gen)
3742 update_batch_size(walk, page, old_gen, new_gen);
3743 }
3744
3745 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3746 goto restart;
3747
3748 pte_unmap(pte);
3749
3750 arch_leave_lazy_mmu_mode();
3751 spin_unlock(ptl);
3752
3753 return suitable_to_scan(total, young);
3754}
3755
3756#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3757static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3758 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3759{
3760 int i;
3761 pmd_t *pmd;
3762 spinlock_t *ptl;
3763 struct lru_gen_mm_walk *walk = args->private;
3764 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3765 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3766 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3767
3768 VM_WARN_ON_ONCE(pud_leaf(*pud));
3769
3770 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3771 if (*start == -1) {
3772 *start = next;
3773 return;
3774 }
3775
3776 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3777 if (i && i <= MIN_LRU_BATCH) {
3778 __set_bit(i - 1, bitmap);
3779 return;
3780 }
3781
3782 pmd = pmd_offset(pud, *start);
3783
3784 ptl = pmd_lockptr(args->mm, pmd);
3785 if (!spin_trylock(ptl))
3786 goto done;
3787
3788 arch_enter_lazy_mmu_mode();
3789
3790 do {
3791 unsigned long pfn;
3792 struct page *page;
3793 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3794
3795 pfn = get_pmd_pfn(pmd[i], vma, addr);
3796 if (pfn == -1)
3797 goto next;
3798
3799 if (!pmd_trans_huge(pmd[i])) {
3800 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG))
3801 pmdp_test_and_clear_young(vma, addr, pmd + i);
3802 goto next;
3803 }
3804
3805 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3806 if (!page)
3807 goto next;
3808
3809 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3810 goto next;
3811
3812 walk->mm_stats[MM_LEAF_YOUNG]++;
3813
3814 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3815 !(PageAnon(page) && PageSwapBacked(page) &&
3816 !PageSwapCache(page)))
3817 set_page_dirty(page);
3818
3819 old_gen = page_update_gen(page, new_gen);
3820 if (old_gen >= 0 && old_gen != new_gen)
3821 update_batch_size(walk, page, old_gen, new_gen);
3822next:
3823 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(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(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 *args, unsigned long *bitmap, 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 *args)
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 *walk = args->private;
3849 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3850
3851 VM_WARN_ON_ONCE(pud_leaf(*pud));
3852
3853 /*
3854 * Finish an entire PMD in two passes: the first only reaches to PTE
3855 * tables to avoid taking the PMD lock; the second, if necessary, takes
3856 * the PMD lock to clear the accessed bit in PMD entries.
3857 */
3858 pmd = pmd_offset(pud, start & PUD_MASK);
3859restart:
3860 /* walk_pte_range() may call get_next_vma() */
3861 vma = args->vma;
3862 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3863 pmd_t val = pmd_read_atomic(pmd + i);
3864
3865 /* for pmd_read_atomic() */
3866 barrier();
3867
3868 next = pmd_addr_end(addr, end);
3869
3870 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3871 walk->mm_stats[MM_LEAF_TOTAL]++;
3872 continue;
3873 }
3874
3875#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3876 if (pmd_trans_huge(val)) {
3877 unsigned long pfn = pmd_pfn(val);
3878 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3879
3880 walk->mm_stats[MM_LEAF_TOTAL]++;
3881
3882 if (!pmd_young(val)) {
3883 walk->mm_stats[MM_LEAF_OLD]++;
3884 continue;
3885 }
3886
3887 /* try to avoid unnecessary memory loads */
3888 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3889 continue;
3890
3891 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3892 continue;
3893 }
3894#endif
3895 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3896
3897#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
3898 if (!pmd_young(val))
3899 continue;
3900
3901 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3902#endif
3903 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3904 continue;
3905
3906 walk->mm_stats[MM_NONLEAF_FOUND]++;
3907
3908 if (!walk_pte_range(&val, addr, next, args))
3909 continue;
3910
3911 walk->mm_stats[MM_NONLEAF_ADDED]++;
3912
3913 /* carry over to the next generation */
3914 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3915 }
3916
3917 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3918
3919 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3920 goto restart;
3921}
3922
3923static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3924 struct mm_walk *args)
3925{
3926 int i;
3927 pud_t *pud;
3928 unsigned long addr;
3929 unsigned long next;
3930 struct lru_gen_mm_walk *walk = args->private;
3931
3932 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3933
3934 pud = pud_offset(p4d, start & P4D_MASK);
3935restart:
3936 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3937 pud_t val = READ_ONCE(pud[i]);
3938
3939 next = pud_addr_end(addr, end);
3940
3941 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3942 continue;
3943
3944 walk_pmd_range(&val, addr, next, args);
3945
3946 /* a racy check to curtail the waiting time */
3947 if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
3948 return 1;
3949
3950 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3951 end = (addr | ~PUD_MASK) + 1;
3952 goto done;
3953 }
3954 }
3955
3956 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3957 goto restart;
3958
3959 end = round_up(end, P4D_SIZE);
3960done:
3961 if (!end || !args->vma)
3962 return 1;
3963
3964 walk->next_addr = max(end, args->vma->vm_start);
3965
3966 return -EAGAIN;
3967}
3968
3969static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3970{
3971 static const struct mm_walk_ops mm_walk_ops = {
3972 .test_walk = should_skip_vma,
3973 .p4d_entry = walk_pud_range,
3974 };
3975
3976 int err;
3977 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3978
3979 walk->next_addr = FIRST_USER_ADDRESS;
3980
3981 do {
3982 err = -EBUSY;
3983
3984 /* page_update_gen() requires stable page_memcg() */
3985 if (!mem_cgroup_trylock_pages(memcg))
3986 break;
3987
3988 /* the caller might be holding the lock for write */
3989 if (mmap_read_trylock(mm)) {
3990 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3991
3992 mmap_read_unlock(mm);
3993 }
3994
3995 mem_cgroup_unlock_pages();
3996
3997 if (walk->batched) {
3998 spin_lock_irq(&lruvec->lru_lock);
3999 reset_batch_size(lruvec, walk);
4000 spin_unlock_irq(&lruvec->lru_lock);
4001 }
4002
4003 cond_resched();
4004 } while (err == -EAGAIN);
4005}
4006
4007static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
4008{
4009 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4010
4011 if (pgdat && current_is_kswapd()) {
4012 VM_WARN_ON_ONCE(walk);
4013
4014 walk = &pgdat->mm_walk;
4015 } else if (!pgdat && !walk) {
4016 VM_WARN_ON_ONCE(current_is_kswapd());
4017
4018 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4019 }
4020
4021 current->reclaim_state->mm_walk = walk;
4022
4023 return walk;
4024}
4025
4026static void clear_mm_walk(void)
4027{
4028 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4029
4030 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4031 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4032
4033 current->reclaim_state->mm_walk = NULL;
4034
4035 if (!current_is_kswapd())
4036 kfree(walk);
4037}
4038
Yu Zhao37397872022-09-18 02:00:03 -06004039static void inc_min_seq(struct lruvec *lruvec, int type)
4040{
4041 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4042
4043 reset_ctrl_pos(lruvec, type, true);
4044 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4045}
4046
4047static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4048{
4049 int gen, type, zone;
4050 bool success = false;
4051 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4052 DEFINE_MIN_SEQ(lruvec);
4053
4054 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4055
4056 /* find the oldest populated generation */
4057 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4058 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4059 gen = lru_gen_from_seq(min_seq[type]);
4060
4061 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4062 if (!list_empty(&lrugen->lists[gen][type][zone]))
4063 goto next;
4064 }
4065
4066 min_seq[type]++;
4067 }
4068next:
4069 ;
4070 }
4071
4072 /* see the comment on lru_gen_struct */
4073 if (can_swap) {
4074 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4075 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4076 }
4077
4078 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4079 if (min_seq[type] == lrugen->min_seq[type])
4080 continue;
4081
4082 reset_ctrl_pos(lruvec, type, true);
4083 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4084 success = true;
4085 }
4086
4087 return success;
4088}
4089
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004090static void inc_max_seq(struct lruvec *lruvec, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004091{
4092 int prev, next;
4093 int type, zone;
4094 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4095
4096 spin_lock_irq(&lruvec->lru_lock);
4097
4098 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4099
Yu Zhao37397872022-09-18 02:00:03 -06004100 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4101 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4102 continue;
4103
4104 VM_WARN_ON_ONCE(type == LRU_GEN_FILE || can_swap);
4105
4106 inc_min_seq(lruvec, type);
4107 }
4108
4109 /*
4110 * Update the active/inactive LRU sizes for compatibility. Both sides of
4111 * the current max_seq need to be covered, since max_seq+1 can overlap
4112 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4113 * overlap, cold/hot inversion happens.
4114 */
4115 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4116 next = lru_gen_from_seq(lrugen->max_seq + 1);
4117
4118 for (type = 0; type < ANON_AND_FILE; type++) {
4119 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4120 enum lru_list lru = type * LRU_INACTIVE_FILE;
4121 long delta = lrugen->nr_pages[prev][type][zone] -
4122 lrugen->nr_pages[next][type][zone];
4123
4124 if (!delta)
4125 continue;
4126
4127 __update_lru_size(lruvec, lru, zone, delta);
4128 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4129 }
4130 }
4131
4132 for (type = 0; type < ANON_AND_FILE; type++)
4133 reset_ctrl_pos(lruvec, type, false);
4134
4135 /* make sure preceding modifications appear */
4136 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004137
Yu Zhao37397872022-09-18 02:00:03 -06004138 spin_unlock_irq(&lruvec->lru_lock);
4139}
4140
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004141static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4142 struct scan_control *sc, bool can_swap)
4143{
4144 bool success;
4145 struct lru_gen_mm_walk *walk;
4146 struct mm_struct *mm = NULL;
4147 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4148
4149 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4150
4151 /* see the comment in iterate_mm_list() */
4152 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4153 success = false;
4154 goto done;
4155 }
4156
4157 /*
4158 * If the hardware doesn't automatically set the accessed bit, fallback
4159 * to lru_gen_look_around(), which only clears the accessed bit in a
4160 * handful of PTEs. Spreading the work out over a period of time usually
4161 * is less efficient, but it avoids bursty page faults.
4162 */
4163 if (!arch_has_hw_pte_young()) {
4164 success = iterate_mm_list_nowalk(lruvec, max_seq);
4165 goto done;
4166 }
4167
4168 walk = set_mm_walk(NULL);
4169 if (!walk) {
4170 success = iterate_mm_list_nowalk(lruvec, max_seq);
4171 goto done;
4172 }
4173
4174 walk->lruvec = lruvec;
4175 walk->max_seq = max_seq;
4176 walk->can_swap = can_swap;
4177 walk->force_scan = false;
4178
4179 do {
4180 success = iterate_mm_list(lruvec, walk, &mm);
4181 if (mm)
4182 walk_mm(lruvec, mm, walk);
4183
4184 cond_resched();
4185 } while (mm);
4186done:
4187 if (!success) {
4188 if (sc->priority <= DEF_PRIORITY - 2)
4189 wait_event_killable(lruvec->mm_state.wait,
4190 max_seq < READ_ONCE(lrugen->max_seq));
4191
4192 return max_seq < READ_ONCE(lrugen->max_seq);
4193 }
4194
4195 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4196
4197 inc_max_seq(lruvec, can_swap);
4198 /* either this sees any waiters or they will see updated max_seq */
4199 if (wq_has_sleeper(&lruvec->mm_state.wait))
4200 wake_up_all(&lruvec->mm_state.wait);
4201
4202 return true;
4203}
4204
Yu Zhao37397872022-09-18 02:00:03 -06004205static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
4206 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4207{
4208 int gen, type, zone;
4209 unsigned long old = 0;
4210 unsigned long young = 0;
4211 unsigned long total = 0;
4212 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4213 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4214
4215 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4216 unsigned long seq;
4217
4218 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4219 unsigned long size = 0;
4220
4221 gen = lru_gen_from_seq(seq);
4222
4223 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4224 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4225
4226 total += size;
4227 if (seq == max_seq)
4228 young += size;
4229 else if (seq + MIN_NR_GENS == max_seq)
4230 old += size;
4231 }
4232 }
4233
4234 /* try to scrape all its memory if this memcg was deleted */
4235 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4236
4237 /*
4238 * The aging tries to be lazy to reduce the overhead, while the eviction
4239 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4240 * ideal number of generations is MIN_NR_GENS+1.
4241 */
4242 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
4243 return true;
4244 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4245 return false;
4246
4247 /*
4248 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4249 * of the total number of pages for each generation. A reasonable range
4250 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4251 * aging cares about the upper bound of hot pages, while the eviction
4252 * cares about the lower bound of cold pages.
4253 */
4254 if (young * MIN_NR_GENS > total)
4255 return true;
4256 if (old * (MIN_NR_GENS + 2) < total)
4257 return true;
4258
4259 return false;
4260}
4261
4262static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4263{
4264 bool need_aging;
4265 unsigned long nr_to_scan;
4266 int swappiness = get_swappiness(lruvec, sc);
4267 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4268 DEFINE_MAX_SEQ(lruvec);
4269 DEFINE_MIN_SEQ(lruvec);
4270
4271 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
4272
4273 mem_cgroup_calculate_protection(NULL, memcg);
4274
4275 if (mem_cgroup_below_min(memcg))
4276 return;
4277
4278 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
4279 if (need_aging)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004280 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness);
Yu Zhao37397872022-09-18 02:00:03 -06004281}
4282
4283static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4284{
4285 struct mem_cgroup *memcg;
4286
4287 VM_WARN_ON_ONCE(!current_is_kswapd());
4288
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004289 set_mm_walk(pgdat);
4290
Yu Zhao37397872022-09-18 02:00:03 -06004291 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4292 do {
4293 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4294
4295 age_lruvec(lruvec, sc);
4296
4297 cond_resched();
4298 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004299
4300 clear_mm_walk();
Yu Zhao37397872022-09-18 02:00:03 -06004301}
4302
Yu Zhao0182f922022-09-18 02:00:04 -06004303/*
4304 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004305 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4306 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4307 * the PTE table to the Bloom filter. This forms a feedback loop between the
4308 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004309 */
4310void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4311{
4312 int i;
4313 pte_t *pte;
4314 unsigned long start;
4315 unsigned long end;
4316 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004317 struct lru_gen_mm_walk *walk;
4318 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004319 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4320 struct page *page = pvmw->page;
4321 struct mem_cgroup *memcg = page_memcg(page);
4322 struct pglist_data *pgdat = page_pgdat(page);
4323 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4324 DEFINE_MAX_SEQ(lruvec);
4325 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4326
4327 lockdep_assert_held(pvmw->ptl);
4328 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4329
4330 if (spin_is_contended(pvmw->ptl))
4331 return;
4332
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004333 /* avoid taking the LRU lock under the PTL when possible */
4334 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4335
Yu Zhao0182f922022-09-18 02:00:04 -06004336 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4337 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4338
4339 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4340 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4341 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4342 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4343 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4344 else {
4345 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4346 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4347 }
4348 }
4349
4350 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4351
4352 rcu_read_lock();
4353 arch_enter_lazy_mmu_mode();
4354
4355 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4356 unsigned long pfn;
4357
4358 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4359 if (pfn == -1)
4360 continue;
4361
4362 if (!pte_young(pte[i]))
4363 continue;
4364
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004365 page = get_pfn_page(pfn, memcg, pgdat, !walk || walk->can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004366 if (!page)
4367 continue;
4368
4369 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4370 VM_WARN_ON_ONCE(true);
4371
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004372 young++;
4373
Yu Zhao0182f922022-09-18 02:00:04 -06004374 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4375 !(PageAnon(page) && PageSwapBacked(page) &&
4376 !PageSwapCache(page)))
4377 set_page_dirty(page);
4378
4379 old_gen = page_lru_gen(page);
4380 if (old_gen < 0)
4381 SetPageReferenced(page);
4382 else if (old_gen != new_gen)
4383 __set_bit(i, bitmap);
4384 }
4385
4386 arch_leave_lazy_mmu_mode();
4387 rcu_read_unlock();
4388
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004389 /* feedback from rmap walkers to page table walkers */
4390 if (suitable_to_scan(i, young))
4391 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4392
4393 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004394 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4395 page = pte_page(pte[i]);
4396 activate_page(page);
4397 }
4398 return;
4399 }
4400
4401 /* page_update_gen() requires stable page_memcg() */
4402 if (!mem_cgroup_trylock_pages(memcg))
4403 return;
4404
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004405 if (!walk) {
4406 spin_lock_irq(&lruvec->lru_lock);
4407 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4408 }
Yu Zhao0182f922022-09-18 02:00:04 -06004409
4410 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4411 page = compound_head(pte_page(pte[i]));
4412 if (page_memcg_rcu(page) != memcg)
4413 continue;
4414
4415 old_gen = page_update_gen(page, new_gen);
4416 if (old_gen < 0 || old_gen == new_gen)
4417 continue;
4418
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004419 if (walk)
4420 update_batch_size(walk, page, old_gen, new_gen);
4421 else
4422 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004423 }
4424
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004425 if (!walk)
4426 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004427
4428 mem_cgroup_unlock_pages();
4429}
4430
Yu Zhao37397872022-09-18 02:00:03 -06004431/******************************************************************************
4432 * the eviction
4433 ******************************************************************************/
4434
4435static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4436{
4437 bool success;
4438 int gen = page_lru_gen(page);
4439 int type = page_is_file_lru(page);
4440 int zone = page_zonenum(page);
4441 int delta = thp_nr_pages(page);
4442 int refs = page_lru_refs(page);
4443 int tier = lru_tier_from_refs(refs);
4444 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4445
4446 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4447
4448 /* unevictable */
4449 if (!page_evictable(page)) {
4450 success = lru_gen_del_page(lruvec, page, true);
4451 VM_WARN_ON_ONCE_PAGE(!success, page);
4452 SetPageUnevictable(page);
4453 add_page_to_lru_list(page, lruvec);
4454 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4455 return true;
4456 }
4457
4458 /* dirty lazyfree */
4459 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4460 success = lru_gen_del_page(lruvec, page, true);
4461 VM_WARN_ON_ONCE_PAGE(!success, page);
4462 SetPageSwapBacked(page);
4463 add_page_to_lru_list_tail(page, lruvec);
4464 return true;
4465 }
4466
Yu Zhao0182f922022-09-18 02:00:04 -06004467 /* promoted */
4468 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4469 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4470 return true;
4471 }
4472
Yu Zhao37397872022-09-18 02:00:03 -06004473 /* protected */
4474 if (tier > tier_idx) {
4475 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4476
4477 gen = page_inc_gen(lruvec, page, false);
4478 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4479
4480 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4481 lrugen->protected[hist][type][tier - 1] + delta);
4482 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4483 return true;
4484 }
4485
4486 /* waiting for writeback */
4487 if (PageLocked(page) || PageWriteback(page) ||
4488 (type == LRU_GEN_FILE && PageDirty(page))) {
4489 gen = page_inc_gen(lruvec, page, true);
4490 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4491 return true;
4492 }
4493
4494 return false;
4495}
4496
4497static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4498{
4499 bool success;
4500
4501 /* unmapping inhibited */
4502 if (!sc->may_unmap && page_mapped(page))
4503 return false;
4504
4505 /* swapping inhibited */
4506 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4507 (PageDirty(page) ||
4508 (PageAnon(page) && !PageSwapCache(page))))
4509 return false;
4510
4511 /* raced with release_pages() */
4512 if (!get_page_unless_zero(page))
4513 return false;
4514
4515 /* raced with another isolation */
4516 if (!TestClearPageLRU(page)) {
4517 put_page(page);
4518 return false;
4519 }
4520
4521 /* see the comment on MAX_NR_TIERS */
4522 if (!PageReferenced(page))
4523 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4524
4525 /* for shrink_page_list() */
4526 ClearPageReclaim(page);
4527 ClearPageReferenced(page);
4528
4529 success = lru_gen_del_page(lruvec, page, true);
4530 VM_WARN_ON_ONCE_PAGE(!success, page);
4531
4532 return true;
4533}
4534
4535static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4536 int type, int tier, struct list_head *list)
4537{
4538 int gen, zone;
4539 enum vm_event_item item;
4540 int sorted = 0;
4541 int scanned = 0;
4542 int isolated = 0;
4543 int remaining = MAX_LRU_BATCH;
4544 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4545 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4546
4547 VM_WARN_ON_ONCE(!list_empty(list));
4548
4549 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4550 return 0;
4551
4552 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4553
4554 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4555 LIST_HEAD(moved);
4556 int skipped = 0;
4557 struct list_head *head = &lrugen->lists[gen][type][zone];
4558
4559 while (!list_empty(head)) {
4560 struct page *page = lru_to_page(head);
4561 int delta = thp_nr_pages(page);
4562
4563 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4564 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4565 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4566 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4567
4568 scanned += delta;
4569
4570 if (sort_page(lruvec, page, tier))
4571 sorted += delta;
4572 else if (isolate_page(lruvec, page, sc)) {
4573 list_add(&page->lru, list);
4574 isolated += delta;
4575 } else {
4576 list_move(&page->lru, &moved);
4577 skipped += delta;
4578 }
4579
4580 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4581 break;
4582 }
4583
4584 if (skipped) {
4585 list_splice(&moved, head);
4586 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4587 }
4588
4589 if (!remaining || isolated >= MIN_LRU_BATCH)
4590 break;
4591 }
4592
4593 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4594 if (!cgroup_reclaim(sc)) {
4595 __count_vm_events(item, isolated);
4596 __count_vm_events(PGREFILL, sorted);
4597 }
4598 __count_memcg_events(memcg, item, isolated);
4599 __count_memcg_events(memcg, PGREFILL, sorted);
4600 __count_vm_events(PGSCAN_ANON + type, isolated);
4601
4602 /*
4603 * There might not be eligible pages due to reclaim_idx, may_unmap and
4604 * may_writepage. Check the remaining to prevent livelock if it's not
4605 * making progress.
4606 */
4607 return isolated || !remaining ? scanned : 0;
4608}
4609
4610static int get_tier_idx(struct lruvec *lruvec, int type)
4611{
4612 int tier;
4613 struct ctrl_pos sp, pv;
4614
4615 /*
4616 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4617 * This value is chosen because any other tier would have at least twice
4618 * as many refaults as the first tier.
4619 */
4620 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4621 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4622 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4623 if (!positive_ctrl_err(&sp, &pv))
4624 break;
4625 }
4626
4627 return tier - 1;
4628}
4629
4630static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4631{
4632 int type, tier;
4633 struct ctrl_pos sp, pv;
4634 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4635
4636 /*
4637 * Compare the first tier of anon with that of file to determine which
4638 * type to scan. Also need to compare other tiers of the selected type
4639 * with the first tier of the other type to determine the last tier (of
4640 * the selected type) to evict.
4641 */
4642 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4643 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4644 type = positive_ctrl_err(&sp, &pv);
4645
4646 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4647 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4648 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4649 if (!positive_ctrl_err(&sp, &pv))
4650 break;
4651 }
4652
4653 *tier_idx = tier - 1;
4654
4655 return type;
4656}
4657
4658static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4659 int *type_scanned, struct list_head *list)
4660{
4661 int i;
4662 int type;
4663 int scanned;
4664 int tier = -1;
4665 DEFINE_MIN_SEQ(lruvec);
4666
4667 /*
4668 * Try to make the obvious choice first. When anon and file are both
4669 * available from the same generation, interpret swappiness 1 as file
4670 * first and 200 as anon first.
4671 */
4672 if (!swappiness)
4673 type = LRU_GEN_FILE;
4674 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4675 type = LRU_GEN_ANON;
4676 else if (swappiness == 1)
4677 type = LRU_GEN_FILE;
4678 else if (swappiness == 200)
4679 type = LRU_GEN_ANON;
4680 else
4681 type = get_type_to_scan(lruvec, swappiness, &tier);
4682
4683 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4684 if (tier < 0)
4685 tier = get_tier_idx(lruvec, type);
4686
4687 scanned = scan_pages(lruvec, sc, type, tier, list);
4688 if (scanned)
4689 break;
4690
4691 type = !type;
4692 tier = -1;
4693 }
4694
4695 *type_scanned = type;
4696
4697 return scanned;
4698}
4699
4700static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
4701{
4702 int type;
4703 int scanned;
4704 int reclaimed;
4705 LIST_HEAD(list);
4706 struct page *page;
4707 enum vm_event_item item;
4708 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004709 struct lru_gen_mm_walk *walk;
Yu Zhao37397872022-09-18 02:00:03 -06004710 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4711 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4712
4713 spin_lock_irq(&lruvec->lru_lock);
4714
4715 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4716
4717 scanned += try_to_inc_min_seq(lruvec, swappiness);
4718
4719 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4720 scanned = 0;
4721
4722 spin_unlock_irq(&lruvec->lru_lock);
4723
4724 if (list_empty(&list))
4725 return scanned;
4726
4727 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4728
4729 list_for_each_entry(page, &list, lru) {
4730 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4731 if (PageWorkingset(page))
4732 SetPageReferenced(page);
4733
4734 /* don't add rejected pages to the oldest generation */
4735 if (PageReclaim(page) &&
4736 (PageDirty(page) || PageWriteback(page)))
4737 ClearPageActive(page);
4738 else
4739 SetPageActive(page);
4740 }
4741
4742 spin_lock_irq(&lruvec->lru_lock);
4743
4744 move_pages_to_lru(lruvec, &list);
4745
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004746 walk = current->reclaim_state->mm_walk;
4747 if (walk && walk->batched)
4748 reset_batch_size(lruvec, walk);
4749
Yu Zhao37397872022-09-18 02:00:03 -06004750 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4751 if (!cgroup_reclaim(sc))
4752 __count_vm_events(item, reclaimed);
4753 __count_memcg_events(memcg, item, reclaimed);
4754 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4755
4756 spin_unlock_irq(&lruvec->lru_lock);
4757
4758 mem_cgroup_uncharge_list(&list);
4759 free_unref_page_list(&list);
4760
4761 sc->nr_reclaimed += reclaimed;
4762
4763 return scanned;
4764}
4765
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004766/*
4767 * For future optimizations:
4768 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4769 * reclaim.
4770 */
Yu Zhao37397872022-09-18 02:00:03 -06004771static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
4772 bool can_swap)
4773{
4774 bool need_aging;
4775 unsigned long nr_to_scan;
4776 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4777 DEFINE_MAX_SEQ(lruvec);
4778 DEFINE_MIN_SEQ(lruvec);
4779
4780 if (mem_cgroup_below_min(memcg) ||
4781 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4782 return 0;
4783
4784 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
4785 if (!need_aging)
4786 return nr_to_scan;
4787
4788 /* skip the aging path at the default priority */
4789 if (sc->priority == DEF_PRIORITY)
4790 goto done;
4791
4792 /* leave the work to lru_gen_age_node() */
4793 if (current_is_kswapd())
4794 return 0;
4795
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004796 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap))
4797 return nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004798done:
4799 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
4800}
4801
4802static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4803{
4804 struct blk_plug plug;
4805 unsigned long scanned = 0;
4806
4807 lru_add_drain();
4808
4809 blk_start_plug(&plug);
4810
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004811 set_mm_walk(lruvec_pgdat(lruvec));
4812
Yu Zhao37397872022-09-18 02:00:03 -06004813 while (true) {
4814 int delta;
4815 int swappiness;
4816 unsigned long nr_to_scan;
4817
4818 if (sc->may_swap)
4819 swappiness = get_swappiness(lruvec, sc);
4820 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4821 swappiness = 1;
4822 else
4823 swappiness = 0;
4824
4825 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
4826 if (!nr_to_scan)
4827 break;
4828
4829 delta = evict_pages(lruvec, sc, swappiness);
4830 if (!delta)
4831 break;
4832
4833 scanned += delta;
4834 if (scanned >= nr_to_scan)
4835 break;
4836
4837 cond_resched();
4838 }
4839
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004840 clear_mm_walk();
4841
Yu Zhao37397872022-09-18 02:00:03 -06004842 blk_finish_plug(&plug);
4843}
4844
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004845/******************************************************************************
4846 * initialization
4847 ******************************************************************************/
4848
4849void lru_gen_init_lruvec(struct lruvec *lruvec)
4850{
4851 int gen, type, zone;
4852 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4853
4854 lrugen->max_seq = MIN_NR_GENS + 1;
4855
4856 for_each_gen_type_zone(gen, type, zone)
4857 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004858
4859 lruvec->mm_state.seq = MIN_NR_GENS;
4860 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004861}
4862
4863#ifdef CONFIG_MEMCG
4864void lru_gen_init_memcg(struct mem_cgroup *memcg)
4865{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004866 INIT_LIST_HEAD(&memcg->mm_list.fifo);
4867 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004868}
4869
4870void lru_gen_exit_memcg(struct mem_cgroup *memcg)
4871{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004872 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004873 int nid;
4874
4875 for_each_node(nid) {
4876 struct lruvec *lruvec = get_lruvec(memcg, nid);
4877
4878 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
4879 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004880
4881 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
4882 bitmap_free(lruvec->mm_state.filters[i]);
4883 lruvec->mm_state.filters[i] = NULL;
4884 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004885 }
4886}
4887#endif
4888
4889static int __init init_lru_gen(void)
4890{
4891 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
4892 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
4893
4894 return 0;
4895};
4896late_initcall(init_lru_gen);
4897
Yu Zhao37397872022-09-18 02:00:03 -06004898#else /* !CONFIG_LRU_GEN */
4899
4900static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4901{
4902}
4903
4904static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4905{
4906}
4907
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004908#endif /* CONFIG_LRU_GEN */
4909
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004910static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004911{
4912 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07004913 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004914 unsigned long nr_to_scan;
4915 enum lru_list lru;
4916 unsigned long nr_reclaimed = 0;
4917 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
4918 struct blk_plug plug;
Mel Gorman1a501902014-06-04 16:10:49 -07004919 bool scan_adjusted;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004920
Yu Zhao37397872022-09-18 02:00:03 -06004921 if (lru_gen_enabled()) {
4922 lru_gen_shrink_lruvec(lruvec, sc);
4923 return;
4924 }
4925
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004926 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004927
Mel Gormane82e0562013-07-03 15:01:44 -07004928 /* Record the original scan target for proportional adjustments later */
4929 memcpy(targets, nr, sizeof(nr));
4930
Mel Gorman1a501902014-06-04 16:10:49 -07004931 /*
4932 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
4933 * event that can occur when there is little memory pressure e.g.
4934 * multiple streaming readers/writers. Hence, we do not abort scanning
4935 * when the requested number of pages are reclaimed when scanning at
4936 * DEF_PRIORITY on the assumption that the fact we are direct
4937 * reclaiming implies that kswapd is not keeping up and it is best to
4938 * do a batch of work at once. For memcg reclaim one check is made to
4939 * abort proportional reclaim if either the file or anon lru has already
4940 * dropped to zero at the first pass.
4941 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08004942 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
Mel Gorman1a501902014-06-04 16:10:49 -07004943 sc->priority == DEF_PRIORITY);
4944
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004945 blk_start_plug(&plug);
4946 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
4947 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07004948 unsigned long nr_anon, nr_file, percentage;
4949 unsigned long nr_scanned;
4950
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004951 for_each_evictable_lru(lru) {
4952 if (nr[lru]) {
4953 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
4954 nr[lru] -= nr_to_scan;
4955
4956 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07004957 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004958 }
4959 }
Mel Gormane82e0562013-07-03 15:01:44 -07004960
Michal Hockobd041732016-12-02 17:26:48 -08004961 cond_resched();
4962
Mel Gormane82e0562013-07-03 15:01:44 -07004963 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
4964 continue;
4965
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004966 /*
Mel Gormane82e0562013-07-03 15:01:44 -07004967 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07004968 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07004969 * proportionally what was requested by get_scan_count(). We
4970 * stop reclaiming one LRU and reduce the amount scanning
4971 * proportional to the original scan target.
4972 */
4973 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
4974 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
4975
Mel Gorman1a501902014-06-04 16:10:49 -07004976 /*
4977 * It's just vindictive to attack the larger once the smaller
4978 * has gone to zero. And given the way we stop scanning the
4979 * smaller below, this makes sure that we only make one nudge
4980 * towards proportionality once we've got nr_to_reclaim.
4981 */
4982 if (!nr_file || !nr_anon)
4983 break;
4984
Mel Gormane82e0562013-07-03 15:01:44 -07004985 if (nr_file > nr_anon) {
4986 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
4987 targets[LRU_ACTIVE_ANON] + 1;
4988 lru = LRU_BASE;
4989 percentage = nr_anon * 100 / scan_target;
4990 } else {
4991 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
4992 targets[LRU_ACTIVE_FILE] + 1;
4993 lru = LRU_FILE;
4994 percentage = nr_file * 100 / scan_target;
4995 }
4996
4997 /* Stop scanning the smaller of the LRU */
4998 nr[lru] = 0;
4999 nr[lru + LRU_ACTIVE] = 0;
5000
5001 /*
5002 * Recalculate the other LRU scan count based on its original
5003 * scan target and the percentage scanning already complete
5004 */
5005 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5006 nr_scanned = targets[lru] - nr[lru];
5007 nr[lru] = targets[lru] * (100 - percentage) / 100;
5008 nr[lru] -= min(nr[lru], nr_scanned);
5009
5010 lru += LRU_ACTIVE;
5011 nr_scanned = targets[lru] - nr[lru];
5012 nr[lru] = targets[lru] * (100 - percentage) / 100;
5013 nr[lru] -= min(nr[lru], nr_scanned);
5014
5015 scan_adjusted = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005016 }
5017 blk_finish_plug(&plug);
5018 sc->nr_reclaimed += nr_reclaimed;
5019
5020 /*
5021 * Even if we did not try to evict anon pages at all, we want to
5022 * rebalance the anon lru active/inactive ratio.
5023 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005024 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5025 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005026 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5027 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005028}
5029
Mel Gorman23b9da52012-05-29 15:06:20 -07005030/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005031static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005032{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005033 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005034 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005035 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005036 return true;
5037
5038 return false;
5039}
5040
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005041/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005042 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5043 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5044 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005045 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005046 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005047 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005048static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005049 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005050 struct scan_control *sc)
5051{
5052 unsigned long pages_for_compaction;
5053 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005054 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005055
5056 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005057 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005058 return false;
5059
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005060 /*
5061 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5062 * number of pages that were scanned. This will return to the caller
5063 * with the risk reclaim/compaction and the resulting allocation attempt
5064 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5065 * allocations through requiring that the full LRU list has been scanned
5066 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5067 * scan, but that approximation was wrong, and there were corner cases
5068 * where always a non-zero amount of pages were scanned.
5069 */
5070 if (!nr_reclaimed)
5071 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005072
Mel Gorman3e7d3442011-01-13 15:45:56 -08005073 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005074 for (z = 0; z <= sc->reclaim_idx; z++) {
5075 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005076 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005077 continue;
5078
5079 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005080 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005081 case COMPACT_CONTINUE:
5082 return false;
5083 default:
5084 /* check next zone */
5085 ;
5086 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005087 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005088
5089 /*
5090 * If we have not reclaimed enough pages for compaction and the
5091 * inactive lists are large enough, continue reclaiming
5092 */
5093 pages_for_compaction = compact_gap(sc->order);
5094 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005095 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005096 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5097
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005098 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005099}
5100
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005101static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005102{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005103 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005104 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005105
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005106 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005107 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005108 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005109 unsigned long reclaimed;
5110 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005111 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08005112
Xunlei Pange3336ca2020-09-04 16:35:27 -07005113 /*
5114 * This loop can become CPU-bound when target memcgs
5115 * aren't eligible for reclaim - either because they
5116 * don't have any reclaimable pages, or because their
5117 * memory is explicitly protected. Avoid soft lockups.
5118 */
5119 cond_resched();
5120
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005121 trace_android_vh_shrink_node_memcgs(memcg, &skip);
5122 if (skip)
5123 continue;
5124
Chris Down45c7f7e2020-08-06 23:22:05 -07005125 mem_cgroup_calculate_protection(target_memcg, memcg);
5126
5127 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005128 /*
5129 * Hard protection.
5130 * If there is no reclaimable memory, OOM.
5131 */
5132 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005133 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005134 /*
5135 * Soft protection.
5136 * Respect the protection only as long as
5137 * there is an unprotected supply
5138 * of reclaimable memory from other cgroups.
5139 */
5140 if (!sc->memcg_low_reclaim) {
5141 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005142 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005143 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005144 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005145 }
5146
Johannes Weinerd2af3392019-11-30 17:55:43 -08005147 reclaimed = sc->nr_reclaimed;
5148 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005149
5150 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005151
Johannes Weinerd2af3392019-11-30 17:55:43 -08005152 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5153 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005154
Johannes Weinerd2af3392019-11-30 17:55:43 -08005155 /* Record the group's reclaim efficiency */
5156 vmpressure(sc->gfp_mask, memcg, false,
5157 sc->nr_scanned - scanned,
5158 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005159
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005160 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5161}
5162
Liu Song6c9e09072020-01-30 22:14:08 -08005163static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005164{
5165 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005166 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005167 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005168 bool reclaimable = false;
5169
Johannes Weiner1b051172019-11-30 17:55:52 -08005170 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5171
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005172again:
5173 memset(&sc->nr, 0, sizeof(sc->nr));
5174
5175 nr_reclaimed = sc->nr_reclaimed;
5176 nr_scanned = sc->nr_scanned;
5177
Yu Zhao6d313442022-09-18 02:00:00 -06005178 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005179
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005180 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005181
Johannes Weinerd2af3392019-11-30 17:55:43 -08005182 if (reclaim_state) {
5183 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5184 reclaim_state->reclaimed_slab = 0;
5185 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005186
Johannes Weinerd2af3392019-11-30 17:55:43 -08005187 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005188 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005189 sc->nr_scanned - nr_scanned,
5190 sc->nr_reclaimed - nr_reclaimed);
5191
5192 if (sc->nr_reclaimed - nr_reclaimed)
5193 reclaimable = true;
5194
5195 if (current_is_kswapd()) {
5196 /*
5197 * If reclaim is isolating dirty pages under writeback,
5198 * it implies that the long-lived page allocation rate
5199 * is exceeding the page laundering rate. Either the
5200 * global limits are not being effective at throttling
5201 * processes due to the page distribution throughout
5202 * zones or there is heavy usage of a slow backing
5203 * device. The only option is to throttle from reclaim
5204 * context which is not ideal as there is no guarantee
5205 * the dirtying process is throttled in the same way
5206 * balance_dirty_pages() manages.
5207 *
5208 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5209 * count the number of pages under pages flagged for
5210 * immediate reclaim and stall if any are encountered
5211 * in the nr_immediate check below.
5212 */
5213 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5214 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005215
Johannes Weinerd2af3392019-11-30 17:55:43 -08005216 /* Allow kswapd to start writing pages during reclaim.*/
5217 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5218 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005219
5220 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005221 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005222 * reclaim and under writeback (nr_immediate), it
5223 * implies that pages are cycling through the LRU
5224 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005225 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005226 if (sc->nr.immediate)
5227 congestion_wait(BLK_RW_ASYNC, HZ/10);
5228 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005229
Johannes Weinerd2af3392019-11-30 17:55:43 -08005230 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005231 * Tag a node/memcg as congested if all the dirty pages
5232 * scanned were backed by a congested BDI and
5233 * wait_iff_congested will stall.
5234 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005235 * Legacy memcg will stall in page writeback so avoid forcibly
5236 * stalling in wait_iff_congested().
5237 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005238 if ((current_is_kswapd() ||
5239 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005240 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005241 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005242
5243 /*
5244 * Stall direct reclaim for IO completions if underlying BDIs
5245 * and node is congested. Allow kswapd to continue until it
5246 * starts encountering unqueued dirty pages or cycling through
5247 * the LRU too quickly.
5248 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005249 if (!current_is_kswapd() && current_may_throttle() &&
5250 !sc->hibernation_mode &&
5251 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005252 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5253
5254 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5255 sc))
5256 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005257
Johannes Weinerc73322d2017-05-03 14:51:51 -07005258 /*
5259 * Kswapd gives up on balancing particular nodes after too
5260 * many failures to reclaim anything from them and goes to
5261 * sleep. On reclaim progress, reset the failure counter. A
5262 * successful direct reclaim run will revive a dormant kswapd.
5263 */
5264 if (reclaimable)
5265 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005266}
5267
Vlastimil Babka53853e22014-10-09 15:27:02 -07005268/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005269 * Returns true if compaction should go ahead for a costly-order request, or
5270 * the allocation would already succeed without compaction. Return false if we
5271 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07005272 */
Mel Gorman4f588332016-07-28 15:46:38 -07005273static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005274{
Mel Gorman31483b62016-07-28 15:45:46 -07005275 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005276 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005277
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005278 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
5279 if (suitable == COMPACT_SUCCESS)
5280 /* Allocation should succeed already. Don't reclaim. */
5281 return true;
5282 if (suitable == COMPACT_SKIPPED)
5283 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005284 return false;
5285
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005286 /*
5287 * Compaction is already possible, but it takes time to run and there
5288 * are potentially other callers using the pages just freed. So proceed
5289 * with reclaim to make a buffer of free pages available to give
5290 * compaction a reasonable chance of completing and allocating the page.
5291 * Note that we won't actually reclaim the whole buffer in one attempt
5292 * as the target watermark in should_continue_reclaim() is lower. But if
5293 * we are already above the high+gap watermark, don't reclaim at all.
5294 */
5295 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
5296
5297 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005298}
5299
Linus Torvalds1da177e2005-04-16 15:20:36 -07005300/*
5301 * This is the direct reclaim path, for page-allocating processes. We only
5302 * try to reclaim pages from zones which will satisfy the caller's allocation
5303 * request.
5304 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07005305 * If a zone is deemed to be full of pinned pages then just give it a light
5306 * scan then give up on it.
5307 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07005308static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005309{
Mel Gormandd1a2392008-04-28 02:12:17 -07005310 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07005311 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07005312 unsigned long nr_soft_reclaimed;
5313 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07005314 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07005315 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005316
Mel Gormancc715d92012-03-21 16:34:00 -07005317 /*
5318 * If the number of buffer_heads in the machine exceeds the maximum
5319 * allowed level, force direct reclaim to scan the highmem zone as
5320 * highmem pages could be pinning lowmem pages storing buffer_heads
5321 */
Weijie Yang619d0d762014-04-07 15:36:59 -07005322 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07005323 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07005324 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07005325 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07005326 }
Mel Gormancc715d92012-03-21 16:34:00 -07005327
Mel Gormand4debc62010-08-09 17:19:29 -07005328 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07005329 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07005330 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005331 * Take care memory controller reclaiming has small influence
5332 * to global LRU.
5333 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005334 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04005335 if (!cpuset_zone_allowed(zone,
5336 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005337 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005338
Johannes Weiner0b064962014-08-06 16:06:12 -07005339 /*
5340 * If we already have plenty of memory free for
5341 * compaction in this zone, don't free any more.
5342 * Even though compaction is invoked for any
5343 * non-zero order, only frequent costly order
5344 * reclamation is disruptive enough to become a
5345 * noticeable problem, like transparent huge
5346 * page allocations.
5347 */
5348 if (IS_ENABLED(CONFIG_COMPACTION) &&
5349 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07005350 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07005351 sc->compaction_ready = true;
5352 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07005353 }
Johannes Weiner0b064962014-08-06 16:06:12 -07005354
Andrew Morton0608f432013-09-24 15:27:41 -07005355 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07005356 * Shrink each node in the zonelist once. If the
5357 * zonelist is ordered by zone (not the default) then a
5358 * node may be shrunk multiple times but in that case
5359 * the user prefers lower zones being preserved.
5360 */
5361 if (zone->zone_pgdat == last_pgdat)
5362 continue;
5363
5364 /*
Andrew Morton0608f432013-09-24 15:27:41 -07005365 * This steals pages from memory cgroups over softlimit
5366 * and returns the number of reclaimed pages and
5367 * scanned pages. This works for global memory pressure
5368 * and balancing, not for a memcg's limit.
5369 */
5370 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07005371 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07005372 sc->order, sc->gfp_mask,
5373 &nr_soft_scanned);
5374 sc->nr_reclaimed += nr_soft_reclaimed;
5375 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07005376 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005377 }
Nick Piggin408d8542006-09-25 23:31:27 -07005378
Mel Gorman79dafcd2016-07-28 15:45:53 -07005379 /* See comment about same check for global reclaim above */
5380 if (zone->zone_pgdat == last_pgdat)
5381 continue;
5382 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07005383 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005384 }
Mel Gormane0c23272011-10-31 17:09:33 -07005385
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005386 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07005387 * Restore to original mask to avoid the impact on the caller if we
5388 * promoted it to __GFP_HIGHMEM.
5389 */
5390 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005391}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005392
Johannes Weinerb9107182019-11-30 17:55:59 -08005393static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005394{
Johannes Weinerb9107182019-11-30 17:55:59 -08005395 struct lruvec *target_lruvec;
5396 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005397
Yu Zhao37397872022-09-18 02:00:03 -06005398 if (lru_gen_enabled())
5399 return;
5400
Johannes Weinerb9107182019-11-30 17:55:59 -08005401 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07005402 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
5403 target_lruvec->refaults[0] = refaults;
5404 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
5405 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005406}
5407
Linus Torvalds1da177e2005-04-16 15:20:36 -07005408/*
5409 * This is the main entry point to direct page reclaim.
5410 *
5411 * If a full scan of the inactive list fails to free enough memory then we
5412 * are "out of memory" and something needs to be killed.
5413 *
5414 * If the caller is !__GFP_FS then the probability of a failure is reasonably
5415 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02005416 * caller can't do much about. We kick the writeback threads and take explicit
5417 * naps in the hope that some of these pages can be written. But if the
5418 * allocating task holds filesystem locks which prevent writeout this might not
5419 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07005420 *
5421 * returns: 0, if no pages reclaimed
5422 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07005423 */
Mel Gormandac1d272008-04-28 02:12:12 -07005424static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005425 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005426{
Johannes Weiner241994ed2015-02-11 15:26:06 -08005427 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005428 pg_data_t *last_pgdat;
5429 struct zoneref *z;
5430 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005431retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07005432 delayacct_freepages_start();
5433
Johannes Weinerb5ead352019-11-30 17:55:40 -08005434 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07005435 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005436
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005437 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005438 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
5439 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08005440 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07005441 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07005442
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005443 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07005444 break;
5445
5446 if (sc->compaction_ready)
5447 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005448
5449 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08005450 * If we're getting trouble reclaiming, start doing
5451 * writepage even in laptop mode.
5452 */
5453 if (sc->priority < DEF_PRIORITY - 2)
5454 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07005455 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005456
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005457 last_pgdat = NULL;
5458 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
5459 sc->nodemask) {
5460 if (zone->zone_pgdat == last_pgdat)
5461 continue;
5462 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08005463
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005464 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08005465
5466 if (cgroup_reclaim(sc)) {
5467 struct lruvec *lruvec;
5468
5469 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
5470 zone->zone_pgdat);
5471 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
5472 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005473 }
5474
Keika Kobayashi873b4772008-07-25 01:48:52 -07005475 delayacct_freepages_end();
5476
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005477 if (sc->nr_reclaimed)
5478 return sc->nr_reclaimed;
5479
Mel Gorman0cee34f2012-01-12 17:19:49 -08005480 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07005481 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08005482 return 1;
5483
Johannes Weinerb91ac372019-11-30 17:56:02 -08005484 /*
5485 * We make inactive:active ratio decisions based on the node's
5486 * composition of memory, but a restrictive reclaim_idx or a
5487 * memory.low cgroup setting can exempt large amounts of
5488 * memory from reclaim. Neither of which are very common, so
5489 * instead of doing costly eligibility calculations of the
5490 * entire cgroup subtree up front, we assume the estimates are
5491 * good, and retry with forcible deactivation if that fails.
5492 */
5493 if (sc->skipped_deactivate) {
5494 sc->priority = initial_priority;
5495 sc->force_deactivate = 1;
5496 sc->skipped_deactivate = 0;
5497 goto retry;
5498 }
5499
Johannes Weiner241994ed2015-02-11 15:26:06 -08005500 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07005501 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08005502 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08005503 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07005504 sc->memcg_low_reclaim = 1;
5505 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005506 goto retry;
5507 }
5508
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005509 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005510}
5511
Johannes Weinerc73322d2017-05-03 14:51:51 -07005512static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07005513{
5514 struct zone *zone;
5515 unsigned long pfmemalloc_reserve = 0;
5516 unsigned long free_pages = 0;
5517 int i;
5518 bool wmark_ok;
5519
Johannes Weinerc73322d2017-05-03 14:51:51 -07005520 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
5521 return true;
5522
Mel Gorman55150612012-07-31 16:44:35 -07005523 for (i = 0; i <= ZONE_NORMAL; i++) {
5524 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07005525 if (!managed_zone(zone))
5526 continue;
5527
5528 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07005529 continue;
5530
Mel Gorman55150612012-07-31 16:44:35 -07005531 pfmemalloc_reserve += min_wmark_pages(zone);
5532 free_pages += zone_page_state(zone, NR_FREE_PAGES);
5533 }
5534
Mel Gorman675becc2014-06-04 16:07:35 -07005535 /* If there are no reserves (unexpected config) then do not throttle */
5536 if (!pfmemalloc_reserve)
5537 return true;
5538
Mel Gorman55150612012-07-31 16:44:35 -07005539 wmark_ok = free_pages > pfmemalloc_reserve / 2;
5540
5541 /* kswapd must be awake if processes are being throttled */
5542 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005543 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
5544 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005545
Mel Gorman55150612012-07-31 16:44:35 -07005546 wake_up_interruptible(&pgdat->kswapd_wait);
5547 }
5548
5549 return wmark_ok;
5550}
5551
5552/*
5553 * Throttle direct reclaimers if backing storage is backed by the network
5554 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
5555 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08005556 * when the low watermark is reached.
5557 *
5558 * Returns true if a fatal signal was delivered during throttling. If this
5559 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07005560 */
Mel Gorman50694c22012-11-26 16:29:48 -08005561static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07005562 nodemask_t *nodemask)
5563{
Mel Gorman675becc2014-06-04 16:07:35 -07005564 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07005565 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07005566 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07005567
5568 /*
5569 * Kernel threads should not be throttled as they may be indirectly
5570 * responsible for cleaning pages necessary for reclaim to make forward
5571 * progress. kjournald for example may enter direct reclaim while
5572 * committing a transaction where throttling it could forcing other
5573 * processes to block on log_wait_commit().
5574 */
5575 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08005576 goto out;
5577
5578 /*
5579 * If a fatal signal is pending, this process should not throttle.
5580 * It should return quickly so it can exit and free its memory
5581 */
5582 if (fatal_signal_pending(current))
5583 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005584
Mel Gorman675becc2014-06-04 16:07:35 -07005585 /*
5586 * Check if the pfmemalloc reserves are ok by finding the first node
5587 * with a usable ZONE_NORMAL or lower zone. The expectation is that
5588 * GFP_KERNEL will be required for allocating network buffers when
5589 * swapping over the network so ZONE_HIGHMEM is unusable.
5590 *
5591 * Throttling is based on the first usable node and throttled processes
5592 * wait on a queue until kswapd makes progress and wakes them. There
5593 * is an affinity then between processes waking up and where reclaim
5594 * progress has been made assuming the process wakes on the same node.
5595 * More importantly, processes running on remote nodes will not compete
5596 * for remote pfmemalloc reserves and processes on different nodes
5597 * should make reasonable progress.
5598 */
5599 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08005600 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07005601 if (zone_idx(zone) > ZONE_NORMAL)
5602 continue;
5603
5604 /* Throttle based on the first usable node */
5605 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07005606 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07005607 goto out;
5608 break;
5609 }
5610
5611 /* If no zone was usable by the allocation flags then do not throttle */
5612 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08005613 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005614
Mel Gorman68243e72012-07-31 16:44:39 -07005615 /* Account for the throttling */
5616 count_vm_event(PGSCAN_DIRECT_THROTTLE);
5617
Mel Gorman55150612012-07-31 16:44:35 -07005618 /*
5619 * If the caller cannot enter the filesystem, it's possible that it
5620 * is due to the caller holding an FS lock or performing a journal
5621 * transaction in the case of a filesystem like ext[3|4]. In this case,
5622 * it is not safe to block on pfmemalloc_wait as kswapd could be
5623 * blocked waiting on the same lock. Instead, throttle for up to a
5624 * second before continuing.
5625 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07005626 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07005627 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07005628 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07005629 else
5630 /* Throttle until kswapd wakes the process */
5631 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
5632 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08005633
Mel Gorman50694c22012-11-26 16:29:48 -08005634 if (fatal_signal_pending(current))
5635 return true;
5636
5637out:
5638 return false;
Mel Gorman55150612012-07-31 16:44:35 -07005639}
5640
Mel Gormandac1d272008-04-28 02:12:12 -07005641unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07005642 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08005643{
Mel Gorman33906bc2010-08-09 17:19:16 -07005644 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005645 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08005646 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005647 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07005648 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07005649 .order = order,
5650 .nodemask = nodemask,
5651 .priority = DEF_PRIORITY,
5652 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005653 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07005654 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08005655 };
5656
Mel Gorman55150612012-07-31 16:44:35 -07005657 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07005658 * scan_control uses s8 fields for order, priority, and reclaim_idx.
5659 * Confirm they are large enough for max values.
5660 */
5661 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
5662 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
5663 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
5664
5665 /*
Mel Gorman50694c22012-11-26 16:29:48 -08005666 * Do not enter reclaim if fatal signal was delivered while throttled.
5667 * 1 is returned so that the page allocator does not OOM kill at this
5668 * point.
Mel Gorman55150612012-07-31 16:44:35 -07005669 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005670 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07005671 return 1;
5672
Andrew Morton1732d2b012019-07-16 16:26:15 -07005673 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005674 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07005675
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005676 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07005677
5678 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005679 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07005680
5681 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005682}
5683
Andrew Mortonc255a452012-07-31 16:43:02 -07005684#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08005685
Michal Hockod2e5fb92019-08-30 16:04:50 -07005686/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005687unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005688 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07005689 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07005690 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07005691{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005692 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07005693 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07005694 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07005695 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005696 .may_writepage = !laptop_mode,
5697 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07005698 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07005699 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07005700 };
Ying Han0ae5e892011-05-26 16:25:25 -07005701
Michal Hockod2e5fb92019-08-30 16:04:50 -07005702 WARN_ON_ONCE(!current->reclaim_state);
5703
Balbir Singh4e416952009-09-23 15:56:39 -07005704 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
5705 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005706
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005707 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07005708 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005709
Balbir Singh4e416952009-09-23 15:56:39 -07005710 /*
5711 * NOTE: Although we can get the priority field, using it
5712 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07005713 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07005714 * will pick up pages from other mem cgroup's as well. We hack
5715 * the priority and make it zero.
5716 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005717 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005718
5719 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
5720
Ying Han0ae5e892011-05-26 16:25:25 -07005721 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07005722
Balbir Singh4e416952009-09-23 15:56:39 -07005723 return sc.nr_reclaimed;
5724}
5725
Johannes Weiner72835c82012-01-12 17:18:32 -08005726unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005727 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08005728 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005729 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08005730{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005731 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07005732 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08005733 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005734 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07005735 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07005736 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07005737 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07005738 .target_mem_cgroup = memcg,
5739 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08005740 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005741 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005742 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07005743 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08005744 /*
5745 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
5746 * equal pressure on all the nodes. This is based on the assumption that
5747 * the reclaim does not bail out early.
5748 */
5749 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08005750
Andrew Morton1732d2b012019-07-16 16:26:15 -07005751 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005752 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07005753 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07005754
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005755 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07005756
Vlastimil Babka499118e2017-05-08 15:59:50 -07005757 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005758 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005759 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005760
5761 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005762}
Liujie Xie1ed025b2021-06-25 22:21:35 +08005763EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08005764#endif
5765
Yu Zhao37397872022-09-18 02:00:03 -06005766static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005767{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005768 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08005769 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005770
Yu Zhao37397872022-09-18 02:00:03 -06005771 if (lru_gen_enabled()) {
5772 lru_gen_age_node(pgdat, sc);
5773 return;
5774 }
5775
Dave Hansen2f368a92021-09-02 14:59:23 -07005776 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005777 return;
5778
Johannes Weinerb91ac372019-11-30 17:56:02 -08005779 lruvec = mem_cgroup_lruvec(NULL, pgdat);
5780 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
5781 return;
5782
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005783 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5784 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08005785 lruvec = mem_cgroup_lruvec(memcg, pgdat);
5786 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5787 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005788 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5789 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08005790}
5791
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005792static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08005793{
5794 int i;
5795 struct zone *zone;
5796
5797 /*
5798 * Check for watermark boosts top-down as the higher zones
5799 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005800 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08005801 * start prematurely when there is no boosting and a lower
5802 * zone is balanced.
5803 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005804 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08005805 zone = pgdat->node_zones + i;
5806 if (!managed_zone(zone))
5807 continue;
5808
5809 if (zone->watermark_boost)
5810 return true;
5811 }
5812
5813 return false;
5814}
5815
Mel Gormane716f2e2017-05-03 14:53:45 -07005816/*
5817 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005818 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07005819 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005820static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08005821{
Mel Gormane716f2e2017-05-03 14:53:45 -07005822 int i;
5823 unsigned long mark = -1;
5824 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08005825
Mel Gorman1c308442018-12-28 00:35:52 -08005826 /*
5827 * Check watermarks bottom-up as lower zones are more likely to
5828 * meet watermarks.
5829 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005830 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07005831 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07005832
Mel Gormane716f2e2017-05-03 14:53:45 -07005833 if (!managed_zone(zone))
5834 continue;
5835
5836 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005837 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07005838 return true;
5839 }
5840
5841 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005842 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07005843 * need balancing by definition. This can happen if a zone-restricted
5844 * allocation tries to wake a remote kswapd.
5845 */
5846 if (mark == -1)
5847 return true;
5848
5849 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08005850}
5851
Mel Gorman631b6e02017-05-03 14:53:41 -07005852/* Clear pgdat state for congested, dirty or under writeback. */
5853static void clear_pgdat_congested(pg_data_t *pgdat)
5854{
Johannes Weiner1b051172019-11-30 17:55:52 -08005855 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5856
5857 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07005858 clear_bit(PGDAT_DIRTY, &pgdat->flags);
5859 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
5860}
5861
Mel Gorman1741c872011-01-13 15:46:21 -08005862/*
Mel Gorman55150612012-07-31 16:44:35 -07005863 * Prepare kswapd for sleeping. This verifies that there are no processes
5864 * waiting in throttle_direct_reclaim() and that watermarks have been met.
5865 *
5866 * Returns true if kswapd is ready to sleep
5867 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005868static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
5869 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08005870{
Mel Gorman55150612012-07-31 16:44:35 -07005871 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005872 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07005873 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005874 * race between when kswapd checks the watermarks and a process gets
5875 * throttled. There is also a potential race if processes get
5876 * throttled, kswapd wakes, a large process exits thereby balancing the
5877 * zones, which causes kswapd to exit balance_pgdat() before reaching
5878 * the wake up checks. If kswapd is going to sleep, no process should
5879 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
5880 * the wake up is premature, processes will wake kswapd and get
5881 * throttled again. The difference from wake ups in balance_pgdat() is
5882 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07005883 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005884 if (waitqueue_active(&pgdat->pfmemalloc_wait))
5885 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08005886
Johannes Weinerc73322d2017-05-03 14:51:51 -07005887 /* Hopeless node, leave it to direct reclaim */
5888 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
5889 return true;
5890
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005891 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07005892 clear_pgdat_congested(pgdat);
5893 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07005894 }
5895
Shantanu Goel333b0a42017-05-03 14:53:38 -07005896 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08005897}
5898
Linus Torvalds1da177e2005-04-16 15:20:36 -07005899/*
Mel Gorman1d82de62016-07-28 15:45:43 -07005900 * kswapd shrinks a node of pages that are at or below the highest usable
5901 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07005902 *
5903 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07005904 * reclaim or if the lack of progress was due to pages under writeback.
5905 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07005906 */
Mel Gorman1d82de62016-07-28 15:45:43 -07005907static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07005908 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07005909{
Mel Gorman1d82de62016-07-28 15:45:43 -07005910 struct zone *zone;
5911 int z;
Mel Gorman75485362013-07-03 15:01:42 -07005912
Mel Gorman1d82de62016-07-28 15:45:43 -07005913 /* Reclaim a number of pages proportional to the number of zones */
5914 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07005915 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07005916 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07005917 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07005918 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07005919
Mel Gorman1d82de62016-07-28 15:45:43 -07005920 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07005921 }
5922
Mel Gorman1d82de62016-07-28 15:45:43 -07005923 /*
5924 * Historically care was taken to put equal pressure on all zones but
5925 * now pressure is applied based on node LRU order.
5926 */
Mel Gorman970a39a2016-07-28 15:46:35 -07005927 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07005928
5929 /*
5930 * Fragmentation may mean that the system cannot be rebalanced for
5931 * high-order allocations. If twice the allocation size has been
5932 * reclaimed then recheck watermarks only at order-0 to prevent
5933 * excessive reclaim. Assume that a process requested a high-order
5934 * can direct reclaim/compact.
5935 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07005936 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07005937 sc->order = 0;
5938
Mel Gormanb8e83b92013-07-03 15:01:45 -07005939 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07005940}
5941
Mel Gormanc49c2c42021-06-28 19:42:21 -07005942/* Page allocator PCP high watermark is lowered if reclaim is active. */
5943static inline void
5944update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
5945{
5946 int i;
5947 struct zone *zone;
5948
5949 for (i = 0; i <= highest_zoneidx; i++) {
5950 zone = pgdat->node_zones + i;
5951
5952 if (!managed_zone(zone))
5953 continue;
5954
5955 if (active)
5956 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
5957 else
5958 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
5959 }
5960}
5961
5962static inline void
5963set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
5964{
5965 update_reclaim_active(pgdat, highest_zoneidx, true);
5966}
5967
5968static inline void
5969clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
5970{
5971 update_reclaim_active(pgdat, highest_zoneidx, false);
5972}
5973
Mel Gorman75485362013-07-03 15:01:42 -07005974/*
Mel Gorman1d82de62016-07-28 15:45:43 -07005975 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
5976 * that are eligible for use by the caller until at least one zone is
5977 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005978 *
Mel Gorman1d82de62016-07-28 15:45:43 -07005979 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005980 *
5981 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07005982 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08005983 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07005984 * or lower is eligible for reclaim until at least one usable zone is
5985 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005986 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005987static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005988{
Linus Torvalds1da177e2005-04-16 15:20:36 -07005989 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07005990 unsigned long nr_soft_reclaimed;
5991 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07005992 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08005993 unsigned long nr_boost_reclaim;
5994 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
5995 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07005996 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08005997 struct scan_control sc = {
5998 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07005999 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006000 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08006001 };
Omar Sandoval93781322018-06-07 17:07:02 -07006002
Andrew Morton1732d2b012019-07-16 16:26:15 -07006003 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07006004 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006005 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006006
Christoph Lameterf8891e52006-06-30 01:55:45 -07006007 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006008
Mel Gorman1c308442018-12-28 00:35:52 -08006009 /*
6010 * Account for the reclaim boost. Note that the zone boost is left in
6011 * place so that parallel allocations that are near the watermark will
6012 * stall or direct reclaim until kswapd is finished.
6013 */
6014 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006015 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006016 zone = pgdat->node_zones + i;
6017 if (!managed_zone(zone))
6018 continue;
6019
6020 nr_boost_reclaim += zone->watermark_boost;
6021 zone_boosts[i] = zone->watermark_boost;
6022 }
6023 boosted = nr_boost_reclaim;
6024
6025restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006026 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006027 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006028 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006029 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006030 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006031 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006032 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006033
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006034 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006035
Mel Gorman86c79f62016-07-28 15:45:59 -07006036 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006037 * If the number of buffer_heads exceeds the maximum allowed
6038 * then consider reclaiming from all zones. This has a dual
6039 * purpose -- on 64-bit systems it is expected that
6040 * buffer_heads are stripped during active rotation. On 32-bit
6041 * systems, highmem pages can pin lowmem memory and shrinking
6042 * buffers can relieve lowmem pressure. Reclaim may still not
6043 * go ahead if all eligible zones for the original allocation
6044 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006045 */
6046 if (buffer_heads_over_limit) {
6047 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6048 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006049 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006050 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006051
Mel Gorman970a39a2016-07-28 15:46:35 -07006052 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006053 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006054 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006055 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006056
Mel Gorman86c79f62016-07-28 15:45:59 -07006057 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006058 * If the pgdat is imbalanced then ignore boosting and preserve
6059 * the watermarks for a later time and restart. Note that the
6060 * zone watermarks will be still reset at the end of balancing
6061 * on the grounds that the normal reclaim should be enough to
6062 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006063 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006064 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006065 if (!balanced && nr_boost_reclaim) {
6066 nr_boost_reclaim = 0;
6067 goto restart;
6068 }
6069
6070 /*
6071 * If boosting is not active then only reclaim if there are no
6072 * eligible zones. Note that sc.reclaim_idx is not used as
6073 * buffer_heads_over_limit may have adjusted it.
6074 */
6075 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006076 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006077
Mel Gorman1c308442018-12-28 00:35:52 -08006078 /* Limit the priority of boosting to avoid reclaim writeback */
6079 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6080 raise_priority = false;
6081
6082 /*
6083 * Do not writeback or swap pages for boosted reclaim. The
6084 * intent is to relieve pressure not issue sub-optimal IO
6085 * from reclaim context. If no pages are reclaimed, the
6086 * reclaim will be aborted.
6087 */
6088 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6089 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006090
Linus Torvalds1da177e2005-04-16 15:20:36 -07006091 /*
Yu Zhao37397872022-09-18 02:00:03 -06006092 * Do some background aging, to give pages a chance to be
6093 * referenced before reclaiming. All pages are rotated
6094 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07006095 */
Yu Zhao37397872022-09-18 02:00:03 -06006096 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006097
6098 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006099 * If we're getting trouble reclaiming, start doing writepage
6100 * even in laptop mode.
6101 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006102 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006103 sc.may_writepage = 1;
6104
Mel Gorman1d82de62016-07-28 15:45:43 -07006105 /* Call soft limit reclaim before calling shrink_node. */
6106 sc.nr_scanned = 0;
6107 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006108 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006109 sc.gfp_mask, &nr_soft_scanned);
6110 sc.nr_reclaimed += nr_soft_reclaimed;
6111
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006112 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006113 * There should be no need to raise the scanning priority if
6114 * enough pages are already being scanned that that high
6115 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006116 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006117 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006118 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006119
6120 /*
6121 * If the low watermark is met there is no need for processes
6122 * to be throttled on pfmemalloc_wait as they should not be
6123 * able to safely make forward progress. Wake them
6124 */
6125 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006126 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006127 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006128
Mel Gormanb8e83b92013-07-03 15:01:45 -07006129 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006130 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006131 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006132 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006133 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006134 break;
6135
6136 /*
6137 * Raise priority if scanning rate is too low or there was no
6138 * progress in reclaiming pages
6139 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006140 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006141 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6142
6143 /*
6144 * If reclaim made no progress for a boost, stop reclaim as
6145 * IO cannot be queued and it could be an infinite loop in
6146 * extreme circumstances.
6147 */
6148 if (nr_boost_reclaim && !nr_reclaimed)
6149 break;
6150
Johannes Weinerc73322d2017-05-03 14:51:51 -07006151 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006152 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006153 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006154
Johannes Weinerc73322d2017-05-03 14:51:51 -07006155 if (!sc.nr_reclaimed)
6156 pgdat->kswapd_failures++;
6157
Mel Gormanb8e83b92013-07-03 15:01:45 -07006158out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006159 clear_reclaim_active(pgdat, highest_zoneidx);
6160
Mel Gorman1c308442018-12-28 00:35:52 -08006161 /* If reclaim was boosted, account for the reclaim done in this pass */
6162 if (boosted) {
6163 unsigned long flags;
6164
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006165 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006166 if (!zone_boosts[i])
6167 continue;
6168
6169 /* Increments are under the zone lock */
6170 zone = pgdat->node_zones + i;
6171 spin_lock_irqsave(&zone->lock, flags);
6172 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6173 spin_unlock_irqrestore(&zone->lock, flags);
6174 }
6175
6176 /*
6177 * As there is now likely space, wakeup kcompact to defragment
6178 * pageblocks.
6179 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006180 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006181 }
6182
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006183 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006184 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006185 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006186 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006187
Mel Gorman0abdee22011-01-13 15:46:22 -08006188 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006189 * Return the order kswapd stopped reclaiming at as
6190 * prepare_kswapd_sleep() takes it into account. If another caller
6191 * entered the allocator slow path while kswapd was awake, order will
6192 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006193 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006194 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006195}
6196
Mel Gormane716f2e2017-05-03 14:53:45 -07006197/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006198 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6199 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6200 * not a valid index then either kswapd runs for first time or kswapd couldn't
6201 * sleep after previous reclaim attempt (node is still unbalanced). In that
6202 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006203 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006204static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6205 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006206{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006207 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006208
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006209 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006210}
6211
Mel Gorman38087d92016-07-28 15:45:49 -07006212static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006213 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006214{
6215 long remaining = 0;
6216 DEFINE_WAIT(wait);
6217
6218 if (freezing(current) || kthread_should_stop())
6219 return;
6220
6221 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6222
Shantanu Goel333b0a42017-05-03 14:53:38 -07006223 /*
6224 * Try to sleep for a short interval. Note that kcompactd will only be
6225 * woken if it is possible to sleep for a short interval. This is
6226 * deliberate on the assumption that if reclaim cannot keep an
6227 * eligible zone balanced that it's also unlikely that compaction will
6228 * succeed.
6229 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006230 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006231 /*
6232 * Compaction records what page blocks it recently failed to
6233 * isolate pages from and skips them in the future scanning.
6234 * When kswapd is going to sleep, it is reasonable to assume
6235 * that pages and compaction may succeed so reset the cache.
6236 */
6237 reset_isolation_suitable(pgdat);
6238
6239 /*
6240 * We have freed the memory, now we should compact it to make
6241 * allocation of the requested order possible.
6242 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006243 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006244
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006245 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006246
6247 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006248 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006249 * order. The values will either be from a wakeup request or
6250 * the previous request that slept prematurely.
6251 */
6252 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006253 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6254 kswapd_highest_zoneidx(pgdat,
6255 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006256
6257 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6258 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006259 }
6260
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006261 finish_wait(&pgdat->kswapd_wait, &wait);
6262 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6263 }
6264
6265 /*
6266 * After a short sleep, check if it was a premature sleep. If not, then
6267 * go fully to sleep until explicitly woken up.
6268 */
Mel Gormand9f21d42016-07-28 15:46:41 -07006269 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006270 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006271 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6272
6273 /*
6274 * vmstat counters are not perfectly accurate and the estimated
6275 * value for counters such as NR_FREE_PAGES can deviate from the
6276 * true value by nr_online_cpus * threshold. To avoid the zone
6277 * watermarks being breached while under pressure, we reduce the
6278 * per-cpu vmstat threshold while kswapd is awake and restore
6279 * them before going back to sleep.
6280 */
6281 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07006282
6283 if (!kthread_should_stop())
6284 schedule();
6285
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006286 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
6287 } else {
6288 if (remaining)
6289 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
6290 else
6291 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
6292 }
6293 finish_wait(&pgdat->kswapd_wait, &wait);
6294}
6295
Linus Torvalds1da177e2005-04-16 15:20:36 -07006296/*
6297 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006298 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006299 *
6300 * This basically trickles out pages so that we have _some_
6301 * free memory available even if there is no other activity
6302 * that frees anything up. This is needed for things like routing
6303 * etc, where we otherwise might have all activity going on in
6304 * asynchronous contexts that cannot page things out.
6305 *
6306 * If there are applications that are active memory-allocators
6307 * (most normal use), this basically shouldn't matter.
6308 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306309int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006310{
Mel Gormane716f2e2017-05-03 14:53:45 -07006311 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006312 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07006313 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006314 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10306315 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006316
Rusty Russell174596a2009-01-01 10:12:29 +10306317 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07006318 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006319
6320 /*
6321 * Tell the memory management that we're a "memory allocator",
6322 * and that if we need more memory we should get access to it
6323 * regardless (see "__alloc_pages()"). "kswapd" should
6324 * never get caught in the normal page freeing logic.
6325 *
6326 * (Kswapd normally doesn't need memory anyway, but sometimes
6327 * you need a small amount of memory in order to be able to
6328 * page out something else, and this flag essentially protects
6329 * us from recursively trying to free more memory as we're
6330 * trying to free the first piece of memory in the first place).
6331 */
Christoph Lameter930d9152006-01-08 01:00:47 -08006332 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07006333 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07006334
Qian Cai5644e1fb2020-04-01 21:10:12 -07006335 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006336 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006337 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08006338 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07006339
Qian Cai5644e1fb2020-04-01 21:10:12 -07006340 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006341 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6342 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07006343
Mel Gorman38087d92016-07-28 15:45:49 -07006344kswapd_try_sleep:
6345 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006346 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07006347
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006348 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08006349 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006350 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6351 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006352 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006353 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006354
David Rientjes8fe23e02009-12-14 17:58:33 -08006355 ret = try_to_freeze();
6356 if (kthread_should_stop())
6357 break;
6358
6359 /*
6360 * We can speed up thawing tasks if we don't call balance_pgdat
6361 * after returning from the refrigerator
6362 */
Mel Gorman38087d92016-07-28 15:45:49 -07006363 if (ret)
6364 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07006365
Mel Gorman38087d92016-07-28 15:45:49 -07006366 /*
6367 * Reclaim begins at the requested order but if a high-order
6368 * reclaim fails then kswapd falls back to reclaiming for
6369 * order-0. If that happens, kswapd will consider sleeping
6370 * for the order it finished reclaiming at (reclaim_order)
6371 * but kcompactd is woken to compact for the original
6372 * request (alloc_order).
6373 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006374 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07006375 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006376 reclaim_order = balance_pgdat(pgdat, alloc_order,
6377 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07006378 if (reclaim_order < alloc_order)
6379 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006380 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08006381
Johannes Weiner71abdc12014-06-06 14:35:35 -07006382 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07006383
Linus Torvalds1da177e2005-04-16 15:20:36 -07006384 return 0;
6385}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306386EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006387
6388/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07006389 * A zone is low on free memory or too fragmented for high-order memory. If
6390 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
6391 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
6392 * has failed or is not needed, still wake up kcompactd if only compaction is
6393 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006394 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07006395void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006396 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006397{
6398 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07006399 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006400
Mel Gorman6aa303d2016-09-01 16:14:55 -07006401 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006402 return;
6403
David Rientjes5ecd9d42018-04-05 16:25:16 -07006404 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006405 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07006406
Qian Cai5644e1fb2020-04-01 21:10:12 -07006407 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006408 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006409
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006410 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
6411 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006412
6413 if (READ_ONCE(pgdat->kswapd_order) < order)
6414 WRITE_ONCE(pgdat->kswapd_order, order);
6415
Con Kolivas8d0986e2005-09-13 01:25:07 -07006416 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006417 return;
Mel Gormane1a55632016-07-28 15:46:26 -07006418
David Rientjes5ecd9d42018-04-05 16:25:16 -07006419 /* Hopeless node, leave it to direct reclaim if possible */
6420 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006421 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
6422 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07006423 /*
6424 * There may be plenty of free memory available, but it's too
6425 * fragmented for high-order allocations. Wake up kcompactd
6426 * and rely on compaction_suitable() to determine if it's
6427 * needed. If it fails, it will defer subsequent attempts to
6428 * ratelimit its work.
6429 */
6430 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006431 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07006432 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07006433 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07006434
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006435 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07006436 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07006437 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006438}
6439
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006440#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07006441/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006442 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006443 * freed pages.
6444 *
6445 * Rather than trying to age LRUs the aim is to preserve the overall
6446 * LRU order by reclaiming preferentially
6447 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07006448 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006449unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006450{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006451 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006452 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07006453 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07006454 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006455 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07006456 .may_writepage = 1,
6457 .may_unmap = 1,
6458 .may_swap = 1,
6459 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07006460 };
Ying Hana09ed5e2011-05-24 17:12:26 -07006461 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006462 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006463 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006464
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01006465 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07006466 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07006467 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08006468
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006469 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006470
Andrew Morton1732d2b012019-07-16 16:26:15 -07006471 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006472 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006473 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006474
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006475 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006476}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006477#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07006478
Yasunori Goto3218ae12006-06-27 02:53:33 -07006479/*
6480 * This kswapd start function will be called by init and node-hot-add.
6481 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
6482 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07006483void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006484{
6485 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306486 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006487
6488 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07006489 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006490
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306491 trace_android_vh_kswapd_per_node(nid, &skip, true);
6492 if (skip)
6493 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006494 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
6495 if (IS_ERR(pgdat->kswapd)) {
6496 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02006497 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07006498 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07006499 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006500 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07006501}
6502
David Rientjes8fe23e02009-12-14 17:58:33 -08006503/*
Jiang Liud8adde12012-07-11 14:01:52 -07006504 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07006505 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08006506 */
6507void kswapd_stop(int nid)
6508{
6509 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306510 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08006511
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306512 trace_android_vh_kswapd_per_node(nid, &skip, false);
6513 if (skip)
6514 return;
Jiang Liud8adde12012-07-11 14:01:52 -07006515 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08006516 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07006517 NODE_DATA(nid)->kswapd = NULL;
6518 }
David Rientjes8fe23e02009-12-14 17:58:33 -08006519}
6520
Linus Torvalds1da177e2005-04-16 15:20:36 -07006521static int __init kswapd_init(void)
6522{
Wei Yang6b700b52020-04-01 21:10:09 -07006523 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08006524
Linus Torvalds1da177e2005-04-16 15:20:36 -07006525 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08006526 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006527 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006528 return 0;
6529}
6530
6531module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006532
6533#ifdef CONFIG_NUMA
6534/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006535 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08006536 *
Mel Gormana5f5f912016-07-28 15:46:32 -07006537 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08006538 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006539 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006540int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006541
Dave Hansen51998362021-02-24 12:09:15 -08006542/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006543 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08006544 * of a node considered for each zone_reclaim. 4 scans 1/16th of
6545 * a zone.
6546 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006547#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08006548
Christoph Lameter9eeff232006-01-18 17:42:31 -08006549/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006550 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07006551 * occur.
6552 */
6553int sysctl_min_unmapped_ratio = 1;
6554
6555/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07006556 * If the number of slab pages in a zone grows beyond this percentage then
6557 * slab reclaim needs to occur.
6558 */
6559int sysctl_min_slab_ratio = 5;
6560
Mel Gorman11fb9982016-07-28 15:46:20 -07006561static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006562{
Mel Gorman11fb9982016-07-28 15:46:20 -07006563 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
6564 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
6565 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006566
6567 /*
6568 * It's possible for there to be more file mapped pages than
6569 * accounted for by the pages on the file LRU lists because
6570 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
6571 */
6572 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
6573}
6574
6575/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07006576static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006577{
Alexandru Moised031a152015-11-05 18:48:08 -08006578 unsigned long nr_pagecache_reclaimable;
6579 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07006580
6581 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006582 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07006583 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07006584 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07006585 * a better estimate
6586 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006587 if (node_reclaim_mode & RECLAIM_UNMAP)
6588 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006589 else
Mel Gormana5f5f912016-07-28 15:46:32 -07006590 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006591
6592 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07006593 if (!(node_reclaim_mode & RECLAIM_WRITE))
6594 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006595
6596 /* Watch for any possible underflows due to delta */
6597 if (unlikely(delta > nr_pagecache_reclaimable))
6598 delta = nr_pagecache_reclaimable;
6599
6600 return nr_pagecache_reclaimable - delta;
6601}
6602
Christoph Lameter0ff38492006-09-25 23:31:52 -07006603/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006604 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006605 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006606static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006607{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08006608 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08006609 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006610 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006611 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08006612 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08006613 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006614 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07006615 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07006616 .priority = NODE_RECLAIM_PRIORITY,
6617 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
6618 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07006619 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006620 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08006621 };
Johannes Weiner57f29762021-08-19 19:04:27 -07006622 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006623
Yafang Shao132bb8c2019-05-13 17:17:53 -07006624 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
6625 sc.gfp_mask);
6626
Christoph Lameter9eeff232006-01-18 17:42:31 -08006627 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07006628 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07006629 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08006630 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006631 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08006632 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006633 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08006634 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07006635 noreclaim_flag = memalloc_noreclaim_save();
6636 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07006637 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08006638
Mel Gormana5f5f912016-07-28 15:46:32 -07006639 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07006640 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07006641 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07006642 * priorities until we have enough memory freed.
6643 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07006644 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07006645 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006646 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07006647 }
Christoph Lameterc84db232006-02-01 03:05:29 -08006648
Andrew Morton1732d2b012019-07-16 16:26:15 -07006649 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006650 current->flags &= ~PF_SWAPWRITE;
6651 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006652 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07006653 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07006654
6655 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
6656
Rik van Riela79311c2009-01-06 14:40:01 -08006657 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006658}
Andrew Morton179e9632006-03-22 00:08:18 -08006659
Mel Gormana5f5f912016-07-28 15:46:32 -07006660int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08006661{
David Rientjesd773ed62007-10-16 23:26:01 -07006662 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006663
6664 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006665 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07006666 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07006667 *
Christoph Lameter96146342006-07-03 00:24:13 -07006668 * A small portion of unmapped file backed pages is needed for
6669 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07006670 * thrown out if the node is overallocated. So we do not reclaim
6671 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07006672 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08006673 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006674 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07006675 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
6676 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07006677 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08006678
6679 /*
David Rientjesd773ed62007-10-16 23:26:01 -07006680 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08006681 */
Mel Gormand0164ad2015-11-06 16:28:21 -08006682 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07006683 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08006684
6685 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006686 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08006687 * have associated processors. This will favor the local processor
6688 * over remote processors and spread off node memory allocations
6689 * as wide as possible.
6690 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006691 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
6692 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07006693
Mel Gormana5f5f912016-07-28 15:46:32 -07006694 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
6695 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07006696
Mel Gormana5f5f912016-07-28 15:46:32 -07006697 ret = __node_reclaim(pgdat, gfp_mask, order);
6698 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07006699
Mel Gorman24cf725182009-06-16 15:33:23 -07006700 if (!ret)
6701 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
6702
David Rientjesd773ed62007-10-16 23:26:01 -07006703 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006704}
Christoph Lameter9eeff232006-01-18 17:42:31 -08006705#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07006706
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006707/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006708 * check_move_unevictable_pages - check pages for evictability and move to
6709 * appropriate zone lru list
6710 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006711 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006712 * Checks pages for evictability, if an evictable page is in the unevictable
6713 * lru list, moves it to the appropriate evictable lru list. This function
6714 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006715 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006716void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006717{
Alex Shi6168d0d2020-12-15 12:34:29 -08006718 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08006719 int pgscanned = 0;
6720 int pgrescued = 0;
6721 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006722
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006723 for (i = 0; i < pvec->nr; i++) {
6724 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006725 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07006726
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006727 if (PageTransTail(page))
6728 continue;
6729
6730 nr_pages = thp_nr_pages(page);
6731 pgscanned += nr_pages;
6732
Alex Shid25b5bd2020-12-15 12:34:16 -08006733 /* block memcg migration during page moving between lru */
6734 if (!TestClearPageLRU(page))
6735 continue;
6736
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08006737 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08006738 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08006739 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08006740 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08006741 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006742 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08006743 }
Alex Shid25b5bd2020-12-15 12:34:16 -08006744 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006745 }
Hugh Dickins24513262012-01-20 14:34:21 -08006746
Alex Shi6168d0d2020-12-15 12:34:29 -08006747 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08006748 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
6749 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08006750 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08006751 } else if (pgscanned) {
6752 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08006753 }
Hugh Dickins850465792012-01-20 14:34:19 -08006754}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006755EXPORT_SYMBOL_GPL(check_move_unevictable_pages);