blob: 84e3d79f2e51d2ccabc2ffcfb5a68797c67e8fba [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001// SPDX-License-Identifier: GPL-2.0
Linus Torvalds1da177e2005-04-16 15:20:36 -07002/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07003 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
4 *
5 * Swap reorganised 29.12.95, Stephen Tweedie.
6 * kswapd added: 7.1.96 sct
7 * Removed kswapd_ctl limits, and swap out as many pages as needed
8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
10 * Multiqueue VM started 5.8.00, Rik van Riel.
11 */
12
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070013#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
Linus Torvalds1da177e2005-04-16 15:20:36 -070015#include <linux/mm.h>
Ingo Molnar5b3cc152017-02-02 20:43:54 +010016#include <linux/sched/mm.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070017#include <linux/module.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090018#include <linux/gfp.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070019#include <linux/kernel_stat.h>
20#include <linux/swap.h>
21#include <linux/pagemap.h>
22#include <linux/init.h>
23#include <linux/highmem.h>
Anton Vorontsov70ddf632013-04-29 15:08:31 -070024#include <linux/vmpressure.h>
Andrew Mortone129b5c2006-09-27 01:50:00 -070025#include <linux/vmstat.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070026#include <linux/file.h>
27#include <linux/writeback.h>
28#include <linux/blkdev.h>
29#include <linux/buffer_head.h> /* for try_to_release_page(),
30 buffer_heads_over_limit */
31#include <linux/mm_inline.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070032#include <linux/backing-dev.h>
33#include <linux/rmap.h>
34#include <linux/topology.h>
35#include <linux/cpu.h>
36#include <linux/cpuset.h>
Mel Gorman3e7d3442011-01-13 15:45:56 -080037#include <linux/compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070038#include <linux/notifier.h>
39#include <linux/rwsem.h>
Rafael J. Wysocki248a0302006-03-22 00:09:04 -080040#include <linux/delay.h>
Yasunori Goto3218ae12006-06-27 02:53:33 -070041#include <linux/kthread.h>
Nigel Cunningham7dfb7102006-12-06 20:34:23 -080042#include <linux/freezer.h>
Balbir Singh66e17072008-02-07 00:13:56 -080043#include <linux/memcontrol.h>
Dave Hansen26aa2d12021-09-02 14:59:16 -070044#include <linux/migrate.h>
Keika Kobayashi873b4772008-07-25 01:48:52 -070045#include <linux/delayacct.h>
Lee Schermerhornaf936a12008-10-18 20:26:53 -070046#include <linux/sysctl.h>
KOSAKI Motohiro929bea72011-04-14 15:22:12 -070047#include <linux/oom.h>
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +000048#include <linux/pagevec.h>
Linus Torvalds268bb0c2011-05-20 12:50:29 -070049#include <linux/prefetch.h>
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070050#include <linux/printk.h>
Ross Zwislerf9fe48b2016-01-22 15:10:40 -080051#include <linux/dax.h>
Johannes Weinereb414682018-10-26 15:06:27 -070052#include <linux/psi.h>
Yu Zhao5280d762022-01-27 19:23:01 -070053#include <linux/pagewalk.h>
54#include <linux/shmem_fs.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070055
56#include <asm/tlbflush.h>
57#include <asm/div64.h>
58
59#include <linux/swapops.h>
Rafael Aquini117aad12013-09-30 13:45:16 -070060#include <linux/balloon_compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070061
Nick Piggin0f8053a2006-03-22 00:08:33 -080062#include "internal.h"
63
Mel Gorman33906bc2010-08-09 17:19:16 -070064#define CREATE_TRACE_POINTS
65#include <trace/events/vmscan.h>
66
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -070067#undef CREATE_TRACE_POINTS
68#include <trace/hooks/vmscan.h>
69
Linus Torvalds1da177e2005-04-16 15:20:36 -070070struct scan_control {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -080071 /* How many pages shrink_list() should reclaim */
72 unsigned long nr_to_reclaim;
73
Johannes Weineree814fe2014-08-06 16:06:19 -070074 /*
75 * Nodemask of nodes allowed by the caller. If NULL, all nodes
76 * are scanned.
77 */
78 nodemask_t *nodemask;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -070079
KOSAKI Motohiro5f53e762010-05-24 14:32:37 -070080 /*
Johannes Weinerf16015f2012-01-12 17:17:52 -080081 * The memory cgroup that hit its limit and as a result is the
82 * primary target of this reclaim invocation.
83 */
84 struct mem_cgroup *target_mem_cgroup;
Balbir Singh66e17072008-02-07 00:13:56 -080085
Johannes Weiner7cf111b2020-06-03 16:03:06 -070086 /*
87 * Scan pressure balancing between anon and file LRUs
88 */
89 unsigned long anon_cost;
90 unsigned long file_cost;
91
Johannes Weinerb91ac372019-11-30 17:56:02 -080092 /* Can active pages be deactivated as part of reclaim? */
93#define DEACTIVATE_ANON 1
94#define DEACTIVATE_FILE 2
95 unsigned int may_deactivate:2;
96 unsigned int force_deactivate:1;
97 unsigned int skipped_deactivate:1;
98
Johannes Weiner1276ad62017-02-24 14:56:11 -080099 /* Writepage batching in laptop mode; RECLAIM_WRITE */
Johannes Weineree814fe2014-08-06 16:06:19 -0700100 unsigned int may_writepage:1;
101
102 /* Can mapped pages be reclaimed? */
103 unsigned int may_unmap:1;
104
105 /* Can pages be swapped as part of reclaim? */
106 unsigned int may_swap:1;
107
Yisheng Xied6622f62017-05-03 14:53:57 -0700108 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700109 * Cgroup memory below memory.low is protected as long as we
110 * don't threaten to OOM. If any cgroup is reclaimed at
111 * reduced force or passed over entirely due to its memory.low
112 * setting (memcg_low_skipped), and nothing is reclaimed as a
113 * result, then go back for one more cycle that reclaims the protected
114 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700115 */
116 unsigned int memcg_low_reclaim:1;
117 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800118
Johannes Weineree814fe2014-08-06 16:06:19 -0700119 unsigned int hibernation_mode:1;
120
121 /* One of the zones is ready for compaction */
122 unsigned int compaction_ready:1;
123
Johannes Weinerb91ac372019-11-30 17:56:02 -0800124 /* There is easily reclaimable cold cache in the current node */
125 unsigned int cache_trim_mode:1;
126
Johannes Weiner53138ce2019-11-30 17:55:56 -0800127 /* The file pages on the current node are dangerously low */
128 unsigned int file_is_tiny:1;
129
Dave Hansen26aa2d12021-09-02 14:59:16 -0700130 /* Always discard instead of demoting to lower tier memory */
131 unsigned int no_demotion:1;
132
Greg Thelenbb451fd2018-08-17 15:45:19 -0700133 /* Allocation order */
134 s8 order;
135
136 /* Scan (total_size >> priority) pages at once */
137 s8 priority;
138
139 /* The highest zone to isolate pages for reclaim from */
140 s8 reclaim_idx;
141
142 /* This context's GFP mask */
143 gfp_t gfp_mask;
144
Johannes Weineree814fe2014-08-06 16:06:19 -0700145 /* Incremented by the number of inactive pages that were scanned */
146 unsigned long nr_scanned;
147
148 /* Number of pages freed so far during a call to shrink_zones() */
149 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700150
151 struct {
152 unsigned int dirty;
153 unsigned int unqueued_dirty;
154 unsigned int congested;
155 unsigned int writeback;
156 unsigned int immediate;
157 unsigned int file_taken;
158 unsigned int taken;
159 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700160
161 /* for recording the reclaimed slab by now */
162 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700163};
164
Linus Torvalds1da177e2005-04-16 15:20:36 -0700165#ifdef ARCH_HAS_PREFETCHW
166#define prefetchw_prev_lru_page(_page, _base, _field) \
167 do { \
168 if ((_page)->lru.prev != _base) { \
169 struct page *prev; \
170 \
171 prev = lru_to_page(&(_page->lru)); \
172 prefetchw(&prev->_field); \
173 } \
174 } while (0)
175#else
176#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
177#endif
178
179/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700180 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700181 */
182int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700183
Yang Shi0a432dc2019-09-23 15:38:12 -0700184static void set_task_reclaim_state(struct task_struct *task,
185 struct reclaim_state *rs)
186{
187 /* Check for an overwrite */
188 WARN_ON_ONCE(rs && task->reclaim_state);
189
190 /* Check for the nulling of an already-nulled member */
191 WARN_ON_ONCE(!rs && !task->reclaim_state);
192
193 task->reclaim_state = rs;
194}
195
Linus Torvalds1da177e2005-04-16 15:20:36 -0700196static LIST_HEAD(shrinker_list);
197static DECLARE_RWSEM(shrinker_rwsem);
198
Yang Shi0a432dc2019-09-23 15:38:12 -0700199#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700200static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700201
Yang Shi3c6f17e2021-05-04 18:36:33 -0700202/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700203static inline int shrinker_map_size(int nr_items)
204{
205 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
206}
Yang Shi2bfd3632021-05-04 18:36:11 -0700207
Yang Shi3c6f17e2021-05-04 18:36:33 -0700208static inline int shrinker_defer_size(int nr_items)
209{
210 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
211}
212
Yang Shi468ab842021-05-04 18:36:26 -0700213static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
214 int nid)
215{
216 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
217 lockdep_is_held(&shrinker_rwsem));
218}
219
Yang Shie4262c42021-05-04 18:36:23 -0700220static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700221 int map_size, int defer_size,
222 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700223{
Yang Shie4262c42021-05-04 18:36:23 -0700224 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700225 struct mem_cgroup_per_node *pn;
226 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700227 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700228
Yang Shi2bfd3632021-05-04 18:36:11 -0700229 for_each_node(nid) {
230 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700231 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700232 /* Not yet online memcg */
233 if (!old)
234 return 0;
235
236 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
237 if (!new)
238 return -ENOMEM;
239
Yang Shi3c6f17e2021-05-04 18:36:33 -0700240 new->nr_deferred = (atomic_long_t *)(new + 1);
241 new->map = (void *)new->nr_deferred + defer_size;
242
243 /* map: set all old bits, clear all new bits */
244 memset(new->map, (int)0xff, old_map_size);
245 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
246 /* nr_deferred: copy old values, clear all new values */
247 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
248 memset((void *)new->nr_deferred + old_defer_size, 0,
249 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700250
Yang Shie4262c42021-05-04 18:36:23 -0700251 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700252 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700253 }
254
255 return 0;
256}
257
Yang Shie4262c42021-05-04 18:36:23 -0700258void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700259{
260 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700261 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700262 int nid;
263
Yang Shi2bfd3632021-05-04 18:36:11 -0700264 for_each_node(nid) {
265 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700266 info = rcu_dereference_protected(pn->shrinker_info, true);
267 kvfree(info);
268 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700269 }
270}
271
Yang Shie4262c42021-05-04 18:36:23 -0700272int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700273{
Yang Shie4262c42021-05-04 18:36:23 -0700274 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700275 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700276 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700277
Yang Shid27cf2a2021-05-04 18:36:14 -0700278 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700279 map_size = shrinker_map_size(shrinker_nr_max);
280 defer_size = shrinker_defer_size(shrinker_nr_max);
281 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700282 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700283 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
284 if (!info) {
285 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700286 ret = -ENOMEM;
287 break;
288 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700289 info->nr_deferred = (atomic_long_t *)(info + 1);
290 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700291 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700292 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700293 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700294
295 return ret;
296}
297
Yang Shi3c6f17e2021-05-04 18:36:33 -0700298static inline bool need_expand(int nr_max)
299{
300 return round_up(nr_max, BITS_PER_LONG) >
301 round_up(shrinker_nr_max, BITS_PER_LONG);
302}
303
Yang Shie4262c42021-05-04 18:36:23 -0700304static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700305{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700306 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700307 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700308 int map_size, defer_size = 0;
309 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700310 struct mem_cgroup *memcg;
311
Yang Shi3c6f17e2021-05-04 18:36:33 -0700312 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700313 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700314
Yang Shi2bfd3632021-05-04 18:36:11 -0700315 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700316 goto out;
317
318 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700319
Yang Shi3c6f17e2021-05-04 18:36:33 -0700320 map_size = shrinker_map_size(new_nr_max);
321 defer_size = shrinker_defer_size(new_nr_max);
322 old_map_size = shrinker_map_size(shrinker_nr_max);
323 old_defer_size = shrinker_defer_size(shrinker_nr_max);
324
Yang Shi2bfd3632021-05-04 18:36:11 -0700325 memcg = mem_cgroup_iter(NULL, NULL, NULL);
326 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700327 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
328 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700329 if (ret) {
330 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700331 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700332 }
333 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700334out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700335 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700336 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700337
Yang Shi2bfd3632021-05-04 18:36:11 -0700338 return ret;
339}
340
341void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
342{
343 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700344 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700345
346 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700347 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700348 /* Pairs with smp mb in shrink_slab() */
349 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700350 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700351 rcu_read_unlock();
352 }
353}
354
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700355static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700356
357static int prealloc_memcg_shrinker(struct shrinker *shrinker)
358{
359 int id, ret = -ENOMEM;
360
Yang Shi476b30a2021-05-04 18:36:39 -0700361 if (mem_cgroup_disabled())
362 return -ENOSYS;
363
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700364 down_write(&shrinker_rwsem);
365 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700366 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700367 if (id < 0)
368 goto unlock;
369
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700370 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700371 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700372 idr_remove(&shrinker_idr, id);
373 goto unlock;
374 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700375 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700376 shrinker->id = id;
377 ret = 0;
378unlock:
379 up_write(&shrinker_rwsem);
380 return ret;
381}
382
383static void unregister_memcg_shrinker(struct shrinker *shrinker)
384{
385 int id = shrinker->id;
386
387 BUG_ON(id < 0);
388
Yang Shi41ca6682021-05-04 18:36:29 -0700389 lockdep_assert_held(&shrinker_rwsem);
390
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700391 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700392}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700393
Yang Shi86750832021-05-04 18:36:36 -0700394static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
395 struct mem_cgroup *memcg)
396{
397 struct shrinker_info *info;
398
399 info = shrinker_info_protected(memcg, nid);
400 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
401}
402
403static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
404 struct mem_cgroup *memcg)
405{
406 struct shrinker_info *info;
407
408 info = shrinker_info_protected(memcg, nid);
409 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
410}
411
Yang Shia1780152021-05-04 18:36:42 -0700412void reparent_shrinker_deferred(struct mem_cgroup *memcg)
413{
414 int i, nid;
415 long nr;
416 struct mem_cgroup *parent;
417 struct shrinker_info *child_info, *parent_info;
418
419 parent = parent_mem_cgroup(memcg);
420 if (!parent)
421 parent = root_mem_cgroup;
422
423 /* Prevent from concurrent shrinker_info expand */
424 down_read(&shrinker_rwsem);
425 for_each_node(nid) {
426 child_info = shrinker_info_protected(memcg, nid);
427 parent_info = shrinker_info_protected(parent, nid);
428 for (i = 0; i < shrinker_nr_max; i++) {
429 nr = atomic_long_read(&child_info->nr_deferred[i]);
430 atomic_long_add(nr, &parent_info->nr_deferred[i]);
431 }
432 }
433 up_read(&shrinker_rwsem);
434}
435
Johannes Weinerb5ead352019-11-30 17:55:40 -0800436static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800437{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800438 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800439}
Tejun Heo97c93412015-05-22 18:23:36 -0400440
441/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800442 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400443 * @sc: scan_control in question
444 *
445 * The normal page dirty throttling mechanism in balance_dirty_pages() is
446 * completely broken with the legacy memcg and direct stalling in
447 * shrink_page_list() is used for throttling instead, which lacks all the
448 * niceties such as fairness, adaptive pausing, bandwidth proportional
449 * allocation and configurability.
450 *
451 * This function tests whether the vmscan currently in progress can assume
452 * that the normal dirty throttling mechanism is operational.
453 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800454static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400455{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800456 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400457 return true;
458#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800459 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400460 return true;
461#endif
462 return false;
463}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800464#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700465static int prealloc_memcg_shrinker(struct shrinker *shrinker)
466{
Yang Shi476b30a2021-05-04 18:36:39 -0700467 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700468}
469
470static void unregister_memcg_shrinker(struct shrinker *shrinker)
471{
472}
473
Yang Shi86750832021-05-04 18:36:36 -0700474static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
475 struct mem_cgroup *memcg)
476{
477 return 0;
478}
479
480static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
481 struct mem_cgroup *memcg)
482{
483 return 0;
484}
485
Johannes Weinerb5ead352019-11-30 17:55:40 -0800486static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800487{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800488 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800489}
Tejun Heo97c93412015-05-22 18:23:36 -0400490
Johannes Weinerb5ead352019-11-30 17:55:40 -0800491static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400492{
493 return true;
494}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800495#endif
496
Yang Shi86750832021-05-04 18:36:36 -0700497static long xchg_nr_deferred(struct shrinker *shrinker,
498 struct shrink_control *sc)
499{
500 int nid = sc->nid;
501
502 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
503 nid = 0;
504
505 if (sc->memcg &&
506 (shrinker->flags & SHRINKER_MEMCG_AWARE))
507 return xchg_nr_deferred_memcg(nid, shrinker,
508 sc->memcg);
509
510 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
511}
512
513
514static long add_nr_deferred(long nr, struct shrinker *shrinker,
515 struct shrink_control *sc)
516{
517 int nid = sc->nid;
518
519 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
520 nid = 0;
521
522 if (sc->memcg &&
523 (shrinker->flags & SHRINKER_MEMCG_AWARE))
524 return add_nr_deferred_memcg(nr, nid, shrinker,
525 sc->memcg);
526
527 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
528}
529
Dave Hansen26aa2d12021-09-02 14:59:16 -0700530static bool can_demote(int nid, struct scan_control *sc)
531{
Huang Ying20b51af12021-09-02 14:59:33 -0700532 if (!numa_demotion_enabled)
533 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700534 if (sc) {
535 if (sc->no_demotion)
536 return false;
537 /* It is pointless to do demotion in memcg reclaim */
538 if (cgroup_reclaim(sc))
539 return false;
540 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700541 if (next_demotion_node(nid) == NUMA_NO_NODE)
542 return false;
543
Huang Ying20b51af12021-09-02 14:59:33 -0700544 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700545}
546
Keith Buscha2a36482021-09-02 14:59:26 -0700547static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
548 int nid,
549 struct scan_control *sc)
550{
551 if (memcg == NULL) {
552 /*
553 * For non-memcg reclaim, is there
554 * space in any swap device?
555 */
556 if (get_nr_swap_pages() > 0)
557 return true;
558 } else {
559 /* Is the memcg below its swap limit? */
560 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
561 return true;
562 }
563
564 /*
565 * The page can not be swapped.
566 *
567 * Can it be reclaimed from this node via demotion?
568 */
569 return can_demote(nid, sc);
570}
571
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700572/*
573 * This misses isolated pages which are not accounted for to save counters.
574 * As the data only determines if reclaim or compaction continues, it is
575 * not expected that isolated pages will be a dominating factor.
576 */
577unsigned long zone_reclaimable_pages(struct zone *zone)
578{
579 unsigned long nr;
580
581 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
582 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700583 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700584 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
585 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
586
587 return nr;
588}
589
Michal Hockofd538802017-02-22 15:45:58 -0800590/**
591 * lruvec_lru_size - Returns the number of pages on the given LRU list.
592 * @lruvec: lru vector
593 * @lru: lru to use
594 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
595 */
Yu Zhao20913392021-02-24 12:08:44 -0800596static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
597 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800598{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800599 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800600 int zid;
601
Johannes Weinerde3b0152019-11-30 17:55:31 -0800602 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800603 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800604
Michal Hockofd538802017-02-22 15:45:58 -0800605 if (!managed_zone(zone))
606 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800607
Michal Hockofd538802017-02-22 15:45:58 -0800608 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800609 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800610 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800611 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800612 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800613 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800614}
615
Linus Torvalds1da177e2005-04-16 15:20:36 -0700616/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000617 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700618 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900619int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700620{
Yang Shi476b30a2021-05-04 18:36:39 -0700621 unsigned int size;
622 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000623
Yang Shi476b30a2021-05-04 18:36:39 -0700624 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
625 err = prealloc_memcg_shrinker(shrinker);
626 if (err != -ENOSYS)
627 return err;
628
629 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
630 }
631
632 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000633 if (shrinker->flags & SHRINKER_NUMA_AWARE)
634 size *= nr_node_ids;
635
636 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
637 if (!shrinker->nr_deferred)
638 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700639
Tetsuo Handa8e049442018-04-04 19:53:07 +0900640 return 0;
641}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000642
Tetsuo Handa8e049442018-04-04 19:53:07 +0900643void free_prealloced_shrinker(struct shrinker *shrinker)
644{
Yang Shi41ca6682021-05-04 18:36:29 -0700645 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
646 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700647 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700648 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700649 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700650 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700651
Tetsuo Handa8e049442018-04-04 19:53:07 +0900652 kfree(shrinker->nr_deferred);
653 shrinker->nr_deferred = NULL;
654}
655
656void register_shrinker_prepared(struct shrinker *shrinker)
657{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700658 down_write(&shrinker_rwsem);
659 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700660 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700661 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900662}
663
664int register_shrinker(struct shrinker *shrinker)
665{
666 int err = prealloc_shrinker(shrinker);
667
668 if (err)
669 return err;
670 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000671 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700672}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700673EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700674
675/*
676 * Remove one
677 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700678void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700679{
Yang Shi41ca6682021-05-04 18:36:29 -0700680 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900681 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700682
Linus Torvalds1da177e2005-04-16 15:20:36 -0700683 down_write(&shrinker_rwsem);
684 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700685 shrinker->flags &= ~SHRINKER_REGISTERED;
686 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
687 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700688 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700689
Andrew Vaginae393322013-10-16 13:46:46 -0700690 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900691 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700692}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700693EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700694
695#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000696
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800697static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800698 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700699{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000700 unsigned long freed = 0;
701 unsigned long long delta;
702 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700703 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000704 long nr;
705 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000706 long batch_size = shrinker->batch ? shrinker->batch
707 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800708 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000709
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700710 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700711 if (freeable == 0 || freeable == SHRINK_EMPTY)
712 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000713
714 /*
715 * copy the current shrinker scan count into a local variable
716 * and zero it so that other concurrent shrinker invocations
717 * don't also do this scanning work.
718 */
Yang Shi86750832021-05-04 18:36:36 -0700719 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000720
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700721 if (shrinker->seeks) {
722 delta = freeable >> priority;
723 delta *= 4;
724 do_div(delta, shrinker->seeks);
725 } else {
726 /*
727 * These objects don't require any IO to create. Trim
728 * them aggressively under memory pressure to keep
729 * them from causing refetches in the IO caches.
730 */
731 delta = freeable / 2;
732 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700733
Yang Shi18bb4732021-05-04 18:36:45 -0700734 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000735 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700736 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000737
738 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800739 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000740
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800741 /*
742 * Normally, we should not scan less than batch_size objects in one
743 * pass to avoid too frequent shrinker calls, but if the slab has less
744 * than batch_size objects in total and we are really tight on memory,
745 * we will try to reclaim all available objects, otherwise we can end
746 * up failing allocations although there are plenty of reclaimable
747 * objects spread over several slabs with usage less than the
748 * batch_size.
749 *
750 * We detect the "tight on memory" situations by looking at the total
751 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700752 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800753 * scanning at high prio and therefore should try to reclaim as much as
754 * possible.
755 */
756 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700757 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000758 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800759 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000760
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800761 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700762 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000763 ret = shrinker->scan_objects(shrinker, shrinkctl);
764 if (ret == SHRINK_STOP)
765 break;
766 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000767
Chris Wilsond460acb2017-09-06 16:19:26 -0700768 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
769 total_scan -= shrinkctl->nr_scanned;
770 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000771
772 cond_resched();
773 }
774
Yang Shi18bb4732021-05-04 18:36:45 -0700775 /*
776 * The deferred work is increased by any new work (delta) that wasn't
777 * done, decreased by old deferred work that was done now.
778 *
779 * And it is capped to two times of the freeable items.
780 */
781 next_deferred = max_t(long, (nr + delta - scanned), 0);
782 next_deferred = min(next_deferred, (2 * freeable));
783
Glauber Costa1d3d4432013-08-28 10:18:04 +1000784 /*
785 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700786 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000787 */
Yang Shi86750832021-05-04 18:36:36 -0700788 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000789
Yang Shi8efb4b52021-05-04 18:36:08 -0700790 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000791 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700792}
793
Yang Shi0a432dc2019-09-23 15:38:12 -0700794#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700795static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
796 struct mem_cgroup *memcg, int priority)
797{
Yang Shie4262c42021-05-04 18:36:23 -0700798 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700799 unsigned long ret, freed = 0;
800 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700801
Yang Shi0a432dc2019-09-23 15:38:12 -0700802 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700803 return 0;
804
805 if (!down_read_trylock(&shrinker_rwsem))
806 return 0;
807
Yang Shi468ab842021-05-04 18:36:26 -0700808 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700809 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700810 goto unlock;
811
Yang Shie4262c42021-05-04 18:36:23 -0700812 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700813 struct shrink_control sc = {
814 .gfp_mask = gfp_mask,
815 .nid = nid,
816 .memcg = memcg,
817 };
818 struct shrinker *shrinker;
819
820 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700821 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700822 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700823 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700824 continue;
825 }
826
Yang Shi0a432dc2019-09-23 15:38:12 -0700827 /* Call non-slab shrinkers even though kmem is disabled */
828 if (!memcg_kmem_enabled() &&
829 !(shrinker->flags & SHRINKER_NONSLAB))
830 continue;
831
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700832 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700833 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700834 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700835 /*
836 * After the shrinker reported that it had no objects to
837 * free, but before we cleared the corresponding bit in
838 * the memcg shrinker map, a new object might have been
839 * added. To make sure, we have the bit set in this
840 * case, we invoke the shrinker one more time and reset
841 * the bit if it reports that it is not empty anymore.
842 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700843 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700844 *
845 * list_lru_add() shrink_slab_memcg()
846 * list_add_tail() clear_bit()
847 * <MB> <MB>
848 * set_bit() do_shrink_slab()
849 */
850 smp_mb__after_atomic();
851 ret = do_shrink_slab(&sc, shrinker, priority);
852 if (ret == SHRINK_EMPTY)
853 ret = 0;
854 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700855 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700856 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700857 freed += ret;
858
859 if (rwsem_is_contended(&shrinker_rwsem)) {
860 freed = freed ? : 1;
861 break;
862 }
863 }
864unlock:
865 up_read(&shrinker_rwsem);
866 return freed;
867}
Yang Shi0a432dc2019-09-23 15:38:12 -0700868#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700869static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
870 struct mem_cgroup *memcg, int priority)
871{
872 return 0;
873}
Yang Shi0a432dc2019-09-23 15:38:12 -0700874#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700875
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800876/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800877 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800878 * @gfp_mask: allocation context
879 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800880 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800881 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700882 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800883 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700884 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800885 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
886 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700887 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700888 * @memcg specifies the memory cgroup to target. Unaware shrinkers
889 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800890 *
Josef Bacik9092c712018-01-31 16:16:26 -0800891 * @priority is sc->priority, we take the number of objects and >> by priority
892 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700893 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800894 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700895 */
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800896static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
897 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800898 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700899{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700900 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700901 struct shrinker *shrinker;
902
Yang Shifa1e5122019-08-02 21:48:44 -0700903 /*
904 * The root memcg might be allocated even though memcg is disabled
905 * via "cgroup_disable=memory" boot parameter. This could make
906 * mem_cgroup_is_root() return false, then just run memcg slab
907 * shrink, but skip global shrink. This may result in premature
908 * oom.
909 */
910 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700911 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800912
Tetsuo Handae830c632018-04-05 16:23:35 -0700913 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700914 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700915
916 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800917 struct shrink_control sc = {
918 .gfp_mask = gfp_mask,
919 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800920 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800921 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800922
Kirill Tkhai9b996462018-08-17 15:48:21 -0700923 ret = do_shrink_slab(&sc, shrinker, priority);
924 if (ret == SHRINK_EMPTY)
925 ret = 0;
926 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800927 /*
928 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700929 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800930 * by parallel ongoing shrinking.
931 */
932 if (rwsem_is_contended(&shrinker_rwsem)) {
933 freed = freed ? : 1;
934 break;
935 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700936 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800937
Linus Torvalds1da177e2005-04-16 15:20:36 -0700938 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700939out:
940 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000941 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700942}
943
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800944void drop_slab_node(int nid)
945{
946 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700947 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800948
949 do {
950 struct mem_cgroup *memcg = NULL;
951
Chunxin Zang069c4112020-10-13 16:56:46 -0700952 if (fatal_signal_pending(current))
953 return;
954
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800955 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700956 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800957 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800958 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800959 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700960 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800961}
962
963void drop_slab(void)
964{
965 int nid;
966
967 for_each_online_node(nid)
968 drop_slab_node(nid);
969}
970
Linus Torvalds1da177e2005-04-16 15:20:36 -0700971static inline int is_page_cache_freeable(struct page *page)
972{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700973 /*
974 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400975 * that isolated the page, the page cache and optional buffer
976 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700977 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -0700978 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400979 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700980}
981
Yang Shicb165562019-11-30 17:55:28 -0800982static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700983{
Christoph Lameter930d9152006-01-08 01:00:47 -0800984 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700985 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400986 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700987 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400988 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700989 return 1;
990 return 0;
991}
992
993/*
994 * We detected a synchronous write error writing a page out. Probably
995 * -ENOSPC. We need to propagate that into the address_space for a subsequent
996 * fsync(), msync() or close().
997 *
998 * The tricky part is that after writepage we cannot touch the mapping: nothing
999 * prevents it from being freed up. But we have a ref on the page and once
1000 * that page is locked, the mapping is pinned.
1001 *
1002 * We're allowed to run sleeping lock_page() here because we know the caller has
1003 * __GFP_FS.
1004 */
1005static void handle_write_error(struct address_space *mapping,
1006 struct page *page, int error)
1007{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001008 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001009 if (page_mapping(page) == mapping)
1010 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001011 unlock_page(page);
1012}
1013
Christoph Lameter04e62a22006-06-23 02:03:38 -07001014/* possible outcome of pageout() */
1015typedef enum {
1016 /* failed to write page out, page is locked */
1017 PAGE_KEEP,
1018 /* move page to the active list, page is locked */
1019 PAGE_ACTIVATE,
1020 /* page has been sent to the disk successfully, page is unlocked */
1021 PAGE_SUCCESS,
1022 /* page is clean and locked */
1023 PAGE_CLEAN,
1024} pageout_t;
1025
Linus Torvalds1da177e2005-04-16 15:20:36 -07001026/*
Andrew Morton1742f192006-03-22 00:08:21 -08001027 * pageout is called by shrink_page_list() for each dirty page.
1028 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001029 */
Yang Shicb165562019-11-30 17:55:28 -08001030static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001031{
1032 /*
1033 * If the page is dirty, only perform writeback if that write
1034 * will be non-blocking. To prevent this allocation from being
1035 * stalled by pagecache activity. But note that there may be
1036 * stalls if we need to run get_block(). We could test
1037 * PagePrivate for that.
1038 *
Al Viro81742022014-04-03 03:17:43 -04001039 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001040 * this page's queue, we can perform writeback even if that
1041 * will block.
1042 *
1043 * If the page is swapcache, write it back even if that would
1044 * block, for some throttling. This happens by accident, because
1045 * swap_backing_dev_info is bust: it doesn't reflect the
1046 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001047 */
1048 if (!is_page_cache_freeable(page))
1049 return PAGE_KEEP;
1050 if (!mapping) {
1051 /*
1052 * Some data journaling orphaned pages can have
1053 * page->mapping == NULL while being dirty with clean buffers.
1054 */
David Howells266cf652009-04-03 16:42:36 +01001055 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001056 if (try_to_free_buffers(page)) {
1057 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001058 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001059 return PAGE_CLEAN;
1060 }
1061 }
1062 return PAGE_KEEP;
1063 }
1064 if (mapping->a_ops->writepage == NULL)
1065 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001066 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001067 return PAGE_KEEP;
1068
1069 if (clear_page_dirty_for_io(page)) {
1070 int res;
1071 struct writeback_control wbc = {
1072 .sync_mode = WB_SYNC_NONE,
1073 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001074 .range_start = 0,
1075 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001076 .for_reclaim = 1,
1077 };
1078
1079 SetPageReclaim(page);
1080 res = mapping->a_ops->writepage(page, &wbc);
1081 if (res < 0)
1082 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001083 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001084 ClearPageReclaim(page);
1085 return PAGE_ACTIVATE;
1086 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001087
Linus Torvalds1da177e2005-04-16 15:20:36 -07001088 if (!PageWriteback(page)) {
1089 /* synchronous write or broken a_ops? */
1090 ClearPageReclaim(page);
1091 }
yalin wang3aa23852016-01-14 15:18:30 -08001092 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001093 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001094 return PAGE_SUCCESS;
1095 }
1096
1097 return PAGE_CLEAN;
1098}
1099
Andrew Mortona649fd92006-10-17 00:09:36 -07001100/*
Nick Piggine2867812008-07-25 19:45:30 -07001101 * Same as remove_mapping, but if the page is removed from the mapping, it
1102 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001103 */
Johannes Weinera5289102014-04-03 14:47:51 -07001104static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001105 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001106{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001107 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001108 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001109
Nick Piggin28e4d962006-09-25 23:31:23 -07001110 BUG_ON(!PageLocked(page));
1111 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001112
Johannes Weiner30472502021-09-02 14:53:18 -07001113 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001114 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001115 * The non racy check for a busy page.
1116 *
1117 * Must be careful with the order of the tests. When someone has
1118 * a ref to the page, it may be possible that they dirty it then
1119 * drop the reference. So if PageDirty is tested before page_count
1120 * here, then the following race may occur:
1121 *
1122 * get_user_pages(&page);
1123 * [user mapping goes away]
1124 * write_to(page);
1125 * !PageDirty(page) [good]
1126 * SetPageDirty(page);
1127 * put_page(page);
1128 * !page_count(page) [good, discard it]
1129 *
1130 * [oops, our write_to data is lost]
1131 *
1132 * Reversing the order of the tests ensures such a situation cannot
1133 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001134 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001135 *
1136 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001137 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001138 */
William Kucharski906d2782019-10-18 20:20:33 -07001139 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001140 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001141 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001142 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001143 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001144 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001145 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001146 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001147
1148 if (PageSwapCache(page)) {
1149 swp_entry_t swap = { .val = page_private(page) };
Yu Zhaoa1537a62022-01-27 20:32:37 -07001150
1151 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001152 if (reclaimed && !mapping_exiting(mapping))
1153 shadow = workingset_eviction(page, target_memcg);
Yu Zhaoa1537a62022-01-27 20:32:37 -07001154 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001155 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001156 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001157 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001158 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001159 void (*freepage)(struct page *);
1160
1161 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001162 /*
1163 * Remember a shadow entry for reclaimed file cache in
1164 * order to detect refaults, thus thrashing, later on.
1165 *
1166 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001167 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001168 * inode reclaim needs to empty out the radix tree or
1169 * the nodes are lost. Don't plant shadows behind its
1170 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001171 *
1172 * We also don't store shadows for DAX mappings because the
1173 * only page cache pages found in these are zero pages
1174 * covering holes, and because we don't want to mix DAX
1175 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001176 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001177 */
Huang Ying9de4f222020-04-06 20:04:41 -07001178 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001179 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001180 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001181 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001182 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001183
1184 if (freepage != NULL)
1185 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001186 }
1187
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001188 return 1;
1189
1190cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001191 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001192 return 0;
1193}
1194
Linus Torvalds1da177e2005-04-16 15:20:36 -07001195/*
Nick Piggine2867812008-07-25 19:45:30 -07001196 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1197 * someone else has a ref on the page, abort and return 0. If it was
1198 * successfully detached, return 1. Assumes the caller has a single ref on
1199 * this page.
1200 */
1201int remove_mapping(struct address_space *mapping, struct page *page)
1202{
Johannes Weinerb9107182019-11-30 17:55:59 -08001203 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001204 /*
1205 * Unfreezing the refcount with 1 rather than 2 effectively
1206 * drops the pagecache ref for us without requiring another
1207 * atomic operation.
1208 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001209 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001210 return 1;
1211 }
1212 return 0;
1213}
1214
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001215/**
1216 * putback_lru_page - put previously isolated page onto appropriate LRU list
1217 * @page: page to be put back to appropriate lru list
1218 *
1219 * Add previously isolated @page to appropriate LRU list.
1220 * Page may still be unevictable for other reasons.
1221 *
1222 * lru_lock must not be held, interrupts must be enabled.
1223 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001224void putback_lru_page(struct page *page)
1225{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001226 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001227 put_page(page); /* drop ref from isolate */
1228}
1229
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001230enum page_references {
1231 PAGEREF_RECLAIM,
1232 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001233 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001234 PAGEREF_ACTIVATE,
1235};
1236
1237static enum page_references page_check_references(struct page *page,
1238 struct scan_control *sc)
1239{
Johannes Weiner645747462010-03-05 13:42:22 -08001240 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001241 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001242
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001243 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1244 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001245 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001246
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001247 /*
1248 * Mlock lost the isolation race with us. Let try_to_unmap()
1249 * move the page to the unevictable list.
1250 */
1251 if (vm_flags & VM_LOCKED)
1252 return PAGEREF_RECLAIM;
1253
Johannes Weiner645747462010-03-05 13:42:22 -08001254 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001255 /*
1256 * All mapped pages start out with page table
1257 * references from the instantiating fault, so we need
1258 * to look twice if a mapped file page is used more
1259 * than once.
1260 *
1261 * Mark it and spare it for another trip around the
1262 * inactive list. Another page table reference will
1263 * lead to its activation.
1264 *
1265 * Note: the mark is set for activated pages as well
1266 * so that recently deactivated but used pages are
1267 * quickly recovered.
1268 */
1269 SetPageReferenced(page);
1270
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001271 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001272 return PAGEREF_ACTIVATE;
1273
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001274 /*
1275 * Activate file-backed executable pages after first usage.
1276 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001277 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001278 return PAGEREF_ACTIVATE;
1279
Johannes Weiner645747462010-03-05 13:42:22 -08001280 return PAGEREF_KEEP;
1281 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001282
1283 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001284 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001285 return PAGEREF_RECLAIM_CLEAN;
1286
1287 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001288}
1289
Mel Gormane2be15f2013-07-03 15:01:57 -07001290/* Check if a page is dirty or under writeback */
1291static void page_check_dirty_writeback(struct page *page,
1292 bool *dirty, bool *writeback)
1293{
Mel Gormanb4597222013-07-03 15:02:05 -07001294 struct address_space *mapping;
1295
Mel Gormane2be15f2013-07-03 15:01:57 -07001296 /*
1297 * Anonymous pages are not handled by flushers and must be written
1298 * from reclaim context. Do not stall reclaim based on them
1299 */
Huang Ying9de4f222020-04-06 20:04:41 -07001300 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001301 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001302 *dirty = false;
1303 *writeback = false;
1304 return;
1305 }
1306
1307 /* By default assume that the page flags are accurate */
1308 *dirty = PageDirty(page);
1309 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001310
1311 /* Verify dirty/writeback state if the filesystem supports it */
1312 if (!page_has_private(page))
1313 return;
1314
1315 mapping = page_mapping(page);
1316 if (mapping && mapping->a_ops->is_dirty_writeback)
1317 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001318}
1319
Dave Hansen26aa2d12021-09-02 14:59:16 -07001320static struct page *alloc_demote_page(struct page *page, unsigned long node)
1321{
1322 struct migration_target_control mtc = {
1323 /*
1324 * Allocate from 'node', or fail quickly and quietly.
1325 * When this happens, 'page' will likely just be discarded
1326 * instead of migrated.
1327 */
1328 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1329 __GFP_THISNODE | __GFP_NOWARN |
1330 __GFP_NOMEMALLOC | GFP_NOWAIT,
1331 .nid = node
1332 };
1333
1334 return alloc_migration_target(page, (unsigned long)&mtc);
1335}
1336
1337/*
1338 * Take pages on @demote_list and attempt to demote them to
1339 * another node. Pages which are not demoted are left on
1340 * @demote_pages.
1341 */
1342static unsigned int demote_page_list(struct list_head *demote_pages,
1343 struct pglist_data *pgdat)
1344{
1345 int target_nid = next_demotion_node(pgdat->node_id);
1346 unsigned int nr_succeeded;
1347 int err;
1348
1349 if (list_empty(demote_pages))
1350 return 0;
1351
1352 if (target_nid == NUMA_NO_NODE)
1353 return 0;
1354
1355 /* Demotion ignores all cpuset and mempolicy settings */
1356 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1357 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1358 &nr_succeeded);
1359
Yang Shi668e4142021-09-02 14:59:19 -07001360 if (current_is_kswapd())
1361 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1362 else
1363 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1364
Dave Hansen26aa2d12021-09-02 14:59:16 -07001365 return nr_succeeded;
1366}
1367
Nick Piggine2867812008-07-25 19:45:30 -07001368/*
Andrew Morton1742f192006-03-22 00:08:21 -08001369 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001370 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001371static unsigned int shrink_page_list(struct list_head *page_list,
1372 struct pglist_data *pgdat,
1373 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001374 struct reclaim_stat *stat,
1375 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001376{
1377 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001378 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001379 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001380 unsigned int nr_reclaimed = 0;
1381 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001382 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001383
Kirill Tkhai060f0052019-03-05 15:48:15 -08001384 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001385 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001386 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001387
Dave Hansen26aa2d12021-09-02 14:59:16 -07001388retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001389 while (!list_empty(page_list)) {
1390 struct address_space *mapping;
1391 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001392 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001393 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001394 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001395
1396 cond_resched();
1397
1398 page = lru_to_page(page_list);
1399 list_del(&page->lru);
1400
Nick Piggin529ae9a2008-08-02 12:01:03 +02001401 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001402 goto keep;
1403
Sasha Levin309381fea2014-01-23 15:52:54 -08001404 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001405
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001406 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001407
1408 /* Account the number of base pages even though THP */
1409 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001410
Hugh Dickins39b5f292012-10-08 16:33:18 -07001411 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001412 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001413
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001414 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001415 goto keep_locked;
1416
Yu Zhaoafd94c92022-01-27 20:43:22 -07001417 /* page_update_gen() tried to promote this page? */
1418 if (lru_gen_enabled() && !ignore_references &&
1419 page_mapped(page) && PageReferenced(page))
1420 goto keep_locked;
1421
Andy Whitcroftc661b072007-08-22 14:01:26 -07001422 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1423 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1424
Mel Gorman283aba92013-07-03 15:01:51 -07001425 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001426 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001427 * reclaim_congested which affects wait_iff_congested. kswapd
1428 * will stall and start writing pages if the tail of the LRU
1429 * is all dirty unqueued pages.
1430 */
1431 page_check_dirty_writeback(page, &dirty, &writeback);
1432 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001433 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001434
1435 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001436 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001437
Mel Gormand04e8ac2013-07-03 15:02:03 -07001438 /*
1439 * Treat this page as congested if the underlying BDI is or if
1440 * pages are cycling through the LRU so quickly that the
1441 * pages marked for immediate reclaim are making it to the
1442 * end of the LRU a second time.
1443 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001444 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001445 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001446 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001447 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001448 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001449
1450 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001451 * If a page at the tail of the LRU is under writeback, there
1452 * are three cases to consider.
1453 *
1454 * 1) If reclaim is encountering an excessive number of pages
1455 * under writeback and this page is both under writeback and
1456 * PageReclaim then it indicates that pages are being queued
1457 * for IO but are being recycled through the LRU before the
1458 * IO can complete. Waiting on the page itself risks an
1459 * indefinite stall if it is impossible to writeback the
1460 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001461 * note that the LRU is being scanned too quickly and the
1462 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001463 *
Tejun Heo97c93412015-05-22 18:23:36 -04001464 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001465 * not marked for immediate reclaim, or the caller does not
1466 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1467 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001468 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001469 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001470 * Require may_enter_fs because we would wait on fs, which
1471 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001472 * enter reclaim, and deadlock if it waits on a page for
1473 * which it is needed to do the write (loop masks off
1474 * __GFP_IO|__GFP_FS for this reason); but more thought
1475 * would probably show more reasons.
1476 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001477 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001478 * PageReclaim. memcg does not have any dirty pages
1479 * throttling so we could easily OOM just because too many
1480 * pages are in writeback and there is nothing else to
1481 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001482 *
1483 * In cases 1) and 2) we activate the pages to get them out of
1484 * the way while we continue scanning for clean pages on the
1485 * inactive list and refilling from the active list. The
1486 * observation here is that waiting for disk writes is more
1487 * expensive than potentially causing reloads down the line.
1488 * Since they're marked for immediate reclaim, they won't put
1489 * memory pressure on the cache working set any longer than it
1490 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001491 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001492 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001493 /* Case 1 above */
1494 if (current_is_kswapd() &&
1495 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001496 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001497 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001498 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001499
1500 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001501 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001502 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001503 /*
1504 * This is slightly racy - end_page_writeback()
1505 * might have just cleared PageReclaim, then
1506 * setting PageReclaim here end up interpreted
1507 * as PageReadahead - but that does not matter
1508 * enough to care. What we do want is for this
1509 * page to have PageReclaim set next time memcg
1510 * reclaim reaches the tests above, so it will
1511 * then wait_on_page_writeback() to avoid OOM;
1512 * and it's also appropriate in global reclaim.
1513 */
1514 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001515 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001516 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001517
1518 /* Case 3 above */
1519 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001520 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001521 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001522 /* then go back and try same page again */
1523 list_add_tail(&page->lru, page_list);
1524 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001525 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001526 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001527
Minchan Kim8940b342019-09-25 16:49:11 -07001528 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001529 references = page_check_references(page, sc);
1530
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001531 switch (references) {
1532 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001533 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001534 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001535 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001536 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001537 case PAGEREF_RECLAIM:
1538 case PAGEREF_RECLAIM_CLEAN:
1539 ; /* try to reclaim the page below */
1540 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001541
Linus Torvalds1da177e2005-04-16 15:20:36 -07001542 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001543 * Before reclaiming the page, try to relocate
1544 * its contents to another node.
1545 */
1546 if (do_demote_pass &&
1547 (thp_migration_supported() || !PageTransHuge(page))) {
1548 list_add(&page->lru, &demote_pages);
1549 unlock_page(page);
1550 continue;
1551 }
1552
1553 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001554 * Anonymous process memory has backing store?
1555 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001556 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001557 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001558 if (PageAnon(page) && PageSwapBacked(page)) {
1559 if (!PageSwapCache(page)) {
1560 if (!(sc->gfp_mask & __GFP_IO))
1561 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001562 if (page_maybe_dma_pinned(page))
1563 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001564 if (PageTransHuge(page)) {
1565 /* cannot split THP, skip it */
1566 if (!can_split_huge_page(page, NULL))
1567 goto activate_locked;
1568 /*
1569 * Split pages without a PMD map right
1570 * away. Chances are some or all of the
1571 * tail pages can be freed without IO.
1572 */
1573 if (!compound_mapcount(page) &&
1574 split_huge_page_to_list(page,
1575 page_list))
1576 goto activate_locked;
1577 }
1578 if (!add_to_swap(page)) {
1579 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001580 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001581 /* Fallback to swap normal pages */
1582 if (split_huge_page_to_list(page,
1583 page_list))
1584 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001585#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1586 count_vm_event(THP_SWPOUT_FALLBACK);
1587#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001588 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001589 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001590 }
Minchan Kim0f074652017-07-06 15:37:24 -07001591
Kirill Tkhai4b793062020-04-01 21:10:18 -07001592 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001593
1594 /* Adding to swap updated mapping */
1595 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001596 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001597 } else if (unlikely(PageTransHuge(page))) {
1598 /* Split file THP */
1599 if (split_huge_page_to_list(page, page_list))
1600 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001601 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001602
1603 /*
Yang Shi98879b32019-07-11 20:59:30 -07001604 * THP may get split above, need minus tail pages and update
1605 * nr_pages to avoid accounting tail pages twice.
1606 *
1607 * The tail pages that are added into swap cache successfully
1608 * reach here.
1609 */
1610 if ((nr_pages > 1) && !PageTransHuge(page)) {
1611 sc->nr_scanned -= (nr_pages - 1);
1612 nr_pages = 1;
1613 }
1614
1615 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001616 * The page is mapped into the page tables of one or more
1617 * processes. Try to unmap it here.
1618 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001619 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001620 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001621 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001622
1623 if (unlikely(PageTransHuge(page)))
1624 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001625
Yang Shi1fb08ac2021-06-30 18:52:01 -07001626 try_to_unmap(page, flags);
1627 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001628 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001629 if (!was_swapbacked && PageSwapBacked(page))
1630 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001631 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001632 }
1633 }
1634
1635 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001636 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001637 * Only kswapd can writeback filesystem pages
1638 * to avoid risk of stack overflow. But avoid
1639 * injecting inefficient single-page IO into
1640 * flusher writeback as much as possible: only
1641 * write pages when we've encountered many
1642 * dirty pages, and when we've already scanned
1643 * the rest of the LRU for clean pages and see
1644 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001645 */
Huang Ying9de4f222020-04-06 20:04:41 -07001646 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001647 (!current_is_kswapd() || !PageReclaim(page) ||
1648 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001649 /*
1650 * Immediately reclaim when written back.
1651 * Similar in principal to deactivate_page()
1652 * except we already have the page isolated
1653 * and know it's dirty
1654 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001655 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001656 SetPageReclaim(page);
1657
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001658 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001659 }
1660
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001661 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001662 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001663 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001664 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001665 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001666 goto keep_locked;
1667
Mel Gormand950c942015-09-04 15:47:35 -07001668 /*
1669 * Page is dirty. Flush the TLB if a writable entry
1670 * potentially exists to avoid CPU writes after IO
1671 * starts and then write it out here.
1672 */
1673 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001674 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001675 case PAGE_KEEP:
1676 goto keep_locked;
1677 case PAGE_ACTIVATE:
1678 goto activate_locked;
1679 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001680 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001681
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001682 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001683 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001684 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001685 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001686
Linus Torvalds1da177e2005-04-16 15:20:36 -07001687 /*
1688 * A synchronous write - probably a ramdisk. Go
1689 * ahead and try to reclaim the page.
1690 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001691 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001692 goto keep;
1693 if (PageDirty(page) || PageWriteback(page))
1694 goto keep_locked;
1695 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001696 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001697 case PAGE_CLEAN:
1698 ; /* try to free the page below */
1699 }
1700 }
1701
1702 /*
1703 * If the page has buffers, try to free the buffer mappings
1704 * associated with this page. If we succeed we try to free
1705 * the page as well.
1706 *
1707 * We do this even if the page is PageDirty().
1708 * try_to_release_page() does not perform I/O, but it is
1709 * possible for a page to have PageDirty set, but it is actually
1710 * clean (all its buffers are clean). This happens if the
1711 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001712 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001713 * try_to_release_page() will discover that cleanness and will
1714 * drop the buffers and mark the page clean - it can be freed.
1715 *
1716 * Rarely, pages can have buffers and no ->mapping. These are
1717 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001718 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001719 * and if that worked, and the page is no longer mapped into
1720 * process address space (page_count == 1) it can be freed.
1721 * Otherwise, leave the page on the LRU so it is swappable.
1722 */
David Howells266cf652009-04-03 16:42:36 +01001723 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001724 if (!try_to_release_page(page, sc->gfp_mask))
1725 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001726 if (!mapping && page_count(page) == 1) {
1727 unlock_page(page);
1728 if (put_page_testzero(page))
1729 goto free_it;
1730 else {
1731 /*
1732 * rare race with speculative reference.
1733 * the speculative reference will free
1734 * this page shortly, so we may
1735 * increment nr_reclaimed here (and
1736 * leave it off the LRU).
1737 */
1738 nr_reclaimed++;
1739 continue;
1740 }
1741 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001742 }
1743
Shaohua Li802a3a92017-05-03 14:52:32 -07001744 if (PageAnon(page) && !PageSwapBacked(page)) {
1745 /* follow __remove_mapping for reference */
1746 if (!page_ref_freeze(page, 1))
1747 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001748 /*
1749 * The page has only one reference left, which is
1750 * from the isolation. After the caller puts the
1751 * page back on lru and drops the reference, the
1752 * page will be freed anyway. It doesn't matter
1753 * which lru it goes. So we don't bother checking
1754 * PageDirty here.
1755 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001756 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001757 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001758 } else if (!mapping || !__remove_mapping(mapping, page, true,
1759 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001760 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001761
1762 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001763free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001764 /*
1765 * THP may get swapped out in a whole, need account
1766 * all base pages.
1767 */
1768 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001769
1770 /*
1771 * Is there need to periodically free_page_list? It would
1772 * appear not as the counts should be low
1773 */
Yang Shi7ae88532019-09-23 15:38:09 -07001774 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001775 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001776 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001777 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001778 continue;
1779
Yang Shi98879b32019-07-11 20:59:30 -07001780activate_locked_split:
1781 /*
1782 * The tail pages that are failed to add into swap cache
1783 * reach here. Fixup nr_scanned and nr_pages.
1784 */
1785 if (nr_pages > 1) {
1786 sc->nr_scanned -= (nr_pages - 1);
1787 nr_pages = 1;
1788 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001789activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001790 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001791 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1792 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001793 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001794 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001795 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001796 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001797 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001798 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001799 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001800 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001801keep_locked:
1802 unlock_page(page);
1803keep:
1804 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001805 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001806 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001807 /* 'page_list' is always empty here */
1808
1809 /* Migrate pages selected for demotion */
1810 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1811 /* Pages that could not be demoted are still in @demote_pages */
1812 if (!list_empty(&demote_pages)) {
1813 /* Pages which failed to demoted go back on @page_list for retry: */
1814 list_splice_init(&demote_pages, page_list);
1815 do_demote_pass = false;
1816 goto retry;
1817 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001818
Yang Shi98879b32019-07-11 20:59:30 -07001819 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1820
Johannes Weiner747db952014-08-08 14:19:24 -07001821 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001822 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001823 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001824
Linus Torvalds1da177e2005-04-16 15:20:36 -07001825 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001826 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001827
Andrew Morton05ff5132006-03-22 00:08:20 -08001828 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001829}
1830
Maninder Singh730ec8c2020-06-03 16:01:18 -07001831unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001832 struct list_head *page_list)
1833{
1834 struct scan_control sc = {
1835 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001836 .may_unmap = 1,
1837 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001838 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001839 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001840 struct page *page, *next;
1841 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001842 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001843
1844 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001845 if (!PageHuge(page) && page_is_file_lru(page) &&
1846 !PageDirty(page) && !__PageMovable(page) &&
1847 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001848 ClearPageActive(page);
1849 list_move(&page->lru, &clean_pages);
1850 }
1851 }
1852
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001853 /*
1854 * We should be safe here since we are only dealing with file pages and
1855 * we are not kswapd and therefore cannot write dirty file pages. But
1856 * call memalloc_noreclaim_save() anyway, just in case these conditions
1857 * change in the future.
1858 */
1859 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001860 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001861 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001862 memalloc_noreclaim_restore(noreclaim_flag);
1863
Minchan Kim02c6de82012-10-08 16:31:55 -07001864 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001865 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1866 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001867 /*
1868 * Since lazyfree pages are isolated from file LRU from the beginning,
1869 * they will rotate back to anonymous LRU in the end if it failed to
1870 * discard so isolated count will be mismatched.
1871 * Compensate the isolated count for both LRU lists.
1872 */
1873 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1874 stat.nr_lazyfree_fail);
1875 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001876 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001877 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001878}
1879
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001880/*
1881 * Attempt to remove the specified page from its LRU. Only take this page
1882 * if it is of the appropriate PageActive status. Pages which are being
1883 * freed elsewhere are also ignored.
1884 *
1885 * page: page to consider
1886 * mode: one of the LRU isolation modes defined above
1887 *
Alex Shic2135f72021-02-24 12:08:01 -08001888 * returns true on success, false on failure.
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001889 */
Alex Shic2135f72021-02-24 12:08:01 -08001890bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001891{
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001892 /* Only take pages on the LRU. */
1893 if (!PageLRU(page))
Alex Shic2135f72021-02-24 12:08:01 -08001894 return false;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001895
Minchan Kime46a2872012-10-08 16:33:48 -07001896 /* Compaction should not handle unevictable pages but CMA can do so */
1897 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
Alex Shic2135f72021-02-24 12:08:01 -08001898 return false;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001899
Mel Gormanc8244932012-01-12 17:19:38 -08001900 /*
1901 * To minimise LRU disruption, the caller can indicate that it only
1902 * wants to isolate pages it will be able to operate on without
1903 * blocking - clean pages for the most part.
1904 *
Mel Gormanc8244932012-01-12 17:19:38 -08001905 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1906 * that it is possible to migrate without blocking
1907 */
Johannes Weiner1276ad62017-02-24 14:56:11 -08001908 if (mode & ISOLATE_ASYNC_MIGRATE) {
Mel Gormanc8244932012-01-12 17:19:38 -08001909 /* All the caller can do on PageWriteback is block */
1910 if (PageWriteback(page))
Alex Shic2135f72021-02-24 12:08:01 -08001911 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001912
1913 if (PageDirty(page)) {
1914 struct address_space *mapping;
Mel Gorman69d763f2018-01-31 16:19:52 -08001915 bool migrate_dirty;
Mel Gormanc8244932012-01-12 17:19:38 -08001916
Mel Gormanc8244932012-01-12 17:19:38 -08001917 /*
1918 * Only pages without mappings or that have a
1919 * ->migratepage callback are possible to migrate
Mel Gorman69d763f2018-01-31 16:19:52 -08001920 * without blocking. However, we can be racing with
1921 * truncation so it's necessary to lock the page
1922 * to stabilise the mapping as truncation holds
1923 * the page lock until after the page is removed
1924 * from the page cache.
Mel Gormanc8244932012-01-12 17:19:38 -08001925 */
Mel Gorman69d763f2018-01-31 16:19:52 -08001926 if (!trylock_page(page))
Alex Shic2135f72021-02-24 12:08:01 -08001927 return false;
Mel Gorman69d763f2018-01-31 16:19:52 -08001928
Mel Gormanc8244932012-01-12 17:19:38 -08001929 mapping = page_mapping(page);
Hugh Dickins145e1a72018-06-01 16:50:50 -07001930 migrate_dirty = !mapping || mapping->a_ops->migratepage;
Mel Gorman69d763f2018-01-31 16:19:52 -08001931 unlock_page(page);
1932 if (!migrate_dirty)
Alex Shic2135f72021-02-24 12:08:01 -08001933 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001934 }
1935 }
Minchan Kim39deaf82011-10-31 17:06:51 -07001936
Minchan Kimf80c0672011-10-31 17:06:55 -07001937 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
Alex Shic2135f72021-02-24 12:08:01 -08001938 return false;
Minchan Kimf80c0672011-10-31 17:06:55 -07001939
Alex Shic2135f72021-02-24 12:08:01 -08001940 return true;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001941}
1942
Mel Gorman7ee36a12016-07-28 15:47:17 -07001943/*
1944 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001945 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001946 */
1947static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001948 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001949{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001950 int zid;
1951
Mel Gorman7ee36a12016-07-28 15:47:17 -07001952 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1953 if (!nr_zone_taken[zid])
1954 continue;
1955
Wei Yanga892cb62020-06-03 16:01:12 -07001956 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001957 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001958
Mel Gorman7ee36a12016-07-28 15:47:17 -07001959}
1960
Mel Gormanf611fab2021-06-30 18:53:19 -07001961/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001962 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1963 *
1964 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001965 * shrink the lists perform better by taking out a batch of pages
1966 * and working on them outside the LRU lock.
1967 *
1968 * For pagecache intensive workloads, this function is the hottest
1969 * spot in the kernel (apart from copy_*_user functions).
1970 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001971 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001972 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001973 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001974 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001975 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001976 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001977 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001978 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001979 *
1980 * returns how many pages were moved onto *@dst.
1981 */
Andrew Morton69e05942006-03-22 00:08:19 -08001982static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001983 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001984 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001985 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001986{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001987 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001988 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001989 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001990 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07001991 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001992 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07001993 LIST_HEAD(pages_skipped);
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001994 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001995
Yang Shi98879b32019-07-11 20:59:30 -07001996 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001997 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07001998 while (scan < nr_to_scan && !list_empty(src)) {
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001999 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002000
Linus Torvalds1da177e2005-04-16 15:20:36 -07002001 page = lru_to_page(src);
2002 prefetchw_prev_lru_page(page, src, flags);
2003
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002004 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002005 total_scan += nr_pages;
2006
Mel Gormanb2e18752016-07-28 15:45:37 -07002007 if (page_zonenum(page) > sc->reclaim_idx) {
2008 list_move(&page->lru, &pages_skipped);
Yang Shi98879b32019-07-11 20:59:30 -07002009 nr_skipped[page_zonenum(page)] += nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002010 continue;
2011 }
2012
Minchan Kim791b48b2017-05-12 15:47:06 -07002013 /*
2014 * Do not count skipped pages because that makes the function
2015 * return with no isolated pages if the LRU mostly contains
2016 * ineligible pages. This causes the VM to not reclaim any
2017 * pages, triggering a premature OOM.
Yang Shi98879b32019-07-11 20:59:30 -07002018 *
2019 * Account all tail pages of THP. This would not cause
2020 * premature OOM since __isolate_lru_page() returns -EBUSY
2021 * only when the page is being freed somewhere else.
Minchan Kim791b48b2017-05-12 15:47:06 -07002022 */
Yang Shi98879b32019-07-11 20:59:30 -07002023 scan += nr_pages;
Alex Shic2135f72021-02-24 12:08:01 -08002024 if (!__isolate_lru_page_prepare(page, mode)) {
2025 /* It is being freed elsewhere */
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002026 list_move(&page->lru, src);
Alex Shic2135f72021-02-24 12:08:01 -08002027 continue;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002028 }
Alex Shic2135f72021-02-24 12:08:01 -08002029 /*
2030 * Be careful not to clear PageLRU until after we're
2031 * sure the page is not being freed elsewhere -- the
2032 * page release code relies on it.
2033 */
2034 if (unlikely(!get_page_unless_zero(page))) {
2035 list_move(&page->lru, src);
2036 continue;
2037 }
2038
2039 if (!TestClearPageLRU(page)) {
2040 /* Another thread is already isolating this page */
2041 put_page(page);
2042 list_move(&page->lru, src);
2043 continue;
2044 }
2045
2046 nr_taken += nr_pages;
2047 nr_zone_taken[page_zonenum(page)] += nr_pages;
2048 list_move(&page->lru, dst);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002049 }
2050
Mel Gormanb2e18752016-07-28 15:45:37 -07002051 /*
2052 * Splice any skipped pages to the start of the LRU list. Note that
2053 * this disrupts the LRU order when reclaiming for lower zones but
2054 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2055 * scanning would soon rescan the same pages to skip and put the
2056 * system at risk of premature OOM.
2057 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002058 if (!list_empty(&pages_skipped)) {
2059 int zid;
2060
Johannes Weiner3db65812017-05-03 14:52:13 -07002061 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002062 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2063 if (!nr_skipped[zid])
2064 continue;
2065
2066 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002067 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002068 }
2069 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002070 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002071 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Minchan Kim791b48b2017-05-12 15:47:06 -07002072 total_scan, skipped, nr_taken, mode, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002073 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002074 return nr_taken;
2075}
2076
Nick Piggin62695a82008-10-18 20:26:09 -07002077/**
2078 * isolate_lru_page - tries to isolate a page from its LRU list
2079 * @page: page to isolate from its LRU list
2080 *
2081 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2082 * vmstat statistic corresponding to whatever LRU list the page was on.
2083 *
2084 * Returns 0 if the page was removed from an LRU list.
2085 * Returns -EBUSY if the page was not on an LRU list.
2086 *
2087 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002088 * the active list, it will have PageActive set. If it was found on
2089 * the unevictable list, it will have the PageUnevictable bit set. That flag
2090 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002091 *
2092 * The vmstat statistic corresponding to the list on which the page was
2093 * found will be decremented.
2094 *
2095 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002096 *
Nick Piggin62695a82008-10-18 20:26:09 -07002097 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002098 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002099 * without a stable reference).
2100 * (2) the lru_lock must not be held.
2101 * (3) interrupts must be enabled.
2102 */
2103int isolate_lru_page(struct page *page)
2104{
2105 int ret = -EBUSY;
2106
Sasha Levin309381fea2014-01-23 15:52:54 -08002107 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002108 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002109
Alex Shid25b5bd2020-12-15 12:34:16 -08002110 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002111 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002112
Alex Shid25b5bd2020-12-15 12:34:16 -08002113 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002114 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002115 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002116 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002117 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002118 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002119
Nick Piggin62695a82008-10-18 20:26:09 -07002120 return ret;
2121}
2122
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002123/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002124 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002125 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002126 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2127 * the LRU list will go small and be scanned faster than necessary, leading to
2128 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002129 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002130static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002131 struct scan_control *sc)
2132{
2133 unsigned long inactive, isolated;
2134
2135 if (current_is_kswapd())
2136 return 0;
2137
Johannes Weinerb5ead352019-11-30 17:55:40 -08002138 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002139 return 0;
2140
2141 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002142 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2143 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002144 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002145 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2146 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002147 }
2148
Fengguang Wu3cf23842012-12-18 14:23:31 -08002149 /*
2150 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2151 * won't get blocked by normal direct-reclaimers, forming a circular
2152 * deadlock.
2153 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002154 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002155 inactive >>= 3;
2156
Rik van Riel35cd7812009-09-21 17:01:38 -07002157 return isolated > inactive;
2158}
2159
Kirill Tkhaia222f342019-05-13 17:17:00 -07002160/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002161 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2162 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002163 *
2164 * Returns the number of pages moved to the given lruvec.
2165 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002166static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2167 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002168{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002169 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002170 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002171 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002172
Kirill Tkhaia222f342019-05-13 17:17:00 -07002173 while (!list_empty(list)) {
2174 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002175 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002176 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002177 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002178 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002179 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002180 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002181 continue;
2182 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002183
Alex Shi3d06afa2020-12-15 12:33:37 -08002184 /*
2185 * The SetPageLRU needs to be kept here for list integrity.
2186 * Otherwise:
2187 * #0 move_pages_to_lru #1 release_pages
2188 * if !put_page_testzero
2189 * if (put_page_testzero())
2190 * !PageLRU //skip lru_lock
2191 * SetPageLRU()
2192 * list_add(&page->lru,)
2193 * list_add(&page->lru,)
2194 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002195 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002196
Alex Shi3d06afa2020-12-15 12:33:37 -08002197 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002198 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002199
2200 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002201 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002202 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002203 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002204 } else
2205 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002206
2207 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002208 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002209
Alex Shiafca9152020-12-15 12:34:02 -08002210 /*
2211 * All pages were isolated from the same lruvec (and isolation
2212 * inhibits memcg migration).
2213 */
Muchun Song7467c392021-06-28 19:37:59 -07002214 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002215 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002216 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002217 nr_moved += nr_pages;
2218 if (PageActive(page))
2219 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002220 }
Mel Gorman66635622010-08-09 17:19:30 -07002221
Hugh Dickins3f797682012-01-12 17:20:07 -08002222 /*
2223 * To save our caller's stack, now use input list for pages to free.
2224 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002225 list_splice(&pages_to_free, list);
2226
2227 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002228}
2229
2230/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002231 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002232 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002233 * In that case we should only throttle if the backing device it is
2234 * writing to is congested. In other cases it is safe to throttle.
2235 */
2236static int current_may_throttle(void)
2237{
NeilBrowna37b0712020-06-01 21:48:18 -07002238 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002239 current->backing_dev_info == NULL ||
2240 bdi_write_congested(current->backing_dev_info);
2241}
2242
2243/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002244 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002245 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002246 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002247static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002248shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002249 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002250{
2251 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002252 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002253 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002254 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002255 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002256 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002257 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002258 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002259 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002260
Mel Gorman599d0c92016-07-28 15:45:31 -07002261 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002262 if (stalled)
2263 return 0;
2264
2265 /* wait a bit for the reclaimer. */
2266 msleep(100);
2267 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002268
2269 /* We are about to die and free our memory. Return now. */
2270 if (fatal_signal_pending(current))
2271 return SWAP_CLUSTER_MAX;
2272 }
2273
Linus Torvalds1da177e2005-04-16 15:20:36 -07002274 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002275
Alex Shi6168d0d2020-12-15 12:34:29 -08002276 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002277
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002278 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002279 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002280
Mel Gorman599d0c92016-07-28 15:45:31 -07002281 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002282 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002283 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002284 __count_vm_events(item, nr_scanned);
2285 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002286 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2287
Alex Shi6168d0d2020-12-15 12:34:29 -08002288 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002289
Hillf Dantond563c052012-03-21 16:34:02 -07002290 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002291 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002292
Shakeel Butt013339d2020-12-14 19:06:39 -08002293 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002294
Alex Shi6168d0d2020-12-15 12:34:29 -08002295 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002296 move_pages_to_lru(lruvec, &page_list);
2297
2298 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002299 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002300 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002301 __count_vm_events(item, nr_reclaimed);
2302 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002303 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002304 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002305
Alex Shi75cc3c92020-12-15 14:20:50 -08002306 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002307 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002308 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002309
Mel Gorman92df3a72011-10-31 17:07:56 -07002310 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002311 * If dirty pages are scanned that are not queued for IO, it
2312 * implies that flushers are not doing their job. This can
2313 * happen when memory pressure pushes dirty pages to the end of
2314 * the LRU before the dirty limits are breached and the dirty
2315 * data has expired. It can also happen when the proportion of
2316 * dirty pages grows not through writes but through memory
2317 * pressure reclaiming all the clean cache. And in some cases,
2318 * the flushers simply cannot keep up with the allocation
2319 * rate. Nudge the flusher threads in case they are asleep.
2320 */
2321 if (stat.nr_unqueued_dirty == nr_taken)
2322 wakeup_flusher_threads(WB_REASON_VMSCAN);
2323
Andrey Ryabinind108c772018-04-10 16:27:59 -07002324 sc->nr.dirty += stat.nr_dirty;
2325 sc->nr.congested += stat.nr_congested;
2326 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2327 sc->nr.writeback += stat.nr_writeback;
2328 sc->nr.immediate += stat.nr_immediate;
2329 sc->nr.taken += nr_taken;
2330 if (file)
2331 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002332
Mel Gorman599d0c92016-07-28 15:45:31 -07002333 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002334 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002335 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002336}
2337
Hugh Dickins15b44732020-12-15 14:21:31 -08002338/*
2339 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2340 *
2341 * We move them the other way if the page is referenced by one or more
2342 * processes.
2343 *
2344 * If the pages are mostly unmapped, the processing is fast and it is
2345 * appropriate to hold lru_lock across the whole operation. But if
2346 * the pages are mapped, the processing is slow (page_referenced()), so
2347 * we should drop lru_lock around each page. It's impossible to balance
2348 * this, so instead we remove the pages from the LRU while processing them.
2349 * It is safe to rely on PG_active against the non-LRU pages in here because
2350 * nobody will play with that bit on a non-LRU page.
2351 *
2352 * The downside is that we have to touch page->_refcount against each page.
2353 * But we had to alter page->flags anyway.
2354 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002355static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002356 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002357 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002358 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002359{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002360 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002361 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002362 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002363 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002364 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002365 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002366 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002367 unsigned nr_deactivate, nr_activate;
2368 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002369 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002370 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002371
2372 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002373
Alex Shi6168d0d2020-12-15 12:34:29 -08002374 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002375
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002376 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002377 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002378
Mel Gorman599d0c92016-07-28 15:45:31 -07002379 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002380
Shakeel Butt912c0572020-08-06 23:26:32 -07002381 if (!cgroup_reclaim(sc))
2382 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002383 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002384
Alex Shi6168d0d2020-12-15 12:34:29 -08002385 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002386
Linus Torvalds1da177e2005-04-16 15:20:36 -07002387 while (!list_empty(&l_hold)) {
2388 cond_resched();
2389 page = lru_to_page(&l_hold);
2390 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002391
Hugh Dickins39b5f292012-10-08 16:33:18 -07002392 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002393 putback_lru_page(page);
2394 continue;
2395 }
2396
Mel Gormancc715d92012-03-21 16:34:00 -07002397 if (unlikely(buffer_heads_over_limit)) {
2398 if (page_has_private(page) && trylock_page(page)) {
2399 if (page_has_private(page))
2400 try_to_release_page(page, 0);
2401 unlock_page(page);
2402 }
2403 }
2404
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002405 if (page_referenced(page, 0, sc->target_mem_cgroup,
2406 &vm_flags)) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002407 /*
2408 * Identify referenced, file-backed active pages and
2409 * give them one more trip around the active list. So
2410 * that executable code get better chances to stay in
2411 * memory under moderate memory pressure. Anon pages
2412 * are not likely to be evicted by use-once streaming
2413 * IO, plus JVM can create lots of anon VM_EXEC pages,
2414 * so we ignore them here.
2415 */
Huang Ying9de4f222020-04-06 20:04:41 -07002416 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002417 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002418 list_add(&page->lru, &l_active);
2419 continue;
2420 }
2421 }
Rik van Riel7e9cd482008-10-18 20:26:35 -07002422
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002423 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002424 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002425 list_add(&page->lru, &l_inactive);
2426 }
2427
Andrew Mortonb5557492009-01-06 14:40:13 -08002428 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002429 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002430 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002431 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002432
Kirill Tkhaia222f342019-05-13 17:17:00 -07002433 nr_activate = move_pages_to_lru(lruvec, &l_active);
2434 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002435 /* Keep all free pages in l_active list */
2436 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002437
2438 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2439 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2440
Mel Gorman599d0c92016-07-28 15:45:31 -07002441 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002442 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002443
Kirill Tkhaif372d892019-05-13 17:16:57 -07002444 mem_cgroup_uncharge_list(&l_active);
2445 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002446 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2447 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002448}
2449
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002450unsigned long reclaim_pages(struct list_head *page_list)
2451{
Yang Shif661d002020-04-01 21:10:05 -07002452 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002453 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002454 LIST_HEAD(node_page_list);
2455 struct reclaim_stat dummy_stat;
2456 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002457 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002458 struct scan_control sc = {
2459 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002460 .may_writepage = 1,
2461 .may_unmap = 1,
2462 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002463 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002464 };
2465
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002466 noreclaim_flag = memalloc_noreclaim_save();
2467
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002468 while (!list_empty(page_list)) {
2469 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002470 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002471 nid = page_to_nid(page);
2472 INIT_LIST_HEAD(&node_page_list);
2473 }
2474
2475 if (nid == page_to_nid(page)) {
2476 ClearPageActive(page);
2477 list_move(&page->lru, &node_page_list);
2478 continue;
2479 }
2480
2481 nr_reclaimed += shrink_page_list(&node_page_list,
2482 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002483 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002484 while (!list_empty(&node_page_list)) {
2485 page = lru_to_page(&node_page_list);
2486 list_del(&page->lru);
2487 putback_lru_page(page);
2488 }
2489
Yang Shif661d002020-04-01 21:10:05 -07002490 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002491 }
2492
2493 if (!list_empty(&node_page_list)) {
2494 nr_reclaimed += shrink_page_list(&node_page_list,
2495 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002496 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002497 while (!list_empty(&node_page_list)) {
2498 page = lru_to_page(&node_page_list);
2499 list_del(&page->lru);
2500 putback_lru_page(page);
2501 }
2502 }
2503
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002504 memalloc_noreclaim_restore(noreclaim_flag);
2505
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002506 return nr_reclaimed;
2507}
2508
Johannes Weinerb91ac372019-11-30 17:56:02 -08002509static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2510 struct lruvec *lruvec, struct scan_control *sc)
2511{
2512 if (is_active_lru(lru)) {
2513 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2514 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2515 else
2516 sc->skipped_deactivate = 1;
2517 return 0;
2518 }
2519
2520 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2521}
2522
Rik van Riel59dc76b2016-05-20 16:56:31 -07002523/*
2524 * The inactive anon list should be small enough that the VM never has
2525 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002526 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002527 * The inactive file list should be small enough to leave most memory
2528 * to the established workingset on the scan-resistant active list,
2529 * but large enough to avoid thrashing the aggregate readahead window.
2530 *
2531 * Both inactive lists should also be large enough that each inactive
2532 * page has a chance to be referenced again before it is reclaimed.
2533 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002534 * If that fails and refaulting is observed, the inactive list grows.
2535 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002536 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002537 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002538 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2539 *
2540 * total target max
2541 * memory ratio inactive
2542 * -------------------------------------
2543 * 10MB 1 5MB
2544 * 100MB 1 50MB
2545 * 1GB 3 250MB
2546 * 10GB 10 0.9GB
2547 * 100GB 31 3GB
2548 * 1TB 101 10GB
2549 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002550 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002551static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002552{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002553 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002554 unsigned long inactive, active;
2555 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002556 unsigned long gb;
2557
Johannes Weinerb91ac372019-11-30 17:56:02 -08002558 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2559 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002560
Johannes Weinerb91ac372019-11-30 17:56:02 -08002561 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002562 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002563 inactive_ratio = int_sqrt(10 * gb);
2564 else
2565 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002566
Rik van Riel59dc76b2016-05-20 16:56:31 -07002567 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002568}
2569
Johannes Weiner9a265112013-02-22 16:32:17 -08002570enum scan_balance {
2571 SCAN_EQUAL,
2572 SCAN_FRACT,
2573 SCAN_ANON,
2574 SCAN_FILE,
2575};
2576
Yu Zhao3eb07702020-09-27 20:49:08 -06002577static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2578{
2579 unsigned long file;
2580 struct lruvec *target_lruvec;
2581
Yu Zhaoa1537a62022-01-27 20:32:37 -07002582 if (lru_gen_enabled())
2583 return;
2584
Yu Zhao3eb07702020-09-27 20:49:08 -06002585 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2586
2587 /*
2588 * Flush the memory cgroup stats, so that we read accurate per-memcg
2589 * lruvec stats for heuristics.
2590 */
2591 mem_cgroup_flush_stats();
2592
2593 /*
2594 * Determine the scan balance between anon and file LRUs.
2595 */
2596 spin_lock_irq(&target_lruvec->lru_lock);
2597 sc->anon_cost = target_lruvec->anon_cost;
2598 sc->file_cost = target_lruvec->file_cost;
2599 spin_unlock_irq(&target_lruvec->lru_lock);
2600
2601 /*
2602 * Target desirable inactive:active list ratios for the anon
2603 * and file LRU lists.
2604 */
2605 if (!sc->force_deactivate) {
2606 unsigned long refaults;
2607
2608 refaults = lruvec_page_state(target_lruvec,
2609 WORKINGSET_ACTIVATE_ANON);
2610 if (refaults != target_lruvec->refaults[0] ||
2611 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2612 sc->may_deactivate |= DEACTIVATE_ANON;
2613 else
2614 sc->may_deactivate &= ~DEACTIVATE_ANON;
2615
2616 /*
2617 * When refaults are being observed, it means a new
2618 * workingset is being established. Deactivate to get
2619 * rid of any stale active pages quickly.
2620 */
2621 refaults = lruvec_page_state(target_lruvec,
2622 WORKINGSET_ACTIVATE_FILE);
2623 if (refaults != target_lruvec->refaults[1] ||
2624 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2625 sc->may_deactivate |= DEACTIVATE_FILE;
2626 else
2627 sc->may_deactivate &= ~DEACTIVATE_FILE;
2628 } else
2629 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2630
2631 /*
2632 * If we have plenty of inactive file pages that aren't
2633 * thrashing, try to reclaim those first before touching
2634 * anonymous pages.
2635 */
2636 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2637 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2638 sc->cache_trim_mode = 1;
2639 else
2640 sc->cache_trim_mode = 0;
2641
2642 /*
2643 * Prevent the reclaimer from falling into the cache trap: as
2644 * cache pages start out inactive, every cache fault will tip
2645 * the scan balance towards the file LRU. And as the file LRU
2646 * shrinks, so does the window for rotation from references.
2647 * This means we have a runaway feedback loop where a tiny
2648 * thrashing file LRU becomes infinitely more attractive than
2649 * anon pages. Try to detect this based on file LRU size.
2650 */
2651 if (!cgroup_reclaim(sc)) {
2652 unsigned long total_high_wmark = 0;
2653 unsigned long free, anon;
2654 int z;
2655
2656 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2657 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2658 node_page_state(pgdat, NR_INACTIVE_FILE);
2659
2660 for (z = 0; z < MAX_NR_ZONES; z++) {
2661 struct zone *zone = &pgdat->node_zones[z];
2662
2663 if (!managed_zone(zone))
2664 continue;
2665
2666 total_high_wmark += high_wmark_pages(zone);
2667 }
2668
2669 /*
2670 * Consider anon: if that's low too, this isn't a
2671 * runaway file reclaim problem, but rather just
2672 * extreme pressure. Reclaim as per usual then.
2673 */
2674 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2675
2676 sc->file_is_tiny =
2677 file + free <= total_high_wmark &&
2678 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2679 anon >> sc->priority;
2680 }
2681}
2682
Linus Torvalds1da177e2005-04-16 15:20:36 -07002683/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002684 * Determine how aggressively the anon and file LRU lists should be
2685 * scanned. The relative value of each set of LRU lists is determined
2686 * by looking at the fraction of the pages scanned we did rotate back
2687 * onto the active list instead of evict.
2688 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002689 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2690 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002691 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002692static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2693 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002694{
Keith Buscha2a36482021-09-02 14:59:26 -07002695 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002696 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002697 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002698 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002699 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002700 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002701 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002702 unsigned long ap, fp;
2703 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002704 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002705
2706 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002707 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002708 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002709 goto out;
2710 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002711
Johannes Weiner10316b32013-02-22 16:32:14 -08002712 /*
2713 * Global reclaim will swap to prevent OOM even with no
2714 * swappiness, but memcg users want to use this knob to
2715 * disable swapping for individual groups completely when
2716 * using the memory controller's swap limit feature would be
2717 * too expensive.
2718 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002719 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002720 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002721 goto out;
2722 }
2723
2724 /*
2725 * Do not apply any pressure balancing cleverness when the
2726 * system is close to OOM, scan both anon and file equally
2727 * (unless the swappiness setting disagrees with swapping).
2728 */
Johannes Weiner02695172014-08-06 16:06:17 -07002729 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002730 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002731 goto out;
2732 }
2733
Johannes Weiner11d16c22013-02-22 16:32:15 -08002734 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002735 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002736 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002737 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002738 scan_balance = SCAN_ANON;
2739 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002740 }
2741
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002742 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2743
Johannes Weiner62376252014-05-06 12:50:07 -07002744 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002745 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002746 * anything from the anonymous working right now. But when balancing
2747 * anon and page cache files for reclaim, allow swapping of anon pages
2748 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002749 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002750 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002751 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002752 goto out;
2753 }
2754
Johannes Weiner9a265112013-02-22 16:32:17 -08002755 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002756 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002757 * Calculate the pressure balance between anon and file pages.
2758 *
2759 * The amount of pressure we put on each LRU is inversely
2760 * proportional to the cost of reclaiming each list, as
2761 * determined by the share of pages that are refaulting, times
2762 * the relative IO cost of bringing back a swapped out
2763 * anonymous page vs reloading a filesystem page (swappiness).
2764 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002765 * Although we limit that influence to ensure no list gets
2766 * left behind completely: at least a third of the pressure is
2767 * applied, before swappiness.
2768 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002769 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002770 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002771 total_cost = sc->anon_cost + sc->file_cost;
2772 anon_cost = total_cost + sc->anon_cost;
2773 file_cost = total_cost + sc->file_cost;
2774 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002775
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002776 ap = swappiness * (total_cost + 1);
2777 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002778
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002779 fp = (200 - swappiness) * (total_cost + 1);
2780 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002781
Shaohua Li76a33fc2010-05-24 14:32:36 -07002782 fraction[0] = ap;
2783 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002784 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002785out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002786 for_each_evictable_lru(lru) {
2787 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002788 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002789 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002790 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002791
Chris Down9783aa92019-10-06 17:58:32 -07002792 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002793 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2794 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002795
Johannes Weinerf56ce412021-08-19 19:04:21 -07002796 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002797 /*
2798 * Scale a cgroup's reclaim pressure by proportioning
2799 * its current usage to its memory.low or memory.min
2800 * setting.
2801 *
2802 * This is important, as otherwise scanning aggression
2803 * becomes extremely binary -- from nothing as we
2804 * approach the memory protection threshold, to totally
2805 * nominal as we exceed it. This results in requiring
2806 * setting extremely liberal protection thresholds. It
2807 * also means we simply get no protection at all if we
2808 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002809 *
2810 * If there is any protection in place, we reduce scan
2811 * pressure by how much of the total memory used is
2812 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002813 *
Chris Down9de7ca42019-10-06 17:58:35 -07002814 * There is one special case: in the first reclaim pass,
2815 * we skip over all groups that are within their low
2816 * protection. If that fails to reclaim enough pages to
2817 * satisfy the reclaim goal, we come back and override
2818 * the best-effort low protection. However, we still
2819 * ideally want to honor how well-behaved groups are in
2820 * that case instead of simply punishing them all
2821 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002822 * memory they are using, reducing the scan pressure
2823 * again by how much of the total memory used is under
2824 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002825 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002826 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002827 unsigned long protection;
2828
2829 /* memory.low scaling, make sure we retry before OOM */
2830 if (!sc->memcg_low_reclaim && low > min) {
2831 protection = low;
2832 sc->memcg_low_skipped = 1;
2833 } else {
2834 protection = min;
2835 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002836
2837 /* Avoid TOCTOU with earlier protection check */
2838 cgroup_size = max(cgroup_size, protection);
2839
2840 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002841 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002842
2843 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002844 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002845 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002846 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002847 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002848 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002849 } else {
2850 scan = lruvec_size;
2851 }
2852
2853 scan >>= sc->priority;
2854
Johannes Weiner688035f2017-05-03 14:52:07 -07002855 /*
2856 * If the cgroup's already been deleted, make sure to
2857 * scrape out the remaining cache.
2858 */
2859 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002860 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002861
Johannes Weiner688035f2017-05-03 14:52:07 -07002862 switch (scan_balance) {
2863 case SCAN_EQUAL:
2864 /* Scan lists relative to size */
2865 break;
2866 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002867 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002868 * Scan types proportional to swappiness and
2869 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002870 * Make sure we don't miss the last page on
2871 * the offlined memory cgroups because of a
2872 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002873 */
Gavin Shan76073c62020-02-20 20:04:24 -08002874 scan = mem_cgroup_online(memcg) ?
2875 div64_u64(scan * fraction[file], denominator) :
2876 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002877 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002878 break;
2879 case SCAN_FILE:
2880 case SCAN_ANON:
2881 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002882 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002883 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002884 break;
2885 default:
2886 /* Look ma, no brain */
2887 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002888 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002889
Johannes Weiner688035f2017-05-03 14:52:07 -07002890 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002891 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002892}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002893
Dave Hansen2f368a92021-09-02 14:59:23 -07002894/*
2895 * Anonymous LRU management is a waste if there is
2896 * ultimately no way to reclaim the memory.
2897 */
2898static bool can_age_anon_pages(struct pglist_data *pgdat,
2899 struct scan_control *sc)
2900{
2901 /* Aging the anon LRU is valuable if swap is present: */
2902 if (total_swap_pages > 0)
2903 return true;
2904
2905 /* Also valuable if anon pages can be demoted: */
2906 return can_demote(pgdat->node_id, sc);
2907}
2908
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002909#ifdef CONFIG_LRU_GEN
2910
2911/******************************************************************************
2912 * shorthand helpers
2913 ******************************************************************************/
2914
Yu Zhaoa1537a62022-01-27 20:32:37 -07002915#define DEFINE_MAX_SEQ(lruvec) \
2916 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2917
2918#define DEFINE_MIN_SEQ(lruvec) \
2919 unsigned long min_seq[ANON_AND_FILE] = { \
2920 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2921 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2922 }
2923
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002924#define for_each_gen_type_zone(gen, type, zone) \
2925 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2926 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2927 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2928
Yu Zhaoa1537a62022-01-27 20:32:37 -07002929static int page_lru_gen(struct page *page)
2930{
2931 unsigned long flags = READ_ONCE(page->flags);
2932
2933 return ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
2934}
2935
2936static int page_lru_tier(struct page *page)
2937{
2938 int refs;
2939 unsigned long flags = READ_ONCE(page->flags);
2940
2941 refs = (flags & LRU_REFS_FLAGS) == LRU_REFS_FLAGS ?
2942 ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) + 1 : 0;
2943
2944 return lru_tier_from_refs(refs);
2945}
2946
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002947static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
2948{
2949 struct pglist_data *pgdat = NODE_DATA(nid);
2950
2951#ifdef CONFIG_MEMCG
2952 if (memcg) {
2953 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2954
2955 /* for hotadd_new_pgdat() */
2956 if (!lruvec->pgdat)
2957 lruvec->pgdat = pgdat;
2958
2959 return lruvec;
2960 }
2961#endif
2962 VM_BUG_ON(!mem_cgroup_disabled());
2963
2964 return pgdat ? &pgdat->__lruvec : NULL;
2965}
2966
Yu Zhaoa1537a62022-01-27 20:32:37 -07002967static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2968{
2969 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2970 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2971
2972 if (!can_demote(pgdat->node_id, sc) &&
2973 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2974 return 0;
2975
2976 return mem_cgroup_swappiness(memcg);
2977}
2978
2979static int get_nr_gens(struct lruvec *lruvec, int type)
2980{
2981 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2982}
2983
2984static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2985{
2986 /* see the comment on lru_gen_struct */
2987 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2988 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2989 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2990}
2991
2992/******************************************************************************
Yu Zhao5280d762022-01-27 19:23:01 -07002993 * mm_struct list
2994 ******************************************************************************/
2995
2996static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
2997{
2998 static struct lru_gen_mm_list mm_list = {
2999 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3000 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3001 };
3002
3003#ifdef CONFIG_MEMCG
3004 if (memcg)
3005 return &memcg->mm_list;
3006#endif
3007 VM_BUG_ON(!mem_cgroup_disabled());
3008
3009 return &mm_list;
3010}
3011
3012void lru_gen_add_mm(struct mm_struct *mm)
3013{
3014 int nid;
3015 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3016 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3017
3018 VM_BUG_ON_MM(!list_empty(&mm->lru_gen.list), mm);
3019#ifdef CONFIG_MEMCG
3020 VM_BUG_ON_MM(mm->lru_gen.memcg, mm);
3021 mm->lru_gen.memcg = memcg;
3022#endif
3023 spin_lock(&mm_list->lock);
3024
3025 for_each_node_state(nid, N_MEMORY) {
3026 struct lruvec *lruvec = get_lruvec(memcg, nid);
3027
3028 if (!lruvec)
3029 continue;
3030
3031 if (lruvec->mm_state.tail == &mm_list->fifo)
3032 lruvec->mm_state.tail = &mm->lru_gen.list;
3033 }
3034
3035 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3036
3037 spin_unlock(&mm_list->lock);
3038}
3039
3040void lru_gen_del_mm(struct mm_struct *mm)
3041{
3042 int nid;
3043 struct lru_gen_mm_list *mm_list;
3044 struct mem_cgroup *memcg = NULL;
3045
3046 if (list_empty(&mm->lru_gen.list))
3047 return;
3048
3049#ifdef CONFIG_MEMCG
3050 memcg = mm->lru_gen.memcg;
3051#endif
3052 mm_list = get_mm_list(memcg);
3053
3054 spin_lock(&mm_list->lock);
3055
3056 for_each_node(nid) {
3057 struct lruvec *lruvec = get_lruvec(memcg, nid);
3058
3059 if (!lruvec)
3060 continue;
3061
3062 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3063 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3064
3065 if (lruvec->mm_state.head != &mm->lru_gen.list)
3066 continue;
3067
3068 lruvec->mm_state.head = lruvec->mm_state.head->next;
3069 if (lruvec->mm_state.head == &mm_list->fifo)
3070 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3071 }
3072
3073 list_del_init(&mm->lru_gen.list);
3074
3075 spin_unlock(&mm_list->lock);
3076
3077#ifdef CONFIG_MEMCG
3078 mem_cgroup_put(mm->lru_gen.memcg);
3079 mm->lru_gen.memcg = NULL;
3080#endif
3081}
3082
3083#ifdef CONFIG_MEMCG
3084void lru_gen_migrate_mm(struct mm_struct *mm)
3085{
3086 struct mem_cgroup *memcg;
3087
3088 lockdep_assert_held(&mm->owner->alloc_lock);
3089
3090 /* for mm_update_next_owner() */
3091 if (mem_cgroup_disabled())
3092 return;
3093
3094 rcu_read_lock();
3095 memcg = mem_cgroup_from_task(mm->owner);
3096 rcu_read_unlock();
3097 if (memcg == mm->lru_gen.memcg)
3098 return;
3099
3100 VM_BUG_ON_MM(!mm->lru_gen.memcg, mm);
3101 VM_BUG_ON_MM(list_empty(&mm->lru_gen.list), mm);
3102
3103 lru_gen_del_mm(mm);
3104 lru_gen_add_mm(mm);
3105}
3106#endif
3107
3108/*
3109 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3110 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3111 * bits in a bitmap, k is the number of hash functions and n is the number of
3112 * inserted items.
3113 *
3114 * Page table walkers use one of the two filters to reduce their search space.
3115 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3116 * aging uses the double-buffering technique to flip to the other filter each
3117 * time it produces a new generation. For non-leaf entries that have enough
3118 * leaf entries, the aging carries them over to the next generation in
3119 * walk_pmd_range(); the eviction also report them when walking the rmap
3120 * in lru_gen_look_around().
3121 *
3122 * For future optimizations:
3123 * 1. It's not necessary to keep both filters all the time. The spare one can be
3124 * freed after the RCU grace period and reallocated if needed again.
3125 * 2. And when reallocating, it's worth scaling its size according to the number
3126 * of inserted entries in the other filter, to reduce the memory overhead on
3127 * small systems and false positives on large systems.
3128 * 3. Jenkins' hash function is an alternative to Knuth's.
3129 */
3130#define BLOOM_FILTER_SHIFT 15
3131
3132static inline int filter_gen_from_seq(unsigned long seq)
3133{
3134 return seq % NR_BLOOM_FILTERS;
3135}
3136
3137static void get_item_key(void *item, int *key)
3138{
3139 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3140
3141 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3142
3143 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3144 key[1] = hash >> BLOOM_FILTER_SHIFT;
3145}
3146
3147static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3148{
3149 unsigned long *filter;
3150 int gen = filter_gen_from_seq(seq);
3151
3152 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3153
3154 filter = lruvec->mm_state.filters[gen];
3155 if (filter) {
3156 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3157 return;
3158 }
3159
3160 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT), GFP_ATOMIC);
3161 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3162}
3163
3164static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3165{
3166 int key[2];
3167 unsigned long *filter;
3168 int gen = filter_gen_from_seq(seq);
3169
3170 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3171 if (!filter)
3172 return;
3173
3174 get_item_key(item, key);
3175
3176 if (!test_bit(key[0], filter))
3177 set_bit(key[0], filter);
3178 if (!test_bit(key[1], filter))
3179 set_bit(key[1], filter);
3180}
3181
3182static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3183{
3184 int key[2];
3185 unsigned long *filter;
3186 int gen = filter_gen_from_seq(seq);
3187
3188 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3189 if (!filter)
3190 return true;
3191
3192 get_item_key(item, key);
3193
3194 return test_bit(key[0], filter) && test_bit(key[1], filter);
3195}
3196
3197static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3198{
3199 int i;
3200 int hist;
3201
3202 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3203
3204 if (walk) {
3205 hist = lru_hist_from_seq(walk->max_seq);
3206
3207 for (i = 0; i < NR_MM_STATS; i++) {
3208 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3209 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3210 walk->mm_stats[i] = 0;
3211 }
3212 }
3213
3214 if (NR_HIST_GENS > 1 && last) {
3215 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3216
3217 for (i = 0; i < NR_MM_STATS; i++)
3218 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3219 }
3220}
3221
3222static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3223{
3224 int type;
3225 unsigned long size = 0;
3226 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3227
3228 if (!walk->full_scan && cpumask_empty(mm_cpumask(mm)) &&
3229 !node_isset(pgdat->node_id, mm->lru_gen.nodes))
3230 return true;
3231
3232 node_clear(pgdat->node_id, mm->lru_gen.nodes);
3233
3234 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3235 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3236 get_mm_counter(mm, MM_ANONPAGES) +
3237 get_mm_counter(mm, MM_SHMEMPAGES);
3238 }
3239
3240 if (size < MIN_LRU_BATCH)
3241 return true;
3242
3243 if (mm_is_oom_victim(mm))
3244 return true;
3245
3246 return !mmget_not_zero(mm);
3247}
3248
3249static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3250 struct mm_struct **iter)
3251{
3252 bool first = false;
3253 bool last = true;
3254 struct mm_struct *mm = NULL;
3255 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3256 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3257 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3258
3259 /*
3260 * There are four interesting cases for this page table walker:
3261 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3262 * there is nothing to be done.
3263 * 2. It's the first of the current generation, and it needs to reset
3264 * the Bloom filter for the next generation.
3265 * 3. It reaches the end of mm_list, and it needs to increment
3266 * mm_state->seq; the iteration is done.
3267 * 4. It's the last of the current generation, and it needs to reset the
3268 * mm stats counters for the next generation.
3269 */
3270 if (*iter)
3271 mmput_async(*iter);
3272 else if (walk->max_seq <= READ_ONCE(mm_state->seq))
3273 return false;
3274
3275 spin_lock(&mm_list->lock);
3276
3277 VM_BUG_ON(mm_state->seq + 1 < walk->max_seq);
3278 VM_BUG_ON(*iter && mm_state->seq > walk->max_seq);
3279 VM_BUG_ON(*iter && !mm_state->nr_walkers);
3280
3281 if (walk->max_seq <= mm_state->seq) {
3282 if (!*iter)
3283 last = false;
3284 goto done;
3285 }
3286
3287 if (!mm_state->nr_walkers) {
3288 VM_BUG_ON(mm_state->head && mm_state->head != &mm_list->fifo);
3289
3290 mm_state->head = mm_list->fifo.next;
3291 first = true;
3292 }
3293
3294 while (!mm && mm_state->head != &mm_list->fifo) {
3295 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3296
3297 mm_state->head = mm_state->head->next;
3298
3299 /* full scan for those added after the last iteration */
3300 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3301 mm_state->tail = mm_state->head;
3302 walk->full_scan = true;
3303 }
3304
3305 if (should_skip_mm(mm, walk))
3306 mm = NULL;
3307 }
3308
3309 if (mm_state->head == &mm_list->fifo)
3310 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3311done:
3312 if (*iter && !mm)
3313 mm_state->nr_walkers--;
3314 if (!*iter && mm)
3315 mm_state->nr_walkers++;
3316
3317 if (mm_state->nr_walkers)
3318 last = false;
3319
3320 if (mm && first)
3321 reset_bloom_filter(lruvec, walk->max_seq + 1);
3322
3323 if (*iter || last)
3324 reset_mm_stats(lruvec, walk, last);
3325
3326 spin_unlock(&mm_list->lock);
3327
3328 *iter = mm;
3329
3330 return last;
3331}
3332
3333static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3334{
3335 bool success = false;
3336 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3337 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3338 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3339
3340 if (max_seq <= READ_ONCE(mm_state->seq))
3341 return false;
3342
3343 spin_lock(&mm_list->lock);
3344
3345 VM_BUG_ON(mm_state->seq + 1 < max_seq);
3346
3347 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3348 VM_BUG_ON(mm_state->head && mm_state->head != &mm_list->fifo);
3349
3350 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3351 reset_mm_stats(lruvec, NULL, true);
3352 success = true;
3353 }
3354
3355 spin_unlock(&mm_list->lock);
3356
3357 return success;
3358}
3359
3360/******************************************************************************
Yu Zhaoa1537a62022-01-27 20:32:37 -07003361 * refault feedback loop
3362 ******************************************************************************/
3363
3364/*
3365 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3366 *
3367 * The P term is refaulted/(evicted+protected) from a tier in the generation
3368 * currently being evicted; the I term is the exponential moving average of the
3369 * P term over the generations previously evicted, using the smoothing factor
3370 * 1/2; the D term isn't supported.
3371 *
3372 * The setpoint (SP) is always the first tier of one type; the process variable
3373 * (PV) is either any tier of the other type or any other tier of the same
3374 * type.
3375 *
3376 * The error is the difference between the SP and the PV; the correction is
3377 * turn off protection when SP>PV or turn on protection when SP<PV.
3378 *
3379 * For future optimizations:
3380 * 1. The D term may discount the other two terms over time so that long-lived
3381 * generations can resist stale information.
3382 */
3383struct ctrl_pos {
3384 unsigned long refaulted;
3385 unsigned long total;
3386 int gain;
3387};
3388
3389static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3390 struct ctrl_pos *pos)
3391{
3392 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3393 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3394
3395 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3396 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3397 pos->total = lrugen->avg_total[type][tier] +
3398 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3399 if (tier)
3400 pos->total += lrugen->protected[hist][type][tier - 1];
3401 pos->gain = gain;
3402}
3403
3404static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3405{
3406 int hist, tier;
3407 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3408 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3409 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3410
3411 lockdep_assert_held(&lruvec->lru_lock);
3412
3413 if (!carryover && !clear)
3414 return;
3415
3416 hist = lru_hist_from_seq(seq);
3417
3418 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3419 if (carryover) {
3420 unsigned long sum;
3421
3422 sum = lrugen->avg_refaulted[type][tier] +
3423 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3424 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3425
3426 sum = lrugen->avg_total[type][tier] +
3427 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3428 if (tier)
3429 sum += lrugen->protected[hist][type][tier - 1];
3430 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3431 }
3432
3433 if (clear) {
3434 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3435 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3436 if (tier)
3437 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3438 }
3439 }
3440}
3441
3442static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3443{
3444 /*
3445 * Return true if the PV has a limited number of refaults or a lower
3446 * refaulted/total than the SP.
3447 */
3448 return pv->refaulted < MIN_LRU_BATCH ||
3449 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3450 (sp->refaulted + 1) * pv->total * pv->gain;
3451}
3452
3453/******************************************************************************
3454 * the aging
3455 ******************************************************************************/
3456
Yu Zhaoafd94c92022-01-27 20:43:22 -07003457static int page_update_gen(struct page *page, int gen)
3458{
3459 unsigned long old_flags, new_flags;
3460
3461 VM_BUG_ON(gen >= MAX_NR_GENS);
3462 VM_BUG_ON(!rcu_read_lock_held());
3463
3464 do {
3465 new_flags = old_flags = READ_ONCE(page->flags);
3466
3467 /* for shrink_page_list() */
3468 if (!(new_flags & LRU_GEN_MASK)) {
3469 new_flags |= BIT(PG_referenced);
3470 continue;
3471 }
3472
3473 new_flags &= ~LRU_GEN_MASK;
3474 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3475 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3476 } while (new_flags != old_flags &&
3477 cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3478
3479 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3480}
3481
Yu Zhaoa1537a62022-01-27 20:32:37 -07003482static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3483{
3484 unsigned long old_flags, new_flags;
3485 int type = page_is_file_lru(page);
3486 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3487 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3488
3489 do {
3490 new_flags = old_flags = READ_ONCE(page->flags);
3491 VM_BUG_ON_PAGE(!(new_flags & LRU_GEN_MASK), page);
3492
Yu Zhaoafd94c92022-01-27 20:43:22 -07003493 new_gen = ((new_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3494 /* page_update_gen() has promoted this page? */
3495 if (new_gen >= 0 && new_gen != old_gen)
3496 return new_gen;
3497
Yu Zhaoa1537a62022-01-27 20:32:37 -07003498 new_gen = (old_gen + 1) % MAX_NR_GENS;
3499
3500 new_flags &= ~LRU_GEN_MASK;
3501 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3502 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3503 /* for end_page_writeback() */
3504 if (reclaiming)
3505 new_flags |= BIT(PG_reclaim);
3506 } while (cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3507
3508 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3509
3510 return new_gen;
3511}
3512
Yu Zhao5280d762022-01-27 19:23:01 -07003513static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3514 int old_gen, int new_gen)
3515{
3516 int type = page_is_file_lru(page);
3517 int zone = page_zonenum(page);
3518 int delta = thp_nr_pages(page);
3519
3520 VM_BUG_ON(old_gen >= MAX_NR_GENS);
3521 VM_BUG_ON(new_gen >= MAX_NR_GENS);
3522
3523 walk->batched++;
3524
3525 walk->nr_pages[old_gen][type][zone] -= delta;
3526 walk->nr_pages[new_gen][type][zone] += delta;
3527}
3528
3529static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3530{
3531 int gen, type, zone;
3532 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3533
3534 walk->batched = 0;
3535
3536 for_each_gen_type_zone(gen, type, zone) {
3537 enum lru_list lru = type * LRU_INACTIVE_FILE;
3538 int delta = walk->nr_pages[gen][type][zone];
3539
3540 if (!delta)
3541 continue;
3542
3543 walk->nr_pages[gen][type][zone] = 0;
3544 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3545 lrugen->nr_pages[gen][type][zone] + delta);
3546
3547 if (lru_gen_is_active(lruvec, gen))
3548 lru += LRU_ACTIVE;
3549 __update_lru_size(lruvec, lru, zone, delta);
3550 }
3551}
3552
3553static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *walk)
3554{
3555 struct address_space *mapping;
3556 struct vm_area_struct *vma = walk->vma;
3557 struct lru_gen_mm_walk *priv = walk->private;
3558
3559 if (!vma_is_accessible(vma) || is_vm_hugetlb_page(vma) ||
3560 (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ)) ||
3561 vma == get_gate_vma(vma->vm_mm))
3562 return true;
3563
3564 if (vma_is_anonymous(vma))
3565 return !priv->can_swap;
3566
3567 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3568 return true;
3569
3570 mapping = vma->vm_file->f_mapping;
3571 if (mapping_unevictable(mapping))
3572 return true;
3573
3574 /* check readpage to exclude special mappings like dax, etc. */
3575 return shmem_mapping(mapping) ? !priv->can_swap : !mapping->a_ops->readpage;
3576}
3577
3578/*
3579 * Some userspace memory allocators map many single-page VMAs. Instead of
3580 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3581 * table to reduce zigzags and improve cache performance.
3582 */
3583static bool get_next_vma(struct mm_walk *walk, unsigned long mask, unsigned long size,
3584 unsigned long *start, unsigned long *end)
3585{
3586 unsigned long next = round_up(*end, size);
3587
3588 VM_BUG_ON(mask & size);
3589 VM_BUG_ON(*start >= *end);
3590 VM_BUG_ON((next & mask) != (*start & mask));
3591
3592 while (walk->vma) {
3593 if (next >= walk->vma->vm_end) {
3594 walk->vma = walk->vma->vm_next;
3595 continue;
3596 }
3597
3598 if ((next & mask) != (walk->vma->vm_start & mask))
3599 return false;
3600
3601 if (should_skip_vma(walk->vma->vm_start, walk->vma->vm_end, walk)) {
3602 walk->vma = walk->vma->vm_next;
3603 continue;
3604 }
3605
3606 *start = max(next, walk->vma->vm_start);
3607 next = (next | ~mask) + 1;
3608 /* rounded-up boundaries can wrap to 0 */
3609 *end = next && next < walk->vma->vm_end ? next : walk->vma->vm_end;
3610
3611 return true;
3612 }
3613
3614 return false;
3615}
3616
3617static bool suitable_to_scan(int total, int young)
3618{
3619 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3620
3621 /* suitable if the average number of young PTEs per cacheline is >=1 */
3622 return young * n >= total;
3623}
3624
3625static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3626 struct mm_walk *walk)
3627{
3628 int i;
3629 pte_t *pte;
3630 spinlock_t *ptl;
3631 unsigned long addr;
3632 int total = 0;
3633 int young = 0;
3634 struct lru_gen_mm_walk *priv = walk->private;
3635 struct mem_cgroup *memcg = lruvec_memcg(priv->lruvec);
3636 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3637 int old_gen, new_gen = lru_gen_from_seq(priv->max_seq);
3638
3639 VM_BUG_ON(pmd_leaf(*pmd));
3640
3641 ptl = pte_lockptr(walk->mm, pmd);
3642 if (!spin_trylock(ptl))
3643 return false;
3644
3645 arch_enter_lazy_mmu_mode();
3646
3647 pte = pte_offset_map(pmd, start & PMD_MASK);
3648restart:
3649 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3650 struct page *page;
3651 unsigned long pfn = pte_pfn(pte[i]);
3652
3653 VM_BUG_ON(addr < walk->vma->vm_start || addr >= walk->vma->vm_end);
3654
3655 total++;
3656 priv->mm_stats[MM_PTE_TOTAL]++;
3657
3658 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
3659 continue;
3660
3661 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
3662 continue;
3663
3664 if (!pte_young(pte[i])) {
3665 priv->mm_stats[MM_PTE_OLD]++;
3666 continue;
3667 }
3668
3669 VM_BUG_ON(!pfn_valid(pfn));
3670 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3671 continue;
3672
3673 page = compound_head(pfn_to_page(pfn));
3674 if (page_to_nid(page) != pgdat->node_id)
3675 continue;
3676
3677 if (page_memcg_rcu(page) != memcg)
3678 continue;
3679
3680 if (!ptep_test_and_clear_young(walk->vma, addr, pte + i))
3681 continue;
3682
3683 young++;
3684 priv->mm_stats[MM_PTE_YOUNG]++;
3685
3686 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3687 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3688 set_page_dirty(page);
3689
3690 old_gen = page_update_gen(page, new_gen);
3691 if (old_gen >= 0 && old_gen != new_gen)
3692 update_batch_size(priv, page, old_gen, new_gen);
3693 }
3694
3695 if (i < PTRS_PER_PTE && get_next_vma(walk, PMD_MASK, PAGE_SIZE, &start, &end))
3696 goto restart;
3697
3698 pte_unmap(pte);
3699
3700 arch_leave_lazy_mmu_mode();
3701 spin_unlock(ptl);
3702
3703 return suitable_to_scan(total, young);
3704}
3705
3706#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3707static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3708 struct mm_walk *walk, unsigned long *start)
3709{
3710 int i;
3711 pmd_t *pmd;
3712 spinlock_t *ptl;
3713 struct lru_gen_mm_walk *priv = walk->private;
3714 struct mem_cgroup *memcg = lruvec_memcg(priv->lruvec);
3715 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3716 int old_gen, new_gen = lru_gen_from_seq(priv->max_seq);
3717
3718 VM_BUG_ON(pud_leaf(*pud));
3719
3720 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3721 if (*start == -1) {
3722 *start = next;
3723 return;
3724 }
3725
3726 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3727 if (i && i <= MIN_LRU_BATCH) {
3728 __set_bit(i - 1, priv->bitmap);
3729 return;
3730 }
3731
3732 pmd = pmd_offset(pud, *start);
3733
3734 ptl = pmd_lockptr(walk->mm, pmd);
3735 if (!spin_trylock(ptl))
3736 goto done;
3737
3738 arch_enter_lazy_mmu_mode();
3739
3740 do {
3741 struct page *page;
3742 unsigned long pfn = pmd_pfn(pmd[i]);
3743 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3744
3745 VM_BUG_ON(addr < vma->vm_start || addr >= vma->vm_end);
3746
3747 if (!pmd_present(pmd[i]) || is_huge_zero_pmd(pmd[i]))
3748 goto next;
3749
3750 if (WARN_ON_ONCE(pmd_devmap(pmd[i])))
3751 goto next;
3752
3753 if (!pmd_trans_huge(pmd[i])) {
3754 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG))
3755 pmdp_test_and_clear_young(vma, addr, pmd + i);
3756 goto next;
3757 }
3758
3759 VM_BUG_ON(!pfn_valid(pfn));
3760 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3761 goto next;
3762
3763 page = pfn_to_page(pfn);
3764 VM_BUG_ON_PAGE(PageTail(page), page);
3765 if (page_to_nid(page) != pgdat->node_id)
3766 goto next;
3767
3768 if (page_memcg_rcu(page) != memcg)
3769 goto next;
3770
3771 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3772 goto next;
3773
3774 priv->mm_stats[MM_PTE_YOUNG]++;
3775
3776 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3777 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3778 set_page_dirty(page);
3779
3780 old_gen = page_update_gen(page, new_gen);
3781 if (old_gen >= 0 && old_gen != new_gen)
3782 update_batch_size(priv, page, old_gen, new_gen);
3783next:
3784 i = i > MIN_LRU_BATCH ? 0 :
3785 find_next_bit(priv->bitmap, MIN_LRU_BATCH, i) + 1;
3786 } while (i <= MIN_LRU_BATCH);
3787
3788 arch_leave_lazy_mmu_mode();
3789 spin_unlock(ptl);
3790done:
3791 *start = -1;
3792 bitmap_zero(priv->bitmap, MIN_LRU_BATCH);
3793}
3794#else
3795static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3796 struct mm_walk *walk, unsigned long *start)
3797{
3798}
3799#endif
3800
3801static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3802 struct mm_walk *walk)
3803{
3804 int i;
3805 pmd_t *pmd;
3806 unsigned long next;
3807 unsigned long addr;
3808 struct vm_area_struct *vma;
3809 unsigned long pos = -1;
3810 struct lru_gen_mm_walk *priv = walk->private;
3811
3812 VM_BUG_ON(pud_leaf(*pud));
3813
3814 /*
3815 * Finish an entire PMD in two passes: the first only reaches to PTE
3816 * tables to avoid taking the PMD lock; the second, if necessary, takes
3817 * the PMD lock to clear the accessed bit in PMD entries.
3818 */
3819 pmd = pmd_offset(pud, start & PUD_MASK);
3820restart:
3821 /* walk_pte_range() may call get_next_vma() */
3822 vma = walk->vma;
3823 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3824 pmd_t val = pmd_read_atomic(pmd + i);
3825
3826 /* for pmd_read_atomic() */
3827 barrier();
3828
3829 next = pmd_addr_end(addr, end);
3830
3831 if (!pmd_present(val)) {
3832 priv->mm_stats[MM_PTE_TOTAL]++;
3833 continue;
3834 }
3835
3836#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3837 if (pmd_trans_huge(val)) {
3838 unsigned long pfn = pmd_pfn(val);
3839 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3840
3841 priv->mm_stats[MM_PTE_TOTAL]++;
3842
3843 if (is_huge_zero_pmd(val))
3844 continue;
3845
3846 if (!pmd_young(val)) {
3847 priv->mm_stats[MM_PTE_OLD]++;
3848 continue;
3849 }
3850
3851 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3852 continue;
3853
3854 walk_pmd_range_locked(pud, addr, vma, walk, &pos);
3855 continue;
3856 }
3857#endif
3858 priv->mm_stats[MM_PMD_TOTAL]++;
3859
3860#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
3861 if (!pmd_young(val))
3862 continue;
3863
3864 walk_pmd_range_locked(pud, addr, vma, walk, &pos);
3865#endif
3866 if (!priv->full_scan && !test_bloom_filter(priv->lruvec, priv->max_seq, pmd + i))
3867 continue;
3868
3869 priv->mm_stats[MM_PMD_FOUND]++;
3870
3871 if (!walk_pte_range(&val, addr, next, walk))
3872 continue;
3873
3874 priv->mm_stats[MM_PMD_ADDED]++;
3875
3876 /* carry over to the next generation */
3877 update_bloom_filter(priv->lruvec, priv->max_seq + 1, pmd + i);
3878 }
3879
3880 walk_pmd_range_locked(pud, -1, vma, walk, &pos);
3881
3882 if (i < PTRS_PER_PMD && get_next_vma(walk, PUD_MASK, PMD_SIZE, &start, &end))
3883 goto restart;
3884}
3885
3886static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3887 struct mm_walk *walk)
3888{
3889 int i;
3890 pud_t *pud;
3891 unsigned long addr;
3892 unsigned long next;
3893 struct lru_gen_mm_walk *priv = walk->private;
3894
3895 VM_BUG_ON(p4d_leaf(*p4d));
3896
3897 pud = pud_offset(p4d, start & P4D_MASK);
3898restart:
3899 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3900 pud_t val = READ_ONCE(pud[i]);
3901
3902 next = pud_addr_end(addr, end);
3903
3904 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3905 continue;
3906
3907 walk_pmd_range(&val, addr, next, walk);
3908
3909 if (priv->batched >= MAX_LRU_BATCH) {
3910 end = (addr | ~PUD_MASK) + 1;
3911 goto done;
3912 }
3913 }
3914
3915 if (i < PTRS_PER_PUD && get_next_vma(walk, P4D_MASK, PUD_SIZE, &start, &end))
3916 goto restart;
3917
3918 end = round_up(end, P4D_SIZE);
3919done:
3920 /* rounded-up boundaries can wrap to 0 */
3921 priv->next_addr = end && walk->vma ? max(end, walk->vma->vm_start) : 0;
3922
3923 return -EAGAIN;
3924}
3925
3926static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3927{
3928 static const struct mm_walk_ops mm_walk_ops = {
3929 .test_walk = should_skip_vma,
3930 .p4d_entry = walk_pud_range,
3931 };
3932
3933 int err;
3934 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3935
3936 walk->next_addr = FIRST_USER_ADDRESS;
3937
3938 do {
3939 err = -EBUSY;
3940
3941 /* page_update_gen() requires stable page_memcg() */
3942 if (!mem_cgroup_trylock_pages(memcg))
3943 break;
3944
3945 /* the caller might be holding the lock for write */
3946 if (mmap_read_trylock(mm)) {
3947 unsigned long start = walk->next_addr;
3948 unsigned long end = mm->highest_vm_end;
3949
3950 err = walk_page_range(mm, start, end, &mm_walk_ops, walk);
3951
3952 mmap_read_unlock(mm);
3953
3954 if (walk->batched) {
3955 spin_lock_irq(&lruvec->lru_lock);
3956 reset_batch_size(lruvec, walk);
3957 spin_unlock_irq(&lruvec->lru_lock);
3958 }
3959 }
3960
3961 mem_cgroup_unlock_pages();
3962
3963 cond_resched();
3964 } while (err == -EAGAIN && walk->next_addr && !mm_is_oom_victim(mm));
3965}
3966
3967static struct lru_gen_mm_walk *alloc_mm_walk(void)
3968{
3969 if (current->reclaim_state && current->reclaim_state->mm_walk)
3970 return current->reclaim_state->mm_walk;
3971
3972 return kzalloc(sizeof(struct lru_gen_mm_walk),
3973 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3974}
3975
3976static void free_mm_walk(struct lru_gen_mm_walk *walk)
3977{
3978 if (!current->reclaim_state || !current->reclaim_state->mm_walk)
3979 kfree(walk);
3980}
3981
Yu Zhaoa1537a62022-01-27 20:32:37 -07003982static void inc_min_seq(struct lruvec *lruvec)
3983{
3984 int type;
3985 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3986
3987 VM_BUG_ON(!seq_is_valid(lruvec));
3988
3989 for (type = 0; type < ANON_AND_FILE; type++) {
3990 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
3991 continue;
3992
3993 reset_ctrl_pos(lruvec, type, true);
3994 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
3995 }
3996}
3997
3998static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
3999{
4000 int gen, type, zone;
4001 bool success = false;
4002 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4003 DEFINE_MIN_SEQ(lruvec);
4004
4005 VM_BUG_ON(!seq_is_valid(lruvec));
4006
4007 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4008 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4009 gen = lru_gen_from_seq(min_seq[type]);
4010
4011 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4012 if (!list_empty(&lrugen->lists[gen][type][zone]))
4013 goto next;
4014 }
4015
4016 min_seq[type]++;
4017 }
4018next:
4019 ;
4020 }
4021
4022 /* see the comment on lru_gen_struct */
4023 if (can_swap) {
4024 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4025 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4026 }
4027
4028 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4029 if (min_seq[type] == lrugen->min_seq[type])
4030 continue;
4031
4032 reset_ctrl_pos(lruvec, type, true);
4033 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4034 success = true;
4035 }
4036
4037 return success;
4038}
4039
Yu Zhao5280d762022-01-27 19:23:01 -07004040static void inc_max_seq(struct lruvec *lruvec)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004041{
4042 int prev, next;
4043 int type, zone;
4044 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4045
4046 spin_lock_irq(&lruvec->lru_lock);
4047
4048 VM_BUG_ON(!seq_is_valid(lruvec));
4049
Yu Zhaoa1537a62022-01-27 20:32:37 -07004050 inc_min_seq(lruvec);
4051
4052 /*
4053 * Update the active/inactive LRU sizes for compatibility. Both sides of
4054 * the current max_seq need to be covered, since max_seq+1 can overlap
4055 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4056 * overlap, cold/hot inversion happens. This can be solved by moving
4057 * pages from min_seq to min_seq+1 but is omitted for simplicity.
4058 */
4059 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4060 next = lru_gen_from_seq(lrugen->max_seq + 1);
4061
4062 for (type = 0; type < ANON_AND_FILE; type++) {
4063 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4064 enum lru_list lru = type * LRU_INACTIVE_FILE;
4065 long delta = lrugen->nr_pages[prev][type][zone] -
4066 lrugen->nr_pages[next][type][zone];
4067
4068 if (!delta)
4069 continue;
4070
4071 __update_lru_size(lruvec, lru, zone, delta);
4072 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4073 }
4074 }
4075
4076 for (type = 0; type < ANON_AND_FILE; type++)
4077 reset_ctrl_pos(lruvec, type, false);
4078
4079 /* make sure preceding modifications appear */
4080 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao5280d762022-01-27 19:23:01 -07004081
Yu Zhaoa1537a62022-01-27 20:32:37 -07004082 spin_unlock_irq(&lruvec->lru_lock);
4083}
4084
Yu Zhao5280d762022-01-27 19:23:01 -07004085static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4086 struct scan_control *sc, bool can_swap, bool full_scan)
4087{
4088 bool success;
4089 struct lru_gen_mm_walk *walk;
4090 struct mm_struct *mm = NULL;
4091 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4092
4093 VM_BUG_ON(max_seq > READ_ONCE(lrugen->max_seq));
4094
4095 /*
4096 * If the hardware doesn't automatically set the accessed bit, fallback
4097 * to lru_gen_look_around(), which only clears the accessed bit in a
4098 * handful of PTEs. Spreading the work out over a period of time usually
4099 * is less efficient, but it avoids bursty page faults.
4100 */
4101 if (!full_scan && !arch_has_hw_pte_young()) {
4102 success = iterate_mm_list_nowalk(lruvec, max_seq);
4103 goto done;
4104 }
4105
4106 walk = alloc_mm_walk();
4107 if (!walk) {
4108 success = iterate_mm_list_nowalk(lruvec, max_seq);
4109 goto done;
4110 }
4111
4112 walk->lruvec = lruvec;
4113 walk->max_seq = max_seq;
4114 walk->can_swap = can_swap;
4115 walk->full_scan = full_scan;
4116
4117 do {
4118 success = iterate_mm_list(lruvec, walk, &mm);
4119 if (mm)
4120 walk_mm(lruvec, mm, walk);
4121
4122 cond_resched();
4123 } while (mm);
4124
4125 free_mm_walk(walk);
4126done:
4127 if (!success) {
4128 if (!current_is_kswapd() && !sc->priority)
4129 wait_event_killable(lruvec->mm_state.wait,
4130 max_seq < READ_ONCE(lrugen->max_seq));
4131
4132 return max_seq < READ_ONCE(lrugen->max_seq);
4133 }
4134
4135 VM_BUG_ON(max_seq != READ_ONCE(lrugen->max_seq));
4136
4137 inc_max_seq(lruvec);
4138 /* either this sees any waiters or they will see updated max_seq */
4139 if (wq_has_sleeper(&lruvec->mm_state.wait))
4140 wake_up_all(&lruvec->mm_state.wait);
4141
4142 wakeup_flusher_threads(WB_REASON_VMSCAN);
4143
4144 return true;
4145}
4146
Yu Zhaoa1537a62022-01-27 20:32:37 -07004147static long get_nr_evictable(struct lruvec *lruvec, unsigned long max_seq,
4148 unsigned long *min_seq, bool can_swap, bool *need_aging)
4149{
4150 int gen, type, zone;
4151 long old = 0;
4152 long young = 0;
4153 long total = 0;
4154 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4155
4156 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4157 unsigned long seq;
4158
4159 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4160 long size = 0;
4161
4162 gen = lru_gen_from_seq(seq);
4163
4164 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4165 size += READ_ONCE(lrugen->nr_pages[gen][type][zone]);
4166
4167 total += size;
4168 if (seq == max_seq)
4169 young += size;
4170 if (seq + MIN_NR_GENS == max_seq)
4171 old += size;
4172 }
4173 }
4174
4175 /*
4176 * The aging and the eviction is a typical producer-consumer model. The
4177 * aging tries to be lazy to reduce the unnecessary overhead. On the
4178 * other hand, the eviction stalls when the number of generations
4179 * reaches MIN_NR_GENS. So ideally, there should be MIN_NR_GENS+1
4180 * generations, hence the first two if's.
4181 *
4182 * In addition, it's ideal to spread pages out evenly, meaning
4183 * 1/(MIN_NR_GENS+1) of the total number of pages for each generation. A
4184 * reasonable range for this average portion would [1/MIN_NR_GENS,
4185 * 1/(MIN_NR_GENS+2)]. From the consumer's POV, the eviction only cares
4186 * about the lower bound of cold pages, i.e., 1/(MIN_NR_GENS+2), whereas
4187 * from the producer's POV, the aging only cares about the upper bound
4188 * of hot pages, i.e., 1/MIN_NR_GENS.
4189 */
4190 if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS > max_seq)
4191 *need_aging = true;
4192 else if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS < max_seq)
4193 *need_aging = false;
4194 else if (young * MIN_NR_GENS > total)
4195 *need_aging = true;
4196 else if (old * (MIN_NR_GENS + 2) < total)
4197 *need_aging = true;
4198 else
4199 *need_aging = false;
4200
4201 return total > 0 ? total : 0;
4202}
4203
4204static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4205{
4206 bool need_aging;
4207 long nr_to_scan;
4208 int swappiness = get_swappiness(lruvec, sc);
4209 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4210 DEFINE_MAX_SEQ(lruvec);
4211 DEFINE_MIN_SEQ(lruvec);
4212
4213 mem_cgroup_calculate_protection(NULL, memcg);
4214
4215 if (mem_cgroup_below_min(memcg))
4216 return;
4217
4218 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, swappiness, &need_aging);
4219 if (!nr_to_scan)
4220 return;
4221
4222 nr_to_scan >>= sc->priority;
4223
4224 if (!mem_cgroup_online(memcg))
4225 nr_to_scan++;
4226
4227 if (nr_to_scan && need_aging && (!mem_cgroup_below_low(memcg) || sc->memcg_low_reclaim))
Yu Zhao5280d762022-01-27 19:23:01 -07004228 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004229}
4230
4231static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4232{
4233 struct mem_cgroup *memcg;
4234
4235 VM_BUG_ON(!current_is_kswapd());
4236
Yu Zhao5280d762022-01-27 19:23:01 -07004237 current->reclaim_state->mm_walk = &pgdat->mm_walk;
4238
Yu Zhaoa1537a62022-01-27 20:32:37 -07004239 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4240 do {
4241 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4242
4243 age_lruvec(lruvec, sc);
4244
4245 cond_resched();
4246 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao5280d762022-01-27 19:23:01 -07004247
4248 current->reclaim_state->mm_walk = NULL;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004249}
4250
Yu Zhaoafd94c92022-01-27 20:43:22 -07004251/*
4252 * This function exploits spatial locality when shrink_page_list() walks the
4253 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages.
Yu Zhao5280d762022-01-27 19:23:01 -07004254 * If the scan was done cacheline efficiently, it adds the PMD entry pointing
4255 * to the PTE table to the Bloom filter. This process is a feedback loop from
4256 * the eviction to the aging.
Yu Zhaoafd94c92022-01-27 20:43:22 -07004257 */
4258void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4259{
4260 int i;
4261 pte_t *pte;
4262 unsigned long start;
4263 unsigned long end;
4264 unsigned long addr;
4265 struct page *page;
Yu Zhao5280d762022-01-27 19:23:01 -07004266 struct lru_gen_mm_walk *walk;
4267 int young = 0;
Yu Zhaoafd94c92022-01-27 20:43:22 -07004268 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4269 struct mem_cgroup *memcg = page_memcg(pvmw->page);
4270 struct pglist_data *pgdat = page_pgdat(pvmw->page);
4271 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4272 DEFINE_MAX_SEQ(lruvec);
4273 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4274
4275 lockdep_assert_held(pvmw->ptl);
4276 VM_BUG_ON_PAGE(PageLRU(pvmw->page), pvmw->page);
4277
4278 if (spin_is_contended(pvmw->ptl))
4279 return;
4280
4281 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4282 end = pmd_addr_end(pvmw->address, pvmw->vma->vm_end);
4283
4284 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4285 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4286 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4287 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4288 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4289 else {
4290 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4291 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4292 }
4293 }
4294
4295 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4296
4297 rcu_read_lock();
4298 arch_enter_lazy_mmu_mode();
4299
4300 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4301 unsigned long pfn = pte_pfn(pte[i]);
4302
4303 VM_BUG_ON(addr < pvmw->vma->vm_start || addr >= pvmw->vma->vm_end);
4304
4305 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
4306 continue;
4307
4308 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
4309 continue;
4310
4311 if (!pte_young(pte[i]))
4312 continue;
4313
4314 VM_BUG_ON(!pfn_valid(pfn));
4315 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
4316 continue;
4317
4318 page = compound_head(pfn_to_page(pfn));
4319 if (page_to_nid(page) != pgdat->node_id)
4320 continue;
4321
4322 if (page_memcg_rcu(page) != memcg)
4323 continue;
4324
4325 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4326 continue;
4327
Yu Zhao5280d762022-01-27 19:23:01 -07004328 young++;
4329
Yu Zhaoafd94c92022-01-27 20:43:22 -07004330 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4331 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
4332 set_page_dirty(page);
4333
4334 old_gen = page_lru_gen(page);
4335 if (old_gen < 0)
4336 SetPageReferenced(page);
4337 else if (old_gen != new_gen)
4338 __set_bit(i, bitmap);
4339 }
4340
4341 arch_leave_lazy_mmu_mode();
4342 rcu_read_unlock();
4343
Yu Zhao5280d762022-01-27 19:23:01 -07004344 /* feedback from rmap walkers to page table walkers */
4345 if (suitable_to_scan(i, young))
4346 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4347
4348 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4349
4350 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhaoafd94c92022-01-27 20:43:22 -07004351 for_each_set_bit(i, bitmap, MIN_LRU_BATCH)
4352 activate_page(pte_page(pte[i]));
4353 return;
4354 }
4355
4356 /* page_update_gen() requires stable page_memcg() */
4357 if (!mem_cgroup_trylock_pages(memcg))
4358 return;
4359
Yu Zhao5280d762022-01-27 19:23:01 -07004360 if (!walk) {
4361 spin_lock_irq(&lruvec->lru_lock);
4362 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4363 }
Yu Zhaoafd94c92022-01-27 20:43:22 -07004364
4365 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4366 page = compound_head(pte_page(pte[i]));
4367 if (page_memcg_rcu(page) != memcg)
4368 continue;
4369
4370 old_gen = page_update_gen(page, new_gen);
4371 if (old_gen < 0 || old_gen == new_gen)
4372 continue;
4373
Yu Zhao5280d762022-01-27 19:23:01 -07004374 if (walk)
4375 update_batch_size(walk, page, old_gen, new_gen);
4376 else
4377 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhaoafd94c92022-01-27 20:43:22 -07004378 }
4379
Yu Zhao5280d762022-01-27 19:23:01 -07004380 if (!walk)
4381 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhaoafd94c92022-01-27 20:43:22 -07004382
4383 mem_cgroup_unlock_pages();
4384}
4385
Yu Zhaoa1537a62022-01-27 20:32:37 -07004386/******************************************************************************
4387 * the eviction
4388 ******************************************************************************/
4389
4390static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4391{
4392 bool success;
4393 int gen = page_lru_gen(page);
4394 int type = page_is_file_lru(page);
4395 int zone = page_zonenum(page);
4396 int tier = page_lru_tier(page);
4397 int delta = thp_nr_pages(page);
4398 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4399
4400 VM_BUG_ON_PAGE(gen >= MAX_NR_GENS, page);
4401
4402 if (!page_evictable(page)) {
4403 success = lru_gen_del_page(lruvec, page, true);
4404 VM_BUG_ON_PAGE(!success, page);
4405 SetPageUnevictable(page);
4406 add_page_to_lru_list(page, lruvec);
4407 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4408 return true;
4409 }
4410
4411 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4412 success = lru_gen_del_page(lruvec, page, true);
4413 VM_BUG_ON_PAGE(!success, page);
4414 SetPageSwapBacked(page);
4415 add_page_to_lru_list_tail(page, lruvec);
4416 return true;
4417 }
4418
Yu Zhaoafd94c92022-01-27 20:43:22 -07004419 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4420 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4421 return true;
4422 }
4423
Yu Zhaoa1537a62022-01-27 20:32:37 -07004424 if (tier > tier_idx) {
4425 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4426
4427 gen = page_inc_gen(lruvec, page, false);
4428 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4429
4430 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4431 lrugen->protected[hist][type][tier - 1] + delta);
4432 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4433 return true;
4434 }
4435
4436 if (PageLocked(page) || PageWriteback(page) ||
4437 (type == LRU_GEN_FILE && PageDirty(page))) {
4438 gen = page_inc_gen(lruvec, page, true);
4439 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4440 return true;
4441 }
4442
4443 return false;
4444}
4445
4446static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4447{
4448 bool success;
4449
4450 if (!sc->may_unmap && page_mapped(page))
4451 return false;
4452
4453 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4454 (PageDirty(page) || (PageAnon(page) && !PageSwapCache(page))))
4455 return false;
4456
4457 if (!get_page_unless_zero(page))
4458 return false;
4459
4460 if (!TestClearPageLRU(page)) {
4461 put_page(page);
4462 return false;
4463 }
4464
4465 success = lru_gen_del_page(lruvec, page, true);
4466 VM_BUG_ON_PAGE(!success, page);
4467
4468 return true;
4469}
4470
4471static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4472 int type, int tier, struct list_head *list)
4473{
4474 int gen, zone;
4475 enum vm_event_item item;
4476 int sorted = 0;
4477 int scanned = 0;
4478 int isolated = 0;
4479 int remaining = MAX_LRU_BATCH;
4480 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4481 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4482
4483 VM_BUG_ON(!list_empty(list));
4484
4485 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4486 return 0;
4487
4488 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4489
4490 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4491 LIST_HEAD(moved);
4492 int skipped = 0;
4493 struct list_head *head = &lrugen->lists[gen][type][zone];
4494
4495 while (!list_empty(head)) {
4496 struct page *page = lru_to_page(head);
4497 int delta = thp_nr_pages(page);
4498
4499 VM_BUG_ON_PAGE(PageTail(page), page);
4500 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4501 VM_BUG_ON_PAGE(PageActive(page), page);
4502 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4503 VM_BUG_ON_PAGE(page_zonenum(page) != zone, page);
4504
4505 prefetchw_prev_lru_page(page, head, flags);
4506
4507 scanned += delta;
4508
4509 if (sort_page(lruvec, page, tier))
4510 sorted += delta;
4511 else if (isolate_page(lruvec, page, sc)) {
4512 list_add(&page->lru, list);
4513 isolated += delta;
4514 } else {
4515 list_move(&page->lru, &moved);
4516 skipped += delta;
4517 }
4518
4519 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4520 break;
4521 }
4522
4523 if (skipped) {
4524 list_splice(&moved, head);
4525 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4526 }
4527
4528 if (!remaining || isolated >= MIN_LRU_BATCH)
4529 break;
4530 }
4531
4532 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4533 if (!cgroup_reclaim(sc)) {
4534 __count_vm_events(item, isolated);
4535 __count_vm_events(PGREFILL, sorted);
4536 }
4537 __count_memcg_events(memcg, item, isolated);
4538 __count_memcg_events(memcg, PGREFILL, sorted);
4539 __count_vm_events(PGSCAN_ANON + type, isolated);
4540
4541 /*
4542 * There might not be eligible pages due to reclaim_idx, may_unmap and
4543 * may_writepage. Check the remaining to prevent livelock if there is no
4544 * progress.
4545 */
4546 return isolated || !remaining ? scanned : 0;
4547}
4548
4549static int get_tier_idx(struct lruvec *lruvec, int type)
4550{
4551 int tier;
4552 struct ctrl_pos sp, pv;
4553
4554 /*
4555 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4556 * This value is chosen because any other tier would have at least twice
4557 * as many refaults as the first tier.
4558 */
4559 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4560 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4561 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4562 if (!positive_ctrl_err(&sp, &pv))
4563 break;
4564 }
4565
4566 return tier - 1;
4567}
4568
4569static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4570{
4571 int type, tier;
4572 struct ctrl_pos sp, pv;
4573 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4574
4575 /*
4576 * Compare the first tier of anon with that of file to determine which
4577 * type to scan. Also need to compare other tiers of the selected type
4578 * with the first tier of the other type to determine the last tier (of
4579 * the selected type) to evict.
4580 */
4581 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4582 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4583 type = positive_ctrl_err(&sp, &pv);
4584
4585 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4586 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4587 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4588 if (!positive_ctrl_err(&sp, &pv))
4589 break;
4590 }
4591
4592 *tier_idx = tier - 1;
4593
4594 return type;
4595}
4596
4597static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4598 int *type_scanned, struct list_head *list)
4599{
4600 int i;
4601 int type;
4602 int scanned;
4603 int tier = -1;
4604 DEFINE_MIN_SEQ(lruvec);
4605
4606 VM_BUG_ON(!seq_is_valid(lruvec));
4607
4608 /*
4609 * Try to make the obvious choice first. When anon and file are both
4610 * available from the same generation, interpret swappiness 1 as file
4611 * first and 200 as anon first.
4612 */
4613 if (!swappiness)
4614 type = LRU_GEN_FILE;
4615 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4616 type = LRU_GEN_ANON;
4617 else if (swappiness == 1)
4618 type = LRU_GEN_FILE;
4619 else if (swappiness == 200)
4620 type = LRU_GEN_ANON;
4621 else
4622 type = get_type_to_scan(lruvec, swappiness, &tier);
4623
4624 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4625 if (tier < 0)
4626 tier = get_tier_idx(lruvec, type);
4627
4628 scanned = scan_pages(lruvec, sc, type, tier, list);
4629 if (scanned)
4630 break;
4631
4632 type = !type;
4633 tier = -1;
4634 }
4635
4636 *type_scanned = type;
4637
4638 return scanned;
4639}
4640
4641static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
4642{
4643 int type;
4644 int scanned;
4645 int reclaimed;
4646 LIST_HEAD(list);
4647 struct page *page;
4648 enum vm_event_item item;
4649 struct reclaim_stat stat;
Yu Zhao5280d762022-01-27 19:23:01 -07004650 struct lru_gen_mm_walk *walk;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004651 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4652 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4653
4654 spin_lock_irq(&lruvec->lru_lock);
4655
4656 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4657
4658 if (try_to_inc_min_seq(lruvec, swappiness))
4659 scanned++;
4660
4661 if (get_nr_gens(lruvec, LRU_GEN_FILE) == MIN_NR_GENS)
4662 scanned = 0;
4663
4664 spin_unlock_irq(&lruvec->lru_lock);
4665
4666 if (list_empty(&list))
4667 return scanned;
4668
4669 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4670
4671 /*
4672 * To avoid livelock, don't add rejected pages back to the same lists
4673 * they were isolated from. See lru_gen_add_page().
4674 */
4675 list_for_each_entry(page, &list, lru) {
4676 ClearPageReferenced(page);
4677 ClearPageWorkingset(page);
4678
4679 if (PageReclaim(page) && (PageDirty(page) || PageWriteback(page)))
4680 ClearPageActive(page);
4681 else if (page_is_file_lru(page) || PageSwapCache(page))
4682 SetPageActive(page);
4683 }
4684
4685 spin_lock_irq(&lruvec->lru_lock);
4686
4687 move_pages_to_lru(lruvec, &list);
4688
Yu Zhao5280d762022-01-27 19:23:01 -07004689 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4690 if (walk && walk->batched)
4691 reset_batch_size(lruvec, walk);
4692
Yu Zhaoa1537a62022-01-27 20:32:37 -07004693 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4694 if (!cgroup_reclaim(sc))
4695 __count_vm_events(item, reclaimed);
4696 __count_memcg_events(memcg, item, reclaimed);
4697 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4698
4699 spin_unlock_irq(&lruvec->lru_lock);
4700
4701 mem_cgroup_uncharge_list(&list);
4702 free_unref_page_list(&list);
4703
4704 sc->nr_reclaimed += reclaimed;
4705
4706 return scanned;
4707}
4708
4709static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
4710{
4711 bool need_aging;
4712 long nr_to_scan;
4713 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4714 DEFINE_MAX_SEQ(lruvec);
4715 DEFINE_MIN_SEQ(lruvec);
4716
4717 if (mem_cgroup_below_min(memcg) ||
4718 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4719 return 0;
4720
4721 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, can_swap, &need_aging);
4722 if (!nr_to_scan)
4723 return 0;
4724
4725 /* reset the priority if the target has been met */
4726 nr_to_scan >>= sc->nr_reclaimed < sc->nr_to_reclaim ? sc->priority : DEF_PRIORITY;
4727
4728 if (!mem_cgroup_online(memcg))
4729 nr_to_scan++;
4730
4731 if (!nr_to_scan)
4732 return 0;
4733
4734 if (!need_aging)
4735 return nr_to_scan;
4736
4737 /* leave the work to lru_gen_age_node() */
4738 if (current_is_kswapd())
4739 return 0;
4740
4741 /* try other memcgs before going to the aging path */
4742 if (!cgroup_reclaim(sc) && !sc->force_deactivate) {
4743 sc->skipped_deactivate = true;
4744 return 0;
4745 }
4746
Yu Zhao5280d762022-01-27 19:23:01 -07004747 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
4748 return nr_to_scan;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004749
Yu Zhao5280d762022-01-27 19:23:01 -07004750 return min_seq[LRU_GEN_FILE] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004751}
4752
4753static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4754{
4755 struct blk_plug plug;
4756 long scanned = 0;
Yu Zhao5280d762022-01-27 19:23:01 -07004757 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004758
4759 lru_add_drain();
4760
4761 blk_start_plug(&plug);
4762
Yu Zhao5280d762022-01-27 19:23:01 -07004763 if (current_is_kswapd())
4764 current->reclaim_state->mm_walk = &pgdat->mm_walk;
4765
Yu Zhaoa1537a62022-01-27 20:32:37 -07004766 while (true) {
4767 int delta;
4768 int swappiness;
4769 long nr_to_scan;
4770
4771 if (sc->may_swap)
4772 swappiness = get_swappiness(lruvec, sc);
4773 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4774 swappiness = 1;
4775 else
4776 swappiness = 0;
4777
4778 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
4779 if (!nr_to_scan)
4780 break;
4781
4782 delta = evict_pages(lruvec, sc, swappiness);
4783 if (!delta)
4784 break;
4785
4786 scanned += delta;
4787 if (scanned >= nr_to_scan)
4788 break;
4789
4790 cond_resched();
4791 }
4792
Yu Zhao5280d762022-01-27 19:23:01 -07004793 if (current_is_kswapd())
4794 current->reclaim_state->mm_walk = NULL;
4795
Yu Zhaoa1537a62022-01-27 20:32:37 -07004796 blk_finish_plug(&plug);
4797}
4798
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004799/******************************************************************************
4800 * initialization
4801 ******************************************************************************/
4802
4803void lru_gen_init_lruvec(struct lruvec *lruvec)
4804{
4805 int gen, type, zone;
4806 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4807
4808 lrugen->max_seq = MIN_NR_GENS + 1;
4809
4810 for_each_gen_type_zone(gen, type, zone)
4811 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao5280d762022-01-27 19:23:01 -07004812
4813 lruvec->mm_state.seq = MIN_NR_GENS;
4814 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004815}
4816
4817#ifdef CONFIG_MEMCG
4818void lru_gen_init_memcg(struct mem_cgroup *memcg)
4819{
Yu Zhao5280d762022-01-27 19:23:01 -07004820 INIT_LIST_HEAD(&memcg->mm_list.fifo);
4821 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004822}
4823
4824void lru_gen_exit_memcg(struct mem_cgroup *memcg)
4825{
Yu Zhao5280d762022-01-27 19:23:01 -07004826 int i;
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004827 int nid;
4828
4829 for_each_node(nid) {
4830 struct lruvec *lruvec = get_lruvec(memcg, nid);
4831
4832 VM_BUG_ON(memchr_inv(lruvec->lrugen.nr_pages, 0,
4833 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao5280d762022-01-27 19:23:01 -07004834
4835 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
4836 bitmap_free(lruvec->mm_state.filters[i]);
4837 lruvec->mm_state.filters[i] = NULL;
4838 }
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004839 }
4840}
4841#endif
4842
4843static int __init init_lru_gen(void)
4844{
4845 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
4846 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
Yu Zhao5280d762022-01-27 19:23:01 -07004847 BUILD_BUG_ON(sizeof(MM_STAT_CODES) != NR_MM_STATS + 1);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004848
4849 return 0;
4850};
4851late_initcall(init_lru_gen);
4852
Yu Zhaoa1537a62022-01-27 20:32:37 -07004853#else
4854
4855static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4856{
4857}
4858
4859static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4860{
4861}
4862
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004863#endif /* CONFIG_LRU_GEN */
4864
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004865static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004866{
4867 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07004868 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004869 unsigned long nr_to_scan;
4870 enum lru_list lru;
4871 unsigned long nr_reclaimed = 0;
4872 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
4873 struct blk_plug plug;
Mel Gorman1a501902014-06-04 16:10:49 -07004874 bool scan_adjusted;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004875
Yu Zhaoa1537a62022-01-27 20:32:37 -07004876 if (lru_gen_enabled()) {
4877 lru_gen_shrink_lruvec(lruvec, sc);
4878 return;
4879 }
4880
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004881 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004882
Mel Gormane82e0562013-07-03 15:01:44 -07004883 /* Record the original scan target for proportional adjustments later */
4884 memcpy(targets, nr, sizeof(nr));
4885
Mel Gorman1a501902014-06-04 16:10:49 -07004886 /*
4887 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
4888 * event that can occur when there is little memory pressure e.g.
4889 * multiple streaming readers/writers. Hence, we do not abort scanning
4890 * when the requested number of pages are reclaimed when scanning at
4891 * DEF_PRIORITY on the assumption that the fact we are direct
4892 * reclaiming implies that kswapd is not keeping up and it is best to
4893 * do a batch of work at once. For memcg reclaim one check is made to
4894 * abort proportional reclaim if either the file or anon lru has already
4895 * dropped to zero at the first pass.
4896 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08004897 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
Mel Gorman1a501902014-06-04 16:10:49 -07004898 sc->priority == DEF_PRIORITY);
4899
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004900 blk_start_plug(&plug);
4901 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
4902 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07004903 unsigned long nr_anon, nr_file, percentage;
4904 unsigned long nr_scanned;
4905
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004906 for_each_evictable_lru(lru) {
4907 if (nr[lru]) {
4908 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
4909 nr[lru] -= nr_to_scan;
4910
4911 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07004912 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004913 }
4914 }
Mel Gormane82e0562013-07-03 15:01:44 -07004915
Michal Hockobd041732016-12-02 17:26:48 -08004916 cond_resched();
4917
Mel Gormane82e0562013-07-03 15:01:44 -07004918 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
4919 continue;
4920
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004921 /*
Mel Gormane82e0562013-07-03 15:01:44 -07004922 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07004923 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07004924 * proportionally what was requested by get_scan_count(). We
4925 * stop reclaiming one LRU and reduce the amount scanning
4926 * proportional to the original scan target.
4927 */
4928 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
4929 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
4930
Mel Gorman1a501902014-06-04 16:10:49 -07004931 /*
4932 * It's just vindictive to attack the larger once the smaller
4933 * has gone to zero. And given the way we stop scanning the
4934 * smaller below, this makes sure that we only make one nudge
4935 * towards proportionality once we've got nr_to_reclaim.
4936 */
4937 if (!nr_file || !nr_anon)
4938 break;
4939
Mel Gormane82e0562013-07-03 15:01:44 -07004940 if (nr_file > nr_anon) {
4941 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
4942 targets[LRU_ACTIVE_ANON] + 1;
4943 lru = LRU_BASE;
4944 percentage = nr_anon * 100 / scan_target;
4945 } else {
4946 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
4947 targets[LRU_ACTIVE_FILE] + 1;
4948 lru = LRU_FILE;
4949 percentage = nr_file * 100 / scan_target;
4950 }
4951
4952 /* Stop scanning the smaller of the LRU */
4953 nr[lru] = 0;
4954 nr[lru + LRU_ACTIVE] = 0;
4955
4956 /*
4957 * Recalculate the other LRU scan count based on its original
4958 * scan target and the percentage scanning already complete
4959 */
4960 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
4961 nr_scanned = targets[lru] - nr[lru];
4962 nr[lru] = targets[lru] * (100 - percentage) / 100;
4963 nr[lru] -= min(nr[lru], nr_scanned);
4964
4965 lru += LRU_ACTIVE;
4966 nr_scanned = targets[lru] - nr[lru];
4967 nr[lru] = targets[lru] * (100 - percentage) / 100;
4968 nr[lru] -= min(nr[lru], nr_scanned);
4969
4970 scan_adjusted = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004971 }
4972 blk_finish_plug(&plug);
4973 sc->nr_reclaimed += nr_reclaimed;
4974
4975 /*
4976 * Even if we did not try to evict anon pages at all, we want to
4977 * rebalance the anon lru active/inactive ratio.
4978 */
Dave Hansen2f368a92021-09-02 14:59:23 -07004979 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
4980 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004981 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
4982 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004983}
4984
Mel Gorman23b9da52012-05-29 15:06:20 -07004985/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004986static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07004987{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08004988 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07004989 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004990 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07004991 return true;
4992
4993 return false;
4994}
4995
Rik van Riel4f98a2f2008-10-18 20:26:32 -07004996/*
Mel Gorman23b9da52012-05-29 15:06:20 -07004997 * Reclaim/compaction is used for high-order allocation requests. It reclaims
4998 * order-0 pages before compacting the zone. should_continue_reclaim() returns
4999 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005000 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005001 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005002 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005003static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005004 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005005 struct scan_control *sc)
5006{
5007 unsigned long pages_for_compaction;
5008 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005009 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005010
5011 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005012 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005013 return false;
5014
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005015 /*
5016 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5017 * number of pages that were scanned. This will return to the caller
5018 * with the risk reclaim/compaction and the resulting allocation attempt
5019 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5020 * allocations through requiring that the full LRU list has been scanned
5021 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5022 * scan, but that approximation was wrong, and there were corner cases
5023 * where always a non-zero amount of pages were scanned.
5024 */
5025 if (!nr_reclaimed)
5026 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005027
Mel Gorman3e7d3442011-01-13 15:45:56 -08005028 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005029 for (z = 0; z <= sc->reclaim_idx; z++) {
5030 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005031 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005032 continue;
5033
5034 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005035 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005036 case COMPACT_CONTINUE:
5037 return false;
5038 default:
5039 /* check next zone */
5040 ;
5041 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005042 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005043
5044 /*
5045 * If we have not reclaimed enough pages for compaction and the
5046 * inactive lists are large enough, continue reclaiming
5047 */
5048 pages_for_compaction = compact_gap(sc->order);
5049 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005050 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005051 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5052
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005053 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005054}
5055
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005056static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005057{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005058 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005059 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005060
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005061 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005062 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005063 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005064 unsigned long reclaimed;
5065 unsigned long scanned;
Johannes Weiner56600482012-01-12 17:17:59 -08005066
Xunlei Pange3336ca2020-09-04 16:35:27 -07005067 /*
5068 * This loop can become CPU-bound when target memcgs
5069 * aren't eligible for reclaim - either because they
5070 * don't have any reclaimable pages, or because their
5071 * memory is explicitly protected. Avoid soft lockups.
5072 */
5073 cond_resched();
5074
Chris Down45c7f7e2020-08-06 23:22:05 -07005075 mem_cgroup_calculate_protection(target_memcg, memcg);
5076
5077 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005078 /*
5079 * Hard protection.
5080 * If there is no reclaimable memory, OOM.
5081 */
5082 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005083 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005084 /*
5085 * Soft protection.
5086 * Respect the protection only as long as
5087 * there is an unprotected supply
5088 * of reclaimable memory from other cgroups.
5089 */
5090 if (!sc->memcg_low_reclaim) {
5091 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005092 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005093 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005094 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005095 }
5096
Johannes Weinerd2af3392019-11-30 17:55:43 -08005097 reclaimed = sc->nr_reclaimed;
5098 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005099
5100 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005101
Johannes Weinerd2af3392019-11-30 17:55:43 -08005102 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5103 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005104
Johannes Weinerd2af3392019-11-30 17:55:43 -08005105 /* Record the group's reclaim efficiency */
5106 vmpressure(sc->gfp_mask, memcg, false,
5107 sc->nr_scanned - scanned,
5108 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005109
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005110 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5111}
5112
Liu Song6c9e09072020-01-30 22:14:08 -08005113static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005114{
5115 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005116 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005117 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005118 bool reclaimable = false;
5119
Johannes Weiner1b051172019-11-30 17:55:52 -08005120 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5121
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005122again:
5123 memset(&sc->nr, 0, sizeof(sc->nr));
5124
5125 nr_reclaimed = sc->nr_reclaimed;
5126 nr_scanned = sc->nr_scanned;
5127
Yu Zhao3eb07702020-09-27 20:49:08 -06005128 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005129
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005130 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005131
Johannes Weinerd2af3392019-11-30 17:55:43 -08005132 if (reclaim_state) {
5133 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5134 reclaim_state->reclaimed_slab = 0;
5135 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005136
Johannes Weinerd2af3392019-11-30 17:55:43 -08005137 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005138 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005139 sc->nr_scanned - nr_scanned,
5140 sc->nr_reclaimed - nr_reclaimed);
5141
5142 if (sc->nr_reclaimed - nr_reclaimed)
5143 reclaimable = true;
5144
5145 if (current_is_kswapd()) {
5146 /*
5147 * If reclaim is isolating dirty pages under writeback,
5148 * it implies that the long-lived page allocation rate
5149 * is exceeding the page laundering rate. Either the
5150 * global limits are not being effective at throttling
5151 * processes due to the page distribution throughout
5152 * zones or there is heavy usage of a slow backing
5153 * device. The only option is to throttle from reclaim
5154 * context which is not ideal as there is no guarantee
5155 * the dirtying process is throttled in the same way
5156 * balance_dirty_pages() manages.
5157 *
5158 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5159 * count the number of pages under pages flagged for
5160 * immediate reclaim and stall if any are encountered
5161 * in the nr_immediate check below.
5162 */
5163 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5164 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005165
Johannes Weinerd2af3392019-11-30 17:55:43 -08005166 /* Allow kswapd to start writing pages during reclaim.*/
5167 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5168 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005169
5170 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005171 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005172 * reclaim and under writeback (nr_immediate), it
5173 * implies that pages are cycling through the LRU
5174 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005175 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005176 if (sc->nr.immediate)
5177 congestion_wait(BLK_RW_ASYNC, HZ/10);
5178 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005179
Johannes Weinerd2af3392019-11-30 17:55:43 -08005180 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005181 * Tag a node/memcg as congested if all the dirty pages
5182 * scanned were backed by a congested BDI and
5183 * wait_iff_congested will stall.
5184 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005185 * Legacy memcg will stall in page writeback so avoid forcibly
5186 * stalling in wait_iff_congested().
5187 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005188 if ((current_is_kswapd() ||
5189 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005190 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005191 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005192
5193 /*
5194 * Stall direct reclaim for IO completions if underlying BDIs
5195 * and node is congested. Allow kswapd to continue until it
5196 * starts encountering unqueued dirty pages or cycling through
5197 * the LRU too quickly.
5198 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005199 if (!current_is_kswapd() && current_may_throttle() &&
5200 !sc->hibernation_mode &&
5201 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005202 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5203
5204 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5205 sc))
5206 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005207
Johannes Weinerc73322d2017-05-03 14:51:51 -07005208 /*
5209 * Kswapd gives up on balancing particular nodes after too
5210 * many failures to reclaim anything from them and goes to
5211 * sleep. On reclaim progress, reset the failure counter. A
5212 * successful direct reclaim run will revive a dormant kswapd.
5213 */
5214 if (reclaimable)
5215 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005216}
5217
Vlastimil Babka53853e22014-10-09 15:27:02 -07005218/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005219 * Returns true if compaction should go ahead for a costly-order request, or
5220 * the allocation would already succeed without compaction. Return false if we
5221 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07005222 */
Mel Gorman4f588332016-07-28 15:46:38 -07005223static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005224{
Mel Gorman31483b62016-07-28 15:45:46 -07005225 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005226 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005227
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005228 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
5229 if (suitable == COMPACT_SUCCESS)
5230 /* Allocation should succeed already. Don't reclaim. */
5231 return true;
5232 if (suitable == COMPACT_SKIPPED)
5233 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005234 return false;
5235
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005236 /*
5237 * Compaction is already possible, but it takes time to run and there
5238 * are potentially other callers using the pages just freed. So proceed
5239 * with reclaim to make a buffer of free pages available to give
5240 * compaction a reasonable chance of completing and allocating the page.
5241 * Note that we won't actually reclaim the whole buffer in one attempt
5242 * as the target watermark in should_continue_reclaim() is lower. But if
5243 * we are already above the high+gap watermark, don't reclaim at all.
5244 */
5245 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
5246
5247 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005248}
5249
Linus Torvalds1da177e2005-04-16 15:20:36 -07005250/*
5251 * This is the direct reclaim path, for page-allocating processes. We only
5252 * try to reclaim pages from zones which will satisfy the caller's allocation
5253 * request.
5254 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07005255 * If a zone is deemed to be full of pinned pages then just give it a light
5256 * scan then give up on it.
5257 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07005258static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005259{
Mel Gormandd1a2392008-04-28 02:12:17 -07005260 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07005261 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07005262 unsigned long nr_soft_reclaimed;
5263 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07005264 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07005265 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005266
Mel Gormancc715d92012-03-21 16:34:00 -07005267 /*
5268 * If the number of buffer_heads in the machine exceeds the maximum
5269 * allowed level, force direct reclaim to scan the highmem zone as
5270 * highmem pages could be pinning lowmem pages storing buffer_heads
5271 */
Weijie Yang619d0d762014-04-07 15:36:59 -07005272 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07005273 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07005274 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07005275 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07005276 }
Mel Gormancc715d92012-03-21 16:34:00 -07005277
Mel Gormand4debc62010-08-09 17:19:29 -07005278 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07005279 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07005280 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005281 * Take care memory controller reclaiming has small influence
5282 * to global LRU.
5283 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005284 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04005285 if (!cpuset_zone_allowed(zone,
5286 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005287 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005288
Johannes Weiner0b064962014-08-06 16:06:12 -07005289 /*
5290 * If we already have plenty of memory free for
5291 * compaction in this zone, don't free any more.
5292 * Even though compaction is invoked for any
5293 * non-zero order, only frequent costly order
5294 * reclamation is disruptive enough to become a
5295 * noticeable problem, like transparent huge
5296 * page allocations.
5297 */
5298 if (IS_ENABLED(CONFIG_COMPACTION) &&
5299 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07005300 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07005301 sc->compaction_ready = true;
5302 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07005303 }
Johannes Weiner0b064962014-08-06 16:06:12 -07005304
Andrew Morton0608f432013-09-24 15:27:41 -07005305 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07005306 * Shrink each node in the zonelist once. If the
5307 * zonelist is ordered by zone (not the default) then a
5308 * node may be shrunk multiple times but in that case
5309 * the user prefers lower zones being preserved.
5310 */
5311 if (zone->zone_pgdat == last_pgdat)
5312 continue;
5313
5314 /*
Andrew Morton0608f432013-09-24 15:27:41 -07005315 * This steals pages from memory cgroups over softlimit
5316 * and returns the number of reclaimed pages and
5317 * scanned pages. This works for global memory pressure
5318 * and balancing, not for a memcg's limit.
5319 */
5320 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07005321 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07005322 sc->order, sc->gfp_mask,
5323 &nr_soft_scanned);
5324 sc->nr_reclaimed += nr_soft_reclaimed;
5325 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07005326 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005327 }
Nick Piggin408d8542006-09-25 23:31:27 -07005328
Mel Gorman79dafcd2016-07-28 15:45:53 -07005329 /* See comment about same check for global reclaim above */
5330 if (zone->zone_pgdat == last_pgdat)
5331 continue;
5332 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07005333 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005334 }
Mel Gormane0c23272011-10-31 17:09:33 -07005335
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005336 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07005337 * Restore to original mask to avoid the impact on the caller if we
5338 * promoted it to __GFP_HIGHMEM.
5339 */
5340 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005341}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005342
Johannes Weinerb9107182019-11-30 17:55:59 -08005343static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005344{
Johannes Weinerb9107182019-11-30 17:55:59 -08005345 struct lruvec *target_lruvec;
5346 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005347
Yu Zhaoa1537a62022-01-27 20:32:37 -07005348 if (lru_gen_enabled())
5349 return;
5350
Johannes Weinerb9107182019-11-30 17:55:59 -08005351 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07005352 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
5353 target_lruvec->refaults[0] = refaults;
5354 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
5355 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005356}
5357
Linus Torvalds1da177e2005-04-16 15:20:36 -07005358/*
5359 * This is the main entry point to direct page reclaim.
5360 *
5361 * If a full scan of the inactive list fails to free enough memory then we
5362 * are "out of memory" and something needs to be killed.
5363 *
5364 * If the caller is !__GFP_FS then the probability of a failure is reasonably
5365 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02005366 * caller can't do much about. We kick the writeback threads and take explicit
5367 * naps in the hope that some of these pages can be written. But if the
5368 * allocating task holds filesystem locks which prevent writeout this might not
5369 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07005370 *
5371 * returns: 0, if no pages reclaimed
5372 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07005373 */
Mel Gormandac1d272008-04-28 02:12:12 -07005374static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005375 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005376{
Johannes Weiner241994ed2015-02-11 15:26:06 -08005377 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005378 pg_data_t *last_pgdat;
5379 struct zoneref *z;
5380 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005381retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07005382 delayacct_freepages_start();
5383
Johannes Weinerb5ead352019-11-30 17:55:40 -08005384 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07005385 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005386
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005387 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005388 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
5389 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08005390 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07005391 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07005392
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005393 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07005394 break;
5395
5396 if (sc->compaction_ready)
5397 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005398
5399 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08005400 * If we're getting trouble reclaiming, start doing
5401 * writepage even in laptop mode.
5402 */
5403 if (sc->priority < DEF_PRIORITY - 2)
5404 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07005405 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005406
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005407 last_pgdat = NULL;
5408 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
5409 sc->nodemask) {
5410 if (zone->zone_pgdat == last_pgdat)
5411 continue;
5412 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08005413
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005414 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08005415
5416 if (cgroup_reclaim(sc)) {
5417 struct lruvec *lruvec;
5418
5419 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
5420 zone->zone_pgdat);
5421 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
5422 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005423 }
5424
Keika Kobayashi873b4772008-07-25 01:48:52 -07005425 delayacct_freepages_end();
5426
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005427 if (sc->nr_reclaimed)
5428 return sc->nr_reclaimed;
5429
Mel Gorman0cee34f2012-01-12 17:19:49 -08005430 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07005431 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08005432 return 1;
5433
Johannes Weinerb91ac372019-11-30 17:56:02 -08005434 /*
5435 * We make inactive:active ratio decisions based on the node's
5436 * composition of memory, but a restrictive reclaim_idx or a
5437 * memory.low cgroup setting can exempt large amounts of
5438 * memory from reclaim. Neither of which are very common, so
5439 * instead of doing costly eligibility calculations of the
5440 * entire cgroup subtree up front, we assume the estimates are
5441 * good, and retry with forcible deactivation if that fails.
5442 */
5443 if (sc->skipped_deactivate) {
5444 sc->priority = initial_priority;
5445 sc->force_deactivate = 1;
5446 sc->skipped_deactivate = 0;
5447 goto retry;
5448 }
5449
Johannes Weiner241994ed2015-02-11 15:26:06 -08005450 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07005451 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08005452 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08005453 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07005454 sc->memcg_low_reclaim = 1;
5455 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005456 goto retry;
5457 }
5458
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005459 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005460}
5461
Johannes Weinerc73322d2017-05-03 14:51:51 -07005462static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07005463{
5464 struct zone *zone;
5465 unsigned long pfmemalloc_reserve = 0;
5466 unsigned long free_pages = 0;
5467 int i;
5468 bool wmark_ok;
5469
Johannes Weinerc73322d2017-05-03 14:51:51 -07005470 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
5471 return true;
5472
Mel Gorman55150612012-07-31 16:44:35 -07005473 for (i = 0; i <= ZONE_NORMAL; i++) {
5474 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07005475 if (!managed_zone(zone))
5476 continue;
5477
5478 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07005479 continue;
5480
Mel Gorman55150612012-07-31 16:44:35 -07005481 pfmemalloc_reserve += min_wmark_pages(zone);
5482 free_pages += zone_page_state(zone, NR_FREE_PAGES);
5483 }
5484
Mel Gorman675becc2014-06-04 16:07:35 -07005485 /* If there are no reserves (unexpected config) then do not throttle */
5486 if (!pfmemalloc_reserve)
5487 return true;
5488
Mel Gorman55150612012-07-31 16:44:35 -07005489 wmark_ok = free_pages > pfmemalloc_reserve / 2;
5490
5491 /* kswapd must be awake if processes are being throttled */
5492 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005493 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
5494 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005495
Mel Gorman55150612012-07-31 16:44:35 -07005496 wake_up_interruptible(&pgdat->kswapd_wait);
5497 }
5498
5499 return wmark_ok;
5500}
5501
5502/*
5503 * Throttle direct reclaimers if backing storage is backed by the network
5504 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
5505 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08005506 * when the low watermark is reached.
5507 *
5508 * Returns true if a fatal signal was delivered during throttling. If this
5509 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07005510 */
Mel Gorman50694c22012-11-26 16:29:48 -08005511static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07005512 nodemask_t *nodemask)
5513{
Mel Gorman675becc2014-06-04 16:07:35 -07005514 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07005515 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07005516 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07005517
5518 /*
5519 * Kernel threads should not be throttled as they may be indirectly
5520 * responsible for cleaning pages necessary for reclaim to make forward
5521 * progress. kjournald for example may enter direct reclaim while
5522 * committing a transaction where throttling it could forcing other
5523 * processes to block on log_wait_commit().
5524 */
5525 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08005526 goto out;
5527
5528 /*
5529 * If a fatal signal is pending, this process should not throttle.
5530 * It should return quickly so it can exit and free its memory
5531 */
5532 if (fatal_signal_pending(current))
5533 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005534
Mel Gorman675becc2014-06-04 16:07:35 -07005535 /*
5536 * Check if the pfmemalloc reserves are ok by finding the first node
5537 * with a usable ZONE_NORMAL or lower zone. The expectation is that
5538 * GFP_KERNEL will be required for allocating network buffers when
5539 * swapping over the network so ZONE_HIGHMEM is unusable.
5540 *
5541 * Throttling is based on the first usable node and throttled processes
5542 * wait on a queue until kswapd makes progress and wakes them. There
5543 * is an affinity then between processes waking up and where reclaim
5544 * progress has been made assuming the process wakes on the same node.
5545 * More importantly, processes running on remote nodes will not compete
5546 * for remote pfmemalloc reserves and processes on different nodes
5547 * should make reasonable progress.
5548 */
5549 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08005550 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07005551 if (zone_idx(zone) > ZONE_NORMAL)
5552 continue;
5553
5554 /* Throttle based on the first usable node */
5555 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07005556 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07005557 goto out;
5558 break;
5559 }
5560
5561 /* If no zone was usable by the allocation flags then do not throttle */
5562 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08005563 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005564
Mel Gorman68243e72012-07-31 16:44:39 -07005565 /* Account for the throttling */
5566 count_vm_event(PGSCAN_DIRECT_THROTTLE);
5567
Mel Gorman55150612012-07-31 16:44:35 -07005568 /*
5569 * If the caller cannot enter the filesystem, it's possible that it
5570 * is due to the caller holding an FS lock or performing a journal
5571 * transaction in the case of a filesystem like ext[3|4]. In this case,
5572 * it is not safe to block on pfmemalloc_wait as kswapd could be
5573 * blocked waiting on the same lock. Instead, throttle for up to a
5574 * second before continuing.
5575 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07005576 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07005577 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07005578 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07005579 else
5580 /* Throttle until kswapd wakes the process */
5581 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
5582 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08005583
Mel Gorman50694c22012-11-26 16:29:48 -08005584 if (fatal_signal_pending(current))
5585 return true;
5586
5587out:
5588 return false;
Mel Gorman55150612012-07-31 16:44:35 -07005589}
5590
Mel Gormandac1d272008-04-28 02:12:12 -07005591unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07005592 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08005593{
Mel Gorman33906bc2010-08-09 17:19:16 -07005594 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005595 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08005596 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005597 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07005598 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07005599 .order = order,
5600 .nodemask = nodemask,
5601 .priority = DEF_PRIORITY,
5602 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005603 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07005604 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08005605 };
5606
Mel Gorman55150612012-07-31 16:44:35 -07005607 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07005608 * scan_control uses s8 fields for order, priority, and reclaim_idx.
5609 * Confirm they are large enough for max values.
5610 */
5611 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
5612 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
5613 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
5614
5615 /*
Mel Gorman50694c22012-11-26 16:29:48 -08005616 * Do not enter reclaim if fatal signal was delivered while throttled.
5617 * 1 is returned so that the page allocator does not OOM kill at this
5618 * point.
Mel Gorman55150612012-07-31 16:44:35 -07005619 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005620 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07005621 return 1;
5622
Andrew Morton1732d2b012019-07-16 16:26:15 -07005623 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005624 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07005625
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005626 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07005627
5628 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005629 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07005630
5631 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005632}
5633
Andrew Mortonc255a452012-07-31 16:43:02 -07005634#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08005635
Michal Hockod2e5fb92019-08-30 16:04:50 -07005636/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005637unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005638 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07005639 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07005640 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07005641{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005642 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07005643 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07005644 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07005645 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005646 .may_writepage = !laptop_mode,
5647 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07005648 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07005649 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07005650 };
Ying Han0ae5e892011-05-26 16:25:25 -07005651
Michal Hockod2e5fb92019-08-30 16:04:50 -07005652 WARN_ON_ONCE(!current->reclaim_state);
5653
Balbir Singh4e416952009-09-23 15:56:39 -07005654 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
5655 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005656
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005657 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07005658 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005659
Balbir Singh4e416952009-09-23 15:56:39 -07005660 /*
5661 * NOTE: Although we can get the priority field, using it
5662 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07005663 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07005664 * will pick up pages from other mem cgroup's as well. We hack
5665 * the priority and make it zero.
5666 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005667 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005668
5669 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
5670
Ying Han0ae5e892011-05-26 16:25:25 -07005671 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07005672
Balbir Singh4e416952009-09-23 15:56:39 -07005673 return sc.nr_reclaimed;
5674}
5675
Johannes Weiner72835c82012-01-12 17:18:32 -08005676unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005677 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08005678 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005679 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08005680{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005681 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07005682 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08005683 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005684 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07005685 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07005686 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07005687 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07005688 .target_mem_cgroup = memcg,
5689 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08005690 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005691 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005692 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07005693 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08005694 /*
5695 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
5696 * equal pressure on all the nodes. This is based on the assumption that
5697 * the reclaim does not bail out early.
5698 */
5699 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08005700
Andrew Morton1732d2b012019-07-16 16:26:15 -07005701 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005702 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07005703 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07005704
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005705 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07005706
Vlastimil Babka499118e2017-05-08 15:59:50 -07005707 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005708 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005709 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005710
5711 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005712}
5713#endif
5714
Mel Gorman1d82de62016-07-28 15:45:43 -07005715static void age_active_anon(struct pglist_data *pgdat,
Mel Gormanef8f2322016-07-28 15:46:05 -07005716 struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005717{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005718 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08005719 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005720
Yu Zhaoa1537a62022-01-27 20:32:37 -07005721 if (lru_gen_enabled()) {
5722 lru_gen_age_node(pgdat, sc);
5723 return;
5724 }
5725
Dave Hansen2f368a92021-09-02 14:59:23 -07005726 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005727 return;
5728
Johannes Weinerb91ac372019-11-30 17:56:02 -08005729 lruvec = mem_cgroup_lruvec(NULL, pgdat);
5730 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
5731 return;
5732
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005733 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5734 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08005735 lruvec = mem_cgroup_lruvec(memcg, pgdat);
5736 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5737 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005738 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5739 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08005740}
5741
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005742static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08005743{
5744 int i;
5745 struct zone *zone;
5746
5747 /*
5748 * Check for watermark boosts top-down as the higher zones
5749 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005750 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08005751 * start prematurely when there is no boosting and a lower
5752 * zone is balanced.
5753 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005754 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08005755 zone = pgdat->node_zones + i;
5756 if (!managed_zone(zone))
5757 continue;
5758
5759 if (zone->watermark_boost)
5760 return true;
5761 }
5762
5763 return false;
5764}
5765
Mel Gormane716f2e2017-05-03 14:53:45 -07005766/*
5767 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005768 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07005769 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005770static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08005771{
Mel Gormane716f2e2017-05-03 14:53:45 -07005772 int i;
5773 unsigned long mark = -1;
5774 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08005775
Mel Gorman1c308442018-12-28 00:35:52 -08005776 /*
5777 * Check watermarks bottom-up as lower zones are more likely to
5778 * meet watermarks.
5779 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005780 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07005781 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07005782
Mel Gormane716f2e2017-05-03 14:53:45 -07005783 if (!managed_zone(zone))
5784 continue;
5785
5786 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005787 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07005788 return true;
5789 }
5790
5791 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005792 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07005793 * need balancing by definition. This can happen if a zone-restricted
5794 * allocation tries to wake a remote kswapd.
5795 */
5796 if (mark == -1)
5797 return true;
5798
5799 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08005800}
5801
Mel Gorman631b6e02017-05-03 14:53:41 -07005802/* Clear pgdat state for congested, dirty or under writeback. */
5803static void clear_pgdat_congested(pg_data_t *pgdat)
5804{
Johannes Weiner1b051172019-11-30 17:55:52 -08005805 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5806
5807 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07005808 clear_bit(PGDAT_DIRTY, &pgdat->flags);
5809 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
5810}
5811
Mel Gorman1741c872011-01-13 15:46:21 -08005812/*
Mel Gorman55150612012-07-31 16:44:35 -07005813 * Prepare kswapd for sleeping. This verifies that there are no processes
5814 * waiting in throttle_direct_reclaim() and that watermarks have been met.
5815 *
5816 * Returns true if kswapd is ready to sleep
5817 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005818static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
5819 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08005820{
Mel Gorman55150612012-07-31 16:44:35 -07005821 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005822 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07005823 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005824 * race between when kswapd checks the watermarks and a process gets
5825 * throttled. There is also a potential race if processes get
5826 * throttled, kswapd wakes, a large process exits thereby balancing the
5827 * zones, which causes kswapd to exit balance_pgdat() before reaching
5828 * the wake up checks. If kswapd is going to sleep, no process should
5829 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
5830 * the wake up is premature, processes will wake kswapd and get
5831 * throttled again. The difference from wake ups in balance_pgdat() is
5832 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07005833 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005834 if (waitqueue_active(&pgdat->pfmemalloc_wait))
5835 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08005836
Johannes Weinerc73322d2017-05-03 14:51:51 -07005837 /* Hopeless node, leave it to direct reclaim */
5838 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
5839 return true;
5840
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005841 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07005842 clear_pgdat_congested(pgdat);
5843 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07005844 }
5845
Shantanu Goel333b0a42017-05-03 14:53:38 -07005846 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08005847}
5848
Linus Torvalds1da177e2005-04-16 15:20:36 -07005849/*
Mel Gorman1d82de62016-07-28 15:45:43 -07005850 * kswapd shrinks a node of pages that are at or below the highest usable
5851 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07005852 *
5853 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07005854 * reclaim or if the lack of progress was due to pages under writeback.
5855 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07005856 */
Mel Gorman1d82de62016-07-28 15:45:43 -07005857static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07005858 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07005859{
Mel Gorman1d82de62016-07-28 15:45:43 -07005860 struct zone *zone;
5861 int z;
Mel Gorman75485362013-07-03 15:01:42 -07005862
Mel Gorman1d82de62016-07-28 15:45:43 -07005863 /* Reclaim a number of pages proportional to the number of zones */
5864 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07005865 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07005866 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07005867 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07005868 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07005869
Mel Gorman1d82de62016-07-28 15:45:43 -07005870 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07005871 }
5872
Mel Gorman1d82de62016-07-28 15:45:43 -07005873 /*
5874 * Historically care was taken to put equal pressure on all zones but
5875 * now pressure is applied based on node LRU order.
5876 */
Mel Gorman970a39a2016-07-28 15:46:35 -07005877 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07005878
5879 /*
5880 * Fragmentation may mean that the system cannot be rebalanced for
5881 * high-order allocations. If twice the allocation size has been
5882 * reclaimed then recheck watermarks only at order-0 to prevent
5883 * excessive reclaim. Assume that a process requested a high-order
5884 * can direct reclaim/compact.
5885 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07005886 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07005887 sc->order = 0;
5888
Mel Gormanb8e83b92013-07-03 15:01:45 -07005889 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07005890}
5891
Mel Gormanc49c2c42021-06-28 19:42:21 -07005892/* Page allocator PCP high watermark is lowered if reclaim is active. */
5893static inline void
5894update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
5895{
5896 int i;
5897 struct zone *zone;
5898
5899 for (i = 0; i <= highest_zoneidx; i++) {
5900 zone = pgdat->node_zones + i;
5901
5902 if (!managed_zone(zone))
5903 continue;
5904
5905 if (active)
5906 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
5907 else
5908 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
5909 }
5910}
5911
5912static inline void
5913set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
5914{
5915 update_reclaim_active(pgdat, highest_zoneidx, true);
5916}
5917
5918static inline void
5919clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
5920{
5921 update_reclaim_active(pgdat, highest_zoneidx, false);
5922}
5923
Mel Gorman75485362013-07-03 15:01:42 -07005924/*
Mel Gorman1d82de62016-07-28 15:45:43 -07005925 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
5926 * that are eligible for use by the caller until at least one zone is
5927 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005928 *
Mel Gorman1d82de62016-07-28 15:45:43 -07005929 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005930 *
5931 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07005932 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08005933 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07005934 * or lower is eligible for reclaim until at least one usable zone is
5935 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005936 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005937static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005938{
Linus Torvalds1da177e2005-04-16 15:20:36 -07005939 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07005940 unsigned long nr_soft_reclaimed;
5941 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07005942 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08005943 unsigned long nr_boost_reclaim;
5944 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
5945 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07005946 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08005947 struct scan_control sc = {
5948 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07005949 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005950 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08005951 };
Omar Sandoval93781322018-06-07 17:07:02 -07005952
Andrew Morton1732d2b012019-07-16 16:26:15 -07005953 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07005954 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07005955 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07005956
Christoph Lameterf8891e52006-06-30 01:55:45 -07005957 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005958
Mel Gorman1c308442018-12-28 00:35:52 -08005959 /*
5960 * Account for the reclaim boost. Note that the zone boost is left in
5961 * place so that parallel allocations that are near the watermark will
5962 * stall or direct reclaim until kswapd is finished.
5963 */
5964 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005965 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08005966 zone = pgdat->node_zones + i;
5967 if (!managed_zone(zone))
5968 continue;
5969
5970 nr_boost_reclaim += zone->watermark_boost;
5971 zone_boosts[i] = zone->watermark_boost;
5972 }
5973 boosted = nr_boost_reclaim;
5974
5975restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07005976 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08005977 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005978 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07005979 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07005980 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08005981 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07005982 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07005983
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005984 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005985
Mel Gorman86c79f62016-07-28 15:45:59 -07005986 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07005987 * If the number of buffer_heads exceeds the maximum allowed
5988 * then consider reclaiming from all zones. This has a dual
5989 * purpose -- on 64-bit systems it is expected that
5990 * buffer_heads are stripped during active rotation. On 32-bit
5991 * systems, highmem pages can pin lowmem memory and shrinking
5992 * buffers can relieve lowmem pressure. Reclaim may still not
5993 * go ahead if all eligible zones for the original allocation
5994 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07005995 */
5996 if (buffer_heads_over_limit) {
5997 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
5998 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07005999 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006000 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006001
Mel Gorman970a39a2016-07-28 15:46:35 -07006002 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006003 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006004 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006005 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006006
Mel Gorman86c79f62016-07-28 15:45:59 -07006007 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006008 * If the pgdat is imbalanced then ignore boosting and preserve
6009 * the watermarks for a later time and restart. Note that the
6010 * zone watermarks will be still reset at the end of balancing
6011 * on the grounds that the normal reclaim should be enough to
6012 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006013 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006014 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006015 if (!balanced && nr_boost_reclaim) {
6016 nr_boost_reclaim = 0;
6017 goto restart;
6018 }
6019
6020 /*
6021 * If boosting is not active then only reclaim if there are no
6022 * eligible zones. Note that sc.reclaim_idx is not used as
6023 * buffer_heads_over_limit may have adjusted it.
6024 */
6025 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006026 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006027
Mel Gorman1c308442018-12-28 00:35:52 -08006028 /* Limit the priority of boosting to avoid reclaim writeback */
6029 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6030 raise_priority = false;
6031
6032 /*
6033 * Do not writeback or swap pages for boosted reclaim. The
6034 * intent is to relieve pressure not issue sub-optimal IO
6035 * from reclaim context. If no pages are reclaimed, the
6036 * reclaim will be aborted.
6037 */
6038 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6039 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006040
Linus Torvalds1da177e2005-04-16 15:20:36 -07006041 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006042 * Do some background aging of the anon list, to give
6043 * pages a chance to be referenced before reclaiming. All
6044 * pages are rotated regardless of classzone as this is
6045 * about consistent aging.
6046 */
Mel Gormanef8f2322016-07-28 15:46:05 -07006047 age_active_anon(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006048
6049 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006050 * If we're getting trouble reclaiming, start doing writepage
6051 * even in laptop mode.
6052 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006053 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006054 sc.may_writepage = 1;
6055
Mel Gorman1d82de62016-07-28 15:45:43 -07006056 /* Call soft limit reclaim before calling shrink_node. */
6057 sc.nr_scanned = 0;
6058 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006059 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006060 sc.gfp_mask, &nr_soft_scanned);
6061 sc.nr_reclaimed += nr_soft_reclaimed;
6062
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006063 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006064 * There should be no need to raise the scanning priority if
6065 * enough pages are already being scanned that that high
6066 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006067 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006068 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006069 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006070
6071 /*
6072 * If the low watermark is met there is no need for processes
6073 * to be throttled on pfmemalloc_wait as they should not be
6074 * able to safely make forward progress. Wake them
6075 */
6076 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006077 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006078 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006079
Mel Gormanb8e83b92013-07-03 15:01:45 -07006080 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006081 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006082 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006083 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006084 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006085 break;
6086
6087 /*
6088 * Raise priority if scanning rate is too low or there was no
6089 * progress in reclaiming pages
6090 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006091 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006092 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6093
6094 /*
6095 * If reclaim made no progress for a boost, stop reclaim as
6096 * IO cannot be queued and it could be an infinite loop in
6097 * extreme circumstances.
6098 */
6099 if (nr_boost_reclaim && !nr_reclaimed)
6100 break;
6101
Johannes Weinerc73322d2017-05-03 14:51:51 -07006102 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006103 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006104 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006105
Johannes Weinerc73322d2017-05-03 14:51:51 -07006106 if (!sc.nr_reclaimed)
6107 pgdat->kswapd_failures++;
6108
Mel Gormanb8e83b92013-07-03 15:01:45 -07006109out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006110 clear_reclaim_active(pgdat, highest_zoneidx);
6111
Mel Gorman1c308442018-12-28 00:35:52 -08006112 /* If reclaim was boosted, account for the reclaim done in this pass */
6113 if (boosted) {
6114 unsigned long flags;
6115
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006116 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006117 if (!zone_boosts[i])
6118 continue;
6119
6120 /* Increments are under the zone lock */
6121 zone = pgdat->node_zones + i;
6122 spin_lock_irqsave(&zone->lock, flags);
6123 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6124 spin_unlock_irqrestore(&zone->lock, flags);
6125 }
6126
6127 /*
6128 * As there is now likely space, wakeup kcompact to defragment
6129 * pageblocks.
6130 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006131 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006132 }
6133
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006134 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006135 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006136 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006137 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006138
Mel Gorman0abdee22011-01-13 15:46:22 -08006139 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006140 * Return the order kswapd stopped reclaiming at as
6141 * prepare_kswapd_sleep() takes it into account. If another caller
6142 * entered the allocator slow path while kswapd was awake, order will
6143 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006144 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006145 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006146}
6147
Mel Gormane716f2e2017-05-03 14:53:45 -07006148/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006149 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6150 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6151 * not a valid index then either kswapd runs for first time or kswapd couldn't
6152 * sleep after previous reclaim attempt (node is still unbalanced). In that
6153 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006154 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006155static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6156 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006157{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006158 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006159
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006160 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006161}
6162
Mel Gorman38087d92016-07-28 15:45:49 -07006163static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006164 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006165{
6166 long remaining = 0;
6167 DEFINE_WAIT(wait);
6168
6169 if (freezing(current) || kthread_should_stop())
6170 return;
6171
6172 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6173
Shantanu Goel333b0a42017-05-03 14:53:38 -07006174 /*
6175 * Try to sleep for a short interval. Note that kcompactd will only be
6176 * woken if it is possible to sleep for a short interval. This is
6177 * deliberate on the assumption that if reclaim cannot keep an
6178 * eligible zone balanced that it's also unlikely that compaction will
6179 * succeed.
6180 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006181 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006182 /*
6183 * Compaction records what page blocks it recently failed to
6184 * isolate pages from and skips them in the future scanning.
6185 * When kswapd is going to sleep, it is reasonable to assume
6186 * that pages and compaction may succeed so reset the cache.
6187 */
6188 reset_isolation_suitable(pgdat);
6189
6190 /*
6191 * We have freed the memory, now we should compact it to make
6192 * allocation of the requested order possible.
6193 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006194 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006195
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006196 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006197
6198 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006199 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006200 * order. The values will either be from a wakeup request or
6201 * the previous request that slept prematurely.
6202 */
6203 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006204 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6205 kswapd_highest_zoneidx(pgdat,
6206 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006207
6208 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6209 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006210 }
6211
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006212 finish_wait(&pgdat->kswapd_wait, &wait);
6213 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6214 }
6215
6216 /*
6217 * After a short sleep, check if it was a premature sleep. If not, then
6218 * go fully to sleep until explicitly woken up.
6219 */
Mel Gormand9f21d42016-07-28 15:46:41 -07006220 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006221 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006222 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6223
6224 /*
6225 * vmstat counters are not perfectly accurate and the estimated
6226 * value for counters such as NR_FREE_PAGES can deviate from the
6227 * true value by nr_online_cpus * threshold. To avoid the zone
6228 * watermarks being breached while under pressure, we reduce the
6229 * per-cpu vmstat threshold while kswapd is awake and restore
6230 * them before going back to sleep.
6231 */
6232 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07006233
6234 if (!kthread_should_stop())
6235 schedule();
6236
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006237 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
6238 } else {
6239 if (remaining)
6240 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
6241 else
6242 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
6243 }
6244 finish_wait(&pgdat->kswapd_wait, &wait);
6245}
6246
Linus Torvalds1da177e2005-04-16 15:20:36 -07006247/*
6248 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006249 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006250 *
6251 * This basically trickles out pages so that we have _some_
6252 * free memory available even if there is no other activity
6253 * that frees anything up. This is needed for things like routing
6254 * etc, where we otherwise might have all activity going on in
6255 * asynchronous contexts that cannot page things out.
6256 *
6257 * If there are applications that are active memory-allocators
6258 * (most normal use), this basically shouldn't matter.
6259 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306260int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006261{
Mel Gormane716f2e2017-05-03 14:53:45 -07006262 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006263 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07006264 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006265 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10306266 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006267
Rusty Russell174596a2009-01-01 10:12:29 +10306268 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07006269 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006270
6271 /*
6272 * Tell the memory management that we're a "memory allocator",
6273 * and that if we need more memory we should get access to it
6274 * regardless (see "__alloc_pages()"). "kswapd" should
6275 * never get caught in the normal page freeing logic.
6276 *
6277 * (Kswapd normally doesn't need memory anyway, but sometimes
6278 * you need a small amount of memory in order to be able to
6279 * page out something else, and this flag essentially protects
6280 * us from recursively trying to free more memory as we're
6281 * trying to free the first piece of memory in the first place).
6282 */
Christoph Lameter930d9152006-01-08 01:00:47 -08006283 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07006284 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07006285
Qian Cai5644e1fb2020-04-01 21:10:12 -07006286 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006287 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006288 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08006289 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07006290
Qian Cai5644e1fb2020-04-01 21:10:12 -07006291 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006292 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6293 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07006294
Mel Gorman38087d92016-07-28 15:45:49 -07006295kswapd_try_sleep:
6296 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006297 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07006298
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006299 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08006300 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006301 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6302 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006303 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006304 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006305
David Rientjes8fe23e02009-12-14 17:58:33 -08006306 ret = try_to_freeze();
6307 if (kthread_should_stop())
6308 break;
6309
6310 /*
6311 * We can speed up thawing tasks if we don't call balance_pgdat
6312 * after returning from the refrigerator
6313 */
Mel Gorman38087d92016-07-28 15:45:49 -07006314 if (ret)
6315 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07006316
Mel Gorman38087d92016-07-28 15:45:49 -07006317 /*
6318 * Reclaim begins at the requested order but if a high-order
6319 * reclaim fails then kswapd falls back to reclaiming for
6320 * order-0. If that happens, kswapd will consider sleeping
6321 * for the order it finished reclaiming at (reclaim_order)
6322 * but kcompactd is woken to compact for the original
6323 * request (alloc_order).
6324 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006325 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07006326 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006327 reclaim_order = balance_pgdat(pgdat, alloc_order,
6328 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07006329 if (reclaim_order < alloc_order)
6330 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006331 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08006332
Johannes Weiner71abdc12014-06-06 14:35:35 -07006333 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07006334
Linus Torvalds1da177e2005-04-16 15:20:36 -07006335 return 0;
6336}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306337EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006338
6339/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07006340 * A zone is low on free memory or too fragmented for high-order memory. If
6341 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
6342 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
6343 * has failed or is not needed, still wake up kcompactd if only compaction is
6344 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006345 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07006346void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006347 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006348{
6349 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07006350 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006351
Mel Gorman6aa303d2016-09-01 16:14:55 -07006352 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006353 return;
6354
David Rientjes5ecd9d42018-04-05 16:25:16 -07006355 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006356 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07006357
Qian Cai5644e1fb2020-04-01 21:10:12 -07006358 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006359 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006360
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006361 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
6362 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006363
6364 if (READ_ONCE(pgdat->kswapd_order) < order)
6365 WRITE_ONCE(pgdat->kswapd_order, order);
6366
Con Kolivas8d0986e2005-09-13 01:25:07 -07006367 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006368 return;
Mel Gormane1a55632016-07-28 15:46:26 -07006369
David Rientjes5ecd9d42018-04-05 16:25:16 -07006370 /* Hopeless node, leave it to direct reclaim if possible */
6371 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006372 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
6373 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07006374 /*
6375 * There may be plenty of free memory available, but it's too
6376 * fragmented for high-order allocations. Wake up kcompactd
6377 * and rely on compaction_suitable() to determine if it's
6378 * needed. If it fails, it will defer subsequent attempts to
6379 * ratelimit its work.
6380 */
6381 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006382 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07006383 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07006384 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07006385
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006386 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07006387 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07006388 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006389}
6390
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006391#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07006392/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006393 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006394 * freed pages.
6395 *
6396 * Rather than trying to age LRUs the aim is to preserve the overall
6397 * LRU order by reclaiming preferentially
6398 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07006399 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006400unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006401{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006402 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006403 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07006404 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07006405 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006406 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07006407 .may_writepage = 1,
6408 .may_unmap = 1,
6409 .may_swap = 1,
6410 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07006411 };
Ying Hana09ed5e2011-05-24 17:12:26 -07006412 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006413 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006414 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006415
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01006416 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07006417 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07006418 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08006419
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006420 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006421
Andrew Morton1732d2b012019-07-16 16:26:15 -07006422 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006423 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006424 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006425
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006426 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006427}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006428#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07006429
Yasunori Goto3218ae12006-06-27 02:53:33 -07006430/*
6431 * This kswapd start function will be called by init and node-hot-add.
6432 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
6433 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07006434void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006435{
6436 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306437 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006438
6439 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07006440 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006441
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306442 trace_android_vh_kswapd_per_node(nid, &skip, true);
6443 if (skip)
6444 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006445 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
6446 if (IS_ERR(pgdat->kswapd)) {
6447 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02006448 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07006449 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07006450 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006451 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07006452}
6453
David Rientjes8fe23e02009-12-14 17:58:33 -08006454/*
Jiang Liud8adde12012-07-11 14:01:52 -07006455 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07006456 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08006457 */
6458void kswapd_stop(int nid)
6459{
6460 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306461 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08006462
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306463 trace_android_vh_kswapd_per_node(nid, &skip, false);
6464 if (skip)
6465 return;
Jiang Liud8adde12012-07-11 14:01:52 -07006466 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08006467 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07006468 NODE_DATA(nid)->kswapd = NULL;
6469 }
David Rientjes8fe23e02009-12-14 17:58:33 -08006470}
6471
Linus Torvalds1da177e2005-04-16 15:20:36 -07006472static int __init kswapd_init(void)
6473{
Wei Yang6b700b52020-04-01 21:10:09 -07006474 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08006475
Linus Torvalds1da177e2005-04-16 15:20:36 -07006476 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08006477 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006478 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006479 return 0;
6480}
6481
6482module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006483
6484#ifdef CONFIG_NUMA
6485/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006486 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08006487 *
Mel Gormana5f5f912016-07-28 15:46:32 -07006488 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08006489 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006490 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006491int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006492
Dave Hansen51998362021-02-24 12:09:15 -08006493/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006494 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08006495 * of a node considered for each zone_reclaim. 4 scans 1/16th of
6496 * a zone.
6497 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006498#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08006499
Christoph Lameter9eeff232006-01-18 17:42:31 -08006500/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006501 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07006502 * occur.
6503 */
6504int sysctl_min_unmapped_ratio = 1;
6505
6506/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07006507 * If the number of slab pages in a zone grows beyond this percentage then
6508 * slab reclaim needs to occur.
6509 */
6510int sysctl_min_slab_ratio = 5;
6511
Mel Gorman11fb9982016-07-28 15:46:20 -07006512static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006513{
Mel Gorman11fb9982016-07-28 15:46:20 -07006514 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
6515 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
6516 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006517
6518 /*
6519 * It's possible for there to be more file mapped pages than
6520 * accounted for by the pages on the file LRU lists because
6521 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
6522 */
6523 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
6524}
6525
6526/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07006527static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006528{
Alexandru Moised031a152015-11-05 18:48:08 -08006529 unsigned long nr_pagecache_reclaimable;
6530 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07006531
6532 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006533 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07006534 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07006535 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07006536 * a better estimate
6537 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006538 if (node_reclaim_mode & RECLAIM_UNMAP)
6539 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006540 else
Mel Gormana5f5f912016-07-28 15:46:32 -07006541 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006542
6543 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07006544 if (!(node_reclaim_mode & RECLAIM_WRITE))
6545 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006546
6547 /* Watch for any possible underflows due to delta */
6548 if (unlikely(delta > nr_pagecache_reclaimable))
6549 delta = nr_pagecache_reclaimable;
6550
6551 return nr_pagecache_reclaimable - delta;
6552}
6553
Christoph Lameter0ff38492006-09-25 23:31:52 -07006554/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006555 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006556 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006557static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006558{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08006559 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08006560 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006561 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006562 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08006563 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08006564 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006565 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07006566 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07006567 .priority = NODE_RECLAIM_PRIORITY,
6568 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
6569 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07006570 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006571 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08006572 };
Johannes Weiner57f29762021-08-19 19:04:27 -07006573 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006574
Yafang Shao132bb8c2019-05-13 17:17:53 -07006575 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
6576 sc.gfp_mask);
6577
Christoph Lameter9eeff232006-01-18 17:42:31 -08006578 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07006579 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07006580 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08006581 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006582 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08006583 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006584 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08006585 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07006586 noreclaim_flag = memalloc_noreclaim_save();
6587 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07006588 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08006589
Mel Gormana5f5f912016-07-28 15:46:32 -07006590 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07006591 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07006592 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07006593 * priorities until we have enough memory freed.
6594 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07006595 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07006596 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006597 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07006598 }
Christoph Lameterc84db232006-02-01 03:05:29 -08006599
Andrew Morton1732d2b012019-07-16 16:26:15 -07006600 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006601 current->flags &= ~PF_SWAPWRITE;
6602 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006603 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07006604 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07006605
6606 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
6607
Rik van Riela79311c2009-01-06 14:40:01 -08006608 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006609}
Andrew Morton179e9632006-03-22 00:08:18 -08006610
Mel Gormana5f5f912016-07-28 15:46:32 -07006611int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08006612{
David Rientjesd773ed62007-10-16 23:26:01 -07006613 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006614
6615 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006616 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07006617 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07006618 *
Christoph Lameter96146342006-07-03 00:24:13 -07006619 * A small portion of unmapped file backed pages is needed for
6620 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07006621 * thrown out if the node is overallocated. So we do not reclaim
6622 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07006623 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08006624 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006625 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07006626 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
6627 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07006628 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08006629
6630 /*
David Rientjesd773ed62007-10-16 23:26:01 -07006631 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08006632 */
Mel Gormand0164ad2015-11-06 16:28:21 -08006633 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07006634 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08006635
6636 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006637 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08006638 * have associated processors. This will favor the local processor
6639 * over remote processors and spread off node memory allocations
6640 * as wide as possible.
6641 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006642 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
6643 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07006644
Mel Gormana5f5f912016-07-28 15:46:32 -07006645 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
6646 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07006647
Mel Gormana5f5f912016-07-28 15:46:32 -07006648 ret = __node_reclaim(pgdat, gfp_mask, order);
6649 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07006650
Mel Gorman24cf725182009-06-16 15:33:23 -07006651 if (!ret)
6652 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
6653
David Rientjesd773ed62007-10-16 23:26:01 -07006654 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006655}
Christoph Lameter9eeff232006-01-18 17:42:31 -08006656#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07006657
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006658/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006659 * check_move_unevictable_pages - check pages for evictability and move to
6660 * appropriate zone lru list
6661 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006662 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006663 * Checks pages for evictability, if an evictable page is in the unevictable
6664 * lru list, moves it to the appropriate evictable lru list. This function
6665 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006666 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006667void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006668{
Alex Shi6168d0d2020-12-15 12:34:29 -08006669 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08006670 int pgscanned = 0;
6671 int pgrescued = 0;
6672 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006673
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006674 for (i = 0; i < pvec->nr; i++) {
6675 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006676 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07006677
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006678 if (PageTransTail(page))
6679 continue;
6680
6681 nr_pages = thp_nr_pages(page);
6682 pgscanned += nr_pages;
6683
Alex Shid25b5bd2020-12-15 12:34:16 -08006684 /* block memcg migration during page moving between lru */
6685 if (!TestClearPageLRU(page))
6686 continue;
6687
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08006688 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08006689 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08006690 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08006691 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08006692 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006693 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08006694 }
Alex Shid25b5bd2020-12-15 12:34:16 -08006695 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006696 }
Hugh Dickins24513262012-01-20 14:34:21 -08006697
Alex Shi6168d0d2020-12-15 12:34:29 -08006698 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08006699 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
6700 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08006701 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08006702 } else if (pgscanned) {
6703 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08006704 }
Hugh Dickins850465792012-01-20 14:34:19 -08006705}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006706EXPORT_SYMBOL_GPL(check_move_unevictable_pages);