blob: de7c184786e6b980e47c1fce69b48a2930e01657 [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
Yu Zhao4d905e92022-01-27 19:59:54 -0700133#ifdef CONFIG_LRU_GEN
134 /* help make better choices when multiple memcgs are available */
135 unsigned int memcgs_need_aging:1;
136 unsigned int memcgs_need_swapping:1;
137 unsigned int memcgs_avoid_swapping:1;
138#endif
139
Greg Thelenbb451fd2018-08-17 15:45:19 -0700140 /* Allocation order */
141 s8 order;
142
143 /* Scan (total_size >> priority) pages at once */
144 s8 priority;
145
146 /* The highest zone to isolate pages for reclaim from */
147 s8 reclaim_idx;
148
149 /* This context's GFP mask */
150 gfp_t gfp_mask;
151
Johannes Weineree814fe2014-08-06 16:06:19 -0700152 /* Incremented by the number of inactive pages that were scanned */
153 unsigned long nr_scanned;
154
155 /* Number of pages freed so far during a call to shrink_zones() */
156 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700157
158 struct {
159 unsigned int dirty;
160 unsigned int unqueued_dirty;
161 unsigned int congested;
162 unsigned int writeback;
163 unsigned int immediate;
164 unsigned int file_taken;
165 unsigned int taken;
166 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700167
168 /* for recording the reclaimed slab by now */
169 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700170};
171
Linus Torvalds1da177e2005-04-16 15:20:36 -0700172#ifdef ARCH_HAS_PREFETCHW
173#define prefetchw_prev_lru_page(_page, _base, _field) \
174 do { \
175 if ((_page)->lru.prev != _base) { \
176 struct page *prev; \
177 \
178 prev = lru_to_page(&(_page->lru)); \
179 prefetchw(&prev->_field); \
180 } \
181 } while (0)
182#else
183#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
184#endif
185
186/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700187 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700188 */
189int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700190
Yang Shi0a432dc2019-09-23 15:38:12 -0700191static void set_task_reclaim_state(struct task_struct *task,
192 struct reclaim_state *rs)
193{
194 /* Check for an overwrite */
195 WARN_ON_ONCE(rs && task->reclaim_state);
196
197 /* Check for the nulling of an already-nulled member */
198 WARN_ON_ONCE(!rs && !task->reclaim_state);
199
200 task->reclaim_state = rs;
201}
202
Linus Torvalds1da177e2005-04-16 15:20:36 -0700203static LIST_HEAD(shrinker_list);
204static DECLARE_RWSEM(shrinker_rwsem);
205
Yang Shi0a432dc2019-09-23 15:38:12 -0700206#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700207static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700208
Yang Shi3c6f17e2021-05-04 18:36:33 -0700209/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700210static inline int shrinker_map_size(int nr_items)
211{
212 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
213}
Yang Shi2bfd3632021-05-04 18:36:11 -0700214
Yang Shi3c6f17e2021-05-04 18:36:33 -0700215static inline int shrinker_defer_size(int nr_items)
216{
217 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
218}
219
Yang Shi468ab842021-05-04 18:36:26 -0700220static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
221 int nid)
222{
223 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
224 lockdep_is_held(&shrinker_rwsem));
225}
226
Yang Shie4262c42021-05-04 18:36:23 -0700227static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700228 int map_size, int defer_size,
229 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700230{
Yang Shie4262c42021-05-04 18:36:23 -0700231 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700232 struct mem_cgroup_per_node *pn;
233 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700234 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700235
Yang Shi2bfd3632021-05-04 18:36:11 -0700236 for_each_node(nid) {
237 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700238 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700239 /* Not yet online memcg */
240 if (!old)
241 return 0;
242
243 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
244 if (!new)
245 return -ENOMEM;
246
Yang Shi3c6f17e2021-05-04 18:36:33 -0700247 new->nr_deferred = (atomic_long_t *)(new + 1);
248 new->map = (void *)new->nr_deferred + defer_size;
249
250 /* map: set all old bits, clear all new bits */
251 memset(new->map, (int)0xff, old_map_size);
252 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
253 /* nr_deferred: copy old values, clear all new values */
254 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
255 memset((void *)new->nr_deferred + old_defer_size, 0,
256 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700257
Yang Shie4262c42021-05-04 18:36:23 -0700258 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700259 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700260 }
261
262 return 0;
263}
264
Yang Shie4262c42021-05-04 18:36:23 -0700265void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700266{
267 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700268 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700269 int nid;
270
Yang Shi2bfd3632021-05-04 18:36:11 -0700271 for_each_node(nid) {
272 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700273 info = rcu_dereference_protected(pn->shrinker_info, true);
274 kvfree(info);
275 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700276 }
277}
278
Yang Shie4262c42021-05-04 18:36:23 -0700279int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700280{
Yang Shie4262c42021-05-04 18:36:23 -0700281 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700282 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700283 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700284
Yang Shid27cf2a2021-05-04 18:36:14 -0700285 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700286 map_size = shrinker_map_size(shrinker_nr_max);
287 defer_size = shrinker_defer_size(shrinker_nr_max);
288 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700289 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700290 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
291 if (!info) {
292 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700293 ret = -ENOMEM;
294 break;
295 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700296 info->nr_deferred = (atomic_long_t *)(info + 1);
297 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700298 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700299 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700300 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700301
302 return ret;
303}
304
Yang Shi3c6f17e2021-05-04 18:36:33 -0700305static inline bool need_expand(int nr_max)
306{
307 return round_up(nr_max, BITS_PER_LONG) >
308 round_up(shrinker_nr_max, BITS_PER_LONG);
309}
310
Yang Shie4262c42021-05-04 18:36:23 -0700311static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700312{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700313 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700314 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700315 int map_size, defer_size = 0;
316 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700317 struct mem_cgroup *memcg;
318
Yang Shi3c6f17e2021-05-04 18:36:33 -0700319 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700320 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700321
Yang Shi2bfd3632021-05-04 18:36:11 -0700322 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700323 goto out;
324
325 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700326
Yang Shi3c6f17e2021-05-04 18:36:33 -0700327 map_size = shrinker_map_size(new_nr_max);
328 defer_size = shrinker_defer_size(new_nr_max);
329 old_map_size = shrinker_map_size(shrinker_nr_max);
330 old_defer_size = shrinker_defer_size(shrinker_nr_max);
331
Yang Shi2bfd3632021-05-04 18:36:11 -0700332 memcg = mem_cgroup_iter(NULL, NULL, NULL);
333 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700334 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
335 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700336 if (ret) {
337 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700338 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700339 }
340 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700341out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700342 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700343 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700344
Yang Shi2bfd3632021-05-04 18:36:11 -0700345 return ret;
346}
347
348void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
349{
350 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700351 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700352
353 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700354 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700355 /* Pairs with smp mb in shrink_slab() */
356 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700357 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700358 rcu_read_unlock();
359 }
360}
361
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700362static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700363
364static int prealloc_memcg_shrinker(struct shrinker *shrinker)
365{
366 int id, ret = -ENOMEM;
367
Yang Shi476b30a2021-05-04 18:36:39 -0700368 if (mem_cgroup_disabled())
369 return -ENOSYS;
370
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700371 down_write(&shrinker_rwsem);
372 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700373 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700374 if (id < 0)
375 goto unlock;
376
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700377 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700378 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700379 idr_remove(&shrinker_idr, id);
380 goto unlock;
381 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700382 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700383 shrinker->id = id;
384 ret = 0;
385unlock:
386 up_write(&shrinker_rwsem);
387 return ret;
388}
389
390static void unregister_memcg_shrinker(struct shrinker *shrinker)
391{
392 int id = shrinker->id;
393
394 BUG_ON(id < 0);
395
Yang Shi41ca6682021-05-04 18:36:29 -0700396 lockdep_assert_held(&shrinker_rwsem);
397
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700398 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700399}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700400
Yang Shi86750832021-05-04 18:36:36 -0700401static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
402 struct mem_cgroup *memcg)
403{
404 struct shrinker_info *info;
405
406 info = shrinker_info_protected(memcg, nid);
407 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
408}
409
410static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
411 struct mem_cgroup *memcg)
412{
413 struct shrinker_info *info;
414
415 info = shrinker_info_protected(memcg, nid);
416 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
417}
418
Yang Shia1780152021-05-04 18:36:42 -0700419void reparent_shrinker_deferred(struct mem_cgroup *memcg)
420{
421 int i, nid;
422 long nr;
423 struct mem_cgroup *parent;
424 struct shrinker_info *child_info, *parent_info;
425
426 parent = parent_mem_cgroup(memcg);
427 if (!parent)
428 parent = root_mem_cgroup;
429
430 /* Prevent from concurrent shrinker_info expand */
431 down_read(&shrinker_rwsem);
432 for_each_node(nid) {
433 child_info = shrinker_info_protected(memcg, nid);
434 parent_info = shrinker_info_protected(parent, nid);
435 for (i = 0; i < shrinker_nr_max; i++) {
436 nr = atomic_long_read(&child_info->nr_deferred[i]);
437 atomic_long_add(nr, &parent_info->nr_deferred[i]);
438 }
439 }
440 up_read(&shrinker_rwsem);
441}
442
Johannes Weinerb5ead352019-11-30 17:55:40 -0800443static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800444{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800445 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800446}
Tejun Heo97c93412015-05-22 18:23:36 -0400447
448/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800449 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400450 * @sc: scan_control in question
451 *
452 * The normal page dirty throttling mechanism in balance_dirty_pages() is
453 * completely broken with the legacy memcg and direct stalling in
454 * shrink_page_list() is used for throttling instead, which lacks all the
455 * niceties such as fairness, adaptive pausing, bandwidth proportional
456 * allocation and configurability.
457 *
458 * This function tests whether the vmscan currently in progress can assume
459 * that the normal dirty throttling mechanism is operational.
460 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800461static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400462{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800463 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400464 return true;
465#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800466 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400467 return true;
468#endif
469 return false;
470}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800471#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700472static int prealloc_memcg_shrinker(struct shrinker *shrinker)
473{
Yang Shi476b30a2021-05-04 18:36:39 -0700474 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700475}
476
477static void unregister_memcg_shrinker(struct shrinker *shrinker)
478{
479}
480
Yang Shi86750832021-05-04 18:36:36 -0700481static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
482 struct mem_cgroup *memcg)
483{
484 return 0;
485}
486
487static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
488 struct mem_cgroup *memcg)
489{
490 return 0;
491}
492
Johannes Weinerb5ead352019-11-30 17:55:40 -0800493static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800494{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800495 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800496}
Tejun Heo97c93412015-05-22 18:23:36 -0400497
Johannes Weinerb5ead352019-11-30 17:55:40 -0800498static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400499{
500 return true;
501}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800502#endif
503
Yang Shi86750832021-05-04 18:36:36 -0700504static long xchg_nr_deferred(struct shrinker *shrinker,
505 struct shrink_control *sc)
506{
507 int nid = sc->nid;
508
509 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
510 nid = 0;
511
512 if (sc->memcg &&
513 (shrinker->flags & SHRINKER_MEMCG_AWARE))
514 return xchg_nr_deferred_memcg(nid, shrinker,
515 sc->memcg);
516
517 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
518}
519
520
521static long add_nr_deferred(long nr, struct shrinker *shrinker,
522 struct shrink_control *sc)
523{
524 int nid = sc->nid;
525
526 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
527 nid = 0;
528
529 if (sc->memcg &&
530 (shrinker->flags & SHRINKER_MEMCG_AWARE))
531 return add_nr_deferred_memcg(nr, nid, shrinker,
532 sc->memcg);
533
534 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
535}
536
Dave Hansen26aa2d12021-09-02 14:59:16 -0700537static bool can_demote(int nid, struct scan_control *sc)
538{
Huang Ying20b51af12021-09-02 14:59:33 -0700539 if (!numa_demotion_enabled)
540 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700541 if (sc) {
542 if (sc->no_demotion)
543 return false;
544 /* It is pointless to do demotion in memcg reclaim */
545 if (cgroup_reclaim(sc))
546 return false;
547 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700548 if (next_demotion_node(nid) == NUMA_NO_NODE)
549 return false;
550
Huang Ying20b51af12021-09-02 14:59:33 -0700551 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700552}
553
Keith Buscha2a36482021-09-02 14:59:26 -0700554static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
555 int nid,
556 struct scan_control *sc)
557{
558 if (memcg == NULL) {
559 /*
560 * For non-memcg reclaim, is there
561 * space in any swap device?
562 */
563 if (get_nr_swap_pages() > 0)
564 return true;
565 } else {
566 /* Is the memcg below its swap limit? */
567 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
568 return true;
569 }
570
571 /*
572 * The page can not be swapped.
573 *
574 * Can it be reclaimed from this node via demotion?
575 */
576 return can_demote(nid, sc);
577}
578
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700579/*
580 * This misses isolated pages which are not accounted for to save counters.
581 * As the data only determines if reclaim or compaction continues, it is
582 * not expected that isolated pages will be a dominating factor.
583 */
584unsigned long zone_reclaimable_pages(struct zone *zone)
585{
586 unsigned long nr;
587
588 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
589 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700590 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700591 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
592 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
593
594 return nr;
595}
596
Michal Hockofd538802017-02-22 15:45:58 -0800597/**
598 * lruvec_lru_size - Returns the number of pages on the given LRU list.
599 * @lruvec: lru vector
600 * @lru: lru to use
601 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
602 */
Yu Zhao20913392021-02-24 12:08:44 -0800603static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
604 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800605{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800606 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800607 int zid;
608
Johannes Weinerde3b0152019-11-30 17:55:31 -0800609 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800610 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800611
Michal Hockofd538802017-02-22 15:45:58 -0800612 if (!managed_zone(zone))
613 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800614
Michal Hockofd538802017-02-22 15:45:58 -0800615 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800616 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800617 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800618 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800619 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800620 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800621}
622
Linus Torvalds1da177e2005-04-16 15:20:36 -0700623/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000624 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700625 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900626int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700627{
Yang Shi476b30a2021-05-04 18:36:39 -0700628 unsigned int size;
629 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000630
Yang Shi476b30a2021-05-04 18:36:39 -0700631 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
632 err = prealloc_memcg_shrinker(shrinker);
633 if (err != -ENOSYS)
634 return err;
635
636 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
637 }
638
639 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000640 if (shrinker->flags & SHRINKER_NUMA_AWARE)
641 size *= nr_node_ids;
642
643 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
644 if (!shrinker->nr_deferred)
645 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700646
Tetsuo Handa8e049442018-04-04 19:53:07 +0900647 return 0;
648}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000649
Tetsuo Handa8e049442018-04-04 19:53:07 +0900650void free_prealloced_shrinker(struct shrinker *shrinker)
651{
Yang Shi41ca6682021-05-04 18:36:29 -0700652 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
653 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700654 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700655 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700656 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700657 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700658
Tetsuo Handa8e049442018-04-04 19:53:07 +0900659 kfree(shrinker->nr_deferred);
660 shrinker->nr_deferred = NULL;
661}
662
663void register_shrinker_prepared(struct shrinker *shrinker)
664{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700665 down_write(&shrinker_rwsem);
666 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700667 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700668 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900669}
670
671int register_shrinker(struct shrinker *shrinker)
672{
673 int err = prealloc_shrinker(shrinker);
674
675 if (err)
676 return err;
677 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000678 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700679}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700680EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700681
682/*
683 * Remove one
684 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700685void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700686{
Yang Shi41ca6682021-05-04 18:36:29 -0700687 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900688 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700689
Linus Torvalds1da177e2005-04-16 15:20:36 -0700690 down_write(&shrinker_rwsem);
691 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700692 shrinker->flags &= ~SHRINKER_REGISTERED;
693 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
694 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700695 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700696
Andrew Vaginae393322013-10-16 13:46:46 -0700697 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900698 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700699}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700700EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700701
702#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000703
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800704static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800705 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700706{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000707 unsigned long freed = 0;
708 unsigned long long delta;
709 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700710 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000711 long nr;
712 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000713 long batch_size = shrinker->batch ? shrinker->batch
714 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800715 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000716
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700717 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700718 if (freeable == 0 || freeable == SHRINK_EMPTY)
719 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000720
721 /*
722 * copy the current shrinker scan count into a local variable
723 * and zero it so that other concurrent shrinker invocations
724 * don't also do this scanning work.
725 */
Yang Shi86750832021-05-04 18:36:36 -0700726 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000727
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700728 if (shrinker->seeks) {
729 delta = freeable >> priority;
730 delta *= 4;
731 do_div(delta, shrinker->seeks);
732 } else {
733 /*
734 * These objects don't require any IO to create. Trim
735 * them aggressively under memory pressure to keep
736 * them from causing refetches in the IO caches.
737 */
738 delta = freeable / 2;
739 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700740
Yang Shi18bb4732021-05-04 18:36:45 -0700741 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000742 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700743 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000744
745 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800746 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000747
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800748 /*
749 * Normally, we should not scan less than batch_size objects in one
750 * pass to avoid too frequent shrinker calls, but if the slab has less
751 * than batch_size objects in total and we are really tight on memory,
752 * we will try to reclaim all available objects, otherwise we can end
753 * up failing allocations although there are plenty of reclaimable
754 * objects spread over several slabs with usage less than the
755 * batch_size.
756 *
757 * We detect the "tight on memory" situations by looking at the total
758 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700759 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800760 * scanning at high prio and therefore should try to reclaim as much as
761 * possible.
762 */
763 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700764 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000765 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800766 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000767
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800768 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700769 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000770 ret = shrinker->scan_objects(shrinker, shrinkctl);
771 if (ret == SHRINK_STOP)
772 break;
773 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000774
Chris Wilsond460acb2017-09-06 16:19:26 -0700775 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
776 total_scan -= shrinkctl->nr_scanned;
777 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000778
779 cond_resched();
780 }
781
Yang Shi18bb4732021-05-04 18:36:45 -0700782 /*
783 * The deferred work is increased by any new work (delta) that wasn't
784 * done, decreased by old deferred work that was done now.
785 *
786 * And it is capped to two times of the freeable items.
787 */
788 next_deferred = max_t(long, (nr + delta - scanned), 0);
789 next_deferred = min(next_deferred, (2 * freeable));
790
Glauber Costa1d3d4432013-08-28 10:18:04 +1000791 /*
792 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700793 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000794 */
Yang Shi86750832021-05-04 18:36:36 -0700795 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000796
Yang Shi8efb4b52021-05-04 18:36:08 -0700797 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000798 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700799}
800
Yang Shi0a432dc2019-09-23 15:38:12 -0700801#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700802static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
803 struct mem_cgroup *memcg, int priority)
804{
Yang Shie4262c42021-05-04 18:36:23 -0700805 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700806 unsigned long ret, freed = 0;
807 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700808
Yang Shi0a432dc2019-09-23 15:38:12 -0700809 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700810 return 0;
811
812 if (!down_read_trylock(&shrinker_rwsem))
813 return 0;
814
Yang Shi468ab842021-05-04 18:36:26 -0700815 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700816 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700817 goto unlock;
818
Yang Shie4262c42021-05-04 18:36:23 -0700819 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700820 struct shrink_control sc = {
821 .gfp_mask = gfp_mask,
822 .nid = nid,
823 .memcg = memcg,
824 };
825 struct shrinker *shrinker;
826
827 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700828 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700829 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700830 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700831 continue;
832 }
833
Yang Shi0a432dc2019-09-23 15:38:12 -0700834 /* Call non-slab shrinkers even though kmem is disabled */
835 if (!memcg_kmem_enabled() &&
836 !(shrinker->flags & SHRINKER_NONSLAB))
837 continue;
838
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700839 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700840 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700841 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700842 /*
843 * After the shrinker reported that it had no objects to
844 * free, but before we cleared the corresponding bit in
845 * the memcg shrinker map, a new object might have been
846 * added. To make sure, we have the bit set in this
847 * case, we invoke the shrinker one more time and reset
848 * the bit if it reports that it is not empty anymore.
849 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700850 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700851 *
852 * list_lru_add() shrink_slab_memcg()
853 * list_add_tail() clear_bit()
854 * <MB> <MB>
855 * set_bit() do_shrink_slab()
856 */
857 smp_mb__after_atomic();
858 ret = do_shrink_slab(&sc, shrinker, priority);
859 if (ret == SHRINK_EMPTY)
860 ret = 0;
861 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700862 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700863 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700864 freed += ret;
865
866 if (rwsem_is_contended(&shrinker_rwsem)) {
867 freed = freed ? : 1;
868 break;
869 }
870 }
871unlock:
872 up_read(&shrinker_rwsem);
873 return freed;
874}
Yang Shi0a432dc2019-09-23 15:38:12 -0700875#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700876static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
877 struct mem_cgroup *memcg, int priority)
878{
879 return 0;
880}
Yang Shi0a432dc2019-09-23 15:38:12 -0700881#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700882
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800883/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800884 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800885 * @gfp_mask: allocation context
886 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800887 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800888 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700889 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800890 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700891 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800892 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
893 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700894 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700895 * @memcg specifies the memory cgroup to target. Unaware shrinkers
896 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800897 *
Josef Bacik9092c712018-01-31 16:16:26 -0800898 * @priority is sc->priority, we take the number of objects and >> by priority
899 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700900 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800901 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700902 */
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800903static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
904 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800905 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700906{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700907 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700908 struct shrinker *shrinker;
909
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}
950
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800951void drop_slab_node(int nid)
952{
953 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700954 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800955
956 do {
957 struct mem_cgroup *memcg = NULL;
958
Chunxin Zang069c4112020-10-13 16:56:46 -0700959 if (fatal_signal_pending(current))
960 return;
961
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800962 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700963 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800964 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800965 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800966 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700967 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800968}
969
970void drop_slab(void)
971{
972 int nid;
973
974 for_each_online_node(nid)
975 drop_slab_node(nid);
976}
977
Linus Torvalds1da177e2005-04-16 15:20:36 -0700978static inline int is_page_cache_freeable(struct page *page)
979{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700980 /*
981 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400982 * that isolated the page, the page cache and optional buffer
983 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700984 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -0700985 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400986 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700987}
988
Yang Shicb165562019-11-30 17:55:28 -0800989static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700990{
Christoph Lameter930d9152006-01-08 01:00:47 -0800991 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700992 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400993 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700994 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400995 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700996 return 1;
997 return 0;
998}
999
1000/*
1001 * We detected a synchronous write error writing a page out. Probably
1002 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1003 * fsync(), msync() or close().
1004 *
1005 * The tricky part is that after writepage we cannot touch the mapping: nothing
1006 * prevents it from being freed up. But we have a ref on the page and once
1007 * that page is locked, the mapping is pinned.
1008 *
1009 * We're allowed to run sleeping lock_page() here because we know the caller has
1010 * __GFP_FS.
1011 */
1012static void handle_write_error(struct address_space *mapping,
1013 struct page *page, int error)
1014{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001015 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001016 if (page_mapping(page) == mapping)
1017 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001018 unlock_page(page);
1019}
1020
Christoph Lameter04e62a22006-06-23 02:03:38 -07001021/* possible outcome of pageout() */
1022typedef enum {
1023 /* failed to write page out, page is locked */
1024 PAGE_KEEP,
1025 /* move page to the active list, page is locked */
1026 PAGE_ACTIVATE,
1027 /* page has been sent to the disk successfully, page is unlocked */
1028 PAGE_SUCCESS,
1029 /* page is clean and locked */
1030 PAGE_CLEAN,
1031} pageout_t;
1032
Linus Torvalds1da177e2005-04-16 15:20:36 -07001033/*
Andrew Morton1742f192006-03-22 00:08:21 -08001034 * pageout is called by shrink_page_list() for each dirty page.
1035 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001036 */
Yang Shicb165562019-11-30 17:55:28 -08001037static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001038{
1039 /*
1040 * If the page is dirty, only perform writeback if that write
1041 * will be non-blocking. To prevent this allocation from being
1042 * stalled by pagecache activity. But note that there may be
1043 * stalls if we need to run get_block(). We could test
1044 * PagePrivate for that.
1045 *
Al Viro81742022014-04-03 03:17:43 -04001046 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001047 * this page's queue, we can perform writeback even if that
1048 * will block.
1049 *
1050 * If the page is swapcache, write it back even if that would
1051 * block, for some throttling. This happens by accident, because
1052 * swap_backing_dev_info is bust: it doesn't reflect the
1053 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001054 */
1055 if (!is_page_cache_freeable(page))
1056 return PAGE_KEEP;
1057 if (!mapping) {
1058 /*
1059 * Some data journaling orphaned pages can have
1060 * page->mapping == NULL while being dirty with clean buffers.
1061 */
David Howells266cf652009-04-03 16:42:36 +01001062 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001063 if (try_to_free_buffers(page)) {
1064 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001065 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001066 return PAGE_CLEAN;
1067 }
1068 }
1069 return PAGE_KEEP;
1070 }
1071 if (mapping->a_ops->writepage == NULL)
1072 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001073 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001074 return PAGE_KEEP;
1075
1076 if (clear_page_dirty_for_io(page)) {
1077 int res;
1078 struct writeback_control wbc = {
1079 .sync_mode = WB_SYNC_NONE,
1080 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001081 .range_start = 0,
1082 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001083 .for_reclaim = 1,
1084 };
1085
1086 SetPageReclaim(page);
1087 res = mapping->a_ops->writepage(page, &wbc);
1088 if (res < 0)
1089 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001090 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001091 ClearPageReclaim(page);
1092 return PAGE_ACTIVATE;
1093 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001094
Linus Torvalds1da177e2005-04-16 15:20:36 -07001095 if (!PageWriteback(page)) {
1096 /* synchronous write or broken a_ops? */
1097 ClearPageReclaim(page);
1098 }
yalin wang3aa23852016-01-14 15:18:30 -08001099 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001100 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001101 return PAGE_SUCCESS;
1102 }
1103
1104 return PAGE_CLEAN;
1105}
1106
Andrew Mortona649fd92006-10-17 00:09:36 -07001107/*
Nick Piggine2867812008-07-25 19:45:30 -07001108 * Same as remove_mapping, but if the page is removed from the mapping, it
1109 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001110 */
Johannes Weinera5289102014-04-03 14:47:51 -07001111static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001112 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001113{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001114 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001115 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001116
Nick Piggin28e4d962006-09-25 23:31:23 -07001117 BUG_ON(!PageLocked(page));
1118 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001119
Johannes Weiner30472502021-09-02 14:53:18 -07001120 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001121 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001122 * The non racy check for a busy page.
1123 *
1124 * Must be careful with the order of the tests. When someone has
1125 * a ref to the page, it may be possible that they dirty it then
1126 * drop the reference. So if PageDirty is tested before page_count
1127 * here, then the following race may occur:
1128 *
1129 * get_user_pages(&page);
1130 * [user mapping goes away]
1131 * write_to(page);
1132 * !PageDirty(page) [good]
1133 * SetPageDirty(page);
1134 * put_page(page);
1135 * !page_count(page) [good, discard it]
1136 *
1137 * [oops, our write_to data is lost]
1138 *
1139 * Reversing the order of the tests ensures such a situation cannot
1140 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001141 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001142 *
1143 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001144 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001145 */
William Kucharski906d2782019-10-18 20:20:33 -07001146 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001147 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001148 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001149 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001150 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001151 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001152 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001153 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001154
1155 if (PageSwapCache(page)) {
1156 swp_entry_t swap = { .val = page_private(page) };
Yu Zhaoa1537a62022-01-27 20:32:37 -07001157
1158 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001159 if (reclaimed && !mapping_exiting(mapping))
1160 shadow = workingset_eviction(page, target_memcg);
Yu Zhaoa1537a62022-01-27 20:32:37 -07001161 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001162 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001163 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001164 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001165 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001166 void (*freepage)(struct page *);
1167
1168 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001169 /*
1170 * Remember a shadow entry for reclaimed file cache in
1171 * order to detect refaults, thus thrashing, later on.
1172 *
1173 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001174 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001175 * inode reclaim needs to empty out the radix tree or
1176 * the nodes are lost. Don't plant shadows behind its
1177 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001178 *
1179 * We also don't store shadows for DAX mappings because the
1180 * only page cache pages found in these are zero pages
1181 * covering holes, and because we don't want to mix DAX
1182 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001183 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001184 */
Huang Ying9de4f222020-04-06 20:04:41 -07001185 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001186 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001187 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001188 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001189 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001190
1191 if (freepage != NULL)
1192 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001193 }
1194
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001195 return 1;
1196
1197cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001198 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001199 return 0;
1200}
1201
Linus Torvalds1da177e2005-04-16 15:20:36 -07001202/*
Nick Piggine2867812008-07-25 19:45:30 -07001203 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1204 * someone else has a ref on the page, abort and return 0. If it was
1205 * successfully detached, return 1. Assumes the caller has a single ref on
1206 * this page.
1207 */
1208int remove_mapping(struct address_space *mapping, struct page *page)
1209{
Johannes Weinerb9107182019-11-30 17:55:59 -08001210 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001211 /*
1212 * Unfreezing the refcount with 1 rather than 2 effectively
1213 * drops the pagecache ref for us without requiring another
1214 * atomic operation.
1215 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001216 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001217 return 1;
1218 }
1219 return 0;
1220}
1221
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001222/**
1223 * putback_lru_page - put previously isolated page onto appropriate LRU list
1224 * @page: page to be put back to appropriate lru list
1225 *
1226 * Add previously isolated @page to appropriate LRU list.
1227 * Page may still be unevictable for other reasons.
1228 *
1229 * lru_lock must not be held, interrupts must be enabled.
1230 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001231void putback_lru_page(struct page *page)
1232{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001233 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001234 put_page(page); /* drop ref from isolate */
1235}
1236
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001237enum page_references {
1238 PAGEREF_RECLAIM,
1239 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001240 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001241 PAGEREF_ACTIVATE,
1242};
1243
1244static enum page_references page_check_references(struct page *page,
1245 struct scan_control *sc)
1246{
Johannes Weiner645747462010-03-05 13:42:22 -08001247 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001248 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001249
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001250 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1251 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001252 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001253
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001254 /*
1255 * Mlock lost the isolation race with us. Let try_to_unmap()
1256 * move the page to the unevictable list.
1257 */
1258 if (vm_flags & VM_LOCKED)
1259 return PAGEREF_RECLAIM;
1260
Johannes Weiner645747462010-03-05 13:42:22 -08001261 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001262 /*
1263 * All mapped pages start out with page table
1264 * references from the instantiating fault, so we need
1265 * to look twice if a mapped file page is used more
1266 * than once.
1267 *
1268 * Mark it and spare it for another trip around the
1269 * inactive list. Another page table reference will
1270 * lead to its activation.
1271 *
1272 * Note: the mark is set for activated pages as well
1273 * so that recently deactivated but used pages are
1274 * quickly recovered.
1275 */
1276 SetPageReferenced(page);
1277
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001278 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001279 return PAGEREF_ACTIVATE;
1280
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001281 /*
1282 * Activate file-backed executable pages after first usage.
1283 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001284 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001285 return PAGEREF_ACTIVATE;
1286
Johannes Weiner645747462010-03-05 13:42:22 -08001287 return PAGEREF_KEEP;
1288 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001289
1290 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001291 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001292 return PAGEREF_RECLAIM_CLEAN;
1293
1294 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001295}
1296
Mel Gormane2be15f2013-07-03 15:01:57 -07001297/* Check if a page is dirty or under writeback */
1298static void page_check_dirty_writeback(struct page *page,
1299 bool *dirty, bool *writeback)
1300{
Mel Gormanb4597222013-07-03 15:02:05 -07001301 struct address_space *mapping;
1302
Mel Gormane2be15f2013-07-03 15:01:57 -07001303 /*
1304 * Anonymous pages are not handled by flushers and must be written
1305 * from reclaim context. Do not stall reclaim based on them
1306 */
Huang Ying9de4f222020-04-06 20:04:41 -07001307 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001308 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001309 *dirty = false;
1310 *writeback = false;
1311 return;
1312 }
1313
1314 /* By default assume that the page flags are accurate */
1315 *dirty = PageDirty(page);
1316 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001317
1318 /* Verify dirty/writeback state if the filesystem supports it */
1319 if (!page_has_private(page))
1320 return;
1321
1322 mapping = page_mapping(page);
1323 if (mapping && mapping->a_ops->is_dirty_writeback)
1324 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001325}
1326
Dave Hansen26aa2d12021-09-02 14:59:16 -07001327static struct page *alloc_demote_page(struct page *page, unsigned long node)
1328{
1329 struct migration_target_control mtc = {
1330 /*
1331 * Allocate from 'node', or fail quickly and quietly.
1332 * When this happens, 'page' will likely just be discarded
1333 * instead of migrated.
1334 */
1335 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1336 __GFP_THISNODE | __GFP_NOWARN |
1337 __GFP_NOMEMALLOC | GFP_NOWAIT,
1338 .nid = node
1339 };
1340
1341 return alloc_migration_target(page, (unsigned long)&mtc);
1342}
1343
1344/*
1345 * Take pages on @demote_list and attempt to demote them to
1346 * another node. Pages which are not demoted are left on
1347 * @demote_pages.
1348 */
1349static unsigned int demote_page_list(struct list_head *demote_pages,
1350 struct pglist_data *pgdat)
1351{
1352 int target_nid = next_demotion_node(pgdat->node_id);
1353 unsigned int nr_succeeded;
1354 int err;
1355
1356 if (list_empty(demote_pages))
1357 return 0;
1358
1359 if (target_nid == NUMA_NO_NODE)
1360 return 0;
1361
1362 /* Demotion ignores all cpuset and mempolicy settings */
1363 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1364 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1365 &nr_succeeded);
1366
Yang Shi668e4142021-09-02 14:59:19 -07001367 if (current_is_kswapd())
1368 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1369 else
1370 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1371
Dave Hansen26aa2d12021-09-02 14:59:16 -07001372 return nr_succeeded;
1373}
1374
Nick Piggine2867812008-07-25 19:45:30 -07001375/*
Andrew Morton1742f192006-03-22 00:08:21 -08001376 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001377 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001378static unsigned int shrink_page_list(struct list_head *page_list,
1379 struct pglist_data *pgdat,
1380 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001381 struct reclaim_stat *stat,
1382 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001383{
1384 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001385 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001386 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001387 unsigned int nr_reclaimed = 0;
1388 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001389 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001390
Kirill Tkhai060f0052019-03-05 15:48:15 -08001391 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001392 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001393 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001394
Dave Hansen26aa2d12021-09-02 14:59:16 -07001395retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001396 while (!list_empty(page_list)) {
1397 struct address_space *mapping;
1398 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001399 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001400 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001401 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001402
1403 cond_resched();
1404
1405 page = lru_to_page(page_list);
1406 list_del(&page->lru);
1407
Nick Piggin529ae9a2008-08-02 12:01:03 +02001408 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001409 goto keep;
1410
Sasha Levin309381fea2014-01-23 15:52:54 -08001411 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001412
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001413 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001414
1415 /* Account the number of base pages even though THP */
1416 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001417
Hugh Dickins39b5f292012-10-08 16:33:18 -07001418 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001419 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001420
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001421 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001422 goto keep_locked;
1423
Yu Zhaoafd94c92022-01-27 20:43:22 -07001424 /* page_update_gen() tried to promote this page? */
1425 if (lru_gen_enabled() && !ignore_references &&
1426 page_mapped(page) && PageReferenced(page))
1427 goto keep_locked;
1428
Andy Whitcroftc661b072007-08-22 14:01:26 -07001429 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1430 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1431
Mel Gorman283aba92013-07-03 15:01:51 -07001432 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001433 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001434 * reclaim_congested which affects wait_iff_congested. kswapd
1435 * will stall and start writing pages if the tail of the LRU
1436 * is all dirty unqueued pages.
1437 */
1438 page_check_dirty_writeback(page, &dirty, &writeback);
1439 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001440 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001441
1442 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001443 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001444
Mel Gormand04e8ac2013-07-03 15:02:03 -07001445 /*
1446 * Treat this page as congested if the underlying BDI is or if
1447 * pages are cycling through the LRU so quickly that the
1448 * pages marked for immediate reclaim are making it to the
1449 * end of the LRU a second time.
1450 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001451 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001452 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001453 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001454 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001455 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001456
1457 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001458 * If a page at the tail of the LRU is under writeback, there
1459 * are three cases to consider.
1460 *
1461 * 1) If reclaim is encountering an excessive number of pages
1462 * under writeback and this page is both under writeback and
1463 * PageReclaim then it indicates that pages are being queued
1464 * for IO but are being recycled through the LRU before the
1465 * IO can complete. Waiting on the page itself risks an
1466 * indefinite stall if it is impossible to writeback the
1467 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001468 * note that the LRU is being scanned too quickly and the
1469 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001470 *
Tejun Heo97c93412015-05-22 18:23:36 -04001471 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001472 * not marked for immediate reclaim, or the caller does not
1473 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1474 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001475 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001476 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001477 * Require may_enter_fs because we would wait on fs, which
1478 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001479 * enter reclaim, and deadlock if it waits on a page for
1480 * which it is needed to do the write (loop masks off
1481 * __GFP_IO|__GFP_FS for this reason); but more thought
1482 * would probably show more reasons.
1483 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001484 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001485 * PageReclaim. memcg does not have any dirty pages
1486 * throttling so we could easily OOM just because too many
1487 * pages are in writeback and there is nothing else to
1488 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001489 *
1490 * In cases 1) and 2) we activate the pages to get them out of
1491 * the way while we continue scanning for clean pages on the
1492 * inactive list and refilling from the active list. The
1493 * observation here is that waiting for disk writes is more
1494 * expensive than potentially causing reloads down the line.
1495 * Since they're marked for immediate reclaim, they won't put
1496 * memory pressure on the cache working set any longer than it
1497 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001498 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001499 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001500 /* Case 1 above */
1501 if (current_is_kswapd() &&
1502 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001503 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001504 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001505 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001506
1507 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001508 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001509 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001510 /*
1511 * This is slightly racy - end_page_writeback()
1512 * might have just cleared PageReclaim, then
1513 * setting PageReclaim here end up interpreted
1514 * as PageReadahead - but that does not matter
1515 * enough to care. What we do want is for this
1516 * page to have PageReclaim set next time memcg
1517 * reclaim reaches the tests above, so it will
1518 * then wait_on_page_writeback() to avoid OOM;
1519 * and it's also appropriate in global reclaim.
1520 */
1521 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001522 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001523 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001524
1525 /* Case 3 above */
1526 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001527 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001528 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001529 /* then go back and try same page again */
1530 list_add_tail(&page->lru, page_list);
1531 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001532 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001533 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001534
Minchan Kim8940b342019-09-25 16:49:11 -07001535 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001536 references = page_check_references(page, sc);
1537
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001538 switch (references) {
1539 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001540 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001541 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001542 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001543 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001544 case PAGEREF_RECLAIM:
1545 case PAGEREF_RECLAIM_CLEAN:
1546 ; /* try to reclaim the page below */
1547 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001548
Linus Torvalds1da177e2005-04-16 15:20:36 -07001549 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001550 * Before reclaiming the page, try to relocate
1551 * its contents to another node.
1552 */
1553 if (do_demote_pass &&
1554 (thp_migration_supported() || !PageTransHuge(page))) {
1555 list_add(&page->lru, &demote_pages);
1556 unlock_page(page);
1557 continue;
1558 }
1559
1560 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001561 * Anonymous process memory has backing store?
1562 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001563 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001564 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001565 if (PageAnon(page) && PageSwapBacked(page)) {
1566 if (!PageSwapCache(page)) {
1567 if (!(sc->gfp_mask & __GFP_IO))
1568 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001569 if (page_maybe_dma_pinned(page))
1570 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001571 if (PageTransHuge(page)) {
1572 /* cannot split THP, skip it */
1573 if (!can_split_huge_page(page, NULL))
1574 goto activate_locked;
1575 /*
1576 * Split pages without a PMD map right
1577 * away. Chances are some or all of the
1578 * tail pages can be freed without IO.
1579 */
1580 if (!compound_mapcount(page) &&
1581 split_huge_page_to_list(page,
1582 page_list))
1583 goto activate_locked;
1584 }
1585 if (!add_to_swap(page)) {
1586 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001587 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001588 /* Fallback to swap normal pages */
1589 if (split_huge_page_to_list(page,
1590 page_list))
1591 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001592#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1593 count_vm_event(THP_SWPOUT_FALLBACK);
1594#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001595 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001596 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001597 }
Minchan Kim0f074652017-07-06 15:37:24 -07001598
Kirill Tkhai4b793062020-04-01 21:10:18 -07001599 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001600
1601 /* Adding to swap updated mapping */
1602 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001603 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001604 } else if (unlikely(PageTransHuge(page))) {
1605 /* Split file THP */
1606 if (split_huge_page_to_list(page, page_list))
1607 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001608 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001609
1610 /*
Yang Shi98879b32019-07-11 20:59:30 -07001611 * THP may get split above, need minus tail pages and update
1612 * nr_pages to avoid accounting tail pages twice.
1613 *
1614 * The tail pages that are added into swap cache successfully
1615 * reach here.
1616 */
1617 if ((nr_pages > 1) && !PageTransHuge(page)) {
1618 sc->nr_scanned -= (nr_pages - 1);
1619 nr_pages = 1;
1620 }
1621
1622 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001623 * The page is mapped into the page tables of one or more
1624 * processes. Try to unmap it here.
1625 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001626 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001627 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001628 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001629
1630 if (unlikely(PageTransHuge(page)))
1631 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001632
Yang Shi1fb08ac2021-06-30 18:52:01 -07001633 try_to_unmap(page, flags);
1634 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001635 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001636 if (!was_swapbacked && PageSwapBacked(page))
1637 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001638 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001639 }
1640 }
1641
1642 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001643 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001644 * Only kswapd can writeback filesystem pages
1645 * to avoid risk of stack overflow. But avoid
1646 * injecting inefficient single-page IO into
1647 * flusher writeback as much as possible: only
1648 * write pages when we've encountered many
1649 * dirty pages, and when we've already scanned
1650 * the rest of the LRU for clean pages and see
1651 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001652 */
Huang Ying9de4f222020-04-06 20:04:41 -07001653 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001654 (!current_is_kswapd() || !PageReclaim(page) ||
1655 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001656 /*
1657 * Immediately reclaim when written back.
1658 * Similar in principal to deactivate_page()
1659 * except we already have the page isolated
1660 * and know it's dirty
1661 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001662 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001663 SetPageReclaim(page);
1664
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001665 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001666 }
1667
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001668 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001669 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001670 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001671 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001672 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001673 goto keep_locked;
1674
Mel Gormand950c942015-09-04 15:47:35 -07001675 /*
1676 * Page is dirty. Flush the TLB if a writable entry
1677 * potentially exists to avoid CPU writes after IO
1678 * starts and then write it out here.
1679 */
1680 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001681 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001682 case PAGE_KEEP:
1683 goto keep_locked;
1684 case PAGE_ACTIVATE:
1685 goto activate_locked;
1686 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001687 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001688
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001689 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001690 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001691 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001692 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001693
Linus Torvalds1da177e2005-04-16 15:20:36 -07001694 /*
1695 * A synchronous write - probably a ramdisk. Go
1696 * ahead and try to reclaim the page.
1697 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001698 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001699 goto keep;
1700 if (PageDirty(page) || PageWriteback(page))
1701 goto keep_locked;
1702 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001703 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001704 case PAGE_CLEAN:
1705 ; /* try to free the page below */
1706 }
1707 }
1708
1709 /*
1710 * If the page has buffers, try to free the buffer mappings
1711 * associated with this page. If we succeed we try to free
1712 * the page as well.
1713 *
1714 * We do this even if the page is PageDirty().
1715 * try_to_release_page() does not perform I/O, but it is
1716 * possible for a page to have PageDirty set, but it is actually
1717 * clean (all its buffers are clean). This happens if the
1718 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001719 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001720 * try_to_release_page() will discover that cleanness and will
1721 * drop the buffers and mark the page clean - it can be freed.
1722 *
1723 * Rarely, pages can have buffers and no ->mapping. These are
1724 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001725 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001726 * and if that worked, and the page is no longer mapped into
1727 * process address space (page_count == 1) it can be freed.
1728 * Otherwise, leave the page on the LRU so it is swappable.
1729 */
David Howells266cf652009-04-03 16:42:36 +01001730 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001731 if (!try_to_release_page(page, sc->gfp_mask))
1732 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001733 if (!mapping && page_count(page) == 1) {
1734 unlock_page(page);
1735 if (put_page_testzero(page))
1736 goto free_it;
1737 else {
1738 /*
1739 * rare race with speculative reference.
1740 * the speculative reference will free
1741 * this page shortly, so we may
1742 * increment nr_reclaimed here (and
1743 * leave it off the LRU).
1744 */
1745 nr_reclaimed++;
1746 continue;
1747 }
1748 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001749 }
1750
Shaohua Li802a3a92017-05-03 14:52:32 -07001751 if (PageAnon(page) && !PageSwapBacked(page)) {
1752 /* follow __remove_mapping for reference */
1753 if (!page_ref_freeze(page, 1))
1754 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001755 /*
1756 * The page has only one reference left, which is
1757 * from the isolation. After the caller puts the
1758 * page back on lru and drops the reference, the
1759 * page will be freed anyway. It doesn't matter
1760 * which lru it goes. So we don't bother checking
1761 * PageDirty here.
1762 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001763 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001764 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001765 } else if (!mapping || !__remove_mapping(mapping, page, true,
1766 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001767 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001768
1769 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001770free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001771 /*
1772 * THP may get swapped out in a whole, need account
1773 * all base pages.
1774 */
1775 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001776
1777 /*
1778 * Is there need to periodically free_page_list? It would
1779 * appear not as the counts should be low
1780 */
Yang Shi7ae88532019-09-23 15:38:09 -07001781 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001782 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001783 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001784 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001785 continue;
1786
Yang Shi98879b32019-07-11 20:59:30 -07001787activate_locked_split:
1788 /*
1789 * The tail pages that are failed to add into swap cache
1790 * reach here. Fixup nr_scanned and nr_pages.
1791 */
1792 if (nr_pages > 1) {
1793 sc->nr_scanned -= (nr_pages - 1);
1794 nr_pages = 1;
1795 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001796activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001797 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001798 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1799 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001800 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001801 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001802 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001803 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001804 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001805 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001806 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001807 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001808keep_locked:
1809 unlock_page(page);
1810keep:
1811 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001812 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001813 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001814 /* 'page_list' is always empty here */
1815
1816 /* Migrate pages selected for demotion */
1817 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1818 /* Pages that could not be demoted are still in @demote_pages */
1819 if (!list_empty(&demote_pages)) {
1820 /* Pages which failed to demoted go back on @page_list for retry: */
1821 list_splice_init(&demote_pages, page_list);
1822 do_demote_pass = false;
1823 goto retry;
1824 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001825
Yang Shi98879b32019-07-11 20:59:30 -07001826 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1827
Johannes Weiner747db952014-08-08 14:19:24 -07001828 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001829 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001830 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001831
Linus Torvalds1da177e2005-04-16 15:20:36 -07001832 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001833 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001834
Andrew Morton05ff5132006-03-22 00:08:20 -08001835 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001836}
1837
Maninder Singh730ec8c2020-06-03 16:01:18 -07001838unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001839 struct list_head *page_list)
1840{
1841 struct scan_control sc = {
1842 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001843 .may_unmap = 1,
1844 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001845 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001846 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001847 struct page *page, *next;
1848 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001849 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001850
1851 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001852 if (!PageHuge(page) && page_is_file_lru(page) &&
1853 !PageDirty(page) && !__PageMovable(page) &&
1854 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001855 ClearPageActive(page);
1856 list_move(&page->lru, &clean_pages);
1857 }
1858 }
1859
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001860 /*
1861 * We should be safe here since we are only dealing with file pages and
1862 * we are not kswapd and therefore cannot write dirty file pages. But
1863 * call memalloc_noreclaim_save() anyway, just in case these conditions
1864 * change in the future.
1865 */
1866 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001867 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001868 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001869 memalloc_noreclaim_restore(noreclaim_flag);
1870
Minchan Kim02c6de82012-10-08 16:31:55 -07001871 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001872 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1873 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001874 /*
1875 * Since lazyfree pages are isolated from file LRU from the beginning,
1876 * they will rotate back to anonymous LRU in the end if it failed to
1877 * discard so isolated count will be mismatched.
1878 * Compensate the isolated count for both LRU lists.
1879 */
1880 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1881 stat.nr_lazyfree_fail);
1882 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001883 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001884 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001885}
1886
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001887/*
1888 * Attempt to remove the specified page from its LRU. Only take this page
1889 * if it is of the appropriate PageActive status. Pages which are being
1890 * freed elsewhere are also ignored.
1891 *
1892 * page: page to consider
1893 * mode: one of the LRU isolation modes defined above
1894 *
Alex Shic2135f72021-02-24 12:08:01 -08001895 * returns true on success, false on failure.
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001896 */
Alex Shic2135f72021-02-24 12:08:01 -08001897bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001898{
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001899 /* Only take pages on the LRU. */
1900 if (!PageLRU(page))
Alex Shic2135f72021-02-24 12:08:01 -08001901 return false;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001902
Minchan Kime46a2872012-10-08 16:33:48 -07001903 /* Compaction should not handle unevictable pages but CMA can do so */
1904 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
Alex Shic2135f72021-02-24 12:08:01 -08001905 return false;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001906
Mel Gormanc8244932012-01-12 17:19:38 -08001907 /*
1908 * To minimise LRU disruption, the caller can indicate that it only
1909 * wants to isolate pages it will be able to operate on without
1910 * blocking - clean pages for the most part.
1911 *
Mel Gormanc8244932012-01-12 17:19:38 -08001912 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1913 * that it is possible to migrate without blocking
1914 */
Johannes Weiner1276ad62017-02-24 14:56:11 -08001915 if (mode & ISOLATE_ASYNC_MIGRATE) {
Mel Gormanc8244932012-01-12 17:19:38 -08001916 /* All the caller can do on PageWriteback is block */
1917 if (PageWriteback(page))
Alex Shic2135f72021-02-24 12:08:01 -08001918 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001919
1920 if (PageDirty(page)) {
1921 struct address_space *mapping;
Mel Gorman69d763f2018-01-31 16:19:52 -08001922 bool migrate_dirty;
Mel Gormanc8244932012-01-12 17:19:38 -08001923
Mel Gormanc8244932012-01-12 17:19:38 -08001924 /*
1925 * Only pages without mappings or that have a
1926 * ->migratepage callback are possible to migrate
Mel Gorman69d763f2018-01-31 16:19:52 -08001927 * without blocking. However, we can be racing with
1928 * truncation so it's necessary to lock the page
1929 * to stabilise the mapping as truncation holds
1930 * the page lock until after the page is removed
1931 * from the page cache.
Mel Gormanc8244932012-01-12 17:19:38 -08001932 */
Mel Gorman69d763f2018-01-31 16:19:52 -08001933 if (!trylock_page(page))
Alex Shic2135f72021-02-24 12:08:01 -08001934 return false;
Mel Gorman69d763f2018-01-31 16:19:52 -08001935
Mel Gormanc8244932012-01-12 17:19:38 -08001936 mapping = page_mapping(page);
Hugh Dickins145e1a72018-06-01 16:50:50 -07001937 migrate_dirty = !mapping || mapping->a_ops->migratepage;
Mel Gorman69d763f2018-01-31 16:19:52 -08001938 unlock_page(page);
1939 if (!migrate_dirty)
Alex Shic2135f72021-02-24 12:08:01 -08001940 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001941 }
1942 }
Minchan Kim39deaf82011-10-31 17:06:51 -07001943
Minchan Kimf80c0672011-10-31 17:06:55 -07001944 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
Alex Shic2135f72021-02-24 12:08:01 -08001945 return false;
Minchan Kimf80c0672011-10-31 17:06:55 -07001946
Alex Shic2135f72021-02-24 12:08:01 -08001947 return true;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001948}
1949
Mel Gorman7ee36a12016-07-28 15:47:17 -07001950/*
1951 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001952 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001953 */
1954static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001955 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001956{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001957 int zid;
1958
Mel Gorman7ee36a12016-07-28 15:47:17 -07001959 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1960 if (!nr_zone_taken[zid])
1961 continue;
1962
Wei Yanga892cb62020-06-03 16:01:12 -07001963 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001964 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001965
Mel Gorman7ee36a12016-07-28 15:47:17 -07001966}
1967
Mel Gormanf611fab2021-06-30 18:53:19 -07001968/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001969 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1970 *
1971 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001972 * shrink the lists perform better by taking out a batch of pages
1973 * and working on them outside the LRU lock.
1974 *
1975 * For pagecache intensive workloads, this function is the hottest
1976 * spot in the kernel (apart from copy_*_user functions).
1977 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001978 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001979 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001980 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001981 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001982 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001983 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001984 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001985 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001986 *
1987 * returns how many pages were moved onto *@dst.
1988 */
Andrew Morton69e05942006-03-22 00:08:19 -08001989static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001990 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001991 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001992 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001993{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001994 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001995 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001996 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001997 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07001998 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001999 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002000 LIST_HEAD(pages_skipped);
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002001 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002002
Yang Shi98879b32019-07-11 20:59:30 -07002003 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002004 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07002005 while (scan < nr_to_scan && !list_empty(src)) {
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002006 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002007
Linus Torvalds1da177e2005-04-16 15:20:36 -07002008 page = lru_to_page(src);
2009 prefetchw_prev_lru_page(page, src, flags);
2010
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002011 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002012 total_scan += nr_pages;
2013
Mel Gormanb2e18752016-07-28 15:45:37 -07002014 if (page_zonenum(page) > sc->reclaim_idx) {
2015 list_move(&page->lru, &pages_skipped);
Yang Shi98879b32019-07-11 20:59:30 -07002016 nr_skipped[page_zonenum(page)] += nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002017 continue;
2018 }
2019
Minchan Kim791b48b2017-05-12 15:47:06 -07002020 /*
2021 * Do not count skipped pages because that makes the function
2022 * return with no isolated pages if the LRU mostly contains
2023 * ineligible pages. This causes the VM to not reclaim any
2024 * pages, triggering a premature OOM.
Yang Shi98879b32019-07-11 20:59:30 -07002025 *
2026 * Account all tail pages of THP. This would not cause
2027 * premature OOM since __isolate_lru_page() returns -EBUSY
2028 * only when the page is being freed somewhere else.
Minchan Kim791b48b2017-05-12 15:47:06 -07002029 */
Yang Shi98879b32019-07-11 20:59:30 -07002030 scan += nr_pages;
Alex Shic2135f72021-02-24 12:08:01 -08002031 if (!__isolate_lru_page_prepare(page, mode)) {
2032 /* It is being freed elsewhere */
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002033 list_move(&page->lru, src);
Alex Shic2135f72021-02-24 12:08:01 -08002034 continue;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002035 }
Alex Shic2135f72021-02-24 12:08:01 -08002036 /*
2037 * Be careful not to clear PageLRU until after we're
2038 * sure the page is not being freed elsewhere -- the
2039 * page release code relies on it.
2040 */
2041 if (unlikely(!get_page_unless_zero(page))) {
2042 list_move(&page->lru, src);
2043 continue;
2044 }
2045
2046 if (!TestClearPageLRU(page)) {
2047 /* Another thread is already isolating this page */
2048 put_page(page);
2049 list_move(&page->lru, src);
2050 continue;
2051 }
2052
2053 nr_taken += nr_pages;
2054 nr_zone_taken[page_zonenum(page)] += nr_pages;
2055 list_move(&page->lru, dst);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002056 }
2057
Mel Gormanb2e18752016-07-28 15:45:37 -07002058 /*
2059 * Splice any skipped pages to the start of the LRU list. Note that
2060 * this disrupts the LRU order when reclaiming for lower zones but
2061 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2062 * scanning would soon rescan the same pages to skip and put the
2063 * system at risk of premature OOM.
2064 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002065 if (!list_empty(&pages_skipped)) {
2066 int zid;
2067
Johannes Weiner3db65812017-05-03 14:52:13 -07002068 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002069 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2070 if (!nr_skipped[zid])
2071 continue;
2072
2073 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002074 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002075 }
2076 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002077 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002078 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Minchan Kim791b48b2017-05-12 15:47:06 -07002079 total_scan, skipped, nr_taken, mode, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002080 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002081 return nr_taken;
2082}
2083
Nick Piggin62695a82008-10-18 20:26:09 -07002084/**
2085 * isolate_lru_page - tries to isolate a page from its LRU list
2086 * @page: page to isolate from its LRU list
2087 *
2088 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2089 * vmstat statistic corresponding to whatever LRU list the page was on.
2090 *
2091 * Returns 0 if the page was removed from an LRU list.
2092 * Returns -EBUSY if the page was not on an LRU list.
2093 *
2094 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002095 * the active list, it will have PageActive set. If it was found on
2096 * the unevictable list, it will have the PageUnevictable bit set. That flag
2097 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002098 *
2099 * The vmstat statistic corresponding to the list on which the page was
2100 * found will be decremented.
2101 *
2102 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002103 *
Nick Piggin62695a82008-10-18 20:26:09 -07002104 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002105 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002106 * without a stable reference).
2107 * (2) the lru_lock must not be held.
2108 * (3) interrupts must be enabled.
2109 */
2110int isolate_lru_page(struct page *page)
2111{
2112 int ret = -EBUSY;
2113
Sasha Levin309381fea2014-01-23 15:52:54 -08002114 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002115 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002116
Alex Shid25b5bd2020-12-15 12:34:16 -08002117 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002118 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002119
Alex Shid25b5bd2020-12-15 12:34:16 -08002120 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002121 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002122 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002123 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002124 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002125 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002126
Nick Piggin62695a82008-10-18 20:26:09 -07002127 return ret;
2128}
2129
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002130/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002131 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002132 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002133 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2134 * the LRU list will go small and be scanned faster than necessary, leading to
2135 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002136 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002137static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002138 struct scan_control *sc)
2139{
2140 unsigned long inactive, isolated;
2141
2142 if (current_is_kswapd())
2143 return 0;
2144
Johannes Weinerb5ead352019-11-30 17:55:40 -08002145 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002146 return 0;
2147
2148 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002149 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2150 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002151 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002152 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2153 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002154 }
2155
Fengguang Wu3cf23842012-12-18 14:23:31 -08002156 /*
2157 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2158 * won't get blocked by normal direct-reclaimers, forming a circular
2159 * deadlock.
2160 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002161 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002162 inactive >>= 3;
2163
Rik van Riel35cd7812009-09-21 17:01:38 -07002164 return isolated > inactive;
2165}
2166
Kirill Tkhaia222f342019-05-13 17:17:00 -07002167/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002168 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2169 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002170 *
2171 * Returns the number of pages moved to the given lruvec.
2172 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002173static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2174 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002175{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002176 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002177 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002178 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002179
Kirill Tkhaia222f342019-05-13 17:17:00 -07002180 while (!list_empty(list)) {
2181 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002182 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002183 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002184 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002185 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002186 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002187 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002188 continue;
2189 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002190
Alex Shi3d06afa2020-12-15 12:33:37 -08002191 /*
2192 * The SetPageLRU needs to be kept here for list integrity.
2193 * Otherwise:
2194 * #0 move_pages_to_lru #1 release_pages
2195 * if !put_page_testzero
2196 * if (put_page_testzero())
2197 * !PageLRU //skip lru_lock
2198 * SetPageLRU()
2199 * list_add(&page->lru,)
2200 * list_add(&page->lru,)
2201 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002202 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002203
Alex Shi3d06afa2020-12-15 12:33:37 -08002204 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002205 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002206
2207 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002208 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002209 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002210 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002211 } else
2212 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002213
2214 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002215 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002216
Alex Shiafca9152020-12-15 12:34:02 -08002217 /*
2218 * All pages were isolated from the same lruvec (and isolation
2219 * inhibits memcg migration).
2220 */
Muchun Song7467c392021-06-28 19:37:59 -07002221 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002222 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002223 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002224 nr_moved += nr_pages;
2225 if (PageActive(page))
2226 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002227 }
Mel Gorman66635622010-08-09 17:19:30 -07002228
Hugh Dickins3f797682012-01-12 17:20:07 -08002229 /*
2230 * To save our caller's stack, now use input list for pages to free.
2231 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002232 list_splice(&pages_to_free, list);
2233
2234 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002235}
2236
2237/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002238 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002239 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002240 * In that case we should only throttle if the backing device it is
2241 * writing to is congested. In other cases it is safe to throttle.
2242 */
2243static int current_may_throttle(void)
2244{
NeilBrowna37b0712020-06-01 21:48:18 -07002245 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002246 current->backing_dev_info == NULL ||
2247 bdi_write_congested(current->backing_dev_info);
2248}
2249
2250/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002251 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002252 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002253 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002254static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002255shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002256 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002257{
2258 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002259 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002260 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002261 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002262 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002263 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002264 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002265 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002266 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002267
Mel Gorman599d0c92016-07-28 15:45:31 -07002268 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002269 if (stalled)
2270 return 0;
2271
2272 /* wait a bit for the reclaimer. */
2273 msleep(100);
2274 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002275
2276 /* We are about to die and free our memory. Return now. */
2277 if (fatal_signal_pending(current))
2278 return SWAP_CLUSTER_MAX;
2279 }
2280
Linus Torvalds1da177e2005-04-16 15:20:36 -07002281 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002282
Alex Shi6168d0d2020-12-15 12:34:29 -08002283 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002284
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002285 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002286 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002287
Mel Gorman599d0c92016-07-28 15:45:31 -07002288 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002289 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002290 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002291 __count_vm_events(item, nr_scanned);
2292 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002293 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2294
Alex Shi6168d0d2020-12-15 12:34:29 -08002295 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002296
Hillf Dantond563c052012-03-21 16:34:02 -07002297 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002298 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002299
Shakeel Butt013339d2020-12-14 19:06:39 -08002300 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002301
Alex Shi6168d0d2020-12-15 12:34:29 -08002302 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002303 move_pages_to_lru(lruvec, &page_list);
2304
2305 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002306 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002307 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002308 __count_vm_events(item, nr_reclaimed);
2309 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002310 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002311 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002312
Alex Shi75cc3c92020-12-15 14:20:50 -08002313 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002314 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002315 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002316
Mel Gorman92df3a72011-10-31 17:07:56 -07002317 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002318 * If dirty pages are scanned that are not queued for IO, it
2319 * implies that flushers are not doing their job. This can
2320 * happen when memory pressure pushes dirty pages to the end of
2321 * the LRU before the dirty limits are breached and the dirty
2322 * data has expired. It can also happen when the proportion of
2323 * dirty pages grows not through writes but through memory
2324 * pressure reclaiming all the clean cache. And in some cases,
2325 * the flushers simply cannot keep up with the allocation
2326 * rate. Nudge the flusher threads in case they are asleep.
2327 */
2328 if (stat.nr_unqueued_dirty == nr_taken)
2329 wakeup_flusher_threads(WB_REASON_VMSCAN);
2330
Andrey Ryabinind108c772018-04-10 16:27:59 -07002331 sc->nr.dirty += stat.nr_dirty;
2332 sc->nr.congested += stat.nr_congested;
2333 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2334 sc->nr.writeback += stat.nr_writeback;
2335 sc->nr.immediate += stat.nr_immediate;
2336 sc->nr.taken += nr_taken;
2337 if (file)
2338 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002339
Mel Gorman599d0c92016-07-28 15:45:31 -07002340 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002341 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002342 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002343}
2344
Hugh Dickins15b44732020-12-15 14:21:31 -08002345/*
2346 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2347 *
2348 * We move them the other way if the page is referenced by one or more
2349 * processes.
2350 *
2351 * If the pages are mostly unmapped, the processing is fast and it is
2352 * appropriate to hold lru_lock across the whole operation. But if
2353 * the pages are mapped, the processing is slow (page_referenced()), so
2354 * we should drop lru_lock around each page. It's impossible to balance
2355 * this, so instead we remove the pages from the LRU while processing them.
2356 * It is safe to rely on PG_active against the non-LRU pages in here because
2357 * nobody will play with that bit on a non-LRU page.
2358 *
2359 * The downside is that we have to touch page->_refcount against each page.
2360 * But we had to alter page->flags anyway.
2361 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002362static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002363 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002364 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002365 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002366{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002367 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002368 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002369 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002370 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002371 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002372 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002373 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002374 unsigned nr_deactivate, nr_activate;
2375 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002376 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002377 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002378
2379 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002380
Alex Shi6168d0d2020-12-15 12:34:29 -08002381 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002382
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002383 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002384 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002385
Mel Gorman599d0c92016-07-28 15:45:31 -07002386 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002387
Shakeel Butt912c0572020-08-06 23:26:32 -07002388 if (!cgroup_reclaim(sc))
2389 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002390 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002391
Alex Shi6168d0d2020-12-15 12:34:29 -08002392 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002393
Linus Torvalds1da177e2005-04-16 15:20:36 -07002394 while (!list_empty(&l_hold)) {
2395 cond_resched();
2396 page = lru_to_page(&l_hold);
2397 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002398
Hugh Dickins39b5f292012-10-08 16:33:18 -07002399 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002400 putback_lru_page(page);
2401 continue;
2402 }
2403
Mel Gormancc715d92012-03-21 16:34:00 -07002404 if (unlikely(buffer_heads_over_limit)) {
2405 if (page_has_private(page) && trylock_page(page)) {
2406 if (page_has_private(page))
2407 try_to_release_page(page, 0);
2408 unlock_page(page);
2409 }
2410 }
2411
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002412 if (page_referenced(page, 0, sc->target_mem_cgroup,
2413 &vm_flags)) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002414 /*
2415 * Identify referenced, file-backed active pages and
2416 * give them one more trip around the active list. So
2417 * that executable code get better chances to stay in
2418 * memory under moderate memory pressure. Anon pages
2419 * are not likely to be evicted by use-once streaming
2420 * IO, plus JVM can create lots of anon VM_EXEC pages,
2421 * so we ignore them here.
2422 */
Huang Ying9de4f222020-04-06 20:04:41 -07002423 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002424 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002425 list_add(&page->lru, &l_active);
2426 continue;
2427 }
2428 }
Rik van Riel7e9cd482008-10-18 20:26:35 -07002429
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002430 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002431 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002432 list_add(&page->lru, &l_inactive);
2433 }
2434
Andrew Mortonb5557492009-01-06 14:40:13 -08002435 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002436 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002437 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002438 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002439
Kirill Tkhaia222f342019-05-13 17:17:00 -07002440 nr_activate = move_pages_to_lru(lruvec, &l_active);
2441 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002442 /* Keep all free pages in l_active list */
2443 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002444
2445 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2446 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2447
Mel Gorman599d0c92016-07-28 15:45:31 -07002448 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002449 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002450
Kirill Tkhaif372d892019-05-13 17:16:57 -07002451 mem_cgroup_uncharge_list(&l_active);
2452 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002453 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2454 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002455}
2456
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002457unsigned long reclaim_pages(struct list_head *page_list)
2458{
Yang Shif661d002020-04-01 21:10:05 -07002459 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002460 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002461 LIST_HEAD(node_page_list);
2462 struct reclaim_stat dummy_stat;
2463 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002464 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002465 struct scan_control sc = {
2466 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002467 .may_writepage = 1,
2468 .may_unmap = 1,
2469 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002470 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002471 };
2472
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002473 noreclaim_flag = memalloc_noreclaim_save();
2474
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002475 while (!list_empty(page_list)) {
2476 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002477 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002478 nid = page_to_nid(page);
2479 INIT_LIST_HEAD(&node_page_list);
2480 }
2481
2482 if (nid == page_to_nid(page)) {
2483 ClearPageActive(page);
2484 list_move(&page->lru, &node_page_list);
2485 continue;
2486 }
2487
2488 nr_reclaimed += shrink_page_list(&node_page_list,
2489 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002490 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002491 while (!list_empty(&node_page_list)) {
2492 page = lru_to_page(&node_page_list);
2493 list_del(&page->lru);
2494 putback_lru_page(page);
2495 }
2496
Yang Shif661d002020-04-01 21:10:05 -07002497 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002498 }
2499
2500 if (!list_empty(&node_page_list)) {
2501 nr_reclaimed += shrink_page_list(&node_page_list,
2502 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002503 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002504 while (!list_empty(&node_page_list)) {
2505 page = lru_to_page(&node_page_list);
2506 list_del(&page->lru);
2507 putback_lru_page(page);
2508 }
2509 }
2510
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002511 memalloc_noreclaim_restore(noreclaim_flag);
2512
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002513 return nr_reclaimed;
2514}
2515
Johannes Weinerb91ac372019-11-30 17:56:02 -08002516static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2517 struct lruvec *lruvec, struct scan_control *sc)
2518{
2519 if (is_active_lru(lru)) {
2520 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2521 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2522 else
2523 sc->skipped_deactivate = 1;
2524 return 0;
2525 }
2526
2527 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2528}
2529
Rik van Riel59dc76b2016-05-20 16:56:31 -07002530/*
2531 * The inactive anon list should be small enough that the VM never has
2532 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002533 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002534 * The inactive file list should be small enough to leave most memory
2535 * to the established workingset on the scan-resistant active list,
2536 * but large enough to avoid thrashing the aggregate readahead window.
2537 *
2538 * Both inactive lists should also be large enough that each inactive
2539 * page has a chance to be referenced again before it is reclaimed.
2540 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002541 * If that fails and refaulting is observed, the inactive list grows.
2542 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002543 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002544 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002545 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2546 *
2547 * total target max
2548 * memory ratio inactive
2549 * -------------------------------------
2550 * 10MB 1 5MB
2551 * 100MB 1 50MB
2552 * 1GB 3 250MB
2553 * 10GB 10 0.9GB
2554 * 100GB 31 3GB
2555 * 1TB 101 10GB
2556 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002557 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002558static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002559{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002560 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002561 unsigned long inactive, active;
2562 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002563 unsigned long gb;
2564
Johannes Weinerb91ac372019-11-30 17:56:02 -08002565 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2566 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002567
Johannes Weinerb91ac372019-11-30 17:56:02 -08002568 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002569 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002570 inactive_ratio = int_sqrt(10 * gb);
2571 else
2572 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002573
Rik van Riel59dc76b2016-05-20 16:56:31 -07002574 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002575}
2576
Johannes Weiner9a265112013-02-22 16:32:17 -08002577enum scan_balance {
2578 SCAN_EQUAL,
2579 SCAN_FRACT,
2580 SCAN_ANON,
2581 SCAN_FILE,
2582};
2583
Yu Zhao3eb07702020-09-27 20:49:08 -06002584static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2585{
2586 unsigned long file;
2587 struct lruvec *target_lruvec;
2588
Yu Zhaoa1537a62022-01-27 20:32:37 -07002589 if (lru_gen_enabled())
2590 return;
2591
Yu Zhao3eb07702020-09-27 20:49:08 -06002592 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2593
2594 /*
2595 * Flush the memory cgroup stats, so that we read accurate per-memcg
2596 * lruvec stats for heuristics.
2597 */
2598 mem_cgroup_flush_stats();
2599
2600 /*
2601 * Determine the scan balance between anon and file LRUs.
2602 */
2603 spin_lock_irq(&target_lruvec->lru_lock);
2604 sc->anon_cost = target_lruvec->anon_cost;
2605 sc->file_cost = target_lruvec->file_cost;
2606 spin_unlock_irq(&target_lruvec->lru_lock);
2607
2608 /*
2609 * Target desirable inactive:active list ratios for the anon
2610 * and file LRU lists.
2611 */
2612 if (!sc->force_deactivate) {
2613 unsigned long refaults;
2614
2615 refaults = lruvec_page_state(target_lruvec,
2616 WORKINGSET_ACTIVATE_ANON);
2617 if (refaults != target_lruvec->refaults[0] ||
2618 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2619 sc->may_deactivate |= DEACTIVATE_ANON;
2620 else
2621 sc->may_deactivate &= ~DEACTIVATE_ANON;
2622
2623 /*
2624 * When refaults are being observed, it means a new
2625 * workingset is being established. Deactivate to get
2626 * rid of any stale active pages quickly.
2627 */
2628 refaults = lruvec_page_state(target_lruvec,
2629 WORKINGSET_ACTIVATE_FILE);
2630 if (refaults != target_lruvec->refaults[1] ||
2631 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2632 sc->may_deactivate |= DEACTIVATE_FILE;
2633 else
2634 sc->may_deactivate &= ~DEACTIVATE_FILE;
2635 } else
2636 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2637
2638 /*
2639 * If we have plenty of inactive file pages that aren't
2640 * thrashing, try to reclaim those first before touching
2641 * anonymous pages.
2642 */
2643 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2644 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2645 sc->cache_trim_mode = 1;
2646 else
2647 sc->cache_trim_mode = 0;
2648
2649 /*
2650 * Prevent the reclaimer from falling into the cache trap: as
2651 * cache pages start out inactive, every cache fault will tip
2652 * the scan balance towards the file LRU. And as the file LRU
2653 * shrinks, so does the window for rotation from references.
2654 * This means we have a runaway feedback loop where a tiny
2655 * thrashing file LRU becomes infinitely more attractive than
2656 * anon pages. Try to detect this based on file LRU size.
2657 */
2658 if (!cgroup_reclaim(sc)) {
2659 unsigned long total_high_wmark = 0;
2660 unsigned long free, anon;
2661 int z;
2662
2663 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2664 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2665 node_page_state(pgdat, NR_INACTIVE_FILE);
2666
2667 for (z = 0; z < MAX_NR_ZONES; z++) {
2668 struct zone *zone = &pgdat->node_zones[z];
2669
2670 if (!managed_zone(zone))
2671 continue;
2672
2673 total_high_wmark += high_wmark_pages(zone);
2674 }
2675
2676 /*
2677 * Consider anon: if that's low too, this isn't a
2678 * runaway file reclaim problem, but rather just
2679 * extreme pressure. Reclaim as per usual then.
2680 */
2681 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2682
2683 sc->file_is_tiny =
2684 file + free <= total_high_wmark &&
2685 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2686 anon >> sc->priority;
2687 }
2688}
2689
Linus Torvalds1da177e2005-04-16 15:20:36 -07002690/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002691 * Determine how aggressively the anon and file LRU lists should be
2692 * scanned. The relative value of each set of LRU lists is determined
2693 * by looking at the fraction of the pages scanned we did rotate back
2694 * onto the active list instead of evict.
2695 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002696 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2697 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002698 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002699static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2700 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002701{
Keith Buscha2a36482021-09-02 14:59:26 -07002702 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002703 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002704 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002705 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002706 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002707 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002708 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002709 unsigned long ap, fp;
2710 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002711 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002712
2713 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002714 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002715 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002716 goto out;
2717 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002718
Johannes Weiner10316b32013-02-22 16:32:14 -08002719 /*
2720 * Global reclaim will swap to prevent OOM even with no
2721 * swappiness, but memcg users want to use this knob to
2722 * disable swapping for individual groups completely when
2723 * using the memory controller's swap limit feature would be
2724 * too expensive.
2725 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002726 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002727 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002728 goto out;
2729 }
2730
2731 /*
2732 * Do not apply any pressure balancing cleverness when the
2733 * system is close to OOM, scan both anon and file equally
2734 * (unless the swappiness setting disagrees with swapping).
2735 */
Johannes Weiner02695172014-08-06 16:06:17 -07002736 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002737 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002738 goto out;
2739 }
2740
Johannes Weiner11d16c22013-02-22 16:32:15 -08002741 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002742 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002743 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002744 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002745 scan_balance = SCAN_ANON;
2746 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002747 }
2748
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002749 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2750
Johannes Weiner62376252014-05-06 12:50:07 -07002751 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002752 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002753 * anything from the anonymous working right now. But when balancing
2754 * anon and page cache files for reclaim, allow swapping of anon pages
2755 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002756 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002757 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002758 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002759 goto out;
2760 }
2761
Johannes Weiner9a265112013-02-22 16:32:17 -08002762 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002763 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002764 * Calculate the pressure balance between anon and file pages.
2765 *
2766 * The amount of pressure we put on each LRU is inversely
2767 * proportional to the cost of reclaiming each list, as
2768 * determined by the share of pages that are refaulting, times
2769 * the relative IO cost of bringing back a swapped out
2770 * anonymous page vs reloading a filesystem page (swappiness).
2771 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002772 * Although we limit that influence to ensure no list gets
2773 * left behind completely: at least a third of the pressure is
2774 * applied, before swappiness.
2775 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002776 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002777 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002778 total_cost = sc->anon_cost + sc->file_cost;
2779 anon_cost = total_cost + sc->anon_cost;
2780 file_cost = total_cost + sc->file_cost;
2781 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002782
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002783 ap = swappiness * (total_cost + 1);
2784 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002785
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002786 fp = (200 - swappiness) * (total_cost + 1);
2787 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002788
Shaohua Li76a33fc2010-05-24 14:32:36 -07002789 fraction[0] = ap;
2790 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002791 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002792out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002793 for_each_evictable_lru(lru) {
2794 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002795 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002796 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002797 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002798
Chris Down9783aa92019-10-06 17:58:32 -07002799 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002800 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2801 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002802
Johannes Weinerf56ce412021-08-19 19:04:21 -07002803 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002804 /*
2805 * Scale a cgroup's reclaim pressure by proportioning
2806 * its current usage to its memory.low or memory.min
2807 * setting.
2808 *
2809 * This is important, as otherwise scanning aggression
2810 * becomes extremely binary -- from nothing as we
2811 * approach the memory protection threshold, to totally
2812 * nominal as we exceed it. This results in requiring
2813 * setting extremely liberal protection thresholds. It
2814 * also means we simply get no protection at all if we
2815 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002816 *
2817 * If there is any protection in place, we reduce scan
2818 * pressure by how much of the total memory used is
2819 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002820 *
Chris Down9de7ca42019-10-06 17:58:35 -07002821 * There is one special case: in the first reclaim pass,
2822 * we skip over all groups that are within their low
2823 * protection. If that fails to reclaim enough pages to
2824 * satisfy the reclaim goal, we come back and override
2825 * the best-effort low protection. However, we still
2826 * ideally want to honor how well-behaved groups are in
2827 * that case instead of simply punishing them all
2828 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002829 * memory they are using, reducing the scan pressure
2830 * again by how much of the total memory used is under
2831 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002832 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002833 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002834 unsigned long protection;
2835
2836 /* memory.low scaling, make sure we retry before OOM */
2837 if (!sc->memcg_low_reclaim && low > min) {
2838 protection = low;
2839 sc->memcg_low_skipped = 1;
2840 } else {
2841 protection = min;
2842 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002843
2844 /* Avoid TOCTOU with earlier protection check */
2845 cgroup_size = max(cgroup_size, protection);
2846
2847 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002848 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002849
2850 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002851 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002852 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002853 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002854 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002855 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002856 } else {
2857 scan = lruvec_size;
2858 }
2859
2860 scan >>= sc->priority;
2861
Johannes Weiner688035f2017-05-03 14:52:07 -07002862 /*
2863 * If the cgroup's already been deleted, make sure to
2864 * scrape out the remaining cache.
2865 */
2866 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002867 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002868
Johannes Weiner688035f2017-05-03 14:52:07 -07002869 switch (scan_balance) {
2870 case SCAN_EQUAL:
2871 /* Scan lists relative to size */
2872 break;
2873 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002874 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002875 * Scan types proportional to swappiness and
2876 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002877 * Make sure we don't miss the last page on
2878 * the offlined memory cgroups because of a
2879 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002880 */
Gavin Shan76073c62020-02-20 20:04:24 -08002881 scan = mem_cgroup_online(memcg) ?
2882 div64_u64(scan * fraction[file], denominator) :
2883 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002884 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002885 break;
2886 case SCAN_FILE:
2887 case SCAN_ANON:
2888 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002889 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002890 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002891 break;
2892 default:
2893 /* Look ma, no brain */
2894 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002895 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002896
Johannes Weiner688035f2017-05-03 14:52:07 -07002897 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002898 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002899}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002900
Dave Hansen2f368a92021-09-02 14:59:23 -07002901/*
2902 * Anonymous LRU management is a waste if there is
2903 * ultimately no way to reclaim the memory.
2904 */
2905static bool can_age_anon_pages(struct pglist_data *pgdat,
2906 struct scan_control *sc)
2907{
2908 /* Aging the anon LRU is valuable if swap is present: */
2909 if (total_swap_pages > 0)
2910 return true;
2911
2912 /* Also valuable if anon pages can be demoted: */
2913 return can_demote(pgdat->node_id, sc);
2914}
2915
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002916#ifdef CONFIG_LRU_GEN
2917
2918/******************************************************************************
2919 * shorthand helpers
2920 ******************************************************************************/
2921
Yu Zhaoa1537a62022-01-27 20:32:37 -07002922#define DEFINE_MAX_SEQ(lruvec) \
2923 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2924
2925#define DEFINE_MIN_SEQ(lruvec) \
2926 unsigned long min_seq[ANON_AND_FILE] = { \
2927 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2928 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2929 }
2930
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002931#define for_each_gen_type_zone(gen, type, zone) \
2932 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2933 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2934 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2935
Yu Zhaoa1537a62022-01-27 20:32:37 -07002936static int page_lru_gen(struct page *page)
2937{
2938 unsigned long flags = READ_ONCE(page->flags);
2939
2940 return ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
2941}
2942
2943static int page_lru_tier(struct page *page)
2944{
2945 int refs;
2946 unsigned long flags = READ_ONCE(page->flags);
2947
2948 refs = (flags & LRU_REFS_FLAGS) == LRU_REFS_FLAGS ?
2949 ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) + 1 : 0;
2950
2951 return lru_tier_from_refs(refs);
2952}
2953
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002954static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
2955{
2956 struct pglist_data *pgdat = NODE_DATA(nid);
2957
2958#ifdef CONFIG_MEMCG
2959 if (memcg) {
2960 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2961
2962 /* for hotadd_new_pgdat() */
2963 if (!lruvec->pgdat)
2964 lruvec->pgdat = pgdat;
2965
2966 return lruvec;
2967 }
2968#endif
2969 VM_BUG_ON(!mem_cgroup_disabled());
2970
2971 return pgdat ? &pgdat->__lruvec : NULL;
2972}
2973
Yu Zhaoa1537a62022-01-27 20:32:37 -07002974static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2975{
2976 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2977 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2978
2979 if (!can_demote(pgdat->node_id, sc) &&
2980 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2981 return 0;
2982
2983 return mem_cgroup_swappiness(memcg);
2984}
2985
2986static int get_nr_gens(struct lruvec *lruvec, int type)
2987{
2988 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2989}
2990
2991static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2992{
2993 /* see the comment on lru_gen_struct */
2994 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2995 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2996 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2997}
2998
2999/******************************************************************************
Yu Zhao5280d762022-01-27 19:23:01 -07003000 * mm_struct list
3001 ******************************************************************************/
3002
3003static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3004{
3005 static struct lru_gen_mm_list mm_list = {
3006 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3007 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3008 };
3009
3010#ifdef CONFIG_MEMCG
3011 if (memcg)
3012 return &memcg->mm_list;
3013#endif
3014 VM_BUG_ON(!mem_cgroup_disabled());
3015
3016 return &mm_list;
3017}
3018
3019void lru_gen_add_mm(struct mm_struct *mm)
3020{
3021 int nid;
3022 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3023 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3024
3025 VM_BUG_ON_MM(!list_empty(&mm->lru_gen.list), mm);
3026#ifdef CONFIG_MEMCG
3027 VM_BUG_ON_MM(mm->lru_gen.memcg, mm);
3028 mm->lru_gen.memcg = memcg;
3029#endif
3030 spin_lock(&mm_list->lock);
3031
3032 for_each_node_state(nid, N_MEMORY) {
3033 struct lruvec *lruvec = get_lruvec(memcg, nid);
3034
3035 if (!lruvec)
3036 continue;
3037
3038 if (lruvec->mm_state.tail == &mm_list->fifo)
3039 lruvec->mm_state.tail = &mm->lru_gen.list;
3040 }
3041
3042 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3043
3044 spin_unlock(&mm_list->lock);
3045}
3046
3047void lru_gen_del_mm(struct mm_struct *mm)
3048{
3049 int nid;
3050 struct lru_gen_mm_list *mm_list;
3051 struct mem_cgroup *memcg = NULL;
3052
3053 if (list_empty(&mm->lru_gen.list))
3054 return;
3055
3056#ifdef CONFIG_MEMCG
3057 memcg = mm->lru_gen.memcg;
3058#endif
3059 mm_list = get_mm_list(memcg);
3060
3061 spin_lock(&mm_list->lock);
3062
3063 for_each_node(nid) {
3064 struct lruvec *lruvec = get_lruvec(memcg, nid);
3065
3066 if (!lruvec)
3067 continue;
3068
3069 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3070 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3071
3072 if (lruvec->mm_state.head != &mm->lru_gen.list)
3073 continue;
3074
3075 lruvec->mm_state.head = lruvec->mm_state.head->next;
3076 if (lruvec->mm_state.head == &mm_list->fifo)
3077 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3078 }
3079
3080 list_del_init(&mm->lru_gen.list);
3081
3082 spin_unlock(&mm_list->lock);
3083
3084#ifdef CONFIG_MEMCG
3085 mem_cgroup_put(mm->lru_gen.memcg);
3086 mm->lru_gen.memcg = NULL;
3087#endif
3088}
3089
3090#ifdef CONFIG_MEMCG
3091void lru_gen_migrate_mm(struct mm_struct *mm)
3092{
3093 struct mem_cgroup *memcg;
3094
3095 lockdep_assert_held(&mm->owner->alloc_lock);
3096
3097 /* for mm_update_next_owner() */
3098 if (mem_cgroup_disabled())
3099 return;
3100
3101 rcu_read_lock();
3102 memcg = mem_cgroup_from_task(mm->owner);
3103 rcu_read_unlock();
3104 if (memcg == mm->lru_gen.memcg)
3105 return;
3106
3107 VM_BUG_ON_MM(!mm->lru_gen.memcg, mm);
3108 VM_BUG_ON_MM(list_empty(&mm->lru_gen.list), mm);
3109
3110 lru_gen_del_mm(mm);
3111 lru_gen_add_mm(mm);
3112}
3113#endif
3114
3115/*
3116 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3117 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3118 * bits in a bitmap, k is the number of hash functions and n is the number of
3119 * inserted items.
3120 *
3121 * Page table walkers use one of the two filters to reduce their search space.
3122 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3123 * aging uses the double-buffering technique to flip to the other filter each
3124 * time it produces a new generation. For non-leaf entries that have enough
3125 * leaf entries, the aging carries them over to the next generation in
3126 * walk_pmd_range(); the eviction also report them when walking the rmap
3127 * in lru_gen_look_around().
3128 *
3129 * For future optimizations:
3130 * 1. It's not necessary to keep both filters all the time. The spare one can be
3131 * freed after the RCU grace period and reallocated if needed again.
3132 * 2. And when reallocating, it's worth scaling its size according to the number
3133 * of inserted entries in the other filter, to reduce the memory overhead on
3134 * small systems and false positives on large systems.
3135 * 3. Jenkins' hash function is an alternative to Knuth's.
3136 */
3137#define BLOOM_FILTER_SHIFT 15
3138
3139static inline int filter_gen_from_seq(unsigned long seq)
3140{
3141 return seq % NR_BLOOM_FILTERS;
3142}
3143
3144static void get_item_key(void *item, int *key)
3145{
3146 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3147
3148 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3149
3150 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3151 key[1] = hash >> BLOOM_FILTER_SHIFT;
3152}
3153
3154static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3155{
3156 unsigned long *filter;
3157 int gen = filter_gen_from_seq(seq);
3158
3159 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3160
3161 filter = lruvec->mm_state.filters[gen];
3162 if (filter) {
3163 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3164 return;
3165 }
3166
3167 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT), GFP_ATOMIC);
3168 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3169}
3170
3171static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3172{
3173 int key[2];
3174 unsigned long *filter;
3175 int gen = filter_gen_from_seq(seq);
3176
3177 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3178 if (!filter)
3179 return;
3180
3181 get_item_key(item, key);
3182
3183 if (!test_bit(key[0], filter))
3184 set_bit(key[0], filter);
3185 if (!test_bit(key[1], filter))
3186 set_bit(key[1], filter);
3187}
3188
3189static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3190{
3191 int key[2];
3192 unsigned long *filter;
3193 int gen = filter_gen_from_seq(seq);
3194
3195 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3196 if (!filter)
3197 return true;
3198
3199 get_item_key(item, key);
3200
3201 return test_bit(key[0], filter) && test_bit(key[1], filter);
3202}
3203
3204static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3205{
3206 int i;
3207 int hist;
3208
3209 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3210
3211 if (walk) {
3212 hist = lru_hist_from_seq(walk->max_seq);
3213
3214 for (i = 0; i < NR_MM_STATS; i++) {
3215 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3216 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3217 walk->mm_stats[i] = 0;
3218 }
3219 }
3220
3221 if (NR_HIST_GENS > 1 && last) {
3222 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3223
3224 for (i = 0; i < NR_MM_STATS; i++)
3225 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3226 }
3227}
3228
3229static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3230{
3231 int type;
3232 unsigned long size = 0;
3233 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3234
3235 if (!walk->full_scan && cpumask_empty(mm_cpumask(mm)) &&
3236 !node_isset(pgdat->node_id, mm->lru_gen.nodes))
3237 return true;
3238
3239 node_clear(pgdat->node_id, mm->lru_gen.nodes);
3240
3241 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3242 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3243 get_mm_counter(mm, MM_ANONPAGES) +
3244 get_mm_counter(mm, MM_SHMEMPAGES);
3245 }
3246
3247 if (size < MIN_LRU_BATCH)
3248 return true;
3249
3250 if (mm_is_oom_victim(mm))
3251 return true;
3252
3253 return !mmget_not_zero(mm);
3254}
3255
3256static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3257 struct mm_struct **iter)
3258{
3259 bool first = false;
3260 bool last = true;
3261 struct mm_struct *mm = NULL;
3262 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3263 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3264 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3265
3266 /*
3267 * There are four interesting cases for this page table walker:
3268 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3269 * there is nothing to be done.
3270 * 2. It's the first of the current generation, and it needs to reset
3271 * the Bloom filter for the next generation.
3272 * 3. It reaches the end of mm_list, and it needs to increment
3273 * mm_state->seq; the iteration is done.
3274 * 4. It's the last of the current generation, and it needs to reset the
3275 * mm stats counters for the next generation.
3276 */
3277 if (*iter)
3278 mmput_async(*iter);
3279 else if (walk->max_seq <= READ_ONCE(mm_state->seq))
3280 return false;
3281
3282 spin_lock(&mm_list->lock);
3283
3284 VM_BUG_ON(mm_state->seq + 1 < walk->max_seq);
3285 VM_BUG_ON(*iter && mm_state->seq > walk->max_seq);
3286 VM_BUG_ON(*iter && !mm_state->nr_walkers);
3287
3288 if (walk->max_seq <= mm_state->seq) {
3289 if (!*iter)
3290 last = false;
3291 goto done;
3292 }
3293
3294 if (!mm_state->nr_walkers) {
3295 VM_BUG_ON(mm_state->head && mm_state->head != &mm_list->fifo);
3296
3297 mm_state->head = mm_list->fifo.next;
3298 first = true;
3299 }
3300
3301 while (!mm && mm_state->head != &mm_list->fifo) {
3302 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3303
3304 mm_state->head = mm_state->head->next;
3305
3306 /* full scan for those added after the last iteration */
3307 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3308 mm_state->tail = mm_state->head;
3309 walk->full_scan = true;
3310 }
3311
3312 if (should_skip_mm(mm, walk))
3313 mm = NULL;
3314 }
3315
3316 if (mm_state->head == &mm_list->fifo)
3317 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3318done:
3319 if (*iter && !mm)
3320 mm_state->nr_walkers--;
3321 if (!*iter && mm)
3322 mm_state->nr_walkers++;
3323
3324 if (mm_state->nr_walkers)
3325 last = false;
3326
3327 if (mm && first)
3328 reset_bloom_filter(lruvec, walk->max_seq + 1);
3329
3330 if (*iter || last)
3331 reset_mm_stats(lruvec, walk, last);
3332
3333 spin_unlock(&mm_list->lock);
3334
3335 *iter = mm;
3336
3337 return last;
3338}
3339
3340static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3341{
3342 bool success = false;
3343 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3344 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3345 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3346
3347 if (max_seq <= READ_ONCE(mm_state->seq))
3348 return false;
3349
3350 spin_lock(&mm_list->lock);
3351
3352 VM_BUG_ON(mm_state->seq + 1 < max_seq);
3353
3354 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3355 VM_BUG_ON(mm_state->head && mm_state->head != &mm_list->fifo);
3356
3357 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3358 reset_mm_stats(lruvec, NULL, true);
3359 success = true;
3360 }
3361
3362 spin_unlock(&mm_list->lock);
3363
3364 return success;
3365}
3366
3367/******************************************************************************
Yu Zhaoa1537a62022-01-27 20:32:37 -07003368 * refault feedback loop
3369 ******************************************************************************/
3370
3371/*
3372 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3373 *
3374 * The P term is refaulted/(evicted+protected) from a tier in the generation
3375 * currently being evicted; the I term is the exponential moving average of the
3376 * P term over the generations previously evicted, using the smoothing factor
3377 * 1/2; the D term isn't supported.
3378 *
3379 * The setpoint (SP) is always the first tier of one type; the process variable
3380 * (PV) is either any tier of the other type or any other tier of the same
3381 * type.
3382 *
3383 * The error is the difference between the SP and the PV; the correction is
3384 * turn off protection when SP>PV or turn on protection when SP<PV.
3385 *
3386 * For future optimizations:
3387 * 1. The D term may discount the other two terms over time so that long-lived
3388 * generations can resist stale information.
3389 */
3390struct ctrl_pos {
3391 unsigned long refaulted;
3392 unsigned long total;
3393 int gain;
3394};
3395
3396static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3397 struct ctrl_pos *pos)
3398{
3399 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3400 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3401
3402 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3403 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3404 pos->total = lrugen->avg_total[type][tier] +
3405 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3406 if (tier)
3407 pos->total += lrugen->protected[hist][type][tier - 1];
3408 pos->gain = gain;
3409}
3410
3411static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3412{
3413 int hist, tier;
3414 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3415 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3416 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3417
3418 lockdep_assert_held(&lruvec->lru_lock);
3419
3420 if (!carryover && !clear)
3421 return;
3422
3423 hist = lru_hist_from_seq(seq);
3424
3425 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3426 if (carryover) {
3427 unsigned long sum;
3428
3429 sum = lrugen->avg_refaulted[type][tier] +
3430 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3431 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3432
3433 sum = lrugen->avg_total[type][tier] +
3434 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3435 if (tier)
3436 sum += lrugen->protected[hist][type][tier - 1];
3437 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3438 }
3439
3440 if (clear) {
3441 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3442 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3443 if (tier)
3444 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3445 }
3446 }
3447}
3448
3449static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3450{
3451 /*
3452 * Return true if the PV has a limited number of refaults or a lower
3453 * refaulted/total than the SP.
3454 */
3455 return pv->refaulted < MIN_LRU_BATCH ||
3456 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3457 (sp->refaulted + 1) * pv->total * pv->gain;
3458}
3459
3460/******************************************************************************
3461 * the aging
3462 ******************************************************************************/
3463
Yu Zhaoafd94c92022-01-27 20:43:22 -07003464static int page_update_gen(struct page *page, int gen)
3465{
3466 unsigned long old_flags, new_flags;
3467
3468 VM_BUG_ON(gen >= MAX_NR_GENS);
3469 VM_BUG_ON(!rcu_read_lock_held());
3470
3471 do {
3472 new_flags = old_flags = READ_ONCE(page->flags);
3473
3474 /* for shrink_page_list() */
3475 if (!(new_flags & LRU_GEN_MASK)) {
3476 new_flags |= BIT(PG_referenced);
3477 continue;
3478 }
3479
3480 new_flags &= ~LRU_GEN_MASK;
3481 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3482 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3483 } while (new_flags != old_flags &&
3484 cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3485
3486 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3487}
3488
Yu Zhaoa1537a62022-01-27 20:32:37 -07003489static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3490{
3491 unsigned long old_flags, new_flags;
3492 int type = page_is_file_lru(page);
3493 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3494 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3495
3496 do {
3497 new_flags = old_flags = READ_ONCE(page->flags);
3498 VM_BUG_ON_PAGE(!(new_flags & LRU_GEN_MASK), page);
3499
Yu Zhaoafd94c92022-01-27 20:43:22 -07003500 new_gen = ((new_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3501 /* page_update_gen() has promoted this page? */
3502 if (new_gen >= 0 && new_gen != old_gen)
3503 return new_gen;
3504
Yu Zhaoa1537a62022-01-27 20:32:37 -07003505 new_gen = (old_gen + 1) % MAX_NR_GENS;
3506
3507 new_flags &= ~LRU_GEN_MASK;
3508 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3509 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3510 /* for end_page_writeback() */
3511 if (reclaiming)
3512 new_flags |= BIT(PG_reclaim);
3513 } while (cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3514
3515 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3516
3517 return new_gen;
3518}
3519
Yu Zhao5280d762022-01-27 19:23:01 -07003520static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3521 int old_gen, int new_gen)
3522{
3523 int type = page_is_file_lru(page);
3524 int zone = page_zonenum(page);
3525 int delta = thp_nr_pages(page);
3526
3527 VM_BUG_ON(old_gen >= MAX_NR_GENS);
3528 VM_BUG_ON(new_gen >= MAX_NR_GENS);
3529
3530 walk->batched++;
3531
3532 walk->nr_pages[old_gen][type][zone] -= delta;
3533 walk->nr_pages[new_gen][type][zone] += delta;
3534}
3535
3536static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3537{
3538 int gen, type, zone;
3539 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3540
3541 walk->batched = 0;
3542
3543 for_each_gen_type_zone(gen, type, zone) {
3544 enum lru_list lru = type * LRU_INACTIVE_FILE;
3545 int delta = walk->nr_pages[gen][type][zone];
3546
3547 if (!delta)
3548 continue;
3549
3550 walk->nr_pages[gen][type][zone] = 0;
3551 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3552 lrugen->nr_pages[gen][type][zone] + delta);
3553
3554 if (lru_gen_is_active(lruvec, gen))
3555 lru += LRU_ACTIVE;
3556 __update_lru_size(lruvec, lru, zone, delta);
3557 }
3558}
3559
3560static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *walk)
3561{
3562 struct address_space *mapping;
3563 struct vm_area_struct *vma = walk->vma;
3564 struct lru_gen_mm_walk *priv = walk->private;
3565
3566 if (!vma_is_accessible(vma) || is_vm_hugetlb_page(vma) ||
3567 (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ)) ||
3568 vma == get_gate_vma(vma->vm_mm))
3569 return true;
3570
3571 if (vma_is_anonymous(vma))
3572 return !priv->can_swap;
3573
3574 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3575 return true;
3576
3577 mapping = vma->vm_file->f_mapping;
3578 if (mapping_unevictable(mapping))
3579 return true;
3580
3581 /* check readpage to exclude special mappings like dax, etc. */
3582 return shmem_mapping(mapping) ? !priv->can_swap : !mapping->a_ops->readpage;
3583}
3584
3585/*
3586 * Some userspace memory allocators map many single-page VMAs. Instead of
3587 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3588 * table to reduce zigzags and improve cache performance.
3589 */
3590static bool get_next_vma(struct mm_walk *walk, unsigned long mask, unsigned long size,
3591 unsigned long *start, unsigned long *end)
3592{
3593 unsigned long next = round_up(*end, size);
3594
3595 VM_BUG_ON(mask & size);
3596 VM_BUG_ON(*start >= *end);
3597 VM_BUG_ON((next & mask) != (*start & mask));
3598
3599 while (walk->vma) {
3600 if (next >= walk->vma->vm_end) {
3601 walk->vma = walk->vma->vm_next;
3602 continue;
3603 }
3604
3605 if ((next & mask) != (walk->vma->vm_start & mask))
3606 return false;
3607
3608 if (should_skip_vma(walk->vma->vm_start, walk->vma->vm_end, walk)) {
3609 walk->vma = walk->vma->vm_next;
3610 continue;
3611 }
3612
3613 *start = max(next, walk->vma->vm_start);
3614 next = (next | ~mask) + 1;
3615 /* rounded-up boundaries can wrap to 0 */
3616 *end = next && next < walk->vma->vm_end ? next : walk->vma->vm_end;
3617
3618 return true;
3619 }
3620
3621 return false;
3622}
3623
3624static bool suitable_to_scan(int total, int young)
3625{
3626 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3627
3628 /* suitable if the average number of young PTEs per cacheline is >=1 */
3629 return young * n >= total;
3630}
3631
3632static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3633 struct mm_walk *walk)
3634{
3635 int i;
3636 pte_t *pte;
3637 spinlock_t *ptl;
3638 unsigned long addr;
3639 int total = 0;
3640 int young = 0;
3641 struct lru_gen_mm_walk *priv = walk->private;
3642 struct mem_cgroup *memcg = lruvec_memcg(priv->lruvec);
3643 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3644 int old_gen, new_gen = lru_gen_from_seq(priv->max_seq);
3645
3646 VM_BUG_ON(pmd_leaf(*pmd));
3647
3648 ptl = pte_lockptr(walk->mm, pmd);
3649 if (!spin_trylock(ptl))
3650 return false;
3651
3652 arch_enter_lazy_mmu_mode();
3653
3654 pte = pte_offset_map(pmd, start & PMD_MASK);
3655restart:
3656 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3657 struct page *page;
3658 unsigned long pfn = pte_pfn(pte[i]);
3659
3660 VM_BUG_ON(addr < walk->vma->vm_start || addr >= walk->vma->vm_end);
3661
3662 total++;
3663 priv->mm_stats[MM_PTE_TOTAL]++;
3664
3665 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
3666 continue;
3667
3668 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
3669 continue;
3670
3671 if (!pte_young(pte[i])) {
3672 priv->mm_stats[MM_PTE_OLD]++;
3673 continue;
3674 }
3675
3676 VM_BUG_ON(!pfn_valid(pfn));
3677 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3678 continue;
3679
3680 page = compound_head(pfn_to_page(pfn));
3681 if (page_to_nid(page) != pgdat->node_id)
3682 continue;
3683
3684 if (page_memcg_rcu(page) != memcg)
3685 continue;
3686
3687 if (!ptep_test_and_clear_young(walk->vma, addr, pte + i))
3688 continue;
3689
3690 young++;
3691 priv->mm_stats[MM_PTE_YOUNG]++;
3692
3693 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3694 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3695 set_page_dirty(page);
3696
3697 old_gen = page_update_gen(page, new_gen);
3698 if (old_gen >= 0 && old_gen != new_gen)
3699 update_batch_size(priv, page, old_gen, new_gen);
3700 }
3701
3702 if (i < PTRS_PER_PTE && get_next_vma(walk, PMD_MASK, PAGE_SIZE, &start, &end))
3703 goto restart;
3704
3705 pte_unmap(pte);
3706
3707 arch_leave_lazy_mmu_mode();
3708 spin_unlock(ptl);
3709
3710 return suitable_to_scan(total, young);
3711}
3712
3713#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3714static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3715 struct mm_walk *walk, unsigned long *start)
3716{
3717 int i;
3718 pmd_t *pmd;
3719 spinlock_t *ptl;
3720 struct lru_gen_mm_walk *priv = walk->private;
3721 struct mem_cgroup *memcg = lruvec_memcg(priv->lruvec);
3722 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3723 int old_gen, new_gen = lru_gen_from_seq(priv->max_seq);
3724
3725 VM_BUG_ON(pud_leaf(*pud));
3726
3727 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3728 if (*start == -1) {
3729 *start = next;
3730 return;
3731 }
3732
3733 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3734 if (i && i <= MIN_LRU_BATCH) {
3735 __set_bit(i - 1, priv->bitmap);
3736 return;
3737 }
3738
3739 pmd = pmd_offset(pud, *start);
3740
3741 ptl = pmd_lockptr(walk->mm, pmd);
3742 if (!spin_trylock(ptl))
3743 goto done;
3744
3745 arch_enter_lazy_mmu_mode();
3746
3747 do {
3748 struct page *page;
3749 unsigned long pfn = pmd_pfn(pmd[i]);
3750 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3751
3752 VM_BUG_ON(addr < vma->vm_start || addr >= vma->vm_end);
3753
3754 if (!pmd_present(pmd[i]) || is_huge_zero_pmd(pmd[i]))
3755 goto next;
3756
3757 if (WARN_ON_ONCE(pmd_devmap(pmd[i])))
3758 goto next;
3759
3760 if (!pmd_trans_huge(pmd[i])) {
3761 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG))
3762 pmdp_test_and_clear_young(vma, addr, pmd + i);
3763 goto next;
3764 }
3765
3766 VM_BUG_ON(!pfn_valid(pfn));
3767 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3768 goto next;
3769
3770 page = pfn_to_page(pfn);
3771 VM_BUG_ON_PAGE(PageTail(page), page);
3772 if (page_to_nid(page) != pgdat->node_id)
3773 goto next;
3774
3775 if (page_memcg_rcu(page) != memcg)
3776 goto next;
3777
3778 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3779 goto next;
3780
3781 priv->mm_stats[MM_PTE_YOUNG]++;
3782
3783 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3784 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3785 set_page_dirty(page);
3786
3787 old_gen = page_update_gen(page, new_gen);
3788 if (old_gen >= 0 && old_gen != new_gen)
3789 update_batch_size(priv, page, old_gen, new_gen);
3790next:
3791 i = i > MIN_LRU_BATCH ? 0 :
3792 find_next_bit(priv->bitmap, MIN_LRU_BATCH, i) + 1;
3793 } while (i <= MIN_LRU_BATCH);
3794
3795 arch_leave_lazy_mmu_mode();
3796 spin_unlock(ptl);
3797done:
3798 *start = -1;
3799 bitmap_zero(priv->bitmap, MIN_LRU_BATCH);
3800}
3801#else
3802static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3803 struct mm_walk *walk, unsigned long *start)
3804{
3805}
3806#endif
3807
3808static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3809 struct mm_walk *walk)
3810{
3811 int i;
3812 pmd_t *pmd;
3813 unsigned long next;
3814 unsigned long addr;
3815 struct vm_area_struct *vma;
3816 unsigned long pos = -1;
3817 struct lru_gen_mm_walk *priv = walk->private;
3818
3819 VM_BUG_ON(pud_leaf(*pud));
3820
3821 /*
3822 * Finish an entire PMD in two passes: the first only reaches to PTE
3823 * tables to avoid taking the PMD lock; the second, if necessary, takes
3824 * the PMD lock to clear the accessed bit in PMD entries.
3825 */
3826 pmd = pmd_offset(pud, start & PUD_MASK);
3827restart:
3828 /* walk_pte_range() may call get_next_vma() */
3829 vma = walk->vma;
3830 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3831 pmd_t val = pmd_read_atomic(pmd + i);
3832
3833 /* for pmd_read_atomic() */
3834 barrier();
3835
3836 next = pmd_addr_end(addr, end);
3837
3838 if (!pmd_present(val)) {
3839 priv->mm_stats[MM_PTE_TOTAL]++;
3840 continue;
3841 }
3842
3843#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3844 if (pmd_trans_huge(val)) {
3845 unsigned long pfn = pmd_pfn(val);
3846 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3847
3848 priv->mm_stats[MM_PTE_TOTAL]++;
3849
3850 if (is_huge_zero_pmd(val))
3851 continue;
3852
3853 if (!pmd_young(val)) {
3854 priv->mm_stats[MM_PTE_OLD]++;
3855 continue;
3856 }
3857
3858 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3859 continue;
3860
3861 walk_pmd_range_locked(pud, addr, vma, walk, &pos);
3862 continue;
3863 }
3864#endif
3865 priv->mm_stats[MM_PMD_TOTAL]++;
3866
3867#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
3868 if (!pmd_young(val))
3869 continue;
3870
3871 walk_pmd_range_locked(pud, addr, vma, walk, &pos);
3872#endif
3873 if (!priv->full_scan && !test_bloom_filter(priv->lruvec, priv->max_seq, pmd + i))
3874 continue;
3875
3876 priv->mm_stats[MM_PMD_FOUND]++;
3877
3878 if (!walk_pte_range(&val, addr, next, walk))
3879 continue;
3880
3881 priv->mm_stats[MM_PMD_ADDED]++;
3882
3883 /* carry over to the next generation */
3884 update_bloom_filter(priv->lruvec, priv->max_seq + 1, pmd + i);
3885 }
3886
3887 walk_pmd_range_locked(pud, -1, vma, walk, &pos);
3888
3889 if (i < PTRS_PER_PMD && get_next_vma(walk, PUD_MASK, PMD_SIZE, &start, &end))
3890 goto restart;
3891}
3892
3893static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3894 struct mm_walk *walk)
3895{
3896 int i;
3897 pud_t *pud;
3898 unsigned long addr;
3899 unsigned long next;
3900 struct lru_gen_mm_walk *priv = walk->private;
3901
3902 VM_BUG_ON(p4d_leaf(*p4d));
3903
3904 pud = pud_offset(p4d, start & P4D_MASK);
3905restart:
3906 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3907 pud_t val = READ_ONCE(pud[i]);
3908
3909 next = pud_addr_end(addr, end);
3910
3911 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3912 continue;
3913
3914 walk_pmd_range(&val, addr, next, walk);
3915
3916 if (priv->batched >= MAX_LRU_BATCH) {
3917 end = (addr | ~PUD_MASK) + 1;
3918 goto done;
3919 }
3920 }
3921
3922 if (i < PTRS_PER_PUD && get_next_vma(walk, P4D_MASK, PUD_SIZE, &start, &end))
3923 goto restart;
3924
3925 end = round_up(end, P4D_SIZE);
3926done:
3927 /* rounded-up boundaries can wrap to 0 */
3928 priv->next_addr = end && walk->vma ? max(end, walk->vma->vm_start) : 0;
3929
3930 return -EAGAIN;
3931}
3932
3933static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3934{
3935 static const struct mm_walk_ops mm_walk_ops = {
3936 .test_walk = should_skip_vma,
3937 .p4d_entry = walk_pud_range,
3938 };
3939
3940 int err;
3941 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3942
3943 walk->next_addr = FIRST_USER_ADDRESS;
3944
3945 do {
3946 err = -EBUSY;
3947
3948 /* page_update_gen() requires stable page_memcg() */
3949 if (!mem_cgroup_trylock_pages(memcg))
3950 break;
3951
3952 /* the caller might be holding the lock for write */
3953 if (mmap_read_trylock(mm)) {
3954 unsigned long start = walk->next_addr;
3955 unsigned long end = mm->highest_vm_end;
3956
3957 err = walk_page_range(mm, start, end, &mm_walk_ops, walk);
3958
3959 mmap_read_unlock(mm);
3960
3961 if (walk->batched) {
3962 spin_lock_irq(&lruvec->lru_lock);
3963 reset_batch_size(lruvec, walk);
3964 spin_unlock_irq(&lruvec->lru_lock);
3965 }
3966 }
3967
3968 mem_cgroup_unlock_pages();
3969
3970 cond_resched();
3971 } while (err == -EAGAIN && walk->next_addr && !mm_is_oom_victim(mm));
3972}
3973
3974static struct lru_gen_mm_walk *alloc_mm_walk(void)
3975{
3976 if (current->reclaim_state && current->reclaim_state->mm_walk)
3977 return current->reclaim_state->mm_walk;
3978
3979 return kzalloc(sizeof(struct lru_gen_mm_walk),
3980 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3981}
3982
3983static void free_mm_walk(struct lru_gen_mm_walk *walk)
3984{
3985 if (!current->reclaim_state || !current->reclaim_state->mm_walk)
3986 kfree(walk);
3987}
3988
Yu Zhaoa1537a62022-01-27 20:32:37 -07003989static void inc_min_seq(struct lruvec *lruvec)
3990{
3991 int type;
3992 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3993
3994 VM_BUG_ON(!seq_is_valid(lruvec));
3995
3996 for (type = 0; type < ANON_AND_FILE; type++) {
3997 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
3998 continue;
3999
4000 reset_ctrl_pos(lruvec, type, true);
4001 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4002 }
4003}
4004
4005static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4006{
4007 int gen, type, zone;
4008 bool success = false;
4009 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4010 DEFINE_MIN_SEQ(lruvec);
4011
4012 VM_BUG_ON(!seq_is_valid(lruvec));
4013
4014 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4015 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4016 gen = lru_gen_from_seq(min_seq[type]);
4017
4018 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4019 if (!list_empty(&lrugen->lists[gen][type][zone]))
4020 goto next;
4021 }
4022
4023 min_seq[type]++;
4024 }
4025next:
4026 ;
4027 }
4028
4029 /* see the comment on lru_gen_struct */
4030 if (can_swap) {
4031 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4032 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4033 }
4034
4035 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4036 if (min_seq[type] == lrugen->min_seq[type])
4037 continue;
4038
4039 reset_ctrl_pos(lruvec, type, true);
4040 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4041 success = true;
4042 }
4043
4044 return success;
4045}
4046
Yu Zhao5280d762022-01-27 19:23:01 -07004047static void inc_max_seq(struct lruvec *lruvec)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004048{
4049 int prev, next;
4050 int type, zone;
4051 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4052
4053 spin_lock_irq(&lruvec->lru_lock);
4054
4055 VM_BUG_ON(!seq_is_valid(lruvec));
4056
Yu Zhaoa1537a62022-01-27 20:32:37 -07004057 inc_min_seq(lruvec);
4058
4059 /*
4060 * Update the active/inactive LRU sizes for compatibility. Both sides of
4061 * the current max_seq need to be covered, since max_seq+1 can overlap
4062 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4063 * overlap, cold/hot inversion happens. This can be solved by moving
4064 * pages from min_seq to min_seq+1 but is omitted for simplicity.
4065 */
4066 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4067 next = lru_gen_from_seq(lrugen->max_seq + 1);
4068
4069 for (type = 0; type < ANON_AND_FILE; type++) {
4070 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4071 enum lru_list lru = type * LRU_INACTIVE_FILE;
4072 long delta = lrugen->nr_pages[prev][type][zone] -
4073 lrugen->nr_pages[next][type][zone];
4074
4075 if (!delta)
4076 continue;
4077
4078 __update_lru_size(lruvec, lru, zone, delta);
4079 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4080 }
4081 }
4082
4083 for (type = 0; type < ANON_AND_FILE; type++)
4084 reset_ctrl_pos(lruvec, type, false);
4085
4086 /* make sure preceding modifications appear */
4087 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao5280d762022-01-27 19:23:01 -07004088
Yu Zhaoa1537a62022-01-27 20:32:37 -07004089 spin_unlock_irq(&lruvec->lru_lock);
4090}
4091
Yu Zhao5280d762022-01-27 19:23:01 -07004092static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4093 struct scan_control *sc, bool can_swap, bool full_scan)
4094{
4095 bool success;
4096 struct lru_gen_mm_walk *walk;
4097 struct mm_struct *mm = NULL;
4098 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4099
4100 VM_BUG_ON(max_seq > READ_ONCE(lrugen->max_seq));
4101
4102 /*
4103 * If the hardware doesn't automatically set the accessed bit, fallback
4104 * to lru_gen_look_around(), which only clears the accessed bit in a
4105 * handful of PTEs. Spreading the work out over a period of time usually
4106 * is less efficient, but it avoids bursty page faults.
4107 */
4108 if (!full_scan && !arch_has_hw_pte_young()) {
4109 success = iterate_mm_list_nowalk(lruvec, max_seq);
4110 goto done;
4111 }
4112
4113 walk = alloc_mm_walk();
4114 if (!walk) {
4115 success = iterate_mm_list_nowalk(lruvec, max_seq);
4116 goto done;
4117 }
4118
4119 walk->lruvec = lruvec;
4120 walk->max_seq = max_seq;
4121 walk->can_swap = can_swap;
4122 walk->full_scan = full_scan;
4123
4124 do {
4125 success = iterate_mm_list(lruvec, walk, &mm);
4126 if (mm)
4127 walk_mm(lruvec, mm, walk);
4128
4129 cond_resched();
4130 } while (mm);
4131
4132 free_mm_walk(walk);
4133done:
4134 if (!success) {
4135 if (!current_is_kswapd() && !sc->priority)
4136 wait_event_killable(lruvec->mm_state.wait,
4137 max_seq < READ_ONCE(lrugen->max_seq));
4138
4139 return max_seq < READ_ONCE(lrugen->max_seq);
4140 }
4141
4142 VM_BUG_ON(max_seq != READ_ONCE(lrugen->max_seq));
4143
4144 inc_max_seq(lruvec);
4145 /* either this sees any waiters or they will see updated max_seq */
4146 if (wq_has_sleeper(&lruvec->mm_state.wait))
4147 wake_up_all(&lruvec->mm_state.wait);
4148
4149 wakeup_flusher_threads(WB_REASON_VMSCAN);
4150
4151 return true;
4152}
4153
Yu Zhaoa1537a62022-01-27 20:32:37 -07004154static long get_nr_evictable(struct lruvec *lruvec, unsigned long max_seq,
4155 unsigned long *min_seq, bool can_swap, bool *need_aging)
4156{
4157 int gen, type, zone;
4158 long old = 0;
4159 long young = 0;
4160 long total = 0;
4161 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4162
4163 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4164 unsigned long seq;
4165
4166 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4167 long size = 0;
4168
4169 gen = lru_gen_from_seq(seq);
4170
4171 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4172 size += READ_ONCE(lrugen->nr_pages[gen][type][zone]);
4173
4174 total += size;
4175 if (seq == max_seq)
4176 young += size;
4177 if (seq + MIN_NR_GENS == max_seq)
4178 old += size;
4179 }
4180 }
4181
4182 /*
4183 * The aging and the eviction is a typical producer-consumer model. The
4184 * aging tries to be lazy to reduce the unnecessary overhead. On the
4185 * other hand, the eviction stalls when the number of generations
4186 * reaches MIN_NR_GENS. So ideally, there should be MIN_NR_GENS+1
4187 * generations, hence the first two if's.
4188 *
4189 * In addition, it's ideal to spread pages out evenly, meaning
4190 * 1/(MIN_NR_GENS+1) of the total number of pages for each generation. A
4191 * reasonable range for this average portion would [1/MIN_NR_GENS,
4192 * 1/(MIN_NR_GENS+2)]. From the consumer's POV, the eviction only cares
4193 * about the lower bound of cold pages, i.e., 1/(MIN_NR_GENS+2), whereas
4194 * from the producer's POV, the aging only cares about the upper bound
4195 * of hot pages, i.e., 1/MIN_NR_GENS.
4196 */
4197 if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS > max_seq)
4198 *need_aging = true;
4199 else if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS < max_seq)
4200 *need_aging = false;
4201 else if (young * MIN_NR_GENS > total)
4202 *need_aging = true;
4203 else if (old * (MIN_NR_GENS + 2) < total)
4204 *need_aging = true;
4205 else
4206 *need_aging = false;
4207
4208 return total > 0 ? total : 0;
4209}
4210
4211static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4212{
4213 bool need_aging;
4214 long nr_to_scan;
4215 int swappiness = get_swappiness(lruvec, sc);
4216 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4217 DEFINE_MAX_SEQ(lruvec);
4218 DEFINE_MIN_SEQ(lruvec);
4219
4220 mem_cgroup_calculate_protection(NULL, memcg);
4221
4222 if (mem_cgroup_below_min(memcg))
4223 return;
4224
4225 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, swappiness, &need_aging);
4226 if (!nr_to_scan)
4227 return;
4228
4229 nr_to_scan >>= sc->priority;
4230
4231 if (!mem_cgroup_online(memcg))
4232 nr_to_scan++;
4233
4234 if (nr_to_scan && need_aging && (!mem_cgroup_below_low(memcg) || sc->memcg_low_reclaim))
Yu Zhao5280d762022-01-27 19:23:01 -07004235 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004236}
4237
4238static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4239{
4240 struct mem_cgroup *memcg;
4241
4242 VM_BUG_ON(!current_is_kswapd());
4243
Yu Zhao4d905e92022-01-27 19:59:54 -07004244 /*
4245 * To reduce the chance of going into the aging path or swapping, which
4246 * can be costly, optimistically skip them unless their corresponding
4247 * flags were cleared in the eviction path. This improves the overall
4248 * performance when multiple memcgs are available.
4249 */
4250 if (!sc->memcgs_need_aging) {
4251 sc->memcgs_need_aging = true;
4252 sc->memcgs_avoid_swapping = !sc->memcgs_need_swapping;
4253 sc->memcgs_need_swapping = true;
4254 return;
4255 }
4256
4257 sc->memcgs_need_swapping = true;
4258 sc->memcgs_avoid_swapping = true;
4259
Yu Zhao5280d762022-01-27 19:23:01 -07004260 current->reclaim_state->mm_walk = &pgdat->mm_walk;
4261
Yu Zhaoa1537a62022-01-27 20:32:37 -07004262 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4263 do {
4264 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4265
4266 age_lruvec(lruvec, sc);
4267
4268 cond_resched();
4269 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao5280d762022-01-27 19:23:01 -07004270
4271 current->reclaim_state->mm_walk = NULL;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004272}
4273
Yu Zhaoafd94c92022-01-27 20:43:22 -07004274/*
4275 * This function exploits spatial locality when shrink_page_list() walks the
4276 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages.
Yu Zhao5280d762022-01-27 19:23:01 -07004277 * If the scan was done cacheline efficiently, it adds the PMD entry pointing
4278 * to the PTE table to the Bloom filter. This process is a feedback loop from
4279 * the eviction to the aging.
Yu Zhaoafd94c92022-01-27 20:43:22 -07004280 */
4281void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4282{
4283 int i;
4284 pte_t *pte;
4285 unsigned long start;
4286 unsigned long end;
4287 unsigned long addr;
4288 struct page *page;
Yu Zhao5280d762022-01-27 19:23:01 -07004289 struct lru_gen_mm_walk *walk;
4290 int young = 0;
Yu Zhaoafd94c92022-01-27 20:43:22 -07004291 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4292 struct mem_cgroup *memcg = page_memcg(pvmw->page);
4293 struct pglist_data *pgdat = page_pgdat(pvmw->page);
4294 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4295 DEFINE_MAX_SEQ(lruvec);
4296 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4297
4298 lockdep_assert_held(pvmw->ptl);
4299 VM_BUG_ON_PAGE(PageLRU(pvmw->page), pvmw->page);
4300
4301 if (spin_is_contended(pvmw->ptl))
4302 return;
4303
4304 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4305 end = pmd_addr_end(pvmw->address, pvmw->vma->vm_end);
4306
4307 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4308 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4309 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4310 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4311 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4312 else {
4313 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4314 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4315 }
4316 }
4317
4318 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4319
4320 rcu_read_lock();
4321 arch_enter_lazy_mmu_mode();
4322
4323 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4324 unsigned long pfn = pte_pfn(pte[i]);
4325
4326 VM_BUG_ON(addr < pvmw->vma->vm_start || addr >= pvmw->vma->vm_end);
4327
4328 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
4329 continue;
4330
4331 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
4332 continue;
4333
4334 if (!pte_young(pte[i]))
4335 continue;
4336
4337 VM_BUG_ON(!pfn_valid(pfn));
4338 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
4339 continue;
4340
4341 page = compound_head(pfn_to_page(pfn));
4342 if (page_to_nid(page) != pgdat->node_id)
4343 continue;
4344
4345 if (page_memcg_rcu(page) != memcg)
4346 continue;
4347
4348 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4349 continue;
4350
Yu Zhao5280d762022-01-27 19:23:01 -07004351 young++;
4352
Yu Zhaoafd94c92022-01-27 20:43:22 -07004353 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4354 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
4355 set_page_dirty(page);
4356
4357 old_gen = page_lru_gen(page);
4358 if (old_gen < 0)
4359 SetPageReferenced(page);
4360 else if (old_gen != new_gen)
4361 __set_bit(i, bitmap);
4362 }
4363
4364 arch_leave_lazy_mmu_mode();
4365 rcu_read_unlock();
4366
Yu Zhao5280d762022-01-27 19:23:01 -07004367 /* feedback from rmap walkers to page table walkers */
4368 if (suitable_to_scan(i, young))
4369 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4370
4371 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4372
4373 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhaoafd94c92022-01-27 20:43:22 -07004374 for_each_set_bit(i, bitmap, MIN_LRU_BATCH)
4375 activate_page(pte_page(pte[i]));
4376 return;
4377 }
4378
4379 /* page_update_gen() requires stable page_memcg() */
4380 if (!mem_cgroup_trylock_pages(memcg))
4381 return;
4382
Yu Zhao5280d762022-01-27 19:23:01 -07004383 if (!walk) {
4384 spin_lock_irq(&lruvec->lru_lock);
4385 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4386 }
Yu Zhaoafd94c92022-01-27 20:43:22 -07004387
4388 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4389 page = compound_head(pte_page(pte[i]));
4390 if (page_memcg_rcu(page) != memcg)
4391 continue;
4392
4393 old_gen = page_update_gen(page, new_gen);
4394 if (old_gen < 0 || old_gen == new_gen)
4395 continue;
4396
Yu Zhao5280d762022-01-27 19:23:01 -07004397 if (walk)
4398 update_batch_size(walk, page, old_gen, new_gen);
4399 else
4400 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhaoafd94c92022-01-27 20:43:22 -07004401 }
4402
Yu Zhao5280d762022-01-27 19:23:01 -07004403 if (!walk)
4404 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhaoafd94c92022-01-27 20:43:22 -07004405
4406 mem_cgroup_unlock_pages();
4407}
4408
Yu Zhaoa1537a62022-01-27 20:32:37 -07004409/******************************************************************************
4410 * the eviction
4411 ******************************************************************************/
4412
4413static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4414{
4415 bool success;
4416 int gen = page_lru_gen(page);
4417 int type = page_is_file_lru(page);
4418 int zone = page_zonenum(page);
4419 int tier = page_lru_tier(page);
4420 int delta = thp_nr_pages(page);
4421 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4422
4423 VM_BUG_ON_PAGE(gen >= MAX_NR_GENS, page);
4424
4425 if (!page_evictable(page)) {
4426 success = lru_gen_del_page(lruvec, page, true);
4427 VM_BUG_ON_PAGE(!success, page);
4428 SetPageUnevictable(page);
4429 add_page_to_lru_list(page, lruvec);
4430 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4431 return true;
4432 }
4433
4434 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4435 success = lru_gen_del_page(lruvec, page, true);
4436 VM_BUG_ON_PAGE(!success, page);
4437 SetPageSwapBacked(page);
4438 add_page_to_lru_list_tail(page, lruvec);
4439 return true;
4440 }
4441
Yu Zhaoafd94c92022-01-27 20:43:22 -07004442 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4443 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4444 return true;
4445 }
4446
Yu Zhaoa1537a62022-01-27 20:32:37 -07004447 if (tier > tier_idx) {
4448 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4449
4450 gen = page_inc_gen(lruvec, page, false);
4451 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4452
4453 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4454 lrugen->protected[hist][type][tier - 1] + delta);
4455 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4456 return true;
4457 }
4458
4459 if (PageLocked(page) || PageWriteback(page) ||
4460 (type == LRU_GEN_FILE && PageDirty(page))) {
4461 gen = page_inc_gen(lruvec, page, true);
4462 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4463 return true;
4464 }
4465
4466 return false;
4467}
4468
4469static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4470{
4471 bool success;
4472
4473 if (!sc->may_unmap && page_mapped(page))
4474 return false;
4475
4476 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4477 (PageDirty(page) || (PageAnon(page) && !PageSwapCache(page))))
4478 return false;
4479
4480 if (!get_page_unless_zero(page))
4481 return false;
4482
4483 if (!TestClearPageLRU(page)) {
4484 put_page(page);
4485 return false;
4486 }
4487
4488 success = lru_gen_del_page(lruvec, page, true);
4489 VM_BUG_ON_PAGE(!success, page);
4490
4491 return true;
4492}
4493
4494static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4495 int type, int tier, struct list_head *list)
4496{
4497 int gen, zone;
4498 enum vm_event_item item;
4499 int sorted = 0;
4500 int scanned = 0;
4501 int isolated = 0;
4502 int remaining = MAX_LRU_BATCH;
4503 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4504 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4505
4506 VM_BUG_ON(!list_empty(list));
4507
4508 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4509 return 0;
4510
4511 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4512
4513 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4514 LIST_HEAD(moved);
4515 int skipped = 0;
4516 struct list_head *head = &lrugen->lists[gen][type][zone];
4517
4518 while (!list_empty(head)) {
4519 struct page *page = lru_to_page(head);
4520 int delta = thp_nr_pages(page);
4521
4522 VM_BUG_ON_PAGE(PageTail(page), page);
4523 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4524 VM_BUG_ON_PAGE(PageActive(page), page);
4525 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4526 VM_BUG_ON_PAGE(page_zonenum(page) != zone, page);
4527
4528 prefetchw_prev_lru_page(page, head, flags);
4529
4530 scanned += delta;
4531
4532 if (sort_page(lruvec, page, tier))
4533 sorted += delta;
4534 else if (isolate_page(lruvec, page, sc)) {
4535 list_add(&page->lru, list);
4536 isolated += delta;
4537 } else {
4538 list_move(&page->lru, &moved);
4539 skipped += delta;
4540 }
4541
4542 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4543 break;
4544 }
4545
4546 if (skipped) {
4547 list_splice(&moved, head);
4548 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4549 }
4550
4551 if (!remaining || isolated >= MIN_LRU_BATCH)
4552 break;
4553 }
4554
4555 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4556 if (!cgroup_reclaim(sc)) {
4557 __count_vm_events(item, isolated);
4558 __count_vm_events(PGREFILL, sorted);
4559 }
4560 __count_memcg_events(memcg, item, isolated);
4561 __count_memcg_events(memcg, PGREFILL, sorted);
4562 __count_vm_events(PGSCAN_ANON + type, isolated);
4563
4564 /*
4565 * There might not be eligible pages due to reclaim_idx, may_unmap and
4566 * may_writepage. Check the remaining to prevent livelock if there is no
4567 * progress.
4568 */
4569 return isolated || !remaining ? scanned : 0;
4570}
4571
4572static int get_tier_idx(struct lruvec *lruvec, int type)
4573{
4574 int tier;
4575 struct ctrl_pos sp, pv;
4576
4577 /*
4578 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4579 * This value is chosen because any other tier would have at least twice
4580 * as many refaults as the first tier.
4581 */
4582 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4583 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4584 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4585 if (!positive_ctrl_err(&sp, &pv))
4586 break;
4587 }
4588
4589 return tier - 1;
4590}
4591
4592static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4593{
4594 int type, tier;
4595 struct ctrl_pos sp, pv;
4596 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4597
4598 /*
4599 * Compare the first tier of anon with that of file to determine which
4600 * type to scan. Also need to compare other tiers of the selected type
4601 * with the first tier of the other type to determine the last tier (of
4602 * the selected type) to evict.
4603 */
4604 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4605 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4606 type = positive_ctrl_err(&sp, &pv);
4607
4608 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4609 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4610 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4611 if (!positive_ctrl_err(&sp, &pv))
4612 break;
4613 }
4614
4615 *tier_idx = tier - 1;
4616
4617 return type;
4618}
4619
4620static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4621 int *type_scanned, struct list_head *list)
4622{
4623 int i;
4624 int type;
4625 int scanned;
4626 int tier = -1;
4627 DEFINE_MIN_SEQ(lruvec);
4628
4629 VM_BUG_ON(!seq_is_valid(lruvec));
4630
4631 /*
4632 * Try to make the obvious choice first. When anon and file are both
4633 * available from the same generation, interpret swappiness 1 as file
4634 * first and 200 as anon first.
4635 */
4636 if (!swappiness)
4637 type = LRU_GEN_FILE;
4638 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4639 type = LRU_GEN_ANON;
4640 else if (swappiness == 1)
4641 type = LRU_GEN_FILE;
4642 else if (swappiness == 200)
4643 type = LRU_GEN_ANON;
4644 else
4645 type = get_type_to_scan(lruvec, swappiness, &tier);
4646
4647 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4648 if (tier < 0)
4649 tier = get_tier_idx(lruvec, type);
4650
4651 scanned = scan_pages(lruvec, sc, type, tier, list);
4652 if (scanned)
4653 break;
4654
4655 type = !type;
4656 tier = -1;
4657 }
4658
4659 *type_scanned = type;
4660
4661 return scanned;
4662}
4663
Yu Zhao4d905e92022-01-27 19:59:54 -07004664static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4665 bool *swapped)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004666{
4667 int type;
4668 int scanned;
4669 int reclaimed;
4670 LIST_HEAD(list);
4671 struct page *page;
4672 enum vm_event_item item;
4673 struct reclaim_stat stat;
Yu Zhao5280d762022-01-27 19:23:01 -07004674 struct lru_gen_mm_walk *walk;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004675 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4676 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4677
4678 spin_lock_irq(&lruvec->lru_lock);
4679
4680 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4681
4682 if (try_to_inc_min_seq(lruvec, swappiness))
4683 scanned++;
4684
4685 if (get_nr_gens(lruvec, LRU_GEN_FILE) == MIN_NR_GENS)
4686 scanned = 0;
4687
4688 spin_unlock_irq(&lruvec->lru_lock);
4689
4690 if (list_empty(&list))
4691 return scanned;
4692
4693 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4694
4695 /*
4696 * To avoid livelock, don't add rejected pages back to the same lists
4697 * they were isolated from. See lru_gen_add_page().
4698 */
4699 list_for_each_entry(page, &list, lru) {
4700 ClearPageReferenced(page);
4701 ClearPageWorkingset(page);
4702
4703 if (PageReclaim(page) && (PageDirty(page) || PageWriteback(page)))
4704 ClearPageActive(page);
4705 else if (page_is_file_lru(page) || PageSwapCache(page))
4706 SetPageActive(page);
4707 }
4708
4709 spin_lock_irq(&lruvec->lru_lock);
4710
4711 move_pages_to_lru(lruvec, &list);
4712
Yu Zhao5280d762022-01-27 19:23:01 -07004713 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4714 if (walk && walk->batched)
4715 reset_batch_size(lruvec, walk);
4716
Yu Zhaoa1537a62022-01-27 20:32:37 -07004717 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4718 if (!cgroup_reclaim(sc))
4719 __count_vm_events(item, reclaimed);
4720 __count_memcg_events(memcg, item, reclaimed);
4721 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4722
4723 spin_unlock_irq(&lruvec->lru_lock);
4724
4725 mem_cgroup_uncharge_list(&list);
4726 free_unref_page_list(&list);
4727
4728 sc->nr_reclaimed += reclaimed;
4729
Yu Zhao4d905e92022-01-27 19:59:54 -07004730 if (type == LRU_GEN_ANON && swapped)
4731 *swapped = true;
4732
Yu Zhaoa1537a62022-01-27 20:32:37 -07004733 return scanned;
4734}
4735
4736static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
4737{
4738 bool need_aging;
4739 long nr_to_scan;
4740 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4741 DEFINE_MAX_SEQ(lruvec);
4742 DEFINE_MIN_SEQ(lruvec);
4743
4744 if (mem_cgroup_below_min(memcg) ||
4745 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4746 return 0;
4747
4748 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, can_swap, &need_aging);
4749 if (!nr_to_scan)
4750 return 0;
4751
4752 /* reset the priority if the target has been met */
4753 nr_to_scan >>= sc->nr_reclaimed < sc->nr_to_reclaim ? sc->priority : DEF_PRIORITY;
4754
4755 if (!mem_cgroup_online(memcg))
4756 nr_to_scan++;
4757
4758 if (!nr_to_scan)
4759 return 0;
4760
Yu Zhao4d905e92022-01-27 19:59:54 -07004761 if (!need_aging) {
4762 sc->memcgs_need_aging = false;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004763 return nr_to_scan;
Yu Zhao4d905e92022-01-27 19:59:54 -07004764 }
Yu Zhaoa1537a62022-01-27 20:32:37 -07004765
4766 /* leave the work to lru_gen_age_node() */
4767 if (current_is_kswapd())
4768 return 0;
4769
4770 /* try other memcgs before going to the aging path */
4771 if (!cgroup_reclaim(sc) && !sc->force_deactivate) {
4772 sc->skipped_deactivate = true;
4773 return 0;
4774 }
4775
Yu Zhao5280d762022-01-27 19:23:01 -07004776 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
4777 return nr_to_scan;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004778
Yu Zhao5280d762022-01-27 19:23:01 -07004779 return min_seq[LRU_GEN_FILE] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004780}
4781
4782static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4783{
4784 struct blk_plug plug;
4785 long scanned = 0;
Yu Zhao4d905e92022-01-27 19:59:54 -07004786 bool swapped = false;
4787 unsigned long reclaimed = sc->nr_reclaimed;
Yu Zhao5280d762022-01-27 19:23:01 -07004788 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004789
4790 lru_add_drain();
4791
4792 blk_start_plug(&plug);
4793
Yu Zhao5280d762022-01-27 19:23:01 -07004794 if (current_is_kswapd())
4795 current->reclaim_state->mm_walk = &pgdat->mm_walk;
4796
Yu Zhaoa1537a62022-01-27 20:32:37 -07004797 while (true) {
4798 int delta;
4799 int swappiness;
4800 long nr_to_scan;
4801
4802 if (sc->may_swap)
4803 swappiness = get_swappiness(lruvec, sc);
4804 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4805 swappiness = 1;
4806 else
4807 swappiness = 0;
4808
4809 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
4810 if (!nr_to_scan)
4811 break;
4812
Yu Zhao4d905e92022-01-27 19:59:54 -07004813 delta = evict_pages(lruvec, sc, swappiness, &swapped);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004814 if (!delta)
4815 break;
4816
Yu Zhao4d905e92022-01-27 19:59:54 -07004817 if (sc->memcgs_avoid_swapping && swappiness < 200 && swapped)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004818 break;
4819
Yu Zhao4d905e92022-01-27 19:59:54 -07004820 scanned += delta;
4821 if (scanned >= nr_to_scan) {
4822 if (!swapped && sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH)
4823 sc->memcgs_need_swapping = false;
4824 break;
4825 }
4826
Yu Zhaoa1537a62022-01-27 20:32:37 -07004827 cond_resched();
4828 }
4829
Yu Zhao5280d762022-01-27 19:23:01 -07004830 if (current_is_kswapd())
4831 current->reclaim_state->mm_walk = NULL;
4832
Yu Zhaoa1537a62022-01-27 20:32:37 -07004833 blk_finish_plug(&plug);
4834}
4835
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004836/******************************************************************************
4837 * initialization
4838 ******************************************************************************/
4839
4840void lru_gen_init_lruvec(struct lruvec *lruvec)
4841{
4842 int gen, type, zone;
4843 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4844
4845 lrugen->max_seq = MIN_NR_GENS + 1;
4846
4847 for_each_gen_type_zone(gen, type, zone)
4848 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao5280d762022-01-27 19:23:01 -07004849
4850 lruvec->mm_state.seq = MIN_NR_GENS;
4851 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004852}
4853
4854#ifdef CONFIG_MEMCG
4855void lru_gen_init_memcg(struct mem_cgroup *memcg)
4856{
Yu Zhao5280d762022-01-27 19:23:01 -07004857 INIT_LIST_HEAD(&memcg->mm_list.fifo);
4858 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004859}
4860
4861void lru_gen_exit_memcg(struct mem_cgroup *memcg)
4862{
Yu Zhao5280d762022-01-27 19:23:01 -07004863 int i;
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004864 int nid;
4865
4866 for_each_node(nid) {
4867 struct lruvec *lruvec = get_lruvec(memcg, nid);
4868
4869 VM_BUG_ON(memchr_inv(lruvec->lrugen.nr_pages, 0,
4870 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao5280d762022-01-27 19:23:01 -07004871
4872 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
4873 bitmap_free(lruvec->mm_state.filters[i]);
4874 lruvec->mm_state.filters[i] = NULL;
4875 }
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004876 }
4877}
4878#endif
4879
4880static int __init init_lru_gen(void)
4881{
4882 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
4883 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
Yu Zhao5280d762022-01-27 19:23:01 -07004884 BUILD_BUG_ON(sizeof(MM_STAT_CODES) != NR_MM_STATS + 1);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004885
4886 return 0;
4887};
4888late_initcall(init_lru_gen);
4889
Yu Zhaoa1537a62022-01-27 20:32:37 -07004890#else
4891
4892static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4893{
4894}
4895
4896static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4897{
4898}
4899
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004900#endif /* CONFIG_LRU_GEN */
4901
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004902static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004903{
4904 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07004905 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004906 unsigned long nr_to_scan;
4907 enum lru_list lru;
4908 unsigned long nr_reclaimed = 0;
4909 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
4910 struct blk_plug plug;
Mel Gorman1a501902014-06-04 16:10:49 -07004911 bool scan_adjusted;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004912
Yu Zhaoa1537a62022-01-27 20:32:37 -07004913 if (lru_gen_enabled()) {
4914 lru_gen_shrink_lruvec(lruvec, sc);
4915 return;
4916 }
4917
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004918 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004919
Mel Gormane82e0562013-07-03 15:01:44 -07004920 /* Record the original scan target for proportional adjustments later */
4921 memcpy(targets, nr, sizeof(nr));
4922
Mel Gorman1a501902014-06-04 16:10:49 -07004923 /*
4924 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
4925 * event that can occur when there is little memory pressure e.g.
4926 * multiple streaming readers/writers. Hence, we do not abort scanning
4927 * when the requested number of pages are reclaimed when scanning at
4928 * DEF_PRIORITY on the assumption that the fact we are direct
4929 * reclaiming implies that kswapd is not keeping up and it is best to
4930 * do a batch of work at once. For memcg reclaim one check is made to
4931 * abort proportional reclaim if either the file or anon lru has already
4932 * dropped to zero at the first pass.
4933 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08004934 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
Mel Gorman1a501902014-06-04 16:10:49 -07004935 sc->priority == DEF_PRIORITY);
4936
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004937 blk_start_plug(&plug);
4938 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
4939 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07004940 unsigned long nr_anon, nr_file, percentage;
4941 unsigned long nr_scanned;
4942
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004943 for_each_evictable_lru(lru) {
4944 if (nr[lru]) {
4945 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
4946 nr[lru] -= nr_to_scan;
4947
4948 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07004949 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004950 }
4951 }
Mel Gormane82e0562013-07-03 15:01:44 -07004952
Michal Hockobd041732016-12-02 17:26:48 -08004953 cond_resched();
4954
Mel Gormane82e0562013-07-03 15:01:44 -07004955 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
4956 continue;
4957
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004958 /*
Mel Gormane82e0562013-07-03 15:01:44 -07004959 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07004960 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07004961 * proportionally what was requested by get_scan_count(). We
4962 * stop reclaiming one LRU and reduce the amount scanning
4963 * proportional to the original scan target.
4964 */
4965 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
4966 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
4967
Mel Gorman1a501902014-06-04 16:10:49 -07004968 /*
4969 * It's just vindictive to attack the larger once the smaller
4970 * has gone to zero. And given the way we stop scanning the
4971 * smaller below, this makes sure that we only make one nudge
4972 * towards proportionality once we've got nr_to_reclaim.
4973 */
4974 if (!nr_file || !nr_anon)
4975 break;
4976
Mel Gormane82e0562013-07-03 15:01:44 -07004977 if (nr_file > nr_anon) {
4978 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
4979 targets[LRU_ACTIVE_ANON] + 1;
4980 lru = LRU_BASE;
4981 percentage = nr_anon * 100 / scan_target;
4982 } else {
4983 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
4984 targets[LRU_ACTIVE_FILE] + 1;
4985 lru = LRU_FILE;
4986 percentage = nr_file * 100 / scan_target;
4987 }
4988
4989 /* Stop scanning the smaller of the LRU */
4990 nr[lru] = 0;
4991 nr[lru + LRU_ACTIVE] = 0;
4992
4993 /*
4994 * Recalculate the other LRU scan count based on its original
4995 * scan target and the percentage scanning already complete
4996 */
4997 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
4998 nr_scanned = targets[lru] - nr[lru];
4999 nr[lru] = targets[lru] * (100 - percentage) / 100;
5000 nr[lru] -= min(nr[lru], nr_scanned);
5001
5002 lru += LRU_ACTIVE;
5003 nr_scanned = targets[lru] - nr[lru];
5004 nr[lru] = targets[lru] * (100 - percentage) / 100;
5005 nr[lru] -= min(nr[lru], nr_scanned);
5006
5007 scan_adjusted = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005008 }
5009 blk_finish_plug(&plug);
5010 sc->nr_reclaimed += nr_reclaimed;
5011
5012 /*
5013 * Even if we did not try to evict anon pages at all, we want to
5014 * rebalance the anon lru active/inactive ratio.
5015 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005016 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5017 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005018 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5019 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005020}
5021
Mel Gorman23b9da52012-05-29 15:06:20 -07005022/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005023static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005024{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005025 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005026 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005027 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005028 return true;
5029
5030 return false;
5031}
5032
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005033/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005034 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5035 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5036 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005037 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005038 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005039 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005040static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005041 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005042 struct scan_control *sc)
5043{
5044 unsigned long pages_for_compaction;
5045 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005046 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005047
5048 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005049 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005050 return false;
5051
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005052 /*
5053 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5054 * number of pages that were scanned. This will return to the caller
5055 * with the risk reclaim/compaction and the resulting allocation attempt
5056 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5057 * allocations through requiring that the full LRU list has been scanned
5058 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5059 * scan, but that approximation was wrong, and there were corner cases
5060 * where always a non-zero amount of pages were scanned.
5061 */
5062 if (!nr_reclaimed)
5063 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005064
Mel Gorman3e7d3442011-01-13 15:45:56 -08005065 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005066 for (z = 0; z <= sc->reclaim_idx; z++) {
5067 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005068 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005069 continue;
5070
5071 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005072 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005073 case COMPACT_CONTINUE:
5074 return false;
5075 default:
5076 /* check next zone */
5077 ;
5078 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005079 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005080
5081 /*
5082 * If we have not reclaimed enough pages for compaction and the
5083 * inactive lists are large enough, continue reclaiming
5084 */
5085 pages_for_compaction = compact_gap(sc->order);
5086 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005087 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005088 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5089
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005090 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005091}
5092
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005093static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005094{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005095 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005096 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005097
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005098 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005099 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005100 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005101 unsigned long reclaimed;
5102 unsigned long scanned;
Johannes Weiner56600482012-01-12 17:17:59 -08005103
Xunlei Pange3336ca2020-09-04 16:35:27 -07005104 /*
5105 * This loop can become CPU-bound when target memcgs
5106 * aren't eligible for reclaim - either because they
5107 * don't have any reclaimable pages, or because their
5108 * memory is explicitly protected. Avoid soft lockups.
5109 */
5110 cond_resched();
5111
Chris Down45c7f7e2020-08-06 23:22:05 -07005112 mem_cgroup_calculate_protection(target_memcg, memcg);
5113
5114 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005115 /*
5116 * Hard protection.
5117 * If there is no reclaimable memory, OOM.
5118 */
5119 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005120 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005121 /*
5122 * Soft protection.
5123 * Respect the protection only as long as
5124 * there is an unprotected supply
5125 * of reclaimable memory from other cgroups.
5126 */
5127 if (!sc->memcg_low_reclaim) {
5128 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005129 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005130 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005131 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005132 }
5133
Johannes Weinerd2af3392019-11-30 17:55:43 -08005134 reclaimed = sc->nr_reclaimed;
5135 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005136
5137 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005138
Johannes Weinerd2af3392019-11-30 17:55:43 -08005139 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5140 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005141
Johannes Weinerd2af3392019-11-30 17:55:43 -08005142 /* Record the group's reclaim efficiency */
5143 vmpressure(sc->gfp_mask, memcg, false,
5144 sc->nr_scanned - scanned,
5145 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005146
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005147 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5148}
5149
Liu Song6c9e09072020-01-30 22:14:08 -08005150static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005151{
5152 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005153 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005154 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005155 bool reclaimable = false;
5156
Johannes Weiner1b051172019-11-30 17:55:52 -08005157 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5158
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005159again:
5160 memset(&sc->nr, 0, sizeof(sc->nr));
5161
5162 nr_reclaimed = sc->nr_reclaimed;
5163 nr_scanned = sc->nr_scanned;
5164
Yu Zhao3eb07702020-09-27 20:49:08 -06005165 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005166
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005167 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005168
Johannes Weinerd2af3392019-11-30 17:55:43 -08005169 if (reclaim_state) {
5170 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5171 reclaim_state->reclaimed_slab = 0;
5172 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005173
Johannes Weinerd2af3392019-11-30 17:55:43 -08005174 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005175 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005176 sc->nr_scanned - nr_scanned,
5177 sc->nr_reclaimed - nr_reclaimed);
5178
5179 if (sc->nr_reclaimed - nr_reclaimed)
5180 reclaimable = true;
5181
5182 if (current_is_kswapd()) {
5183 /*
5184 * If reclaim is isolating dirty pages under writeback,
5185 * it implies that the long-lived page allocation rate
5186 * is exceeding the page laundering rate. Either the
5187 * global limits are not being effective at throttling
5188 * processes due to the page distribution throughout
5189 * zones or there is heavy usage of a slow backing
5190 * device. The only option is to throttle from reclaim
5191 * context which is not ideal as there is no guarantee
5192 * the dirtying process is throttled in the same way
5193 * balance_dirty_pages() manages.
5194 *
5195 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5196 * count the number of pages under pages flagged for
5197 * immediate reclaim and stall if any are encountered
5198 * in the nr_immediate check below.
5199 */
5200 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5201 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005202
Johannes Weinerd2af3392019-11-30 17:55:43 -08005203 /* Allow kswapd to start writing pages during reclaim.*/
5204 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5205 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005206
5207 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005208 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005209 * reclaim and under writeback (nr_immediate), it
5210 * implies that pages are cycling through the LRU
5211 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005212 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005213 if (sc->nr.immediate)
5214 congestion_wait(BLK_RW_ASYNC, HZ/10);
5215 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005216
Johannes Weinerd2af3392019-11-30 17:55:43 -08005217 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005218 * Tag a node/memcg as congested if all the dirty pages
5219 * scanned were backed by a congested BDI and
5220 * wait_iff_congested will stall.
5221 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005222 * Legacy memcg will stall in page writeback so avoid forcibly
5223 * stalling in wait_iff_congested().
5224 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005225 if ((current_is_kswapd() ||
5226 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005227 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005228 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005229
5230 /*
5231 * Stall direct reclaim for IO completions if underlying BDIs
5232 * and node is congested. Allow kswapd to continue until it
5233 * starts encountering unqueued dirty pages or cycling through
5234 * the LRU too quickly.
5235 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005236 if (!current_is_kswapd() && current_may_throttle() &&
5237 !sc->hibernation_mode &&
5238 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005239 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5240
5241 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5242 sc))
5243 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005244
Johannes Weinerc73322d2017-05-03 14:51:51 -07005245 /*
5246 * Kswapd gives up on balancing particular nodes after too
5247 * many failures to reclaim anything from them and goes to
5248 * sleep. On reclaim progress, reset the failure counter. A
5249 * successful direct reclaim run will revive a dormant kswapd.
5250 */
5251 if (reclaimable)
5252 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005253}
5254
Vlastimil Babka53853e22014-10-09 15:27:02 -07005255/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005256 * Returns true if compaction should go ahead for a costly-order request, or
5257 * the allocation would already succeed without compaction. Return false if we
5258 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07005259 */
Mel Gorman4f588332016-07-28 15:46:38 -07005260static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005261{
Mel Gorman31483b62016-07-28 15:45:46 -07005262 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005263 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005264
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005265 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
5266 if (suitable == COMPACT_SUCCESS)
5267 /* Allocation should succeed already. Don't reclaim. */
5268 return true;
5269 if (suitable == COMPACT_SKIPPED)
5270 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005271 return false;
5272
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005273 /*
5274 * Compaction is already possible, but it takes time to run and there
5275 * are potentially other callers using the pages just freed. So proceed
5276 * with reclaim to make a buffer of free pages available to give
5277 * compaction a reasonable chance of completing and allocating the page.
5278 * Note that we won't actually reclaim the whole buffer in one attempt
5279 * as the target watermark in should_continue_reclaim() is lower. But if
5280 * we are already above the high+gap watermark, don't reclaim at all.
5281 */
5282 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
5283
5284 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005285}
5286
Linus Torvalds1da177e2005-04-16 15:20:36 -07005287/*
5288 * This is the direct reclaim path, for page-allocating processes. We only
5289 * try to reclaim pages from zones which will satisfy the caller's allocation
5290 * request.
5291 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07005292 * If a zone is deemed to be full of pinned pages then just give it a light
5293 * scan then give up on it.
5294 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07005295static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005296{
Mel Gormandd1a2392008-04-28 02:12:17 -07005297 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07005298 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07005299 unsigned long nr_soft_reclaimed;
5300 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07005301 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07005302 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005303
Mel Gormancc715d92012-03-21 16:34:00 -07005304 /*
5305 * If the number of buffer_heads in the machine exceeds the maximum
5306 * allowed level, force direct reclaim to scan the highmem zone as
5307 * highmem pages could be pinning lowmem pages storing buffer_heads
5308 */
Weijie Yang619d0d762014-04-07 15:36:59 -07005309 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07005310 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07005311 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07005312 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07005313 }
Mel Gormancc715d92012-03-21 16:34:00 -07005314
Mel Gormand4debc62010-08-09 17:19:29 -07005315 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07005316 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07005317 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005318 * Take care memory controller reclaiming has small influence
5319 * to global LRU.
5320 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005321 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04005322 if (!cpuset_zone_allowed(zone,
5323 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005324 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005325
Johannes Weiner0b064962014-08-06 16:06:12 -07005326 /*
5327 * If we already have plenty of memory free for
5328 * compaction in this zone, don't free any more.
5329 * Even though compaction is invoked for any
5330 * non-zero order, only frequent costly order
5331 * reclamation is disruptive enough to become a
5332 * noticeable problem, like transparent huge
5333 * page allocations.
5334 */
5335 if (IS_ENABLED(CONFIG_COMPACTION) &&
5336 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07005337 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07005338 sc->compaction_ready = true;
5339 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07005340 }
Johannes Weiner0b064962014-08-06 16:06:12 -07005341
Andrew Morton0608f432013-09-24 15:27:41 -07005342 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07005343 * Shrink each node in the zonelist once. If the
5344 * zonelist is ordered by zone (not the default) then a
5345 * node may be shrunk multiple times but in that case
5346 * the user prefers lower zones being preserved.
5347 */
5348 if (zone->zone_pgdat == last_pgdat)
5349 continue;
5350
5351 /*
Andrew Morton0608f432013-09-24 15:27:41 -07005352 * This steals pages from memory cgroups over softlimit
5353 * and returns the number of reclaimed pages and
5354 * scanned pages. This works for global memory pressure
5355 * and balancing, not for a memcg's limit.
5356 */
5357 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07005358 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07005359 sc->order, sc->gfp_mask,
5360 &nr_soft_scanned);
5361 sc->nr_reclaimed += nr_soft_reclaimed;
5362 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07005363 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005364 }
Nick Piggin408d8542006-09-25 23:31:27 -07005365
Mel Gorman79dafcd2016-07-28 15:45:53 -07005366 /* See comment about same check for global reclaim above */
5367 if (zone->zone_pgdat == last_pgdat)
5368 continue;
5369 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07005370 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005371 }
Mel Gormane0c23272011-10-31 17:09:33 -07005372
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005373 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07005374 * Restore to original mask to avoid the impact on the caller if we
5375 * promoted it to __GFP_HIGHMEM.
5376 */
5377 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005378}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005379
Johannes Weinerb9107182019-11-30 17:55:59 -08005380static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005381{
Johannes Weinerb9107182019-11-30 17:55:59 -08005382 struct lruvec *target_lruvec;
5383 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005384
Yu Zhaoa1537a62022-01-27 20:32:37 -07005385 if (lru_gen_enabled())
5386 return;
5387
Johannes Weinerb9107182019-11-30 17:55:59 -08005388 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07005389 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
5390 target_lruvec->refaults[0] = refaults;
5391 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
5392 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005393}
5394
Linus Torvalds1da177e2005-04-16 15:20:36 -07005395/*
5396 * This is the main entry point to direct page reclaim.
5397 *
5398 * If a full scan of the inactive list fails to free enough memory then we
5399 * are "out of memory" and something needs to be killed.
5400 *
5401 * If the caller is !__GFP_FS then the probability of a failure is reasonably
5402 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02005403 * caller can't do much about. We kick the writeback threads and take explicit
5404 * naps in the hope that some of these pages can be written. But if the
5405 * allocating task holds filesystem locks which prevent writeout this might not
5406 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07005407 *
5408 * returns: 0, if no pages reclaimed
5409 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07005410 */
Mel Gormandac1d272008-04-28 02:12:12 -07005411static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005412 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005413{
Johannes Weiner241994ed2015-02-11 15:26:06 -08005414 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005415 pg_data_t *last_pgdat;
5416 struct zoneref *z;
5417 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005418retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07005419 delayacct_freepages_start();
5420
Johannes Weinerb5ead352019-11-30 17:55:40 -08005421 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07005422 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005423
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005424 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005425 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
5426 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08005427 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07005428 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07005429
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005430 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07005431 break;
5432
5433 if (sc->compaction_ready)
5434 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005435
5436 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08005437 * If we're getting trouble reclaiming, start doing
5438 * writepage even in laptop mode.
5439 */
5440 if (sc->priority < DEF_PRIORITY - 2)
5441 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07005442 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005443
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005444 last_pgdat = NULL;
5445 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
5446 sc->nodemask) {
5447 if (zone->zone_pgdat == last_pgdat)
5448 continue;
5449 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08005450
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005451 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08005452
5453 if (cgroup_reclaim(sc)) {
5454 struct lruvec *lruvec;
5455
5456 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
5457 zone->zone_pgdat);
5458 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
5459 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005460 }
5461
Keika Kobayashi873b4772008-07-25 01:48:52 -07005462 delayacct_freepages_end();
5463
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005464 if (sc->nr_reclaimed)
5465 return sc->nr_reclaimed;
5466
Mel Gorman0cee34f2012-01-12 17:19:49 -08005467 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07005468 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08005469 return 1;
5470
Johannes Weinerb91ac372019-11-30 17:56:02 -08005471 /*
5472 * We make inactive:active ratio decisions based on the node's
5473 * composition of memory, but a restrictive reclaim_idx or a
5474 * memory.low cgroup setting can exempt large amounts of
5475 * memory from reclaim. Neither of which are very common, so
5476 * instead of doing costly eligibility calculations of the
5477 * entire cgroup subtree up front, we assume the estimates are
5478 * good, and retry with forcible deactivation if that fails.
5479 */
5480 if (sc->skipped_deactivate) {
5481 sc->priority = initial_priority;
5482 sc->force_deactivate = 1;
5483 sc->skipped_deactivate = 0;
5484 goto retry;
5485 }
5486
Johannes Weiner241994ed2015-02-11 15:26:06 -08005487 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07005488 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08005489 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08005490 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07005491 sc->memcg_low_reclaim = 1;
5492 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005493 goto retry;
5494 }
5495
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005496 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005497}
5498
Johannes Weinerc73322d2017-05-03 14:51:51 -07005499static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07005500{
5501 struct zone *zone;
5502 unsigned long pfmemalloc_reserve = 0;
5503 unsigned long free_pages = 0;
5504 int i;
5505 bool wmark_ok;
5506
Johannes Weinerc73322d2017-05-03 14:51:51 -07005507 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
5508 return true;
5509
Mel Gorman55150612012-07-31 16:44:35 -07005510 for (i = 0; i <= ZONE_NORMAL; i++) {
5511 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07005512 if (!managed_zone(zone))
5513 continue;
5514
5515 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07005516 continue;
5517
Mel Gorman55150612012-07-31 16:44:35 -07005518 pfmemalloc_reserve += min_wmark_pages(zone);
5519 free_pages += zone_page_state(zone, NR_FREE_PAGES);
5520 }
5521
Mel Gorman675becc2014-06-04 16:07:35 -07005522 /* If there are no reserves (unexpected config) then do not throttle */
5523 if (!pfmemalloc_reserve)
5524 return true;
5525
Mel Gorman55150612012-07-31 16:44:35 -07005526 wmark_ok = free_pages > pfmemalloc_reserve / 2;
5527
5528 /* kswapd must be awake if processes are being throttled */
5529 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005530 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
5531 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005532
Mel Gorman55150612012-07-31 16:44:35 -07005533 wake_up_interruptible(&pgdat->kswapd_wait);
5534 }
5535
5536 return wmark_ok;
5537}
5538
5539/*
5540 * Throttle direct reclaimers if backing storage is backed by the network
5541 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
5542 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08005543 * when the low watermark is reached.
5544 *
5545 * Returns true if a fatal signal was delivered during throttling. If this
5546 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07005547 */
Mel Gorman50694c22012-11-26 16:29:48 -08005548static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07005549 nodemask_t *nodemask)
5550{
Mel Gorman675becc2014-06-04 16:07:35 -07005551 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07005552 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07005553 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07005554
5555 /*
5556 * Kernel threads should not be throttled as they may be indirectly
5557 * responsible for cleaning pages necessary for reclaim to make forward
5558 * progress. kjournald for example may enter direct reclaim while
5559 * committing a transaction where throttling it could forcing other
5560 * processes to block on log_wait_commit().
5561 */
5562 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08005563 goto out;
5564
5565 /*
5566 * If a fatal signal is pending, this process should not throttle.
5567 * It should return quickly so it can exit and free its memory
5568 */
5569 if (fatal_signal_pending(current))
5570 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005571
Mel Gorman675becc2014-06-04 16:07:35 -07005572 /*
5573 * Check if the pfmemalloc reserves are ok by finding the first node
5574 * with a usable ZONE_NORMAL or lower zone. The expectation is that
5575 * GFP_KERNEL will be required for allocating network buffers when
5576 * swapping over the network so ZONE_HIGHMEM is unusable.
5577 *
5578 * Throttling is based on the first usable node and throttled processes
5579 * wait on a queue until kswapd makes progress and wakes them. There
5580 * is an affinity then between processes waking up and where reclaim
5581 * progress has been made assuming the process wakes on the same node.
5582 * More importantly, processes running on remote nodes will not compete
5583 * for remote pfmemalloc reserves and processes on different nodes
5584 * should make reasonable progress.
5585 */
5586 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08005587 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07005588 if (zone_idx(zone) > ZONE_NORMAL)
5589 continue;
5590
5591 /* Throttle based on the first usable node */
5592 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07005593 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07005594 goto out;
5595 break;
5596 }
5597
5598 /* If no zone was usable by the allocation flags then do not throttle */
5599 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08005600 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005601
Mel Gorman68243e72012-07-31 16:44:39 -07005602 /* Account for the throttling */
5603 count_vm_event(PGSCAN_DIRECT_THROTTLE);
5604
Mel Gorman55150612012-07-31 16:44:35 -07005605 /*
5606 * If the caller cannot enter the filesystem, it's possible that it
5607 * is due to the caller holding an FS lock or performing a journal
5608 * transaction in the case of a filesystem like ext[3|4]. In this case,
5609 * it is not safe to block on pfmemalloc_wait as kswapd could be
5610 * blocked waiting on the same lock. Instead, throttle for up to a
5611 * second before continuing.
5612 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07005613 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07005614 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07005615 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07005616 else
5617 /* Throttle until kswapd wakes the process */
5618 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
5619 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08005620
Mel Gorman50694c22012-11-26 16:29:48 -08005621 if (fatal_signal_pending(current))
5622 return true;
5623
5624out:
5625 return false;
Mel Gorman55150612012-07-31 16:44:35 -07005626}
5627
Mel Gormandac1d272008-04-28 02:12:12 -07005628unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07005629 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08005630{
Mel Gorman33906bc2010-08-09 17:19:16 -07005631 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005632 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08005633 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005634 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07005635 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07005636 .order = order,
5637 .nodemask = nodemask,
5638 .priority = DEF_PRIORITY,
5639 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005640 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07005641 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08005642 };
5643
Mel Gorman55150612012-07-31 16:44:35 -07005644 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07005645 * scan_control uses s8 fields for order, priority, and reclaim_idx.
5646 * Confirm they are large enough for max values.
5647 */
5648 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
5649 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
5650 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
5651
5652 /*
Mel Gorman50694c22012-11-26 16:29:48 -08005653 * Do not enter reclaim if fatal signal was delivered while throttled.
5654 * 1 is returned so that the page allocator does not OOM kill at this
5655 * point.
Mel Gorman55150612012-07-31 16:44:35 -07005656 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005657 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07005658 return 1;
5659
Andrew Morton1732d2b012019-07-16 16:26:15 -07005660 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005661 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07005662
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005663 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07005664
5665 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005666 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07005667
5668 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005669}
5670
Andrew Mortonc255a452012-07-31 16:43:02 -07005671#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08005672
Michal Hockod2e5fb92019-08-30 16:04:50 -07005673/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005674unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005675 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07005676 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07005677 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07005678{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005679 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07005680 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07005681 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07005682 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005683 .may_writepage = !laptop_mode,
5684 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07005685 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07005686 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07005687 };
Ying Han0ae5e892011-05-26 16:25:25 -07005688
Michal Hockod2e5fb92019-08-30 16:04:50 -07005689 WARN_ON_ONCE(!current->reclaim_state);
5690
Balbir Singh4e416952009-09-23 15:56:39 -07005691 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
5692 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005693
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005694 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07005695 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005696
Balbir Singh4e416952009-09-23 15:56:39 -07005697 /*
5698 * NOTE: Although we can get the priority field, using it
5699 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07005700 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07005701 * will pick up pages from other mem cgroup's as well. We hack
5702 * the priority and make it zero.
5703 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005704 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005705
5706 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
5707
Ying Han0ae5e892011-05-26 16:25:25 -07005708 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07005709
Balbir Singh4e416952009-09-23 15:56:39 -07005710 return sc.nr_reclaimed;
5711}
5712
Johannes Weiner72835c82012-01-12 17:18:32 -08005713unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005714 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08005715 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005716 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08005717{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005718 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07005719 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08005720 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005721 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07005722 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07005723 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07005724 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07005725 .target_mem_cgroup = memcg,
5726 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08005727 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005728 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005729 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07005730 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08005731 /*
5732 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
5733 * equal pressure on all the nodes. This is based on the assumption that
5734 * the reclaim does not bail out early.
5735 */
5736 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08005737
Andrew Morton1732d2b012019-07-16 16:26:15 -07005738 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005739 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07005740 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07005741
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005742 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07005743
Vlastimil Babka499118e2017-05-08 15:59:50 -07005744 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005745 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005746 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005747
5748 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005749}
5750#endif
5751
Mel Gorman1d82de62016-07-28 15:45:43 -07005752static void age_active_anon(struct pglist_data *pgdat,
Mel Gormanef8f2322016-07-28 15:46:05 -07005753 struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005754{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005755 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08005756 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005757
Yu Zhaoa1537a62022-01-27 20:32:37 -07005758 if (lru_gen_enabled()) {
5759 lru_gen_age_node(pgdat, sc);
5760 return;
5761 }
5762
Dave Hansen2f368a92021-09-02 14:59:23 -07005763 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005764 return;
5765
Johannes Weinerb91ac372019-11-30 17:56:02 -08005766 lruvec = mem_cgroup_lruvec(NULL, pgdat);
5767 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
5768 return;
5769
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005770 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5771 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08005772 lruvec = mem_cgroup_lruvec(memcg, pgdat);
5773 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5774 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005775 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5776 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08005777}
5778
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005779static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08005780{
5781 int i;
5782 struct zone *zone;
5783
5784 /*
5785 * Check for watermark boosts top-down as the higher zones
5786 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005787 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08005788 * start prematurely when there is no boosting and a lower
5789 * zone is balanced.
5790 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005791 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08005792 zone = pgdat->node_zones + i;
5793 if (!managed_zone(zone))
5794 continue;
5795
5796 if (zone->watermark_boost)
5797 return true;
5798 }
5799
5800 return false;
5801}
5802
Mel Gormane716f2e2017-05-03 14:53:45 -07005803/*
5804 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005805 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07005806 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005807static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08005808{
Mel Gormane716f2e2017-05-03 14:53:45 -07005809 int i;
5810 unsigned long mark = -1;
5811 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08005812
Mel Gorman1c308442018-12-28 00:35:52 -08005813 /*
5814 * Check watermarks bottom-up as lower zones are more likely to
5815 * meet watermarks.
5816 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005817 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07005818 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07005819
Mel Gormane716f2e2017-05-03 14:53:45 -07005820 if (!managed_zone(zone))
5821 continue;
5822
5823 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005824 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07005825 return true;
5826 }
5827
5828 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005829 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07005830 * need balancing by definition. This can happen if a zone-restricted
5831 * allocation tries to wake a remote kswapd.
5832 */
5833 if (mark == -1)
5834 return true;
5835
5836 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08005837}
5838
Mel Gorman631b6e02017-05-03 14:53:41 -07005839/* Clear pgdat state for congested, dirty or under writeback. */
5840static void clear_pgdat_congested(pg_data_t *pgdat)
5841{
Johannes Weiner1b051172019-11-30 17:55:52 -08005842 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5843
5844 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07005845 clear_bit(PGDAT_DIRTY, &pgdat->flags);
5846 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
5847}
5848
Mel Gorman1741c872011-01-13 15:46:21 -08005849/*
Mel Gorman55150612012-07-31 16:44:35 -07005850 * Prepare kswapd for sleeping. This verifies that there are no processes
5851 * waiting in throttle_direct_reclaim() and that watermarks have been met.
5852 *
5853 * Returns true if kswapd is ready to sleep
5854 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005855static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
5856 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08005857{
Mel Gorman55150612012-07-31 16:44:35 -07005858 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005859 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07005860 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005861 * race between when kswapd checks the watermarks and a process gets
5862 * throttled. There is also a potential race if processes get
5863 * throttled, kswapd wakes, a large process exits thereby balancing the
5864 * zones, which causes kswapd to exit balance_pgdat() before reaching
5865 * the wake up checks. If kswapd is going to sleep, no process should
5866 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
5867 * the wake up is premature, processes will wake kswapd and get
5868 * throttled again. The difference from wake ups in balance_pgdat() is
5869 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07005870 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005871 if (waitqueue_active(&pgdat->pfmemalloc_wait))
5872 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08005873
Johannes Weinerc73322d2017-05-03 14:51:51 -07005874 /* Hopeless node, leave it to direct reclaim */
5875 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
5876 return true;
5877
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005878 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07005879 clear_pgdat_congested(pgdat);
5880 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07005881 }
5882
Shantanu Goel333b0a42017-05-03 14:53:38 -07005883 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08005884}
5885
Linus Torvalds1da177e2005-04-16 15:20:36 -07005886/*
Mel Gorman1d82de62016-07-28 15:45:43 -07005887 * kswapd shrinks a node of pages that are at or below the highest usable
5888 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07005889 *
5890 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07005891 * reclaim or if the lack of progress was due to pages under writeback.
5892 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07005893 */
Mel Gorman1d82de62016-07-28 15:45:43 -07005894static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07005895 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07005896{
Mel Gorman1d82de62016-07-28 15:45:43 -07005897 struct zone *zone;
5898 int z;
Mel Gorman75485362013-07-03 15:01:42 -07005899
Mel Gorman1d82de62016-07-28 15:45:43 -07005900 /* Reclaim a number of pages proportional to the number of zones */
5901 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07005902 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07005903 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07005904 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07005905 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07005906
Mel Gorman1d82de62016-07-28 15:45:43 -07005907 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07005908 }
5909
Mel Gorman1d82de62016-07-28 15:45:43 -07005910 /*
5911 * Historically care was taken to put equal pressure on all zones but
5912 * now pressure is applied based on node LRU order.
5913 */
Mel Gorman970a39a2016-07-28 15:46:35 -07005914 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07005915
5916 /*
5917 * Fragmentation may mean that the system cannot be rebalanced for
5918 * high-order allocations. If twice the allocation size has been
5919 * reclaimed then recheck watermarks only at order-0 to prevent
5920 * excessive reclaim. Assume that a process requested a high-order
5921 * can direct reclaim/compact.
5922 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07005923 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07005924 sc->order = 0;
5925
Mel Gormanb8e83b92013-07-03 15:01:45 -07005926 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07005927}
5928
Mel Gormanc49c2c42021-06-28 19:42:21 -07005929/* Page allocator PCP high watermark is lowered if reclaim is active. */
5930static inline void
5931update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
5932{
5933 int i;
5934 struct zone *zone;
5935
5936 for (i = 0; i <= highest_zoneidx; i++) {
5937 zone = pgdat->node_zones + i;
5938
5939 if (!managed_zone(zone))
5940 continue;
5941
5942 if (active)
5943 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
5944 else
5945 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
5946 }
5947}
5948
5949static inline void
5950set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
5951{
5952 update_reclaim_active(pgdat, highest_zoneidx, true);
5953}
5954
5955static inline void
5956clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
5957{
5958 update_reclaim_active(pgdat, highest_zoneidx, false);
5959}
5960
Mel Gorman75485362013-07-03 15:01:42 -07005961/*
Mel Gorman1d82de62016-07-28 15:45:43 -07005962 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
5963 * that are eligible for use by the caller until at least one zone is
5964 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005965 *
Mel Gorman1d82de62016-07-28 15:45:43 -07005966 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005967 *
5968 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07005969 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08005970 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07005971 * or lower is eligible for reclaim until at least one usable zone is
5972 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005973 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005974static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005975{
Linus Torvalds1da177e2005-04-16 15:20:36 -07005976 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07005977 unsigned long nr_soft_reclaimed;
5978 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07005979 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08005980 unsigned long nr_boost_reclaim;
5981 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
5982 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07005983 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08005984 struct scan_control sc = {
5985 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07005986 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005987 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08005988 };
Omar Sandoval93781322018-06-07 17:07:02 -07005989
Andrew Morton1732d2b012019-07-16 16:26:15 -07005990 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07005991 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07005992 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07005993
Christoph Lameterf8891e52006-06-30 01:55:45 -07005994 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005995
Mel Gorman1c308442018-12-28 00:35:52 -08005996 /*
5997 * Account for the reclaim boost. Note that the zone boost is left in
5998 * place so that parallel allocations that are near the watermark will
5999 * stall or direct reclaim until kswapd is finished.
6000 */
6001 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006002 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006003 zone = pgdat->node_zones + i;
6004 if (!managed_zone(zone))
6005 continue;
6006
6007 nr_boost_reclaim += zone->watermark_boost;
6008 zone_boosts[i] = zone->watermark_boost;
6009 }
6010 boosted = nr_boost_reclaim;
6011
6012restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006013 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006014 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006015 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006016 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006017 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006018 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006019 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006020
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006021 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006022
Mel Gorman86c79f62016-07-28 15:45:59 -07006023 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006024 * If the number of buffer_heads exceeds the maximum allowed
6025 * then consider reclaiming from all zones. This has a dual
6026 * purpose -- on 64-bit systems it is expected that
6027 * buffer_heads are stripped during active rotation. On 32-bit
6028 * systems, highmem pages can pin lowmem memory and shrinking
6029 * buffers can relieve lowmem pressure. Reclaim may still not
6030 * go ahead if all eligible zones for the original allocation
6031 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006032 */
6033 if (buffer_heads_over_limit) {
6034 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6035 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006036 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006037 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006038
Mel Gorman970a39a2016-07-28 15:46:35 -07006039 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006040 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006041 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006042 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006043
Mel Gorman86c79f62016-07-28 15:45:59 -07006044 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006045 * If the pgdat is imbalanced then ignore boosting and preserve
6046 * the watermarks for a later time and restart. Note that the
6047 * zone watermarks will be still reset at the end of balancing
6048 * on the grounds that the normal reclaim should be enough to
6049 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006050 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006051 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006052 if (!balanced && nr_boost_reclaim) {
6053 nr_boost_reclaim = 0;
6054 goto restart;
6055 }
6056
6057 /*
6058 * If boosting is not active then only reclaim if there are no
6059 * eligible zones. Note that sc.reclaim_idx is not used as
6060 * buffer_heads_over_limit may have adjusted it.
6061 */
6062 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006063 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006064
Mel Gorman1c308442018-12-28 00:35:52 -08006065 /* Limit the priority of boosting to avoid reclaim writeback */
6066 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6067 raise_priority = false;
6068
6069 /*
6070 * Do not writeback or swap pages for boosted reclaim. The
6071 * intent is to relieve pressure not issue sub-optimal IO
6072 * from reclaim context. If no pages are reclaimed, the
6073 * reclaim will be aborted.
6074 */
6075 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6076 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006077
Linus Torvalds1da177e2005-04-16 15:20:36 -07006078 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006079 * Do some background aging of the anon list, to give
6080 * pages a chance to be referenced before reclaiming. All
6081 * pages are rotated regardless of classzone as this is
6082 * about consistent aging.
6083 */
Mel Gormanef8f2322016-07-28 15:46:05 -07006084 age_active_anon(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006085
6086 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006087 * If we're getting trouble reclaiming, start doing writepage
6088 * even in laptop mode.
6089 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006090 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006091 sc.may_writepage = 1;
6092
Mel Gorman1d82de62016-07-28 15:45:43 -07006093 /* Call soft limit reclaim before calling shrink_node. */
6094 sc.nr_scanned = 0;
6095 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006096 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006097 sc.gfp_mask, &nr_soft_scanned);
6098 sc.nr_reclaimed += nr_soft_reclaimed;
6099
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006100 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006101 * There should be no need to raise the scanning priority if
6102 * enough pages are already being scanned that that high
6103 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006104 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006105 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006106 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006107
6108 /*
6109 * If the low watermark is met there is no need for processes
6110 * to be throttled on pfmemalloc_wait as they should not be
6111 * able to safely make forward progress. Wake them
6112 */
6113 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006114 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006115 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006116
Mel Gormanb8e83b92013-07-03 15:01:45 -07006117 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006118 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006119 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006120 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006121 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006122 break;
6123
6124 /*
6125 * Raise priority if scanning rate is too low or there was no
6126 * progress in reclaiming pages
6127 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006128 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006129 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6130
6131 /*
6132 * If reclaim made no progress for a boost, stop reclaim as
6133 * IO cannot be queued and it could be an infinite loop in
6134 * extreme circumstances.
6135 */
6136 if (nr_boost_reclaim && !nr_reclaimed)
6137 break;
6138
Johannes Weinerc73322d2017-05-03 14:51:51 -07006139 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006140 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006141 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006142
Johannes Weinerc73322d2017-05-03 14:51:51 -07006143 if (!sc.nr_reclaimed)
6144 pgdat->kswapd_failures++;
6145
Mel Gormanb8e83b92013-07-03 15:01:45 -07006146out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006147 clear_reclaim_active(pgdat, highest_zoneidx);
6148
Mel Gorman1c308442018-12-28 00:35:52 -08006149 /* If reclaim was boosted, account for the reclaim done in this pass */
6150 if (boosted) {
6151 unsigned long flags;
6152
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006153 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006154 if (!zone_boosts[i])
6155 continue;
6156
6157 /* Increments are under the zone lock */
6158 zone = pgdat->node_zones + i;
6159 spin_lock_irqsave(&zone->lock, flags);
6160 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6161 spin_unlock_irqrestore(&zone->lock, flags);
6162 }
6163
6164 /*
6165 * As there is now likely space, wakeup kcompact to defragment
6166 * pageblocks.
6167 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006168 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006169 }
6170
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006171 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006172 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006173 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006174 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006175
Mel Gorman0abdee22011-01-13 15:46:22 -08006176 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006177 * Return the order kswapd stopped reclaiming at as
6178 * prepare_kswapd_sleep() takes it into account. If another caller
6179 * entered the allocator slow path while kswapd was awake, order will
6180 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006181 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006182 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006183}
6184
Mel Gormane716f2e2017-05-03 14:53:45 -07006185/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006186 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6187 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6188 * not a valid index then either kswapd runs for first time or kswapd couldn't
6189 * sleep after previous reclaim attempt (node is still unbalanced). In that
6190 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006191 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006192static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6193 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006194{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006195 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006196
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006197 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006198}
6199
Mel Gorman38087d92016-07-28 15:45:49 -07006200static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006201 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006202{
6203 long remaining = 0;
6204 DEFINE_WAIT(wait);
6205
6206 if (freezing(current) || kthread_should_stop())
6207 return;
6208
6209 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6210
Shantanu Goel333b0a42017-05-03 14:53:38 -07006211 /*
6212 * Try to sleep for a short interval. Note that kcompactd will only be
6213 * woken if it is possible to sleep for a short interval. This is
6214 * deliberate on the assumption that if reclaim cannot keep an
6215 * eligible zone balanced that it's also unlikely that compaction will
6216 * succeed.
6217 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006218 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006219 /*
6220 * Compaction records what page blocks it recently failed to
6221 * isolate pages from and skips them in the future scanning.
6222 * When kswapd is going to sleep, it is reasonable to assume
6223 * that pages and compaction may succeed so reset the cache.
6224 */
6225 reset_isolation_suitable(pgdat);
6226
6227 /*
6228 * We have freed the memory, now we should compact it to make
6229 * allocation of the requested order possible.
6230 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006231 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006232
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006233 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006234
6235 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006236 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006237 * order. The values will either be from a wakeup request or
6238 * the previous request that slept prematurely.
6239 */
6240 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006241 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6242 kswapd_highest_zoneidx(pgdat,
6243 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006244
6245 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6246 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006247 }
6248
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006249 finish_wait(&pgdat->kswapd_wait, &wait);
6250 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6251 }
6252
6253 /*
6254 * After a short sleep, check if it was a premature sleep. If not, then
6255 * go fully to sleep until explicitly woken up.
6256 */
Mel Gormand9f21d42016-07-28 15:46:41 -07006257 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006258 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006259 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6260
6261 /*
6262 * vmstat counters are not perfectly accurate and the estimated
6263 * value for counters such as NR_FREE_PAGES can deviate from the
6264 * true value by nr_online_cpus * threshold. To avoid the zone
6265 * watermarks being breached while under pressure, we reduce the
6266 * per-cpu vmstat threshold while kswapd is awake and restore
6267 * them before going back to sleep.
6268 */
6269 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07006270
6271 if (!kthread_should_stop())
6272 schedule();
6273
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006274 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
6275 } else {
6276 if (remaining)
6277 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
6278 else
6279 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
6280 }
6281 finish_wait(&pgdat->kswapd_wait, &wait);
6282}
6283
Linus Torvalds1da177e2005-04-16 15:20:36 -07006284/*
6285 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006286 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006287 *
6288 * This basically trickles out pages so that we have _some_
6289 * free memory available even if there is no other activity
6290 * that frees anything up. This is needed for things like routing
6291 * etc, where we otherwise might have all activity going on in
6292 * asynchronous contexts that cannot page things out.
6293 *
6294 * If there are applications that are active memory-allocators
6295 * (most normal use), this basically shouldn't matter.
6296 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306297int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006298{
Mel Gormane716f2e2017-05-03 14:53:45 -07006299 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006300 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07006301 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006302 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10306303 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006304
Rusty Russell174596a2009-01-01 10:12:29 +10306305 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07006306 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006307
6308 /*
6309 * Tell the memory management that we're a "memory allocator",
6310 * and that if we need more memory we should get access to it
6311 * regardless (see "__alloc_pages()"). "kswapd" should
6312 * never get caught in the normal page freeing logic.
6313 *
6314 * (Kswapd normally doesn't need memory anyway, but sometimes
6315 * you need a small amount of memory in order to be able to
6316 * page out something else, and this flag essentially protects
6317 * us from recursively trying to free more memory as we're
6318 * trying to free the first piece of memory in the first place).
6319 */
Christoph Lameter930d9152006-01-08 01:00:47 -08006320 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07006321 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07006322
Qian Cai5644e1fb2020-04-01 21:10:12 -07006323 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006324 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006325 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08006326 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07006327
Qian Cai5644e1fb2020-04-01 21:10:12 -07006328 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006329 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6330 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07006331
Mel Gorman38087d92016-07-28 15:45:49 -07006332kswapd_try_sleep:
6333 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006334 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07006335
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006336 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08006337 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006338 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6339 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006340 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006341 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006342
David Rientjes8fe23e02009-12-14 17:58:33 -08006343 ret = try_to_freeze();
6344 if (kthread_should_stop())
6345 break;
6346
6347 /*
6348 * We can speed up thawing tasks if we don't call balance_pgdat
6349 * after returning from the refrigerator
6350 */
Mel Gorman38087d92016-07-28 15:45:49 -07006351 if (ret)
6352 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07006353
Mel Gorman38087d92016-07-28 15:45:49 -07006354 /*
6355 * Reclaim begins at the requested order but if a high-order
6356 * reclaim fails then kswapd falls back to reclaiming for
6357 * order-0. If that happens, kswapd will consider sleeping
6358 * for the order it finished reclaiming at (reclaim_order)
6359 * but kcompactd is woken to compact for the original
6360 * request (alloc_order).
6361 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006362 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07006363 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006364 reclaim_order = balance_pgdat(pgdat, alloc_order,
6365 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07006366 if (reclaim_order < alloc_order)
6367 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006368 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08006369
Johannes Weiner71abdc12014-06-06 14:35:35 -07006370 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07006371
Linus Torvalds1da177e2005-04-16 15:20:36 -07006372 return 0;
6373}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306374EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006375
6376/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07006377 * A zone is low on free memory or too fragmented for high-order memory. If
6378 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
6379 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
6380 * has failed or is not needed, still wake up kcompactd if only compaction is
6381 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006382 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07006383void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006384 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006385{
6386 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07006387 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006388
Mel Gorman6aa303d2016-09-01 16:14:55 -07006389 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006390 return;
6391
David Rientjes5ecd9d42018-04-05 16:25:16 -07006392 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006393 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07006394
Qian Cai5644e1fb2020-04-01 21:10:12 -07006395 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006396 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006397
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006398 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
6399 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006400
6401 if (READ_ONCE(pgdat->kswapd_order) < order)
6402 WRITE_ONCE(pgdat->kswapd_order, order);
6403
Con Kolivas8d0986e2005-09-13 01:25:07 -07006404 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006405 return;
Mel Gormane1a55632016-07-28 15:46:26 -07006406
David Rientjes5ecd9d42018-04-05 16:25:16 -07006407 /* Hopeless node, leave it to direct reclaim if possible */
6408 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006409 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
6410 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07006411 /*
6412 * There may be plenty of free memory available, but it's too
6413 * fragmented for high-order allocations. Wake up kcompactd
6414 * and rely on compaction_suitable() to determine if it's
6415 * needed. If it fails, it will defer subsequent attempts to
6416 * ratelimit its work.
6417 */
6418 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006419 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07006420 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07006421 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07006422
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006423 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07006424 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07006425 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006426}
6427
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006428#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07006429/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006430 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006431 * freed pages.
6432 *
6433 * Rather than trying to age LRUs the aim is to preserve the overall
6434 * LRU order by reclaiming preferentially
6435 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07006436 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006437unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006438{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006439 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006440 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07006441 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07006442 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006443 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07006444 .may_writepage = 1,
6445 .may_unmap = 1,
6446 .may_swap = 1,
6447 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07006448 };
Ying Hana09ed5e2011-05-24 17:12:26 -07006449 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006450 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006451 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006452
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01006453 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07006454 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07006455 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08006456
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006457 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006458
Andrew Morton1732d2b012019-07-16 16:26:15 -07006459 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006460 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006461 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006462
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006463 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006464}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006465#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07006466
Yasunori Goto3218ae12006-06-27 02:53:33 -07006467/*
6468 * This kswapd start function will be called by init and node-hot-add.
6469 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
6470 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07006471void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006472{
6473 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306474 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006475
6476 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07006477 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006478
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306479 trace_android_vh_kswapd_per_node(nid, &skip, true);
6480 if (skip)
6481 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006482 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
6483 if (IS_ERR(pgdat->kswapd)) {
6484 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02006485 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07006486 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07006487 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006488 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07006489}
6490
David Rientjes8fe23e02009-12-14 17:58:33 -08006491/*
Jiang Liud8adde12012-07-11 14:01:52 -07006492 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07006493 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08006494 */
6495void kswapd_stop(int nid)
6496{
6497 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306498 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08006499
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306500 trace_android_vh_kswapd_per_node(nid, &skip, false);
6501 if (skip)
6502 return;
Jiang Liud8adde12012-07-11 14:01:52 -07006503 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08006504 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07006505 NODE_DATA(nid)->kswapd = NULL;
6506 }
David Rientjes8fe23e02009-12-14 17:58:33 -08006507}
6508
Linus Torvalds1da177e2005-04-16 15:20:36 -07006509static int __init kswapd_init(void)
6510{
Wei Yang6b700b52020-04-01 21:10:09 -07006511 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08006512
Linus Torvalds1da177e2005-04-16 15:20:36 -07006513 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08006514 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006515 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006516 return 0;
6517}
6518
6519module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006520
6521#ifdef CONFIG_NUMA
6522/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006523 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08006524 *
Mel Gormana5f5f912016-07-28 15:46:32 -07006525 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08006526 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006527 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006528int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006529
Dave Hansen51998362021-02-24 12:09:15 -08006530/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006531 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08006532 * of a node considered for each zone_reclaim. 4 scans 1/16th of
6533 * a zone.
6534 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006535#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08006536
Christoph Lameter9eeff232006-01-18 17:42:31 -08006537/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006538 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07006539 * occur.
6540 */
6541int sysctl_min_unmapped_ratio = 1;
6542
6543/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07006544 * If the number of slab pages in a zone grows beyond this percentage then
6545 * slab reclaim needs to occur.
6546 */
6547int sysctl_min_slab_ratio = 5;
6548
Mel Gorman11fb9982016-07-28 15:46:20 -07006549static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006550{
Mel Gorman11fb9982016-07-28 15:46:20 -07006551 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
6552 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
6553 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006554
6555 /*
6556 * It's possible for there to be more file mapped pages than
6557 * accounted for by the pages on the file LRU lists because
6558 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
6559 */
6560 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
6561}
6562
6563/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07006564static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006565{
Alexandru Moised031a152015-11-05 18:48:08 -08006566 unsigned long nr_pagecache_reclaimable;
6567 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07006568
6569 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006570 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07006571 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07006572 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07006573 * a better estimate
6574 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006575 if (node_reclaim_mode & RECLAIM_UNMAP)
6576 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006577 else
Mel Gormana5f5f912016-07-28 15:46:32 -07006578 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006579
6580 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07006581 if (!(node_reclaim_mode & RECLAIM_WRITE))
6582 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006583
6584 /* Watch for any possible underflows due to delta */
6585 if (unlikely(delta > nr_pagecache_reclaimable))
6586 delta = nr_pagecache_reclaimable;
6587
6588 return nr_pagecache_reclaimable - delta;
6589}
6590
Christoph Lameter0ff38492006-09-25 23:31:52 -07006591/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006592 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006593 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006594static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006595{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08006596 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08006597 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006598 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006599 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08006600 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08006601 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006602 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07006603 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07006604 .priority = NODE_RECLAIM_PRIORITY,
6605 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
6606 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07006607 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006608 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08006609 };
Johannes Weiner57f29762021-08-19 19:04:27 -07006610 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006611
Yafang Shao132bb8c2019-05-13 17:17:53 -07006612 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
6613 sc.gfp_mask);
6614
Christoph Lameter9eeff232006-01-18 17:42:31 -08006615 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07006616 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07006617 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08006618 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006619 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08006620 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006621 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08006622 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07006623 noreclaim_flag = memalloc_noreclaim_save();
6624 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07006625 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08006626
Mel Gormana5f5f912016-07-28 15:46:32 -07006627 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07006628 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07006629 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07006630 * priorities until we have enough memory freed.
6631 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07006632 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07006633 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006634 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07006635 }
Christoph Lameterc84db232006-02-01 03:05:29 -08006636
Andrew Morton1732d2b012019-07-16 16:26:15 -07006637 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006638 current->flags &= ~PF_SWAPWRITE;
6639 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006640 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07006641 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07006642
6643 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
6644
Rik van Riela79311c2009-01-06 14:40:01 -08006645 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006646}
Andrew Morton179e9632006-03-22 00:08:18 -08006647
Mel Gormana5f5f912016-07-28 15:46:32 -07006648int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08006649{
David Rientjesd773ed62007-10-16 23:26:01 -07006650 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006651
6652 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006653 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07006654 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07006655 *
Christoph Lameter96146342006-07-03 00:24:13 -07006656 * A small portion of unmapped file backed pages is needed for
6657 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07006658 * thrown out if the node is overallocated. So we do not reclaim
6659 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07006660 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08006661 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006662 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07006663 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
6664 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07006665 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08006666
6667 /*
David Rientjesd773ed62007-10-16 23:26:01 -07006668 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08006669 */
Mel Gormand0164ad2015-11-06 16:28:21 -08006670 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07006671 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08006672
6673 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006674 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08006675 * have associated processors. This will favor the local processor
6676 * over remote processors and spread off node memory allocations
6677 * as wide as possible.
6678 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006679 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
6680 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07006681
Mel Gormana5f5f912016-07-28 15:46:32 -07006682 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
6683 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07006684
Mel Gormana5f5f912016-07-28 15:46:32 -07006685 ret = __node_reclaim(pgdat, gfp_mask, order);
6686 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07006687
Mel Gorman24cf725182009-06-16 15:33:23 -07006688 if (!ret)
6689 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
6690
David Rientjesd773ed62007-10-16 23:26:01 -07006691 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006692}
Christoph Lameter9eeff232006-01-18 17:42:31 -08006693#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07006694
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006695/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006696 * check_move_unevictable_pages - check pages for evictability and move to
6697 * appropriate zone lru list
6698 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006699 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006700 * Checks pages for evictability, if an evictable page is in the unevictable
6701 * lru list, moves it to the appropriate evictable lru list. This function
6702 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006703 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006704void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006705{
Alex Shi6168d0d2020-12-15 12:34:29 -08006706 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08006707 int pgscanned = 0;
6708 int pgrescued = 0;
6709 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006710
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006711 for (i = 0; i < pvec->nr; i++) {
6712 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006713 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07006714
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006715 if (PageTransTail(page))
6716 continue;
6717
6718 nr_pages = thp_nr_pages(page);
6719 pgscanned += nr_pages;
6720
Alex Shid25b5bd2020-12-15 12:34:16 -08006721 /* block memcg migration during page moving between lru */
6722 if (!TestClearPageLRU(page))
6723 continue;
6724
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08006725 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08006726 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08006727 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08006728 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08006729 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006730 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08006731 }
Alex Shid25b5bd2020-12-15 12:34:16 -08006732 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006733 }
Hugh Dickins24513262012-01-20 14:34:21 -08006734
Alex Shi6168d0d2020-12-15 12:34:29 -08006735 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08006736 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
6737 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08006738 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08006739 } else if (pgscanned) {
6740 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08006741 }
Hugh Dickins850465792012-01-20 14:34:19 -08006742}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006743EXPORT_SYMBOL_GPL(check_move_unevictable_pages);