blob: 094b1992abf0bc430543db30df688f856a01b996 [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001// SPDX-License-Identifier: GPL-2.0
Linus Torvalds1da177e2005-04-16 15:20:36 -07002/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07003 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
4 *
5 * Swap reorganised 29.12.95, Stephen Tweedie.
6 * kswapd added: 7.1.96 sct
7 * Removed kswapd_ctl limits, and swap out as many pages as needed
8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
10 * Multiqueue VM started 5.8.00, Rik van Riel.
11 */
12
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070013#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
Linus Torvalds1da177e2005-04-16 15:20:36 -070015#include <linux/mm.h>
Ingo Molnar5b3cc152017-02-02 20:43:54 +010016#include <linux/sched/mm.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070017#include <linux/module.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090018#include <linux/gfp.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070019#include <linux/kernel_stat.h>
20#include <linux/swap.h>
21#include <linux/pagemap.h>
22#include <linux/init.h>
23#include <linux/highmem.h>
Anton Vorontsov70ddf632013-04-29 15:08:31 -070024#include <linux/vmpressure.h>
Andrew Mortone129b5c2006-09-27 01:50:00 -070025#include <linux/vmstat.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070026#include <linux/file.h>
27#include <linux/writeback.h>
28#include <linux/blkdev.h>
29#include <linux/buffer_head.h> /* for try_to_release_page(),
30 buffer_heads_over_limit */
31#include <linux/mm_inline.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070032#include <linux/backing-dev.h>
33#include <linux/rmap.h>
34#include <linux/topology.h>
35#include <linux/cpu.h>
36#include <linux/cpuset.h>
Mel Gorman3e7d3442011-01-13 15:45:56 -080037#include <linux/compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070038#include <linux/notifier.h>
39#include <linux/rwsem.h>
Rafael J. Wysocki248a0302006-03-22 00:09:04 -080040#include <linux/delay.h>
Yasunori Goto3218ae12006-06-27 02:53:33 -070041#include <linux/kthread.h>
Nigel Cunningham7dfb7102006-12-06 20:34:23 -080042#include <linux/freezer.h>
Balbir Singh66e17072008-02-07 00:13:56 -080043#include <linux/memcontrol.h>
Dave Hansen26aa2d12021-09-02 14:59:16 -070044#include <linux/migrate.h>
Keika Kobayashi873b4772008-07-25 01:48:52 -070045#include <linux/delayacct.h>
Lee Schermerhornaf936a12008-10-18 20:26:53 -070046#include <linux/sysctl.h>
KOSAKI Motohiro929bea72011-04-14 15:22:12 -070047#include <linux/oom.h>
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +000048#include <linux/pagevec.h>
Linus Torvalds268bb0c2011-05-20 12:50:29 -070049#include <linux/prefetch.h>
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070050#include <linux/printk.h>
Ross Zwislerf9fe48b2016-01-22 15:10:40 -080051#include <linux/dax.h>
Johannes Weinereb414682018-10-26 15:06:27 -070052#include <linux/psi.h>
Yu Zhao7f53b0e2022-09-18 02:00:05 -060053#include <linux/pagewalk.h>
54#include <linux/shmem_fs.h>
Yu Zhaobaeb9a02022-09-18 02:00:07 -060055#include <linux/ctype.h>
Yu Zhao4983c522022-09-18 02:00:09 -060056#include <linux/debugfs.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070057
58#include <asm/tlbflush.h>
59#include <asm/div64.h>
60
61#include <linux/swapops.h>
Rafael Aquini117aad12013-09-30 13:45:16 -070062#include <linux/balloon_compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070063
Nick Piggin0f8053a2006-03-22 00:08:33 -080064#include "internal.h"
65
Mel Gorman33906bc2010-08-09 17:19:16 -070066#define CREATE_TRACE_POINTS
67#include <trace/events/vmscan.h>
68
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -070069#undef CREATE_TRACE_POINTS
70#include <trace/hooks/vmscan.h>
71
Linus Torvalds1da177e2005-04-16 15:20:36 -070072struct scan_control {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -080073 /* How many pages shrink_list() should reclaim */
74 unsigned long nr_to_reclaim;
75
Johannes Weineree814fe2014-08-06 16:06:19 -070076 /*
77 * Nodemask of nodes allowed by the caller. If NULL, all nodes
78 * are scanned.
79 */
80 nodemask_t *nodemask;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -070081
KOSAKI Motohiro5f53e762010-05-24 14:32:37 -070082 /*
Johannes Weinerf16015f2012-01-12 17:17:52 -080083 * The memory cgroup that hit its limit and as a result is the
84 * primary target of this reclaim invocation.
85 */
86 struct mem_cgroup *target_mem_cgroup;
Balbir Singh66e17072008-02-07 00:13:56 -080087
Johannes Weiner7cf111b2020-06-03 16:03:06 -070088 /*
89 * Scan pressure balancing between anon and file LRUs
90 */
91 unsigned long anon_cost;
92 unsigned long file_cost;
93
Johannes Weinerb91ac372019-11-30 17:56:02 -080094 /* Can active pages be deactivated as part of reclaim? */
95#define DEACTIVATE_ANON 1
96#define DEACTIVATE_FILE 2
97 unsigned int may_deactivate:2;
98 unsigned int force_deactivate:1;
99 unsigned int skipped_deactivate:1;
100
Johannes Weiner1276ad62017-02-24 14:56:11 -0800101 /* Writepage batching in laptop mode; RECLAIM_WRITE */
Johannes Weineree814fe2014-08-06 16:06:19 -0700102 unsigned int may_writepage:1;
103
104 /* Can mapped pages be reclaimed? */
105 unsigned int may_unmap:1;
106
107 /* Can pages be swapped as part of reclaim? */
108 unsigned int may_swap:1;
109
Yisheng Xied6622f62017-05-03 14:53:57 -0700110 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700111 * Cgroup memory below memory.low is protected as long as we
112 * don't threaten to OOM. If any cgroup is reclaimed at
113 * reduced force or passed over entirely due to its memory.low
114 * setting (memcg_low_skipped), and nothing is reclaimed as a
115 * result, then go back for one more cycle that reclaims the protected
116 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700117 */
118 unsigned int memcg_low_reclaim:1;
119 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800120
Johannes Weineree814fe2014-08-06 16:06:19 -0700121 unsigned int hibernation_mode:1;
122
123 /* One of the zones is ready for compaction */
124 unsigned int compaction_ready:1;
125
Johannes Weinerb91ac372019-11-30 17:56:02 -0800126 /* There is easily reclaimable cold cache in the current node */
127 unsigned int cache_trim_mode:1;
128
Johannes Weiner53138ce2019-11-30 17:55:56 -0800129 /* The file pages on the current node are dangerously low */
130 unsigned int file_is_tiny:1;
131
Dave Hansen26aa2d12021-09-02 14:59:16 -0700132 /* Always discard instead of demoting to lower tier memory */
133 unsigned int no_demotion:1;
134
Yu Zhaoa8a158a2022-09-18 02:00:06 -0600135#ifdef CONFIG_LRU_GEN
136 /* help kswapd make better choices among multiple memcgs */
137 unsigned int memcgs_need_aging:1;
138 unsigned long last_reclaimed;
139#endif
140
Greg Thelenbb451fd2018-08-17 15:45:19 -0700141 /* Allocation order */
142 s8 order;
143
144 /* Scan (total_size >> priority) pages at once */
145 s8 priority;
146
147 /* The highest zone to isolate pages for reclaim from */
148 s8 reclaim_idx;
149
150 /* This context's GFP mask */
151 gfp_t gfp_mask;
152
Johannes Weineree814fe2014-08-06 16:06:19 -0700153 /* Incremented by the number of inactive pages that were scanned */
154 unsigned long nr_scanned;
155
156 /* Number of pages freed so far during a call to shrink_zones() */
157 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700158
159 struct {
160 unsigned int dirty;
161 unsigned int unqueued_dirty;
162 unsigned int congested;
163 unsigned int writeback;
164 unsigned int immediate;
165 unsigned int file_taken;
166 unsigned int taken;
167 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700168
169 /* for recording the reclaimed slab by now */
170 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700171};
172
Linus Torvalds1da177e2005-04-16 15:20:36 -0700173#ifdef ARCH_HAS_PREFETCHW
174#define prefetchw_prev_lru_page(_page, _base, _field) \
175 do { \
176 if ((_page)->lru.prev != _base) { \
177 struct page *prev; \
178 \
179 prev = lru_to_page(&(_page->lru)); \
180 prefetchw(&prev->_field); \
181 } \
182 } while (0)
183#else
184#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
185#endif
186
187/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700188 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700189 */
190int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700191
Yang Shi0a432dc2019-09-23 15:38:12 -0700192static void set_task_reclaim_state(struct task_struct *task,
193 struct reclaim_state *rs)
194{
195 /* Check for an overwrite */
196 WARN_ON_ONCE(rs && task->reclaim_state);
197
198 /* Check for the nulling of an already-nulled member */
199 WARN_ON_ONCE(!rs && !task->reclaim_state);
200
201 task->reclaim_state = rs;
202}
203
Linus Torvalds1da177e2005-04-16 15:20:36 -0700204static LIST_HEAD(shrinker_list);
205static DECLARE_RWSEM(shrinker_rwsem);
206
Yang Shi0a432dc2019-09-23 15:38:12 -0700207#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700208static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700209
Yang Shi3c6f17e2021-05-04 18:36:33 -0700210/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700211static inline int shrinker_map_size(int nr_items)
212{
213 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
214}
Yang Shi2bfd3632021-05-04 18:36:11 -0700215
Yang Shi3c6f17e2021-05-04 18:36:33 -0700216static inline int shrinker_defer_size(int nr_items)
217{
218 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
219}
220
Yang Shi468ab842021-05-04 18:36:26 -0700221static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
222 int nid)
223{
224 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
225 lockdep_is_held(&shrinker_rwsem));
226}
227
Yang Shie4262c42021-05-04 18:36:23 -0700228static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700229 int map_size, int defer_size,
230 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700231{
Yang Shie4262c42021-05-04 18:36:23 -0700232 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700233 struct mem_cgroup_per_node *pn;
234 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700235 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700236
Yang Shi2bfd3632021-05-04 18:36:11 -0700237 for_each_node(nid) {
238 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700239 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700240 /* Not yet online memcg */
241 if (!old)
242 return 0;
243
244 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
245 if (!new)
246 return -ENOMEM;
247
Yang Shi3c6f17e2021-05-04 18:36:33 -0700248 new->nr_deferred = (atomic_long_t *)(new + 1);
249 new->map = (void *)new->nr_deferred + defer_size;
250
251 /* map: set all old bits, clear all new bits */
252 memset(new->map, (int)0xff, old_map_size);
253 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
254 /* nr_deferred: copy old values, clear all new values */
255 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
256 memset((void *)new->nr_deferred + old_defer_size, 0,
257 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700258
Yang Shie4262c42021-05-04 18:36:23 -0700259 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700260 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700261 }
262
263 return 0;
264}
265
Yang Shie4262c42021-05-04 18:36:23 -0700266void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700267{
268 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700269 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700270 int nid;
271
Yang Shi2bfd3632021-05-04 18:36:11 -0700272 for_each_node(nid) {
273 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700274 info = rcu_dereference_protected(pn->shrinker_info, true);
275 kvfree(info);
276 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700277 }
278}
279
Yang Shie4262c42021-05-04 18:36:23 -0700280int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700281{
Yang Shie4262c42021-05-04 18:36:23 -0700282 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700283 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700284 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700285
Yang Shid27cf2a2021-05-04 18:36:14 -0700286 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700287 map_size = shrinker_map_size(shrinker_nr_max);
288 defer_size = shrinker_defer_size(shrinker_nr_max);
289 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700290 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700291 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
292 if (!info) {
293 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700294 ret = -ENOMEM;
295 break;
296 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700297 info->nr_deferred = (atomic_long_t *)(info + 1);
298 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700299 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700300 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700301 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700302
303 return ret;
304}
305
Yang Shi3c6f17e2021-05-04 18:36:33 -0700306static inline bool need_expand(int nr_max)
307{
308 return round_up(nr_max, BITS_PER_LONG) >
309 round_up(shrinker_nr_max, BITS_PER_LONG);
310}
311
Yang Shie4262c42021-05-04 18:36:23 -0700312static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700313{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700314 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700315 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700316 int map_size, defer_size = 0;
317 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700318 struct mem_cgroup *memcg;
319
Yang Shi3c6f17e2021-05-04 18:36:33 -0700320 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700321 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700322
Yang Shi2bfd3632021-05-04 18:36:11 -0700323 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700324 goto out;
325
326 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700327
Yang Shi3c6f17e2021-05-04 18:36:33 -0700328 map_size = shrinker_map_size(new_nr_max);
329 defer_size = shrinker_defer_size(new_nr_max);
330 old_map_size = shrinker_map_size(shrinker_nr_max);
331 old_defer_size = shrinker_defer_size(shrinker_nr_max);
332
Yang Shi2bfd3632021-05-04 18:36:11 -0700333 memcg = mem_cgroup_iter(NULL, NULL, NULL);
334 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700335 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
336 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700337 if (ret) {
338 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700339 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700340 }
341 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700342out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700343 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700344 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700345
Yang Shi2bfd3632021-05-04 18:36:11 -0700346 return ret;
347}
348
349void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
350{
351 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700352 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700353
354 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700355 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700356 /* Pairs with smp mb in shrink_slab() */
357 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700358 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700359 rcu_read_unlock();
360 }
361}
362
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700363static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700364
365static int prealloc_memcg_shrinker(struct shrinker *shrinker)
366{
367 int id, ret = -ENOMEM;
368
Yang Shi476b30a2021-05-04 18:36:39 -0700369 if (mem_cgroup_disabled())
370 return -ENOSYS;
371
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700372 down_write(&shrinker_rwsem);
373 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700374 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700375 if (id < 0)
376 goto unlock;
377
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700378 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700379 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700380 idr_remove(&shrinker_idr, id);
381 goto unlock;
382 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700383 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700384 shrinker->id = id;
385 ret = 0;
386unlock:
387 up_write(&shrinker_rwsem);
388 return ret;
389}
390
391static void unregister_memcg_shrinker(struct shrinker *shrinker)
392{
393 int id = shrinker->id;
394
395 BUG_ON(id < 0);
396
Yang Shi41ca6682021-05-04 18:36:29 -0700397 lockdep_assert_held(&shrinker_rwsem);
398
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700399 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700400}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700401
Yang Shi86750832021-05-04 18:36:36 -0700402static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
403 struct mem_cgroup *memcg)
404{
405 struct shrinker_info *info;
406
407 info = shrinker_info_protected(memcg, nid);
408 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
409}
410
411static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
412 struct mem_cgroup *memcg)
413{
414 struct shrinker_info *info;
415
416 info = shrinker_info_protected(memcg, nid);
417 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
418}
419
Yang Shia1780152021-05-04 18:36:42 -0700420void reparent_shrinker_deferred(struct mem_cgroup *memcg)
421{
422 int i, nid;
423 long nr;
424 struct mem_cgroup *parent;
425 struct shrinker_info *child_info, *parent_info;
426
427 parent = parent_mem_cgroup(memcg);
428 if (!parent)
429 parent = root_mem_cgroup;
430
431 /* Prevent from concurrent shrinker_info expand */
432 down_read(&shrinker_rwsem);
433 for_each_node(nid) {
434 child_info = shrinker_info_protected(memcg, nid);
435 parent_info = shrinker_info_protected(parent, nid);
436 for (i = 0; i < shrinker_nr_max; i++) {
437 nr = atomic_long_read(&child_info->nr_deferred[i]);
438 atomic_long_add(nr, &parent_info->nr_deferred[i]);
439 }
440 }
441 up_read(&shrinker_rwsem);
442}
443
Johannes Weinerb5ead352019-11-30 17:55:40 -0800444static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800445{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800446 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800447}
Tejun Heo97c93412015-05-22 18:23:36 -0400448
449/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800450 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400451 * @sc: scan_control in question
452 *
453 * The normal page dirty throttling mechanism in balance_dirty_pages() is
454 * completely broken with the legacy memcg and direct stalling in
455 * shrink_page_list() is used for throttling instead, which lacks all the
456 * niceties such as fairness, adaptive pausing, bandwidth proportional
457 * allocation and configurability.
458 *
459 * This function tests whether the vmscan currently in progress can assume
460 * that the normal dirty throttling mechanism is operational.
461 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800462static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400463{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800464 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400465 return true;
466#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800467 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400468 return true;
469#endif
470 return false;
471}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800472#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700473static int prealloc_memcg_shrinker(struct shrinker *shrinker)
474{
Yang Shi476b30a2021-05-04 18:36:39 -0700475 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700476}
477
478static void unregister_memcg_shrinker(struct shrinker *shrinker)
479{
480}
481
Yang Shi86750832021-05-04 18:36:36 -0700482static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
483 struct mem_cgroup *memcg)
484{
485 return 0;
486}
487
488static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
489 struct mem_cgroup *memcg)
490{
491 return 0;
492}
493
Johannes Weinerb5ead352019-11-30 17:55:40 -0800494static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800495{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800496 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800497}
Tejun Heo97c93412015-05-22 18:23:36 -0400498
Johannes Weinerb5ead352019-11-30 17:55:40 -0800499static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400500{
501 return true;
502}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800503#endif
504
Yang Shi86750832021-05-04 18:36:36 -0700505static long xchg_nr_deferred(struct shrinker *shrinker,
506 struct shrink_control *sc)
507{
508 int nid = sc->nid;
509
510 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
511 nid = 0;
512
513 if (sc->memcg &&
514 (shrinker->flags & SHRINKER_MEMCG_AWARE))
515 return xchg_nr_deferred_memcg(nid, shrinker,
516 sc->memcg);
517
518 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
519}
520
521
522static long add_nr_deferred(long nr, struct shrinker *shrinker,
523 struct shrink_control *sc)
524{
525 int nid = sc->nid;
526
527 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
528 nid = 0;
529
530 if (sc->memcg &&
531 (shrinker->flags & SHRINKER_MEMCG_AWARE))
532 return add_nr_deferred_memcg(nr, nid, shrinker,
533 sc->memcg);
534
535 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
536}
537
Dave Hansen26aa2d12021-09-02 14:59:16 -0700538static bool can_demote(int nid, struct scan_control *sc)
539{
Huang Ying20b51af12021-09-02 14:59:33 -0700540 if (!numa_demotion_enabled)
541 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700542 if (sc) {
543 if (sc->no_demotion)
544 return false;
545 /* It is pointless to do demotion in memcg reclaim */
546 if (cgroup_reclaim(sc))
547 return false;
548 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700549 if (next_demotion_node(nid) == NUMA_NO_NODE)
550 return false;
551
Huang Ying20b51af12021-09-02 14:59:33 -0700552 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700553}
554
Keith Buscha2a36482021-09-02 14:59:26 -0700555static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
556 int nid,
557 struct scan_control *sc)
558{
559 if (memcg == NULL) {
560 /*
561 * For non-memcg reclaim, is there
562 * space in any swap device?
563 */
564 if (get_nr_swap_pages() > 0)
565 return true;
566 } else {
567 /* Is the memcg below its swap limit? */
568 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
569 return true;
570 }
571
572 /*
573 * The page can not be swapped.
574 *
575 * Can it be reclaimed from this node via demotion?
576 */
577 return can_demote(nid, sc);
578}
579
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700580/*
581 * This misses isolated pages which are not accounted for to save counters.
582 * As the data only determines if reclaim or compaction continues, it is
583 * not expected that isolated pages will be a dominating factor.
584 */
585unsigned long zone_reclaimable_pages(struct zone *zone)
586{
587 unsigned long nr;
588
589 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
590 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700591 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700592 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
593 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
594
595 return nr;
596}
597
Michal Hockofd538802017-02-22 15:45:58 -0800598/**
599 * lruvec_lru_size - Returns the number of pages on the given LRU list.
600 * @lruvec: lru vector
601 * @lru: lru to use
602 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
603 */
Yu Zhao20913392021-02-24 12:08:44 -0800604static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
605 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800606{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800607 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800608 int zid;
609
Johannes Weinerde3b0152019-11-30 17:55:31 -0800610 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800611 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800612
Michal Hockofd538802017-02-22 15:45:58 -0800613 if (!managed_zone(zone))
614 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800615
Michal Hockofd538802017-02-22 15:45:58 -0800616 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800617 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800618 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800619 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800620 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800621 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800622}
623
Linus Torvalds1da177e2005-04-16 15:20:36 -0700624/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000625 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700626 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900627int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700628{
Yang Shi476b30a2021-05-04 18:36:39 -0700629 unsigned int size;
630 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000631
Yang Shi476b30a2021-05-04 18:36:39 -0700632 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
633 err = prealloc_memcg_shrinker(shrinker);
634 if (err != -ENOSYS)
635 return err;
636
637 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
638 }
639
640 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000641 if (shrinker->flags & SHRINKER_NUMA_AWARE)
642 size *= nr_node_ids;
643
644 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
645 if (!shrinker->nr_deferred)
646 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700647
Tetsuo Handa8e049442018-04-04 19:53:07 +0900648 return 0;
649}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000650
Tetsuo Handa8e049442018-04-04 19:53:07 +0900651void free_prealloced_shrinker(struct shrinker *shrinker)
652{
Yang Shi41ca6682021-05-04 18:36:29 -0700653 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
654 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700655 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700656 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700657 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700658 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700659
Tetsuo Handa8e049442018-04-04 19:53:07 +0900660 kfree(shrinker->nr_deferred);
661 shrinker->nr_deferred = NULL;
662}
663
664void register_shrinker_prepared(struct shrinker *shrinker)
665{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700666 down_write(&shrinker_rwsem);
667 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700668 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700669 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900670}
671
672int register_shrinker(struct shrinker *shrinker)
673{
674 int err = prealloc_shrinker(shrinker);
675
676 if (err)
677 return err;
678 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000679 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700680}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700681EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700682
683/*
684 * Remove one
685 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700686void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700687{
Yang Shi41ca6682021-05-04 18:36:29 -0700688 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900689 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700690
Linus Torvalds1da177e2005-04-16 15:20:36 -0700691 down_write(&shrinker_rwsem);
692 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700693 shrinker->flags &= ~SHRINKER_REGISTERED;
694 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
695 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700696 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700697
Andrew Vaginae393322013-10-16 13:46:46 -0700698 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900699 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700700}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700701EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700702
703#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000704
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800705static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800706 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700707{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000708 unsigned long freed = 0;
709 unsigned long long delta;
710 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700711 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000712 long nr;
713 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000714 long batch_size = shrinker->batch ? shrinker->batch
715 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800716 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000717
rongqianfeng8da6ee32021-05-21 10:30:14 +0800718 trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
719
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700720 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700721 if (freeable == 0 || freeable == SHRINK_EMPTY)
722 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000723
724 /*
725 * copy the current shrinker scan count into a local variable
726 * and zero it so that other concurrent shrinker invocations
727 * don't also do this scanning work.
728 */
Yang Shi86750832021-05-04 18:36:36 -0700729 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000730
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700731 if (shrinker->seeks) {
732 delta = freeable >> priority;
733 delta *= 4;
734 do_div(delta, shrinker->seeks);
735 } else {
736 /*
737 * These objects don't require any IO to create. Trim
738 * them aggressively under memory pressure to keep
739 * them from causing refetches in the IO caches.
740 */
741 delta = freeable / 2;
742 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700743
Yang Shi18bb4732021-05-04 18:36:45 -0700744 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000745 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700746 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000747
748 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800749 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000750
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800751 /*
752 * Normally, we should not scan less than batch_size objects in one
753 * pass to avoid too frequent shrinker calls, but if the slab has less
754 * than batch_size objects in total and we are really tight on memory,
755 * we will try to reclaim all available objects, otherwise we can end
756 * up failing allocations although there are plenty of reclaimable
757 * objects spread over several slabs with usage less than the
758 * batch_size.
759 *
760 * We detect the "tight on memory" situations by looking at the total
761 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700762 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800763 * scanning at high prio and therefore should try to reclaim as much as
764 * possible.
765 */
766 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700767 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000768 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800769 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000770
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800771 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700772 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000773 ret = shrinker->scan_objects(shrinker, shrinkctl);
774 if (ret == SHRINK_STOP)
775 break;
776 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000777
Chris Wilsond460acb2017-09-06 16:19:26 -0700778 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
779 total_scan -= shrinkctl->nr_scanned;
780 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000781
782 cond_resched();
783 }
784
Yang Shi18bb4732021-05-04 18:36:45 -0700785 /*
786 * The deferred work is increased by any new work (delta) that wasn't
787 * done, decreased by old deferred work that was done now.
788 *
789 * And it is capped to two times of the freeable items.
790 */
791 next_deferred = max_t(long, (nr + delta - scanned), 0);
792 next_deferred = min(next_deferred, (2 * freeable));
793
Glauber Costa1d3d4432013-08-28 10:18:04 +1000794 /*
795 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700796 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000797 */
Yang Shi86750832021-05-04 18:36:36 -0700798 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000799
Yang Shi8efb4b52021-05-04 18:36:08 -0700800 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000801 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700802}
803
Yang Shi0a432dc2019-09-23 15:38:12 -0700804#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700805static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
806 struct mem_cgroup *memcg, int priority)
807{
Yang Shie4262c42021-05-04 18:36:23 -0700808 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700809 unsigned long ret, freed = 0;
810 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700811
Yang Shi0a432dc2019-09-23 15:38:12 -0700812 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700813 return 0;
814
815 if (!down_read_trylock(&shrinker_rwsem))
816 return 0;
817
Yang Shi468ab842021-05-04 18:36:26 -0700818 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700819 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700820 goto unlock;
821
Yang Shie4262c42021-05-04 18:36:23 -0700822 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700823 struct shrink_control sc = {
824 .gfp_mask = gfp_mask,
825 .nid = nid,
826 .memcg = memcg,
827 };
828 struct shrinker *shrinker;
829
830 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700831 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700832 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700833 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700834 continue;
835 }
836
Yang Shi0a432dc2019-09-23 15:38:12 -0700837 /* Call non-slab shrinkers even though kmem is disabled */
838 if (!memcg_kmem_enabled() &&
839 !(shrinker->flags & SHRINKER_NONSLAB))
840 continue;
841
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700842 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700843 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700844 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700845 /*
846 * After the shrinker reported that it had no objects to
847 * free, but before we cleared the corresponding bit in
848 * the memcg shrinker map, a new object might have been
849 * added. To make sure, we have the bit set in this
850 * case, we invoke the shrinker one more time and reset
851 * the bit if it reports that it is not empty anymore.
852 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700853 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700854 *
855 * list_lru_add() shrink_slab_memcg()
856 * list_add_tail() clear_bit()
857 * <MB> <MB>
858 * set_bit() do_shrink_slab()
859 */
860 smp_mb__after_atomic();
861 ret = do_shrink_slab(&sc, shrinker, priority);
862 if (ret == SHRINK_EMPTY)
863 ret = 0;
864 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700865 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700866 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700867 freed += ret;
868
869 if (rwsem_is_contended(&shrinker_rwsem)) {
870 freed = freed ? : 1;
871 break;
872 }
873 }
874unlock:
875 up_read(&shrinker_rwsem);
876 return freed;
877}
Yang Shi0a432dc2019-09-23 15:38:12 -0700878#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700879static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
880 struct mem_cgroup *memcg, int priority)
881{
882 return 0;
883}
Yang Shi0a432dc2019-09-23 15:38:12 -0700884#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700885
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800886/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800887 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800888 * @gfp_mask: allocation context
889 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800890 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800891 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700892 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800893 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700894 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800895 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
896 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700897 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700898 * @memcg specifies the memory cgroup to target. Unaware shrinkers
899 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800900 *
Josef Bacik9092c712018-01-31 16:16:26 -0800901 * @priority is sc->priority, we take the number of objects and >> by priority
902 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700903 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800904 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700905 */
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800906unsigned long shrink_slab(gfp_t gfp_mask, int nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800907 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800908 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700909{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700910 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700911 struct shrinker *shrinker;
wudean842c68a2021-04-27 17:40:41 +0800912 bool bypass = false;
913
914 trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
915 if (bypass)
916 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700917
Yang Shifa1e5122019-08-02 21:48:44 -0700918 /*
919 * The root memcg might be allocated even though memcg is disabled
920 * via "cgroup_disable=memory" boot parameter. This could make
921 * mem_cgroup_is_root() return false, then just run memcg slab
922 * shrink, but skip global shrink. This may result in premature
923 * oom.
924 */
925 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700926 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800927
Tetsuo Handae830c632018-04-05 16:23:35 -0700928 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700929 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700930
931 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800932 struct shrink_control sc = {
933 .gfp_mask = gfp_mask,
934 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800935 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800936 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800937
Kirill Tkhai9b996462018-08-17 15:48:21 -0700938 ret = do_shrink_slab(&sc, shrinker, priority);
939 if (ret == SHRINK_EMPTY)
940 ret = 0;
941 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800942 /*
943 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700944 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800945 * by parallel ongoing shrinking.
946 */
947 if (rwsem_is_contended(&shrinker_rwsem)) {
948 freed = freed ? : 1;
949 break;
950 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700951 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800952
Linus Torvalds1da177e2005-04-16 15:20:36 -0700953 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700954out:
955 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000956 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700957}
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800958EXPORT_SYMBOL_GPL(shrink_slab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700959
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800960void drop_slab_node(int nid)
961{
962 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700963 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800964
965 do {
966 struct mem_cgroup *memcg = NULL;
967
Chunxin Zang069c4112020-10-13 16:56:46 -0700968 if (fatal_signal_pending(current))
969 return;
970
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800971 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700972 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800973 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800974 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800975 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700976 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800977}
978
979void drop_slab(void)
980{
981 int nid;
982
983 for_each_online_node(nid)
984 drop_slab_node(nid);
985}
986
Linus Torvalds1da177e2005-04-16 15:20:36 -0700987static inline int is_page_cache_freeable(struct page *page)
988{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700989 /*
990 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400991 * that isolated the page, the page cache and optional buffer
992 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700993 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -0700994 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400995 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700996}
997
Yang Shicb165562019-11-30 17:55:28 -0800998static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700999{
Christoph Lameter930d9152006-01-08 01:00:47 -08001000 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001001 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001002 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001003 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001004 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001005 return 1;
1006 return 0;
1007}
1008
1009/*
1010 * We detected a synchronous write error writing a page out. Probably
1011 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1012 * fsync(), msync() or close().
1013 *
1014 * The tricky part is that after writepage we cannot touch the mapping: nothing
1015 * prevents it from being freed up. But we have a ref on the page and once
1016 * that page is locked, the mapping is pinned.
1017 *
1018 * We're allowed to run sleeping lock_page() here because we know the caller has
1019 * __GFP_FS.
1020 */
1021static void handle_write_error(struct address_space *mapping,
1022 struct page *page, int error)
1023{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001024 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001025 if (page_mapping(page) == mapping)
1026 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001027 unlock_page(page);
1028}
1029
Christoph Lameter04e62a22006-06-23 02:03:38 -07001030/* possible outcome of pageout() */
1031typedef enum {
1032 /* failed to write page out, page is locked */
1033 PAGE_KEEP,
1034 /* move page to the active list, page is locked */
1035 PAGE_ACTIVATE,
1036 /* page has been sent to the disk successfully, page is unlocked */
1037 PAGE_SUCCESS,
1038 /* page is clean and locked */
1039 PAGE_CLEAN,
1040} pageout_t;
1041
Linus Torvalds1da177e2005-04-16 15:20:36 -07001042/*
Andrew Morton1742f192006-03-22 00:08:21 -08001043 * pageout is called by shrink_page_list() for each dirty page.
1044 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001045 */
Yang Shicb165562019-11-30 17:55:28 -08001046static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001047{
1048 /*
1049 * If the page is dirty, only perform writeback if that write
1050 * will be non-blocking. To prevent this allocation from being
1051 * stalled by pagecache activity. But note that there may be
1052 * stalls if we need to run get_block(). We could test
1053 * PagePrivate for that.
1054 *
Al Viro81742022014-04-03 03:17:43 -04001055 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001056 * this page's queue, we can perform writeback even if that
1057 * will block.
1058 *
1059 * If the page is swapcache, write it back even if that would
1060 * block, for some throttling. This happens by accident, because
1061 * swap_backing_dev_info is bust: it doesn't reflect the
1062 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001063 */
1064 if (!is_page_cache_freeable(page))
1065 return PAGE_KEEP;
1066 if (!mapping) {
1067 /*
1068 * Some data journaling orphaned pages can have
1069 * page->mapping == NULL while being dirty with clean buffers.
1070 */
David Howells266cf652009-04-03 16:42:36 +01001071 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001072 if (try_to_free_buffers(page)) {
1073 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001074 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001075 return PAGE_CLEAN;
1076 }
1077 }
1078 return PAGE_KEEP;
1079 }
1080 if (mapping->a_ops->writepage == NULL)
1081 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001082 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001083 return PAGE_KEEP;
1084
1085 if (clear_page_dirty_for_io(page)) {
1086 int res;
1087 struct writeback_control wbc = {
1088 .sync_mode = WB_SYNC_NONE,
1089 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001090 .range_start = 0,
1091 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001092 .for_reclaim = 1,
1093 };
1094
1095 SetPageReclaim(page);
1096 res = mapping->a_ops->writepage(page, &wbc);
1097 if (res < 0)
1098 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001099 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001100 ClearPageReclaim(page);
1101 return PAGE_ACTIVATE;
1102 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001103
Linus Torvalds1da177e2005-04-16 15:20:36 -07001104 if (!PageWriteback(page)) {
1105 /* synchronous write or broken a_ops? */
1106 ClearPageReclaim(page);
1107 }
yalin wang3aa23852016-01-14 15:18:30 -08001108 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001109 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001110 return PAGE_SUCCESS;
1111 }
1112
1113 return PAGE_CLEAN;
1114}
1115
Andrew Mortona649fd92006-10-17 00:09:36 -07001116/*
Nick Piggine2867812008-07-25 19:45:30 -07001117 * Same as remove_mapping, but if the page is removed from the mapping, it
1118 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001119 */
Johannes Weinera5289102014-04-03 14:47:51 -07001120static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001121 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001122{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001123 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001124 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001125
Nick Piggin28e4d962006-09-25 23:31:23 -07001126 BUG_ON(!PageLocked(page));
1127 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001128
Johannes Weiner30472502021-09-02 14:53:18 -07001129 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001130 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001131 * The non racy check for a busy page.
1132 *
1133 * Must be careful with the order of the tests. When someone has
1134 * a ref to the page, it may be possible that they dirty it then
1135 * drop the reference. So if PageDirty is tested before page_count
1136 * here, then the following race may occur:
1137 *
1138 * get_user_pages(&page);
1139 * [user mapping goes away]
1140 * write_to(page);
1141 * !PageDirty(page) [good]
1142 * SetPageDirty(page);
1143 * put_page(page);
1144 * !page_count(page) [good, discard it]
1145 *
1146 * [oops, our write_to data is lost]
1147 *
1148 * Reversing the order of the tests ensures such a situation cannot
1149 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001150 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001151 *
1152 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001153 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001154 */
William Kucharski906d2782019-10-18 20:20:33 -07001155 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001156 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001157 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001158 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001159 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001160 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001161 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001162 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001163
1164 if (PageSwapCache(page)) {
1165 swp_entry_t swap = { .val = page_private(page) };
Yu Zhao37397872022-09-18 02:00:03 -06001166
1167 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001168 if (reclaimed && !mapping_exiting(mapping))
1169 shadow = workingset_eviction(page, target_memcg);
Yu Zhao37397872022-09-18 02:00:03 -06001170 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001171 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001172 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001173 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001174 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001175 void (*freepage)(struct page *);
1176
1177 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001178 /*
1179 * Remember a shadow entry for reclaimed file cache in
1180 * order to detect refaults, thus thrashing, later on.
1181 *
1182 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001183 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001184 * inode reclaim needs to empty out the radix tree or
1185 * the nodes are lost. Don't plant shadows behind its
1186 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001187 *
1188 * We also don't store shadows for DAX mappings because the
1189 * only page cache pages found in these are zero pages
1190 * covering holes, and because we don't want to mix DAX
1191 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001192 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001193 */
Huang Ying9de4f222020-04-06 20:04:41 -07001194 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001195 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001196 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001197 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001198 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001199
1200 if (freepage != NULL)
1201 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001202 }
1203
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001204 return 1;
1205
1206cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001207 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001208 return 0;
1209}
1210
Linus Torvalds1da177e2005-04-16 15:20:36 -07001211/*
Nick Piggine2867812008-07-25 19:45:30 -07001212 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1213 * someone else has a ref on the page, abort and return 0. If it was
1214 * successfully detached, return 1. Assumes the caller has a single ref on
1215 * this page.
1216 */
1217int remove_mapping(struct address_space *mapping, struct page *page)
1218{
Johannes Weinerb9107182019-11-30 17:55:59 -08001219 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001220 /*
1221 * Unfreezing the refcount with 1 rather than 2 effectively
1222 * drops the pagecache ref for us without requiring another
1223 * atomic operation.
1224 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001225 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001226 return 1;
1227 }
1228 return 0;
1229}
1230
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001231/**
1232 * putback_lru_page - put previously isolated page onto appropriate LRU list
1233 * @page: page to be put back to appropriate lru list
1234 *
1235 * Add previously isolated @page to appropriate LRU list.
1236 * Page may still be unevictable for other reasons.
1237 *
1238 * lru_lock must not be held, interrupts must be enabled.
1239 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001240void putback_lru_page(struct page *page)
1241{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001242 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001243 put_page(page); /* drop ref from isolate */
1244}
1245
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001246enum page_references {
1247 PAGEREF_RECLAIM,
1248 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001249 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001250 PAGEREF_ACTIVATE,
1251};
1252
1253static enum page_references page_check_references(struct page *page,
1254 struct scan_control *sc)
1255{
Johannes Weiner645747462010-03-05 13:42:22 -08001256 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001257 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001258
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001259 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1260 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001261 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001262
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001263 /*
1264 * Mlock lost the isolation race with us. Let try_to_unmap()
1265 * move the page to the unevictable list.
1266 */
1267 if (vm_flags & VM_LOCKED)
1268 return PAGEREF_RECLAIM;
1269
Minchan Kimf74aca72022-05-19 14:08:54 -07001270 /* rmap lock contention: rotate */
1271 if (referenced_ptes == -1)
1272 return PAGEREF_KEEP;
1273
Johannes Weiner645747462010-03-05 13:42:22 -08001274 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001275 /*
1276 * All mapped pages start out with page table
1277 * references from the instantiating fault, so we need
1278 * to look twice if a mapped file page is used more
1279 * than once.
1280 *
1281 * Mark it and spare it for another trip around the
1282 * inactive list. Another page table reference will
1283 * lead to its activation.
1284 *
1285 * Note: the mark is set for activated pages as well
1286 * so that recently deactivated but used pages are
1287 * quickly recovered.
1288 */
1289 SetPageReferenced(page);
1290
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001291 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001292 return PAGEREF_ACTIVATE;
1293
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001294 /*
1295 * Activate file-backed executable pages after first usage.
1296 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001297 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001298 return PAGEREF_ACTIVATE;
1299
Johannes Weiner645747462010-03-05 13:42:22 -08001300 return PAGEREF_KEEP;
1301 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001302
1303 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001304 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001305 return PAGEREF_RECLAIM_CLEAN;
1306
1307 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001308}
1309
Mel Gormane2be15f2013-07-03 15:01:57 -07001310/* Check if a page is dirty or under writeback */
1311static void page_check_dirty_writeback(struct page *page,
1312 bool *dirty, bool *writeback)
1313{
Mel Gormanb4597222013-07-03 15:02:05 -07001314 struct address_space *mapping;
1315
Mel Gormane2be15f2013-07-03 15:01:57 -07001316 /*
1317 * Anonymous pages are not handled by flushers and must be written
1318 * from reclaim context. Do not stall reclaim based on them
1319 */
Huang Ying9de4f222020-04-06 20:04:41 -07001320 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001321 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001322 *dirty = false;
1323 *writeback = false;
1324 return;
1325 }
1326
1327 /* By default assume that the page flags are accurate */
1328 *dirty = PageDirty(page);
1329 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001330
1331 /* Verify dirty/writeback state if the filesystem supports it */
1332 if (!page_has_private(page))
1333 return;
1334
1335 mapping = page_mapping(page);
1336 if (mapping && mapping->a_ops->is_dirty_writeback)
1337 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001338}
1339
Dave Hansen26aa2d12021-09-02 14:59:16 -07001340static struct page *alloc_demote_page(struct page *page, unsigned long node)
1341{
1342 struct migration_target_control mtc = {
1343 /*
1344 * Allocate from 'node', or fail quickly and quietly.
1345 * When this happens, 'page' will likely just be discarded
1346 * instead of migrated.
1347 */
1348 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1349 __GFP_THISNODE | __GFP_NOWARN |
1350 __GFP_NOMEMALLOC | GFP_NOWAIT,
1351 .nid = node
1352 };
1353
1354 return alloc_migration_target(page, (unsigned long)&mtc);
1355}
1356
1357/*
1358 * Take pages on @demote_list and attempt to demote them to
1359 * another node. Pages which are not demoted are left on
1360 * @demote_pages.
1361 */
1362static unsigned int demote_page_list(struct list_head *demote_pages,
1363 struct pglist_data *pgdat)
1364{
1365 int target_nid = next_demotion_node(pgdat->node_id);
1366 unsigned int nr_succeeded;
1367 int err;
1368
1369 if (list_empty(demote_pages))
1370 return 0;
1371
1372 if (target_nid == NUMA_NO_NODE)
1373 return 0;
1374
1375 /* Demotion ignores all cpuset and mempolicy settings */
1376 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1377 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1378 &nr_succeeded);
1379
Yang Shi668e4142021-09-02 14:59:19 -07001380 if (current_is_kswapd())
1381 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1382 else
1383 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1384
Dave Hansen26aa2d12021-09-02 14:59:16 -07001385 return nr_succeeded;
1386}
1387
Nick Piggine2867812008-07-25 19:45:30 -07001388/*
Andrew Morton1742f192006-03-22 00:08:21 -08001389 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001390 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001391static unsigned int shrink_page_list(struct list_head *page_list,
1392 struct pglist_data *pgdat,
1393 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001394 struct reclaim_stat *stat,
1395 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001396{
1397 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001398 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001399 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001400 unsigned int nr_reclaimed = 0;
1401 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001402 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001403
Kirill Tkhai060f0052019-03-05 15:48:15 -08001404 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001405 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001406 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001407
Dave Hansen26aa2d12021-09-02 14:59:16 -07001408retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001409 while (!list_empty(page_list)) {
1410 struct address_space *mapping;
1411 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001412 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001413 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001414 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001415
1416 cond_resched();
1417
1418 page = lru_to_page(page_list);
1419 list_del(&page->lru);
1420
Nick Piggin529ae9a2008-08-02 12:01:03 +02001421 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001422 goto keep;
1423
Sasha Levin309381fea2014-01-23 15:52:54 -08001424 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001425
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001426 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001427
1428 /* Account the number of base pages even though THP */
1429 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001430
Hugh Dickins39b5f292012-10-08 16:33:18 -07001431 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001432 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001433
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001434 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001435 goto keep_locked;
1436
Yu Zhao0182f922022-09-18 02:00:04 -06001437 /* page_update_gen() tried to promote this page? */
1438 if (lru_gen_enabled() && !ignore_references &&
1439 page_mapped(page) && PageReferenced(page))
1440 goto keep_locked;
1441
Andy Whitcroftc661b072007-08-22 14:01:26 -07001442 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1443 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1444
Mel Gorman283aba92013-07-03 15:01:51 -07001445 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001446 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001447 * reclaim_congested which affects wait_iff_congested. kswapd
1448 * will stall and start writing pages if the tail of the LRU
1449 * is all dirty unqueued pages.
1450 */
1451 page_check_dirty_writeback(page, &dirty, &writeback);
1452 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001453 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001454
1455 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001456 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001457
Mel Gormand04e8ac2013-07-03 15:02:03 -07001458 /*
1459 * Treat this page as congested if the underlying BDI is or if
1460 * pages are cycling through the LRU so quickly that the
1461 * pages marked for immediate reclaim are making it to the
1462 * end of the LRU a second time.
1463 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001464 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001465 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001466 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001467 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001468 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001469
1470 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001471 * If a page at the tail of the LRU is under writeback, there
1472 * are three cases to consider.
1473 *
1474 * 1) If reclaim is encountering an excessive number of pages
1475 * under writeback and this page is both under writeback and
1476 * PageReclaim then it indicates that pages are being queued
1477 * for IO but are being recycled through the LRU before the
1478 * IO can complete. Waiting on the page itself risks an
1479 * indefinite stall if it is impossible to writeback the
1480 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001481 * note that the LRU is being scanned too quickly and the
1482 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001483 *
Tejun Heo97c93412015-05-22 18:23:36 -04001484 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001485 * not marked for immediate reclaim, or the caller does not
1486 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1487 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001488 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001489 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001490 * Require may_enter_fs because we would wait on fs, which
1491 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001492 * enter reclaim, and deadlock if it waits on a page for
1493 * which it is needed to do the write (loop masks off
1494 * __GFP_IO|__GFP_FS for this reason); but more thought
1495 * would probably show more reasons.
1496 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001497 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001498 * PageReclaim. memcg does not have any dirty pages
1499 * throttling so we could easily OOM just because too many
1500 * pages are in writeback and there is nothing else to
1501 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001502 *
1503 * In cases 1) and 2) we activate the pages to get them out of
1504 * the way while we continue scanning for clean pages on the
1505 * inactive list and refilling from the active list. The
1506 * observation here is that waiting for disk writes is more
1507 * expensive than potentially causing reloads down the line.
1508 * Since they're marked for immediate reclaim, they won't put
1509 * memory pressure on the cache working set any longer than it
1510 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001511 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001512 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001513 /* Case 1 above */
1514 if (current_is_kswapd() &&
1515 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001516 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001517 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001518 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001519
1520 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001521 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001522 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001523 /*
1524 * This is slightly racy - end_page_writeback()
1525 * might have just cleared PageReclaim, then
1526 * setting PageReclaim here end up interpreted
1527 * as PageReadahead - but that does not matter
1528 * enough to care. What we do want is for this
1529 * page to have PageReclaim set next time memcg
1530 * reclaim reaches the tests above, so it will
1531 * then wait_on_page_writeback() to avoid OOM;
1532 * and it's also appropriate in global reclaim.
1533 */
1534 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001535 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001536 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001537
1538 /* Case 3 above */
1539 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001540 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001541 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001542 /* then go back and try same page again */
1543 list_add_tail(&page->lru, page_list);
1544 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001545 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001546 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001547
Minchan Kim8940b342019-09-25 16:49:11 -07001548 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001549 references = page_check_references(page, sc);
1550
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001551 switch (references) {
1552 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001553 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001554 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001555 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001556 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001557 case PAGEREF_RECLAIM:
1558 case PAGEREF_RECLAIM_CLEAN:
1559 ; /* try to reclaim the page below */
1560 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001561
Linus Torvalds1da177e2005-04-16 15:20:36 -07001562 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001563 * Before reclaiming the page, try to relocate
1564 * its contents to another node.
1565 */
1566 if (do_demote_pass &&
1567 (thp_migration_supported() || !PageTransHuge(page))) {
1568 list_add(&page->lru, &demote_pages);
1569 unlock_page(page);
1570 continue;
1571 }
1572
1573 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001574 * Anonymous process memory has backing store?
1575 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001576 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001577 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001578 if (PageAnon(page) && PageSwapBacked(page)) {
1579 if (!PageSwapCache(page)) {
1580 if (!(sc->gfp_mask & __GFP_IO))
1581 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001582 if (page_maybe_dma_pinned(page))
1583 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001584 if (PageTransHuge(page)) {
1585 /* cannot split THP, skip it */
1586 if (!can_split_huge_page(page, NULL))
1587 goto activate_locked;
1588 /*
1589 * Split pages without a PMD map right
1590 * away. Chances are some or all of the
1591 * tail pages can be freed without IO.
1592 */
1593 if (!compound_mapcount(page) &&
1594 split_huge_page_to_list(page,
1595 page_list))
1596 goto activate_locked;
1597 }
1598 if (!add_to_swap(page)) {
1599 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001600 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001601 /* Fallback to swap normal pages */
1602 if (split_huge_page_to_list(page,
1603 page_list))
1604 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001605#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1606 count_vm_event(THP_SWPOUT_FALLBACK);
1607#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001608 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001609 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001610 }
Minchan Kim0f074652017-07-06 15:37:24 -07001611
Kirill Tkhai4b793062020-04-01 21:10:18 -07001612 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001613
1614 /* Adding to swap updated mapping */
1615 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001616 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001617 } else if (unlikely(PageTransHuge(page))) {
1618 /* Split file THP */
1619 if (split_huge_page_to_list(page, page_list))
1620 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001621 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001622
1623 /*
Yang Shi98879b32019-07-11 20:59:30 -07001624 * THP may get split above, need minus tail pages and update
1625 * nr_pages to avoid accounting tail pages twice.
1626 *
1627 * The tail pages that are added into swap cache successfully
1628 * reach here.
1629 */
1630 if ((nr_pages > 1) && !PageTransHuge(page)) {
1631 sc->nr_scanned -= (nr_pages - 1);
1632 nr_pages = 1;
1633 }
1634
1635 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001636 * The page is mapped into the page tables of one or more
1637 * processes. Try to unmap it here.
1638 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001639 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001640 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001641 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001642
1643 if (unlikely(PageTransHuge(page)))
1644 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001645
Yang Shi1fb08ac2021-06-30 18:52:01 -07001646 try_to_unmap(page, flags);
1647 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001648 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001649 if (!was_swapbacked && PageSwapBacked(page))
1650 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001651 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001652 }
1653 }
1654
1655 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001656 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001657 * Only kswapd can writeback filesystem pages
1658 * to avoid risk of stack overflow. But avoid
1659 * injecting inefficient single-page IO into
1660 * flusher writeback as much as possible: only
1661 * write pages when we've encountered many
1662 * dirty pages, and when we've already scanned
1663 * the rest of the LRU for clean pages and see
1664 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001665 */
Huang Ying9de4f222020-04-06 20:04:41 -07001666 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001667 (!current_is_kswapd() || !PageReclaim(page) ||
1668 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001669 /*
1670 * Immediately reclaim when written back.
1671 * Similar in principal to deactivate_page()
1672 * except we already have the page isolated
1673 * and know it's dirty
1674 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001675 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001676 SetPageReclaim(page);
1677
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001678 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001679 }
1680
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001681 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001682 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001683 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001684 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001685 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001686 goto keep_locked;
1687
Mel Gormand950c942015-09-04 15:47:35 -07001688 /*
1689 * Page is dirty. Flush the TLB if a writable entry
1690 * potentially exists to avoid CPU writes after IO
1691 * starts and then write it out here.
1692 */
1693 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001694 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001695 case PAGE_KEEP:
1696 goto keep_locked;
1697 case PAGE_ACTIVATE:
1698 goto activate_locked;
1699 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001700 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001701
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001702 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001703 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001704 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001705 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001706
Linus Torvalds1da177e2005-04-16 15:20:36 -07001707 /*
1708 * A synchronous write - probably a ramdisk. Go
1709 * ahead and try to reclaim the page.
1710 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001711 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001712 goto keep;
1713 if (PageDirty(page) || PageWriteback(page))
1714 goto keep_locked;
1715 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001716 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001717 case PAGE_CLEAN:
1718 ; /* try to free the page below */
1719 }
1720 }
1721
1722 /*
1723 * If the page has buffers, try to free the buffer mappings
1724 * associated with this page. If we succeed we try to free
1725 * the page as well.
1726 *
1727 * We do this even if the page is PageDirty().
1728 * try_to_release_page() does not perform I/O, but it is
1729 * possible for a page to have PageDirty set, but it is actually
1730 * clean (all its buffers are clean). This happens if the
1731 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001732 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001733 * try_to_release_page() will discover that cleanness and will
1734 * drop the buffers and mark the page clean - it can be freed.
1735 *
1736 * Rarely, pages can have buffers and no ->mapping. These are
1737 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001738 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001739 * and if that worked, and the page is no longer mapped into
1740 * process address space (page_count == 1) it can be freed.
1741 * Otherwise, leave the page on the LRU so it is swappable.
1742 */
David Howells266cf652009-04-03 16:42:36 +01001743 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001744 if (!try_to_release_page(page, sc->gfp_mask))
1745 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001746 if (!mapping && page_count(page) == 1) {
1747 unlock_page(page);
1748 if (put_page_testzero(page))
1749 goto free_it;
1750 else {
1751 /*
1752 * rare race with speculative reference.
1753 * the speculative reference will free
1754 * this page shortly, so we may
1755 * increment nr_reclaimed here (and
1756 * leave it off the LRU).
1757 */
1758 nr_reclaimed++;
1759 continue;
1760 }
1761 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001762 }
1763
Shaohua Li802a3a92017-05-03 14:52:32 -07001764 if (PageAnon(page) && !PageSwapBacked(page)) {
1765 /* follow __remove_mapping for reference */
1766 if (!page_ref_freeze(page, 1))
1767 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001768 /*
1769 * The page has only one reference left, which is
1770 * from the isolation. After the caller puts the
1771 * page back on lru and drops the reference, the
1772 * page will be freed anyway. It doesn't matter
1773 * which lru it goes. So we don't bother checking
1774 * PageDirty here.
1775 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001776 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001777 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001778 } else if (!mapping || !__remove_mapping(mapping, page, true,
1779 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001780 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001781
1782 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001783free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001784 /*
1785 * THP may get swapped out in a whole, need account
1786 * all base pages.
1787 */
1788 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001789
1790 /*
1791 * Is there need to periodically free_page_list? It would
1792 * appear not as the counts should be low
1793 */
Yang Shi7ae88532019-09-23 15:38:09 -07001794 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001795 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001796 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001797 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001798 continue;
1799
Yang Shi98879b32019-07-11 20:59:30 -07001800activate_locked_split:
1801 /*
1802 * The tail pages that are failed to add into swap cache
1803 * reach here. Fixup nr_scanned and nr_pages.
1804 */
1805 if (nr_pages > 1) {
1806 sc->nr_scanned -= (nr_pages - 1);
1807 nr_pages = 1;
1808 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001809activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001810 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001811 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1812 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001813 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001814 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001815 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001816 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001817 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001818 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001819 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001820 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001821keep_locked:
1822 unlock_page(page);
1823keep:
1824 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001825 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001826 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001827 /* 'page_list' is always empty here */
1828
1829 /* Migrate pages selected for demotion */
1830 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1831 /* Pages that could not be demoted are still in @demote_pages */
1832 if (!list_empty(&demote_pages)) {
1833 /* Pages which failed to demoted go back on @page_list for retry: */
1834 list_splice_init(&demote_pages, page_list);
1835 do_demote_pass = false;
1836 goto retry;
1837 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001838
Yang Shi98879b32019-07-11 20:59:30 -07001839 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1840
Johannes Weiner747db952014-08-08 14:19:24 -07001841 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001842 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001843 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001844
Linus Torvalds1da177e2005-04-16 15:20:36 -07001845 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001846 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001847
Andrew Morton05ff5132006-03-22 00:08:20 -08001848 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001849}
1850
Maninder Singh730ec8c2020-06-03 16:01:18 -07001851unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001852 struct list_head *page_list)
1853{
1854 struct scan_control sc = {
1855 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001856 .may_unmap = 1,
1857 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001858 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001859 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001860 struct page *page, *next;
1861 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001862 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001863
1864 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001865 if (!PageHuge(page) && page_is_file_lru(page) &&
1866 !PageDirty(page) && !__PageMovable(page) &&
1867 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001868 ClearPageActive(page);
1869 list_move(&page->lru, &clean_pages);
1870 }
1871 }
1872
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001873 /*
1874 * We should be safe here since we are only dealing with file pages and
1875 * we are not kswapd and therefore cannot write dirty file pages. But
1876 * call memalloc_noreclaim_save() anyway, just in case these conditions
1877 * change in the future.
1878 */
1879 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001880 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001881 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001882 memalloc_noreclaim_restore(noreclaim_flag);
1883
Minchan Kim02c6de82012-10-08 16:31:55 -07001884 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001885 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1886 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001887 /*
1888 * Since lazyfree pages are isolated from file LRU from the beginning,
1889 * they will rotate back to anonymous LRU in the end if it failed to
1890 * discard so isolated count will be mismatched.
1891 * Compensate the isolated count for both LRU lists.
1892 */
1893 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1894 stat.nr_lazyfree_fail);
1895 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001896 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001897 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001898}
1899
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001900/*
Mel Gorman7ee36a12016-07-28 15:47:17 -07001901 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001902 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001903 */
1904static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001905 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001906{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001907 int zid;
1908
Mel Gorman7ee36a12016-07-28 15:47:17 -07001909 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1910 if (!nr_zone_taken[zid])
1911 continue;
1912
Wei Yanga892cb62020-06-03 16:01:12 -07001913 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001914 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001915
Mel Gorman7ee36a12016-07-28 15:47:17 -07001916}
1917
Mel Gormanf611fab2021-06-30 18:53:19 -07001918/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001919 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1920 *
1921 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001922 * shrink the lists perform better by taking out a batch of pages
1923 * and working on them outside the LRU lock.
1924 *
1925 * For pagecache intensive workloads, this function is the hottest
1926 * spot in the kernel (apart from copy_*_user functions).
1927 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001928 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001929 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001930 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001931 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001932 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001933 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001934 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001935 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001936 *
1937 * returns how many pages were moved onto *@dst.
1938 */
Andrew Morton69e05942006-03-22 00:08:19 -08001939static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001940 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001941 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001942 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001943{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001944 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001945 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001946 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001947 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07001948 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001949 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07001950 LIST_HEAD(pages_skipped);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001951
Yang Shi98879b32019-07-11 20:59:30 -07001952 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001953 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07001954 while (scan < nr_to_scan && !list_empty(src)) {
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001955 struct list_head *move_to = src;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001956 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001957
Linus Torvalds1da177e2005-04-16 15:20:36 -07001958 page = lru_to_page(src);
1959 prefetchw_prev_lru_page(page, src, flags);
1960
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001961 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001962 total_scan += nr_pages;
1963
Mel Gormanb2e18752016-07-28 15:45:37 -07001964 if (page_zonenum(page) > sc->reclaim_idx) {
Yang Shi98879b32019-07-11 20:59:30 -07001965 nr_skipped[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001966 move_to = &pages_skipped;
1967 goto move;
Mel Gormanb2e18752016-07-28 15:45:37 -07001968 }
1969
Minchan Kim791b48b2017-05-12 15:47:06 -07001970 /*
1971 * Do not count skipped pages because that makes the function
1972 * return with no isolated pages if the LRU mostly contains
1973 * ineligible pages. This causes the VM to not reclaim any
1974 * pages, triggering a premature OOM.
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001975 * Account all tail pages of THP.
Minchan Kim791b48b2017-05-12 15:47:06 -07001976 */
Yang Shi98879b32019-07-11 20:59:30 -07001977 scan += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001978
1979 if (!PageLRU(page))
1980 goto move;
1981 if (!sc->may_unmap && page_mapped(page))
1982 goto move;
1983
Alex Shic2135f72021-02-24 12:08:01 -08001984 /*
1985 * Be careful not to clear PageLRU until after we're
1986 * sure the page is not being freed elsewhere -- the
1987 * page release code relies on it.
1988 */
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001989 if (unlikely(!get_page_unless_zero(page)))
1990 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08001991
1992 if (!TestClearPageLRU(page)) {
1993 /* Another thread is already isolating this page */
1994 put_page(page);
Hugh Dickinsc5eda602022-03-22 14:45:41 -07001995 goto move;
Alex Shic2135f72021-02-24 12:08:01 -08001996 }
1997
1998 nr_taken += nr_pages;
1999 nr_zone_taken[page_zonenum(page)] += nr_pages;
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002000 move_to = dst;
2001move:
2002 list_move(&page->lru, move_to);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002003 }
2004
Mel Gormanb2e18752016-07-28 15:45:37 -07002005 /*
2006 * Splice any skipped pages to the start of the LRU list. Note that
2007 * this disrupts the LRU order when reclaiming for lower zones but
2008 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2009 * scanning would soon rescan the same pages to skip and put the
2010 * system at risk of premature OOM.
2011 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002012 if (!list_empty(&pages_skipped)) {
2013 int zid;
2014
Johannes Weiner3db65812017-05-03 14:52:13 -07002015 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002016 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2017 if (!nr_skipped[zid])
2018 continue;
2019
2020 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002021 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002022 }
2023 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002024 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002025 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Hugh Dickinsc5eda602022-03-22 14:45:41 -07002026 total_scan, skipped, nr_taken,
2027 sc->may_unmap ? 0 : ISOLATE_UNMAPPED, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002028 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002029 return nr_taken;
2030}
2031
Nick Piggin62695a82008-10-18 20:26:09 -07002032/**
2033 * isolate_lru_page - tries to isolate a page from its LRU list
2034 * @page: page to isolate from its LRU list
2035 *
2036 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2037 * vmstat statistic corresponding to whatever LRU list the page was on.
2038 *
2039 * Returns 0 if the page was removed from an LRU list.
2040 * Returns -EBUSY if the page was not on an LRU list.
2041 *
2042 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002043 * the active list, it will have PageActive set. If it was found on
2044 * the unevictable list, it will have the PageUnevictable bit set. That flag
2045 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002046 *
2047 * The vmstat statistic corresponding to the list on which the page was
2048 * found will be decremented.
2049 *
2050 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002051 *
Nick Piggin62695a82008-10-18 20:26:09 -07002052 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002053 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002054 * without a stable reference).
2055 * (2) the lru_lock must not be held.
2056 * (3) interrupts must be enabled.
2057 */
2058int isolate_lru_page(struct page *page)
2059{
2060 int ret = -EBUSY;
2061
Sasha Levin309381fea2014-01-23 15:52:54 -08002062 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002063 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002064
Alex Shid25b5bd2020-12-15 12:34:16 -08002065 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002066 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002067
Alex Shid25b5bd2020-12-15 12:34:16 -08002068 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002069 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002070 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002071 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002072 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002073 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002074
Nick Piggin62695a82008-10-18 20:26:09 -07002075 return ret;
2076}
2077
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002078/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002079 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002080 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002081 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2082 * the LRU list will go small and be scanned faster than necessary, leading to
2083 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002084 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002085static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002086 struct scan_control *sc)
2087{
2088 unsigned long inactive, isolated;
2089
2090 if (current_is_kswapd())
2091 return 0;
2092
Johannes Weinerb5ead352019-11-30 17:55:40 -08002093 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002094 return 0;
2095
2096 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002097 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2098 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002099 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002100 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2101 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002102 }
2103
Fengguang Wu3cf23842012-12-18 14:23:31 -08002104 /*
2105 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2106 * won't get blocked by normal direct-reclaimers, forming a circular
2107 * deadlock.
2108 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002109 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002110 inactive >>= 3;
2111
Rik van Riel35cd7812009-09-21 17:01:38 -07002112 return isolated > inactive;
2113}
2114
Kirill Tkhaia222f342019-05-13 17:17:00 -07002115/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002116 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2117 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002118 *
2119 * Returns the number of pages moved to the given lruvec.
2120 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002121static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2122 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002123{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002124 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002125 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002126 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002127
Kirill Tkhaia222f342019-05-13 17:17:00 -07002128 while (!list_empty(list)) {
2129 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002130 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002131 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002132 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002133 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002134 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002135 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002136 continue;
2137 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002138
Alex Shi3d06afa2020-12-15 12:33:37 -08002139 /*
2140 * The SetPageLRU needs to be kept here for list integrity.
2141 * Otherwise:
2142 * #0 move_pages_to_lru #1 release_pages
2143 * if !put_page_testzero
2144 * if (put_page_testzero())
2145 * !PageLRU //skip lru_lock
2146 * SetPageLRU()
2147 * list_add(&page->lru,)
2148 * list_add(&page->lru,)
2149 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002150 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002151
Alex Shi3d06afa2020-12-15 12:33:37 -08002152 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002153 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002154
2155 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002156 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002157 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002158 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002159 } else
2160 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002161
2162 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002163 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002164
Alex Shiafca9152020-12-15 12:34:02 -08002165 /*
2166 * All pages were isolated from the same lruvec (and isolation
2167 * inhibits memcg migration).
2168 */
Muchun Song7467c392021-06-28 19:37:59 -07002169 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002170 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002171 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002172 nr_moved += nr_pages;
2173 if (PageActive(page))
2174 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002175 }
Mel Gorman66635622010-08-09 17:19:30 -07002176
Hugh Dickins3f797682012-01-12 17:20:07 -08002177 /*
2178 * To save our caller's stack, now use input list for pages to free.
2179 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002180 list_splice(&pages_to_free, list);
2181
2182 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002183}
2184
2185/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002186 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002187 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002188 * In that case we should only throttle if the backing device it is
2189 * writing to is congested. In other cases it is safe to throttle.
2190 */
2191static int current_may_throttle(void)
2192{
NeilBrowna37b0712020-06-01 21:48:18 -07002193 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002194 current->backing_dev_info == NULL ||
2195 bdi_write_congested(current->backing_dev_info);
2196}
2197
2198/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002199 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002200 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002201 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002202static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002203shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002204 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002205{
2206 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002207 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002208 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002209 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002210 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002211 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002212 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002213 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002214 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002215
Mel Gorman599d0c92016-07-28 15:45:31 -07002216 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002217 if (stalled)
2218 return 0;
2219
2220 /* wait a bit for the reclaimer. */
2221 msleep(100);
2222 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002223
2224 /* We are about to die and free our memory. Return now. */
2225 if (fatal_signal_pending(current))
2226 return SWAP_CLUSTER_MAX;
2227 }
2228
Linus Torvalds1da177e2005-04-16 15:20:36 -07002229 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002230
Alex Shi6168d0d2020-12-15 12:34:29 -08002231 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002232
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002233 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002234 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002235
Mel Gorman599d0c92016-07-28 15:45:31 -07002236 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002237 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002238 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002239 __count_vm_events(item, nr_scanned);
2240 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002241 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2242
Alex Shi6168d0d2020-12-15 12:34:29 -08002243 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002244
Hillf Dantond563c052012-03-21 16:34:02 -07002245 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002246 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002247
Shakeel Butt013339d2020-12-14 19:06:39 -08002248 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002249
Alex Shi6168d0d2020-12-15 12:34:29 -08002250 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002251 move_pages_to_lru(lruvec, &page_list);
2252
2253 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002254 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002255 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002256 __count_vm_events(item, nr_reclaimed);
2257 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002258 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002259 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002260
Alex Shi75cc3c92020-12-15 14:20:50 -08002261 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002262 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002263 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002264
Mel Gorman92df3a72011-10-31 17:07:56 -07002265 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002266 * If dirty pages are scanned that are not queued for IO, it
2267 * implies that flushers are not doing their job. This can
2268 * happen when memory pressure pushes dirty pages to the end of
2269 * the LRU before the dirty limits are breached and the dirty
2270 * data has expired. It can also happen when the proportion of
2271 * dirty pages grows not through writes but through memory
2272 * pressure reclaiming all the clean cache. And in some cases,
2273 * the flushers simply cannot keep up with the allocation
2274 * rate. Nudge the flusher threads in case they are asleep.
2275 */
2276 if (stat.nr_unqueued_dirty == nr_taken)
2277 wakeup_flusher_threads(WB_REASON_VMSCAN);
2278
Andrey Ryabinind108c772018-04-10 16:27:59 -07002279 sc->nr.dirty += stat.nr_dirty;
2280 sc->nr.congested += stat.nr_congested;
2281 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2282 sc->nr.writeback += stat.nr_writeback;
2283 sc->nr.immediate += stat.nr_immediate;
2284 sc->nr.taken += nr_taken;
2285 if (file)
2286 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002287
Mel Gorman599d0c92016-07-28 15:45:31 -07002288 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002289 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002290 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002291}
2292
Hugh Dickins15b44732020-12-15 14:21:31 -08002293/*
2294 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2295 *
2296 * We move them the other way if the page is referenced by one or more
2297 * processes.
2298 *
2299 * If the pages are mostly unmapped, the processing is fast and it is
2300 * appropriate to hold lru_lock across the whole operation. But if
2301 * the pages are mapped, the processing is slow (page_referenced()), so
2302 * we should drop lru_lock around each page. It's impossible to balance
2303 * this, so instead we remove the pages from the LRU while processing them.
2304 * It is safe to rely on PG_active against the non-LRU pages in here because
2305 * nobody will play with that bit on a non-LRU page.
2306 *
2307 * The downside is that we have to touch page->_refcount against each page.
2308 * But we had to alter page->flags anyway.
2309 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002310static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002311 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002312 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002313 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002314{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002315 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002316 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002317 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002318 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002319 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002320 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002321 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002322 unsigned nr_deactivate, nr_activate;
2323 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002324 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002325 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002326 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002327
2328 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002329
Alex Shi6168d0d2020-12-15 12:34:29 -08002330 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002331
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002332 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002333 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002334
Mel Gorman599d0c92016-07-28 15:45:31 -07002335 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002336
Shakeel Butt912c0572020-08-06 23:26:32 -07002337 if (!cgroup_reclaim(sc))
2338 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002339 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002340
Alex Shi6168d0d2020-12-15 12:34:29 -08002341 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002342
Linus Torvalds1da177e2005-04-16 15:20:36 -07002343 while (!list_empty(&l_hold)) {
2344 cond_resched();
2345 page = lru_to_page(&l_hold);
2346 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002347
Hugh Dickins39b5f292012-10-08 16:33:18 -07002348 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002349 putback_lru_page(page);
2350 continue;
2351 }
2352
Mel Gormancc715d92012-03-21 16:34:00 -07002353 if (unlikely(buffer_heads_over_limit)) {
2354 if (page_has_private(page) && trylock_page(page)) {
2355 if (page_has_private(page))
2356 try_to_release_page(page, 0);
2357 unlock_page(page);
2358 }
2359 }
2360
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002361 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2362 if (bypass)
2363 goto skip_page_referenced;
2364
Minchan Kimf74aca72022-05-19 14:08:54 -07002365 /* Referenced or rmap lock contention: rotate */
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002366 if (page_referenced(page, 0, sc->target_mem_cgroup,
Minchan Kimf74aca72022-05-19 14:08:54 -07002367 &vm_flags) != 0) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002368 /*
2369 * Identify referenced, file-backed active pages and
2370 * give them one more trip around the active list. So
2371 * that executable code get better chances to stay in
2372 * memory under moderate memory pressure. Anon pages
2373 * are not likely to be evicted by use-once streaming
2374 * IO, plus JVM can create lots of anon VM_EXEC pages,
2375 * so we ignore them here.
2376 */
Huang Ying9de4f222020-04-06 20:04:41 -07002377 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002378 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002379 list_add(&page->lru, &l_active);
2380 continue;
2381 }
2382 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002383skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002384 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002385 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002386 list_add(&page->lru, &l_inactive);
2387 }
2388
Andrew Mortonb5557492009-01-06 14:40:13 -08002389 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002390 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002391 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002392 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002393
Kirill Tkhaia222f342019-05-13 17:17:00 -07002394 nr_activate = move_pages_to_lru(lruvec, &l_active);
2395 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002396 /* Keep all free pages in l_active list */
2397 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002398
2399 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2400 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2401
Mel Gorman599d0c92016-07-28 15:45:31 -07002402 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002403 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002404
Kirill Tkhaif372d892019-05-13 17:16:57 -07002405 mem_cgroup_uncharge_list(&l_active);
2406 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002407 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2408 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002409}
2410
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002411unsigned long reclaim_pages(struct list_head *page_list)
2412{
Yang Shif661d002020-04-01 21:10:05 -07002413 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002414 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002415 LIST_HEAD(node_page_list);
2416 struct reclaim_stat dummy_stat;
2417 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002418 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002419 struct scan_control sc = {
2420 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002421 .may_writepage = 1,
2422 .may_unmap = 1,
2423 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002424 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002425 };
2426
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002427 noreclaim_flag = memalloc_noreclaim_save();
2428
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002429 while (!list_empty(page_list)) {
2430 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002431 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002432 nid = page_to_nid(page);
2433 INIT_LIST_HEAD(&node_page_list);
2434 }
2435
2436 if (nid == page_to_nid(page)) {
2437 ClearPageActive(page);
2438 list_move(&page->lru, &node_page_list);
2439 continue;
2440 }
2441
2442 nr_reclaimed += shrink_page_list(&node_page_list,
2443 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002444 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002445 while (!list_empty(&node_page_list)) {
2446 page = lru_to_page(&node_page_list);
2447 list_del(&page->lru);
2448 putback_lru_page(page);
2449 }
2450
Yang Shif661d002020-04-01 21:10:05 -07002451 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002452 }
2453
2454 if (!list_empty(&node_page_list)) {
2455 nr_reclaimed += shrink_page_list(&node_page_list,
2456 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002457 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002458 while (!list_empty(&node_page_list)) {
2459 page = lru_to_page(&node_page_list);
2460 list_del(&page->lru);
2461 putback_lru_page(page);
2462 }
2463 }
2464
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002465 memalloc_noreclaim_restore(noreclaim_flag);
2466
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002467 return nr_reclaimed;
2468}
2469
Johannes Weinerb91ac372019-11-30 17:56:02 -08002470static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2471 struct lruvec *lruvec, struct scan_control *sc)
2472{
2473 if (is_active_lru(lru)) {
2474 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2475 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2476 else
2477 sc->skipped_deactivate = 1;
2478 return 0;
2479 }
2480
2481 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2482}
2483
Rik van Riel59dc76b2016-05-20 16:56:31 -07002484/*
2485 * The inactive anon list should be small enough that the VM never has
2486 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002487 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002488 * The inactive file list should be small enough to leave most memory
2489 * to the established workingset on the scan-resistant active list,
2490 * but large enough to avoid thrashing the aggregate readahead window.
2491 *
2492 * Both inactive lists should also be large enough that each inactive
2493 * page has a chance to be referenced again before it is reclaimed.
2494 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002495 * If that fails and refaulting is observed, the inactive list grows.
2496 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002497 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002498 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002499 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2500 *
2501 * total target max
2502 * memory ratio inactive
2503 * -------------------------------------
2504 * 10MB 1 5MB
2505 * 100MB 1 50MB
2506 * 1GB 3 250MB
2507 * 10GB 10 0.9GB
2508 * 100GB 31 3GB
2509 * 1TB 101 10GB
2510 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002511 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002512static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002513{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002514 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002515 unsigned long inactive, active;
2516 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002517 unsigned long gb;
2518
Johannes Weinerb91ac372019-11-30 17:56:02 -08002519 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2520 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002521
Johannes Weinerb91ac372019-11-30 17:56:02 -08002522 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002523 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002524 inactive_ratio = int_sqrt(10 * gb);
2525 else
2526 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002527
Rik van Riel59dc76b2016-05-20 16:56:31 -07002528 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002529}
2530
Johannes Weiner9a265112013-02-22 16:32:17 -08002531enum scan_balance {
2532 SCAN_EQUAL,
2533 SCAN_FRACT,
2534 SCAN_ANON,
2535 SCAN_FILE,
2536};
2537
Yu Zhao6d313442022-09-18 02:00:00 -06002538static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2539{
2540 unsigned long file;
2541 struct lruvec *target_lruvec;
2542
Yu Zhao37397872022-09-18 02:00:03 -06002543 if (lru_gen_enabled())
2544 return;
2545
Yu Zhao6d313442022-09-18 02:00:00 -06002546 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2547
2548 /*
2549 * Flush the memory cgroup stats, so that we read accurate per-memcg
2550 * lruvec stats for heuristics.
2551 */
2552 mem_cgroup_flush_stats();
2553
2554 /*
2555 * Determine the scan balance between anon and file LRUs.
2556 */
2557 spin_lock_irq(&target_lruvec->lru_lock);
2558 sc->anon_cost = target_lruvec->anon_cost;
2559 sc->file_cost = target_lruvec->file_cost;
2560 spin_unlock_irq(&target_lruvec->lru_lock);
2561
2562 /*
2563 * Target desirable inactive:active list ratios for the anon
2564 * and file LRU lists.
2565 */
2566 if (!sc->force_deactivate) {
2567 unsigned long refaults;
2568
2569 refaults = lruvec_page_state(target_lruvec,
2570 WORKINGSET_ACTIVATE_ANON);
2571 if (refaults != target_lruvec->refaults[0] ||
2572 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2573 sc->may_deactivate |= DEACTIVATE_ANON;
2574 else
2575 sc->may_deactivate &= ~DEACTIVATE_ANON;
2576
2577 /*
2578 * When refaults are being observed, it means a new
2579 * workingset is being established. Deactivate to get
2580 * rid of any stale active pages quickly.
2581 */
2582 refaults = lruvec_page_state(target_lruvec,
2583 WORKINGSET_ACTIVATE_FILE);
2584 if (refaults != target_lruvec->refaults[1] ||
2585 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2586 sc->may_deactivate |= DEACTIVATE_FILE;
2587 else
2588 sc->may_deactivate &= ~DEACTIVATE_FILE;
2589 } else
2590 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2591
2592 /*
2593 * If we have plenty of inactive file pages that aren't
2594 * thrashing, try to reclaim those first before touching
2595 * anonymous pages.
2596 */
2597 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2598 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2599 sc->cache_trim_mode = 1;
2600 else
2601 sc->cache_trim_mode = 0;
2602
2603 /*
2604 * Prevent the reclaimer from falling into the cache trap: as
2605 * cache pages start out inactive, every cache fault will tip
2606 * the scan balance towards the file LRU. And as the file LRU
2607 * shrinks, so does the window for rotation from references.
2608 * This means we have a runaway feedback loop where a tiny
2609 * thrashing file LRU becomes infinitely more attractive than
2610 * anon pages. Try to detect this based on file LRU size.
2611 */
2612 if (!cgroup_reclaim(sc)) {
2613 unsigned long total_high_wmark = 0;
2614 unsigned long free, anon;
2615 int z;
2616
2617 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2618 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2619 node_page_state(pgdat, NR_INACTIVE_FILE);
2620
2621 for (z = 0; z < MAX_NR_ZONES; z++) {
2622 struct zone *zone = &pgdat->node_zones[z];
2623
2624 if (!managed_zone(zone))
2625 continue;
2626
2627 total_high_wmark += high_wmark_pages(zone);
2628 }
2629
2630 /*
2631 * Consider anon: if that's low too, this isn't a
2632 * runaway file reclaim problem, but rather just
2633 * extreme pressure. Reclaim as per usual then.
2634 */
2635 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2636
2637 sc->file_is_tiny =
2638 file + free <= total_high_wmark &&
2639 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2640 anon >> sc->priority;
2641 }
2642}
2643
Linus Torvalds1da177e2005-04-16 15:20:36 -07002644/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002645 * Determine how aggressively the anon and file LRU lists should be
2646 * scanned. The relative value of each set of LRU lists is determined
2647 * by looking at the fraction of the pages scanned we did rotate back
2648 * onto the active list instead of evict.
2649 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002650 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2651 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002652 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002653static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2654 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002655{
Keith Buscha2a36482021-09-02 14:59:26 -07002656 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002657 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002658 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002659 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002660 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002661 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002662 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002663 unsigned long ap, fp;
2664 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002665 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002666
2667 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002668 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002669 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002670 goto out;
2671 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002672
Johannes Weiner10316b32013-02-22 16:32:14 -08002673 /*
2674 * Global reclaim will swap to prevent OOM even with no
2675 * swappiness, but memcg users want to use this knob to
2676 * disable swapping for individual groups completely when
2677 * using the memory controller's swap limit feature would be
2678 * too expensive.
2679 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002680 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002681 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002682 goto out;
2683 }
2684
2685 /*
2686 * Do not apply any pressure balancing cleverness when the
2687 * system is close to OOM, scan both anon and file equally
2688 * (unless the swappiness setting disagrees with swapping).
2689 */
Johannes Weiner02695172014-08-06 16:06:17 -07002690 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002691 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002692 goto out;
2693 }
2694
Johannes Weiner11d16c22013-02-22 16:32:15 -08002695 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002696 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002697 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002698 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002699 scan_balance = SCAN_ANON;
2700 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002701 }
2702
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002703 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2704
Johannes Weiner62376252014-05-06 12:50:07 -07002705 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002706 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002707 * anything from the anonymous working right now. But when balancing
2708 * anon and page cache files for reclaim, allow swapping of anon pages
2709 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002710 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002711 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002712 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002713 goto out;
2714 }
2715
Johannes Weiner9a265112013-02-22 16:32:17 -08002716 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002717 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002718 * Calculate the pressure balance between anon and file pages.
2719 *
2720 * The amount of pressure we put on each LRU is inversely
2721 * proportional to the cost of reclaiming each list, as
2722 * determined by the share of pages that are refaulting, times
2723 * the relative IO cost of bringing back a swapped out
2724 * anonymous page vs reloading a filesystem page (swappiness).
2725 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002726 * Although we limit that influence to ensure no list gets
2727 * left behind completely: at least a third of the pressure is
2728 * applied, before swappiness.
2729 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002730 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002731 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002732 total_cost = sc->anon_cost + sc->file_cost;
2733 anon_cost = total_cost + sc->anon_cost;
2734 file_cost = total_cost + sc->file_cost;
2735 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002736
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002737 ap = swappiness * (total_cost + 1);
2738 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002739
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002740 fp = (200 - swappiness) * (total_cost + 1);
2741 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002742
Shaohua Li76a33fc2010-05-24 14:32:36 -07002743 fraction[0] = ap;
2744 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002745 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002746out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002747 for_each_evictable_lru(lru) {
2748 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002749 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002750 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002751 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002752
Chris Down9783aa92019-10-06 17:58:32 -07002753 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002754 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2755 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002756
Johannes Weinerf56ce412021-08-19 19:04:21 -07002757 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002758 /*
2759 * Scale a cgroup's reclaim pressure by proportioning
2760 * its current usage to its memory.low or memory.min
2761 * setting.
2762 *
2763 * This is important, as otherwise scanning aggression
2764 * becomes extremely binary -- from nothing as we
2765 * approach the memory protection threshold, to totally
2766 * nominal as we exceed it. This results in requiring
2767 * setting extremely liberal protection thresholds. It
2768 * also means we simply get no protection at all if we
2769 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002770 *
2771 * If there is any protection in place, we reduce scan
2772 * pressure by how much of the total memory used is
2773 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002774 *
Chris Down9de7ca42019-10-06 17:58:35 -07002775 * There is one special case: in the first reclaim pass,
2776 * we skip over all groups that are within their low
2777 * protection. If that fails to reclaim enough pages to
2778 * satisfy the reclaim goal, we come back and override
2779 * the best-effort low protection. However, we still
2780 * ideally want to honor how well-behaved groups are in
2781 * that case instead of simply punishing them all
2782 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002783 * memory they are using, reducing the scan pressure
2784 * again by how much of the total memory used is under
2785 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002786 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002787 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002788 unsigned long protection;
2789
2790 /* memory.low scaling, make sure we retry before OOM */
2791 if (!sc->memcg_low_reclaim && low > min) {
2792 protection = low;
2793 sc->memcg_low_skipped = 1;
2794 } else {
2795 protection = min;
2796 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002797
2798 /* Avoid TOCTOU with earlier protection check */
2799 cgroup_size = max(cgroup_size, protection);
2800
2801 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002802 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002803
2804 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002805 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002806 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002807 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002808 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002809 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002810 } else {
2811 scan = lruvec_size;
2812 }
2813
2814 scan >>= sc->priority;
2815
Johannes Weiner688035f2017-05-03 14:52:07 -07002816 /*
2817 * If the cgroup's already been deleted, make sure to
2818 * scrape out the remaining cache.
2819 */
2820 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002821 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002822
Johannes Weiner688035f2017-05-03 14:52:07 -07002823 switch (scan_balance) {
2824 case SCAN_EQUAL:
2825 /* Scan lists relative to size */
2826 break;
2827 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002828 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002829 * Scan types proportional to swappiness and
2830 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002831 * Make sure we don't miss the last page on
2832 * the offlined memory cgroups because of a
2833 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002834 */
Gavin Shan76073c62020-02-20 20:04:24 -08002835 scan = mem_cgroup_online(memcg) ?
2836 div64_u64(scan * fraction[file], denominator) :
2837 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002838 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002839 break;
2840 case SCAN_FILE:
2841 case SCAN_ANON:
2842 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002843 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002844 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002845 break;
2846 default:
2847 /* Look ma, no brain */
2848 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002849 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002850
Johannes Weiner688035f2017-05-03 14:52:07 -07002851 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002852 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002853}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002854
Dave Hansen2f368a92021-09-02 14:59:23 -07002855/*
2856 * Anonymous LRU management is a waste if there is
2857 * ultimately no way to reclaim the memory.
2858 */
2859static bool can_age_anon_pages(struct pglist_data *pgdat,
2860 struct scan_control *sc)
2861{
2862 /* Aging the anon LRU is valuable if swap is present: */
2863 if (total_swap_pages > 0)
2864 return true;
2865
2866 /* Also valuable if anon pages can be demoted: */
2867 return can_demote(pgdat->node_id, sc);
2868}
2869
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002870#ifdef CONFIG_LRU_GEN
2871
Yu Zhaobaeb9a02022-09-18 02:00:07 -06002872#ifdef CONFIG_LRU_GEN_ENABLED
2873DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2874#define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2875#else
2876DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2877#define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2878#endif
2879
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002880/******************************************************************************
2881 * shorthand helpers
2882 ******************************************************************************/
2883
Yu Zhao37397872022-09-18 02:00:03 -06002884#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2885
2886#define DEFINE_MAX_SEQ(lruvec) \
2887 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2888
2889#define DEFINE_MIN_SEQ(lruvec) \
2890 unsigned long min_seq[ANON_AND_FILE] = { \
2891 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2892 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2893 }
2894
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002895#define for_each_gen_type_zone(gen, type, zone) \
2896 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2897 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2898 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2899
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002900static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002901{
2902 struct pglist_data *pgdat = NODE_DATA(nid);
2903
2904#ifdef CONFIG_MEMCG
2905 if (memcg) {
2906 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2907
2908 /* for hotadd_new_pgdat() */
2909 if (!lruvec->pgdat)
2910 lruvec->pgdat = pgdat;
2911
2912 return lruvec;
2913 }
2914#endif
2915 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2916
2917 return pgdat ? &pgdat->__lruvec : NULL;
2918}
2919
Yu Zhao37397872022-09-18 02:00:03 -06002920static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2921{
2922 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2923 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2924
2925 if (!can_demote(pgdat->node_id, sc) &&
2926 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2927 return 0;
2928
2929 return mem_cgroup_swappiness(memcg);
2930}
2931
2932static int get_nr_gens(struct lruvec *lruvec, int type)
2933{
2934 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2935}
2936
2937static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2938{
2939 /* see the comment on lru_gen_struct */
2940 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2941 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2942 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2943}
2944
2945/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002946 * mm_struct list
2947 ******************************************************************************/
2948
2949static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
2950{
2951 static struct lru_gen_mm_list mm_list = {
2952 .fifo = LIST_HEAD_INIT(mm_list.fifo),
2953 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
2954 };
2955
2956#ifdef CONFIG_MEMCG
2957 if (memcg)
2958 return &memcg->mm_list;
2959#endif
2960 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2961
2962 return &mm_list;
2963}
2964
2965void lru_gen_add_mm(struct mm_struct *mm)
2966{
2967 int nid;
2968 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
2969 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
2970
2971 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
2972#ifdef CONFIG_MEMCG
2973 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
2974 mm->lru_gen.memcg = memcg;
2975#endif
2976 spin_lock(&mm_list->lock);
2977
2978 for_each_node_state(nid, N_MEMORY) {
2979 struct lruvec *lruvec = get_lruvec(memcg, nid);
2980
2981 if (!lruvec)
2982 continue;
2983
2984 /* the first addition since the last iteration */
2985 if (lruvec->mm_state.tail == &mm_list->fifo)
2986 lruvec->mm_state.tail = &mm->lru_gen.list;
2987 }
2988
2989 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
2990
2991 spin_unlock(&mm_list->lock);
2992}
2993
2994void lru_gen_del_mm(struct mm_struct *mm)
2995{
2996 int nid;
2997 struct lru_gen_mm_list *mm_list;
2998 struct mem_cgroup *memcg = NULL;
2999
3000 if (list_empty(&mm->lru_gen.list))
3001 return;
3002
3003#ifdef CONFIG_MEMCG
3004 memcg = mm->lru_gen.memcg;
3005#endif
3006 mm_list = get_mm_list(memcg);
3007
3008 spin_lock(&mm_list->lock);
3009
3010 for_each_node(nid) {
3011 struct lruvec *lruvec = get_lruvec(memcg, nid);
3012
3013 if (!lruvec)
3014 continue;
3015
3016 /* where the last iteration ended (exclusive) */
3017 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3018 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3019
3020 /* where the current iteration continues (inclusive) */
3021 if (lruvec->mm_state.head != &mm->lru_gen.list)
3022 continue;
3023
3024 lruvec->mm_state.head = lruvec->mm_state.head->next;
3025 /* the deletion ends the current iteration */
3026 if (lruvec->mm_state.head == &mm_list->fifo)
3027 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3028 }
3029
3030 list_del_init(&mm->lru_gen.list);
3031
3032 spin_unlock(&mm_list->lock);
3033
3034#ifdef CONFIG_MEMCG
3035 mem_cgroup_put(mm->lru_gen.memcg);
3036 mm->lru_gen.memcg = NULL;
3037#endif
3038}
3039
3040#ifdef CONFIG_MEMCG
3041void lru_gen_migrate_mm(struct mm_struct *mm)
3042{
3043 struct mem_cgroup *memcg;
3044 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3045
3046 VM_WARN_ON_ONCE(task->mm != mm);
3047 lockdep_assert_held(&task->alloc_lock);
3048
3049 /* for mm_update_next_owner() */
3050 if (mem_cgroup_disabled())
3051 return;
3052
3053 rcu_read_lock();
3054 memcg = mem_cgroup_from_task(task);
3055 rcu_read_unlock();
3056 if (memcg == mm->lru_gen.memcg)
3057 return;
3058
3059 VM_WARN_ON_ONCE(!mm->lru_gen.memcg);
3060 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3061
3062 lru_gen_del_mm(mm);
3063 lru_gen_add_mm(mm);
3064}
3065#endif
3066
3067/*
3068 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3069 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3070 * bits in a bitmap, k is the number of hash functions and n is the number of
3071 * inserted items.
3072 *
3073 * Page table walkers use one of the two filters to reduce their search space.
3074 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3075 * aging uses the double-buffering technique to flip to the other filter each
3076 * time it produces a new generation. For non-leaf entries that have enough
3077 * leaf entries, the aging carries them over to the next generation in
3078 * walk_pmd_range(); the eviction also report them when walking the rmap
3079 * in lru_gen_look_around().
3080 *
3081 * For future optimizations:
3082 * 1. It's not necessary to keep both filters all the time. The spare one can be
3083 * freed after the RCU grace period and reallocated if needed again.
3084 * 2. And when reallocating, it's worth scaling its size according to the number
3085 * of inserted entries in the other filter, to reduce the memory overhead on
3086 * small systems and false positives on large systems.
3087 * 3. Jenkins' hash function is an alternative to Knuth's.
3088 */
3089#define BLOOM_FILTER_SHIFT 15
3090
3091static inline int filter_gen_from_seq(unsigned long seq)
3092{
3093 return seq % NR_BLOOM_FILTERS;
3094}
3095
3096static void get_item_key(void *item, int *key)
3097{
3098 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3099
3100 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3101
3102 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3103 key[1] = hash >> BLOOM_FILTER_SHIFT;
3104}
3105
3106static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3107{
3108 unsigned long *filter;
3109 int gen = filter_gen_from_seq(seq);
3110
3111 filter = lruvec->mm_state.filters[gen];
3112 if (filter) {
3113 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3114 return;
3115 }
3116
3117 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3118 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3119 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3120}
3121
3122static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3123{
3124 int key[2];
3125 unsigned long *filter;
3126 int gen = filter_gen_from_seq(seq);
3127
3128 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3129 if (!filter)
3130 return;
3131
3132 get_item_key(item, key);
3133
3134 if (!test_bit(key[0], filter))
3135 set_bit(key[0], filter);
3136 if (!test_bit(key[1], filter))
3137 set_bit(key[1], filter);
3138}
3139
3140static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3141{
3142 int key[2];
3143 unsigned long *filter;
3144 int gen = filter_gen_from_seq(seq);
3145
3146 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3147 if (!filter)
3148 return true;
3149
3150 get_item_key(item, key);
3151
3152 return test_bit(key[0], filter) && test_bit(key[1], filter);
3153}
3154
3155static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3156{
3157 int i;
3158 int hist;
3159
3160 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3161
3162 if (walk) {
3163 hist = lru_hist_from_seq(walk->max_seq);
3164
3165 for (i = 0; i < NR_MM_STATS; i++) {
3166 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3167 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3168 walk->mm_stats[i] = 0;
3169 }
3170 }
3171
3172 if (NR_HIST_GENS > 1 && last) {
3173 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3174
3175 for (i = 0; i < NR_MM_STATS; i++)
3176 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3177 }
3178}
3179
3180static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3181{
3182 int type;
3183 unsigned long size = 0;
3184 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3185 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3186
3187 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3188 return true;
3189
3190 clear_bit(key, &mm->lru_gen.bitmap);
3191
3192 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3193 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3194 get_mm_counter(mm, MM_ANONPAGES) +
3195 get_mm_counter(mm, MM_SHMEMPAGES);
3196 }
3197
3198 if (size < MIN_LRU_BATCH)
3199 return true;
3200
3201 return !mmget_not_zero(mm);
3202}
3203
3204static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3205 struct mm_struct **iter)
3206{
3207 bool first = false;
3208 bool last = true;
3209 struct mm_struct *mm = NULL;
3210 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3211 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3212 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3213
3214 /*
3215 * There are four interesting cases for this page table walker:
3216 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3217 * there is nothing left to do.
3218 * 2. It's the first of the current generation, and it needs to reset
3219 * the Bloom filter for the next generation.
3220 * 3. It reaches the end of mm_list, and it needs to increment
3221 * mm_state->seq; the iteration is done.
3222 * 4. It's the last of the current generation, and it needs to reset the
3223 * mm stats counters for the next generation.
3224 */
3225 spin_lock(&mm_list->lock);
3226
3227 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3228 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3229 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3230
3231 if (walk->max_seq <= mm_state->seq) {
3232 if (!*iter)
3233 last = false;
3234 goto done;
3235 }
3236
3237 if (!mm_state->nr_walkers) {
3238 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3239
3240 mm_state->head = mm_list->fifo.next;
3241 first = true;
3242 }
3243
3244 while (!mm && mm_state->head != &mm_list->fifo) {
3245 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3246
3247 mm_state->head = mm_state->head->next;
3248
3249 /* force scan for those added after the last iteration */
3250 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3251 mm_state->tail = mm_state->head;
3252 walk->force_scan = true;
3253 }
3254
3255 if (should_skip_mm(mm, walk))
3256 mm = NULL;
3257 }
3258
3259 if (mm_state->head == &mm_list->fifo)
3260 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3261done:
3262 if (*iter && !mm)
3263 mm_state->nr_walkers--;
3264 if (!*iter && mm)
3265 mm_state->nr_walkers++;
3266
3267 if (mm_state->nr_walkers)
3268 last = false;
3269
3270 if (*iter || last)
3271 reset_mm_stats(lruvec, walk, last);
3272
3273 spin_unlock(&mm_list->lock);
3274
3275 if (mm && first)
3276 reset_bloom_filter(lruvec, walk->max_seq + 1);
3277
3278 if (*iter)
3279 mmput_async(*iter);
3280
3281 *iter = mm;
3282
3283 return last;
3284}
3285
3286static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3287{
3288 bool success = false;
3289 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3290 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3291 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3292
3293 spin_lock(&mm_list->lock);
3294
3295 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3296
3297 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3298 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3299
3300 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3301 reset_mm_stats(lruvec, NULL, true);
3302 success = true;
3303 }
3304
3305 spin_unlock(&mm_list->lock);
3306
3307 return success;
3308}
3309
3310/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003311 * refault feedback loop
3312 ******************************************************************************/
3313
3314/*
3315 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3316 *
3317 * The P term is refaulted/(evicted+protected) from a tier in the generation
3318 * currently being evicted; the I term is the exponential moving average of the
3319 * P term over the generations previously evicted, using the smoothing factor
3320 * 1/2; the D term isn't supported.
3321 *
3322 * The setpoint (SP) is always the first tier of one type; the process variable
3323 * (PV) is either any tier of the other type or any other tier of the same
3324 * type.
3325 *
3326 * The error is the difference between the SP and the PV; the correction is to
3327 * turn off protection when SP>PV or turn on protection when SP<PV.
3328 *
3329 * For future optimizations:
3330 * 1. The D term may discount the other two terms over time so that long-lived
3331 * generations can resist stale information.
3332 */
3333struct ctrl_pos {
3334 unsigned long refaulted;
3335 unsigned long total;
3336 int gain;
3337};
3338
3339static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3340 struct ctrl_pos *pos)
3341{
3342 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3343 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3344
3345 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3346 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3347 pos->total = lrugen->avg_total[type][tier] +
3348 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3349 if (tier)
3350 pos->total += lrugen->protected[hist][type][tier - 1];
3351 pos->gain = gain;
3352}
3353
3354static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3355{
3356 int hist, tier;
3357 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3358 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3359 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3360
3361 lockdep_assert_held(&lruvec->lru_lock);
3362
3363 if (!carryover && !clear)
3364 return;
3365
3366 hist = lru_hist_from_seq(seq);
3367
3368 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3369 if (carryover) {
3370 unsigned long sum;
3371
3372 sum = lrugen->avg_refaulted[type][tier] +
3373 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3374 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3375
3376 sum = lrugen->avg_total[type][tier] +
3377 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3378 if (tier)
3379 sum += lrugen->protected[hist][type][tier - 1];
3380 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3381 }
3382
3383 if (clear) {
3384 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3385 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3386 if (tier)
3387 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3388 }
3389 }
3390}
3391
3392static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3393{
3394 /*
3395 * Return true if the PV has a limited number of refaults or a lower
3396 * refaulted/total than the SP.
3397 */
3398 return pv->refaulted < MIN_LRU_BATCH ||
3399 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3400 (sp->refaulted + 1) * pv->total * pv->gain;
3401}
3402
3403/******************************************************************************
3404 * the aging
3405 ******************************************************************************/
3406
Yu Zhao0182f922022-09-18 02:00:04 -06003407/* promote pages accessed through page tables */
3408static int page_update_gen(struct page *page, int gen)
3409{
3410 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3411
3412 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3413 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3414
3415 do {
3416 /* lru_gen_del_page() has isolated this page? */
3417 if (!(old_flags & LRU_GEN_MASK)) {
3418 /* for shrink_page_list() */
3419 new_flags = old_flags | BIT(PG_referenced);
3420 continue;
3421 }
3422
3423 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3424 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3425 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3426
3427 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3428}
3429
Yu Zhao37397872022-09-18 02:00:03 -06003430/* protect pages accessed multiple times through file descriptors */
3431static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3432{
3433 int type = page_is_file_lru(page);
3434 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3435 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3436 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3437
3438 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3439
3440 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003441 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3442 /* page_update_gen() has promoted this page? */
3443 if (new_gen >= 0 && new_gen != old_gen)
3444 return new_gen;
3445
Yu Zhao37397872022-09-18 02:00:03 -06003446 new_gen = (old_gen + 1) % MAX_NR_GENS;
3447
3448 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3449 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3450 /* for end_page_writeback() */
3451 if (reclaiming)
3452 new_flags |= BIT(PG_reclaim);
3453 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3454
3455 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3456
3457 return new_gen;
3458}
3459
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003460static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3461 int old_gen, int new_gen)
3462{
3463 int type = page_is_file_lru(page);
3464 int zone = page_zonenum(page);
3465 int delta = thp_nr_pages(page);
3466
3467 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3468 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3469
3470 walk->batched++;
3471
3472 walk->nr_pages[old_gen][type][zone] -= delta;
3473 walk->nr_pages[new_gen][type][zone] += delta;
3474}
3475
3476static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3477{
3478 int gen, type, zone;
3479 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3480
3481 walk->batched = 0;
3482
3483 for_each_gen_type_zone(gen, type, zone) {
3484 enum lru_list lru = type * LRU_INACTIVE_FILE;
3485 int delta = walk->nr_pages[gen][type][zone];
3486
3487 if (!delta)
3488 continue;
3489
3490 walk->nr_pages[gen][type][zone] = 0;
3491 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3492 lrugen->nr_pages[gen][type][zone] + delta);
3493
3494 if (lru_gen_is_active(lruvec, gen))
3495 lru += LRU_ACTIVE;
3496 __update_lru_size(lruvec, lru, zone, delta);
3497 }
3498}
3499
3500static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3501{
3502 struct address_space *mapping;
3503 struct vm_area_struct *vma = args->vma;
3504 struct lru_gen_mm_walk *walk = args->private;
3505
3506 if (!vma_is_accessible(vma))
3507 return true;
3508
3509 if (is_vm_hugetlb_page(vma))
3510 return true;
3511
3512 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3513 return true;
3514
3515 if (vma == get_gate_vma(vma->vm_mm))
3516 return true;
3517
3518 if (vma_is_anonymous(vma))
3519 return !walk->can_swap;
3520
3521 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3522 return true;
3523
3524 mapping = vma->vm_file->f_mapping;
3525 if (mapping_unevictable(mapping))
3526 return true;
3527
3528 if (shmem_mapping(mapping))
3529 return !walk->can_swap;
3530
3531 /* to exclude special mappings like dax, etc. */
3532 return !mapping->a_ops->readpage;
3533}
3534
3535/*
3536 * Some userspace memory allocators map many single-page VMAs. Instead of
3537 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3538 * table to reduce zigzags and improve cache performance.
3539 */
3540static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3541 unsigned long *vm_start, unsigned long *vm_end)
3542{
3543 unsigned long start = round_up(*vm_end, size);
3544 unsigned long end = (start | ~mask) + 1;
3545
3546 VM_WARN_ON_ONCE(mask & size);
3547 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3548
3549 while (args->vma) {
3550 if (start >= args->vma->vm_end) {
3551 args->vma = args->vma->vm_next;
3552 continue;
3553 }
3554
3555 if (end && end <= args->vma->vm_start)
3556 return false;
3557
3558 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3559 args->vma = args->vma->vm_next;
3560 continue;
3561 }
3562
3563 *vm_start = max(start, args->vma->vm_start);
3564 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3565
3566 return true;
3567 }
3568
3569 return false;
3570}
3571
Yu Zhao0182f922022-09-18 02:00:04 -06003572static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3573{
3574 unsigned long pfn = pte_pfn(pte);
3575
3576 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3577
3578 if (!pte_present(pte) || is_zero_pfn(pfn))
3579 return -1;
3580
3581 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3582 return -1;
3583
3584 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3585 return -1;
3586
3587 return pfn;
3588}
3589
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003590#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3591static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3592{
3593 unsigned long pfn = pmd_pfn(pmd);
3594
3595 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3596
3597 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3598 return -1;
3599
3600 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3601 return -1;
3602
3603 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3604 return -1;
3605
3606 return pfn;
3607}
3608#endif
3609
Yu Zhao0182f922022-09-18 02:00:04 -06003610static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003611 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003612{
3613 struct page *page;
3614
3615 /* try to avoid unnecessary memory loads */
3616 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3617 return NULL;
3618
3619 page = compound_head(pfn_to_page(pfn));
3620 if (page_to_nid(page) != pgdat->node_id)
3621 return NULL;
3622
3623 if (page_memcg_rcu(page) != memcg)
3624 return NULL;
3625
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003626 /* file VMAs can contain anon pages from COW */
3627 if (!page_is_file_lru(page) && !can_swap)
3628 return NULL;
3629
Yu Zhao0182f922022-09-18 02:00:04 -06003630 return page;
3631}
3632
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003633static bool suitable_to_scan(int total, int young)
3634{
3635 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3636
3637 /* suitable if the average number of young PTEs per cacheline is >=1 */
3638 return young * n >= total;
3639}
3640
3641static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3642 struct mm_walk *args)
3643{
3644 int i;
3645 pte_t *pte;
3646 spinlock_t *ptl;
3647 unsigned long addr;
3648 int total = 0;
3649 int young = 0;
3650 struct lru_gen_mm_walk *walk = args->private;
3651 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3652 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3653 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3654
3655 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3656
3657 ptl = pte_lockptr(args->mm, pmd);
3658 if (!spin_trylock(ptl))
3659 return false;
3660
3661 arch_enter_lazy_mmu_mode();
3662
3663 pte = pte_offset_map(pmd, start & PMD_MASK);
3664restart:
3665 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3666 unsigned long pfn;
3667 struct page *page;
3668
3669 total++;
3670 walk->mm_stats[MM_LEAF_TOTAL]++;
3671
3672 pfn = get_pte_pfn(pte[i], args->vma, addr);
3673 if (pfn == -1)
3674 continue;
3675
3676 if (!pte_young(pte[i])) {
3677 walk->mm_stats[MM_LEAF_OLD]++;
3678 continue;
3679 }
3680
3681 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3682 if (!page)
3683 continue;
3684
3685 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3686 VM_WARN_ON_ONCE(true);
3687
3688 young++;
3689 walk->mm_stats[MM_LEAF_YOUNG]++;
3690
3691 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3692 !(PageAnon(page) && PageSwapBacked(page) &&
3693 !PageSwapCache(page)))
3694 set_page_dirty(page);
3695
3696 old_gen = page_update_gen(page, new_gen);
3697 if (old_gen >= 0 && old_gen != new_gen)
3698 update_batch_size(walk, page, old_gen, new_gen);
3699 }
3700
3701 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3702 goto restart;
3703
3704 pte_unmap(pte);
3705
3706 arch_leave_lazy_mmu_mode();
3707 spin_unlock(ptl);
3708
3709 return suitable_to_scan(total, young);
3710}
3711
3712#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3713static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3714 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3715{
3716 int i;
3717 pmd_t *pmd;
3718 spinlock_t *ptl;
3719 struct lru_gen_mm_walk *walk = args->private;
3720 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3721 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3722 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3723
3724 VM_WARN_ON_ONCE(pud_leaf(*pud));
3725
3726 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3727 if (*start == -1) {
3728 *start = next;
3729 return;
3730 }
3731
3732 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3733 if (i && i <= MIN_LRU_BATCH) {
3734 __set_bit(i - 1, bitmap);
3735 return;
3736 }
3737
3738 pmd = pmd_offset(pud, *start);
3739
3740 ptl = pmd_lockptr(args->mm, pmd);
3741 if (!spin_trylock(ptl))
3742 goto done;
3743
3744 arch_enter_lazy_mmu_mode();
3745
3746 do {
3747 unsigned long pfn;
3748 struct page *page;
3749 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3750
3751 pfn = get_pmd_pfn(pmd[i], vma, addr);
3752 if (pfn == -1)
3753 goto next;
3754
3755 if (!pmd_trans_huge(pmd[i])) {
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003756 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3757 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003758 pmdp_test_and_clear_young(vma, addr, pmd + i);
3759 goto next;
3760 }
3761
3762 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3763 if (!page)
3764 goto next;
3765
3766 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3767 goto next;
3768
3769 walk->mm_stats[MM_LEAF_YOUNG]++;
3770
3771 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3772 !(PageAnon(page) && PageSwapBacked(page) &&
3773 !PageSwapCache(page)))
3774 set_page_dirty(page);
3775
3776 old_gen = page_update_gen(page, new_gen);
3777 if (old_gen >= 0 && old_gen != new_gen)
3778 update_batch_size(walk, page, old_gen, new_gen);
3779next:
3780 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3781 } while (i <= MIN_LRU_BATCH);
3782
3783 arch_leave_lazy_mmu_mode();
3784 spin_unlock(ptl);
3785done:
3786 *start = -1;
3787 bitmap_zero(bitmap, MIN_LRU_BATCH);
3788}
3789#else
3790static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3791 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3792{
3793}
3794#endif
3795
3796static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3797 struct mm_walk *args)
3798{
3799 int i;
3800 pmd_t *pmd;
3801 unsigned long next;
3802 unsigned long addr;
3803 struct vm_area_struct *vma;
3804 unsigned long pos = -1;
3805 struct lru_gen_mm_walk *walk = args->private;
3806 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3807
3808 VM_WARN_ON_ONCE(pud_leaf(*pud));
3809
3810 /*
3811 * Finish an entire PMD in two passes: the first only reaches to PTE
3812 * tables to avoid taking the PMD lock; the second, if necessary, takes
3813 * the PMD lock to clear the accessed bit in PMD entries.
3814 */
3815 pmd = pmd_offset(pud, start & PUD_MASK);
3816restart:
3817 /* walk_pte_range() may call get_next_vma() */
3818 vma = args->vma;
3819 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3820 pmd_t val = pmd_read_atomic(pmd + i);
3821
3822 /* for pmd_read_atomic() */
3823 barrier();
3824
3825 next = pmd_addr_end(addr, end);
3826
3827 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3828 walk->mm_stats[MM_LEAF_TOTAL]++;
3829 continue;
3830 }
3831
3832#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3833 if (pmd_trans_huge(val)) {
3834 unsigned long pfn = pmd_pfn(val);
3835 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3836
3837 walk->mm_stats[MM_LEAF_TOTAL]++;
3838
3839 if (!pmd_young(val)) {
3840 walk->mm_stats[MM_LEAF_OLD]++;
3841 continue;
3842 }
3843
3844 /* try to avoid unnecessary memory loads */
3845 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3846 continue;
3847
3848 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3849 continue;
3850 }
3851#endif
3852 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3853
3854#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003855 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3856 if (!pmd_young(val))
3857 continue;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003858
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003859 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3860 }
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003861#endif
3862 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3863 continue;
3864
3865 walk->mm_stats[MM_NONLEAF_FOUND]++;
3866
3867 if (!walk_pte_range(&val, addr, next, args))
3868 continue;
3869
3870 walk->mm_stats[MM_NONLEAF_ADDED]++;
3871
3872 /* carry over to the next generation */
3873 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3874 }
3875
3876 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3877
3878 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3879 goto restart;
3880}
3881
3882static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3883 struct mm_walk *args)
3884{
3885 int i;
3886 pud_t *pud;
3887 unsigned long addr;
3888 unsigned long next;
3889 struct lru_gen_mm_walk *walk = args->private;
3890
3891 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3892
3893 pud = pud_offset(p4d, start & P4D_MASK);
3894restart:
3895 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3896 pud_t val = READ_ONCE(pud[i]);
3897
3898 next = pud_addr_end(addr, end);
3899
3900 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3901 continue;
3902
3903 walk_pmd_range(&val, addr, next, args);
3904
3905 /* a racy check to curtail the waiting time */
3906 if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
3907 return 1;
3908
3909 if (need_resched() || walk->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(P4D_MASK, PUD_SIZE, args, &start, &end))
3916 goto restart;
3917
3918 end = round_up(end, P4D_SIZE);
3919done:
3920 if (!end || !args->vma)
3921 return 1;
3922
3923 walk->next_addr = max(end, args->vma->vm_start);
3924
3925 return -EAGAIN;
3926}
3927
3928static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3929{
3930 static const struct mm_walk_ops mm_walk_ops = {
3931 .test_walk = should_skip_vma,
3932 .p4d_entry = walk_pud_range,
3933 };
3934
3935 int err;
3936 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3937
3938 walk->next_addr = FIRST_USER_ADDRESS;
3939
3940 do {
3941 err = -EBUSY;
3942
3943 /* page_update_gen() requires stable page_memcg() */
3944 if (!mem_cgroup_trylock_pages(memcg))
3945 break;
3946
3947 /* the caller might be holding the lock for write */
3948 if (mmap_read_trylock(mm)) {
3949 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3950
3951 mmap_read_unlock(mm);
3952 }
3953
3954 mem_cgroup_unlock_pages();
3955
3956 if (walk->batched) {
3957 spin_lock_irq(&lruvec->lru_lock);
3958 reset_batch_size(lruvec, walk);
3959 spin_unlock_irq(&lruvec->lru_lock);
3960 }
3961
3962 cond_resched();
3963 } while (err == -EAGAIN);
3964}
3965
3966static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
3967{
3968 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3969
3970 if (pgdat && current_is_kswapd()) {
3971 VM_WARN_ON_ONCE(walk);
3972
3973 walk = &pgdat->mm_walk;
3974 } else if (!pgdat && !walk) {
3975 VM_WARN_ON_ONCE(current_is_kswapd());
3976
3977 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3978 }
3979
3980 current->reclaim_state->mm_walk = walk;
3981
3982 return walk;
3983}
3984
3985static void clear_mm_walk(void)
3986{
3987 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
3988
3989 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
3990 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
3991
3992 current->reclaim_state->mm_walk = NULL;
3993
3994 if (!current_is_kswapd())
3995 kfree(walk);
3996}
3997
Yu Zhao4983c522022-09-18 02:00:09 -06003998static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06003999{
Yu Zhao4983c522022-09-18 02:00:09 -06004000 int zone;
4001 int remaining = MAX_LRU_BATCH;
Yu Zhao37397872022-09-18 02:00:03 -06004002 struct lru_gen_struct *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06004003 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
Yu Zhao37397872022-09-18 02:00:03 -06004004
Yu Zhao4983c522022-09-18 02:00:09 -06004005 if (type == LRU_GEN_ANON && !can_swap)
4006 goto done;
4007
4008 /* prevent cold/hot inversion if force_scan is true */
4009 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4010 struct list_head *head = &lrugen->lists[old_gen][type][zone];
4011
4012 while (!list_empty(head)) {
4013 struct page *page = lru_to_page(head);
4014
4015 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4016 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4017 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4018 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4019
4020 new_gen = page_inc_gen(lruvec, page, false);
4021 list_move_tail(&page->lru, &lrugen->lists[new_gen][type][zone]);
4022
4023 if (!--remaining)
4024 return false;
4025 }
4026 }
4027done:
Yu Zhao37397872022-09-18 02:00:03 -06004028 reset_ctrl_pos(lruvec, type, true);
4029 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
Yu Zhao4983c522022-09-18 02:00:09 -06004030
4031 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004032}
4033
4034static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4035{
4036 int gen, type, zone;
4037 bool success = false;
4038 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4039 DEFINE_MIN_SEQ(lruvec);
4040
4041 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4042
4043 /* find the oldest populated generation */
4044 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4045 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4046 gen = lru_gen_from_seq(min_seq[type]);
4047
4048 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4049 if (!list_empty(&lrugen->lists[gen][type][zone]))
4050 goto next;
4051 }
4052
4053 min_seq[type]++;
4054 }
4055next:
4056 ;
4057 }
4058
4059 /* see the comment on lru_gen_struct */
4060 if (can_swap) {
4061 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4062 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4063 }
4064
4065 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4066 if (min_seq[type] == lrugen->min_seq[type])
4067 continue;
4068
4069 reset_ctrl_pos(lruvec, type, true);
4070 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4071 success = true;
4072 }
4073
4074 return success;
4075}
4076
Yu Zhao4983c522022-09-18 02:00:09 -06004077static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
Yu Zhao37397872022-09-18 02:00:03 -06004078{
4079 int prev, next;
4080 int type, zone;
4081 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4082
4083 spin_lock_irq(&lruvec->lru_lock);
4084
4085 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4086
Yu Zhao37397872022-09-18 02:00:03 -06004087 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4088 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4089 continue;
4090
Yu Zhao4983c522022-09-18 02:00:09 -06004091 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
Yu Zhao37397872022-09-18 02:00:03 -06004092
Yu Zhao4983c522022-09-18 02:00:09 -06004093 while (!inc_min_seq(lruvec, type, can_swap)) {
4094 spin_unlock_irq(&lruvec->lru_lock);
4095 cond_resched();
4096 spin_lock_irq(&lruvec->lru_lock);
4097 }
Yu Zhao37397872022-09-18 02:00:03 -06004098 }
4099
4100 /*
4101 * Update the active/inactive LRU sizes for compatibility. Both sides of
4102 * the current max_seq need to be covered, since max_seq+1 can overlap
4103 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4104 * overlap, cold/hot inversion happens.
4105 */
4106 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4107 next = lru_gen_from_seq(lrugen->max_seq + 1);
4108
4109 for (type = 0; type < ANON_AND_FILE; type++) {
4110 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4111 enum lru_list lru = type * LRU_INACTIVE_FILE;
4112 long delta = lrugen->nr_pages[prev][type][zone] -
4113 lrugen->nr_pages[next][type][zone];
4114
4115 if (!delta)
4116 continue;
4117
4118 __update_lru_size(lruvec, lru, zone, delta);
4119 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4120 }
4121 }
4122
4123 for (type = 0; type < ANON_AND_FILE; type++)
4124 reset_ctrl_pos(lruvec, type, false);
4125
Yu Zhao430499c2022-09-18 02:00:08 -06004126 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhao37397872022-09-18 02:00:03 -06004127 /* make sure preceding modifications appear */
4128 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004129
Yu Zhao37397872022-09-18 02:00:03 -06004130 spin_unlock_irq(&lruvec->lru_lock);
4131}
4132
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004133static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
Yu Zhao4983c522022-09-18 02:00:09 -06004134 struct scan_control *sc, bool can_swap, bool force_scan)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004135{
4136 bool success;
4137 struct lru_gen_mm_walk *walk;
4138 struct mm_struct *mm = NULL;
4139 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4140
4141 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4142
4143 /* see the comment in iterate_mm_list() */
4144 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4145 success = false;
4146 goto done;
4147 }
4148
4149 /*
4150 * If the hardware doesn't automatically set the accessed bit, fallback
4151 * to lru_gen_look_around(), which only clears the accessed bit in a
4152 * handful of PTEs. Spreading the work out over a period of time usually
4153 * is less efficient, but it avoids bursty page faults.
4154 */
Yu Zhao4983c522022-09-18 02:00:09 -06004155 if (!force_scan && !(arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004156 success = iterate_mm_list_nowalk(lruvec, max_seq);
4157 goto done;
4158 }
4159
4160 walk = set_mm_walk(NULL);
4161 if (!walk) {
4162 success = iterate_mm_list_nowalk(lruvec, max_seq);
4163 goto done;
4164 }
4165
4166 walk->lruvec = lruvec;
4167 walk->max_seq = max_seq;
4168 walk->can_swap = can_swap;
Yu Zhao4983c522022-09-18 02:00:09 -06004169 walk->force_scan = force_scan;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004170
4171 do {
4172 success = iterate_mm_list(lruvec, walk, &mm);
4173 if (mm)
4174 walk_mm(lruvec, mm, walk);
4175
4176 cond_resched();
4177 } while (mm);
4178done:
4179 if (!success) {
4180 if (sc->priority <= DEF_PRIORITY - 2)
4181 wait_event_killable(lruvec->mm_state.wait,
4182 max_seq < READ_ONCE(lrugen->max_seq));
4183
4184 return max_seq < READ_ONCE(lrugen->max_seq);
4185 }
4186
4187 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4188
Yu Zhao4983c522022-09-18 02:00:09 -06004189 inc_max_seq(lruvec, can_swap, force_scan);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004190 /* either this sees any waiters or they will see updated max_seq */
4191 if (wq_has_sleeper(&lruvec->mm_state.wait))
4192 wake_up_all(&lruvec->mm_state.wait);
4193
4194 return true;
4195}
4196
Yu Zhao37397872022-09-18 02:00:03 -06004197static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
4198 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4199{
4200 int gen, type, zone;
4201 unsigned long old = 0;
4202 unsigned long young = 0;
4203 unsigned long total = 0;
4204 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4205 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4206
4207 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4208 unsigned long seq;
4209
4210 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4211 unsigned long size = 0;
4212
4213 gen = lru_gen_from_seq(seq);
4214
4215 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4216 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4217
4218 total += size;
4219 if (seq == max_seq)
4220 young += size;
4221 else if (seq + MIN_NR_GENS == max_seq)
4222 old += size;
4223 }
4224 }
4225
4226 /* try to scrape all its memory if this memcg was deleted */
4227 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4228
4229 /*
4230 * The aging tries to be lazy to reduce the overhead, while the eviction
4231 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4232 * ideal number of generations is MIN_NR_GENS+1.
4233 */
4234 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
4235 return true;
4236 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4237 return false;
4238
4239 /*
4240 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4241 * of the total number of pages for each generation. A reasonable range
4242 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4243 * aging cares about the upper bound of hot pages, while the eviction
4244 * cares about the lower bound of cold pages.
4245 */
4246 if (young * MIN_NR_GENS > total)
4247 return true;
4248 if (old * (MIN_NR_GENS + 2) < total)
4249 return true;
4250
4251 return false;
4252}
4253
Yu Zhao430499c2022-09-18 02:00:08 -06004254static bool age_lruvec(struct lruvec *lruvec, struct scan_control *sc, unsigned long min_ttl)
Yu Zhao37397872022-09-18 02:00:03 -06004255{
4256 bool need_aging;
4257 unsigned long nr_to_scan;
4258 int swappiness = get_swappiness(lruvec, sc);
4259 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4260 DEFINE_MAX_SEQ(lruvec);
4261 DEFINE_MIN_SEQ(lruvec);
4262
4263 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
4264
4265 mem_cgroup_calculate_protection(NULL, memcg);
4266
4267 if (mem_cgroup_below_min(memcg))
Yu Zhao430499c2022-09-18 02:00:08 -06004268 return false;
Yu Zhao37397872022-09-18 02:00:03 -06004269
4270 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
Yu Zhao430499c2022-09-18 02:00:08 -06004271
4272 if (min_ttl) {
4273 int gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4274 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4275
4276 if (time_is_after_jiffies(birth + min_ttl))
4277 return false;
4278
4279 /* the size is likely too small to be helpful */
4280 if (!nr_to_scan && sc->priority != DEF_PRIORITY)
4281 return false;
4282 }
4283
Yu Zhao37397872022-09-18 02:00:03 -06004284 if (need_aging)
Yu Zhao4983c522022-09-18 02:00:09 -06004285 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
Yu Zhao430499c2022-09-18 02:00:08 -06004286
4287 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004288}
4289
Yu Zhao430499c2022-09-18 02:00:08 -06004290/* to protect the working set of the last N jiffies */
4291static unsigned long lru_gen_min_ttl __read_mostly;
4292
Yu Zhao37397872022-09-18 02:00:03 -06004293static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4294{
4295 struct mem_cgroup *memcg;
Yu Zhao430499c2022-09-18 02:00:08 -06004296 bool success = false;
4297 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhao37397872022-09-18 02:00:03 -06004298
4299 VM_WARN_ON_ONCE(!current_is_kswapd());
4300
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004301 sc->last_reclaimed = sc->nr_reclaimed;
4302
4303 /*
4304 * To reduce the chance of going into the aging path, which can be
4305 * costly, optimistically skip it if the flag below was cleared in the
4306 * eviction path. This improves the overall performance when multiple
4307 * memcgs are available.
4308 */
4309 if (!sc->memcgs_need_aging) {
4310 sc->memcgs_need_aging = true;
4311 return;
4312 }
4313
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004314 set_mm_walk(pgdat);
4315
Yu Zhao37397872022-09-18 02:00:03 -06004316 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4317 do {
4318 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4319
Yu Zhao430499c2022-09-18 02:00:08 -06004320 if (age_lruvec(lruvec, sc, min_ttl))
4321 success = true;
Yu Zhao37397872022-09-18 02:00:03 -06004322
4323 cond_resched();
4324 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004325
4326 clear_mm_walk();
Yu Zhao430499c2022-09-18 02:00:08 -06004327
4328 /* check the order to exclude compaction-induced reclaim */
4329 if (success || !min_ttl || sc->order)
4330 return;
4331
4332 /*
4333 * The main goal is to OOM kill if every generation from all memcgs is
4334 * younger than min_ttl. However, another possibility is all memcgs are
4335 * either below min or empty.
4336 */
4337 if (mutex_trylock(&oom_lock)) {
4338 struct oom_control oc = {
4339 .gfp_mask = sc->gfp_mask,
4340 };
4341
4342 out_of_memory(&oc);
4343
4344 mutex_unlock(&oom_lock);
4345 }
Yu Zhao37397872022-09-18 02:00:03 -06004346}
4347
Yu Zhao0182f922022-09-18 02:00:04 -06004348/*
4349 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004350 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4351 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4352 * the PTE table to the Bloom filter. This forms a feedback loop between the
4353 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004354 */
4355void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4356{
4357 int i;
4358 pte_t *pte;
4359 unsigned long start;
4360 unsigned long end;
4361 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004362 struct lru_gen_mm_walk *walk;
4363 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004364 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4365 struct page *page = pvmw->page;
4366 struct mem_cgroup *memcg = page_memcg(page);
4367 struct pglist_data *pgdat = page_pgdat(page);
4368 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4369 DEFINE_MAX_SEQ(lruvec);
4370 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4371
4372 lockdep_assert_held(pvmw->ptl);
4373 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4374
4375 if (spin_is_contended(pvmw->ptl))
4376 return;
4377
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004378 /* avoid taking the LRU lock under the PTL when possible */
4379 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4380
Yu Zhao0182f922022-09-18 02:00:04 -06004381 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4382 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4383
4384 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4385 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4386 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4387 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4388 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4389 else {
4390 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4391 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4392 }
4393 }
4394
4395 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4396
4397 rcu_read_lock();
4398 arch_enter_lazy_mmu_mode();
4399
4400 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4401 unsigned long pfn;
4402
4403 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4404 if (pfn == -1)
4405 continue;
4406
4407 if (!pte_young(pte[i]))
4408 continue;
4409
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004410 page = get_pfn_page(pfn, memcg, pgdat, !walk || walk->can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004411 if (!page)
4412 continue;
4413
4414 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4415 VM_WARN_ON_ONCE(true);
4416
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004417 young++;
4418
Yu Zhao0182f922022-09-18 02:00:04 -06004419 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4420 !(PageAnon(page) && PageSwapBacked(page) &&
4421 !PageSwapCache(page)))
4422 set_page_dirty(page);
4423
4424 old_gen = page_lru_gen(page);
4425 if (old_gen < 0)
4426 SetPageReferenced(page);
4427 else if (old_gen != new_gen)
4428 __set_bit(i, bitmap);
4429 }
4430
4431 arch_leave_lazy_mmu_mode();
4432 rcu_read_unlock();
4433
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004434 /* feedback from rmap walkers to page table walkers */
4435 if (suitable_to_scan(i, young))
4436 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4437
4438 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004439 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4440 page = pte_page(pte[i]);
4441 activate_page(page);
4442 }
4443 return;
4444 }
4445
4446 /* page_update_gen() requires stable page_memcg() */
4447 if (!mem_cgroup_trylock_pages(memcg))
4448 return;
4449
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004450 if (!walk) {
4451 spin_lock_irq(&lruvec->lru_lock);
4452 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4453 }
Yu Zhao0182f922022-09-18 02:00:04 -06004454
4455 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4456 page = compound_head(pte_page(pte[i]));
4457 if (page_memcg_rcu(page) != memcg)
4458 continue;
4459
4460 old_gen = page_update_gen(page, new_gen);
4461 if (old_gen < 0 || old_gen == new_gen)
4462 continue;
4463
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004464 if (walk)
4465 update_batch_size(walk, page, old_gen, new_gen);
4466 else
4467 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004468 }
4469
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004470 if (!walk)
4471 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004472
4473 mem_cgroup_unlock_pages();
4474}
4475
Yu Zhao37397872022-09-18 02:00:03 -06004476/******************************************************************************
4477 * the eviction
4478 ******************************************************************************/
4479
4480static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4481{
4482 bool success;
4483 int gen = page_lru_gen(page);
4484 int type = page_is_file_lru(page);
4485 int zone = page_zonenum(page);
4486 int delta = thp_nr_pages(page);
4487 int refs = page_lru_refs(page);
4488 int tier = lru_tier_from_refs(refs);
4489 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4490
4491 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4492
4493 /* unevictable */
4494 if (!page_evictable(page)) {
4495 success = lru_gen_del_page(lruvec, page, true);
4496 VM_WARN_ON_ONCE_PAGE(!success, page);
4497 SetPageUnevictable(page);
4498 add_page_to_lru_list(page, lruvec);
4499 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4500 return true;
4501 }
4502
4503 /* dirty lazyfree */
4504 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4505 success = lru_gen_del_page(lruvec, page, true);
4506 VM_WARN_ON_ONCE_PAGE(!success, page);
4507 SetPageSwapBacked(page);
4508 add_page_to_lru_list_tail(page, lruvec);
4509 return true;
4510 }
4511
Yu Zhao0182f922022-09-18 02:00:04 -06004512 /* promoted */
4513 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4514 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4515 return true;
4516 }
4517
Yu Zhao37397872022-09-18 02:00:03 -06004518 /* protected */
4519 if (tier > tier_idx) {
4520 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4521
4522 gen = page_inc_gen(lruvec, page, false);
4523 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4524
4525 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4526 lrugen->protected[hist][type][tier - 1] + delta);
4527 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4528 return true;
4529 }
4530
4531 /* waiting for writeback */
4532 if (PageLocked(page) || PageWriteback(page) ||
4533 (type == LRU_GEN_FILE && PageDirty(page))) {
4534 gen = page_inc_gen(lruvec, page, true);
4535 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4536 return true;
4537 }
4538
4539 return false;
4540}
4541
4542static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4543{
4544 bool success;
4545
4546 /* unmapping inhibited */
4547 if (!sc->may_unmap && page_mapped(page))
4548 return false;
4549
4550 /* swapping inhibited */
4551 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4552 (PageDirty(page) ||
4553 (PageAnon(page) && !PageSwapCache(page))))
4554 return false;
4555
4556 /* raced with release_pages() */
4557 if (!get_page_unless_zero(page))
4558 return false;
4559
4560 /* raced with another isolation */
4561 if (!TestClearPageLRU(page)) {
4562 put_page(page);
4563 return false;
4564 }
4565
4566 /* see the comment on MAX_NR_TIERS */
4567 if (!PageReferenced(page))
4568 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4569
4570 /* for shrink_page_list() */
4571 ClearPageReclaim(page);
4572 ClearPageReferenced(page);
4573
4574 success = lru_gen_del_page(lruvec, page, true);
4575 VM_WARN_ON_ONCE_PAGE(!success, page);
4576
4577 return true;
4578}
4579
4580static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4581 int type, int tier, struct list_head *list)
4582{
4583 int gen, zone;
4584 enum vm_event_item item;
4585 int sorted = 0;
4586 int scanned = 0;
4587 int isolated = 0;
4588 int remaining = MAX_LRU_BATCH;
4589 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4590 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4591
4592 VM_WARN_ON_ONCE(!list_empty(list));
4593
4594 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4595 return 0;
4596
4597 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4598
4599 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4600 LIST_HEAD(moved);
4601 int skipped = 0;
4602 struct list_head *head = &lrugen->lists[gen][type][zone];
4603
4604 while (!list_empty(head)) {
4605 struct page *page = lru_to_page(head);
4606 int delta = thp_nr_pages(page);
4607
4608 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4609 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4610 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4611 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4612
4613 scanned += delta;
4614
4615 if (sort_page(lruvec, page, tier))
4616 sorted += delta;
4617 else if (isolate_page(lruvec, page, sc)) {
4618 list_add(&page->lru, list);
4619 isolated += delta;
4620 } else {
4621 list_move(&page->lru, &moved);
4622 skipped += delta;
4623 }
4624
4625 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4626 break;
4627 }
4628
4629 if (skipped) {
4630 list_splice(&moved, head);
4631 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4632 }
4633
4634 if (!remaining || isolated >= MIN_LRU_BATCH)
4635 break;
4636 }
4637
4638 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4639 if (!cgroup_reclaim(sc)) {
4640 __count_vm_events(item, isolated);
4641 __count_vm_events(PGREFILL, sorted);
4642 }
4643 __count_memcg_events(memcg, item, isolated);
4644 __count_memcg_events(memcg, PGREFILL, sorted);
4645 __count_vm_events(PGSCAN_ANON + type, isolated);
4646
4647 /*
4648 * There might not be eligible pages due to reclaim_idx, may_unmap and
4649 * may_writepage. Check the remaining to prevent livelock if it's not
4650 * making progress.
4651 */
4652 return isolated || !remaining ? scanned : 0;
4653}
4654
4655static int get_tier_idx(struct lruvec *lruvec, int type)
4656{
4657 int tier;
4658 struct ctrl_pos sp, pv;
4659
4660 /*
4661 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4662 * This value is chosen because any other tier would have at least twice
4663 * as many refaults as the first tier.
4664 */
4665 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4666 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4667 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4668 if (!positive_ctrl_err(&sp, &pv))
4669 break;
4670 }
4671
4672 return tier - 1;
4673}
4674
4675static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4676{
4677 int type, tier;
4678 struct ctrl_pos sp, pv;
4679 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4680
4681 /*
4682 * Compare the first tier of anon with that of file to determine which
4683 * type to scan. Also need to compare other tiers of the selected type
4684 * with the first tier of the other type to determine the last tier (of
4685 * the selected type) to evict.
4686 */
4687 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4688 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4689 type = positive_ctrl_err(&sp, &pv);
4690
4691 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4692 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4693 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4694 if (!positive_ctrl_err(&sp, &pv))
4695 break;
4696 }
4697
4698 *tier_idx = tier - 1;
4699
4700 return type;
4701}
4702
4703static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4704 int *type_scanned, struct list_head *list)
4705{
4706 int i;
4707 int type;
4708 int scanned;
4709 int tier = -1;
4710 DEFINE_MIN_SEQ(lruvec);
4711
4712 /*
4713 * Try to make the obvious choice first. When anon and file are both
4714 * available from the same generation, interpret swappiness 1 as file
4715 * first and 200 as anon first.
4716 */
4717 if (!swappiness)
4718 type = LRU_GEN_FILE;
4719 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4720 type = LRU_GEN_ANON;
4721 else if (swappiness == 1)
4722 type = LRU_GEN_FILE;
4723 else if (swappiness == 200)
4724 type = LRU_GEN_ANON;
4725 else
4726 type = get_type_to_scan(lruvec, swappiness, &tier);
4727
4728 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4729 if (tier < 0)
4730 tier = get_tier_idx(lruvec, type);
4731
4732 scanned = scan_pages(lruvec, sc, type, tier, list);
4733 if (scanned)
4734 break;
4735
4736 type = !type;
4737 tier = -1;
4738 }
4739
4740 *type_scanned = type;
4741
4742 return scanned;
4743}
4744
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004745static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4746 bool *need_swapping)
Yu Zhao37397872022-09-18 02:00:03 -06004747{
4748 int type;
4749 int scanned;
4750 int reclaimed;
4751 LIST_HEAD(list);
4752 struct page *page;
4753 enum vm_event_item item;
4754 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004755 struct lru_gen_mm_walk *walk;
Yu Zhao37397872022-09-18 02:00:03 -06004756 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4757 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4758
4759 spin_lock_irq(&lruvec->lru_lock);
4760
4761 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4762
4763 scanned += try_to_inc_min_seq(lruvec, swappiness);
4764
4765 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4766 scanned = 0;
4767
4768 spin_unlock_irq(&lruvec->lru_lock);
4769
4770 if (list_empty(&list))
4771 return scanned;
4772
4773 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4774
4775 list_for_each_entry(page, &list, lru) {
4776 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4777 if (PageWorkingset(page))
4778 SetPageReferenced(page);
4779
4780 /* don't add rejected pages to the oldest generation */
4781 if (PageReclaim(page) &&
4782 (PageDirty(page) || PageWriteback(page)))
4783 ClearPageActive(page);
4784 else
4785 SetPageActive(page);
4786 }
4787
4788 spin_lock_irq(&lruvec->lru_lock);
4789
4790 move_pages_to_lru(lruvec, &list);
4791
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004792 walk = current->reclaim_state->mm_walk;
4793 if (walk && walk->batched)
4794 reset_batch_size(lruvec, walk);
4795
Yu Zhao37397872022-09-18 02:00:03 -06004796 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4797 if (!cgroup_reclaim(sc))
4798 __count_vm_events(item, reclaimed);
4799 __count_memcg_events(memcg, item, reclaimed);
4800 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4801
4802 spin_unlock_irq(&lruvec->lru_lock);
4803
4804 mem_cgroup_uncharge_list(&list);
4805 free_unref_page_list(&list);
4806
4807 sc->nr_reclaimed += reclaimed;
4808
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004809 if (need_swapping && type == LRU_GEN_ANON)
4810 *need_swapping = true;
4811
Yu Zhao37397872022-09-18 02:00:03 -06004812 return scanned;
4813}
4814
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004815/*
4816 * For future optimizations:
4817 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4818 * reclaim.
4819 */
Yu Zhao37397872022-09-18 02:00:03 -06004820static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004821 bool can_swap, bool *need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004822{
Yu Zhao37397872022-09-18 02:00:03 -06004823 unsigned long nr_to_scan;
4824 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4825 DEFINE_MAX_SEQ(lruvec);
4826 DEFINE_MIN_SEQ(lruvec);
4827
4828 if (mem_cgroup_below_min(memcg) ||
4829 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4830 return 0;
4831
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004832 *need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
4833 if (!*need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004834 return nr_to_scan;
4835
4836 /* skip the aging path at the default priority */
4837 if (sc->priority == DEF_PRIORITY)
4838 goto done;
4839
4840 /* leave the work to lru_gen_age_node() */
4841 if (current_is_kswapd())
4842 return 0;
4843
Yu Zhao4983c522022-09-18 02:00:09 -06004844 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004845 return nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004846done:
4847 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
4848}
4849
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004850static bool should_abort_scan(struct lruvec *lruvec, unsigned long seq,
4851 struct scan_control *sc, bool need_swapping)
4852{
4853 int i;
4854 DEFINE_MAX_SEQ(lruvec);
4855
4856 if (!current_is_kswapd()) {
4857 /* age each memcg at most once to ensure fairness */
4858 if (max_seq - seq > 1)
4859 return true;
4860
4861 /* over-swapping can increase allocation latency */
4862 if (sc->nr_reclaimed >= sc->nr_to_reclaim && need_swapping)
4863 return true;
4864
4865 /* give this thread a chance to exit and free its memory */
4866 if (fatal_signal_pending(current)) {
4867 sc->nr_reclaimed += MIN_LRU_BATCH;
4868 return true;
4869 }
4870
4871 if (cgroup_reclaim(sc))
4872 return false;
4873 } else if (sc->nr_reclaimed - sc->last_reclaimed < sc->nr_to_reclaim)
4874 return false;
4875
4876 /* keep scanning at low priorities to ensure fairness */
4877 if (sc->priority > DEF_PRIORITY - 2)
4878 return false;
4879
4880 /*
4881 * A minimum amount of work was done under global memory pressure. For
4882 * kswapd, it may be overshooting. For direct reclaim, the allocation
4883 * may succeed if all suitable zones are somewhat safe. In either case,
4884 * it's better to stop now, and restart later if necessary.
4885 */
4886 for (i = 0; i <= sc->reclaim_idx; i++) {
4887 unsigned long wmark;
4888 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
4889
4890 if (!managed_zone(zone))
4891 continue;
4892
4893 wmark = current_is_kswapd() ? high_wmark_pages(zone) : low_wmark_pages(zone);
4894 if (wmark > zone_page_state(zone, NR_FREE_PAGES))
4895 return false;
4896 }
4897
4898 sc->nr_reclaimed += MIN_LRU_BATCH;
4899
4900 return true;
4901}
4902
Yu Zhao37397872022-09-18 02:00:03 -06004903static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4904{
4905 struct blk_plug plug;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004906 bool need_aging = false;
4907 bool need_swapping = false;
Yu Zhao37397872022-09-18 02:00:03 -06004908 unsigned long scanned = 0;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004909 unsigned long reclaimed = sc->nr_reclaimed;
4910 DEFINE_MAX_SEQ(lruvec);
Yu Zhao37397872022-09-18 02:00:03 -06004911
4912 lru_add_drain();
4913
4914 blk_start_plug(&plug);
4915
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004916 set_mm_walk(lruvec_pgdat(lruvec));
4917
Yu Zhao37397872022-09-18 02:00:03 -06004918 while (true) {
4919 int delta;
4920 int swappiness;
4921 unsigned long nr_to_scan;
4922
4923 if (sc->may_swap)
4924 swappiness = get_swappiness(lruvec, sc);
4925 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4926 swappiness = 1;
4927 else
4928 swappiness = 0;
4929
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004930 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, &need_aging);
Yu Zhao37397872022-09-18 02:00:03 -06004931 if (!nr_to_scan)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004932 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004933
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004934 delta = evict_pages(lruvec, sc, swappiness, &need_swapping);
Yu Zhao37397872022-09-18 02:00:03 -06004935 if (!delta)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004936 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004937
4938 scanned += delta;
4939 if (scanned >= nr_to_scan)
4940 break;
4941
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004942 if (should_abort_scan(lruvec, max_seq, sc, need_swapping))
4943 break;
4944
Yu Zhao37397872022-09-18 02:00:03 -06004945 cond_resched();
4946 }
4947
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004948 /* see the comment in lru_gen_age_node() */
4949 if (sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH && !need_aging)
4950 sc->memcgs_need_aging = false;
4951done:
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004952 clear_mm_walk();
4953
Yu Zhao37397872022-09-18 02:00:03 -06004954 blk_finish_plug(&plug);
4955}
4956
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004957/******************************************************************************
Yu Zhaobaeb9a02022-09-18 02:00:07 -06004958 * state change
4959 ******************************************************************************/
4960
4961static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
4962{
4963 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4964
4965 if (lrugen->enabled) {
4966 enum lru_list lru;
4967
4968 for_each_evictable_lru(lru) {
4969 if (!list_empty(&lruvec->lists[lru]))
4970 return false;
4971 }
4972 } else {
4973 int gen, type, zone;
4974
4975 for_each_gen_type_zone(gen, type, zone) {
4976 if (!list_empty(&lrugen->lists[gen][type][zone]))
4977 return false;
4978 }
4979 }
4980
4981 return true;
4982}
4983
4984static bool fill_evictable(struct lruvec *lruvec)
4985{
4986 enum lru_list lru;
4987 int remaining = MAX_LRU_BATCH;
4988
4989 for_each_evictable_lru(lru) {
4990 int type = is_file_lru(lru);
4991 bool active = is_active_lru(lru);
4992 struct list_head *head = &lruvec->lists[lru];
4993
4994 while (!list_empty(head)) {
4995 bool success;
4996 struct page *page = lru_to_page(head);
4997
4998 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4999 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
5000 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5001 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
5002
5003 del_page_from_lru_list(page, lruvec);
5004 success = lru_gen_add_page(lruvec, page, false);
5005 VM_WARN_ON_ONCE(!success);
5006
5007 if (!--remaining)
5008 return false;
5009 }
5010 }
5011
5012 return true;
5013}
5014
5015static bool drain_evictable(struct lruvec *lruvec)
5016{
5017 int gen, type, zone;
5018 int remaining = MAX_LRU_BATCH;
5019
5020 for_each_gen_type_zone(gen, type, zone) {
5021 struct list_head *head = &lruvec->lrugen.lists[gen][type][zone];
5022
5023 while (!list_empty(head)) {
5024 bool success;
5025 struct page *page = lru_to_page(head);
5026
5027 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5028 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5029 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5030 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5031
5032 success = lru_gen_del_page(lruvec, page, false);
5033 VM_WARN_ON_ONCE(!success);
5034 add_page_to_lru_list(page, lruvec);
5035
5036 if (!--remaining)
5037 return false;
5038 }
5039 }
5040
5041 return true;
5042}
5043
5044static void lru_gen_change_state(bool enabled)
5045{
5046 static DEFINE_MUTEX(state_mutex);
5047
5048 struct mem_cgroup *memcg;
5049
5050 cgroup_lock();
5051 cpus_read_lock();
5052 get_online_mems();
5053 mutex_lock(&state_mutex);
5054
5055 if (enabled == lru_gen_enabled())
5056 goto unlock;
5057
5058 if (enabled)
5059 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5060 else
5061 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5062
5063 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5064 do {
5065 int nid;
5066
5067 for_each_node(nid) {
5068 struct lruvec *lruvec = get_lruvec(memcg, nid);
5069
5070 if (!lruvec)
5071 continue;
5072
5073 spin_lock_irq(&lruvec->lru_lock);
5074
5075 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5076 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5077
5078 lruvec->lrugen.enabled = enabled;
5079
5080 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5081 spin_unlock_irq(&lruvec->lru_lock);
5082 cond_resched();
5083 spin_lock_irq(&lruvec->lru_lock);
5084 }
5085
5086 spin_unlock_irq(&lruvec->lru_lock);
5087 }
5088
5089 cond_resched();
5090 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5091unlock:
5092 mutex_unlock(&state_mutex);
5093 put_online_mems();
5094 cpus_read_unlock();
5095 cgroup_unlock();
5096}
5097
5098/******************************************************************************
5099 * sysfs interface
5100 ******************************************************************************/
5101
Yu Zhao430499c2022-09-18 02:00:08 -06005102static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5103{
5104 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5105}
5106
Yu Zhao642d9862022-09-18 02:00:10 -06005107/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao430499c2022-09-18 02:00:08 -06005108static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5109 const char *buf, size_t len)
5110{
5111 unsigned int msecs;
5112
5113 if (kstrtouint(buf, 0, &msecs))
5114 return -EINVAL;
5115
5116 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5117
5118 return len;
5119}
5120
5121static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5122 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5123);
5124
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005125static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5126{
5127 unsigned int caps = 0;
5128
5129 if (get_cap(LRU_GEN_CORE))
5130 caps |= BIT(LRU_GEN_CORE);
5131
5132 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5133 caps |= BIT(LRU_GEN_MM_WALK);
5134
5135 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
5136 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5137
5138 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5139}
5140
Yu Zhao642d9862022-09-18 02:00:10 -06005141/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005142static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5143 const char *buf, size_t len)
5144{
5145 int i;
5146 unsigned int caps;
5147
5148 if (tolower(*buf) == 'n')
5149 caps = 0;
5150 else if (tolower(*buf) == 'y')
5151 caps = -1;
5152 else if (kstrtouint(buf, 0, &caps))
5153 return -EINVAL;
5154
5155 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5156 bool enabled = caps & BIT(i);
5157
5158 if (i == LRU_GEN_CORE)
5159 lru_gen_change_state(enabled);
5160 else if (enabled)
5161 static_branch_enable(&lru_gen_caps[i]);
5162 else
5163 static_branch_disable(&lru_gen_caps[i]);
5164 }
5165
5166 return len;
5167}
5168
5169static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5170 enabled, 0644, show_enabled, store_enabled
5171);
5172
5173static struct attribute *lru_gen_attrs[] = {
Yu Zhao430499c2022-09-18 02:00:08 -06005174 &lru_gen_min_ttl_attr.attr,
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005175 &lru_gen_enabled_attr.attr,
5176 NULL
5177};
5178
5179static struct attribute_group lru_gen_attr_group = {
5180 .name = "lru_gen",
5181 .attrs = lru_gen_attrs,
5182};
5183
5184/******************************************************************************
Yu Zhao4983c522022-09-18 02:00:09 -06005185 * debugfs interface
5186 ******************************************************************************/
5187
5188static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5189{
5190 struct mem_cgroup *memcg;
5191 loff_t nr_to_skip = *pos;
5192
5193 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5194 if (!m->private)
5195 return ERR_PTR(-ENOMEM);
5196
5197 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5198 do {
5199 int nid;
5200
5201 for_each_node_state(nid, N_MEMORY) {
5202 if (!nr_to_skip--)
5203 return get_lruvec(memcg, nid);
5204 }
5205 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5206
5207 return NULL;
5208}
5209
5210static void lru_gen_seq_stop(struct seq_file *m, void *v)
5211{
5212 if (!IS_ERR_OR_NULL(v))
5213 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5214
5215 kvfree(m->private);
5216 m->private = NULL;
5217}
5218
5219static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5220{
5221 int nid = lruvec_pgdat(v)->node_id;
5222 struct mem_cgroup *memcg = lruvec_memcg(v);
5223
5224 ++*pos;
5225
5226 nid = next_memory_node(nid);
5227 if (nid == MAX_NUMNODES) {
5228 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5229 if (!memcg)
5230 return NULL;
5231
5232 nid = first_memory_node;
5233 }
5234
5235 return get_lruvec(memcg, nid);
5236}
5237
5238static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5239 unsigned long max_seq, unsigned long *min_seq,
5240 unsigned long seq)
5241{
5242 int i;
5243 int type, tier;
5244 int hist = lru_hist_from_seq(seq);
5245 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5246
5247 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5248 seq_printf(m, " %10d", tier);
5249 for (type = 0; type < ANON_AND_FILE; type++) {
5250 const char *s = " ";
5251 unsigned long n[3] = {};
5252
5253 if (seq == max_seq) {
5254 s = "RT ";
5255 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5256 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5257 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5258 s = "rep";
5259 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5260 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5261 if (tier)
5262 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5263 }
5264
5265 for (i = 0; i < 3; i++)
5266 seq_printf(m, " %10lu%c", n[i], s[i]);
5267 }
5268 seq_putc(m, '\n');
5269 }
5270
5271 seq_puts(m, " ");
5272 for (i = 0; i < NR_MM_STATS; i++) {
5273 const char *s = " ";
5274 unsigned long n = 0;
5275
5276 if (seq == max_seq && NR_HIST_GENS == 1) {
5277 s = "LOYNFA";
5278 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5279 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5280 s = "loynfa";
5281 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5282 }
5283
5284 seq_printf(m, " %10lu%c", n, s[i]);
5285 }
5286 seq_putc(m, '\n');
5287}
5288
Yu Zhao642d9862022-09-18 02:00:10 -06005289/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005290static int lru_gen_seq_show(struct seq_file *m, void *v)
5291{
5292 unsigned long seq;
5293 bool full = !debugfs_real_fops(m->file)->write;
5294 struct lruvec *lruvec = v;
5295 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5296 int nid = lruvec_pgdat(lruvec)->node_id;
5297 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5298 DEFINE_MAX_SEQ(lruvec);
5299 DEFINE_MIN_SEQ(lruvec);
5300
5301 if (nid == first_memory_node) {
5302 const char *path = memcg ? m->private : "";
5303
5304#ifdef CONFIG_MEMCG
5305 if (memcg)
5306 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5307#endif
5308 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5309 }
5310
5311 seq_printf(m, " node %5d\n", nid);
5312
5313 if (!full)
5314 seq = min_seq[LRU_GEN_ANON];
5315 else if (max_seq >= MAX_NR_GENS)
5316 seq = max_seq - MAX_NR_GENS + 1;
5317 else
5318 seq = 0;
5319
5320 for (; seq <= max_seq; seq++) {
5321 int type, zone;
5322 int gen = lru_gen_from_seq(seq);
5323 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5324
5325 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5326
5327 for (type = 0; type < ANON_AND_FILE; type++) {
5328 unsigned long size = 0;
5329 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5330
5331 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5332 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5333
5334 seq_printf(m, " %10lu%c", size, mark);
5335 }
5336
5337 seq_putc(m, '\n');
5338
5339 if (full)
5340 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5341 }
5342
5343 return 0;
5344}
5345
5346static const struct seq_operations lru_gen_seq_ops = {
5347 .start = lru_gen_seq_start,
5348 .stop = lru_gen_seq_stop,
5349 .next = lru_gen_seq_next,
5350 .show = lru_gen_seq_show,
5351};
5352
5353static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5354 bool can_swap, bool force_scan)
5355{
5356 DEFINE_MAX_SEQ(lruvec);
5357 DEFINE_MIN_SEQ(lruvec);
5358
5359 if (seq < max_seq)
5360 return 0;
5361
5362 if (seq > max_seq)
5363 return -EINVAL;
5364
5365 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5366 return -ERANGE;
5367
5368 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5369
5370 return 0;
5371}
5372
5373static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5374 int swappiness, unsigned long nr_to_reclaim)
5375{
5376 DEFINE_MAX_SEQ(lruvec);
5377
5378 if (seq + MIN_NR_GENS > max_seq)
5379 return -EINVAL;
5380
5381 sc->nr_reclaimed = 0;
5382
5383 while (!signal_pending(current)) {
5384 DEFINE_MIN_SEQ(lruvec);
5385
5386 if (seq < min_seq[!swappiness])
5387 return 0;
5388
5389 if (sc->nr_reclaimed >= nr_to_reclaim)
5390 return 0;
5391
5392 if (!evict_pages(lruvec, sc, swappiness, NULL))
5393 return 0;
5394
5395 cond_resched();
5396 }
5397
5398 return -EINTR;
5399}
5400
5401static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5402 struct scan_control *sc, int swappiness, unsigned long opt)
5403{
5404 struct lruvec *lruvec;
5405 int err = -EINVAL;
5406 struct mem_cgroup *memcg = NULL;
5407
5408 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5409 return -EINVAL;
5410
5411 if (!mem_cgroup_disabled()) {
5412 rcu_read_lock();
5413 memcg = mem_cgroup_from_id(memcg_id);
5414#ifdef CONFIG_MEMCG
5415 if (memcg && !css_tryget(&memcg->css))
5416 memcg = NULL;
5417#endif
5418 rcu_read_unlock();
5419
5420 if (!memcg)
5421 return -EINVAL;
5422 }
5423
5424 if (memcg_id != mem_cgroup_id(memcg))
5425 goto done;
5426
5427 lruvec = get_lruvec(memcg, nid);
5428
5429 if (swappiness < 0)
5430 swappiness = get_swappiness(lruvec, sc);
5431 else if (swappiness > 200)
5432 goto done;
5433
5434 switch (cmd) {
5435 case '+':
5436 err = run_aging(lruvec, seq, sc, swappiness, opt);
5437 break;
5438 case '-':
5439 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5440 break;
5441 }
5442done:
5443 mem_cgroup_put(memcg);
5444
5445 return err;
5446}
5447
Yu Zhao642d9862022-09-18 02:00:10 -06005448/* see Documentation/admin-guide/mm/multigen_lru.rst for details */
Yu Zhao4983c522022-09-18 02:00:09 -06005449static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5450 size_t len, loff_t *pos)
5451{
5452 void *buf;
5453 char *cur, *next;
5454 unsigned int flags;
5455 struct blk_plug plug;
5456 int err = -EINVAL;
5457 struct scan_control sc = {
5458 .may_writepage = true,
5459 .may_unmap = true,
5460 .may_swap = true,
5461 .reclaim_idx = MAX_NR_ZONES - 1,
5462 .gfp_mask = GFP_KERNEL,
5463 };
5464
5465 buf = kvmalloc(len + 1, GFP_KERNEL);
5466 if (!buf)
5467 return -ENOMEM;
5468
5469 if (copy_from_user(buf, src, len)) {
5470 kvfree(buf);
5471 return -EFAULT;
5472 }
5473
5474 set_task_reclaim_state(current, &sc.reclaim_state);
5475 flags = memalloc_noreclaim_save();
5476 blk_start_plug(&plug);
5477 if (!set_mm_walk(NULL)) {
5478 err = -ENOMEM;
5479 goto done;
5480 }
5481
5482 next = buf;
5483 next[len] = '\0';
5484
5485 while ((cur = strsep(&next, ",;\n"))) {
5486 int n;
5487 int end;
5488 char cmd;
5489 unsigned int memcg_id;
5490 unsigned int nid;
5491 unsigned long seq;
5492 unsigned int swappiness = -1;
5493 unsigned long opt = -1;
5494
5495 cur = skip_spaces(cur);
5496 if (!*cur)
5497 continue;
5498
5499 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5500 &seq, &end, &swappiness, &end, &opt, &end);
5501 if (n < 4 || cur[end]) {
5502 err = -EINVAL;
5503 break;
5504 }
5505
5506 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5507 if (err)
5508 break;
5509 }
5510done:
5511 clear_mm_walk();
5512 blk_finish_plug(&plug);
5513 memalloc_noreclaim_restore(flags);
5514 set_task_reclaim_state(current, NULL);
5515
5516 kvfree(buf);
5517
5518 return err ? : len;
5519}
5520
5521static int lru_gen_seq_open(struct inode *inode, struct file *file)
5522{
5523 return seq_open(file, &lru_gen_seq_ops);
5524}
5525
5526static const struct file_operations lru_gen_rw_fops = {
5527 .open = lru_gen_seq_open,
5528 .read = seq_read,
5529 .write = lru_gen_seq_write,
5530 .llseek = seq_lseek,
5531 .release = seq_release,
5532};
5533
5534static const struct file_operations lru_gen_ro_fops = {
5535 .open = lru_gen_seq_open,
5536 .read = seq_read,
5537 .llseek = seq_lseek,
5538 .release = seq_release,
5539};
5540
5541/******************************************************************************
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005542 * initialization
5543 ******************************************************************************/
5544
5545void lru_gen_init_lruvec(struct lruvec *lruvec)
5546{
Yu Zhao430499c2022-09-18 02:00:08 -06005547 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005548 int gen, type, zone;
5549 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5550
5551 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005552 lrugen->enabled = lru_gen_enabled();
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005553
Yu Zhao430499c2022-09-18 02:00:08 -06005554 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5555 lrugen->timestamps[i] = jiffies;
5556
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005557 for_each_gen_type_zone(gen, type, zone)
5558 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005559
5560 lruvec->mm_state.seq = MIN_NR_GENS;
5561 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005562}
5563
5564#ifdef CONFIG_MEMCG
5565void lru_gen_init_memcg(struct mem_cgroup *memcg)
5566{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005567 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5568 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005569}
5570
5571void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5572{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005573 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005574 int nid;
5575
5576 for_each_node(nid) {
5577 struct lruvec *lruvec = get_lruvec(memcg, nid);
5578
5579 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5580 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005581
5582 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5583 bitmap_free(lruvec->mm_state.filters[i]);
5584 lruvec->mm_state.filters[i] = NULL;
5585 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005586 }
5587}
5588#endif
5589
5590static int __init init_lru_gen(void)
5591{
5592 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5593 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5594
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005595 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5596 pr_err("lru_gen: failed to create sysfs group\n");
5597
Yu Zhao4983c522022-09-18 02:00:09 -06005598 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5599 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5600
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005601 return 0;
5602};
5603late_initcall(init_lru_gen);
5604
Yu Zhao37397872022-09-18 02:00:03 -06005605#else /* !CONFIG_LRU_GEN */
5606
5607static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5608{
5609}
5610
5611static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5612{
5613}
5614
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005615#endif /* CONFIG_LRU_GEN */
5616
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005617static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005618{
5619 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005620 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005621 unsigned long nr_to_scan;
5622 enum lru_list lru;
5623 unsigned long nr_reclaimed = 0;
5624 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005625 bool proportional_reclaim;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005626 struct blk_plug plug;
5627
Yu Zhao37397872022-09-18 02:00:03 -06005628 if (lru_gen_enabled()) {
5629 lru_gen_shrink_lruvec(lruvec, sc);
5630 return;
5631 }
5632
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005633 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005634
Mel Gormane82e0562013-07-03 15:01:44 -07005635 /* Record the original scan target for proportional adjustments later */
5636 memcpy(targets, nr, sizeof(nr));
5637
Mel Gorman1a501902014-06-04 16:10:49 -07005638 /*
5639 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5640 * event that can occur when there is little memory pressure e.g.
5641 * multiple streaming readers/writers. Hence, we do not abort scanning
5642 * when the requested number of pages are reclaimed when scanning at
5643 * DEF_PRIORITY on the assumption that the fact we are direct
5644 * reclaiming implies that kswapd is not keeping up and it is best to
5645 * do a batch of work at once. For memcg reclaim one check is made to
5646 * abort proportional reclaim if either the file or anon lru has already
5647 * dropped to zero at the first pass.
5648 */
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005649 proportional_reclaim = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
5650 sc->priority == DEF_PRIORITY);
Mel Gorman1a501902014-06-04 16:10:49 -07005651
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005652 blk_start_plug(&plug);
5653 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5654 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005655 unsigned long nr_anon, nr_file, percentage;
5656 unsigned long nr_scanned;
5657
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005658 for_each_evictable_lru(lru) {
5659 if (nr[lru]) {
5660 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5661 nr[lru] -= nr_to_scan;
5662
5663 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005664 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005665 }
5666 }
Mel Gormane82e0562013-07-03 15:01:44 -07005667
Michal Hockobd041732016-12-02 17:26:48 -08005668 cond_resched();
5669
Johannes Weiner7b3c9402022-08-02 12:28:11 -04005670 if (nr_reclaimed < nr_to_reclaim || proportional_reclaim)
Mel Gormane82e0562013-07-03 15:01:44 -07005671 continue;
5672
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005673 /*
Mel Gormane82e0562013-07-03 15:01:44 -07005674 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07005675 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07005676 * proportionally what was requested by get_scan_count(). We
5677 * stop reclaiming one LRU and reduce the amount scanning
5678 * proportional to the original scan target.
5679 */
5680 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5681 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5682
Mel Gorman1a501902014-06-04 16:10:49 -07005683 /*
5684 * It's just vindictive to attack the larger once the smaller
5685 * has gone to zero. And given the way we stop scanning the
5686 * smaller below, this makes sure that we only make one nudge
5687 * towards proportionality once we've got nr_to_reclaim.
5688 */
5689 if (!nr_file || !nr_anon)
5690 break;
5691
Mel Gormane82e0562013-07-03 15:01:44 -07005692 if (nr_file > nr_anon) {
5693 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5694 targets[LRU_ACTIVE_ANON] + 1;
5695 lru = LRU_BASE;
5696 percentage = nr_anon * 100 / scan_target;
5697 } else {
5698 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5699 targets[LRU_ACTIVE_FILE] + 1;
5700 lru = LRU_FILE;
5701 percentage = nr_file * 100 / scan_target;
5702 }
5703
5704 /* Stop scanning the smaller of the LRU */
5705 nr[lru] = 0;
5706 nr[lru + LRU_ACTIVE] = 0;
5707
5708 /*
5709 * Recalculate the other LRU scan count based on its original
5710 * scan target and the percentage scanning already complete
5711 */
5712 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5713 nr_scanned = targets[lru] - nr[lru];
5714 nr[lru] = targets[lru] * (100 - percentage) / 100;
5715 nr[lru] -= min(nr[lru], nr_scanned);
5716
5717 lru += LRU_ACTIVE;
5718 nr_scanned = targets[lru] - nr[lru];
5719 nr[lru] = targets[lru] * (100 - percentage) / 100;
5720 nr[lru] -= min(nr[lru], nr_scanned);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005721 }
5722 blk_finish_plug(&plug);
5723 sc->nr_reclaimed += nr_reclaimed;
5724
5725 /*
5726 * Even if we did not try to evict anon pages at all, we want to
5727 * rebalance the anon lru active/inactive ratio.
5728 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005729 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5730 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005731 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5732 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005733}
5734
Mel Gorman23b9da52012-05-29 15:06:20 -07005735/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005736static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005737{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005738 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005739 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005740 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005741 return true;
5742
5743 return false;
5744}
5745
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005746/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005747 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5748 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5749 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005750 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005751 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005752 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005753static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005754 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005755 struct scan_control *sc)
5756{
5757 unsigned long pages_for_compaction;
5758 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005759 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005760
5761 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005762 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005763 return false;
5764
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005765 /*
5766 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5767 * number of pages that were scanned. This will return to the caller
5768 * with the risk reclaim/compaction and the resulting allocation attempt
5769 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5770 * allocations through requiring that the full LRU list has been scanned
5771 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5772 * scan, but that approximation was wrong, and there were corner cases
5773 * where always a non-zero amount of pages were scanned.
5774 */
5775 if (!nr_reclaimed)
5776 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005777
Mel Gorman3e7d3442011-01-13 15:45:56 -08005778 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005779 for (z = 0; z <= sc->reclaim_idx; z++) {
5780 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005781 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005782 continue;
5783
5784 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005785 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005786 case COMPACT_CONTINUE:
5787 return false;
5788 default:
5789 /* check next zone */
5790 ;
5791 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005792 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005793
5794 /*
5795 * If we have not reclaimed enough pages for compaction and the
5796 * inactive lists are large enough, continue reclaiming
5797 */
5798 pages_for_compaction = compact_gap(sc->order);
5799 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005800 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005801 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5802
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005803 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005804}
5805
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005806static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005807{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005808 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005809 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005810
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005811 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005812 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005813 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005814 unsigned long reclaimed;
5815 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005816 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08005817
Xunlei Pange3336ca2020-09-04 16:35:27 -07005818 /*
5819 * This loop can become CPU-bound when target memcgs
5820 * aren't eligible for reclaim - either because they
5821 * don't have any reclaimable pages, or because their
5822 * memory is explicitly protected. Avoid soft lockups.
5823 */
5824 cond_resched();
5825
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005826 trace_android_vh_shrink_node_memcgs(memcg, &skip);
5827 if (skip)
5828 continue;
5829
Chris Down45c7f7e2020-08-06 23:22:05 -07005830 mem_cgroup_calculate_protection(target_memcg, memcg);
5831
5832 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005833 /*
5834 * Hard protection.
5835 * If there is no reclaimable memory, OOM.
5836 */
5837 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005838 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005839 /*
5840 * Soft protection.
5841 * Respect the protection only as long as
5842 * there is an unprotected supply
5843 * of reclaimable memory from other cgroups.
5844 */
5845 if (!sc->memcg_low_reclaim) {
5846 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005847 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005848 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005849 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005850 }
5851
Johannes Weinerd2af3392019-11-30 17:55:43 -08005852 reclaimed = sc->nr_reclaimed;
5853 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005854
5855 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005856
Johannes Weinerd2af3392019-11-30 17:55:43 -08005857 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5858 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005859
Johannes Weinerd2af3392019-11-30 17:55:43 -08005860 /* Record the group's reclaim efficiency */
5861 vmpressure(sc->gfp_mask, memcg, false,
5862 sc->nr_scanned - scanned,
5863 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005864
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005865 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5866}
5867
Liu Song6c9e09072020-01-30 22:14:08 -08005868static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005869{
5870 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005871 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005872 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005873 bool reclaimable = false;
5874
Johannes Weiner1b051172019-11-30 17:55:52 -08005875 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5876
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005877again:
5878 memset(&sc->nr, 0, sizeof(sc->nr));
5879
5880 nr_reclaimed = sc->nr_reclaimed;
5881 nr_scanned = sc->nr_scanned;
5882
Yu Zhao6d313442022-09-18 02:00:00 -06005883 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005884
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005885 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005886
Johannes Weinerd2af3392019-11-30 17:55:43 -08005887 if (reclaim_state) {
5888 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5889 reclaim_state->reclaimed_slab = 0;
5890 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005891
Johannes Weinerd2af3392019-11-30 17:55:43 -08005892 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005893 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005894 sc->nr_scanned - nr_scanned,
5895 sc->nr_reclaimed - nr_reclaimed);
5896
5897 if (sc->nr_reclaimed - nr_reclaimed)
5898 reclaimable = true;
5899
5900 if (current_is_kswapd()) {
5901 /*
5902 * If reclaim is isolating dirty pages under writeback,
5903 * it implies that the long-lived page allocation rate
5904 * is exceeding the page laundering rate. Either the
5905 * global limits are not being effective at throttling
5906 * processes due to the page distribution throughout
5907 * zones or there is heavy usage of a slow backing
5908 * device. The only option is to throttle from reclaim
5909 * context which is not ideal as there is no guarantee
5910 * the dirtying process is throttled in the same way
5911 * balance_dirty_pages() manages.
5912 *
5913 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5914 * count the number of pages under pages flagged for
5915 * immediate reclaim and stall if any are encountered
5916 * in the nr_immediate check below.
5917 */
5918 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5919 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005920
Johannes Weinerd2af3392019-11-30 17:55:43 -08005921 /* Allow kswapd to start writing pages during reclaim.*/
5922 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5923 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005924
5925 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005926 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005927 * reclaim and under writeback (nr_immediate), it
5928 * implies that pages are cycling through the LRU
5929 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005930 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005931 if (sc->nr.immediate)
5932 congestion_wait(BLK_RW_ASYNC, HZ/10);
5933 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005934
Johannes Weinerd2af3392019-11-30 17:55:43 -08005935 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005936 * Tag a node/memcg as congested if all the dirty pages
5937 * scanned were backed by a congested BDI and
5938 * wait_iff_congested will stall.
5939 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005940 * Legacy memcg will stall in page writeback so avoid forcibly
5941 * stalling in wait_iff_congested().
5942 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005943 if ((current_is_kswapd() ||
5944 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005945 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005946 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005947
5948 /*
5949 * Stall direct reclaim for IO completions if underlying BDIs
5950 * and node is congested. Allow kswapd to continue until it
5951 * starts encountering unqueued dirty pages or cycling through
5952 * the LRU too quickly.
5953 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005954 if (!current_is_kswapd() && current_may_throttle() &&
5955 !sc->hibernation_mode &&
5956 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005957 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5958
5959 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5960 sc))
5961 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005962
Johannes Weinerc73322d2017-05-03 14:51:51 -07005963 /*
5964 * Kswapd gives up on balancing particular nodes after too
5965 * many failures to reclaim anything from them and goes to
5966 * sleep. On reclaim progress, reset the failure counter. A
5967 * successful direct reclaim run will revive a dormant kswapd.
5968 */
5969 if (reclaimable)
5970 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005971}
5972
Vlastimil Babka53853e22014-10-09 15:27:02 -07005973/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005974 * Returns true if compaction should go ahead for a costly-order request, or
5975 * the allocation would already succeed without compaction. Return false if we
5976 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07005977 */
Mel Gorman4f588332016-07-28 15:46:38 -07005978static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005979{
Mel Gorman31483b62016-07-28 15:45:46 -07005980 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005981 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005982
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005983 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
5984 if (suitable == COMPACT_SUCCESS)
5985 /* Allocation should succeed already. Don't reclaim. */
5986 return true;
5987 if (suitable == COMPACT_SKIPPED)
5988 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005989 return false;
5990
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005991 /*
5992 * Compaction is already possible, but it takes time to run and there
5993 * are potentially other callers using the pages just freed. So proceed
5994 * with reclaim to make a buffer of free pages available to give
5995 * compaction a reasonable chance of completing and allocating the page.
5996 * Note that we won't actually reclaim the whole buffer in one attempt
5997 * as the target watermark in should_continue_reclaim() is lower. But if
5998 * we are already above the high+gap watermark, don't reclaim at all.
5999 */
6000 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6001
6002 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006003}
6004
Linus Torvalds1da177e2005-04-16 15:20:36 -07006005/*
6006 * This is the direct reclaim path, for page-allocating processes. We only
6007 * try to reclaim pages from zones which will satisfy the caller's allocation
6008 * request.
6009 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07006010 * If a zone is deemed to be full of pinned pages then just give it a light
6011 * scan then give up on it.
6012 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07006013static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006014{
Mel Gormandd1a2392008-04-28 02:12:17 -07006015 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07006016 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07006017 unsigned long nr_soft_reclaimed;
6018 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07006019 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07006020 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006021
Mel Gormancc715d92012-03-21 16:34:00 -07006022 /*
6023 * If the number of buffer_heads in the machine exceeds the maximum
6024 * allowed level, force direct reclaim to scan the highmem zone as
6025 * highmem pages could be pinning lowmem pages storing buffer_heads
6026 */
Weijie Yang619d0d762014-04-07 15:36:59 -07006027 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07006028 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07006029 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07006030 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07006031 }
Mel Gormancc715d92012-03-21 16:34:00 -07006032
Mel Gormand4debc62010-08-09 17:19:29 -07006033 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07006034 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07006035 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006036 * Take care memory controller reclaiming has small influence
6037 * to global LRU.
6038 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08006039 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04006040 if (!cpuset_zone_allowed(zone,
6041 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006042 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006043
Johannes Weiner0b064962014-08-06 16:06:12 -07006044 /*
6045 * If we already have plenty of memory free for
6046 * compaction in this zone, don't free any more.
6047 * Even though compaction is invoked for any
6048 * non-zero order, only frequent costly order
6049 * reclamation is disruptive enough to become a
6050 * noticeable problem, like transparent huge
6051 * page allocations.
6052 */
6053 if (IS_ENABLED(CONFIG_COMPACTION) &&
6054 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07006055 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07006056 sc->compaction_ready = true;
6057 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07006058 }
Johannes Weiner0b064962014-08-06 16:06:12 -07006059
Andrew Morton0608f432013-09-24 15:27:41 -07006060 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07006061 * Shrink each node in the zonelist once. If the
6062 * zonelist is ordered by zone (not the default) then a
6063 * node may be shrunk multiple times but in that case
6064 * the user prefers lower zones being preserved.
6065 */
6066 if (zone->zone_pgdat == last_pgdat)
6067 continue;
6068
6069 /*
Andrew Morton0608f432013-09-24 15:27:41 -07006070 * This steals pages from memory cgroups over softlimit
6071 * and returns the number of reclaimed pages and
6072 * scanned pages. This works for global memory pressure
6073 * and balancing, not for a memcg's limit.
6074 */
6075 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006076 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006077 sc->order, sc->gfp_mask,
6078 &nr_soft_scanned);
6079 sc->nr_reclaimed += nr_soft_reclaimed;
6080 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006081 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006082 }
Nick Piggin408d8542006-09-25 23:31:27 -07006083
Mel Gorman79dafcd2016-07-28 15:45:53 -07006084 /* See comment about same check for global reclaim above */
6085 if (zone->zone_pgdat == last_pgdat)
6086 continue;
6087 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006088 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006089 }
Mel Gormane0c23272011-10-31 17:09:33 -07006090
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006091 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006092 * Restore to original mask to avoid the impact on the caller if we
6093 * promoted it to __GFP_HIGHMEM.
6094 */
6095 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006096}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006097
Johannes Weinerb9107182019-11-30 17:55:59 -08006098static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006099{
Johannes Weinerb9107182019-11-30 17:55:59 -08006100 struct lruvec *target_lruvec;
6101 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006102
Yu Zhao37397872022-09-18 02:00:03 -06006103 if (lru_gen_enabled())
6104 return;
6105
Johannes Weinerb9107182019-11-30 17:55:59 -08006106 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006107 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6108 target_lruvec->refaults[0] = refaults;
6109 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6110 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006111}
6112
Linus Torvalds1da177e2005-04-16 15:20:36 -07006113/*
6114 * This is the main entry point to direct page reclaim.
6115 *
6116 * If a full scan of the inactive list fails to free enough memory then we
6117 * are "out of memory" and something needs to be killed.
6118 *
6119 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6120 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006121 * caller can't do much about. We kick the writeback threads and take explicit
6122 * naps in the hope that some of these pages can be written. But if the
6123 * allocating task holds filesystem locks which prevent writeout this might not
6124 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006125 *
6126 * returns: 0, if no pages reclaimed
6127 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006128 */
Mel Gormandac1d272008-04-28 02:12:12 -07006129static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006130 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006131{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006132 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006133 pg_data_t *last_pgdat;
6134 struct zoneref *z;
6135 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006136retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006137 delayacct_freepages_start();
6138
Johannes Weinerb5ead352019-11-30 17:55:40 -08006139 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006140 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006141
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006142 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006143 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6144 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006145 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006146 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006147
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006148 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006149 break;
6150
6151 if (sc->compaction_ready)
6152 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006153
6154 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006155 * If we're getting trouble reclaiming, start doing
6156 * writepage even in laptop mode.
6157 */
6158 if (sc->priority < DEF_PRIORITY - 2)
6159 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006160 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006161
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006162 last_pgdat = NULL;
6163 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6164 sc->nodemask) {
6165 if (zone->zone_pgdat == last_pgdat)
6166 continue;
6167 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006168
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006169 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006170
6171 if (cgroup_reclaim(sc)) {
6172 struct lruvec *lruvec;
6173
6174 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6175 zone->zone_pgdat);
6176 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6177 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006178 }
6179
Keika Kobayashi873b4772008-07-25 01:48:52 -07006180 delayacct_freepages_end();
6181
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006182 if (sc->nr_reclaimed)
6183 return sc->nr_reclaimed;
6184
Mel Gorman0cee34f2012-01-12 17:19:49 -08006185 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006186 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006187 return 1;
6188
Johannes Weinerb91ac372019-11-30 17:56:02 -08006189 /*
6190 * We make inactive:active ratio decisions based on the node's
6191 * composition of memory, but a restrictive reclaim_idx or a
6192 * memory.low cgroup setting can exempt large amounts of
6193 * memory from reclaim. Neither of which are very common, so
6194 * instead of doing costly eligibility calculations of the
6195 * entire cgroup subtree up front, we assume the estimates are
6196 * good, and retry with forcible deactivation if that fails.
6197 */
6198 if (sc->skipped_deactivate) {
6199 sc->priority = initial_priority;
6200 sc->force_deactivate = 1;
6201 sc->skipped_deactivate = 0;
6202 goto retry;
6203 }
6204
Johannes Weiner241994ed2015-02-11 15:26:06 -08006205 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006206 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006207 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006208 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006209 sc->memcg_low_reclaim = 1;
6210 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006211 goto retry;
6212 }
6213
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006214 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006215}
6216
Johannes Weinerc73322d2017-05-03 14:51:51 -07006217static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006218{
6219 struct zone *zone;
6220 unsigned long pfmemalloc_reserve = 0;
6221 unsigned long free_pages = 0;
6222 int i;
6223 bool wmark_ok;
6224
Johannes Weinerc73322d2017-05-03 14:51:51 -07006225 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6226 return true;
6227
Mel Gorman55150612012-07-31 16:44:35 -07006228 for (i = 0; i <= ZONE_NORMAL; i++) {
6229 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006230 if (!managed_zone(zone))
6231 continue;
6232
6233 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006234 continue;
6235
Mel Gorman55150612012-07-31 16:44:35 -07006236 pfmemalloc_reserve += min_wmark_pages(zone);
6237 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6238 }
6239
Mel Gorman675becc2014-06-04 16:07:35 -07006240 /* If there are no reserves (unexpected config) then do not throttle */
6241 if (!pfmemalloc_reserve)
6242 return true;
6243
Mel Gorman55150612012-07-31 16:44:35 -07006244 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6245
6246 /* kswapd must be awake if processes are being throttled */
6247 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006248 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6249 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006250
Mel Gorman55150612012-07-31 16:44:35 -07006251 wake_up_interruptible(&pgdat->kswapd_wait);
6252 }
6253
6254 return wmark_ok;
6255}
6256
6257/*
6258 * Throttle direct reclaimers if backing storage is backed by the network
6259 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6260 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006261 * when the low watermark is reached.
6262 *
6263 * Returns true if a fatal signal was delivered during throttling. If this
6264 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006265 */
Mel Gorman50694c22012-11-26 16:29:48 -08006266static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006267 nodemask_t *nodemask)
6268{
Mel Gorman675becc2014-06-04 16:07:35 -07006269 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006270 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006271 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006272
6273 /*
6274 * Kernel threads should not be throttled as they may be indirectly
6275 * responsible for cleaning pages necessary for reclaim to make forward
6276 * progress. kjournald for example may enter direct reclaim while
6277 * committing a transaction where throttling it could forcing other
6278 * processes to block on log_wait_commit().
6279 */
6280 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006281 goto out;
6282
6283 /*
6284 * If a fatal signal is pending, this process should not throttle.
6285 * It should return quickly so it can exit and free its memory
6286 */
6287 if (fatal_signal_pending(current))
6288 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006289
Mel Gorman675becc2014-06-04 16:07:35 -07006290 /*
6291 * Check if the pfmemalloc reserves are ok by finding the first node
6292 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6293 * GFP_KERNEL will be required for allocating network buffers when
6294 * swapping over the network so ZONE_HIGHMEM is unusable.
6295 *
6296 * Throttling is based on the first usable node and throttled processes
6297 * wait on a queue until kswapd makes progress and wakes them. There
6298 * is an affinity then between processes waking up and where reclaim
6299 * progress has been made assuming the process wakes on the same node.
6300 * More importantly, processes running on remote nodes will not compete
6301 * for remote pfmemalloc reserves and processes on different nodes
6302 * should make reasonable progress.
6303 */
6304 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006305 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006306 if (zone_idx(zone) > ZONE_NORMAL)
6307 continue;
6308
6309 /* Throttle based on the first usable node */
6310 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006311 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006312 goto out;
6313 break;
6314 }
6315
6316 /* If no zone was usable by the allocation flags then do not throttle */
6317 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006318 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006319
Mel Gorman68243e72012-07-31 16:44:39 -07006320 /* Account for the throttling */
6321 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6322
Mel Gorman55150612012-07-31 16:44:35 -07006323 /*
6324 * If the caller cannot enter the filesystem, it's possible that it
6325 * is due to the caller holding an FS lock or performing a journal
6326 * transaction in the case of a filesystem like ext[3|4]. In this case,
6327 * it is not safe to block on pfmemalloc_wait as kswapd could be
6328 * blocked waiting on the same lock. Instead, throttle for up to a
6329 * second before continuing.
6330 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006331 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006332 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006333 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006334 else
6335 /* Throttle until kswapd wakes the process */
6336 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6337 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006338
Mel Gorman50694c22012-11-26 16:29:48 -08006339 if (fatal_signal_pending(current))
6340 return true;
6341
6342out:
6343 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006344}
6345
Mel Gormandac1d272008-04-28 02:12:12 -07006346unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006347 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006348{
Mel Gorman33906bc2010-08-09 17:19:16 -07006349 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006350 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006351 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006352 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006353 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006354 .order = order,
6355 .nodemask = nodemask,
6356 .priority = DEF_PRIORITY,
6357 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006358 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006359 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006360 };
6361
Mel Gorman55150612012-07-31 16:44:35 -07006362 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006363 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6364 * Confirm they are large enough for max values.
6365 */
6366 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6367 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6368 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6369
6370 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006371 * Do not enter reclaim if fatal signal was delivered while throttled.
6372 * 1 is returned so that the page allocator does not OOM kill at this
6373 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006374 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006375 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006376 return 1;
6377
Andrew Morton1732d2b012019-07-16 16:26:15 -07006378 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006379 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006380
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006381 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006382
6383 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006384 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006385
6386 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006387}
6388
Andrew Mortonc255a452012-07-31 16:43:02 -07006389#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006390
Michal Hockod2e5fb92019-08-30 16:04:50 -07006391/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006392unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006393 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006394 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006395 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006396{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006397 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006398 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006399 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006400 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006401 .may_writepage = !laptop_mode,
6402 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006403 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006404 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006405 };
Ying Han0ae5e892011-05-26 16:25:25 -07006406
Michal Hockod2e5fb92019-08-30 16:04:50 -07006407 WARN_ON_ONCE(!current->reclaim_state);
6408
Balbir Singh4e416952009-09-23 15:56:39 -07006409 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6410 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006411
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006412 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006413 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006414
Balbir Singh4e416952009-09-23 15:56:39 -07006415 /*
6416 * NOTE: Although we can get the priority field, using it
6417 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006418 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006419 * will pick up pages from other mem cgroup's as well. We hack
6420 * the priority and make it zero.
6421 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006422 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006423
6424 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6425
Ying Han0ae5e892011-05-26 16:25:25 -07006426 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006427
Balbir Singh4e416952009-09-23 15:56:39 -07006428 return sc.nr_reclaimed;
6429}
6430
Johannes Weiner72835c82012-01-12 17:18:32 -08006431unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006432 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006433 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006434 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08006435{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006436 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006437 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006438 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006439 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006440 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006441 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006442 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006443 .target_mem_cgroup = memcg,
6444 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006445 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006446 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006447 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07006448 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006449 /*
6450 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6451 * equal pressure on all the nodes. This is based on the assumption that
6452 * the reclaim does not bail out early.
6453 */
6454 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006455
Andrew Morton1732d2b012019-07-16 16:26:15 -07006456 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006457 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006458 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006459
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006460 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006461
Vlastimil Babka499118e2017-05-08 15:59:50 -07006462 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006463 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006464 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006465
6466 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006467}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006468EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006469#endif
6470
Yu Zhao37397872022-09-18 02:00:03 -06006471static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006472{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006473 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006474 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006475
Yu Zhao37397872022-09-18 02:00:03 -06006476 if (lru_gen_enabled()) {
6477 lru_gen_age_node(pgdat, sc);
6478 return;
6479 }
6480
Dave Hansen2f368a92021-09-02 14:59:23 -07006481 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006482 return;
6483
Johannes Weinerb91ac372019-11-30 17:56:02 -08006484 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6485 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6486 return;
6487
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006488 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6489 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006490 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6491 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6492 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006493 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6494 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006495}
6496
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006497static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006498{
6499 int i;
6500 struct zone *zone;
6501
6502 /*
6503 * Check for watermark boosts top-down as the higher zones
6504 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006505 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006506 * start prematurely when there is no boosting and a lower
6507 * zone is balanced.
6508 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006509 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006510 zone = pgdat->node_zones + i;
6511 if (!managed_zone(zone))
6512 continue;
6513
6514 if (zone->watermark_boost)
6515 return true;
6516 }
6517
6518 return false;
6519}
6520
Mel Gormane716f2e2017-05-03 14:53:45 -07006521/*
6522 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006523 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006524 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006525static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006526{
Mel Gormane716f2e2017-05-03 14:53:45 -07006527 int i;
6528 unsigned long mark = -1;
6529 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006530
Mel Gorman1c308442018-12-28 00:35:52 -08006531 /*
6532 * Check watermarks bottom-up as lower zones are more likely to
6533 * meet watermarks.
6534 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006535 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006536 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006537
Mel Gormane716f2e2017-05-03 14:53:45 -07006538 if (!managed_zone(zone))
6539 continue;
6540
6541 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006542 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006543 return true;
6544 }
6545
6546 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006547 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006548 * need balancing by definition. This can happen if a zone-restricted
6549 * allocation tries to wake a remote kswapd.
6550 */
6551 if (mark == -1)
6552 return true;
6553
6554 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006555}
6556
Mel Gorman631b6e02017-05-03 14:53:41 -07006557/* Clear pgdat state for congested, dirty or under writeback. */
6558static void clear_pgdat_congested(pg_data_t *pgdat)
6559{
Johannes Weiner1b051172019-11-30 17:55:52 -08006560 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6561
6562 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006563 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6564 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6565}
6566
Mel Gorman1741c872011-01-13 15:46:21 -08006567/*
Mel Gorman55150612012-07-31 16:44:35 -07006568 * Prepare kswapd for sleeping. This verifies that there are no processes
6569 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6570 *
6571 * Returns true if kswapd is ready to sleep
6572 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006573static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6574 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006575{
Mel Gorman55150612012-07-31 16:44:35 -07006576 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006577 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006578 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006579 * race between when kswapd checks the watermarks and a process gets
6580 * throttled. There is also a potential race if processes get
6581 * throttled, kswapd wakes, a large process exits thereby balancing the
6582 * zones, which causes kswapd to exit balance_pgdat() before reaching
6583 * the wake up checks. If kswapd is going to sleep, no process should
6584 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6585 * the wake up is premature, processes will wake kswapd and get
6586 * throttled again. The difference from wake ups in balance_pgdat() is
6587 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006588 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006589 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6590 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006591
Johannes Weinerc73322d2017-05-03 14:51:51 -07006592 /* Hopeless node, leave it to direct reclaim */
6593 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6594 return true;
6595
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006596 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006597 clear_pgdat_congested(pgdat);
6598 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006599 }
6600
Shantanu Goel333b0a42017-05-03 14:53:38 -07006601 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006602}
6603
Linus Torvalds1da177e2005-04-16 15:20:36 -07006604/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006605 * kswapd shrinks a node of pages that are at or below the highest usable
6606 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006607 *
6608 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006609 * reclaim or if the lack of progress was due to pages under writeback.
6610 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006611 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006612static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006613 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006614{
Mel Gorman1d82de62016-07-28 15:45:43 -07006615 struct zone *zone;
6616 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006617
Mel Gorman1d82de62016-07-28 15:45:43 -07006618 /* Reclaim a number of pages proportional to the number of zones */
6619 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006620 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006621 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006622 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006623 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006624
Mel Gorman1d82de62016-07-28 15:45:43 -07006625 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006626 }
6627
Mel Gorman1d82de62016-07-28 15:45:43 -07006628 /*
6629 * Historically care was taken to put equal pressure on all zones but
6630 * now pressure is applied based on node LRU order.
6631 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006632 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006633
6634 /*
6635 * Fragmentation may mean that the system cannot be rebalanced for
6636 * high-order allocations. If twice the allocation size has been
6637 * reclaimed then recheck watermarks only at order-0 to prevent
6638 * excessive reclaim. Assume that a process requested a high-order
6639 * can direct reclaim/compact.
6640 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006641 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006642 sc->order = 0;
6643
Mel Gormanb8e83b92013-07-03 15:01:45 -07006644 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006645}
6646
Mel Gormanc49c2c42021-06-28 19:42:21 -07006647/* Page allocator PCP high watermark is lowered if reclaim is active. */
6648static inline void
6649update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6650{
6651 int i;
6652 struct zone *zone;
6653
6654 for (i = 0; i <= highest_zoneidx; i++) {
6655 zone = pgdat->node_zones + i;
6656
6657 if (!managed_zone(zone))
6658 continue;
6659
6660 if (active)
6661 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6662 else
6663 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6664 }
6665}
6666
6667static inline void
6668set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6669{
6670 update_reclaim_active(pgdat, highest_zoneidx, true);
6671}
6672
6673static inline void
6674clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6675{
6676 update_reclaim_active(pgdat, highest_zoneidx, false);
6677}
6678
Mel Gorman75485362013-07-03 15:01:42 -07006679/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006680 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6681 * that are eligible for use by the caller until at least one zone is
6682 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006683 *
Mel Gorman1d82de62016-07-28 15:45:43 -07006684 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006685 *
6686 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07006687 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08006688 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07006689 * or lower is eligible for reclaim until at least one usable zone is
6690 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006691 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006692static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006693{
Linus Torvalds1da177e2005-04-16 15:20:36 -07006694 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07006695 unsigned long nr_soft_reclaimed;
6696 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07006697 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08006698 unsigned long nr_boost_reclaim;
6699 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6700 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07006701 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08006702 struct scan_control sc = {
6703 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07006704 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006705 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08006706 };
Omar Sandoval93781322018-06-07 17:07:02 -07006707
Andrew Morton1732d2b012019-07-16 16:26:15 -07006708 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07006709 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006710 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006711
Christoph Lameterf8891e52006-06-30 01:55:45 -07006712 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006713
Mel Gorman1c308442018-12-28 00:35:52 -08006714 /*
6715 * Account for the reclaim boost. Note that the zone boost is left in
6716 * place so that parallel allocations that are near the watermark will
6717 * stall or direct reclaim until kswapd is finished.
6718 */
6719 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006720 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006721 zone = pgdat->node_zones + i;
6722 if (!managed_zone(zone))
6723 continue;
6724
6725 nr_boost_reclaim += zone->watermark_boost;
6726 zone_boosts[i] = zone->watermark_boost;
6727 }
6728 boosted = nr_boost_reclaim;
6729
6730restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006731 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006732 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006733 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006734 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006735 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006736 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006737 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006738
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006739 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006740
Mel Gorman86c79f62016-07-28 15:45:59 -07006741 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006742 * If the number of buffer_heads exceeds the maximum allowed
6743 * then consider reclaiming from all zones. This has a dual
6744 * purpose -- on 64-bit systems it is expected that
6745 * buffer_heads are stripped during active rotation. On 32-bit
6746 * systems, highmem pages can pin lowmem memory and shrinking
6747 * buffers can relieve lowmem pressure. Reclaim may still not
6748 * go ahead if all eligible zones for the original allocation
6749 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006750 */
6751 if (buffer_heads_over_limit) {
6752 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6753 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006754 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006755 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006756
Mel Gorman970a39a2016-07-28 15:46:35 -07006757 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006758 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006759 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006760 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006761
Mel Gorman86c79f62016-07-28 15:45:59 -07006762 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006763 * If the pgdat is imbalanced then ignore boosting and preserve
6764 * the watermarks for a later time and restart. Note that the
6765 * zone watermarks will be still reset at the end of balancing
6766 * on the grounds that the normal reclaim should be enough to
6767 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006768 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006769 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006770 if (!balanced && nr_boost_reclaim) {
6771 nr_boost_reclaim = 0;
6772 goto restart;
6773 }
6774
6775 /*
6776 * If boosting is not active then only reclaim if there are no
6777 * eligible zones. Note that sc.reclaim_idx is not used as
6778 * buffer_heads_over_limit may have adjusted it.
6779 */
6780 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006781 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006782
Mel Gorman1c308442018-12-28 00:35:52 -08006783 /* Limit the priority of boosting to avoid reclaim writeback */
6784 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6785 raise_priority = false;
6786
6787 /*
6788 * Do not writeback or swap pages for boosted reclaim. The
6789 * intent is to relieve pressure not issue sub-optimal IO
6790 * from reclaim context. If no pages are reclaimed, the
6791 * reclaim will be aborted.
6792 */
6793 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6794 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006795
Linus Torvalds1da177e2005-04-16 15:20:36 -07006796 /*
Yu Zhao37397872022-09-18 02:00:03 -06006797 * Do some background aging, to give pages a chance to be
6798 * referenced before reclaiming. All pages are rotated
6799 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07006800 */
Yu Zhao37397872022-09-18 02:00:03 -06006801 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006802
6803 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006804 * If we're getting trouble reclaiming, start doing writepage
6805 * even in laptop mode.
6806 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006807 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006808 sc.may_writepage = 1;
6809
Mel Gorman1d82de62016-07-28 15:45:43 -07006810 /* Call soft limit reclaim before calling shrink_node. */
6811 sc.nr_scanned = 0;
6812 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006813 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006814 sc.gfp_mask, &nr_soft_scanned);
6815 sc.nr_reclaimed += nr_soft_reclaimed;
6816
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006817 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006818 * There should be no need to raise the scanning priority if
6819 * enough pages are already being scanned that that high
6820 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006821 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006822 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006823 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006824
6825 /*
6826 * If the low watermark is met there is no need for processes
6827 * to be throttled on pfmemalloc_wait as they should not be
6828 * able to safely make forward progress. Wake them
6829 */
6830 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006831 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006832 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006833
Mel Gormanb8e83b92013-07-03 15:01:45 -07006834 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006835 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006836 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006837 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006838 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006839 break;
6840
6841 /*
6842 * Raise priority if scanning rate is too low or there was no
6843 * progress in reclaiming pages
6844 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006845 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006846 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6847
6848 /*
6849 * If reclaim made no progress for a boost, stop reclaim as
6850 * IO cannot be queued and it could be an infinite loop in
6851 * extreme circumstances.
6852 */
6853 if (nr_boost_reclaim && !nr_reclaimed)
6854 break;
6855
Johannes Weinerc73322d2017-05-03 14:51:51 -07006856 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006857 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006858 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006859
Johannes Weinerc73322d2017-05-03 14:51:51 -07006860 if (!sc.nr_reclaimed)
6861 pgdat->kswapd_failures++;
6862
Mel Gormanb8e83b92013-07-03 15:01:45 -07006863out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006864 clear_reclaim_active(pgdat, highest_zoneidx);
6865
Mel Gorman1c308442018-12-28 00:35:52 -08006866 /* If reclaim was boosted, account for the reclaim done in this pass */
6867 if (boosted) {
6868 unsigned long flags;
6869
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006870 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006871 if (!zone_boosts[i])
6872 continue;
6873
6874 /* Increments are under the zone lock */
6875 zone = pgdat->node_zones + i;
6876 spin_lock_irqsave(&zone->lock, flags);
6877 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6878 spin_unlock_irqrestore(&zone->lock, flags);
6879 }
6880
6881 /*
6882 * As there is now likely space, wakeup kcompact to defragment
6883 * pageblocks.
6884 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006885 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006886 }
6887
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006888 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006889 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006890 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006891 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006892
Mel Gorman0abdee22011-01-13 15:46:22 -08006893 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006894 * Return the order kswapd stopped reclaiming at as
6895 * prepare_kswapd_sleep() takes it into account. If another caller
6896 * entered the allocator slow path while kswapd was awake, order will
6897 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006898 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006899 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006900}
6901
Mel Gormane716f2e2017-05-03 14:53:45 -07006902/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006903 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6904 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6905 * not a valid index then either kswapd runs for first time or kswapd couldn't
6906 * sleep after previous reclaim attempt (node is still unbalanced). In that
6907 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006908 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006909static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6910 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006911{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006912 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006913
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006914 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006915}
6916
Mel Gorman38087d92016-07-28 15:45:49 -07006917static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006918 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006919{
6920 long remaining = 0;
6921 DEFINE_WAIT(wait);
6922
6923 if (freezing(current) || kthread_should_stop())
6924 return;
6925
6926 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6927
Shantanu Goel333b0a42017-05-03 14:53:38 -07006928 /*
6929 * Try to sleep for a short interval. Note that kcompactd will only be
6930 * woken if it is possible to sleep for a short interval. This is
6931 * deliberate on the assumption that if reclaim cannot keep an
6932 * eligible zone balanced that it's also unlikely that compaction will
6933 * succeed.
6934 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006935 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006936 /*
6937 * Compaction records what page blocks it recently failed to
6938 * isolate pages from and skips them in the future scanning.
6939 * When kswapd is going to sleep, it is reasonable to assume
6940 * that pages and compaction may succeed so reset the cache.
6941 */
6942 reset_isolation_suitable(pgdat);
6943
6944 /*
6945 * We have freed the memory, now we should compact it to make
6946 * allocation of the requested order possible.
6947 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006948 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006949
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006950 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006951
6952 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006953 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006954 * order. The values will either be from a wakeup request or
6955 * the previous request that slept prematurely.
6956 */
6957 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006958 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6959 kswapd_highest_zoneidx(pgdat,
6960 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006961
6962 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6963 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006964 }
6965
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006966 finish_wait(&pgdat->kswapd_wait, &wait);
6967 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6968 }
6969
6970 /*
6971 * After a short sleep, check if it was a premature sleep. If not, then
6972 * go fully to sleep until explicitly woken up.
6973 */
Mel Gormand9f21d42016-07-28 15:46:41 -07006974 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006975 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006976 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6977
6978 /*
6979 * vmstat counters are not perfectly accurate and the estimated
6980 * value for counters such as NR_FREE_PAGES can deviate from the
6981 * true value by nr_online_cpus * threshold. To avoid the zone
6982 * watermarks being breached while under pressure, we reduce the
6983 * per-cpu vmstat threshold while kswapd is awake and restore
6984 * them before going back to sleep.
6985 */
6986 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07006987
6988 if (!kthread_should_stop())
6989 schedule();
6990
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006991 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
6992 } else {
6993 if (remaining)
6994 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
6995 else
6996 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
6997 }
6998 finish_wait(&pgdat->kswapd_wait, &wait);
6999}
7000
Linus Torvalds1da177e2005-04-16 15:20:36 -07007001/*
7002 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07007003 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007004 *
7005 * This basically trickles out pages so that we have _some_
7006 * free memory available even if there is no other activity
7007 * that frees anything up. This is needed for things like routing
7008 * etc, where we otherwise might have all activity going on in
7009 * asynchronous contexts that cannot page things out.
7010 *
7011 * If there are applications that are active memory-allocators
7012 * (most normal use), this basically shouldn't matter.
7013 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307014int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007015{
Mel Gormane716f2e2017-05-03 14:53:45 -07007016 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007017 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07007018 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007019 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10307020 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007021
Rusty Russell174596a2009-01-01 10:12:29 +10307022 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07007023 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007024
7025 /*
7026 * Tell the memory management that we're a "memory allocator",
7027 * and that if we need more memory we should get access to it
7028 * regardless (see "__alloc_pages()"). "kswapd" should
7029 * never get caught in the normal page freeing logic.
7030 *
7031 * (Kswapd normally doesn't need memory anyway, but sometimes
7032 * you need a small amount of memory in order to be able to
7033 * page out something else, and this flag essentially protects
7034 * us from recursively trying to free more memory as we're
7035 * trying to free the first piece of memory in the first place).
7036 */
Christoph Lameter930d9152006-01-08 01:00:47 -08007037 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07007038 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07007039
Qian Cai5644e1fb2020-04-01 21:10:12 -07007040 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007041 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007042 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08007043 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07007044
Qian Cai5644e1fb2020-04-01 21:10:12 -07007045 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007046 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7047 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07007048
Mel Gorman38087d92016-07-28 15:45:49 -07007049kswapd_try_sleep:
7050 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007051 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07007052
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007053 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08007054 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007055 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7056 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007057 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007058 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007059
David Rientjes8fe23e02009-12-14 17:58:33 -08007060 ret = try_to_freeze();
7061 if (kthread_should_stop())
7062 break;
7063
7064 /*
7065 * We can speed up thawing tasks if we don't call balance_pgdat
7066 * after returning from the refrigerator
7067 */
Mel Gorman38087d92016-07-28 15:45:49 -07007068 if (ret)
7069 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07007070
Mel Gorman38087d92016-07-28 15:45:49 -07007071 /*
7072 * Reclaim begins at the requested order but if a high-order
7073 * reclaim fails then kswapd falls back to reclaiming for
7074 * order-0. If that happens, kswapd will consider sleeping
7075 * for the order it finished reclaiming at (reclaim_order)
7076 * but kcompactd is woken to compact for the original
7077 * request (alloc_order).
7078 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007079 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007080 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007081 reclaim_order = balance_pgdat(pgdat, alloc_order,
7082 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007083 if (reclaim_order < alloc_order)
7084 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007085 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007086
Johannes Weiner71abdc12014-06-06 14:35:35 -07007087 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007088
Linus Torvalds1da177e2005-04-16 15:20:36 -07007089 return 0;
7090}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307091EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007092
7093/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007094 * A zone is low on free memory or too fragmented for high-order memory. If
7095 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7096 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7097 * has failed or is not needed, still wake up kcompactd if only compaction is
7098 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007099 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007100void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007101 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007102{
7103 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007104 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007105
Mel Gorman6aa303d2016-09-01 16:14:55 -07007106 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007107 return;
7108
David Rientjes5ecd9d42018-04-05 16:25:16 -07007109 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007110 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007111
Qian Cai5644e1fb2020-04-01 21:10:12 -07007112 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007113 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007114
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007115 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7116 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007117
7118 if (READ_ONCE(pgdat->kswapd_order) < order)
7119 WRITE_ONCE(pgdat->kswapd_order, order);
7120
Con Kolivas8d0986e2005-09-13 01:25:07 -07007121 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007122 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007123
David Rientjes5ecd9d42018-04-05 16:25:16 -07007124 /* Hopeless node, leave it to direct reclaim if possible */
7125 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007126 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7127 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007128 /*
7129 * There may be plenty of free memory available, but it's too
7130 * fragmented for high-order allocations. Wake up kcompactd
7131 * and rely on compaction_suitable() to determine if it's
7132 * needed. If it fails, it will defer subsequent attempts to
7133 * ratelimit its work.
7134 */
7135 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007136 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007137 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007138 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007139
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007140 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007141 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007142 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007143}
7144
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007145#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007146/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007147 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007148 * freed pages.
7149 *
7150 * Rather than trying to age LRUs the aim is to preserve the overall
7151 * LRU order by reclaiming preferentially
7152 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007153 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007154unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007155{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007156 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007157 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007158 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007159 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007160 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007161 .may_writepage = 1,
7162 .may_unmap = 1,
7163 .may_swap = 1,
7164 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007165 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007166 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007167 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007168 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007169
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007170 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007171 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007172 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007173
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007174 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007175
Andrew Morton1732d2b012019-07-16 16:26:15 -07007176 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007177 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007178 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007179
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007180 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007181}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007182#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007183
Yasunori Goto3218ae12006-06-27 02:53:33 -07007184/*
7185 * This kswapd start function will be called by init and node-hot-add.
7186 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7187 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007188void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007189{
7190 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307191 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007192
7193 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007194 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007195
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307196 trace_android_vh_kswapd_per_node(nid, &skip, true);
7197 if (skip)
7198 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007199 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7200 if (IS_ERR(pgdat->kswapd)) {
7201 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007202 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007203 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007204 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007205 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007206}
7207
David Rientjes8fe23e02009-12-14 17:58:33 -08007208/*
Jiang Liud8adde12012-07-11 14:01:52 -07007209 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007210 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007211 */
7212void kswapd_stop(int nid)
7213{
7214 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307215 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007216
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307217 trace_android_vh_kswapd_per_node(nid, &skip, false);
7218 if (skip)
7219 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007220 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007221 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007222 NODE_DATA(nid)->kswapd = NULL;
7223 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007224}
7225
Linus Torvalds1da177e2005-04-16 15:20:36 -07007226static int __init kswapd_init(void)
7227{
Wei Yang6b700b52020-04-01 21:10:09 -07007228 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007229
Linus Torvalds1da177e2005-04-16 15:20:36 -07007230 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007231 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007232 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007233 return 0;
7234}
7235
7236module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007237
7238#ifdef CONFIG_NUMA
7239/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007240 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007241 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007242 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007243 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007244 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007245int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007246
Dave Hansen51998362021-02-24 12:09:15 -08007247/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007248 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007249 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7250 * a zone.
7251 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007252#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007253
Christoph Lameter9eeff232006-01-18 17:42:31 -08007254/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007255 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007256 * occur.
7257 */
7258int sysctl_min_unmapped_ratio = 1;
7259
7260/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007261 * If the number of slab pages in a zone grows beyond this percentage then
7262 * slab reclaim needs to occur.
7263 */
7264int sysctl_min_slab_ratio = 5;
7265
Mel Gorman11fb9982016-07-28 15:46:20 -07007266static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007267{
Mel Gorman11fb9982016-07-28 15:46:20 -07007268 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7269 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7270 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007271
7272 /*
7273 * It's possible for there to be more file mapped pages than
7274 * accounted for by the pages on the file LRU lists because
7275 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7276 */
7277 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7278}
7279
7280/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007281static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007282{
Alexandru Moised031a152015-11-05 18:48:08 -08007283 unsigned long nr_pagecache_reclaimable;
7284 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007285
7286 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007287 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007288 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007289 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007290 * a better estimate
7291 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007292 if (node_reclaim_mode & RECLAIM_UNMAP)
7293 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007294 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007295 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007296
7297 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007298 if (!(node_reclaim_mode & RECLAIM_WRITE))
7299 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007300
7301 /* Watch for any possible underflows due to delta */
7302 if (unlikely(delta > nr_pagecache_reclaimable))
7303 delta = nr_pagecache_reclaimable;
7304
7305 return nr_pagecache_reclaimable - delta;
7306}
7307
Christoph Lameter0ff38492006-09-25 23:31:52 -07007308/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007309 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007310 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007311static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007312{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007313 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007314 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007315 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007316 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007317 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007318 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007319 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007320 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007321 .priority = NODE_RECLAIM_PRIORITY,
7322 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7323 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007324 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007325 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007326 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007327 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007328
Yafang Shao132bb8c2019-05-13 17:17:53 -07007329 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7330 sc.gfp_mask);
7331
Christoph Lameter9eeff232006-01-18 17:42:31 -08007332 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007333 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007334 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007335 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007336 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007337 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007338 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007339 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007340 noreclaim_flag = memalloc_noreclaim_save();
7341 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007342 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007343
Mel Gormana5f5f912016-07-28 15:46:32 -07007344 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007345 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007346 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007347 * priorities until we have enough memory freed.
7348 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007349 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007350 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007351 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007352 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007353
Andrew Morton1732d2b012019-07-16 16:26:15 -07007354 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007355 current->flags &= ~PF_SWAPWRITE;
7356 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007357 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007358 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007359
7360 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7361
Rik van Riela79311c2009-01-06 14:40:01 -08007362 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007363}
Andrew Morton179e9632006-03-22 00:08:18 -08007364
Mel Gormana5f5f912016-07-28 15:46:32 -07007365int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007366{
David Rientjesd773ed62007-10-16 23:26:01 -07007367 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007368
7369 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007370 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007371 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007372 *
Christoph Lameter96146342006-07-03 00:24:13 -07007373 * A small portion of unmapped file backed pages is needed for
7374 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007375 * thrown out if the node is overallocated. So we do not reclaim
7376 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007377 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007378 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007379 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007380 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7381 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007382 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007383
7384 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007385 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007386 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007387 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007388 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007389
7390 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007391 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007392 * have associated processors. This will favor the local processor
7393 * over remote processors and spread off node memory allocations
7394 * as wide as possible.
7395 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007396 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7397 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007398
Mel Gormana5f5f912016-07-28 15:46:32 -07007399 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7400 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007401
Mel Gormana5f5f912016-07-28 15:46:32 -07007402 ret = __node_reclaim(pgdat, gfp_mask, order);
7403 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007404
Mel Gorman24cf725182009-06-16 15:33:23 -07007405 if (!ret)
7406 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7407
David Rientjesd773ed62007-10-16 23:26:01 -07007408 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007409}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007410#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007411
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007412/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007413 * check_move_unevictable_pages - check pages for evictability and move to
7414 * appropriate zone lru list
7415 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007416 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007417 * Checks pages for evictability, if an evictable page is in the unevictable
7418 * lru list, moves it to the appropriate evictable lru list. This function
7419 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007420 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007421void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007422{
Alex Shi6168d0d2020-12-15 12:34:29 -08007423 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007424 int pgscanned = 0;
7425 int pgrescued = 0;
7426 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007427
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007428 for (i = 0; i < pvec->nr; i++) {
7429 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007430 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007431
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007432 if (PageTransTail(page))
7433 continue;
7434
7435 nr_pages = thp_nr_pages(page);
7436 pgscanned += nr_pages;
7437
Alex Shid25b5bd2020-12-15 12:34:16 -08007438 /* block memcg migration during page moving between lru */
7439 if (!TestClearPageLRU(page))
7440 continue;
7441
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007442 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007443 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007444 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007445 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007446 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007447 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007448 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007449 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007450 }
Hugh Dickins24513262012-01-20 14:34:21 -08007451
Alex Shi6168d0d2020-12-15 12:34:29 -08007452 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007453 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7454 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007455 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007456 } else if (pgscanned) {
7457 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007458 }
Hugh Dickins850465792012-01-20 14:34:19 -08007459}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007460EXPORT_SYMBOL_GPL(check_move_unevictable_pages);