blob: 093148d7cea79f254c2c1dc45b32eedf9c01bce8 [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001// SPDX-License-Identifier: GPL-2.0
Linus Torvalds1da177e2005-04-16 15:20:36 -07002/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07003 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
4 *
5 * Swap reorganised 29.12.95, Stephen Tweedie.
6 * kswapd added: 7.1.96 sct
7 * Removed kswapd_ctl limits, and swap out as many pages as needed
8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
10 * Multiqueue VM started 5.8.00, Rik van Riel.
11 */
12
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070013#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
Linus Torvalds1da177e2005-04-16 15:20:36 -070015#include <linux/mm.h>
Ingo Molnar5b3cc152017-02-02 20:43:54 +010016#include <linux/sched/mm.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070017#include <linux/module.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090018#include <linux/gfp.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070019#include <linux/kernel_stat.h>
20#include <linux/swap.h>
21#include <linux/pagemap.h>
22#include <linux/init.h>
23#include <linux/highmem.h>
Anton Vorontsov70ddf632013-04-29 15:08:31 -070024#include <linux/vmpressure.h>
Andrew Mortone129b5c2006-09-27 01:50:00 -070025#include <linux/vmstat.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070026#include <linux/file.h>
27#include <linux/writeback.h>
28#include <linux/blkdev.h>
29#include <linux/buffer_head.h> /* for try_to_release_page(),
30 buffer_heads_over_limit */
31#include <linux/mm_inline.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070032#include <linux/backing-dev.h>
33#include <linux/rmap.h>
34#include <linux/topology.h>
35#include <linux/cpu.h>
36#include <linux/cpuset.h>
Mel Gorman3e7d3442011-01-13 15:45:56 -080037#include <linux/compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070038#include <linux/notifier.h>
39#include <linux/rwsem.h>
Rafael J. Wysocki248a0302006-03-22 00:09:04 -080040#include <linux/delay.h>
Yasunori Goto3218ae12006-06-27 02:53:33 -070041#include <linux/kthread.h>
Nigel Cunningham7dfb7102006-12-06 20:34:23 -080042#include <linux/freezer.h>
Balbir Singh66e17072008-02-07 00:13:56 -080043#include <linux/memcontrol.h>
Dave Hansen26aa2d12021-09-02 14:59:16 -070044#include <linux/migrate.h>
Keika Kobayashi873b4772008-07-25 01:48:52 -070045#include <linux/delayacct.h>
Lee Schermerhornaf936a12008-10-18 20:26:53 -070046#include <linux/sysctl.h>
KOSAKI Motohiro929bea72011-04-14 15:22:12 -070047#include <linux/oom.h>
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +000048#include <linux/pagevec.h>
Linus Torvalds268bb0c2011-05-20 12:50:29 -070049#include <linux/prefetch.h>
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070050#include <linux/printk.h>
Ross Zwislerf9fe48b2016-01-22 15:10:40 -080051#include <linux/dax.h>
Johannes Weinereb414682018-10-26 15:06:27 -070052#include <linux/psi.h>
Yu Zhao5280d762022-01-27 19:23:01 -070053#include <linux/pagewalk.h>
54#include <linux/shmem_fs.h>
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 Zhaoa1537a62022-01-27 20:32:37 -07001158
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 Zhaoa1537a62022-01-27 20:32:37 -07001162 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 Zhaoafd94c92022-01-27 20:43:22 -07001425 /* 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 Zhao3eb07702020-09-27 20:49:08 -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 Zhaoa1537a62022-01-27 20:32:37 -07002595 if (lru_gen_enabled())
2596 return;
2597
Yu Zhao3eb07702020-09-27 20:49:08 -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 Zhaof88ed5a2021-01-25 21:12:33 -07002922#ifdef CONFIG_LRU_GEN
2923
2924/******************************************************************************
2925 * shorthand helpers
2926 ******************************************************************************/
2927
Yu Zhaoa1537a62022-01-27 20:32:37 -07002928#define DEFINE_MAX_SEQ(lruvec) \
2929 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2930
2931#define DEFINE_MIN_SEQ(lruvec) \
2932 unsigned long min_seq[ANON_AND_FILE] = { \
2933 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2934 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2935 }
2936
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002937#define for_each_gen_type_zone(gen, type, zone) \
2938 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2939 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2940 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2941
Yu Zhaoa1537a62022-01-27 20:32:37 -07002942static int page_lru_gen(struct page *page)
2943{
2944 unsigned long flags = READ_ONCE(page->flags);
2945
2946 return ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
2947}
2948
2949static int page_lru_tier(struct page *page)
2950{
2951 int refs;
2952 unsigned long flags = READ_ONCE(page->flags);
2953
2954 refs = (flags & LRU_REFS_FLAGS) == LRU_REFS_FLAGS ?
2955 ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) + 1 : 0;
2956
2957 return lru_tier_from_refs(refs);
2958}
2959
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002960static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
2961{
2962 struct pglist_data *pgdat = NODE_DATA(nid);
2963
2964#ifdef CONFIG_MEMCG
2965 if (memcg) {
2966 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2967
2968 /* for hotadd_new_pgdat() */
2969 if (!lruvec->pgdat)
2970 lruvec->pgdat = pgdat;
2971
2972 return lruvec;
2973 }
2974#endif
2975 VM_BUG_ON(!mem_cgroup_disabled());
2976
2977 return pgdat ? &pgdat->__lruvec : NULL;
2978}
2979
Yu Zhaoa1537a62022-01-27 20:32:37 -07002980static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2981{
2982 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2983 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2984
2985 if (!can_demote(pgdat->node_id, sc) &&
2986 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2987 return 0;
2988
2989 return mem_cgroup_swappiness(memcg);
2990}
2991
2992static int get_nr_gens(struct lruvec *lruvec, int type)
2993{
2994 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2995}
2996
2997static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2998{
2999 /* see the comment on lru_gen_struct */
3000 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3001 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3002 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3003}
3004
3005/******************************************************************************
Yu Zhao5280d762022-01-27 19:23:01 -07003006 * mm_struct list
3007 ******************************************************************************/
3008
3009static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3010{
3011 static struct lru_gen_mm_list mm_list = {
3012 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3013 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3014 };
3015
3016#ifdef CONFIG_MEMCG
3017 if (memcg)
3018 return &memcg->mm_list;
3019#endif
3020 VM_BUG_ON(!mem_cgroup_disabled());
3021
3022 return &mm_list;
3023}
3024
3025void lru_gen_add_mm(struct mm_struct *mm)
3026{
3027 int nid;
3028 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3029 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3030
3031 VM_BUG_ON_MM(!list_empty(&mm->lru_gen.list), mm);
3032#ifdef CONFIG_MEMCG
3033 VM_BUG_ON_MM(mm->lru_gen.memcg, mm);
3034 mm->lru_gen.memcg = memcg;
3035#endif
3036 spin_lock(&mm_list->lock);
3037
3038 for_each_node_state(nid, N_MEMORY) {
3039 struct lruvec *lruvec = get_lruvec(memcg, nid);
3040
3041 if (!lruvec)
3042 continue;
3043
3044 if (lruvec->mm_state.tail == &mm_list->fifo)
3045 lruvec->mm_state.tail = &mm->lru_gen.list;
3046 }
3047
3048 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3049
3050 spin_unlock(&mm_list->lock);
3051}
3052
3053void lru_gen_del_mm(struct mm_struct *mm)
3054{
3055 int nid;
3056 struct lru_gen_mm_list *mm_list;
3057 struct mem_cgroup *memcg = NULL;
3058
3059 if (list_empty(&mm->lru_gen.list))
3060 return;
3061
3062#ifdef CONFIG_MEMCG
3063 memcg = mm->lru_gen.memcg;
3064#endif
3065 mm_list = get_mm_list(memcg);
3066
3067 spin_lock(&mm_list->lock);
3068
3069 for_each_node(nid) {
3070 struct lruvec *lruvec = get_lruvec(memcg, nid);
3071
3072 if (!lruvec)
3073 continue;
3074
3075 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3076 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3077
3078 if (lruvec->mm_state.head != &mm->lru_gen.list)
3079 continue;
3080
3081 lruvec->mm_state.head = lruvec->mm_state.head->next;
3082 if (lruvec->mm_state.head == &mm_list->fifo)
3083 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3084 }
3085
3086 list_del_init(&mm->lru_gen.list);
3087
3088 spin_unlock(&mm_list->lock);
3089
3090#ifdef CONFIG_MEMCG
3091 mem_cgroup_put(mm->lru_gen.memcg);
3092 mm->lru_gen.memcg = NULL;
3093#endif
3094}
3095
3096#ifdef CONFIG_MEMCG
3097void lru_gen_migrate_mm(struct mm_struct *mm)
3098{
3099 struct mem_cgroup *memcg;
3100
3101 lockdep_assert_held(&mm->owner->alloc_lock);
3102
3103 /* for mm_update_next_owner() */
3104 if (mem_cgroup_disabled())
3105 return;
3106
3107 rcu_read_lock();
3108 memcg = mem_cgroup_from_task(mm->owner);
3109 rcu_read_unlock();
3110 if (memcg == mm->lru_gen.memcg)
3111 return;
3112
3113 VM_BUG_ON_MM(!mm->lru_gen.memcg, mm);
3114 VM_BUG_ON_MM(list_empty(&mm->lru_gen.list), mm);
3115
3116 lru_gen_del_mm(mm);
3117 lru_gen_add_mm(mm);
3118}
3119#endif
3120
3121/*
3122 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3123 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3124 * bits in a bitmap, k is the number of hash functions and n is the number of
3125 * inserted items.
3126 *
3127 * Page table walkers use one of the two filters to reduce their search space.
3128 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3129 * aging uses the double-buffering technique to flip to the other filter each
3130 * time it produces a new generation. For non-leaf entries that have enough
3131 * leaf entries, the aging carries them over to the next generation in
3132 * walk_pmd_range(); the eviction also report them when walking the rmap
3133 * in lru_gen_look_around().
3134 *
3135 * For future optimizations:
3136 * 1. It's not necessary to keep both filters all the time. The spare one can be
3137 * freed after the RCU grace period and reallocated if needed again.
3138 * 2. And when reallocating, it's worth scaling its size according to the number
3139 * of inserted entries in the other filter, to reduce the memory overhead on
3140 * small systems and false positives on large systems.
3141 * 3. Jenkins' hash function is an alternative to Knuth's.
3142 */
3143#define BLOOM_FILTER_SHIFT 15
3144
3145static inline int filter_gen_from_seq(unsigned long seq)
3146{
3147 return seq % NR_BLOOM_FILTERS;
3148}
3149
3150static void get_item_key(void *item, int *key)
3151{
3152 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3153
3154 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3155
3156 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3157 key[1] = hash >> BLOOM_FILTER_SHIFT;
3158}
3159
3160static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3161{
3162 unsigned long *filter;
3163 int gen = filter_gen_from_seq(seq);
3164
3165 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3166
3167 filter = lruvec->mm_state.filters[gen];
3168 if (filter) {
3169 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3170 return;
3171 }
3172
3173 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT), GFP_ATOMIC);
3174 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3175}
3176
3177static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3178{
3179 int key[2];
3180 unsigned long *filter;
3181 int gen = filter_gen_from_seq(seq);
3182
3183 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3184 if (!filter)
3185 return;
3186
3187 get_item_key(item, key);
3188
3189 if (!test_bit(key[0], filter))
3190 set_bit(key[0], filter);
3191 if (!test_bit(key[1], filter))
3192 set_bit(key[1], filter);
3193}
3194
3195static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3196{
3197 int key[2];
3198 unsigned long *filter;
3199 int gen = filter_gen_from_seq(seq);
3200
3201 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3202 if (!filter)
3203 return true;
3204
3205 get_item_key(item, key);
3206
3207 return test_bit(key[0], filter) && test_bit(key[1], filter);
3208}
3209
3210static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3211{
3212 int i;
3213 int hist;
3214
3215 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3216
3217 if (walk) {
3218 hist = lru_hist_from_seq(walk->max_seq);
3219
3220 for (i = 0; i < NR_MM_STATS; i++) {
3221 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3222 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3223 walk->mm_stats[i] = 0;
3224 }
3225 }
3226
3227 if (NR_HIST_GENS > 1 && last) {
3228 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3229
3230 for (i = 0; i < NR_MM_STATS; i++)
3231 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3232 }
3233}
3234
3235static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3236{
3237 int type;
3238 unsigned long size = 0;
3239 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3240
3241 if (!walk->full_scan && cpumask_empty(mm_cpumask(mm)) &&
3242 !node_isset(pgdat->node_id, mm->lru_gen.nodes))
3243 return true;
3244
3245 node_clear(pgdat->node_id, mm->lru_gen.nodes);
3246
3247 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3248 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3249 get_mm_counter(mm, MM_ANONPAGES) +
3250 get_mm_counter(mm, MM_SHMEMPAGES);
3251 }
3252
3253 if (size < MIN_LRU_BATCH)
3254 return true;
3255
3256 if (mm_is_oom_victim(mm))
3257 return true;
3258
3259 return !mmget_not_zero(mm);
3260}
3261
3262static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3263 struct mm_struct **iter)
3264{
3265 bool first = false;
3266 bool last = true;
3267 struct mm_struct *mm = NULL;
3268 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3269 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3270 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3271
3272 /*
3273 * There are four interesting cases for this page table walker:
3274 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3275 * there is nothing to be done.
3276 * 2. It's the first of the current generation, and it needs to reset
3277 * the Bloom filter for the next generation.
3278 * 3. It reaches the end of mm_list, and it needs to increment
3279 * mm_state->seq; the iteration is done.
3280 * 4. It's the last of the current generation, and it needs to reset the
3281 * mm stats counters for the next generation.
3282 */
3283 if (*iter)
3284 mmput_async(*iter);
3285 else if (walk->max_seq <= READ_ONCE(mm_state->seq))
3286 return false;
3287
3288 spin_lock(&mm_list->lock);
3289
3290 VM_BUG_ON(mm_state->seq + 1 < walk->max_seq);
3291 VM_BUG_ON(*iter && mm_state->seq > walk->max_seq);
3292 VM_BUG_ON(*iter && !mm_state->nr_walkers);
3293
3294 if (walk->max_seq <= mm_state->seq) {
3295 if (!*iter)
3296 last = false;
3297 goto done;
3298 }
3299
3300 if (!mm_state->nr_walkers) {
3301 VM_BUG_ON(mm_state->head && mm_state->head != &mm_list->fifo);
3302
3303 mm_state->head = mm_list->fifo.next;
3304 first = true;
3305 }
3306
3307 while (!mm && mm_state->head != &mm_list->fifo) {
3308 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3309
3310 mm_state->head = mm_state->head->next;
3311
3312 /* full scan for those added after the last iteration */
3313 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3314 mm_state->tail = mm_state->head;
3315 walk->full_scan = true;
3316 }
3317
3318 if (should_skip_mm(mm, walk))
3319 mm = NULL;
3320 }
3321
3322 if (mm_state->head == &mm_list->fifo)
3323 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3324done:
3325 if (*iter && !mm)
3326 mm_state->nr_walkers--;
3327 if (!*iter && mm)
3328 mm_state->nr_walkers++;
3329
3330 if (mm_state->nr_walkers)
3331 last = false;
3332
3333 if (mm && first)
3334 reset_bloom_filter(lruvec, walk->max_seq + 1);
3335
3336 if (*iter || last)
3337 reset_mm_stats(lruvec, walk, last);
3338
3339 spin_unlock(&mm_list->lock);
3340
3341 *iter = mm;
3342
3343 return last;
3344}
3345
3346static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3347{
3348 bool success = false;
3349 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3350 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3351 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3352
3353 if (max_seq <= READ_ONCE(mm_state->seq))
3354 return false;
3355
3356 spin_lock(&mm_list->lock);
3357
3358 VM_BUG_ON(mm_state->seq + 1 < max_seq);
3359
3360 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3361 VM_BUG_ON(mm_state->head && mm_state->head != &mm_list->fifo);
3362
3363 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3364 reset_mm_stats(lruvec, NULL, true);
3365 success = true;
3366 }
3367
3368 spin_unlock(&mm_list->lock);
3369
3370 return success;
3371}
3372
3373/******************************************************************************
Yu Zhaoa1537a62022-01-27 20:32:37 -07003374 * refault feedback loop
3375 ******************************************************************************/
3376
3377/*
3378 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3379 *
3380 * The P term is refaulted/(evicted+protected) from a tier in the generation
3381 * currently being evicted; the I term is the exponential moving average of the
3382 * P term over the generations previously evicted, using the smoothing factor
3383 * 1/2; the D term isn't supported.
3384 *
3385 * The setpoint (SP) is always the first tier of one type; the process variable
3386 * (PV) is either any tier of the other type or any other tier of the same
3387 * type.
3388 *
3389 * The error is the difference between the SP and the PV; the correction is
3390 * turn off protection when SP>PV or turn on protection when SP<PV.
3391 *
3392 * For future optimizations:
3393 * 1. The D term may discount the other two terms over time so that long-lived
3394 * generations can resist stale information.
3395 */
3396struct ctrl_pos {
3397 unsigned long refaulted;
3398 unsigned long total;
3399 int gain;
3400};
3401
3402static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3403 struct ctrl_pos *pos)
3404{
3405 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3406 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3407
3408 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3409 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3410 pos->total = lrugen->avg_total[type][tier] +
3411 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3412 if (tier)
3413 pos->total += lrugen->protected[hist][type][tier - 1];
3414 pos->gain = gain;
3415}
3416
3417static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3418{
3419 int hist, tier;
3420 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3421 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3422 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3423
3424 lockdep_assert_held(&lruvec->lru_lock);
3425
3426 if (!carryover && !clear)
3427 return;
3428
3429 hist = lru_hist_from_seq(seq);
3430
3431 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3432 if (carryover) {
3433 unsigned long sum;
3434
3435 sum = lrugen->avg_refaulted[type][tier] +
3436 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3437 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3438
3439 sum = lrugen->avg_total[type][tier] +
3440 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3441 if (tier)
3442 sum += lrugen->protected[hist][type][tier - 1];
3443 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3444 }
3445
3446 if (clear) {
3447 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3448 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3449 if (tier)
3450 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3451 }
3452 }
3453}
3454
3455static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3456{
3457 /*
3458 * Return true if the PV has a limited number of refaults or a lower
3459 * refaulted/total than the SP.
3460 */
3461 return pv->refaulted < MIN_LRU_BATCH ||
3462 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3463 (sp->refaulted + 1) * pv->total * pv->gain;
3464}
3465
3466/******************************************************************************
3467 * the aging
3468 ******************************************************************************/
3469
Yu Zhaoafd94c92022-01-27 20:43:22 -07003470static int page_update_gen(struct page *page, int gen)
3471{
3472 unsigned long old_flags, new_flags;
3473
3474 VM_BUG_ON(gen >= MAX_NR_GENS);
3475 VM_BUG_ON(!rcu_read_lock_held());
3476
3477 do {
3478 new_flags = old_flags = READ_ONCE(page->flags);
3479
3480 /* for shrink_page_list() */
3481 if (!(new_flags & LRU_GEN_MASK)) {
3482 new_flags |= BIT(PG_referenced);
3483 continue;
3484 }
3485
3486 new_flags &= ~LRU_GEN_MASK;
3487 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3488 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3489 } while (new_flags != old_flags &&
3490 cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3491
3492 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3493}
3494
Yu Zhaoa1537a62022-01-27 20:32:37 -07003495static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3496{
3497 unsigned long old_flags, new_flags;
3498 int type = page_is_file_lru(page);
3499 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3500 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3501
3502 do {
3503 new_flags = old_flags = READ_ONCE(page->flags);
3504 VM_BUG_ON_PAGE(!(new_flags & LRU_GEN_MASK), page);
3505
Yu Zhaoafd94c92022-01-27 20:43:22 -07003506 new_gen = ((new_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3507 /* page_update_gen() has promoted this page? */
3508 if (new_gen >= 0 && new_gen != old_gen)
3509 return new_gen;
3510
Yu Zhaoa1537a62022-01-27 20:32:37 -07003511 new_gen = (old_gen + 1) % MAX_NR_GENS;
3512
3513 new_flags &= ~LRU_GEN_MASK;
3514 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3515 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3516 /* for end_page_writeback() */
3517 if (reclaiming)
3518 new_flags |= BIT(PG_reclaim);
3519 } while (cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3520
3521 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3522
3523 return new_gen;
3524}
3525
Yu Zhao5280d762022-01-27 19:23:01 -07003526static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3527 int old_gen, int new_gen)
3528{
3529 int type = page_is_file_lru(page);
3530 int zone = page_zonenum(page);
3531 int delta = thp_nr_pages(page);
3532
3533 VM_BUG_ON(old_gen >= MAX_NR_GENS);
3534 VM_BUG_ON(new_gen >= MAX_NR_GENS);
3535
3536 walk->batched++;
3537
3538 walk->nr_pages[old_gen][type][zone] -= delta;
3539 walk->nr_pages[new_gen][type][zone] += delta;
3540}
3541
3542static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3543{
3544 int gen, type, zone;
3545 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3546
3547 walk->batched = 0;
3548
3549 for_each_gen_type_zone(gen, type, zone) {
3550 enum lru_list lru = type * LRU_INACTIVE_FILE;
3551 int delta = walk->nr_pages[gen][type][zone];
3552
3553 if (!delta)
3554 continue;
3555
3556 walk->nr_pages[gen][type][zone] = 0;
3557 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3558 lrugen->nr_pages[gen][type][zone] + delta);
3559
3560 if (lru_gen_is_active(lruvec, gen))
3561 lru += LRU_ACTIVE;
3562 __update_lru_size(lruvec, lru, zone, delta);
3563 }
3564}
3565
3566static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *walk)
3567{
3568 struct address_space *mapping;
3569 struct vm_area_struct *vma = walk->vma;
3570 struct lru_gen_mm_walk *priv = walk->private;
3571
3572 if (!vma_is_accessible(vma) || is_vm_hugetlb_page(vma) ||
3573 (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ)) ||
3574 vma == get_gate_vma(vma->vm_mm))
3575 return true;
3576
3577 if (vma_is_anonymous(vma))
3578 return !priv->can_swap;
3579
3580 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3581 return true;
3582
3583 mapping = vma->vm_file->f_mapping;
3584 if (mapping_unevictable(mapping))
3585 return true;
3586
3587 /* check readpage to exclude special mappings like dax, etc. */
3588 return shmem_mapping(mapping) ? !priv->can_swap : !mapping->a_ops->readpage;
3589}
3590
3591/*
3592 * Some userspace memory allocators map many single-page VMAs. Instead of
3593 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3594 * table to reduce zigzags and improve cache performance.
3595 */
3596static bool get_next_vma(struct mm_walk *walk, unsigned long mask, unsigned long size,
3597 unsigned long *start, unsigned long *end)
3598{
3599 unsigned long next = round_up(*end, size);
3600
3601 VM_BUG_ON(mask & size);
3602 VM_BUG_ON(*start >= *end);
3603 VM_BUG_ON((next & mask) != (*start & mask));
3604
3605 while (walk->vma) {
3606 if (next >= walk->vma->vm_end) {
3607 walk->vma = walk->vma->vm_next;
3608 continue;
3609 }
3610
3611 if ((next & mask) != (walk->vma->vm_start & mask))
3612 return false;
3613
3614 if (should_skip_vma(walk->vma->vm_start, walk->vma->vm_end, walk)) {
3615 walk->vma = walk->vma->vm_next;
3616 continue;
3617 }
3618
3619 *start = max(next, walk->vma->vm_start);
3620 next = (next | ~mask) + 1;
3621 /* rounded-up boundaries can wrap to 0 */
3622 *end = next && next < walk->vma->vm_end ? next : walk->vma->vm_end;
3623
3624 return true;
3625 }
3626
3627 return false;
3628}
3629
3630static bool suitable_to_scan(int total, int young)
3631{
3632 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3633
3634 /* suitable if the average number of young PTEs per cacheline is >=1 */
3635 return young * n >= total;
3636}
3637
3638static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3639 struct mm_walk *walk)
3640{
3641 int i;
3642 pte_t *pte;
3643 spinlock_t *ptl;
3644 unsigned long addr;
3645 int total = 0;
3646 int young = 0;
3647 struct lru_gen_mm_walk *priv = walk->private;
3648 struct mem_cgroup *memcg = lruvec_memcg(priv->lruvec);
3649 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3650 int old_gen, new_gen = lru_gen_from_seq(priv->max_seq);
3651
3652 VM_BUG_ON(pmd_leaf(*pmd));
3653
3654 ptl = pte_lockptr(walk->mm, pmd);
3655 if (!spin_trylock(ptl))
3656 return false;
3657
3658 arch_enter_lazy_mmu_mode();
3659
3660 pte = pte_offset_map(pmd, start & PMD_MASK);
3661restart:
3662 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3663 struct page *page;
3664 unsigned long pfn = pte_pfn(pte[i]);
3665
3666 VM_BUG_ON(addr < walk->vma->vm_start || addr >= walk->vma->vm_end);
3667
3668 total++;
3669 priv->mm_stats[MM_PTE_TOTAL]++;
3670
3671 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
3672 continue;
3673
3674 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
3675 continue;
3676
3677 if (!pte_young(pte[i])) {
3678 priv->mm_stats[MM_PTE_OLD]++;
3679 continue;
3680 }
3681
3682 VM_BUG_ON(!pfn_valid(pfn));
3683 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3684 continue;
3685
3686 page = compound_head(pfn_to_page(pfn));
3687 if (page_to_nid(page) != pgdat->node_id)
3688 continue;
3689
3690 if (page_memcg_rcu(page) != memcg)
3691 continue;
3692
3693 if (!ptep_test_and_clear_young(walk->vma, addr, pte + i))
3694 continue;
3695
3696 young++;
3697 priv->mm_stats[MM_PTE_YOUNG]++;
3698
3699 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3700 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3701 set_page_dirty(page);
3702
3703 old_gen = page_update_gen(page, new_gen);
3704 if (old_gen >= 0 && old_gen != new_gen)
3705 update_batch_size(priv, page, old_gen, new_gen);
3706 }
3707
3708 if (i < PTRS_PER_PTE && get_next_vma(walk, PMD_MASK, PAGE_SIZE, &start, &end))
3709 goto restart;
3710
3711 pte_unmap(pte);
3712
3713 arch_leave_lazy_mmu_mode();
3714 spin_unlock(ptl);
3715
3716 return suitable_to_scan(total, young);
3717}
3718
3719#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3720static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3721 struct mm_walk *walk, unsigned long *start)
3722{
3723 int i;
3724 pmd_t *pmd;
3725 spinlock_t *ptl;
3726 struct lru_gen_mm_walk *priv = walk->private;
3727 struct mem_cgroup *memcg = lruvec_memcg(priv->lruvec);
3728 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3729 int old_gen, new_gen = lru_gen_from_seq(priv->max_seq);
3730
3731 VM_BUG_ON(pud_leaf(*pud));
3732
3733 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3734 if (*start == -1) {
3735 *start = next;
3736 return;
3737 }
3738
3739 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3740 if (i && i <= MIN_LRU_BATCH) {
3741 __set_bit(i - 1, priv->bitmap);
3742 return;
3743 }
3744
3745 pmd = pmd_offset(pud, *start);
3746
3747 ptl = pmd_lockptr(walk->mm, pmd);
3748 if (!spin_trylock(ptl))
3749 goto done;
3750
3751 arch_enter_lazy_mmu_mode();
3752
3753 do {
3754 struct page *page;
3755 unsigned long pfn = pmd_pfn(pmd[i]);
3756 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3757
3758 VM_BUG_ON(addr < vma->vm_start || addr >= vma->vm_end);
3759
3760 if (!pmd_present(pmd[i]) || is_huge_zero_pmd(pmd[i]))
3761 goto next;
3762
3763 if (WARN_ON_ONCE(pmd_devmap(pmd[i])))
3764 goto next;
3765
3766 if (!pmd_trans_huge(pmd[i])) {
Kalesh Singh8994fcd2022-11-07 15:57:18 -08003767 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG))
Yu Zhao5280d762022-01-27 19:23:01 -07003768 pmdp_test_and_clear_young(vma, addr, pmd + i);
3769 goto next;
3770 }
3771
3772 VM_BUG_ON(!pfn_valid(pfn));
3773 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3774 goto next;
3775
3776 page = pfn_to_page(pfn);
3777 VM_BUG_ON_PAGE(PageTail(page), page);
3778 if (page_to_nid(page) != pgdat->node_id)
3779 goto next;
3780
3781 if (page_memcg_rcu(page) != memcg)
3782 goto next;
3783
3784 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3785 goto next;
3786
3787 priv->mm_stats[MM_PTE_YOUNG]++;
3788
3789 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3790 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3791 set_page_dirty(page);
3792
3793 old_gen = page_update_gen(page, new_gen);
3794 if (old_gen >= 0 && old_gen != new_gen)
3795 update_batch_size(priv, page, old_gen, new_gen);
3796next:
3797 i = i > MIN_LRU_BATCH ? 0 :
3798 find_next_bit(priv->bitmap, MIN_LRU_BATCH, i) + 1;
3799 } while (i <= MIN_LRU_BATCH);
3800
3801 arch_leave_lazy_mmu_mode();
3802 spin_unlock(ptl);
3803done:
3804 *start = -1;
3805 bitmap_zero(priv->bitmap, MIN_LRU_BATCH);
3806}
3807#else
3808static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3809 struct mm_walk *walk, unsigned long *start)
3810{
3811}
3812#endif
3813
3814static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3815 struct mm_walk *walk)
3816{
3817 int i;
3818 pmd_t *pmd;
3819 unsigned long next;
3820 unsigned long addr;
3821 struct vm_area_struct *vma;
3822 unsigned long pos = -1;
3823 struct lru_gen_mm_walk *priv = walk->private;
3824
3825 VM_BUG_ON(pud_leaf(*pud));
3826
3827 /*
3828 * Finish an entire PMD in two passes: the first only reaches to PTE
3829 * tables to avoid taking the PMD lock; the second, if necessary, takes
3830 * the PMD lock to clear the accessed bit in PMD entries.
3831 */
3832 pmd = pmd_offset(pud, start & PUD_MASK);
3833restart:
3834 /* walk_pte_range() may call get_next_vma() */
3835 vma = walk->vma;
3836 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3837 pmd_t val = pmd_read_atomic(pmd + i);
3838
3839 /* for pmd_read_atomic() */
3840 barrier();
3841
3842 next = pmd_addr_end(addr, end);
3843
3844 if (!pmd_present(val)) {
3845 priv->mm_stats[MM_PTE_TOTAL]++;
3846 continue;
3847 }
3848
3849#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3850 if (pmd_trans_huge(val)) {
3851 unsigned long pfn = pmd_pfn(val);
3852 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3853
3854 priv->mm_stats[MM_PTE_TOTAL]++;
3855
3856 if (is_huge_zero_pmd(val))
3857 continue;
3858
3859 if (!pmd_young(val)) {
3860 priv->mm_stats[MM_PTE_OLD]++;
3861 continue;
3862 }
3863
3864 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3865 continue;
3866
3867 walk_pmd_range_locked(pud, addr, vma, walk, &pos);
3868 continue;
3869 }
3870#endif
3871 priv->mm_stats[MM_PMD_TOTAL]++;
3872
3873#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
Kalesh Singh8994fcd2022-11-07 15:57:18 -08003874 if (!pmd_young(val))
3875 continue;
Yu Zhao5280d762022-01-27 19:23:01 -07003876
Kalesh Singh8994fcd2022-11-07 15:57:18 -08003877 walk_pmd_range_locked(pud, addr, vma, walk, &pos);
Yu Zhao5280d762022-01-27 19:23:01 -07003878#endif
3879 if (!priv->full_scan && !test_bloom_filter(priv->lruvec, priv->max_seq, pmd + i))
3880 continue;
3881
3882 priv->mm_stats[MM_PMD_FOUND]++;
3883
3884 if (!walk_pte_range(&val, addr, next, walk))
3885 continue;
3886
3887 priv->mm_stats[MM_PMD_ADDED]++;
3888
3889 /* carry over to the next generation */
3890 update_bloom_filter(priv->lruvec, priv->max_seq + 1, pmd + i);
3891 }
3892
3893 walk_pmd_range_locked(pud, -1, vma, walk, &pos);
3894
3895 if (i < PTRS_PER_PMD && get_next_vma(walk, PUD_MASK, PMD_SIZE, &start, &end))
3896 goto restart;
3897}
3898
3899static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3900 struct mm_walk *walk)
3901{
3902 int i;
3903 pud_t *pud;
3904 unsigned long addr;
3905 unsigned long next;
3906 struct lru_gen_mm_walk *priv = walk->private;
3907
3908 VM_BUG_ON(p4d_leaf(*p4d));
3909
3910 pud = pud_offset(p4d, start & P4D_MASK);
3911restart:
3912 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3913 pud_t val = READ_ONCE(pud[i]);
3914
3915 next = pud_addr_end(addr, end);
3916
3917 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3918 continue;
3919
3920 walk_pmd_range(&val, addr, next, walk);
3921
3922 if (priv->batched >= MAX_LRU_BATCH) {
3923 end = (addr | ~PUD_MASK) + 1;
3924 goto done;
3925 }
3926 }
3927
3928 if (i < PTRS_PER_PUD && get_next_vma(walk, P4D_MASK, PUD_SIZE, &start, &end))
3929 goto restart;
3930
3931 end = round_up(end, P4D_SIZE);
3932done:
3933 /* rounded-up boundaries can wrap to 0 */
3934 priv->next_addr = end && walk->vma ? max(end, walk->vma->vm_start) : 0;
3935
3936 return -EAGAIN;
3937}
3938
3939static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3940{
3941 static const struct mm_walk_ops mm_walk_ops = {
3942 .test_walk = should_skip_vma,
3943 .p4d_entry = walk_pud_range,
3944 };
3945
3946 int err;
3947 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3948
3949 walk->next_addr = FIRST_USER_ADDRESS;
3950
3951 do {
3952 err = -EBUSY;
3953
3954 /* page_update_gen() requires stable page_memcg() */
3955 if (!mem_cgroup_trylock_pages(memcg))
3956 break;
3957
3958 /* the caller might be holding the lock for write */
3959 if (mmap_read_trylock(mm)) {
3960 unsigned long start = walk->next_addr;
3961 unsigned long end = mm->highest_vm_end;
3962
3963 err = walk_page_range(mm, start, end, &mm_walk_ops, walk);
3964
3965 mmap_read_unlock(mm);
3966
3967 if (walk->batched) {
3968 spin_lock_irq(&lruvec->lru_lock);
3969 reset_batch_size(lruvec, walk);
3970 spin_unlock_irq(&lruvec->lru_lock);
3971 }
3972 }
3973
3974 mem_cgroup_unlock_pages();
3975
3976 cond_resched();
3977 } while (err == -EAGAIN && walk->next_addr && !mm_is_oom_victim(mm));
3978}
3979
3980static struct lru_gen_mm_walk *alloc_mm_walk(void)
3981{
3982 if (current->reclaim_state && current->reclaim_state->mm_walk)
3983 return current->reclaim_state->mm_walk;
3984
3985 return kzalloc(sizeof(struct lru_gen_mm_walk),
3986 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3987}
3988
3989static void free_mm_walk(struct lru_gen_mm_walk *walk)
3990{
3991 if (!current->reclaim_state || !current->reclaim_state->mm_walk)
3992 kfree(walk);
3993}
3994
Yu Zhaoa1537a62022-01-27 20:32:37 -07003995static void inc_min_seq(struct lruvec *lruvec)
3996{
3997 int type;
3998 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3999
4000 VM_BUG_ON(!seq_is_valid(lruvec));
4001
4002 for (type = 0; type < ANON_AND_FILE; type++) {
4003 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4004 continue;
4005
4006 reset_ctrl_pos(lruvec, type, true);
4007 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4008 }
4009}
4010
4011static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4012{
4013 int gen, type, zone;
4014 bool success = false;
4015 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4016 DEFINE_MIN_SEQ(lruvec);
4017
4018 VM_BUG_ON(!seq_is_valid(lruvec));
4019
4020 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4021 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4022 gen = lru_gen_from_seq(min_seq[type]);
4023
4024 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4025 if (!list_empty(&lrugen->lists[gen][type][zone]))
4026 goto next;
4027 }
4028
4029 min_seq[type]++;
4030 }
4031next:
4032 ;
4033 }
4034
4035 /* see the comment on lru_gen_struct */
4036 if (can_swap) {
4037 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4038 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4039 }
4040
4041 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4042 if (min_seq[type] == lrugen->min_seq[type])
4043 continue;
4044
4045 reset_ctrl_pos(lruvec, type, true);
4046 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4047 success = true;
4048 }
4049
4050 return success;
4051}
4052
Yu Zhao5280d762022-01-27 19:23:01 -07004053static void inc_max_seq(struct lruvec *lruvec)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004054{
4055 int prev, next;
4056 int type, zone;
4057 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4058
4059 spin_lock_irq(&lruvec->lru_lock);
4060
4061 VM_BUG_ON(!seq_is_valid(lruvec));
4062
Yu Zhaoa1537a62022-01-27 20:32:37 -07004063 inc_min_seq(lruvec);
4064
4065 /*
4066 * Update the active/inactive LRU sizes for compatibility. Both sides of
4067 * the current max_seq need to be covered, since max_seq+1 can overlap
4068 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4069 * overlap, cold/hot inversion happens. This can be solved by moving
4070 * pages from min_seq to min_seq+1 but is omitted for simplicity.
4071 */
4072 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4073 next = lru_gen_from_seq(lrugen->max_seq + 1);
4074
4075 for (type = 0; type < ANON_AND_FILE; type++) {
4076 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4077 enum lru_list lru = type * LRU_INACTIVE_FILE;
4078 long delta = lrugen->nr_pages[prev][type][zone] -
4079 lrugen->nr_pages[next][type][zone];
4080
4081 if (!delta)
4082 continue;
4083
4084 __update_lru_size(lruvec, lru, zone, delta);
4085 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4086 }
4087 }
4088
4089 for (type = 0; type < ANON_AND_FILE; type++)
4090 reset_ctrl_pos(lruvec, type, false);
4091
4092 /* make sure preceding modifications appear */
4093 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao5280d762022-01-27 19:23:01 -07004094
Yu Zhaoa1537a62022-01-27 20:32:37 -07004095 spin_unlock_irq(&lruvec->lru_lock);
4096}
4097
Yu Zhao5280d762022-01-27 19:23:01 -07004098static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4099 struct scan_control *sc, bool can_swap, bool full_scan)
4100{
4101 bool success;
4102 struct lru_gen_mm_walk *walk;
4103 struct mm_struct *mm = NULL;
4104 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4105
4106 VM_BUG_ON(max_seq > READ_ONCE(lrugen->max_seq));
4107
4108 /*
4109 * If the hardware doesn't automatically set the accessed bit, fallback
4110 * to lru_gen_look_around(), which only clears the accessed bit in a
4111 * handful of PTEs. Spreading the work out over a period of time usually
4112 * is less efficient, but it avoids bursty page faults.
4113 */
Kalesh Singh8994fcd2022-11-07 15:57:18 -08004114 if (!full_scan && !arch_has_hw_pte_young()) {
Yu Zhao5280d762022-01-27 19:23:01 -07004115 success = iterate_mm_list_nowalk(lruvec, max_seq);
4116 goto done;
4117 }
4118
4119 walk = alloc_mm_walk();
4120 if (!walk) {
4121 success = iterate_mm_list_nowalk(lruvec, max_seq);
4122 goto done;
4123 }
4124
4125 walk->lruvec = lruvec;
4126 walk->max_seq = max_seq;
4127 walk->can_swap = can_swap;
4128 walk->full_scan = full_scan;
4129
4130 do {
4131 success = iterate_mm_list(lruvec, walk, &mm);
4132 if (mm)
4133 walk_mm(lruvec, mm, walk);
4134
4135 cond_resched();
4136 } while (mm);
4137
4138 free_mm_walk(walk);
4139done:
4140 if (!success) {
4141 if (!current_is_kswapd() && !sc->priority)
4142 wait_event_killable(lruvec->mm_state.wait,
4143 max_seq < READ_ONCE(lrugen->max_seq));
4144
4145 return max_seq < READ_ONCE(lrugen->max_seq);
4146 }
4147
4148 VM_BUG_ON(max_seq != READ_ONCE(lrugen->max_seq));
4149
4150 inc_max_seq(lruvec);
4151 /* either this sees any waiters or they will see updated max_seq */
4152 if (wq_has_sleeper(&lruvec->mm_state.wait))
4153 wake_up_all(&lruvec->mm_state.wait);
4154
4155 wakeup_flusher_threads(WB_REASON_VMSCAN);
4156
4157 return true;
4158}
4159
Yu Zhaoa1537a62022-01-27 20:32:37 -07004160static long get_nr_evictable(struct lruvec *lruvec, unsigned long max_seq,
4161 unsigned long *min_seq, bool can_swap, bool *need_aging)
4162{
4163 int gen, type, zone;
4164 long old = 0;
4165 long young = 0;
4166 long total = 0;
4167 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4168
4169 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4170 unsigned long seq;
4171
4172 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4173 long size = 0;
4174
4175 gen = lru_gen_from_seq(seq);
4176
4177 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4178 size += READ_ONCE(lrugen->nr_pages[gen][type][zone]);
4179
4180 total += size;
4181 if (seq == max_seq)
4182 young += size;
4183 if (seq + MIN_NR_GENS == max_seq)
4184 old += size;
4185 }
4186 }
4187
4188 /*
4189 * The aging and the eviction is a typical producer-consumer model. The
4190 * aging tries to be lazy to reduce the unnecessary overhead. On the
4191 * other hand, the eviction stalls when the number of generations
4192 * reaches MIN_NR_GENS. So ideally, there should be MIN_NR_GENS+1
4193 * generations, hence the first two if's.
4194 *
4195 * In addition, it's ideal to spread pages out evenly, meaning
4196 * 1/(MIN_NR_GENS+1) of the total number of pages for each generation. A
4197 * reasonable range for this average portion would [1/MIN_NR_GENS,
4198 * 1/(MIN_NR_GENS+2)]. From the consumer's POV, the eviction only cares
4199 * about the lower bound of cold pages, i.e., 1/(MIN_NR_GENS+2), whereas
4200 * from the producer's POV, the aging only cares about the upper bound
4201 * of hot pages, i.e., 1/MIN_NR_GENS.
4202 */
4203 if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS > max_seq)
4204 *need_aging = true;
4205 else if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS < max_seq)
4206 *need_aging = false;
4207 else if (young * MIN_NR_GENS > total)
4208 *need_aging = true;
4209 else if (old * (MIN_NR_GENS + 2) < total)
4210 *need_aging = true;
4211 else
4212 *need_aging = false;
4213
4214 return total > 0 ? total : 0;
4215}
4216
Kalesh Singh657801d2022-11-07 15:57:15 -08004217static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004218{
4219 bool need_aging;
4220 long nr_to_scan;
4221 int swappiness = get_swappiness(lruvec, sc);
4222 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4223 DEFINE_MAX_SEQ(lruvec);
4224 DEFINE_MIN_SEQ(lruvec);
4225
4226 mem_cgroup_calculate_protection(NULL, memcg);
4227
4228 if (mem_cgroup_below_min(memcg))
Kalesh Singh657801d2022-11-07 15:57:15 -08004229 return;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004230
4231 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, swappiness, &need_aging);
4232 if (!nr_to_scan)
Kalesh Singh657801d2022-11-07 15:57:15 -08004233 return;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004234
4235 nr_to_scan >>= sc->priority;
4236
4237 if (!mem_cgroup_online(memcg))
4238 nr_to_scan++;
4239
4240 if (nr_to_scan && need_aging && (!mem_cgroup_below_low(memcg) || sc->memcg_low_reclaim))
Yu Zhao5280d762022-01-27 19:23:01 -07004241 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004242}
4243
4244static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4245{
4246 struct mem_cgroup *memcg;
4247
4248 VM_BUG_ON(!current_is_kswapd());
4249
Yu Zhao5280d762022-01-27 19:23:01 -07004250 current->reclaim_state->mm_walk = &pgdat->mm_walk;
4251
Yu Zhaoa1537a62022-01-27 20:32:37 -07004252 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4253 do {
4254 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4255
Kalesh Singh657801d2022-11-07 15:57:15 -08004256 age_lruvec(lruvec, sc);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004257
4258 cond_resched();
4259 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao5280d762022-01-27 19:23:01 -07004260
4261 current->reclaim_state->mm_walk = NULL;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004262}
4263
Yu Zhaoafd94c92022-01-27 20:43:22 -07004264/*
4265 * This function exploits spatial locality when shrink_page_list() walks the
4266 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages.
Yu Zhao5280d762022-01-27 19:23:01 -07004267 * If the scan was done cacheline efficiently, it adds the PMD entry pointing
4268 * to the PTE table to the Bloom filter. This process is a feedback loop from
4269 * the eviction to the aging.
Yu Zhaoafd94c92022-01-27 20:43:22 -07004270 */
4271void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4272{
4273 int i;
4274 pte_t *pte;
4275 unsigned long start;
4276 unsigned long end;
4277 unsigned long addr;
4278 struct page *page;
Yu Zhao5280d762022-01-27 19:23:01 -07004279 struct lru_gen_mm_walk *walk;
4280 int young = 0;
Yu Zhaoafd94c92022-01-27 20:43:22 -07004281 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4282 struct mem_cgroup *memcg = page_memcg(pvmw->page);
4283 struct pglist_data *pgdat = page_pgdat(pvmw->page);
4284 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4285 DEFINE_MAX_SEQ(lruvec);
4286 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4287
4288 lockdep_assert_held(pvmw->ptl);
4289 VM_BUG_ON_PAGE(PageLRU(pvmw->page), pvmw->page);
4290
4291 if (spin_is_contended(pvmw->ptl))
4292 return;
4293
4294 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4295 end = pmd_addr_end(pvmw->address, pvmw->vma->vm_end);
4296
4297 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4298 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4299 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4300 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4301 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4302 else {
4303 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4304 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4305 }
4306 }
4307
4308 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4309
4310 rcu_read_lock();
4311 arch_enter_lazy_mmu_mode();
4312
4313 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4314 unsigned long pfn = pte_pfn(pte[i]);
4315
4316 VM_BUG_ON(addr < pvmw->vma->vm_start || addr >= pvmw->vma->vm_end);
4317
4318 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
4319 continue;
4320
4321 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
4322 continue;
4323
4324 if (!pte_young(pte[i]))
4325 continue;
4326
4327 VM_BUG_ON(!pfn_valid(pfn));
4328 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
4329 continue;
4330
4331 page = compound_head(pfn_to_page(pfn));
4332 if (page_to_nid(page) != pgdat->node_id)
4333 continue;
4334
4335 if (page_memcg_rcu(page) != memcg)
4336 continue;
4337
4338 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4339 continue;
4340
Yu Zhao5280d762022-01-27 19:23:01 -07004341 young++;
4342
Yu Zhaoafd94c92022-01-27 20:43:22 -07004343 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4344 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
4345 set_page_dirty(page);
4346
4347 old_gen = page_lru_gen(page);
4348 if (old_gen < 0)
4349 SetPageReferenced(page);
4350 else if (old_gen != new_gen)
4351 __set_bit(i, bitmap);
4352 }
4353
4354 arch_leave_lazy_mmu_mode();
4355 rcu_read_unlock();
4356
Yu Zhao5280d762022-01-27 19:23:01 -07004357 /* feedback from rmap walkers to page table walkers */
4358 if (suitable_to_scan(i, young))
4359 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4360
4361 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4362
4363 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhaoafd94c92022-01-27 20:43:22 -07004364 for_each_set_bit(i, bitmap, MIN_LRU_BATCH)
4365 activate_page(pte_page(pte[i]));
4366 return;
4367 }
4368
4369 /* page_update_gen() requires stable page_memcg() */
4370 if (!mem_cgroup_trylock_pages(memcg))
4371 return;
4372
Yu Zhao5280d762022-01-27 19:23:01 -07004373 if (!walk) {
4374 spin_lock_irq(&lruvec->lru_lock);
4375 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4376 }
Yu Zhaoafd94c92022-01-27 20:43:22 -07004377
4378 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4379 page = compound_head(pte_page(pte[i]));
4380 if (page_memcg_rcu(page) != memcg)
4381 continue;
4382
4383 old_gen = page_update_gen(page, new_gen);
4384 if (old_gen < 0 || old_gen == new_gen)
4385 continue;
4386
Yu Zhao5280d762022-01-27 19:23:01 -07004387 if (walk)
4388 update_batch_size(walk, page, old_gen, new_gen);
4389 else
4390 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhaoafd94c92022-01-27 20:43:22 -07004391 }
4392
Yu Zhao5280d762022-01-27 19:23:01 -07004393 if (!walk)
4394 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhaoafd94c92022-01-27 20:43:22 -07004395
4396 mem_cgroup_unlock_pages();
4397}
4398
Yu Zhaoa1537a62022-01-27 20:32:37 -07004399/******************************************************************************
4400 * the eviction
4401 ******************************************************************************/
4402
4403static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4404{
4405 bool success;
4406 int gen = page_lru_gen(page);
4407 int type = page_is_file_lru(page);
4408 int zone = page_zonenum(page);
4409 int tier = page_lru_tier(page);
4410 int delta = thp_nr_pages(page);
4411 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4412
4413 VM_BUG_ON_PAGE(gen >= MAX_NR_GENS, page);
4414
4415 if (!page_evictable(page)) {
4416 success = lru_gen_del_page(lruvec, page, true);
4417 VM_BUG_ON_PAGE(!success, page);
4418 SetPageUnevictable(page);
4419 add_page_to_lru_list(page, lruvec);
4420 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4421 return true;
4422 }
4423
4424 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4425 success = lru_gen_del_page(lruvec, page, true);
4426 VM_BUG_ON_PAGE(!success, page);
4427 SetPageSwapBacked(page);
4428 add_page_to_lru_list_tail(page, lruvec);
4429 return true;
4430 }
4431
Yu Zhaoafd94c92022-01-27 20:43:22 -07004432 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4433 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4434 return true;
4435 }
4436
Yu Zhaoa1537a62022-01-27 20:32:37 -07004437 if (tier > tier_idx) {
4438 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4439
4440 gen = page_inc_gen(lruvec, page, false);
4441 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4442
4443 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4444 lrugen->protected[hist][type][tier - 1] + delta);
4445 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4446 return true;
4447 }
4448
4449 if (PageLocked(page) || PageWriteback(page) ||
4450 (type == LRU_GEN_FILE && PageDirty(page))) {
4451 gen = page_inc_gen(lruvec, page, true);
4452 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4453 return true;
4454 }
4455
4456 return false;
4457}
4458
4459static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4460{
4461 bool success;
4462
4463 if (!sc->may_unmap && page_mapped(page))
4464 return false;
4465
4466 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4467 (PageDirty(page) || (PageAnon(page) && !PageSwapCache(page))))
4468 return false;
4469
4470 if (!get_page_unless_zero(page))
4471 return false;
4472
4473 if (!TestClearPageLRU(page)) {
4474 put_page(page);
4475 return false;
4476 }
4477
4478 success = lru_gen_del_page(lruvec, page, true);
4479 VM_BUG_ON_PAGE(!success, page);
4480
4481 return true;
4482}
4483
4484static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4485 int type, int tier, struct list_head *list)
4486{
4487 int gen, zone;
4488 enum vm_event_item item;
4489 int sorted = 0;
4490 int scanned = 0;
4491 int isolated = 0;
4492 int remaining = MAX_LRU_BATCH;
4493 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4494 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4495
4496 VM_BUG_ON(!list_empty(list));
4497
4498 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4499 return 0;
4500
4501 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4502
4503 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4504 LIST_HEAD(moved);
4505 int skipped = 0;
4506 struct list_head *head = &lrugen->lists[gen][type][zone];
4507
4508 while (!list_empty(head)) {
4509 struct page *page = lru_to_page(head);
4510 int delta = thp_nr_pages(page);
4511
4512 VM_BUG_ON_PAGE(PageTail(page), page);
4513 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4514 VM_BUG_ON_PAGE(PageActive(page), page);
4515 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4516 VM_BUG_ON_PAGE(page_zonenum(page) != zone, page);
4517
4518 prefetchw_prev_lru_page(page, head, flags);
4519
4520 scanned += delta;
4521
4522 if (sort_page(lruvec, page, tier))
4523 sorted += delta;
4524 else if (isolate_page(lruvec, page, sc)) {
4525 list_add(&page->lru, list);
4526 isolated += delta;
4527 } else {
4528 list_move(&page->lru, &moved);
4529 skipped += delta;
4530 }
4531
4532 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4533 break;
4534 }
4535
4536 if (skipped) {
4537 list_splice(&moved, head);
4538 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4539 }
4540
4541 if (!remaining || isolated >= MIN_LRU_BATCH)
4542 break;
4543 }
4544
4545 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4546 if (!cgroup_reclaim(sc)) {
4547 __count_vm_events(item, isolated);
4548 __count_vm_events(PGREFILL, sorted);
4549 }
4550 __count_memcg_events(memcg, item, isolated);
4551 __count_memcg_events(memcg, PGREFILL, sorted);
4552 __count_vm_events(PGSCAN_ANON + type, isolated);
4553
4554 /*
4555 * There might not be eligible pages due to reclaim_idx, may_unmap and
4556 * may_writepage. Check the remaining to prevent livelock if there is no
4557 * progress.
4558 */
4559 return isolated || !remaining ? scanned : 0;
4560}
4561
4562static int get_tier_idx(struct lruvec *lruvec, int type)
4563{
4564 int tier;
4565 struct ctrl_pos sp, pv;
4566
4567 /*
4568 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4569 * This value is chosen because any other tier would have at least twice
4570 * as many refaults as the first tier.
4571 */
4572 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4573 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4574 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4575 if (!positive_ctrl_err(&sp, &pv))
4576 break;
4577 }
4578
4579 return tier - 1;
4580}
4581
4582static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4583{
4584 int type, tier;
4585 struct ctrl_pos sp, pv;
4586 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4587
4588 /*
4589 * Compare the first tier of anon with that of file to determine which
4590 * type to scan. Also need to compare other tiers of the selected type
4591 * with the first tier of the other type to determine the last tier (of
4592 * the selected type) to evict.
4593 */
4594 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4595 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4596 type = positive_ctrl_err(&sp, &pv);
4597
4598 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4599 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4600 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4601 if (!positive_ctrl_err(&sp, &pv))
4602 break;
4603 }
4604
4605 *tier_idx = tier - 1;
4606
4607 return type;
4608}
4609
4610static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4611 int *type_scanned, struct list_head *list)
4612{
4613 int i;
4614 int type;
4615 int scanned;
4616 int tier = -1;
4617 DEFINE_MIN_SEQ(lruvec);
4618
4619 VM_BUG_ON(!seq_is_valid(lruvec));
4620
4621 /*
4622 * Try to make the obvious choice first. When anon and file are both
4623 * available from the same generation, interpret swappiness 1 as file
4624 * first and 200 as anon first.
4625 */
4626 if (!swappiness)
4627 type = LRU_GEN_FILE;
4628 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4629 type = LRU_GEN_ANON;
4630 else if (swappiness == 1)
4631 type = LRU_GEN_FILE;
4632 else if (swappiness == 200)
4633 type = LRU_GEN_ANON;
4634 else
4635 type = get_type_to_scan(lruvec, swappiness, &tier);
4636
4637 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4638 if (tier < 0)
4639 tier = get_tier_idx(lruvec, type);
4640
4641 scanned = scan_pages(lruvec, sc, type, tier, list);
4642 if (scanned)
4643 break;
4644
4645 type = !type;
4646 tier = -1;
4647 }
4648
4649 *type_scanned = type;
4650
4651 return scanned;
4652}
4653
Kalesh Singh52ed44a2022-11-07 15:57:20 -08004654static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004655{
4656 int type;
4657 int scanned;
4658 int reclaimed;
4659 LIST_HEAD(list);
4660 struct page *page;
4661 enum vm_event_item item;
4662 struct reclaim_stat stat;
Yu Zhao5280d762022-01-27 19:23:01 -07004663 struct lru_gen_mm_walk *walk;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004664 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4665 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4666
4667 spin_lock_irq(&lruvec->lru_lock);
4668
4669 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4670
4671 if (try_to_inc_min_seq(lruvec, swappiness))
4672 scanned++;
4673
4674 if (get_nr_gens(lruvec, LRU_GEN_FILE) == MIN_NR_GENS)
4675 scanned = 0;
4676
4677 spin_unlock_irq(&lruvec->lru_lock);
4678
4679 if (list_empty(&list))
4680 return scanned;
4681
4682 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4683
4684 /*
4685 * To avoid livelock, don't add rejected pages back to the same lists
4686 * they were isolated from. See lru_gen_add_page().
4687 */
4688 list_for_each_entry(page, &list, lru) {
4689 ClearPageReferenced(page);
4690 ClearPageWorkingset(page);
4691
4692 if (PageReclaim(page) && (PageDirty(page) || PageWriteback(page)))
4693 ClearPageActive(page);
4694 else if (page_is_file_lru(page) || PageSwapCache(page))
4695 SetPageActive(page);
4696 }
4697
4698 spin_lock_irq(&lruvec->lru_lock);
4699
4700 move_pages_to_lru(lruvec, &list);
4701
Yu Zhao5280d762022-01-27 19:23:01 -07004702 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4703 if (walk && walk->batched)
4704 reset_batch_size(lruvec, walk);
4705
Yu Zhaoa1537a62022-01-27 20:32:37 -07004706 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4707 if (!cgroup_reclaim(sc))
4708 __count_vm_events(item, reclaimed);
4709 __count_memcg_events(memcg, item, reclaimed);
4710 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4711
4712 spin_unlock_irq(&lruvec->lru_lock);
4713
4714 mem_cgroup_uncharge_list(&list);
4715 free_unref_page_list(&list);
4716
4717 sc->nr_reclaimed += reclaimed;
4718
4719 return scanned;
4720}
4721
4722static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
4723{
4724 bool need_aging;
4725 long nr_to_scan;
4726 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4727 DEFINE_MAX_SEQ(lruvec);
4728 DEFINE_MIN_SEQ(lruvec);
4729
4730 if (mem_cgroup_below_min(memcg) ||
4731 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4732 return 0;
4733
4734 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, can_swap, &need_aging);
4735 if (!nr_to_scan)
4736 return 0;
4737
4738 /* reset the priority if the target has been met */
4739 nr_to_scan >>= sc->nr_reclaimed < sc->nr_to_reclaim ? sc->priority : DEF_PRIORITY;
4740
4741 if (!mem_cgroup_online(memcg))
4742 nr_to_scan++;
4743
4744 if (!nr_to_scan)
4745 return 0;
4746
Kalesh Singh52ed44a2022-11-07 15:57:20 -08004747 if (!need_aging)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004748 return nr_to_scan;
4749
4750 /* leave the work to lru_gen_age_node() */
4751 if (current_is_kswapd())
4752 return 0;
4753
4754 /* try other memcgs before going to the aging path */
4755 if (!cgroup_reclaim(sc) && !sc->force_deactivate) {
4756 sc->skipped_deactivate = true;
4757 return 0;
4758 }
4759
Yu Zhao5280d762022-01-27 19:23:01 -07004760 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
4761 return nr_to_scan;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004762
Yu Zhao5280d762022-01-27 19:23:01 -07004763 return min_seq[LRU_GEN_FILE] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004764}
4765
4766static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4767{
4768 struct blk_plug plug;
4769 long scanned = 0;
Yu Zhao5280d762022-01-27 19:23:01 -07004770 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004771
4772 lru_add_drain();
4773
4774 blk_start_plug(&plug);
4775
Yu Zhao5280d762022-01-27 19:23:01 -07004776 if (current_is_kswapd())
4777 current->reclaim_state->mm_walk = &pgdat->mm_walk;
4778
Yu Zhaoa1537a62022-01-27 20:32:37 -07004779 while (true) {
4780 int delta;
4781 int swappiness;
4782 long nr_to_scan;
4783
4784 if (sc->may_swap)
4785 swappiness = get_swappiness(lruvec, sc);
4786 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4787 swappiness = 1;
4788 else
4789 swappiness = 0;
4790
4791 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
4792 if (!nr_to_scan)
4793 break;
4794
Kalesh Singh52ed44a2022-11-07 15:57:20 -08004795 delta = evict_pages(lruvec, sc, swappiness);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004796 if (!delta)
4797 break;
4798
Yu Zhao4d905e92022-01-27 19:59:54 -07004799 scanned += delta;
Kalesh Singh52ed44a2022-11-07 15:57:20 -08004800 if (scanned >= nr_to_scan)
Yu Zhao4d905e92022-01-27 19:59:54 -07004801 break;
Yu Zhao4d905e92022-01-27 19:59:54 -07004802
Yu Zhaoa1537a62022-01-27 20:32:37 -07004803 cond_resched();
4804 }
4805
Yu Zhao5280d762022-01-27 19:23:01 -07004806 if (current_is_kswapd())
4807 current->reclaim_state->mm_walk = NULL;
4808
Yu Zhaoa1537a62022-01-27 20:32:37 -07004809 blk_finish_plug(&plug);
4810}
4811
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004812/******************************************************************************
4813 * initialization
4814 ******************************************************************************/
4815
4816void lru_gen_init_lruvec(struct lruvec *lruvec)
4817{
4818 int gen, type, zone;
4819 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4820
4821 lrugen->max_seq = MIN_NR_GENS + 1;
4822
4823 for_each_gen_type_zone(gen, type, zone)
4824 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao5280d762022-01-27 19:23:01 -07004825
4826 lruvec->mm_state.seq = MIN_NR_GENS;
4827 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004828}
4829
4830#ifdef CONFIG_MEMCG
4831void lru_gen_init_memcg(struct mem_cgroup *memcg)
4832{
Yu Zhao5280d762022-01-27 19:23:01 -07004833 INIT_LIST_HEAD(&memcg->mm_list.fifo);
4834 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004835}
4836
4837void lru_gen_exit_memcg(struct mem_cgroup *memcg)
4838{
Yu Zhao5280d762022-01-27 19:23:01 -07004839 int i;
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004840 int nid;
4841
4842 for_each_node(nid) {
4843 struct lruvec *lruvec = get_lruvec(memcg, nid);
4844
4845 VM_BUG_ON(memchr_inv(lruvec->lrugen.nr_pages, 0,
4846 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao5280d762022-01-27 19:23:01 -07004847
4848 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
4849 bitmap_free(lruvec->mm_state.filters[i]);
4850 lruvec->mm_state.filters[i] = NULL;
4851 }
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004852 }
4853}
4854#endif
4855
4856static int __init init_lru_gen(void)
4857{
4858 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
4859 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
Yu Zhao5280d762022-01-27 19:23:01 -07004860 BUILD_BUG_ON(sizeof(MM_STAT_CODES) != NR_MM_STATS + 1);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004861
4862 return 0;
4863};
4864late_initcall(init_lru_gen);
4865
Yu Zhaoa1537a62022-01-27 20:32:37 -07004866#else
4867
4868static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4869{
4870}
4871
4872static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4873{
4874}
4875
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004876#endif /* CONFIG_LRU_GEN */
4877
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004878static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004879{
4880 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07004881 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004882 unsigned long nr_to_scan;
4883 enum lru_list lru;
4884 unsigned long nr_reclaimed = 0;
4885 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
4886 struct blk_plug plug;
Mel Gorman1a501902014-06-04 16:10:49 -07004887 bool scan_adjusted;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004888
Yu Zhaoa1537a62022-01-27 20:32:37 -07004889 if (lru_gen_enabled()) {
4890 lru_gen_shrink_lruvec(lruvec, sc);
4891 return;
4892 }
4893
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004894 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004895
Mel Gormane82e0562013-07-03 15:01:44 -07004896 /* Record the original scan target for proportional adjustments later */
4897 memcpy(targets, nr, sizeof(nr));
4898
Mel Gorman1a501902014-06-04 16:10:49 -07004899 /*
4900 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
4901 * event that can occur when there is little memory pressure e.g.
4902 * multiple streaming readers/writers. Hence, we do not abort scanning
4903 * when the requested number of pages are reclaimed when scanning at
4904 * DEF_PRIORITY on the assumption that the fact we are direct
4905 * reclaiming implies that kswapd is not keeping up and it is best to
4906 * do a batch of work at once. For memcg reclaim one check is made to
4907 * abort proportional reclaim if either the file or anon lru has already
4908 * dropped to zero at the first pass.
4909 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08004910 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
Mel Gorman1a501902014-06-04 16:10:49 -07004911 sc->priority == DEF_PRIORITY);
4912
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004913 blk_start_plug(&plug);
4914 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
4915 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07004916 unsigned long nr_anon, nr_file, percentage;
4917 unsigned long nr_scanned;
4918
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004919 for_each_evictable_lru(lru) {
4920 if (nr[lru]) {
4921 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
4922 nr[lru] -= nr_to_scan;
4923
4924 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07004925 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004926 }
4927 }
Mel Gormane82e0562013-07-03 15:01:44 -07004928
Michal Hockobd041732016-12-02 17:26:48 -08004929 cond_resched();
4930
Mel Gormane82e0562013-07-03 15:01:44 -07004931 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
4932 continue;
4933
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004934 /*
Mel Gormane82e0562013-07-03 15:01:44 -07004935 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07004936 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07004937 * proportionally what was requested by get_scan_count(). We
4938 * stop reclaiming one LRU and reduce the amount scanning
4939 * proportional to the original scan target.
4940 */
4941 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
4942 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
4943
Mel Gorman1a501902014-06-04 16:10:49 -07004944 /*
4945 * It's just vindictive to attack the larger once the smaller
4946 * has gone to zero. And given the way we stop scanning the
4947 * smaller below, this makes sure that we only make one nudge
4948 * towards proportionality once we've got nr_to_reclaim.
4949 */
4950 if (!nr_file || !nr_anon)
4951 break;
4952
Mel Gormane82e0562013-07-03 15:01:44 -07004953 if (nr_file > nr_anon) {
4954 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
4955 targets[LRU_ACTIVE_ANON] + 1;
4956 lru = LRU_BASE;
4957 percentage = nr_anon * 100 / scan_target;
4958 } else {
4959 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
4960 targets[LRU_ACTIVE_FILE] + 1;
4961 lru = LRU_FILE;
4962 percentage = nr_file * 100 / scan_target;
4963 }
4964
4965 /* Stop scanning the smaller of the LRU */
4966 nr[lru] = 0;
4967 nr[lru + LRU_ACTIVE] = 0;
4968
4969 /*
4970 * Recalculate the other LRU scan count based on its original
4971 * scan target and the percentage scanning already complete
4972 */
4973 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
4974 nr_scanned = targets[lru] - nr[lru];
4975 nr[lru] = targets[lru] * (100 - percentage) / 100;
4976 nr[lru] -= min(nr[lru], nr_scanned);
4977
4978 lru += LRU_ACTIVE;
4979 nr_scanned = targets[lru] - nr[lru];
4980 nr[lru] = targets[lru] * (100 - percentage) / 100;
4981 nr[lru] -= min(nr[lru], nr_scanned);
4982
4983 scan_adjusted = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004984 }
4985 blk_finish_plug(&plug);
4986 sc->nr_reclaimed += nr_reclaimed;
4987
4988 /*
4989 * Even if we did not try to evict anon pages at all, we want to
4990 * rebalance the anon lru active/inactive ratio.
4991 */
Dave Hansen2f368a92021-09-02 14:59:23 -07004992 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
4993 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004994 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
4995 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004996}
4997
Mel Gorman23b9da52012-05-29 15:06:20 -07004998/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004999static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005000{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005001 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005002 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005003 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005004 return true;
5005
5006 return false;
5007}
5008
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005009/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005010 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5011 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5012 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005013 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005014 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005015 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005016static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005017 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005018 struct scan_control *sc)
5019{
5020 unsigned long pages_for_compaction;
5021 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005022 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005023
5024 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005025 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005026 return false;
5027
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005028 /*
5029 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5030 * number of pages that were scanned. This will return to the caller
5031 * with the risk reclaim/compaction and the resulting allocation attempt
5032 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5033 * allocations through requiring that the full LRU list has been scanned
5034 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5035 * scan, but that approximation was wrong, and there were corner cases
5036 * where always a non-zero amount of pages were scanned.
5037 */
5038 if (!nr_reclaimed)
5039 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005040
Mel Gorman3e7d3442011-01-13 15:45:56 -08005041 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005042 for (z = 0; z <= sc->reclaim_idx; z++) {
5043 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005044 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005045 continue;
5046
5047 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005048 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005049 case COMPACT_CONTINUE:
5050 return false;
5051 default:
5052 /* check next zone */
5053 ;
5054 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005055 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005056
5057 /*
5058 * If we have not reclaimed enough pages for compaction and the
5059 * inactive lists are large enough, continue reclaiming
5060 */
5061 pages_for_compaction = compact_gap(sc->order);
5062 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005063 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005064 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5065
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005066 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005067}
5068
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005069static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005070{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005071 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005072 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005073
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005074 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005075 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005076 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005077 unsigned long reclaimed;
5078 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005079 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08005080
Xunlei Pange3336ca2020-09-04 16:35:27 -07005081 /*
5082 * This loop can become CPU-bound when target memcgs
5083 * aren't eligible for reclaim - either because they
5084 * don't have any reclaimable pages, or because their
5085 * memory is explicitly protected. Avoid soft lockups.
5086 */
5087 cond_resched();
5088
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005089 trace_android_vh_shrink_node_memcgs(memcg, &skip);
5090 if (skip)
5091 continue;
5092
Chris Down45c7f7e2020-08-06 23:22:05 -07005093 mem_cgroup_calculate_protection(target_memcg, memcg);
5094
5095 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005096 /*
5097 * Hard protection.
5098 * If there is no reclaimable memory, OOM.
5099 */
5100 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005101 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005102 /*
5103 * Soft protection.
5104 * Respect the protection only as long as
5105 * there is an unprotected supply
5106 * of reclaimable memory from other cgroups.
5107 */
5108 if (!sc->memcg_low_reclaim) {
5109 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005110 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005111 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005112 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005113 }
5114
Johannes Weinerd2af3392019-11-30 17:55:43 -08005115 reclaimed = sc->nr_reclaimed;
5116 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005117
5118 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005119
Johannes Weinerd2af3392019-11-30 17:55:43 -08005120 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5121 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005122
Johannes Weinerd2af3392019-11-30 17:55:43 -08005123 /* Record the group's reclaim efficiency */
5124 vmpressure(sc->gfp_mask, memcg, false,
5125 sc->nr_scanned - scanned,
5126 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005127
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005128 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5129}
5130
Liu Song6c9e09072020-01-30 22:14:08 -08005131static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005132{
5133 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005134 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005135 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005136 bool reclaimable = false;
5137
Johannes Weiner1b051172019-11-30 17:55:52 -08005138 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5139
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005140again:
5141 memset(&sc->nr, 0, sizeof(sc->nr));
5142
5143 nr_reclaimed = sc->nr_reclaimed;
5144 nr_scanned = sc->nr_scanned;
5145
Yu Zhao3eb07702020-09-27 20:49:08 -06005146 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005147
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005148 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005149
Johannes Weinerd2af3392019-11-30 17:55:43 -08005150 if (reclaim_state) {
5151 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5152 reclaim_state->reclaimed_slab = 0;
5153 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005154
Johannes Weinerd2af3392019-11-30 17:55:43 -08005155 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005156 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005157 sc->nr_scanned - nr_scanned,
5158 sc->nr_reclaimed - nr_reclaimed);
5159
5160 if (sc->nr_reclaimed - nr_reclaimed)
5161 reclaimable = true;
5162
5163 if (current_is_kswapd()) {
5164 /*
5165 * If reclaim is isolating dirty pages under writeback,
5166 * it implies that the long-lived page allocation rate
5167 * is exceeding the page laundering rate. Either the
5168 * global limits are not being effective at throttling
5169 * processes due to the page distribution throughout
5170 * zones or there is heavy usage of a slow backing
5171 * device. The only option is to throttle from reclaim
5172 * context which is not ideal as there is no guarantee
5173 * the dirtying process is throttled in the same way
5174 * balance_dirty_pages() manages.
5175 *
5176 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5177 * count the number of pages under pages flagged for
5178 * immediate reclaim and stall if any are encountered
5179 * in the nr_immediate check below.
5180 */
5181 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5182 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005183
Johannes Weinerd2af3392019-11-30 17:55:43 -08005184 /* Allow kswapd to start writing pages during reclaim.*/
5185 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5186 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005187
5188 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005189 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005190 * reclaim and under writeback (nr_immediate), it
5191 * implies that pages are cycling through the LRU
5192 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005193 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005194 if (sc->nr.immediate)
5195 congestion_wait(BLK_RW_ASYNC, HZ/10);
5196 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005197
Johannes Weinerd2af3392019-11-30 17:55:43 -08005198 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005199 * Tag a node/memcg as congested if all the dirty pages
5200 * scanned were backed by a congested BDI and
5201 * wait_iff_congested will stall.
5202 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005203 * Legacy memcg will stall in page writeback so avoid forcibly
5204 * stalling in wait_iff_congested().
5205 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005206 if ((current_is_kswapd() ||
5207 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005208 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005209 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005210
5211 /*
5212 * Stall direct reclaim for IO completions if underlying BDIs
5213 * and node is congested. Allow kswapd to continue until it
5214 * starts encountering unqueued dirty pages or cycling through
5215 * the LRU too quickly.
5216 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005217 if (!current_is_kswapd() && current_may_throttle() &&
5218 !sc->hibernation_mode &&
5219 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005220 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5221
5222 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5223 sc))
5224 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005225
Johannes Weinerc73322d2017-05-03 14:51:51 -07005226 /*
5227 * Kswapd gives up on balancing particular nodes after too
5228 * many failures to reclaim anything from them and goes to
5229 * sleep. On reclaim progress, reset the failure counter. A
5230 * successful direct reclaim run will revive a dormant kswapd.
5231 */
5232 if (reclaimable)
5233 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005234}
5235
Vlastimil Babka53853e22014-10-09 15:27:02 -07005236/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005237 * Returns true if compaction should go ahead for a costly-order request, or
5238 * the allocation would already succeed without compaction. Return false if we
5239 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07005240 */
Mel Gorman4f588332016-07-28 15:46:38 -07005241static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005242{
Mel Gorman31483b62016-07-28 15:45:46 -07005243 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005244 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005245
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005246 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
5247 if (suitable == COMPACT_SUCCESS)
5248 /* Allocation should succeed already. Don't reclaim. */
5249 return true;
5250 if (suitable == COMPACT_SKIPPED)
5251 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005252 return false;
5253
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005254 /*
5255 * Compaction is already possible, but it takes time to run and there
5256 * are potentially other callers using the pages just freed. So proceed
5257 * with reclaim to make a buffer of free pages available to give
5258 * compaction a reasonable chance of completing and allocating the page.
5259 * Note that we won't actually reclaim the whole buffer in one attempt
5260 * as the target watermark in should_continue_reclaim() is lower. But if
5261 * we are already above the high+gap watermark, don't reclaim at all.
5262 */
5263 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
5264
5265 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005266}
5267
Linus Torvalds1da177e2005-04-16 15:20:36 -07005268/*
5269 * This is the direct reclaim path, for page-allocating processes. We only
5270 * try to reclaim pages from zones which will satisfy the caller's allocation
5271 * request.
5272 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07005273 * If a zone is deemed to be full of pinned pages then just give it a light
5274 * scan then give up on it.
5275 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07005276static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005277{
Mel Gormandd1a2392008-04-28 02:12:17 -07005278 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07005279 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07005280 unsigned long nr_soft_reclaimed;
5281 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07005282 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07005283 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005284
Mel Gormancc715d92012-03-21 16:34:00 -07005285 /*
5286 * If the number of buffer_heads in the machine exceeds the maximum
5287 * allowed level, force direct reclaim to scan the highmem zone as
5288 * highmem pages could be pinning lowmem pages storing buffer_heads
5289 */
Weijie Yang619d0d762014-04-07 15:36:59 -07005290 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07005291 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07005292 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07005293 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07005294 }
Mel Gormancc715d92012-03-21 16:34:00 -07005295
Mel Gormand4debc62010-08-09 17:19:29 -07005296 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07005297 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07005298 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005299 * Take care memory controller reclaiming has small influence
5300 * to global LRU.
5301 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005302 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04005303 if (!cpuset_zone_allowed(zone,
5304 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005305 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005306
Johannes Weiner0b064962014-08-06 16:06:12 -07005307 /*
5308 * If we already have plenty of memory free for
5309 * compaction in this zone, don't free any more.
5310 * Even though compaction is invoked for any
5311 * non-zero order, only frequent costly order
5312 * reclamation is disruptive enough to become a
5313 * noticeable problem, like transparent huge
5314 * page allocations.
5315 */
5316 if (IS_ENABLED(CONFIG_COMPACTION) &&
5317 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07005318 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07005319 sc->compaction_ready = true;
5320 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07005321 }
Johannes Weiner0b064962014-08-06 16:06:12 -07005322
Andrew Morton0608f432013-09-24 15:27:41 -07005323 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07005324 * Shrink each node in the zonelist once. If the
5325 * zonelist is ordered by zone (not the default) then a
5326 * node may be shrunk multiple times but in that case
5327 * the user prefers lower zones being preserved.
5328 */
5329 if (zone->zone_pgdat == last_pgdat)
5330 continue;
5331
5332 /*
Andrew Morton0608f432013-09-24 15:27:41 -07005333 * This steals pages from memory cgroups over softlimit
5334 * and returns the number of reclaimed pages and
5335 * scanned pages. This works for global memory pressure
5336 * and balancing, not for a memcg's limit.
5337 */
5338 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07005339 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07005340 sc->order, sc->gfp_mask,
5341 &nr_soft_scanned);
5342 sc->nr_reclaimed += nr_soft_reclaimed;
5343 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07005344 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005345 }
Nick Piggin408d8542006-09-25 23:31:27 -07005346
Mel Gorman79dafcd2016-07-28 15:45:53 -07005347 /* See comment about same check for global reclaim above */
5348 if (zone->zone_pgdat == last_pgdat)
5349 continue;
5350 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07005351 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005352 }
Mel Gormane0c23272011-10-31 17:09:33 -07005353
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005354 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07005355 * Restore to original mask to avoid the impact on the caller if we
5356 * promoted it to __GFP_HIGHMEM.
5357 */
5358 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005359}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005360
Johannes Weinerb9107182019-11-30 17:55:59 -08005361static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005362{
Johannes Weinerb9107182019-11-30 17:55:59 -08005363 struct lruvec *target_lruvec;
5364 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005365
Yu Zhaoa1537a62022-01-27 20:32:37 -07005366 if (lru_gen_enabled())
5367 return;
5368
Johannes Weinerb9107182019-11-30 17:55:59 -08005369 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07005370 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
5371 target_lruvec->refaults[0] = refaults;
5372 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
5373 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005374}
5375
Linus Torvalds1da177e2005-04-16 15:20:36 -07005376/*
5377 * This is the main entry point to direct page reclaim.
5378 *
5379 * If a full scan of the inactive list fails to free enough memory then we
5380 * are "out of memory" and something needs to be killed.
5381 *
5382 * If the caller is !__GFP_FS then the probability of a failure is reasonably
5383 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02005384 * caller can't do much about. We kick the writeback threads and take explicit
5385 * naps in the hope that some of these pages can be written. But if the
5386 * allocating task holds filesystem locks which prevent writeout this might not
5387 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07005388 *
5389 * returns: 0, if no pages reclaimed
5390 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07005391 */
Mel Gormandac1d272008-04-28 02:12:12 -07005392static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005393 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005394{
Johannes Weiner241994ed2015-02-11 15:26:06 -08005395 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005396 pg_data_t *last_pgdat;
5397 struct zoneref *z;
5398 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005399retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07005400 delayacct_freepages_start();
5401
Johannes Weinerb5ead352019-11-30 17:55:40 -08005402 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07005403 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005404
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005405 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005406 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
5407 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08005408 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07005409 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07005410
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005411 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07005412 break;
5413
5414 if (sc->compaction_ready)
5415 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005416
5417 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08005418 * If we're getting trouble reclaiming, start doing
5419 * writepage even in laptop mode.
5420 */
5421 if (sc->priority < DEF_PRIORITY - 2)
5422 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07005423 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005424
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005425 last_pgdat = NULL;
5426 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
5427 sc->nodemask) {
5428 if (zone->zone_pgdat == last_pgdat)
5429 continue;
5430 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08005431
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005432 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08005433
5434 if (cgroup_reclaim(sc)) {
5435 struct lruvec *lruvec;
5436
5437 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
5438 zone->zone_pgdat);
5439 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
5440 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005441 }
5442
Keika Kobayashi873b4772008-07-25 01:48:52 -07005443 delayacct_freepages_end();
5444
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005445 if (sc->nr_reclaimed)
5446 return sc->nr_reclaimed;
5447
Mel Gorman0cee34f2012-01-12 17:19:49 -08005448 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07005449 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08005450 return 1;
5451
Johannes Weinerb91ac372019-11-30 17:56:02 -08005452 /*
5453 * We make inactive:active ratio decisions based on the node's
5454 * composition of memory, but a restrictive reclaim_idx or a
5455 * memory.low cgroup setting can exempt large amounts of
5456 * memory from reclaim. Neither of which are very common, so
5457 * instead of doing costly eligibility calculations of the
5458 * entire cgroup subtree up front, we assume the estimates are
5459 * good, and retry with forcible deactivation if that fails.
5460 */
5461 if (sc->skipped_deactivate) {
5462 sc->priority = initial_priority;
5463 sc->force_deactivate = 1;
5464 sc->skipped_deactivate = 0;
5465 goto retry;
5466 }
5467
Johannes Weiner241994ed2015-02-11 15:26:06 -08005468 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07005469 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08005470 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08005471 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07005472 sc->memcg_low_reclaim = 1;
5473 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005474 goto retry;
5475 }
5476
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005477 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005478}
5479
Johannes Weinerc73322d2017-05-03 14:51:51 -07005480static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07005481{
5482 struct zone *zone;
5483 unsigned long pfmemalloc_reserve = 0;
5484 unsigned long free_pages = 0;
5485 int i;
5486 bool wmark_ok;
5487
Johannes Weinerc73322d2017-05-03 14:51:51 -07005488 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
5489 return true;
5490
Mel Gorman55150612012-07-31 16:44:35 -07005491 for (i = 0; i <= ZONE_NORMAL; i++) {
5492 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07005493 if (!managed_zone(zone))
5494 continue;
5495
5496 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07005497 continue;
5498
Mel Gorman55150612012-07-31 16:44:35 -07005499 pfmemalloc_reserve += min_wmark_pages(zone);
5500 free_pages += zone_page_state(zone, NR_FREE_PAGES);
5501 }
5502
Mel Gorman675becc2014-06-04 16:07:35 -07005503 /* If there are no reserves (unexpected config) then do not throttle */
5504 if (!pfmemalloc_reserve)
5505 return true;
5506
Mel Gorman55150612012-07-31 16:44:35 -07005507 wmark_ok = free_pages > pfmemalloc_reserve / 2;
5508
5509 /* kswapd must be awake if processes are being throttled */
5510 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005511 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
5512 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005513
Mel Gorman55150612012-07-31 16:44:35 -07005514 wake_up_interruptible(&pgdat->kswapd_wait);
5515 }
5516
5517 return wmark_ok;
5518}
5519
5520/*
5521 * Throttle direct reclaimers if backing storage is backed by the network
5522 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
5523 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08005524 * when the low watermark is reached.
5525 *
5526 * Returns true if a fatal signal was delivered during throttling. If this
5527 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07005528 */
Mel Gorman50694c22012-11-26 16:29:48 -08005529static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07005530 nodemask_t *nodemask)
5531{
Mel Gorman675becc2014-06-04 16:07:35 -07005532 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07005533 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07005534 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07005535
5536 /*
5537 * Kernel threads should not be throttled as they may be indirectly
5538 * responsible for cleaning pages necessary for reclaim to make forward
5539 * progress. kjournald for example may enter direct reclaim while
5540 * committing a transaction where throttling it could forcing other
5541 * processes to block on log_wait_commit().
5542 */
5543 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08005544 goto out;
5545
5546 /*
5547 * If a fatal signal is pending, this process should not throttle.
5548 * It should return quickly so it can exit and free its memory
5549 */
5550 if (fatal_signal_pending(current))
5551 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005552
Mel Gorman675becc2014-06-04 16:07:35 -07005553 /*
5554 * Check if the pfmemalloc reserves are ok by finding the first node
5555 * with a usable ZONE_NORMAL or lower zone. The expectation is that
5556 * GFP_KERNEL will be required for allocating network buffers when
5557 * swapping over the network so ZONE_HIGHMEM is unusable.
5558 *
5559 * Throttling is based on the first usable node and throttled processes
5560 * wait on a queue until kswapd makes progress and wakes them. There
5561 * is an affinity then between processes waking up and where reclaim
5562 * progress has been made assuming the process wakes on the same node.
5563 * More importantly, processes running on remote nodes will not compete
5564 * for remote pfmemalloc reserves and processes on different nodes
5565 * should make reasonable progress.
5566 */
5567 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08005568 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07005569 if (zone_idx(zone) > ZONE_NORMAL)
5570 continue;
5571
5572 /* Throttle based on the first usable node */
5573 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07005574 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07005575 goto out;
5576 break;
5577 }
5578
5579 /* If no zone was usable by the allocation flags then do not throttle */
5580 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08005581 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005582
Mel Gorman68243e72012-07-31 16:44:39 -07005583 /* Account for the throttling */
5584 count_vm_event(PGSCAN_DIRECT_THROTTLE);
5585
Mel Gorman55150612012-07-31 16:44:35 -07005586 /*
5587 * If the caller cannot enter the filesystem, it's possible that it
5588 * is due to the caller holding an FS lock or performing a journal
5589 * transaction in the case of a filesystem like ext[3|4]. In this case,
5590 * it is not safe to block on pfmemalloc_wait as kswapd could be
5591 * blocked waiting on the same lock. Instead, throttle for up to a
5592 * second before continuing.
5593 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07005594 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07005595 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07005596 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07005597 else
5598 /* Throttle until kswapd wakes the process */
5599 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
5600 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08005601
Mel Gorman50694c22012-11-26 16:29:48 -08005602 if (fatal_signal_pending(current))
5603 return true;
5604
5605out:
5606 return false;
Mel Gorman55150612012-07-31 16:44:35 -07005607}
5608
Mel Gormandac1d272008-04-28 02:12:12 -07005609unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07005610 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08005611{
Mel Gorman33906bc2010-08-09 17:19:16 -07005612 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005613 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08005614 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005615 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07005616 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07005617 .order = order,
5618 .nodemask = nodemask,
5619 .priority = DEF_PRIORITY,
5620 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005621 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07005622 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08005623 };
5624
Mel Gorman55150612012-07-31 16:44:35 -07005625 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07005626 * scan_control uses s8 fields for order, priority, and reclaim_idx.
5627 * Confirm they are large enough for max values.
5628 */
5629 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
5630 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
5631 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
5632
5633 /*
Mel Gorman50694c22012-11-26 16:29:48 -08005634 * Do not enter reclaim if fatal signal was delivered while throttled.
5635 * 1 is returned so that the page allocator does not OOM kill at this
5636 * point.
Mel Gorman55150612012-07-31 16:44:35 -07005637 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005638 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07005639 return 1;
5640
Andrew Morton1732d2b012019-07-16 16:26:15 -07005641 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005642 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07005643
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005644 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07005645
5646 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005647 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07005648
5649 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005650}
5651
Andrew Mortonc255a452012-07-31 16:43:02 -07005652#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08005653
Michal Hockod2e5fb92019-08-30 16:04:50 -07005654/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005655unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005656 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07005657 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07005658 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07005659{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005660 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07005661 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07005662 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07005663 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005664 .may_writepage = !laptop_mode,
5665 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07005666 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07005667 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07005668 };
Ying Han0ae5e892011-05-26 16:25:25 -07005669
Michal Hockod2e5fb92019-08-30 16:04:50 -07005670 WARN_ON_ONCE(!current->reclaim_state);
5671
Balbir Singh4e416952009-09-23 15:56:39 -07005672 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
5673 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005674
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005675 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07005676 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005677
Balbir Singh4e416952009-09-23 15:56:39 -07005678 /*
5679 * NOTE: Although we can get the priority field, using it
5680 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07005681 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07005682 * will pick up pages from other mem cgroup's as well. We hack
5683 * the priority and make it zero.
5684 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005685 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005686
5687 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
5688
Ying Han0ae5e892011-05-26 16:25:25 -07005689 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07005690
Balbir Singh4e416952009-09-23 15:56:39 -07005691 return sc.nr_reclaimed;
5692}
5693
Johannes Weiner72835c82012-01-12 17:18:32 -08005694unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005695 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08005696 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005697 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08005698{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005699 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07005700 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08005701 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005702 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07005703 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07005704 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07005705 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07005706 .target_mem_cgroup = memcg,
5707 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08005708 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005709 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005710 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07005711 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08005712 /*
5713 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
5714 * equal pressure on all the nodes. This is based on the assumption that
5715 * the reclaim does not bail out early.
5716 */
5717 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08005718
Andrew Morton1732d2b012019-07-16 16:26:15 -07005719 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005720 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07005721 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07005722
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005723 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07005724
Vlastimil Babka499118e2017-05-08 15:59:50 -07005725 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005726 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005727 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005728
5729 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005730}
Liujie Xie1ed025b2021-06-25 22:21:35 +08005731EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08005732#endif
5733
Mel Gorman1d82de62016-07-28 15:45:43 -07005734static void age_active_anon(struct pglist_data *pgdat,
Mel Gormanef8f2322016-07-28 15:46:05 -07005735 struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005736{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005737 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08005738 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005739
Yu Zhaoa1537a62022-01-27 20:32:37 -07005740 if (lru_gen_enabled()) {
5741 lru_gen_age_node(pgdat, sc);
5742 return;
5743 }
5744
Dave Hansen2f368a92021-09-02 14:59:23 -07005745 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005746 return;
5747
Johannes Weinerb91ac372019-11-30 17:56:02 -08005748 lruvec = mem_cgroup_lruvec(NULL, pgdat);
5749 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
5750 return;
5751
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005752 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5753 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08005754 lruvec = mem_cgroup_lruvec(memcg, pgdat);
5755 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5756 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005757 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5758 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08005759}
5760
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005761static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08005762{
5763 int i;
5764 struct zone *zone;
5765
5766 /*
5767 * Check for watermark boosts top-down as the higher zones
5768 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005769 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08005770 * start prematurely when there is no boosting and a lower
5771 * zone is balanced.
5772 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005773 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08005774 zone = pgdat->node_zones + i;
5775 if (!managed_zone(zone))
5776 continue;
5777
5778 if (zone->watermark_boost)
5779 return true;
5780 }
5781
5782 return false;
5783}
5784
Mel Gormane716f2e2017-05-03 14:53:45 -07005785/*
5786 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005787 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07005788 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005789static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08005790{
Mel Gormane716f2e2017-05-03 14:53:45 -07005791 int i;
5792 unsigned long mark = -1;
5793 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08005794
Mel Gorman1c308442018-12-28 00:35:52 -08005795 /*
5796 * Check watermarks bottom-up as lower zones are more likely to
5797 * meet watermarks.
5798 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005799 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07005800 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07005801
Mel Gormane716f2e2017-05-03 14:53:45 -07005802 if (!managed_zone(zone))
5803 continue;
5804
5805 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005806 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07005807 return true;
5808 }
5809
5810 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005811 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07005812 * need balancing by definition. This can happen if a zone-restricted
5813 * allocation tries to wake a remote kswapd.
5814 */
5815 if (mark == -1)
5816 return true;
5817
5818 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08005819}
5820
Mel Gorman631b6e02017-05-03 14:53:41 -07005821/* Clear pgdat state for congested, dirty or under writeback. */
5822static void clear_pgdat_congested(pg_data_t *pgdat)
5823{
Johannes Weiner1b051172019-11-30 17:55:52 -08005824 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5825
5826 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07005827 clear_bit(PGDAT_DIRTY, &pgdat->flags);
5828 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
5829}
5830
Mel Gorman1741c872011-01-13 15:46:21 -08005831/*
Mel Gorman55150612012-07-31 16:44:35 -07005832 * Prepare kswapd for sleeping. This verifies that there are no processes
5833 * waiting in throttle_direct_reclaim() and that watermarks have been met.
5834 *
5835 * Returns true if kswapd is ready to sleep
5836 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005837static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
5838 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08005839{
Mel Gorman55150612012-07-31 16:44:35 -07005840 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005841 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07005842 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005843 * race between when kswapd checks the watermarks and a process gets
5844 * throttled. There is also a potential race if processes get
5845 * throttled, kswapd wakes, a large process exits thereby balancing the
5846 * zones, which causes kswapd to exit balance_pgdat() before reaching
5847 * the wake up checks. If kswapd is going to sleep, no process should
5848 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
5849 * the wake up is premature, processes will wake kswapd and get
5850 * throttled again. The difference from wake ups in balance_pgdat() is
5851 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07005852 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005853 if (waitqueue_active(&pgdat->pfmemalloc_wait))
5854 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08005855
Johannes Weinerc73322d2017-05-03 14:51:51 -07005856 /* Hopeless node, leave it to direct reclaim */
5857 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
5858 return true;
5859
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005860 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07005861 clear_pgdat_congested(pgdat);
5862 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07005863 }
5864
Shantanu Goel333b0a42017-05-03 14:53:38 -07005865 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08005866}
5867
Linus Torvalds1da177e2005-04-16 15:20:36 -07005868/*
Mel Gorman1d82de62016-07-28 15:45:43 -07005869 * kswapd shrinks a node of pages that are at or below the highest usable
5870 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07005871 *
5872 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07005873 * reclaim or if the lack of progress was due to pages under writeback.
5874 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07005875 */
Mel Gorman1d82de62016-07-28 15:45:43 -07005876static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07005877 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07005878{
Mel Gorman1d82de62016-07-28 15:45:43 -07005879 struct zone *zone;
5880 int z;
Mel Gorman75485362013-07-03 15:01:42 -07005881
Mel Gorman1d82de62016-07-28 15:45:43 -07005882 /* Reclaim a number of pages proportional to the number of zones */
5883 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07005884 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07005885 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07005886 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07005887 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07005888
Mel Gorman1d82de62016-07-28 15:45:43 -07005889 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07005890 }
5891
Mel Gorman1d82de62016-07-28 15:45:43 -07005892 /*
5893 * Historically care was taken to put equal pressure on all zones but
5894 * now pressure is applied based on node LRU order.
5895 */
Mel Gorman970a39a2016-07-28 15:46:35 -07005896 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07005897
5898 /*
5899 * Fragmentation may mean that the system cannot be rebalanced for
5900 * high-order allocations. If twice the allocation size has been
5901 * reclaimed then recheck watermarks only at order-0 to prevent
5902 * excessive reclaim. Assume that a process requested a high-order
5903 * can direct reclaim/compact.
5904 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07005905 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07005906 sc->order = 0;
5907
Mel Gormanb8e83b92013-07-03 15:01:45 -07005908 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07005909}
5910
Mel Gormanc49c2c42021-06-28 19:42:21 -07005911/* Page allocator PCP high watermark is lowered if reclaim is active. */
5912static inline void
5913update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
5914{
5915 int i;
5916 struct zone *zone;
5917
5918 for (i = 0; i <= highest_zoneidx; i++) {
5919 zone = pgdat->node_zones + i;
5920
5921 if (!managed_zone(zone))
5922 continue;
5923
5924 if (active)
5925 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
5926 else
5927 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
5928 }
5929}
5930
5931static inline void
5932set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
5933{
5934 update_reclaim_active(pgdat, highest_zoneidx, true);
5935}
5936
5937static inline void
5938clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
5939{
5940 update_reclaim_active(pgdat, highest_zoneidx, false);
5941}
5942
Mel Gorman75485362013-07-03 15:01:42 -07005943/*
Mel Gorman1d82de62016-07-28 15:45:43 -07005944 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
5945 * that are eligible for use by the caller until at least one zone is
5946 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005947 *
Mel Gorman1d82de62016-07-28 15:45:43 -07005948 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005949 *
5950 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07005951 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08005952 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07005953 * or lower is eligible for reclaim until at least one usable zone is
5954 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005955 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005956static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005957{
Linus Torvalds1da177e2005-04-16 15:20:36 -07005958 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07005959 unsigned long nr_soft_reclaimed;
5960 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07005961 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08005962 unsigned long nr_boost_reclaim;
5963 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
5964 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07005965 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08005966 struct scan_control sc = {
5967 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07005968 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005969 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08005970 };
Omar Sandoval93781322018-06-07 17:07:02 -07005971
Andrew Morton1732d2b012019-07-16 16:26:15 -07005972 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07005973 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07005974 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07005975
Christoph Lameterf8891e52006-06-30 01:55:45 -07005976 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005977
Mel Gorman1c308442018-12-28 00:35:52 -08005978 /*
5979 * Account for the reclaim boost. Note that the zone boost is left in
5980 * place so that parallel allocations that are near the watermark will
5981 * stall or direct reclaim until kswapd is finished.
5982 */
5983 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005984 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08005985 zone = pgdat->node_zones + i;
5986 if (!managed_zone(zone))
5987 continue;
5988
5989 nr_boost_reclaim += zone->watermark_boost;
5990 zone_boosts[i] = zone->watermark_boost;
5991 }
5992 boosted = nr_boost_reclaim;
5993
5994restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07005995 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08005996 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005997 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07005998 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07005999 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006000 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006001 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006002
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006003 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006004
Mel Gorman86c79f62016-07-28 15:45:59 -07006005 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006006 * If the number of buffer_heads exceeds the maximum allowed
6007 * then consider reclaiming from all zones. This has a dual
6008 * purpose -- on 64-bit systems it is expected that
6009 * buffer_heads are stripped during active rotation. On 32-bit
6010 * systems, highmem pages can pin lowmem memory and shrinking
6011 * buffers can relieve lowmem pressure. Reclaim may still not
6012 * go ahead if all eligible zones for the original allocation
6013 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006014 */
6015 if (buffer_heads_over_limit) {
6016 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6017 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006018 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006019 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006020
Mel Gorman970a39a2016-07-28 15:46:35 -07006021 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006022 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006023 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006024 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006025
Mel Gorman86c79f62016-07-28 15:45:59 -07006026 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006027 * If the pgdat is imbalanced then ignore boosting and preserve
6028 * the watermarks for a later time and restart. Note that the
6029 * zone watermarks will be still reset at the end of balancing
6030 * on the grounds that the normal reclaim should be enough to
6031 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006032 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006033 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006034 if (!balanced && nr_boost_reclaim) {
6035 nr_boost_reclaim = 0;
6036 goto restart;
6037 }
6038
6039 /*
6040 * If boosting is not active then only reclaim if there are no
6041 * eligible zones. Note that sc.reclaim_idx is not used as
6042 * buffer_heads_over_limit may have adjusted it.
6043 */
6044 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006045 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006046
Mel Gorman1c308442018-12-28 00:35:52 -08006047 /* Limit the priority of boosting to avoid reclaim writeback */
6048 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6049 raise_priority = false;
6050
6051 /*
6052 * Do not writeback or swap pages for boosted reclaim. The
6053 * intent is to relieve pressure not issue sub-optimal IO
6054 * from reclaim context. If no pages are reclaimed, the
6055 * reclaim will be aborted.
6056 */
6057 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6058 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006059
Linus Torvalds1da177e2005-04-16 15:20:36 -07006060 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006061 * Do some background aging of the anon list, to give
6062 * pages a chance to be referenced before reclaiming. All
6063 * pages are rotated regardless of classzone as this is
6064 * about consistent aging.
6065 */
Mel Gormanef8f2322016-07-28 15:46:05 -07006066 age_active_anon(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006067
6068 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006069 * If we're getting trouble reclaiming, start doing writepage
6070 * even in laptop mode.
6071 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006072 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006073 sc.may_writepage = 1;
6074
Mel Gorman1d82de62016-07-28 15:45:43 -07006075 /* Call soft limit reclaim before calling shrink_node. */
6076 sc.nr_scanned = 0;
6077 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006078 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006079 sc.gfp_mask, &nr_soft_scanned);
6080 sc.nr_reclaimed += nr_soft_reclaimed;
6081
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006082 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006083 * There should be no need to raise the scanning priority if
6084 * enough pages are already being scanned that that high
6085 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006086 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006087 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006088 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006089
6090 /*
6091 * If the low watermark is met there is no need for processes
6092 * to be throttled on pfmemalloc_wait as they should not be
6093 * able to safely make forward progress. Wake them
6094 */
6095 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006096 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006097 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006098
Mel Gormanb8e83b92013-07-03 15:01:45 -07006099 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006100 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006101 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006102 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006103 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006104 break;
6105
6106 /*
6107 * Raise priority if scanning rate is too low or there was no
6108 * progress in reclaiming pages
6109 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006110 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006111 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6112
6113 /*
6114 * If reclaim made no progress for a boost, stop reclaim as
6115 * IO cannot be queued and it could be an infinite loop in
6116 * extreme circumstances.
6117 */
6118 if (nr_boost_reclaim && !nr_reclaimed)
6119 break;
6120
Johannes Weinerc73322d2017-05-03 14:51:51 -07006121 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006122 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006123 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006124
Johannes Weinerc73322d2017-05-03 14:51:51 -07006125 if (!sc.nr_reclaimed)
6126 pgdat->kswapd_failures++;
6127
Mel Gormanb8e83b92013-07-03 15:01:45 -07006128out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006129 clear_reclaim_active(pgdat, highest_zoneidx);
6130
Mel Gorman1c308442018-12-28 00:35:52 -08006131 /* If reclaim was boosted, account for the reclaim done in this pass */
6132 if (boosted) {
6133 unsigned long flags;
6134
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006135 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006136 if (!zone_boosts[i])
6137 continue;
6138
6139 /* Increments are under the zone lock */
6140 zone = pgdat->node_zones + i;
6141 spin_lock_irqsave(&zone->lock, flags);
6142 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6143 spin_unlock_irqrestore(&zone->lock, flags);
6144 }
6145
6146 /*
6147 * As there is now likely space, wakeup kcompact to defragment
6148 * pageblocks.
6149 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006150 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006151 }
6152
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006153 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006154 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006155 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006156 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006157
Mel Gorman0abdee22011-01-13 15:46:22 -08006158 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006159 * Return the order kswapd stopped reclaiming at as
6160 * prepare_kswapd_sleep() takes it into account. If another caller
6161 * entered the allocator slow path while kswapd was awake, order will
6162 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006163 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006164 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006165}
6166
Mel Gormane716f2e2017-05-03 14:53:45 -07006167/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006168 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6169 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6170 * not a valid index then either kswapd runs for first time or kswapd couldn't
6171 * sleep after previous reclaim attempt (node is still unbalanced). In that
6172 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006173 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006174static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6175 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006176{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006177 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006178
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006179 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006180}
6181
Mel Gorman38087d92016-07-28 15:45:49 -07006182static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006183 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006184{
6185 long remaining = 0;
6186 DEFINE_WAIT(wait);
6187
6188 if (freezing(current) || kthread_should_stop())
6189 return;
6190
6191 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6192
Shantanu Goel333b0a42017-05-03 14:53:38 -07006193 /*
6194 * Try to sleep for a short interval. Note that kcompactd will only be
6195 * woken if it is possible to sleep for a short interval. This is
6196 * deliberate on the assumption that if reclaim cannot keep an
6197 * eligible zone balanced that it's also unlikely that compaction will
6198 * succeed.
6199 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006200 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006201 /*
6202 * Compaction records what page blocks it recently failed to
6203 * isolate pages from and skips them in the future scanning.
6204 * When kswapd is going to sleep, it is reasonable to assume
6205 * that pages and compaction may succeed so reset the cache.
6206 */
6207 reset_isolation_suitable(pgdat);
6208
6209 /*
6210 * We have freed the memory, now we should compact it to make
6211 * allocation of the requested order possible.
6212 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006213 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006214
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006215 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006216
6217 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006218 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006219 * order. The values will either be from a wakeup request or
6220 * the previous request that slept prematurely.
6221 */
6222 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006223 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6224 kswapd_highest_zoneidx(pgdat,
6225 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006226
6227 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6228 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006229 }
6230
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006231 finish_wait(&pgdat->kswapd_wait, &wait);
6232 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6233 }
6234
6235 /*
6236 * After a short sleep, check if it was a premature sleep. If not, then
6237 * go fully to sleep until explicitly woken up.
6238 */
Mel Gormand9f21d42016-07-28 15:46:41 -07006239 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006240 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006241 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6242
6243 /*
6244 * vmstat counters are not perfectly accurate and the estimated
6245 * value for counters such as NR_FREE_PAGES can deviate from the
6246 * true value by nr_online_cpus * threshold. To avoid the zone
6247 * watermarks being breached while under pressure, we reduce the
6248 * per-cpu vmstat threshold while kswapd is awake and restore
6249 * them before going back to sleep.
6250 */
6251 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07006252
6253 if (!kthread_should_stop())
6254 schedule();
6255
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006256 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
6257 } else {
6258 if (remaining)
6259 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
6260 else
6261 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
6262 }
6263 finish_wait(&pgdat->kswapd_wait, &wait);
6264}
6265
Linus Torvalds1da177e2005-04-16 15:20:36 -07006266/*
6267 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006268 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006269 *
6270 * This basically trickles out pages so that we have _some_
6271 * free memory available even if there is no other activity
6272 * that frees anything up. This is needed for things like routing
6273 * etc, where we otherwise might have all activity going on in
6274 * asynchronous contexts that cannot page things out.
6275 *
6276 * If there are applications that are active memory-allocators
6277 * (most normal use), this basically shouldn't matter.
6278 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306279int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006280{
Mel Gormane716f2e2017-05-03 14:53:45 -07006281 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006282 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07006283 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006284 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10306285 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006286
Rusty Russell174596a2009-01-01 10:12:29 +10306287 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07006288 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006289
6290 /*
6291 * Tell the memory management that we're a "memory allocator",
6292 * and that if we need more memory we should get access to it
6293 * regardless (see "__alloc_pages()"). "kswapd" should
6294 * never get caught in the normal page freeing logic.
6295 *
6296 * (Kswapd normally doesn't need memory anyway, but sometimes
6297 * you need a small amount of memory in order to be able to
6298 * page out something else, and this flag essentially protects
6299 * us from recursively trying to free more memory as we're
6300 * trying to free the first piece of memory in the first place).
6301 */
Christoph Lameter930d9152006-01-08 01:00:47 -08006302 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07006303 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07006304
Qian Cai5644e1fb2020-04-01 21:10:12 -07006305 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006306 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006307 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08006308 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07006309
Qian Cai5644e1fb2020-04-01 21:10:12 -07006310 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006311 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6312 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07006313
Mel Gorman38087d92016-07-28 15:45:49 -07006314kswapd_try_sleep:
6315 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006316 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07006317
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006318 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08006319 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006320 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6321 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006322 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006323 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006324
David Rientjes8fe23e02009-12-14 17:58:33 -08006325 ret = try_to_freeze();
6326 if (kthread_should_stop())
6327 break;
6328
6329 /*
6330 * We can speed up thawing tasks if we don't call balance_pgdat
6331 * after returning from the refrigerator
6332 */
Mel Gorman38087d92016-07-28 15:45:49 -07006333 if (ret)
6334 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07006335
Mel Gorman38087d92016-07-28 15:45:49 -07006336 /*
6337 * Reclaim begins at the requested order but if a high-order
6338 * reclaim fails then kswapd falls back to reclaiming for
6339 * order-0. If that happens, kswapd will consider sleeping
6340 * for the order it finished reclaiming at (reclaim_order)
6341 * but kcompactd is woken to compact for the original
6342 * request (alloc_order).
6343 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006344 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07006345 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006346 reclaim_order = balance_pgdat(pgdat, alloc_order,
6347 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07006348 if (reclaim_order < alloc_order)
6349 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006350 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08006351
Johannes Weiner71abdc12014-06-06 14:35:35 -07006352 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07006353
Linus Torvalds1da177e2005-04-16 15:20:36 -07006354 return 0;
6355}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306356EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006357
6358/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07006359 * A zone is low on free memory or too fragmented for high-order memory. If
6360 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
6361 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
6362 * has failed or is not needed, still wake up kcompactd if only compaction is
6363 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006364 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07006365void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006366 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006367{
6368 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07006369 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006370
Mel Gorman6aa303d2016-09-01 16:14:55 -07006371 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006372 return;
6373
David Rientjes5ecd9d42018-04-05 16:25:16 -07006374 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006375 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07006376
Qian Cai5644e1fb2020-04-01 21:10:12 -07006377 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006378 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006379
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006380 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
6381 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006382
6383 if (READ_ONCE(pgdat->kswapd_order) < order)
6384 WRITE_ONCE(pgdat->kswapd_order, order);
6385
Con Kolivas8d0986e2005-09-13 01:25:07 -07006386 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006387 return;
Mel Gormane1a55632016-07-28 15:46:26 -07006388
David Rientjes5ecd9d42018-04-05 16:25:16 -07006389 /* Hopeless node, leave it to direct reclaim if possible */
6390 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006391 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
6392 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07006393 /*
6394 * There may be plenty of free memory available, but it's too
6395 * fragmented for high-order allocations. Wake up kcompactd
6396 * and rely on compaction_suitable() to determine if it's
6397 * needed. If it fails, it will defer subsequent attempts to
6398 * ratelimit its work.
6399 */
6400 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006401 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07006402 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07006403 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07006404
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006405 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07006406 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07006407 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006408}
6409
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006410#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07006411/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006412 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006413 * freed pages.
6414 *
6415 * Rather than trying to age LRUs the aim is to preserve the overall
6416 * LRU order by reclaiming preferentially
6417 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07006418 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006419unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006420{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006421 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006422 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07006423 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07006424 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006425 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07006426 .may_writepage = 1,
6427 .may_unmap = 1,
6428 .may_swap = 1,
6429 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07006430 };
Ying Hana09ed5e2011-05-24 17:12:26 -07006431 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006432 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006433 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006434
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01006435 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07006436 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07006437 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08006438
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006439 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006440
Andrew Morton1732d2b012019-07-16 16:26:15 -07006441 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006442 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006443 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006444
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006445 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006446}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006447#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07006448
Yasunori Goto3218ae12006-06-27 02:53:33 -07006449/*
6450 * This kswapd start function will be called by init and node-hot-add.
6451 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
6452 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07006453void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006454{
6455 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306456 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006457
6458 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07006459 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006460
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306461 trace_android_vh_kswapd_per_node(nid, &skip, true);
6462 if (skip)
6463 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006464 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
6465 if (IS_ERR(pgdat->kswapd)) {
6466 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02006467 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07006468 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07006469 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006470 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07006471}
6472
David Rientjes8fe23e02009-12-14 17:58:33 -08006473/*
Jiang Liud8adde12012-07-11 14:01:52 -07006474 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07006475 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08006476 */
6477void kswapd_stop(int nid)
6478{
6479 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306480 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08006481
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306482 trace_android_vh_kswapd_per_node(nid, &skip, false);
6483 if (skip)
6484 return;
Jiang Liud8adde12012-07-11 14:01:52 -07006485 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08006486 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07006487 NODE_DATA(nid)->kswapd = NULL;
6488 }
David Rientjes8fe23e02009-12-14 17:58:33 -08006489}
6490
Linus Torvalds1da177e2005-04-16 15:20:36 -07006491static int __init kswapd_init(void)
6492{
Wei Yang6b700b52020-04-01 21:10:09 -07006493 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08006494
Linus Torvalds1da177e2005-04-16 15:20:36 -07006495 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08006496 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006497 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006498 return 0;
6499}
6500
6501module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006502
6503#ifdef CONFIG_NUMA
6504/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006505 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08006506 *
Mel Gormana5f5f912016-07-28 15:46:32 -07006507 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08006508 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006509 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006510int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006511
Dave Hansen51998362021-02-24 12:09:15 -08006512/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006513 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08006514 * of a node considered for each zone_reclaim. 4 scans 1/16th of
6515 * a zone.
6516 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006517#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08006518
Christoph Lameter9eeff232006-01-18 17:42:31 -08006519/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006520 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07006521 * occur.
6522 */
6523int sysctl_min_unmapped_ratio = 1;
6524
6525/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07006526 * If the number of slab pages in a zone grows beyond this percentage then
6527 * slab reclaim needs to occur.
6528 */
6529int sysctl_min_slab_ratio = 5;
6530
Mel Gorman11fb9982016-07-28 15:46:20 -07006531static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006532{
Mel Gorman11fb9982016-07-28 15:46:20 -07006533 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
6534 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
6535 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006536
6537 /*
6538 * It's possible for there to be more file mapped pages than
6539 * accounted for by the pages on the file LRU lists because
6540 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
6541 */
6542 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
6543}
6544
6545/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07006546static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006547{
Alexandru Moised031a152015-11-05 18:48:08 -08006548 unsigned long nr_pagecache_reclaimable;
6549 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07006550
6551 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006552 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07006553 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07006554 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07006555 * a better estimate
6556 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006557 if (node_reclaim_mode & RECLAIM_UNMAP)
6558 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006559 else
Mel Gormana5f5f912016-07-28 15:46:32 -07006560 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006561
6562 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07006563 if (!(node_reclaim_mode & RECLAIM_WRITE))
6564 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006565
6566 /* Watch for any possible underflows due to delta */
6567 if (unlikely(delta > nr_pagecache_reclaimable))
6568 delta = nr_pagecache_reclaimable;
6569
6570 return nr_pagecache_reclaimable - delta;
6571}
6572
Christoph Lameter0ff38492006-09-25 23:31:52 -07006573/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006574 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006575 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006576static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006577{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08006578 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08006579 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006580 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006581 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08006582 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08006583 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006584 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07006585 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07006586 .priority = NODE_RECLAIM_PRIORITY,
6587 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
6588 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07006589 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006590 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08006591 };
Johannes Weiner57f29762021-08-19 19:04:27 -07006592 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006593
Yafang Shao132bb8c2019-05-13 17:17:53 -07006594 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
6595 sc.gfp_mask);
6596
Christoph Lameter9eeff232006-01-18 17:42:31 -08006597 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07006598 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07006599 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08006600 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006601 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08006602 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006603 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08006604 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07006605 noreclaim_flag = memalloc_noreclaim_save();
6606 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07006607 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08006608
Mel Gormana5f5f912016-07-28 15:46:32 -07006609 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07006610 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07006611 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07006612 * priorities until we have enough memory freed.
6613 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07006614 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07006615 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006616 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07006617 }
Christoph Lameterc84db232006-02-01 03:05:29 -08006618
Andrew Morton1732d2b012019-07-16 16:26:15 -07006619 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006620 current->flags &= ~PF_SWAPWRITE;
6621 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006622 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07006623 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07006624
6625 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
6626
Rik van Riela79311c2009-01-06 14:40:01 -08006627 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006628}
Andrew Morton179e9632006-03-22 00:08:18 -08006629
Mel Gormana5f5f912016-07-28 15:46:32 -07006630int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08006631{
David Rientjesd773ed62007-10-16 23:26:01 -07006632 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006633
6634 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006635 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07006636 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07006637 *
Christoph Lameter96146342006-07-03 00:24:13 -07006638 * A small portion of unmapped file backed pages is needed for
6639 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07006640 * thrown out if the node is overallocated. So we do not reclaim
6641 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07006642 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08006643 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006644 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07006645 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
6646 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07006647 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08006648
6649 /*
David Rientjesd773ed62007-10-16 23:26:01 -07006650 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08006651 */
Mel Gormand0164ad2015-11-06 16:28:21 -08006652 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07006653 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08006654
6655 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006656 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08006657 * have associated processors. This will favor the local processor
6658 * over remote processors and spread off node memory allocations
6659 * as wide as possible.
6660 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006661 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
6662 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07006663
Mel Gormana5f5f912016-07-28 15:46:32 -07006664 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
6665 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07006666
Mel Gormana5f5f912016-07-28 15:46:32 -07006667 ret = __node_reclaim(pgdat, gfp_mask, order);
6668 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07006669
Mel Gorman24cf725182009-06-16 15:33:23 -07006670 if (!ret)
6671 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
6672
David Rientjesd773ed62007-10-16 23:26:01 -07006673 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006674}
Christoph Lameter9eeff232006-01-18 17:42:31 -08006675#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07006676
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006677/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006678 * check_move_unevictable_pages - check pages for evictability and move to
6679 * appropriate zone lru list
6680 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006681 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006682 * Checks pages for evictability, if an evictable page is in the unevictable
6683 * lru list, moves it to the appropriate evictable lru list. This function
6684 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006685 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006686void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006687{
Alex Shi6168d0d2020-12-15 12:34:29 -08006688 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08006689 int pgscanned = 0;
6690 int pgrescued = 0;
6691 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006692
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006693 for (i = 0; i < pvec->nr; i++) {
6694 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006695 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07006696
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006697 if (PageTransTail(page))
6698 continue;
6699
6700 nr_pages = thp_nr_pages(page);
6701 pgscanned += nr_pages;
6702
Alex Shid25b5bd2020-12-15 12:34:16 -08006703 /* block memcg migration during page moving between lru */
6704 if (!TestClearPageLRU(page))
6705 continue;
6706
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08006707 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08006708 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08006709 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08006710 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08006711 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006712 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08006713 }
Alex Shid25b5bd2020-12-15 12:34:16 -08006714 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006715 }
Hugh Dickins24513262012-01-20 14:34:21 -08006716
Alex Shi6168d0d2020-12-15 12:34:29 -08006717 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08006718 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
6719 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08006720 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08006721 } else if (pgscanned) {
6722 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08006723 }
Hugh Dickins850465792012-01-20 14:34:19 -08006724}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006725EXPORT_SYMBOL_GPL(check_move_unevictable_pages);