blob: 717c94b4b1d5c35657350e9e7b76d1e58b5fce56 [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
Johannes Weiner645747462010-03-05 13:42:22 -08001270 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001271 /*
1272 * All mapped pages start out with page table
1273 * references from the instantiating fault, so we need
1274 * to look twice if a mapped file page is used more
1275 * than once.
1276 *
1277 * Mark it and spare it for another trip around the
1278 * inactive list. Another page table reference will
1279 * lead to its activation.
1280 *
1281 * Note: the mark is set for activated pages as well
1282 * so that recently deactivated but used pages are
1283 * quickly recovered.
1284 */
1285 SetPageReferenced(page);
1286
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001287 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001288 return PAGEREF_ACTIVATE;
1289
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001290 /*
1291 * Activate file-backed executable pages after first usage.
1292 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001293 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001294 return PAGEREF_ACTIVATE;
1295
Johannes Weiner645747462010-03-05 13:42:22 -08001296 return PAGEREF_KEEP;
1297 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001298
1299 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001300 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001301 return PAGEREF_RECLAIM_CLEAN;
1302
1303 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001304}
1305
Mel Gormane2be15f2013-07-03 15:01:57 -07001306/* Check if a page is dirty or under writeback */
1307static void page_check_dirty_writeback(struct page *page,
1308 bool *dirty, bool *writeback)
1309{
Mel Gormanb4597222013-07-03 15:02:05 -07001310 struct address_space *mapping;
1311
Mel Gormane2be15f2013-07-03 15:01:57 -07001312 /*
1313 * Anonymous pages are not handled by flushers and must be written
1314 * from reclaim context. Do not stall reclaim based on them
1315 */
Huang Ying9de4f222020-04-06 20:04:41 -07001316 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001317 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001318 *dirty = false;
1319 *writeback = false;
1320 return;
1321 }
1322
1323 /* By default assume that the page flags are accurate */
1324 *dirty = PageDirty(page);
1325 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001326
1327 /* Verify dirty/writeback state if the filesystem supports it */
1328 if (!page_has_private(page))
1329 return;
1330
1331 mapping = page_mapping(page);
1332 if (mapping && mapping->a_ops->is_dirty_writeback)
1333 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001334}
1335
Dave Hansen26aa2d12021-09-02 14:59:16 -07001336static struct page *alloc_demote_page(struct page *page, unsigned long node)
1337{
1338 struct migration_target_control mtc = {
1339 /*
1340 * Allocate from 'node', or fail quickly and quietly.
1341 * When this happens, 'page' will likely just be discarded
1342 * instead of migrated.
1343 */
1344 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1345 __GFP_THISNODE | __GFP_NOWARN |
1346 __GFP_NOMEMALLOC | GFP_NOWAIT,
1347 .nid = node
1348 };
1349
1350 return alloc_migration_target(page, (unsigned long)&mtc);
1351}
1352
1353/*
1354 * Take pages on @demote_list and attempt to demote them to
1355 * another node. Pages which are not demoted are left on
1356 * @demote_pages.
1357 */
1358static unsigned int demote_page_list(struct list_head *demote_pages,
1359 struct pglist_data *pgdat)
1360{
1361 int target_nid = next_demotion_node(pgdat->node_id);
1362 unsigned int nr_succeeded;
1363 int err;
1364
1365 if (list_empty(demote_pages))
1366 return 0;
1367
1368 if (target_nid == NUMA_NO_NODE)
1369 return 0;
1370
1371 /* Demotion ignores all cpuset and mempolicy settings */
1372 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1373 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1374 &nr_succeeded);
1375
Yang Shi668e4142021-09-02 14:59:19 -07001376 if (current_is_kswapd())
1377 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1378 else
1379 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1380
Dave Hansen26aa2d12021-09-02 14:59:16 -07001381 return nr_succeeded;
1382}
1383
Nick Piggine2867812008-07-25 19:45:30 -07001384/*
Andrew Morton1742f192006-03-22 00:08:21 -08001385 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001386 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001387static unsigned int shrink_page_list(struct list_head *page_list,
1388 struct pglist_data *pgdat,
1389 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001390 struct reclaim_stat *stat,
1391 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001392{
1393 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001394 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001395 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001396 unsigned int nr_reclaimed = 0;
1397 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001398 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001399
Kirill Tkhai060f0052019-03-05 15:48:15 -08001400 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001401 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001402 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001403
Dave Hansen26aa2d12021-09-02 14:59:16 -07001404retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001405 while (!list_empty(page_list)) {
1406 struct address_space *mapping;
1407 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001408 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001409 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001410 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001411
1412 cond_resched();
1413
1414 page = lru_to_page(page_list);
1415 list_del(&page->lru);
1416
Nick Piggin529ae9a2008-08-02 12:01:03 +02001417 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001418 goto keep;
1419
Sasha Levin309381fea2014-01-23 15:52:54 -08001420 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001421
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001422 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001423
1424 /* Account the number of base pages even though THP */
1425 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001426
Hugh Dickins39b5f292012-10-08 16:33:18 -07001427 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001428 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001429
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001430 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001431 goto keep_locked;
1432
Yu Zhao0182f922022-09-18 02:00:04 -06001433 /* page_update_gen() tried to promote this page? */
1434 if (lru_gen_enabled() && !ignore_references &&
1435 page_mapped(page) && PageReferenced(page))
1436 goto keep_locked;
1437
Andy Whitcroftc661b072007-08-22 14:01:26 -07001438 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1439 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1440
Mel Gorman283aba92013-07-03 15:01:51 -07001441 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001442 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001443 * reclaim_congested which affects wait_iff_congested. kswapd
1444 * will stall and start writing pages if the tail of the LRU
1445 * is all dirty unqueued pages.
1446 */
1447 page_check_dirty_writeback(page, &dirty, &writeback);
1448 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001449 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001450
1451 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001452 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001453
Mel Gormand04e8ac2013-07-03 15:02:03 -07001454 /*
1455 * Treat this page as congested if the underlying BDI is or if
1456 * pages are cycling through the LRU so quickly that the
1457 * pages marked for immediate reclaim are making it to the
1458 * end of the LRU a second time.
1459 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001460 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001461 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001462 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001463 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001464 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001465
1466 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001467 * If a page at the tail of the LRU is under writeback, there
1468 * are three cases to consider.
1469 *
1470 * 1) If reclaim is encountering an excessive number of pages
1471 * under writeback and this page is both under writeback and
1472 * PageReclaim then it indicates that pages are being queued
1473 * for IO but are being recycled through the LRU before the
1474 * IO can complete. Waiting on the page itself risks an
1475 * indefinite stall if it is impossible to writeback the
1476 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001477 * note that the LRU is being scanned too quickly and the
1478 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001479 *
Tejun Heo97c93412015-05-22 18:23:36 -04001480 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001481 * not marked for immediate reclaim, or the caller does not
1482 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1483 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001484 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001485 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001486 * Require may_enter_fs because we would wait on fs, which
1487 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001488 * enter reclaim, and deadlock if it waits on a page for
1489 * which it is needed to do the write (loop masks off
1490 * __GFP_IO|__GFP_FS for this reason); but more thought
1491 * would probably show more reasons.
1492 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001493 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001494 * PageReclaim. memcg does not have any dirty pages
1495 * throttling so we could easily OOM just because too many
1496 * pages are in writeback and there is nothing else to
1497 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001498 *
1499 * In cases 1) and 2) we activate the pages to get them out of
1500 * the way while we continue scanning for clean pages on the
1501 * inactive list and refilling from the active list. The
1502 * observation here is that waiting for disk writes is more
1503 * expensive than potentially causing reloads down the line.
1504 * Since they're marked for immediate reclaim, they won't put
1505 * memory pressure on the cache working set any longer than it
1506 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001507 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001508 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001509 /* Case 1 above */
1510 if (current_is_kswapd() &&
1511 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001512 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001513 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001514 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001515
1516 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001517 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001518 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001519 /*
1520 * This is slightly racy - end_page_writeback()
1521 * might have just cleared PageReclaim, then
1522 * setting PageReclaim here end up interpreted
1523 * as PageReadahead - but that does not matter
1524 * enough to care. What we do want is for this
1525 * page to have PageReclaim set next time memcg
1526 * reclaim reaches the tests above, so it will
1527 * then wait_on_page_writeback() to avoid OOM;
1528 * and it's also appropriate in global reclaim.
1529 */
1530 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001531 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001532 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001533
1534 /* Case 3 above */
1535 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001536 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001537 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001538 /* then go back and try same page again */
1539 list_add_tail(&page->lru, page_list);
1540 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001541 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001542 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001543
Minchan Kim8940b342019-09-25 16:49:11 -07001544 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001545 references = page_check_references(page, sc);
1546
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001547 switch (references) {
1548 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001549 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001550 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001551 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001552 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001553 case PAGEREF_RECLAIM:
1554 case PAGEREF_RECLAIM_CLEAN:
1555 ; /* try to reclaim the page below */
1556 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001557
Linus Torvalds1da177e2005-04-16 15:20:36 -07001558 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001559 * Before reclaiming the page, try to relocate
1560 * its contents to another node.
1561 */
1562 if (do_demote_pass &&
1563 (thp_migration_supported() || !PageTransHuge(page))) {
1564 list_add(&page->lru, &demote_pages);
1565 unlock_page(page);
1566 continue;
1567 }
1568
1569 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001570 * Anonymous process memory has backing store?
1571 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001572 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001573 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001574 if (PageAnon(page) && PageSwapBacked(page)) {
1575 if (!PageSwapCache(page)) {
1576 if (!(sc->gfp_mask & __GFP_IO))
1577 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001578 if (page_maybe_dma_pinned(page))
1579 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001580 if (PageTransHuge(page)) {
1581 /* cannot split THP, skip it */
1582 if (!can_split_huge_page(page, NULL))
1583 goto activate_locked;
1584 /*
1585 * Split pages without a PMD map right
1586 * away. Chances are some or all of the
1587 * tail pages can be freed without IO.
1588 */
1589 if (!compound_mapcount(page) &&
1590 split_huge_page_to_list(page,
1591 page_list))
1592 goto activate_locked;
1593 }
1594 if (!add_to_swap(page)) {
1595 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001596 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001597 /* Fallback to swap normal pages */
1598 if (split_huge_page_to_list(page,
1599 page_list))
1600 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001601#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1602 count_vm_event(THP_SWPOUT_FALLBACK);
1603#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001604 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001605 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001606 }
Minchan Kim0f074652017-07-06 15:37:24 -07001607
Kirill Tkhai4b793062020-04-01 21:10:18 -07001608 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001609
1610 /* Adding to swap updated mapping */
1611 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001612 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001613 } else if (unlikely(PageTransHuge(page))) {
1614 /* Split file THP */
1615 if (split_huge_page_to_list(page, page_list))
1616 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001617 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001618
1619 /*
Yang Shi98879b32019-07-11 20:59:30 -07001620 * THP may get split above, need minus tail pages and update
1621 * nr_pages to avoid accounting tail pages twice.
1622 *
1623 * The tail pages that are added into swap cache successfully
1624 * reach here.
1625 */
1626 if ((nr_pages > 1) && !PageTransHuge(page)) {
1627 sc->nr_scanned -= (nr_pages - 1);
1628 nr_pages = 1;
1629 }
1630
1631 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001632 * The page is mapped into the page tables of one or more
1633 * processes. Try to unmap it here.
1634 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001635 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001636 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001637 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001638
1639 if (unlikely(PageTransHuge(page)))
1640 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001641
Yang Shi1fb08ac2021-06-30 18:52:01 -07001642 try_to_unmap(page, flags);
1643 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001644 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001645 if (!was_swapbacked && PageSwapBacked(page))
1646 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001647 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001648 }
1649 }
1650
1651 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001652 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001653 * Only kswapd can writeback filesystem pages
1654 * to avoid risk of stack overflow. But avoid
1655 * injecting inefficient single-page IO into
1656 * flusher writeback as much as possible: only
1657 * write pages when we've encountered many
1658 * dirty pages, and when we've already scanned
1659 * the rest of the LRU for clean pages and see
1660 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001661 */
Huang Ying9de4f222020-04-06 20:04:41 -07001662 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001663 (!current_is_kswapd() || !PageReclaim(page) ||
1664 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001665 /*
1666 * Immediately reclaim when written back.
1667 * Similar in principal to deactivate_page()
1668 * except we already have the page isolated
1669 * and know it's dirty
1670 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001671 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001672 SetPageReclaim(page);
1673
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001674 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001675 }
1676
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001677 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001678 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001679 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001680 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001681 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001682 goto keep_locked;
1683
Mel Gormand950c942015-09-04 15:47:35 -07001684 /*
1685 * Page is dirty. Flush the TLB if a writable entry
1686 * potentially exists to avoid CPU writes after IO
1687 * starts and then write it out here.
1688 */
1689 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001690 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001691 case PAGE_KEEP:
1692 goto keep_locked;
1693 case PAGE_ACTIVATE:
1694 goto activate_locked;
1695 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001696 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001697
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001698 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001699 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001700 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001701 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001702
Linus Torvalds1da177e2005-04-16 15:20:36 -07001703 /*
1704 * A synchronous write - probably a ramdisk. Go
1705 * ahead and try to reclaim the page.
1706 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001707 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001708 goto keep;
1709 if (PageDirty(page) || PageWriteback(page))
1710 goto keep_locked;
1711 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001712 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001713 case PAGE_CLEAN:
1714 ; /* try to free the page below */
1715 }
1716 }
1717
1718 /*
1719 * If the page has buffers, try to free the buffer mappings
1720 * associated with this page. If we succeed we try to free
1721 * the page as well.
1722 *
1723 * We do this even if the page is PageDirty().
1724 * try_to_release_page() does not perform I/O, but it is
1725 * possible for a page to have PageDirty set, but it is actually
1726 * clean (all its buffers are clean). This happens if the
1727 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001728 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001729 * try_to_release_page() will discover that cleanness and will
1730 * drop the buffers and mark the page clean - it can be freed.
1731 *
1732 * Rarely, pages can have buffers and no ->mapping. These are
1733 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001734 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001735 * and if that worked, and the page is no longer mapped into
1736 * process address space (page_count == 1) it can be freed.
1737 * Otherwise, leave the page on the LRU so it is swappable.
1738 */
David Howells266cf652009-04-03 16:42:36 +01001739 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001740 if (!try_to_release_page(page, sc->gfp_mask))
1741 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001742 if (!mapping && page_count(page) == 1) {
1743 unlock_page(page);
1744 if (put_page_testzero(page))
1745 goto free_it;
1746 else {
1747 /*
1748 * rare race with speculative reference.
1749 * the speculative reference will free
1750 * this page shortly, so we may
1751 * increment nr_reclaimed here (and
1752 * leave it off the LRU).
1753 */
1754 nr_reclaimed++;
1755 continue;
1756 }
1757 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001758 }
1759
Shaohua Li802a3a92017-05-03 14:52:32 -07001760 if (PageAnon(page) && !PageSwapBacked(page)) {
1761 /* follow __remove_mapping for reference */
1762 if (!page_ref_freeze(page, 1))
1763 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001764 /*
1765 * The page has only one reference left, which is
1766 * from the isolation. After the caller puts the
1767 * page back on lru and drops the reference, the
1768 * page will be freed anyway. It doesn't matter
1769 * which lru it goes. So we don't bother checking
1770 * PageDirty here.
1771 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001772 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001773 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001774 } else if (!mapping || !__remove_mapping(mapping, page, true,
1775 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001776 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001777
1778 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001779free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001780 /*
1781 * THP may get swapped out in a whole, need account
1782 * all base pages.
1783 */
1784 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001785
1786 /*
1787 * Is there need to periodically free_page_list? It would
1788 * appear not as the counts should be low
1789 */
Yang Shi7ae88532019-09-23 15:38:09 -07001790 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001791 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001792 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001793 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001794 continue;
1795
Yang Shi98879b32019-07-11 20:59:30 -07001796activate_locked_split:
1797 /*
1798 * The tail pages that are failed to add into swap cache
1799 * reach here. Fixup nr_scanned and nr_pages.
1800 */
1801 if (nr_pages > 1) {
1802 sc->nr_scanned -= (nr_pages - 1);
1803 nr_pages = 1;
1804 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001805activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001806 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001807 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1808 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001809 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001810 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001811 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001812 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001813 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001814 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001815 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001816 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001817keep_locked:
1818 unlock_page(page);
1819keep:
1820 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001821 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001822 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001823 /* 'page_list' is always empty here */
1824
1825 /* Migrate pages selected for demotion */
1826 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1827 /* Pages that could not be demoted are still in @demote_pages */
1828 if (!list_empty(&demote_pages)) {
1829 /* Pages which failed to demoted go back on @page_list for retry: */
1830 list_splice_init(&demote_pages, page_list);
1831 do_demote_pass = false;
1832 goto retry;
1833 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001834
Yang Shi98879b32019-07-11 20:59:30 -07001835 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1836
Johannes Weiner747db952014-08-08 14:19:24 -07001837 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001838 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001839 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001840
Linus Torvalds1da177e2005-04-16 15:20:36 -07001841 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001842 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001843
Andrew Morton05ff5132006-03-22 00:08:20 -08001844 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001845}
1846
Maninder Singh730ec8c2020-06-03 16:01:18 -07001847unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001848 struct list_head *page_list)
1849{
1850 struct scan_control sc = {
1851 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001852 .may_unmap = 1,
1853 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001854 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001855 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001856 struct page *page, *next;
1857 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001858 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001859
1860 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001861 if (!PageHuge(page) && page_is_file_lru(page) &&
1862 !PageDirty(page) && !__PageMovable(page) &&
1863 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001864 ClearPageActive(page);
1865 list_move(&page->lru, &clean_pages);
1866 }
1867 }
1868
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001869 /*
1870 * We should be safe here since we are only dealing with file pages and
1871 * we are not kswapd and therefore cannot write dirty file pages. But
1872 * call memalloc_noreclaim_save() anyway, just in case these conditions
1873 * change in the future.
1874 */
1875 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001876 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001877 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001878 memalloc_noreclaim_restore(noreclaim_flag);
1879
Minchan Kim02c6de82012-10-08 16:31:55 -07001880 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001881 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1882 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001883 /*
1884 * Since lazyfree pages are isolated from file LRU from the beginning,
1885 * they will rotate back to anonymous LRU in the end if it failed to
1886 * discard so isolated count will be mismatched.
1887 * Compensate the isolated count for both LRU lists.
1888 */
1889 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1890 stat.nr_lazyfree_fail);
1891 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001892 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001893 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001894}
1895
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001896/*
1897 * Attempt to remove the specified page from its LRU. Only take this page
1898 * if it is of the appropriate PageActive status. Pages which are being
1899 * freed elsewhere are also ignored.
1900 *
1901 * page: page to consider
1902 * mode: one of the LRU isolation modes defined above
1903 *
Alex Shic2135f72021-02-24 12:08:01 -08001904 * returns true on success, false on failure.
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001905 */
Alex Shic2135f72021-02-24 12:08:01 -08001906bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001907{
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001908 /* Only take pages on the LRU. */
1909 if (!PageLRU(page))
Alex Shic2135f72021-02-24 12:08:01 -08001910 return false;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001911
Minchan Kime46a2872012-10-08 16:33:48 -07001912 /* Compaction should not handle unevictable pages but CMA can do so */
1913 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
Alex Shic2135f72021-02-24 12:08:01 -08001914 return false;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001915
Mel Gormanc8244932012-01-12 17:19:38 -08001916 /*
1917 * To minimise LRU disruption, the caller can indicate that it only
1918 * wants to isolate pages it will be able to operate on without
1919 * blocking - clean pages for the most part.
1920 *
Mel Gormanc8244932012-01-12 17:19:38 -08001921 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1922 * that it is possible to migrate without blocking
1923 */
Johannes Weiner1276ad62017-02-24 14:56:11 -08001924 if (mode & ISOLATE_ASYNC_MIGRATE) {
Mel Gormanc8244932012-01-12 17:19:38 -08001925 /* All the caller can do on PageWriteback is block */
1926 if (PageWriteback(page))
Alex Shic2135f72021-02-24 12:08:01 -08001927 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001928
1929 if (PageDirty(page)) {
1930 struct address_space *mapping;
Mel Gorman69d763f2018-01-31 16:19:52 -08001931 bool migrate_dirty;
Mel Gormanc8244932012-01-12 17:19:38 -08001932
Mel Gormanc8244932012-01-12 17:19:38 -08001933 /*
1934 * Only pages without mappings or that have a
1935 * ->migratepage callback are possible to migrate
Mel Gorman69d763f2018-01-31 16:19:52 -08001936 * without blocking. However, we can be racing with
1937 * truncation so it's necessary to lock the page
1938 * to stabilise the mapping as truncation holds
1939 * the page lock until after the page is removed
1940 * from the page cache.
Mel Gormanc8244932012-01-12 17:19:38 -08001941 */
Mel Gorman69d763f2018-01-31 16:19:52 -08001942 if (!trylock_page(page))
Alex Shic2135f72021-02-24 12:08:01 -08001943 return false;
Mel Gorman69d763f2018-01-31 16:19:52 -08001944
Mel Gormanc8244932012-01-12 17:19:38 -08001945 mapping = page_mapping(page);
Hugh Dickins145e1a72018-06-01 16:50:50 -07001946 migrate_dirty = !mapping || mapping->a_ops->migratepage;
Mel Gorman69d763f2018-01-31 16:19:52 -08001947 unlock_page(page);
1948 if (!migrate_dirty)
Alex Shic2135f72021-02-24 12:08:01 -08001949 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001950 }
1951 }
Minchan Kim39deaf82011-10-31 17:06:51 -07001952
Minchan Kimf80c0672011-10-31 17:06:55 -07001953 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
Alex Shic2135f72021-02-24 12:08:01 -08001954 return false;
Minchan Kimf80c0672011-10-31 17:06:55 -07001955
Alex Shic2135f72021-02-24 12:08:01 -08001956 return true;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001957}
1958
Mel Gorman7ee36a12016-07-28 15:47:17 -07001959/*
1960 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001961 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001962 */
1963static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001964 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001965{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001966 int zid;
1967
Mel Gorman7ee36a12016-07-28 15:47:17 -07001968 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1969 if (!nr_zone_taken[zid])
1970 continue;
1971
Wei Yanga892cb62020-06-03 16:01:12 -07001972 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001973 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001974
Mel Gorman7ee36a12016-07-28 15:47:17 -07001975}
1976
Mel Gormanf611fab2021-06-30 18:53:19 -07001977/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001978 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1979 *
1980 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001981 * shrink the lists perform better by taking out a batch of pages
1982 * and working on them outside the LRU lock.
1983 *
1984 * For pagecache intensive workloads, this function is the hottest
1985 * spot in the kernel (apart from copy_*_user functions).
1986 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001987 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001988 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001989 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001990 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001991 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001992 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001993 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001994 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001995 *
1996 * returns how many pages were moved onto *@dst.
1997 */
Andrew Morton69e05942006-03-22 00:08:19 -08001998static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001999 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07002000 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002001 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002002{
Hugh Dickins75b00af2012-05-29 15:07:09 -07002003 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08002004 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07002005 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002006 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07002007 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002008 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002009 LIST_HEAD(pages_skipped);
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002010 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002011
Yang Shi98879b32019-07-11 20:59:30 -07002012 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002013 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07002014 while (scan < nr_to_scan && !list_empty(src)) {
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002015 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002016
Linus Torvalds1da177e2005-04-16 15:20:36 -07002017 page = lru_to_page(src);
2018 prefetchw_prev_lru_page(page, src, flags);
2019
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002020 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002021 total_scan += nr_pages;
2022
Mel Gormanb2e18752016-07-28 15:45:37 -07002023 if (page_zonenum(page) > sc->reclaim_idx) {
2024 list_move(&page->lru, &pages_skipped);
Yang Shi98879b32019-07-11 20:59:30 -07002025 nr_skipped[page_zonenum(page)] += nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002026 continue;
2027 }
2028
Minchan Kim791b48b2017-05-12 15:47:06 -07002029 /*
2030 * Do not count skipped pages because that makes the function
2031 * return with no isolated pages if the LRU mostly contains
2032 * ineligible pages. This causes the VM to not reclaim any
2033 * pages, triggering a premature OOM.
Yang Shi98879b32019-07-11 20:59:30 -07002034 *
2035 * Account all tail pages of THP. This would not cause
2036 * premature OOM since __isolate_lru_page() returns -EBUSY
2037 * only when the page is being freed somewhere else.
Minchan Kim791b48b2017-05-12 15:47:06 -07002038 */
Yang Shi98879b32019-07-11 20:59:30 -07002039 scan += nr_pages;
Alex Shic2135f72021-02-24 12:08:01 -08002040 if (!__isolate_lru_page_prepare(page, mode)) {
2041 /* It is being freed elsewhere */
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002042 list_move(&page->lru, src);
Alex Shic2135f72021-02-24 12:08:01 -08002043 continue;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002044 }
Alex Shic2135f72021-02-24 12:08:01 -08002045 /*
2046 * Be careful not to clear PageLRU until after we're
2047 * sure the page is not being freed elsewhere -- the
2048 * page release code relies on it.
2049 */
2050 if (unlikely(!get_page_unless_zero(page))) {
2051 list_move(&page->lru, src);
2052 continue;
2053 }
2054
2055 if (!TestClearPageLRU(page)) {
2056 /* Another thread is already isolating this page */
2057 put_page(page);
2058 list_move(&page->lru, src);
2059 continue;
2060 }
2061
2062 nr_taken += nr_pages;
2063 nr_zone_taken[page_zonenum(page)] += nr_pages;
2064 list_move(&page->lru, dst);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002065 }
2066
Mel Gormanb2e18752016-07-28 15:45:37 -07002067 /*
2068 * Splice any skipped pages to the start of the LRU list. Note that
2069 * this disrupts the LRU order when reclaiming for lower zones but
2070 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2071 * scanning would soon rescan the same pages to skip and put the
2072 * system at risk of premature OOM.
2073 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002074 if (!list_empty(&pages_skipped)) {
2075 int zid;
2076
Johannes Weiner3db65812017-05-03 14:52:13 -07002077 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002078 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2079 if (!nr_skipped[zid])
2080 continue;
2081
2082 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002083 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002084 }
2085 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002086 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002087 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Minchan Kim791b48b2017-05-12 15:47:06 -07002088 total_scan, skipped, nr_taken, mode, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002089 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002090 return nr_taken;
2091}
2092
Nick Piggin62695a82008-10-18 20:26:09 -07002093/**
2094 * isolate_lru_page - tries to isolate a page from its LRU list
2095 * @page: page to isolate from its LRU list
2096 *
2097 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2098 * vmstat statistic corresponding to whatever LRU list the page was on.
2099 *
2100 * Returns 0 if the page was removed from an LRU list.
2101 * Returns -EBUSY if the page was not on an LRU list.
2102 *
2103 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002104 * the active list, it will have PageActive set. If it was found on
2105 * the unevictable list, it will have the PageUnevictable bit set. That flag
2106 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002107 *
2108 * The vmstat statistic corresponding to the list on which the page was
2109 * found will be decremented.
2110 *
2111 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002112 *
Nick Piggin62695a82008-10-18 20:26:09 -07002113 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002114 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002115 * without a stable reference).
2116 * (2) the lru_lock must not be held.
2117 * (3) interrupts must be enabled.
2118 */
2119int isolate_lru_page(struct page *page)
2120{
2121 int ret = -EBUSY;
2122
Sasha Levin309381fea2014-01-23 15:52:54 -08002123 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002124 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002125
Alex Shid25b5bd2020-12-15 12:34:16 -08002126 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002127 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002128
Alex Shid25b5bd2020-12-15 12:34:16 -08002129 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002130 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002131 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002132 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002133 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002134 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002135
Nick Piggin62695a82008-10-18 20:26:09 -07002136 return ret;
2137}
2138
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002139/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002140 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002141 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002142 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2143 * the LRU list will go small and be scanned faster than necessary, leading to
2144 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002145 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002146static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002147 struct scan_control *sc)
2148{
2149 unsigned long inactive, isolated;
2150
2151 if (current_is_kswapd())
2152 return 0;
2153
Johannes Weinerb5ead352019-11-30 17:55:40 -08002154 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002155 return 0;
2156
2157 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002158 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2159 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002160 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002161 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2162 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002163 }
2164
Fengguang Wu3cf23842012-12-18 14:23:31 -08002165 /*
2166 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2167 * won't get blocked by normal direct-reclaimers, forming a circular
2168 * deadlock.
2169 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002170 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002171 inactive >>= 3;
2172
Rik van Riel35cd7812009-09-21 17:01:38 -07002173 return isolated > inactive;
2174}
2175
Kirill Tkhaia222f342019-05-13 17:17:00 -07002176/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002177 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2178 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002179 *
2180 * Returns the number of pages moved to the given lruvec.
2181 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002182static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2183 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002184{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002185 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002186 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002187 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002188
Kirill Tkhaia222f342019-05-13 17:17:00 -07002189 while (!list_empty(list)) {
2190 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002191 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002192 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002193 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002194 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002195 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002196 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002197 continue;
2198 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002199
Alex Shi3d06afa2020-12-15 12:33:37 -08002200 /*
2201 * The SetPageLRU needs to be kept here for list integrity.
2202 * Otherwise:
2203 * #0 move_pages_to_lru #1 release_pages
2204 * if !put_page_testzero
2205 * if (put_page_testzero())
2206 * !PageLRU //skip lru_lock
2207 * SetPageLRU()
2208 * list_add(&page->lru,)
2209 * list_add(&page->lru,)
2210 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002211 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002212
Alex Shi3d06afa2020-12-15 12:33:37 -08002213 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002214 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002215
2216 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002217 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002218 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002219 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002220 } else
2221 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002222
2223 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002224 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002225
Alex Shiafca9152020-12-15 12:34:02 -08002226 /*
2227 * All pages were isolated from the same lruvec (and isolation
2228 * inhibits memcg migration).
2229 */
Muchun Song7467c392021-06-28 19:37:59 -07002230 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002231 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002232 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002233 nr_moved += nr_pages;
2234 if (PageActive(page))
2235 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002236 }
Mel Gorman66635622010-08-09 17:19:30 -07002237
Hugh Dickins3f797682012-01-12 17:20:07 -08002238 /*
2239 * To save our caller's stack, now use input list for pages to free.
2240 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002241 list_splice(&pages_to_free, list);
2242
2243 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002244}
2245
2246/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002247 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002248 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002249 * In that case we should only throttle if the backing device it is
2250 * writing to is congested. In other cases it is safe to throttle.
2251 */
2252static int current_may_throttle(void)
2253{
NeilBrowna37b0712020-06-01 21:48:18 -07002254 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002255 current->backing_dev_info == NULL ||
2256 bdi_write_congested(current->backing_dev_info);
2257}
2258
2259/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002260 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002261 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002262 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002263static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002264shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002265 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002266{
2267 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002268 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002269 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002270 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002271 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002272 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002273 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002274 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002275 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002276
Mel Gorman599d0c92016-07-28 15:45:31 -07002277 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002278 if (stalled)
2279 return 0;
2280
2281 /* wait a bit for the reclaimer. */
2282 msleep(100);
2283 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002284
2285 /* We are about to die and free our memory. Return now. */
2286 if (fatal_signal_pending(current))
2287 return SWAP_CLUSTER_MAX;
2288 }
2289
Linus Torvalds1da177e2005-04-16 15:20:36 -07002290 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002291
Alex Shi6168d0d2020-12-15 12:34:29 -08002292 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002293
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002294 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002295 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002296
Mel Gorman599d0c92016-07-28 15:45:31 -07002297 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002298 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002299 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002300 __count_vm_events(item, nr_scanned);
2301 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002302 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2303
Alex Shi6168d0d2020-12-15 12:34:29 -08002304 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002305
Hillf Dantond563c052012-03-21 16:34:02 -07002306 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002307 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002308
Shakeel Butt013339d2020-12-14 19:06:39 -08002309 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002310
Alex Shi6168d0d2020-12-15 12:34:29 -08002311 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002312 move_pages_to_lru(lruvec, &page_list);
2313
2314 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002315 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002316 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002317 __count_vm_events(item, nr_reclaimed);
2318 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002319 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002320 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002321
Alex Shi75cc3c92020-12-15 14:20:50 -08002322 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002323 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002324 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002325
Mel Gorman92df3a72011-10-31 17:07:56 -07002326 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002327 * If dirty pages are scanned that are not queued for IO, it
2328 * implies that flushers are not doing their job. This can
2329 * happen when memory pressure pushes dirty pages to the end of
2330 * the LRU before the dirty limits are breached and the dirty
2331 * data has expired. It can also happen when the proportion of
2332 * dirty pages grows not through writes but through memory
2333 * pressure reclaiming all the clean cache. And in some cases,
2334 * the flushers simply cannot keep up with the allocation
2335 * rate. Nudge the flusher threads in case they are asleep.
2336 */
2337 if (stat.nr_unqueued_dirty == nr_taken)
2338 wakeup_flusher_threads(WB_REASON_VMSCAN);
2339
Andrey Ryabinind108c772018-04-10 16:27:59 -07002340 sc->nr.dirty += stat.nr_dirty;
2341 sc->nr.congested += stat.nr_congested;
2342 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2343 sc->nr.writeback += stat.nr_writeback;
2344 sc->nr.immediate += stat.nr_immediate;
2345 sc->nr.taken += nr_taken;
2346 if (file)
2347 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002348
Mel Gorman599d0c92016-07-28 15:45:31 -07002349 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002350 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002351 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002352}
2353
Hugh Dickins15b44732020-12-15 14:21:31 -08002354/*
2355 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2356 *
2357 * We move them the other way if the page is referenced by one or more
2358 * processes.
2359 *
2360 * If the pages are mostly unmapped, the processing is fast and it is
2361 * appropriate to hold lru_lock across the whole operation. But if
2362 * the pages are mapped, the processing is slow (page_referenced()), so
2363 * we should drop lru_lock around each page. It's impossible to balance
2364 * this, so instead we remove the pages from the LRU while processing them.
2365 * It is safe to rely on PG_active against the non-LRU pages in here because
2366 * nobody will play with that bit on a non-LRU page.
2367 *
2368 * The downside is that we have to touch page->_refcount against each page.
2369 * But we had to alter page->flags anyway.
2370 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002371static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002372 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002373 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002374 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002375{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002376 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002377 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002378 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002379 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002380 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002381 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002382 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002383 unsigned nr_deactivate, nr_activate;
2384 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002385 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002386 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002387 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002388
2389 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002390
Alex Shi6168d0d2020-12-15 12:34:29 -08002391 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002392
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002393 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002394 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002395
Mel Gorman599d0c92016-07-28 15:45:31 -07002396 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002397
Shakeel Butt912c0572020-08-06 23:26:32 -07002398 if (!cgroup_reclaim(sc))
2399 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002400 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002401
Alex Shi6168d0d2020-12-15 12:34:29 -08002402 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002403
Linus Torvalds1da177e2005-04-16 15:20:36 -07002404 while (!list_empty(&l_hold)) {
2405 cond_resched();
2406 page = lru_to_page(&l_hold);
2407 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002408
Hugh Dickins39b5f292012-10-08 16:33:18 -07002409 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002410 putback_lru_page(page);
2411 continue;
2412 }
2413
Mel Gormancc715d92012-03-21 16:34:00 -07002414 if (unlikely(buffer_heads_over_limit)) {
2415 if (page_has_private(page) && trylock_page(page)) {
2416 if (page_has_private(page))
2417 try_to_release_page(page, 0);
2418 unlock_page(page);
2419 }
2420 }
2421
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002422 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2423 if (bypass)
2424 goto skip_page_referenced;
2425
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002426 if (page_referenced(page, 0, sc->target_mem_cgroup,
2427 &vm_flags)) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002428 /*
2429 * Identify referenced, file-backed active pages and
2430 * give them one more trip around the active list. So
2431 * that executable code get better chances to stay in
2432 * memory under moderate memory pressure. Anon pages
2433 * are not likely to be evicted by use-once streaming
2434 * IO, plus JVM can create lots of anon VM_EXEC pages,
2435 * so we ignore them here.
2436 */
Huang Ying9de4f222020-04-06 20:04:41 -07002437 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002438 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002439 list_add(&page->lru, &l_active);
2440 continue;
2441 }
2442 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002443skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002444 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002445 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002446 list_add(&page->lru, &l_inactive);
2447 }
2448
Andrew Mortonb5557492009-01-06 14:40:13 -08002449 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002450 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002451 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002452 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002453
Kirill Tkhaia222f342019-05-13 17:17:00 -07002454 nr_activate = move_pages_to_lru(lruvec, &l_active);
2455 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002456 /* Keep all free pages in l_active list */
2457 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002458
2459 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2460 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2461
Mel Gorman599d0c92016-07-28 15:45:31 -07002462 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002463 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002464
Kirill Tkhaif372d892019-05-13 17:16:57 -07002465 mem_cgroup_uncharge_list(&l_active);
2466 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002467 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2468 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002469}
2470
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002471unsigned long reclaim_pages(struct list_head *page_list)
2472{
Yang Shif661d002020-04-01 21:10:05 -07002473 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002474 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002475 LIST_HEAD(node_page_list);
2476 struct reclaim_stat dummy_stat;
2477 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002478 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002479 struct scan_control sc = {
2480 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002481 .may_writepage = 1,
2482 .may_unmap = 1,
2483 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002484 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002485 };
2486
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002487 noreclaim_flag = memalloc_noreclaim_save();
2488
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002489 while (!list_empty(page_list)) {
2490 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002491 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002492 nid = page_to_nid(page);
2493 INIT_LIST_HEAD(&node_page_list);
2494 }
2495
2496 if (nid == page_to_nid(page)) {
2497 ClearPageActive(page);
2498 list_move(&page->lru, &node_page_list);
2499 continue;
2500 }
2501
2502 nr_reclaimed += shrink_page_list(&node_page_list,
2503 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002504 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002505 while (!list_empty(&node_page_list)) {
2506 page = lru_to_page(&node_page_list);
2507 list_del(&page->lru);
2508 putback_lru_page(page);
2509 }
2510
Yang Shif661d002020-04-01 21:10:05 -07002511 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002512 }
2513
2514 if (!list_empty(&node_page_list)) {
2515 nr_reclaimed += shrink_page_list(&node_page_list,
2516 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002517 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002518 while (!list_empty(&node_page_list)) {
2519 page = lru_to_page(&node_page_list);
2520 list_del(&page->lru);
2521 putback_lru_page(page);
2522 }
2523 }
2524
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002525 memalloc_noreclaim_restore(noreclaim_flag);
2526
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002527 return nr_reclaimed;
2528}
2529
Johannes Weinerb91ac372019-11-30 17:56:02 -08002530static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2531 struct lruvec *lruvec, struct scan_control *sc)
2532{
2533 if (is_active_lru(lru)) {
2534 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2535 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2536 else
2537 sc->skipped_deactivate = 1;
2538 return 0;
2539 }
2540
2541 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2542}
2543
Rik van Riel59dc76b2016-05-20 16:56:31 -07002544/*
2545 * The inactive anon list should be small enough that the VM never has
2546 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002547 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002548 * The inactive file list should be small enough to leave most memory
2549 * to the established workingset on the scan-resistant active list,
2550 * but large enough to avoid thrashing the aggregate readahead window.
2551 *
2552 * Both inactive lists should also be large enough that each inactive
2553 * page has a chance to be referenced again before it is reclaimed.
2554 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002555 * If that fails and refaulting is observed, the inactive list grows.
2556 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002557 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002558 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002559 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2560 *
2561 * total target max
2562 * memory ratio inactive
2563 * -------------------------------------
2564 * 10MB 1 5MB
2565 * 100MB 1 50MB
2566 * 1GB 3 250MB
2567 * 10GB 10 0.9GB
2568 * 100GB 31 3GB
2569 * 1TB 101 10GB
2570 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002571 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002572static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002573{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002574 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002575 unsigned long inactive, active;
2576 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002577 unsigned long gb;
2578
Johannes Weinerb91ac372019-11-30 17:56:02 -08002579 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2580 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002581
Johannes Weinerb91ac372019-11-30 17:56:02 -08002582 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002583 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002584 inactive_ratio = int_sqrt(10 * gb);
2585 else
2586 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002587
Rik van Riel59dc76b2016-05-20 16:56:31 -07002588 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002589}
2590
Johannes Weiner9a265112013-02-22 16:32:17 -08002591enum scan_balance {
2592 SCAN_EQUAL,
2593 SCAN_FRACT,
2594 SCAN_ANON,
2595 SCAN_FILE,
2596};
2597
Yu Zhao6d313442022-09-18 02:00:00 -06002598static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2599{
2600 unsigned long file;
2601 struct lruvec *target_lruvec;
2602
Yu Zhao37397872022-09-18 02:00:03 -06002603 if (lru_gen_enabled())
2604 return;
2605
Yu Zhao6d313442022-09-18 02:00:00 -06002606 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2607
2608 /*
2609 * Flush the memory cgroup stats, so that we read accurate per-memcg
2610 * lruvec stats for heuristics.
2611 */
2612 mem_cgroup_flush_stats();
2613
2614 /*
2615 * Determine the scan balance between anon and file LRUs.
2616 */
2617 spin_lock_irq(&target_lruvec->lru_lock);
2618 sc->anon_cost = target_lruvec->anon_cost;
2619 sc->file_cost = target_lruvec->file_cost;
2620 spin_unlock_irq(&target_lruvec->lru_lock);
2621
2622 /*
2623 * Target desirable inactive:active list ratios for the anon
2624 * and file LRU lists.
2625 */
2626 if (!sc->force_deactivate) {
2627 unsigned long refaults;
2628
2629 refaults = lruvec_page_state(target_lruvec,
2630 WORKINGSET_ACTIVATE_ANON);
2631 if (refaults != target_lruvec->refaults[0] ||
2632 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2633 sc->may_deactivate |= DEACTIVATE_ANON;
2634 else
2635 sc->may_deactivate &= ~DEACTIVATE_ANON;
2636
2637 /*
2638 * When refaults are being observed, it means a new
2639 * workingset is being established. Deactivate to get
2640 * rid of any stale active pages quickly.
2641 */
2642 refaults = lruvec_page_state(target_lruvec,
2643 WORKINGSET_ACTIVATE_FILE);
2644 if (refaults != target_lruvec->refaults[1] ||
2645 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2646 sc->may_deactivate |= DEACTIVATE_FILE;
2647 else
2648 sc->may_deactivate &= ~DEACTIVATE_FILE;
2649 } else
2650 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2651
2652 /*
2653 * If we have plenty of inactive file pages that aren't
2654 * thrashing, try to reclaim those first before touching
2655 * anonymous pages.
2656 */
2657 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2658 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2659 sc->cache_trim_mode = 1;
2660 else
2661 sc->cache_trim_mode = 0;
2662
2663 /*
2664 * Prevent the reclaimer from falling into the cache trap: as
2665 * cache pages start out inactive, every cache fault will tip
2666 * the scan balance towards the file LRU. And as the file LRU
2667 * shrinks, so does the window for rotation from references.
2668 * This means we have a runaway feedback loop where a tiny
2669 * thrashing file LRU becomes infinitely more attractive than
2670 * anon pages. Try to detect this based on file LRU size.
2671 */
2672 if (!cgroup_reclaim(sc)) {
2673 unsigned long total_high_wmark = 0;
2674 unsigned long free, anon;
2675 int z;
2676
2677 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2678 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2679 node_page_state(pgdat, NR_INACTIVE_FILE);
2680
2681 for (z = 0; z < MAX_NR_ZONES; z++) {
2682 struct zone *zone = &pgdat->node_zones[z];
2683
2684 if (!managed_zone(zone))
2685 continue;
2686
2687 total_high_wmark += high_wmark_pages(zone);
2688 }
2689
2690 /*
2691 * Consider anon: if that's low too, this isn't a
2692 * runaway file reclaim problem, but rather just
2693 * extreme pressure. Reclaim as per usual then.
2694 */
2695 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2696
2697 sc->file_is_tiny =
2698 file + free <= total_high_wmark &&
2699 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2700 anon >> sc->priority;
2701 }
2702}
2703
Linus Torvalds1da177e2005-04-16 15:20:36 -07002704/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002705 * Determine how aggressively the anon and file LRU lists should be
2706 * scanned. The relative value of each set of LRU lists is determined
2707 * by looking at the fraction of the pages scanned we did rotate back
2708 * onto the active list instead of evict.
2709 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002710 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2711 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002712 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002713static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2714 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002715{
Keith Buscha2a36482021-09-02 14:59:26 -07002716 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002717 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002718 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002719 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002720 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002721 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002722 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002723 unsigned long ap, fp;
2724 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002725 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002726
2727 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002728 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002729 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002730 goto out;
2731 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002732
Johannes Weiner10316b32013-02-22 16:32:14 -08002733 /*
2734 * Global reclaim will swap to prevent OOM even with no
2735 * swappiness, but memcg users want to use this knob to
2736 * disable swapping for individual groups completely when
2737 * using the memory controller's swap limit feature would be
2738 * too expensive.
2739 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002740 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002741 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002742 goto out;
2743 }
2744
2745 /*
2746 * Do not apply any pressure balancing cleverness when the
2747 * system is close to OOM, scan both anon and file equally
2748 * (unless the swappiness setting disagrees with swapping).
2749 */
Johannes Weiner02695172014-08-06 16:06:17 -07002750 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002751 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002752 goto out;
2753 }
2754
Johannes Weiner11d16c22013-02-22 16:32:15 -08002755 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002756 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002757 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002758 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002759 scan_balance = SCAN_ANON;
2760 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002761 }
2762
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002763 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2764
Johannes Weiner62376252014-05-06 12:50:07 -07002765 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002766 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002767 * anything from the anonymous working right now. But when balancing
2768 * anon and page cache files for reclaim, allow swapping of anon pages
2769 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002770 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002771 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002772 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002773 goto out;
2774 }
2775
Johannes Weiner9a265112013-02-22 16:32:17 -08002776 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002777 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002778 * Calculate the pressure balance between anon and file pages.
2779 *
2780 * The amount of pressure we put on each LRU is inversely
2781 * proportional to the cost of reclaiming each list, as
2782 * determined by the share of pages that are refaulting, times
2783 * the relative IO cost of bringing back a swapped out
2784 * anonymous page vs reloading a filesystem page (swappiness).
2785 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002786 * Although we limit that influence to ensure no list gets
2787 * left behind completely: at least a third of the pressure is
2788 * applied, before swappiness.
2789 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002790 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002791 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002792 total_cost = sc->anon_cost + sc->file_cost;
2793 anon_cost = total_cost + sc->anon_cost;
2794 file_cost = total_cost + sc->file_cost;
2795 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002796
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002797 ap = swappiness * (total_cost + 1);
2798 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002799
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002800 fp = (200 - swappiness) * (total_cost + 1);
2801 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002802
Shaohua Li76a33fc2010-05-24 14:32:36 -07002803 fraction[0] = ap;
2804 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002805 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002806out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002807 for_each_evictable_lru(lru) {
2808 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002809 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002810 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002811 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002812
Chris Down9783aa92019-10-06 17:58:32 -07002813 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002814 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2815 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002816
Johannes Weinerf56ce412021-08-19 19:04:21 -07002817 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002818 /*
2819 * Scale a cgroup's reclaim pressure by proportioning
2820 * its current usage to its memory.low or memory.min
2821 * setting.
2822 *
2823 * This is important, as otherwise scanning aggression
2824 * becomes extremely binary -- from nothing as we
2825 * approach the memory protection threshold, to totally
2826 * nominal as we exceed it. This results in requiring
2827 * setting extremely liberal protection thresholds. It
2828 * also means we simply get no protection at all if we
2829 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002830 *
2831 * If there is any protection in place, we reduce scan
2832 * pressure by how much of the total memory used is
2833 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002834 *
Chris Down9de7ca42019-10-06 17:58:35 -07002835 * There is one special case: in the first reclaim pass,
2836 * we skip over all groups that are within their low
2837 * protection. If that fails to reclaim enough pages to
2838 * satisfy the reclaim goal, we come back and override
2839 * the best-effort low protection. However, we still
2840 * ideally want to honor how well-behaved groups are in
2841 * that case instead of simply punishing them all
2842 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002843 * memory they are using, reducing the scan pressure
2844 * again by how much of the total memory used is under
2845 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002846 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002847 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002848 unsigned long protection;
2849
2850 /* memory.low scaling, make sure we retry before OOM */
2851 if (!sc->memcg_low_reclaim && low > min) {
2852 protection = low;
2853 sc->memcg_low_skipped = 1;
2854 } else {
2855 protection = min;
2856 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002857
2858 /* Avoid TOCTOU with earlier protection check */
2859 cgroup_size = max(cgroup_size, protection);
2860
2861 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002862 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002863
2864 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002865 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002866 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002867 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002868 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002869 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002870 } else {
2871 scan = lruvec_size;
2872 }
2873
2874 scan >>= sc->priority;
2875
Johannes Weiner688035f2017-05-03 14:52:07 -07002876 /*
2877 * If the cgroup's already been deleted, make sure to
2878 * scrape out the remaining cache.
2879 */
2880 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002881 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002882
Johannes Weiner688035f2017-05-03 14:52:07 -07002883 switch (scan_balance) {
2884 case SCAN_EQUAL:
2885 /* Scan lists relative to size */
2886 break;
2887 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002888 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002889 * Scan types proportional to swappiness and
2890 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002891 * Make sure we don't miss the last page on
2892 * the offlined memory cgroups because of a
2893 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002894 */
Gavin Shan76073c62020-02-20 20:04:24 -08002895 scan = mem_cgroup_online(memcg) ?
2896 div64_u64(scan * fraction[file], denominator) :
2897 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002898 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002899 break;
2900 case SCAN_FILE:
2901 case SCAN_ANON:
2902 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002903 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002904 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002905 break;
2906 default:
2907 /* Look ma, no brain */
2908 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002909 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002910
Johannes Weiner688035f2017-05-03 14:52:07 -07002911 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002912 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002913}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002914
Dave Hansen2f368a92021-09-02 14:59:23 -07002915/*
2916 * Anonymous LRU management is a waste if there is
2917 * ultimately no way to reclaim the memory.
2918 */
2919static bool can_age_anon_pages(struct pglist_data *pgdat,
2920 struct scan_control *sc)
2921{
2922 /* Aging the anon LRU is valuable if swap is present: */
2923 if (total_swap_pages > 0)
2924 return true;
2925
2926 /* Also valuable if anon pages can be demoted: */
2927 return can_demote(pgdat->node_id, sc);
2928}
2929
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002930#ifdef CONFIG_LRU_GEN
2931
Yu Zhaobaeb9a02022-09-18 02:00:07 -06002932#ifdef CONFIG_LRU_GEN_ENABLED
2933DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2934#define get_cap(cap) static_branch_likely(&lru_gen_caps[cap])
2935#else
2936DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2937#define get_cap(cap) static_branch_unlikely(&lru_gen_caps[cap])
2938#endif
2939
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002940/******************************************************************************
2941 * shorthand helpers
2942 ******************************************************************************/
2943
Yu Zhao37397872022-09-18 02:00:03 -06002944#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2945
2946#define DEFINE_MAX_SEQ(lruvec) \
2947 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2948
2949#define DEFINE_MIN_SEQ(lruvec) \
2950 unsigned long min_seq[ANON_AND_FILE] = { \
2951 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2952 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2953 }
2954
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002955#define for_each_gen_type_zone(gen, type, zone) \
2956 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2957 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2958 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2959
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002960static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002961{
2962 struct pglist_data *pgdat = NODE_DATA(nid);
2963
2964#ifdef CONFIG_MEMCG
2965 if (memcg) {
2966 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2967
2968 /* for hotadd_new_pgdat() */
2969 if (!lruvec->pgdat)
2970 lruvec->pgdat = pgdat;
2971
2972 return lruvec;
2973 }
2974#endif
2975 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2976
2977 return pgdat ? &pgdat->__lruvec : NULL;
2978}
2979
Yu Zhao37397872022-09-18 02:00:03 -06002980static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2981{
2982 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2983 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2984
2985 if (!can_demote(pgdat->node_id, sc) &&
2986 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2987 return 0;
2988
2989 return mem_cgroup_swappiness(memcg);
2990}
2991
2992static int get_nr_gens(struct lruvec *lruvec, int type)
2993{
2994 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2995}
2996
2997static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2998{
2999 /* see the comment on lru_gen_struct */
3000 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3001 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3002 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3003}
3004
3005/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003006 * mm_struct list
3007 ******************************************************************************/
3008
3009static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3010{
3011 static struct lru_gen_mm_list mm_list = {
3012 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3013 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3014 };
3015
3016#ifdef CONFIG_MEMCG
3017 if (memcg)
3018 return &memcg->mm_list;
3019#endif
3020 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3021
3022 return &mm_list;
3023}
3024
3025void lru_gen_add_mm(struct mm_struct *mm)
3026{
3027 int nid;
3028 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3029 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3030
3031 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3032#ifdef CONFIG_MEMCG
3033 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3034 mm->lru_gen.memcg = memcg;
3035#endif
3036 spin_lock(&mm_list->lock);
3037
3038 for_each_node_state(nid, N_MEMORY) {
3039 struct lruvec *lruvec = get_lruvec(memcg, nid);
3040
3041 if (!lruvec)
3042 continue;
3043
3044 /* the first addition since the last iteration */
3045 if (lruvec->mm_state.tail == &mm_list->fifo)
3046 lruvec->mm_state.tail = &mm->lru_gen.list;
3047 }
3048
3049 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3050
3051 spin_unlock(&mm_list->lock);
3052}
3053
3054void lru_gen_del_mm(struct mm_struct *mm)
3055{
3056 int nid;
3057 struct lru_gen_mm_list *mm_list;
3058 struct mem_cgroup *memcg = NULL;
3059
3060 if (list_empty(&mm->lru_gen.list))
3061 return;
3062
3063#ifdef CONFIG_MEMCG
3064 memcg = mm->lru_gen.memcg;
3065#endif
3066 mm_list = get_mm_list(memcg);
3067
3068 spin_lock(&mm_list->lock);
3069
3070 for_each_node(nid) {
3071 struct lruvec *lruvec = get_lruvec(memcg, nid);
3072
3073 if (!lruvec)
3074 continue;
3075
3076 /* where the last iteration ended (exclusive) */
3077 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3078 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3079
3080 /* where the current iteration continues (inclusive) */
3081 if (lruvec->mm_state.head != &mm->lru_gen.list)
3082 continue;
3083
3084 lruvec->mm_state.head = lruvec->mm_state.head->next;
3085 /* the deletion ends the current iteration */
3086 if (lruvec->mm_state.head == &mm_list->fifo)
3087 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3088 }
3089
3090 list_del_init(&mm->lru_gen.list);
3091
3092 spin_unlock(&mm_list->lock);
3093
3094#ifdef CONFIG_MEMCG
3095 mem_cgroup_put(mm->lru_gen.memcg);
3096 mm->lru_gen.memcg = NULL;
3097#endif
3098}
3099
3100#ifdef CONFIG_MEMCG
3101void lru_gen_migrate_mm(struct mm_struct *mm)
3102{
3103 struct mem_cgroup *memcg;
3104 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3105
3106 VM_WARN_ON_ONCE(task->mm != mm);
3107 lockdep_assert_held(&task->alloc_lock);
3108
3109 /* for mm_update_next_owner() */
3110 if (mem_cgroup_disabled())
3111 return;
3112
3113 rcu_read_lock();
3114 memcg = mem_cgroup_from_task(task);
3115 rcu_read_unlock();
3116 if (memcg == mm->lru_gen.memcg)
3117 return;
3118
3119 VM_WARN_ON_ONCE(!mm->lru_gen.memcg);
3120 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3121
3122 lru_gen_del_mm(mm);
3123 lru_gen_add_mm(mm);
3124}
3125#endif
3126
3127/*
3128 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3129 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3130 * bits in a bitmap, k is the number of hash functions and n is the number of
3131 * inserted items.
3132 *
3133 * Page table walkers use one of the two filters to reduce their search space.
3134 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3135 * aging uses the double-buffering technique to flip to the other filter each
3136 * time it produces a new generation. For non-leaf entries that have enough
3137 * leaf entries, the aging carries them over to the next generation in
3138 * walk_pmd_range(); the eviction also report them when walking the rmap
3139 * in lru_gen_look_around().
3140 *
3141 * For future optimizations:
3142 * 1. It's not necessary to keep both filters all the time. The spare one can be
3143 * freed after the RCU grace period and reallocated if needed again.
3144 * 2. And when reallocating, it's worth scaling its size according to the number
3145 * of inserted entries in the other filter, to reduce the memory overhead on
3146 * small systems and false positives on large systems.
3147 * 3. Jenkins' hash function is an alternative to Knuth's.
3148 */
3149#define BLOOM_FILTER_SHIFT 15
3150
3151static inline int filter_gen_from_seq(unsigned long seq)
3152{
3153 return seq % NR_BLOOM_FILTERS;
3154}
3155
3156static void get_item_key(void *item, int *key)
3157{
3158 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3159
3160 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3161
3162 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3163 key[1] = hash >> BLOOM_FILTER_SHIFT;
3164}
3165
3166static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3167{
3168 unsigned long *filter;
3169 int gen = filter_gen_from_seq(seq);
3170
3171 filter = lruvec->mm_state.filters[gen];
3172 if (filter) {
3173 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3174 return;
3175 }
3176
3177 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3178 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3179 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3180}
3181
3182static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3183{
3184 int key[2];
3185 unsigned long *filter;
3186 int gen = filter_gen_from_seq(seq);
3187
3188 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3189 if (!filter)
3190 return;
3191
3192 get_item_key(item, key);
3193
3194 if (!test_bit(key[0], filter))
3195 set_bit(key[0], filter);
3196 if (!test_bit(key[1], filter))
3197 set_bit(key[1], filter);
3198}
3199
3200static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3201{
3202 int key[2];
3203 unsigned long *filter;
3204 int gen = filter_gen_from_seq(seq);
3205
3206 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3207 if (!filter)
3208 return true;
3209
3210 get_item_key(item, key);
3211
3212 return test_bit(key[0], filter) && test_bit(key[1], filter);
3213}
3214
3215static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3216{
3217 int i;
3218 int hist;
3219
3220 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3221
3222 if (walk) {
3223 hist = lru_hist_from_seq(walk->max_seq);
3224
3225 for (i = 0; i < NR_MM_STATS; i++) {
3226 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3227 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3228 walk->mm_stats[i] = 0;
3229 }
3230 }
3231
3232 if (NR_HIST_GENS > 1 && last) {
3233 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3234
3235 for (i = 0; i < NR_MM_STATS; i++)
3236 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3237 }
3238}
3239
3240static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3241{
3242 int type;
3243 unsigned long size = 0;
3244 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3245 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3246
3247 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3248 return true;
3249
3250 clear_bit(key, &mm->lru_gen.bitmap);
3251
3252 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3253 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3254 get_mm_counter(mm, MM_ANONPAGES) +
3255 get_mm_counter(mm, MM_SHMEMPAGES);
3256 }
3257
3258 if (size < MIN_LRU_BATCH)
3259 return true;
3260
3261 return !mmget_not_zero(mm);
3262}
3263
3264static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3265 struct mm_struct **iter)
3266{
3267 bool first = false;
3268 bool last = true;
3269 struct mm_struct *mm = NULL;
3270 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3271 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3272 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3273
3274 /*
3275 * There are four interesting cases for this page table walker:
3276 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3277 * there is nothing left to do.
3278 * 2. It's the first of the current generation, and it needs to reset
3279 * the Bloom filter for the next generation.
3280 * 3. It reaches the end of mm_list, and it needs to increment
3281 * mm_state->seq; the iteration is done.
3282 * 4. It's the last of the current generation, and it needs to reset the
3283 * mm stats counters for the next generation.
3284 */
3285 spin_lock(&mm_list->lock);
3286
3287 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3288 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3289 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3290
3291 if (walk->max_seq <= mm_state->seq) {
3292 if (!*iter)
3293 last = false;
3294 goto done;
3295 }
3296
3297 if (!mm_state->nr_walkers) {
3298 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3299
3300 mm_state->head = mm_list->fifo.next;
3301 first = true;
3302 }
3303
3304 while (!mm && mm_state->head != &mm_list->fifo) {
3305 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3306
3307 mm_state->head = mm_state->head->next;
3308
3309 /* force scan for those added after the last iteration */
3310 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3311 mm_state->tail = mm_state->head;
3312 walk->force_scan = true;
3313 }
3314
3315 if (should_skip_mm(mm, walk))
3316 mm = NULL;
3317 }
3318
3319 if (mm_state->head == &mm_list->fifo)
3320 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3321done:
3322 if (*iter && !mm)
3323 mm_state->nr_walkers--;
3324 if (!*iter && mm)
3325 mm_state->nr_walkers++;
3326
3327 if (mm_state->nr_walkers)
3328 last = false;
3329
3330 if (*iter || last)
3331 reset_mm_stats(lruvec, walk, last);
3332
3333 spin_unlock(&mm_list->lock);
3334
3335 if (mm && first)
3336 reset_bloom_filter(lruvec, walk->max_seq + 1);
3337
3338 if (*iter)
3339 mmput_async(*iter);
3340
3341 *iter = mm;
3342
3343 return last;
3344}
3345
3346static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3347{
3348 bool success = false;
3349 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3350 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3351 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3352
3353 spin_lock(&mm_list->lock);
3354
3355 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3356
3357 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3358 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3359
3360 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3361 reset_mm_stats(lruvec, NULL, true);
3362 success = true;
3363 }
3364
3365 spin_unlock(&mm_list->lock);
3366
3367 return success;
3368}
3369
3370/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003371 * refault feedback loop
3372 ******************************************************************************/
3373
3374/*
3375 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3376 *
3377 * The P term is refaulted/(evicted+protected) from a tier in the generation
3378 * currently being evicted; the I term is the exponential moving average of the
3379 * P term over the generations previously evicted, using the smoothing factor
3380 * 1/2; the D term isn't supported.
3381 *
3382 * The setpoint (SP) is always the first tier of one type; the process variable
3383 * (PV) is either any tier of the other type or any other tier of the same
3384 * type.
3385 *
3386 * The error is the difference between the SP and the PV; the correction is to
3387 * turn off protection when SP>PV or turn on protection when SP<PV.
3388 *
3389 * For future optimizations:
3390 * 1. The D term may discount the other two terms over time so that long-lived
3391 * generations can resist stale information.
3392 */
3393struct ctrl_pos {
3394 unsigned long refaulted;
3395 unsigned long total;
3396 int gain;
3397};
3398
3399static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3400 struct ctrl_pos *pos)
3401{
3402 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3403 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3404
3405 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3406 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3407 pos->total = lrugen->avg_total[type][tier] +
3408 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3409 if (tier)
3410 pos->total += lrugen->protected[hist][type][tier - 1];
3411 pos->gain = gain;
3412}
3413
3414static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3415{
3416 int hist, tier;
3417 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3418 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3419 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3420
3421 lockdep_assert_held(&lruvec->lru_lock);
3422
3423 if (!carryover && !clear)
3424 return;
3425
3426 hist = lru_hist_from_seq(seq);
3427
3428 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3429 if (carryover) {
3430 unsigned long sum;
3431
3432 sum = lrugen->avg_refaulted[type][tier] +
3433 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3434 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3435
3436 sum = lrugen->avg_total[type][tier] +
3437 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3438 if (tier)
3439 sum += lrugen->protected[hist][type][tier - 1];
3440 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3441 }
3442
3443 if (clear) {
3444 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3445 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3446 if (tier)
3447 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3448 }
3449 }
3450}
3451
3452static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3453{
3454 /*
3455 * Return true if the PV has a limited number of refaults or a lower
3456 * refaulted/total than the SP.
3457 */
3458 return pv->refaulted < MIN_LRU_BATCH ||
3459 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3460 (sp->refaulted + 1) * pv->total * pv->gain;
3461}
3462
3463/******************************************************************************
3464 * the aging
3465 ******************************************************************************/
3466
Yu Zhao0182f922022-09-18 02:00:04 -06003467/* promote pages accessed through page tables */
3468static int page_update_gen(struct page *page, int gen)
3469{
3470 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3471
3472 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3473 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3474
3475 do {
3476 /* lru_gen_del_page() has isolated this page? */
3477 if (!(old_flags & LRU_GEN_MASK)) {
3478 /* for shrink_page_list() */
3479 new_flags = old_flags | BIT(PG_referenced);
3480 continue;
3481 }
3482
3483 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3484 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3485 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3486
3487 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3488}
3489
Yu Zhao37397872022-09-18 02:00:03 -06003490/* protect pages accessed multiple times through file descriptors */
3491static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3492{
3493 int type = page_is_file_lru(page);
3494 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3495 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3496 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3497
3498 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3499
3500 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003501 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3502 /* page_update_gen() has promoted this page? */
3503 if (new_gen >= 0 && new_gen != old_gen)
3504 return new_gen;
3505
Yu Zhao37397872022-09-18 02:00:03 -06003506 new_gen = (old_gen + 1) % MAX_NR_GENS;
3507
3508 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3509 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3510 /* for end_page_writeback() */
3511 if (reclaiming)
3512 new_flags |= BIT(PG_reclaim);
3513 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3514
3515 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3516
3517 return new_gen;
3518}
3519
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003520static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3521 int old_gen, int new_gen)
3522{
3523 int type = page_is_file_lru(page);
3524 int zone = page_zonenum(page);
3525 int delta = thp_nr_pages(page);
3526
3527 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3528 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3529
3530 walk->batched++;
3531
3532 walk->nr_pages[old_gen][type][zone] -= delta;
3533 walk->nr_pages[new_gen][type][zone] += delta;
3534}
3535
3536static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3537{
3538 int gen, type, zone;
3539 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3540
3541 walk->batched = 0;
3542
3543 for_each_gen_type_zone(gen, type, zone) {
3544 enum lru_list lru = type * LRU_INACTIVE_FILE;
3545 int delta = walk->nr_pages[gen][type][zone];
3546
3547 if (!delta)
3548 continue;
3549
3550 walk->nr_pages[gen][type][zone] = 0;
3551 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3552 lrugen->nr_pages[gen][type][zone] + delta);
3553
3554 if (lru_gen_is_active(lruvec, gen))
3555 lru += LRU_ACTIVE;
3556 __update_lru_size(lruvec, lru, zone, delta);
3557 }
3558}
3559
3560static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3561{
3562 struct address_space *mapping;
3563 struct vm_area_struct *vma = args->vma;
3564 struct lru_gen_mm_walk *walk = args->private;
3565
3566 if (!vma_is_accessible(vma))
3567 return true;
3568
3569 if (is_vm_hugetlb_page(vma))
3570 return true;
3571
3572 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3573 return true;
3574
3575 if (vma == get_gate_vma(vma->vm_mm))
3576 return true;
3577
3578 if (vma_is_anonymous(vma))
3579 return !walk->can_swap;
3580
3581 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3582 return true;
3583
3584 mapping = vma->vm_file->f_mapping;
3585 if (mapping_unevictable(mapping))
3586 return true;
3587
3588 if (shmem_mapping(mapping))
3589 return !walk->can_swap;
3590
3591 /* to exclude special mappings like dax, etc. */
3592 return !mapping->a_ops->readpage;
3593}
3594
3595/*
3596 * Some userspace memory allocators map many single-page VMAs. Instead of
3597 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3598 * table to reduce zigzags and improve cache performance.
3599 */
3600static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3601 unsigned long *vm_start, unsigned long *vm_end)
3602{
3603 unsigned long start = round_up(*vm_end, size);
3604 unsigned long end = (start | ~mask) + 1;
3605
3606 VM_WARN_ON_ONCE(mask & size);
3607 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3608
3609 while (args->vma) {
3610 if (start >= args->vma->vm_end) {
3611 args->vma = args->vma->vm_next;
3612 continue;
3613 }
3614
3615 if (end && end <= args->vma->vm_start)
3616 return false;
3617
3618 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3619 args->vma = args->vma->vm_next;
3620 continue;
3621 }
3622
3623 *vm_start = max(start, args->vma->vm_start);
3624 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3625
3626 return true;
3627 }
3628
3629 return false;
3630}
3631
Yu Zhao0182f922022-09-18 02:00:04 -06003632static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3633{
3634 unsigned long pfn = pte_pfn(pte);
3635
3636 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3637
3638 if (!pte_present(pte) || is_zero_pfn(pfn))
3639 return -1;
3640
3641 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3642 return -1;
3643
3644 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3645 return -1;
3646
3647 return pfn;
3648}
3649
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003650#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3651static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3652{
3653 unsigned long pfn = pmd_pfn(pmd);
3654
3655 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3656
3657 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3658 return -1;
3659
3660 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3661 return -1;
3662
3663 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3664 return -1;
3665
3666 return pfn;
3667}
3668#endif
3669
Yu Zhao0182f922022-09-18 02:00:04 -06003670static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003671 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003672{
3673 struct page *page;
3674
3675 /* try to avoid unnecessary memory loads */
3676 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3677 return NULL;
3678
3679 page = compound_head(pfn_to_page(pfn));
3680 if (page_to_nid(page) != pgdat->node_id)
3681 return NULL;
3682
3683 if (page_memcg_rcu(page) != memcg)
3684 return NULL;
3685
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003686 /* file VMAs can contain anon pages from COW */
3687 if (!page_is_file_lru(page) && !can_swap)
3688 return NULL;
3689
Yu Zhao0182f922022-09-18 02:00:04 -06003690 return page;
3691}
3692
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003693static bool suitable_to_scan(int total, int young)
3694{
3695 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3696
3697 /* suitable if the average number of young PTEs per cacheline is >=1 */
3698 return young * n >= total;
3699}
3700
3701static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3702 struct mm_walk *args)
3703{
3704 int i;
3705 pte_t *pte;
3706 spinlock_t *ptl;
3707 unsigned long addr;
3708 int total = 0;
3709 int young = 0;
3710 struct lru_gen_mm_walk *walk = args->private;
3711 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3712 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3713 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3714
3715 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3716
3717 ptl = pte_lockptr(args->mm, pmd);
3718 if (!spin_trylock(ptl))
3719 return false;
3720
3721 arch_enter_lazy_mmu_mode();
3722
3723 pte = pte_offset_map(pmd, start & PMD_MASK);
3724restart:
3725 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3726 unsigned long pfn;
3727 struct page *page;
3728
3729 total++;
3730 walk->mm_stats[MM_LEAF_TOTAL]++;
3731
3732 pfn = get_pte_pfn(pte[i], args->vma, addr);
3733 if (pfn == -1)
3734 continue;
3735
3736 if (!pte_young(pte[i])) {
3737 walk->mm_stats[MM_LEAF_OLD]++;
3738 continue;
3739 }
3740
3741 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3742 if (!page)
3743 continue;
3744
3745 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3746 VM_WARN_ON_ONCE(true);
3747
3748 young++;
3749 walk->mm_stats[MM_LEAF_YOUNG]++;
3750
3751 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3752 !(PageAnon(page) && PageSwapBacked(page) &&
3753 !PageSwapCache(page)))
3754 set_page_dirty(page);
3755
3756 old_gen = page_update_gen(page, new_gen);
3757 if (old_gen >= 0 && old_gen != new_gen)
3758 update_batch_size(walk, page, old_gen, new_gen);
3759 }
3760
3761 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3762 goto restart;
3763
3764 pte_unmap(pte);
3765
3766 arch_leave_lazy_mmu_mode();
3767 spin_unlock(ptl);
3768
3769 return suitable_to_scan(total, young);
3770}
3771
3772#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3773static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3774 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3775{
3776 int i;
3777 pmd_t *pmd;
3778 spinlock_t *ptl;
3779 struct lru_gen_mm_walk *walk = args->private;
3780 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3781 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3782 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3783
3784 VM_WARN_ON_ONCE(pud_leaf(*pud));
3785
3786 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3787 if (*start == -1) {
3788 *start = next;
3789 return;
3790 }
3791
3792 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3793 if (i && i <= MIN_LRU_BATCH) {
3794 __set_bit(i - 1, bitmap);
3795 return;
3796 }
3797
3798 pmd = pmd_offset(pud, *start);
3799
3800 ptl = pmd_lockptr(args->mm, pmd);
3801 if (!spin_trylock(ptl))
3802 goto done;
3803
3804 arch_enter_lazy_mmu_mode();
3805
3806 do {
3807 unsigned long pfn;
3808 struct page *page;
3809 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3810
3811 pfn = get_pmd_pfn(pmd[i], vma, addr);
3812 if (pfn == -1)
3813 goto next;
3814
3815 if (!pmd_trans_huge(pmd[i])) {
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003816 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3817 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003818 pmdp_test_and_clear_young(vma, addr, pmd + i);
3819 goto next;
3820 }
3821
3822 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3823 if (!page)
3824 goto next;
3825
3826 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3827 goto next;
3828
3829 walk->mm_stats[MM_LEAF_YOUNG]++;
3830
3831 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3832 !(PageAnon(page) && PageSwapBacked(page) &&
3833 !PageSwapCache(page)))
3834 set_page_dirty(page);
3835
3836 old_gen = page_update_gen(page, new_gen);
3837 if (old_gen >= 0 && old_gen != new_gen)
3838 update_batch_size(walk, page, old_gen, new_gen);
3839next:
3840 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3841 } while (i <= MIN_LRU_BATCH);
3842
3843 arch_leave_lazy_mmu_mode();
3844 spin_unlock(ptl);
3845done:
3846 *start = -1;
3847 bitmap_zero(bitmap, MIN_LRU_BATCH);
3848}
3849#else
3850static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3851 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3852{
3853}
3854#endif
3855
3856static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3857 struct mm_walk *args)
3858{
3859 int i;
3860 pmd_t *pmd;
3861 unsigned long next;
3862 unsigned long addr;
3863 struct vm_area_struct *vma;
3864 unsigned long pos = -1;
3865 struct lru_gen_mm_walk *walk = args->private;
3866 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3867
3868 VM_WARN_ON_ONCE(pud_leaf(*pud));
3869
3870 /*
3871 * Finish an entire PMD in two passes: the first only reaches to PTE
3872 * tables to avoid taking the PMD lock; the second, if necessary, takes
3873 * the PMD lock to clear the accessed bit in PMD entries.
3874 */
3875 pmd = pmd_offset(pud, start & PUD_MASK);
3876restart:
3877 /* walk_pte_range() may call get_next_vma() */
3878 vma = args->vma;
3879 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3880 pmd_t val = pmd_read_atomic(pmd + i);
3881
3882 /* for pmd_read_atomic() */
3883 barrier();
3884
3885 next = pmd_addr_end(addr, end);
3886
3887 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3888 walk->mm_stats[MM_LEAF_TOTAL]++;
3889 continue;
3890 }
3891
3892#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3893 if (pmd_trans_huge(val)) {
3894 unsigned long pfn = pmd_pfn(val);
3895 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3896
3897 walk->mm_stats[MM_LEAF_TOTAL]++;
3898
3899 if (!pmd_young(val)) {
3900 walk->mm_stats[MM_LEAF_OLD]++;
3901 continue;
3902 }
3903
3904 /* try to avoid unnecessary memory loads */
3905 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3906 continue;
3907
3908 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3909 continue;
3910 }
3911#endif
3912 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3913
3914#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003915 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3916 if (!pmd_young(val))
3917 continue;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003918
Yu Zhaobaeb9a02022-09-18 02:00:07 -06003919 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3920 }
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003921#endif
3922 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3923 continue;
3924
3925 walk->mm_stats[MM_NONLEAF_FOUND]++;
3926
3927 if (!walk_pte_range(&val, addr, next, args))
3928 continue;
3929
3930 walk->mm_stats[MM_NONLEAF_ADDED]++;
3931
3932 /* carry over to the next generation */
3933 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3934 }
3935
3936 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3937
3938 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3939 goto restart;
3940}
3941
3942static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3943 struct mm_walk *args)
3944{
3945 int i;
3946 pud_t *pud;
3947 unsigned long addr;
3948 unsigned long next;
3949 struct lru_gen_mm_walk *walk = args->private;
3950
3951 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3952
3953 pud = pud_offset(p4d, start & P4D_MASK);
3954restart:
3955 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3956 pud_t val = READ_ONCE(pud[i]);
3957
3958 next = pud_addr_end(addr, end);
3959
3960 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3961 continue;
3962
3963 walk_pmd_range(&val, addr, next, args);
3964
3965 /* a racy check to curtail the waiting time */
3966 if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
3967 return 1;
3968
3969 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3970 end = (addr | ~PUD_MASK) + 1;
3971 goto done;
3972 }
3973 }
3974
3975 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3976 goto restart;
3977
3978 end = round_up(end, P4D_SIZE);
3979done:
3980 if (!end || !args->vma)
3981 return 1;
3982
3983 walk->next_addr = max(end, args->vma->vm_start);
3984
3985 return -EAGAIN;
3986}
3987
3988static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3989{
3990 static const struct mm_walk_ops mm_walk_ops = {
3991 .test_walk = should_skip_vma,
3992 .p4d_entry = walk_pud_range,
3993 };
3994
3995 int err;
3996 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3997
3998 walk->next_addr = FIRST_USER_ADDRESS;
3999
4000 do {
4001 err = -EBUSY;
4002
4003 /* page_update_gen() requires stable page_memcg() */
4004 if (!mem_cgroup_trylock_pages(memcg))
4005 break;
4006
4007 /* the caller might be holding the lock for write */
4008 if (mmap_read_trylock(mm)) {
4009 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
4010
4011 mmap_read_unlock(mm);
4012 }
4013
4014 mem_cgroup_unlock_pages();
4015
4016 if (walk->batched) {
4017 spin_lock_irq(&lruvec->lru_lock);
4018 reset_batch_size(lruvec, walk);
4019 spin_unlock_irq(&lruvec->lru_lock);
4020 }
4021
4022 cond_resched();
4023 } while (err == -EAGAIN);
4024}
4025
4026static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
4027{
4028 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4029
4030 if (pgdat && current_is_kswapd()) {
4031 VM_WARN_ON_ONCE(walk);
4032
4033 walk = &pgdat->mm_walk;
4034 } else if (!pgdat && !walk) {
4035 VM_WARN_ON_ONCE(current_is_kswapd());
4036
4037 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4038 }
4039
4040 current->reclaim_state->mm_walk = walk;
4041
4042 return walk;
4043}
4044
4045static void clear_mm_walk(void)
4046{
4047 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4048
4049 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4050 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4051
4052 current->reclaim_state->mm_walk = NULL;
4053
4054 if (!current_is_kswapd())
4055 kfree(walk);
4056}
4057
Yu Zhao4983c522022-09-18 02:00:09 -06004058static bool inc_min_seq(struct lruvec *lruvec, int type, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004059{
Yu Zhao4983c522022-09-18 02:00:09 -06004060 int zone;
4061 int remaining = MAX_LRU_BATCH;
Yu Zhao37397872022-09-18 02:00:03 -06004062 struct lru_gen_struct *lrugen = &lruvec->lrugen;
Yu Zhao4983c522022-09-18 02:00:09 -06004063 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
Yu Zhao37397872022-09-18 02:00:03 -06004064
Yu Zhao4983c522022-09-18 02:00:09 -06004065 if (type == LRU_GEN_ANON && !can_swap)
4066 goto done;
4067
4068 /* prevent cold/hot inversion if force_scan is true */
4069 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4070 struct list_head *head = &lrugen->lists[old_gen][type][zone];
4071
4072 while (!list_empty(head)) {
4073 struct page *page = lru_to_page(head);
4074
4075 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4076 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4077 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4078 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4079
4080 new_gen = page_inc_gen(lruvec, page, false);
4081 list_move_tail(&page->lru, &lrugen->lists[new_gen][type][zone]);
4082
4083 if (!--remaining)
4084 return false;
4085 }
4086 }
4087done:
Yu Zhao37397872022-09-18 02:00:03 -06004088 reset_ctrl_pos(lruvec, type, true);
4089 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
Yu Zhao4983c522022-09-18 02:00:09 -06004090
4091 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004092}
4093
4094static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4095{
4096 int gen, type, zone;
4097 bool success = false;
4098 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4099 DEFINE_MIN_SEQ(lruvec);
4100
4101 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4102
4103 /* find the oldest populated generation */
4104 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4105 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4106 gen = lru_gen_from_seq(min_seq[type]);
4107
4108 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4109 if (!list_empty(&lrugen->lists[gen][type][zone]))
4110 goto next;
4111 }
4112
4113 min_seq[type]++;
4114 }
4115next:
4116 ;
4117 }
4118
4119 /* see the comment on lru_gen_struct */
4120 if (can_swap) {
4121 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4122 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4123 }
4124
4125 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4126 if (min_seq[type] == lrugen->min_seq[type])
4127 continue;
4128
4129 reset_ctrl_pos(lruvec, type, true);
4130 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4131 success = true;
4132 }
4133
4134 return success;
4135}
4136
Yu Zhao4983c522022-09-18 02:00:09 -06004137static void inc_max_seq(struct lruvec *lruvec, bool can_swap, bool force_scan)
Yu Zhao37397872022-09-18 02:00:03 -06004138{
4139 int prev, next;
4140 int type, zone;
4141 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4142
4143 spin_lock_irq(&lruvec->lru_lock);
4144
4145 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4146
Yu Zhao37397872022-09-18 02:00:03 -06004147 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4148 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4149 continue;
4150
Yu Zhao4983c522022-09-18 02:00:09 -06004151 VM_WARN_ON_ONCE(!force_scan && (type == LRU_GEN_FILE || can_swap));
Yu Zhao37397872022-09-18 02:00:03 -06004152
Yu Zhao4983c522022-09-18 02:00:09 -06004153 while (!inc_min_seq(lruvec, type, can_swap)) {
4154 spin_unlock_irq(&lruvec->lru_lock);
4155 cond_resched();
4156 spin_lock_irq(&lruvec->lru_lock);
4157 }
Yu Zhao37397872022-09-18 02:00:03 -06004158 }
4159
4160 /*
4161 * Update the active/inactive LRU sizes for compatibility. Both sides of
4162 * the current max_seq need to be covered, since max_seq+1 can overlap
4163 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4164 * overlap, cold/hot inversion happens.
4165 */
4166 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4167 next = lru_gen_from_seq(lrugen->max_seq + 1);
4168
4169 for (type = 0; type < ANON_AND_FILE; type++) {
4170 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4171 enum lru_list lru = type * LRU_INACTIVE_FILE;
4172 long delta = lrugen->nr_pages[prev][type][zone] -
4173 lrugen->nr_pages[next][type][zone];
4174
4175 if (!delta)
4176 continue;
4177
4178 __update_lru_size(lruvec, lru, zone, delta);
4179 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4180 }
4181 }
4182
4183 for (type = 0; type < ANON_AND_FILE; type++)
4184 reset_ctrl_pos(lruvec, type, false);
4185
Yu Zhao430499c2022-09-18 02:00:08 -06004186 WRITE_ONCE(lrugen->timestamps[next], jiffies);
Yu Zhao37397872022-09-18 02:00:03 -06004187 /* make sure preceding modifications appear */
4188 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004189
Yu Zhao37397872022-09-18 02:00:03 -06004190 spin_unlock_irq(&lruvec->lru_lock);
4191}
4192
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004193static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
Yu Zhao4983c522022-09-18 02:00:09 -06004194 struct scan_control *sc, bool can_swap, bool force_scan)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004195{
4196 bool success;
4197 struct lru_gen_mm_walk *walk;
4198 struct mm_struct *mm = NULL;
4199 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4200
4201 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4202
4203 /* see the comment in iterate_mm_list() */
4204 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4205 success = false;
4206 goto done;
4207 }
4208
4209 /*
4210 * If the hardware doesn't automatically set the accessed bit, fallback
4211 * to lru_gen_look_around(), which only clears the accessed bit in a
4212 * handful of PTEs. Spreading the work out over a period of time usually
4213 * is less efficient, but it avoids bursty page faults.
4214 */
Yu Zhao4983c522022-09-18 02:00:09 -06004215 if (!force_scan && !(arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))) {
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004216 success = iterate_mm_list_nowalk(lruvec, max_seq);
4217 goto done;
4218 }
4219
4220 walk = set_mm_walk(NULL);
4221 if (!walk) {
4222 success = iterate_mm_list_nowalk(lruvec, max_seq);
4223 goto done;
4224 }
4225
4226 walk->lruvec = lruvec;
4227 walk->max_seq = max_seq;
4228 walk->can_swap = can_swap;
Yu Zhao4983c522022-09-18 02:00:09 -06004229 walk->force_scan = force_scan;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004230
4231 do {
4232 success = iterate_mm_list(lruvec, walk, &mm);
4233 if (mm)
4234 walk_mm(lruvec, mm, walk);
4235
4236 cond_resched();
4237 } while (mm);
4238done:
4239 if (!success) {
4240 if (sc->priority <= DEF_PRIORITY - 2)
4241 wait_event_killable(lruvec->mm_state.wait,
4242 max_seq < READ_ONCE(lrugen->max_seq));
4243
4244 return max_seq < READ_ONCE(lrugen->max_seq);
4245 }
4246
4247 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4248
Yu Zhao4983c522022-09-18 02:00:09 -06004249 inc_max_seq(lruvec, can_swap, force_scan);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004250 /* either this sees any waiters or they will see updated max_seq */
4251 if (wq_has_sleeper(&lruvec->mm_state.wait))
4252 wake_up_all(&lruvec->mm_state.wait);
4253
4254 return true;
4255}
4256
Yu Zhao37397872022-09-18 02:00:03 -06004257static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
4258 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4259{
4260 int gen, type, zone;
4261 unsigned long old = 0;
4262 unsigned long young = 0;
4263 unsigned long total = 0;
4264 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4265 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4266
4267 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4268 unsigned long seq;
4269
4270 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4271 unsigned long size = 0;
4272
4273 gen = lru_gen_from_seq(seq);
4274
4275 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4276 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4277
4278 total += size;
4279 if (seq == max_seq)
4280 young += size;
4281 else if (seq + MIN_NR_GENS == max_seq)
4282 old += size;
4283 }
4284 }
4285
4286 /* try to scrape all its memory if this memcg was deleted */
4287 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4288
4289 /*
4290 * The aging tries to be lazy to reduce the overhead, while the eviction
4291 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4292 * ideal number of generations is MIN_NR_GENS+1.
4293 */
4294 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
4295 return true;
4296 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4297 return false;
4298
4299 /*
4300 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4301 * of the total number of pages for each generation. A reasonable range
4302 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4303 * aging cares about the upper bound of hot pages, while the eviction
4304 * cares about the lower bound of cold pages.
4305 */
4306 if (young * MIN_NR_GENS > total)
4307 return true;
4308 if (old * (MIN_NR_GENS + 2) < total)
4309 return true;
4310
4311 return false;
4312}
4313
Yu Zhao430499c2022-09-18 02:00:08 -06004314static bool age_lruvec(struct lruvec *lruvec, struct scan_control *sc, unsigned long min_ttl)
Yu Zhao37397872022-09-18 02:00:03 -06004315{
4316 bool need_aging;
4317 unsigned long nr_to_scan;
4318 int swappiness = get_swappiness(lruvec, sc);
4319 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4320 DEFINE_MAX_SEQ(lruvec);
4321 DEFINE_MIN_SEQ(lruvec);
4322
4323 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
4324
4325 mem_cgroup_calculate_protection(NULL, memcg);
4326
4327 if (mem_cgroup_below_min(memcg))
Yu Zhao430499c2022-09-18 02:00:08 -06004328 return false;
Yu Zhao37397872022-09-18 02:00:03 -06004329
4330 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
Yu Zhao430499c2022-09-18 02:00:08 -06004331
4332 if (min_ttl) {
4333 int gen = lru_gen_from_seq(min_seq[LRU_GEN_FILE]);
4334 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
4335
4336 if (time_is_after_jiffies(birth + min_ttl))
4337 return false;
4338
4339 /* the size is likely too small to be helpful */
4340 if (!nr_to_scan && sc->priority != DEF_PRIORITY)
4341 return false;
4342 }
4343
Yu Zhao37397872022-09-18 02:00:03 -06004344 if (need_aging)
Yu Zhao4983c522022-09-18 02:00:09 -06004345 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
Yu Zhao430499c2022-09-18 02:00:08 -06004346
4347 return true;
Yu Zhao37397872022-09-18 02:00:03 -06004348}
4349
Yu Zhao430499c2022-09-18 02:00:08 -06004350/* to protect the working set of the last N jiffies */
4351static unsigned long lru_gen_min_ttl __read_mostly;
4352
Yu Zhao37397872022-09-18 02:00:03 -06004353static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4354{
4355 struct mem_cgroup *memcg;
Yu Zhao430499c2022-09-18 02:00:08 -06004356 bool success = false;
4357 unsigned long min_ttl = READ_ONCE(lru_gen_min_ttl);
Yu Zhao37397872022-09-18 02:00:03 -06004358
4359 VM_WARN_ON_ONCE(!current_is_kswapd());
4360
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004361 sc->last_reclaimed = sc->nr_reclaimed;
4362
4363 /*
4364 * To reduce the chance of going into the aging path, which can be
4365 * costly, optimistically skip it if the flag below was cleared in the
4366 * eviction path. This improves the overall performance when multiple
4367 * memcgs are available.
4368 */
4369 if (!sc->memcgs_need_aging) {
4370 sc->memcgs_need_aging = true;
4371 return;
4372 }
4373
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004374 set_mm_walk(pgdat);
4375
Yu Zhao37397872022-09-18 02:00:03 -06004376 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4377 do {
4378 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4379
Yu Zhao430499c2022-09-18 02:00:08 -06004380 if (age_lruvec(lruvec, sc, min_ttl))
4381 success = true;
Yu Zhao37397872022-09-18 02:00:03 -06004382
4383 cond_resched();
4384 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004385
4386 clear_mm_walk();
Yu Zhao430499c2022-09-18 02:00:08 -06004387
4388 /* check the order to exclude compaction-induced reclaim */
4389 if (success || !min_ttl || sc->order)
4390 return;
4391
4392 /*
4393 * The main goal is to OOM kill if every generation from all memcgs is
4394 * younger than min_ttl. However, another possibility is all memcgs are
4395 * either below min or empty.
4396 */
4397 if (mutex_trylock(&oom_lock)) {
4398 struct oom_control oc = {
4399 .gfp_mask = sc->gfp_mask,
4400 };
4401
4402 out_of_memory(&oc);
4403
4404 mutex_unlock(&oom_lock);
4405 }
Yu Zhao37397872022-09-18 02:00:03 -06004406}
4407
Yu Zhao0182f922022-09-18 02:00:04 -06004408/*
4409 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004410 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4411 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4412 * the PTE table to the Bloom filter. This forms a feedback loop between the
4413 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004414 */
4415void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4416{
4417 int i;
4418 pte_t *pte;
4419 unsigned long start;
4420 unsigned long end;
4421 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004422 struct lru_gen_mm_walk *walk;
4423 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004424 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4425 struct page *page = pvmw->page;
4426 struct mem_cgroup *memcg = page_memcg(page);
4427 struct pglist_data *pgdat = page_pgdat(page);
4428 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4429 DEFINE_MAX_SEQ(lruvec);
4430 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4431
4432 lockdep_assert_held(pvmw->ptl);
4433 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4434
4435 if (spin_is_contended(pvmw->ptl))
4436 return;
4437
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004438 /* avoid taking the LRU lock under the PTL when possible */
4439 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4440
Yu Zhao0182f922022-09-18 02:00:04 -06004441 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4442 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4443
4444 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4445 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4446 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4447 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4448 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4449 else {
4450 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4451 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4452 }
4453 }
4454
4455 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4456
4457 rcu_read_lock();
4458 arch_enter_lazy_mmu_mode();
4459
4460 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4461 unsigned long pfn;
4462
4463 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4464 if (pfn == -1)
4465 continue;
4466
4467 if (!pte_young(pte[i]))
4468 continue;
4469
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004470 page = get_pfn_page(pfn, memcg, pgdat, !walk || walk->can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004471 if (!page)
4472 continue;
4473
4474 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4475 VM_WARN_ON_ONCE(true);
4476
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004477 young++;
4478
Yu Zhao0182f922022-09-18 02:00:04 -06004479 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4480 !(PageAnon(page) && PageSwapBacked(page) &&
4481 !PageSwapCache(page)))
4482 set_page_dirty(page);
4483
4484 old_gen = page_lru_gen(page);
4485 if (old_gen < 0)
4486 SetPageReferenced(page);
4487 else if (old_gen != new_gen)
4488 __set_bit(i, bitmap);
4489 }
4490
4491 arch_leave_lazy_mmu_mode();
4492 rcu_read_unlock();
4493
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004494 /* feedback from rmap walkers to page table walkers */
4495 if (suitable_to_scan(i, young))
4496 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4497
4498 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004499 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4500 page = pte_page(pte[i]);
4501 activate_page(page);
4502 }
4503 return;
4504 }
4505
4506 /* page_update_gen() requires stable page_memcg() */
4507 if (!mem_cgroup_trylock_pages(memcg))
4508 return;
4509
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004510 if (!walk) {
4511 spin_lock_irq(&lruvec->lru_lock);
4512 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4513 }
Yu Zhao0182f922022-09-18 02:00:04 -06004514
4515 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4516 page = compound_head(pte_page(pte[i]));
4517 if (page_memcg_rcu(page) != memcg)
4518 continue;
4519
4520 old_gen = page_update_gen(page, new_gen);
4521 if (old_gen < 0 || old_gen == new_gen)
4522 continue;
4523
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004524 if (walk)
4525 update_batch_size(walk, page, old_gen, new_gen);
4526 else
4527 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004528 }
4529
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004530 if (!walk)
4531 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004532
4533 mem_cgroup_unlock_pages();
4534}
4535
Yu Zhao37397872022-09-18 02:00:03 -06004536/******************************************************************************
4537 * the eviction
4538 ******************************************************************************/
4539
4540static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4541{
4542 bool success;
4543 int gen = page_lru_gen(page);
4544 int type = page_is_file_lru(page);
4545 int zone = page_zonenum(page);
4546 int delta = thp_nr_pages(page);
4547 int refs = page_lru_refs(page);
4548 int tier = lru_tier_from_refs(refs);
4549 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4550
4551 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4552
4553 /* unevictable */
4554 if (!page_evictable(page)) {
4555 success = lru_gen_del_page(lruvec, page, true);
4556 VM_WARN_ON_ONCE_PAGE(!success, page);
4557 SetPageUnevictable(page);
4558 add_page_to_lru_list(page, lruvec);
4559 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4560 return true;
4561 }
4562
4563 /* dirty lazyfree */
4564 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4565 success = lru_gen_del_page(lruvec, page, true);
4566 VM_WARN_ON_ONCE_PAGE(!success, page);
4567 SetPageSwapBacked(page);
4568 add_page_to_lru_list_tail(page, lruvec);
4569 return true;
4570 }
4571
Yu Zhao0182f922022-09-18 02:00:04 -06004572 /* promoted */
4573 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4574 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4575 return true;
4576 }
4577
Yu Zhao37397872022-09-18 02:00:03 -06004578 /* protected */
4579 if (tier > tier_idx) {
4580 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4581
4582 gen = page_inc_gen(lruvec, page, false);
4583 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4584
4585 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4586 lrugen->protected[hist][type][tier - 1] + delta);
4587 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4588 return true;
4589 }
4590
4591 /* waiting for writeback */
4592 if (PageLocked(page) || PageWriteback(page) ||
4593 (type == LRU_GEN_FILE && PageDirty(page))) {
4594 gen = page_inc_gen(lruvec, page, true);
4595 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4596 return true;
4597 }
4598
4599 return false;
4600}
4601
4602static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4603{
4604 bool success;
4605
4606 /* unmapping inhibited */
4607 if (!sc->may_unmap && page_mapped(page))
4608 return false;
4609
4610 /* swapping inhibited */
4611 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4612 (PageDirty(page) ||
4613 (PageAnon(page) && !PageSwapCache(page))))
4614 return false;
4615
4616 /* raced with release_pages() */
4617 if (!get_page_unless_zero(page))
4618 return false;
4619
4620 /* raced with another isolation */
4621 if (!TestClearPageLRU(page)) {
4622 put_page(page);
4623 return false;
4624 }
4625
4626 /* see the comment on MAX_NR_TIERS */
4627 if (!PageReferenced(page))
4628 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4629
4630 /* for shrink_page_list() */
4631 ClearPageReclaim(page);
4632 ClearPageReferenced(page);
4633
4634 success = lru_gen_del_page(lruvec, page, true);
4635 VM_WARN_ON_ONCE_PAGE(!success, page);
4636
4637 return true;
4638}
4639
4640static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4641 int type, int tier, struct list_head *list)
4642{
4643 int gen, zone;
4644 enum vm_event_item item;
4645 int sorted = 0;
4646 int scanned = 0;
4647 int isolated = 0;
4648 int remaining = MAX_LRU_BATCH;
4649 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4650 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4651
4652 VM_WARN_ON_ONCE(!list_empty(list));
4653
4654 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4655 return 0;
4656
4657 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4658
4659 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4660 LIST_HEAD(moved);
4661 int skipped = 0;
4662 struct list_head *head = &lrugen->lists[gen][type][zone];
4663
4664 while (!list_empty(head)) {
4665 struct page *page = lru_to_page(head);
4666 int delta = thp_nr_pages(page);
4667
4668 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4669 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4670 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4671 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4672
4673 scanned += delta;
4674
4675 if (sort_page(lruvec, page, tier))
4676 sorted += delta;
4677 else if (isolate_page(lruvec, page, sc)) {
4678 list_add(&page->lru, list);
4679 isolated += delta;
4680 } else {
4681 list_move(&page->lru, &moved);
4682 skipped += delta;
4683 }
4684
4685 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4686 break;
4687 }
4688
4689 if (skipped) {
4690 list_splice(&moved, head);
4691 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4692 }
4693
4694 if (!remaining || isolated >= MIN_LRU_BATCH)
4695 break;
4696 }
4697
4698 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4699 if (!cgroup_reclaim(sc)) {
4700 __count_vm_events(item, isolated);
4701 __count_vm_events(PGREFILL, sorted);
4702 }
4703 __count_memcg_events(memcg, item, isolated);
4704 __count_memcg_events(memcg, PGREFILL, sorted);
4705 __count_vm_events(PGSCAN_ANON + type, isolated);
4706
4707 /*
4708 * There might not be eligible pages due to reclaim_idx, may_unmap and
4709 * may_writepage. Check the remaining to prevent livelock if it's not
4710 * making progress.
4711 */
4712 return isolated || !remaining ? scanned : 0;
4713}
4714
4715static int get_tier_idx(struct lruvec *lruvec, int type)
4716{
4717 int tier;
4718 struct ctrl_pos sp, pv;
4719
4720 /*
4721 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4722 * This value is chosen because any other tier would have at least twice
4723 * as many refaults as the first tier.
4724 */
4725 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4726 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4727 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4728 if (!positive_ctrl_err(&sp, &pv))
4729 break;
4730 }
4731
4732 return tier - 1;
4733}
4734
4735static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4736{
4737 int type, tier;
4738 struct ctrl_pos sp, pv;
4739 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4740
4741 /*
4742 * Compare the first tier of anon with that of file to determine which
4743 * type to scan. Also need to compare other tiers of the selected type
4744 * with the first tier of the other type to determine the last tier (of
4745 * the selected type) to evict.
4746 */
4747 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4748 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4749 type = positive_ctrl_err(&sp, &pv);
4750
4751 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4752 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4753 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4754 if (!positive_ctrl_err(&sp, &pv))
4755 break;
4756 }
4757
4758 *tier_idx = tier - 1;
4759
4760 return type;
4761}
4762
4763static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4764 int *type_scanned, struct list_head *list)
4765{
4766 int i;
4767 int type;
4768 int scanned;
4769 int tier = -1;
4770 DEFINE_MIN_SEQ(lruvec);
4771
4772 /*
4773 * Try to make the obvious choice first. When anon and file are both
4774 * available from the same generation, interpret swappiness 1 as file
4775 * first and 200 as anon first.
4776 */
4777 if (!swappiness)
4778 type = LRU_GEN_FILE;
4779 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4780 type = LRU_GEN_ANON;
4781 else if (swappiness == 1)
4782 type = LRU_GEN_FILE;
4783 else if (swappiness == 200)
4784 type = LRU_GEN_ANON;
4785 else
4786 type = get_type_to_scan(lruvec, swappiness, &tier);
4787
4788 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4789 if (tier < 0)
4790 tier = get_tier_idx(lruvec, type);
4791
4792 scanned = scan_pages(lruvec, sc, type, tier, list);
4793 if (scanned)
4794 break;
4795
4796 type = !type;
4797 tier = -1;
4798 }
4799
4800 *type_scanned = type;
4801
4802 return scanned;
4803}
4804
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004805static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4806 bool *need_swapping)
Yu Zhao37397872022-09-18 02:00:03 -06004807{
4808 int type;
4809 int scanned;
4810 int reclaimed;
4811 LIST_HEAD(list);
4812 struct page *page;
4813 enum vm_event_item item;
4814 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004815 struct lru_gen_mm_walk *walk;
Yu Zhao37397872022-09-18 02:00:03 -06004816 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4817 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4818
4819 spin_lock_irq(&lruvec->lru_lock);
4820
4821 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4822
4823 scanned += try_to_inc_min_seq(lruvec, swappiness);
4824
4825 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4826 scanned = 0;
4827
4828 spin_unlock_irq(&lruvec->lru_lock);
4829
4830 if (list_empty(&list))
4831 return scanned;
4832
4833 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4834
4835 list_for_each_entry(page, &list, lru) {
4836 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4837 if (PageWorkingset(page))
4838 SetPageReferenced(page);
4839
4840 /* don't add rejected pages to the oldest generation */
4841 if (PageReclaim(page) &&
4842 (PageDirty(page) || PageWriteback(page)))
4843 ClearPageActive(page);
4844 else
4845 SetPageActive(page);
4846 }
4847
4848 spin_lock_irq(&lruvec->lru_lock);
4849
4850 move_pages_to_lru(lruvec, &list);
4851
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004852 walk = current->reclaim_state->mm_walk;
4853 if (walk && walk->batched)
4854 reset_batch_size(lruvec, walk);
4855
Yu Zhao37397872022-09-18 02:00:03 -06004856 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4857 if (!cgroup_reclaim(sc))
4858 __count_vm_events(item, reclaimed);
4859 __count_memcg_events(memcg, item, reclaimed);
4860 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4861
4862 spin_unlock_irq(&lruvec->lru_lock);
4863
4864 mem_cgroup_uncharge_list(&list);
4865 free_unref_page_list(&list);
4866
4867 sc->nr_reclaimed += reclaimed;
4868
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004869 if (need_swapping && type == LRU_GEN_ANON)
4870 *need_swapping = true;
4871
Yu Zhao37397872022-09-18 02:00:03 -06004872 return scanned;
4873}
4874
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004875/*
4876 * For future optimizations:
4877 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4878 * reclaim.
4879 */
Yu Zhao37397872022-09-18 02:00:03 -06004880static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004881 bool can_swap, bool *need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004882{
Yu Zhao37397872022-09-18 02:00:03 -06004883 unsigned long nr_to_scan;
4884 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4885 DEFINE_MAX_SEQ(lruvec);
4886 DEFINE_MIN_SEQ(lruvec);
4887
4888 if (mem_cgroup_below_min(memcg) ||
4889 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4890 return 0;
4891
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004892 *need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
4893 if (!*need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004894 return nr_to_scan;
4895
4896 /* skip the aging path at the default priority */
4897 if (sc->priority == DEF_PRIORITY)
4898 goto done;
4899
4900 /* leave the work to lru_gen_age_node() */
4901 if (current_is_kswapd())
4902 return 0;
4903
Yu Zhao4983c522022-09-18 02:00:09 -06004904 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004905 return nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004906done:
4907 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
4908}
4909
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004910static bool should_abort_scan(struct lruvec *lruvec, unsigned long seq,
4911 struct scan_control *sc, bool need_swapping)
4912{
4913 int i;
4914 DEFINE_MAX_SEQ(lruvec);
4915
4916 if (!current_is_kswapd()) {
4917 /* age each memcg at most once to ensure fairness */
4918 if (max_seq - seq > 1)
4919 return true;
4920
4921 /* over-swapping can increase allocation latency */
4922 if (sc->nr_reclaimed >= sc->nr_to_reclaim && need_swapping)
4923 return true;
4924
4925 /* give this thread a chance to exit and free its memory */
4926 if (fatal_signal_pending(current)) {
4927 sc->nr_reclaimed += MIN_LRU_BATCH;
4928 return true;
4929 }
4930
4931 if (cgroup_reclaim(sc))
4932 return false;
4933 } else if (sc->nr_reclaimed - sc->last_reclaimed < sc->nr_to_reclaim)
4934 return false;
4935
4936 /* keep scanning at low priorities to ensure fairness */
4937 if (sc->priority > DEF_PRIORITY - 2)
4938 return false;
4939
4940 /*
4941 * A minimum amount of work was done under global memory pressure. For
4942 * kswapd, it may be overshooting. For direct reclaim, the allocation
4943 * may succeed if all suitable zones are somewhat safe. In either case,
4944 * it's better to stop now, and restart later if necessary.
4945 */
4946 for (i = 0; i <= sc->reclaim_idx; i++) {
4947 unsigned long wmark;
4948 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
4949
4950 if (!managed_zone(zone))
4951 continue;
4952
4953 wmark = current_is_kswapd() ? high_wmark_pages(zone) : low_wmark_pages(zone);
4954 if (wmark > zone_page_state(zone, NR_FREE_PAGES))
4955 return false;
4956 }
4957
4958 sc->nr_reclaimed += MIN_LRU_BATCH;
4959
4960 return true;
4961}
4962
Yu Zhao37397872022-09-18 02:00:03 -06004963static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4964{
4965 struct blk_plug plug;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004966 bool need_aging = false;
4967 bool need_swapping = false;
Yu Zhao37397872022-09-18 02:00:03 -06004968 unsigned long scanned = 0;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004969 unsigned long reclaimed = sc->nr_reclaimed;
4970 DEFINE_MAX_SEQ(lruvec);
Yu Zhao37397872022-09-18 02:00:03 -06004971
4972 lru_add_drain();
4973
4974 blk_start_plug(&plug);
4975
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004976 set_mm_walk(lruvec_pgdat(lruvec));
4977
Yu Zhao37397872022-09-18 02:00:03 -06004978 while (true) {
4979 int delta;
4980 int swappiness;
4981 unsigned long nr_to_scan;
4982
4983 if (sc->may_swap)
4984 swappiness = get_swappiness(lruvec, sc);
4985 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4986 swappiness = 1;
4987 else
4988 swappiness = 0;
4989
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004990 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, &need_aging);
Yu Zhao37397872022-09-18 02:00:03 -06004991 if (!nr_to_scan)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004992 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004993
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004994 delta = evict_pages(lruvec, sc, swappiness, &need_swapping);
Yu Zhao37397872022-09-18 02:00:03 -06004995 if (!delta)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004996 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004997
4998 scanned += delta;
4999 if (scanned >= nr_to_scan)
5000 break;
5001
Yu Zhaoa8a158a2022-09-18 02:00:06 -06005002 if (should_abort_scan(lruvec, max_seq, sc, need_swapping))
5003 break;
5004
Yu Zhao37397872022-09-18 02:00:03 -06005005 cond_resched();
5006 }
5007
Yu Zhaoa8a158a2022-09-18 02:00:06 -06005008 /* see the comment in lru_gen_age_node() */
5009 if (sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH && !need_aging)
5010 sc->memcgs_need_aging = false;
5011done:
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005012 clear_mm_walk();
5013
Yu Zhao37397872022-09-18 02:00:03 -06005014 blk_finish_plug(&plug);
5015}
5016
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005017/******************************************************************************
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005018 * state change
5019 ******************************************************************************/
5020
5021static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
5022{
5023 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5024
5025 if (lrugen->enabled) {
5026 enum lru_list lru;
5027
5028 for_each_evictable_lru(lru) {
5029 if (!list_empty(&lruvec->lists[lru]))
5030 return false;
5031 }
5032 } else {
5033 int gen, type, zone;
5034
5035 for_each_gen_type_zone(gen, type, zone) {
5036 if (!list_empty(&lrugen->lists[gen][type][zone]))
5037 return false;
5038 }
5039 }
5040
5041 return true;
5042}
5043
5044static bool fill_evictable(struct lruvec *lruvec)
5045{
5046 enum lru_list lru;
5047 int remaining = MAX_LRU_BATCH;
5048
5049 for_each_evictable_lru(lru) {
5050 int type = is_file_lru(lru);
5051 bool active = is_active_lru(lru);
5052 struct list_head *head = &lruvec->lists[lru];
5053
5054 while (!list_empty(head)) {
5055 bool success;
5056 struct page *page = lru_to_page(head);
5057
5058 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5059 VM_WARN_ON_ONCE_PAGE(PageActive(page) != active, page);
5060 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5061 VM_WARN_ON_ONCE_PAGE(page_lru_gen(page) != -1, page);
5062
5063 del_page_from_lru_list(page, lruvec);
5064 success = lru_gen_add_page(lruvec, page, false);
5065 VM_WARN_ON_ONCE(!success);
5066
5067 if (!--remaining)
5068 return false;
5069 }
5070 }
5071
5072 return true;
5073}
5074
5075static bool drain_evictable(struct lruvec *lruvec)
5076{
5077 int gen, type, zone;
5078 int remaining = MAX_LRU_BATCH;
5079
5080 for_each_gen_type_zone(gen, type, zone) {
5081 struct list_head *head = &lruvec->lrugen.lists[gen][type][zone];
5082
5083 while (!list_empty(head)) {
5084 bool success;
5085 struct page *page = lru_to_page(head);
5086
5087 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
5088 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
5089 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
5090 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
5091
5092 success = lru_gen_del_page(lruvec, page, false);
5093 VM_WARN_ON_ONCE(!success);
5094 add_page_to_lru_list(page, lruvec);
5095
5096 if (!--remaining)
5097 return false;
5098 }
5099 }
5100
5101 return true;
5102}
5103
5104static void lru_gen_change_state(bool enabled)
5105{
5106 static DEFINE_MUTEX(state_mutex);
5107
5108 struct mem_cgroup *memcg;
5109
5110 cgroup_lock();
5111 cpus_read_lock();
5112 get_online_mems();
5113 mutex_lock(&state_mutex);
5114
5115 if (enabled == lru_gen_enabled())
5116 goto unlock;
5117
5118 if (enabled)
5119 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5120 else
5121 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
5122
5123 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5124 do {
5125 int nid;
5126
5127 for_each_node(nid) {
5128 struct lruvec *lruvec = get_lruvec(memcg, nid);
5129
5130 if (!lruvec)
5131 continue;
5132
5133 spin_lock_irq(&lruvec->lru_lock);
5134
5135 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
5136 VM_WARN_ON_ONCE(!state_is_valid(lruvec));
5137
5138 lruvec->lrugen.enabled = enabled;
5139
5140 while (!(enabled ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5141 spin_unlock_irq(&lruvec->lru_lock);
5142 cond_resched();
5143 spin_lock_irq(&lruvec->lru_lock);
5144 }
5145
5146 spin_unlock_irq(&lruvec->lru_lock);
5147 }
5148
5149 cond_resched();
5150 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5151unlock:
5152 mutex_unlock(&state_mutex);
5153 put_online_mems();
5154 cpus_read_unlock();
5155 cgroup_unlock();
5156}
5157
5158/******************************************************************************
5159 * sysfs interface
5160 ******************************************************************************/
5161
Yu Zhao430499c2022-09-18 02:00:08 -06005162static ssize_t show_min_ttl(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5163{
5164 return sprintf(buf, "%u\n", jiffies_to_msecs(READ_ONCE(lru_gen_min_ttl)));
5165}
5166
5167static ssize_t store_min_ttl(struct kobject *kobj, struct kobj_attribute *attr,
5168 const char *buf, size_t len)
5169{
5170 unsigned int msecs;
5171
5172 if (kstrtouint(buf, 0, &msecs))
5173 return -EINVAL;
5174
5175 WRITE_ONCE(lru_gen_min_ttl, msecs_to_jiffies(msecs));
5176
5177 return len;
5178}
5179
5180static struct kobj_attribute lru_gen_min_ttl_attr = __ATTR(
5181 min_ttl_ms, 0644, show_min_ttl, store_min_ttl
5182);
5183
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005184static ssize_t show_enabled(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5185{
5186 unsigned int caps = 0;
5187
5188 if (get_cap(LRU_GEN_CORE))
5189 caps |= BIT(LRU_GEN_CORE);
5190
5191 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5192 caps |= BIT(LRU_GEN_MM_WALK);
5193
5194 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
5195 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5196
5197 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5198}
5199
5200static ssize_t store_enabled(struct kobject *kobj, struct kobj_attribute *attr,
5201 const char *buf, size_t len)
5202{
5203 int i;
5204 unsigned int caps;
5205
5206 if (tolower(*buf) == 'n')
5207 caps = 0;
5208 else if (tolower(*buf) == 'y')
5209 caps = -1;
5210 else if (kstrtouint(buf, 0, &caps))
5211 return -EINVAL;
5212
5213 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5214 bool enabled = caps & BIT(i);
5215
5216 if (i == LRU_GEN_CORE)
5217 lru_gen_change_state(enabled);
5218 else if (enabled)
5219 static_branch_enable(&lru_gen_caps[i]);
5220 else
5221 static_branch_disable(&lru_gen_caps[i]);
5222 }
5223
5224 return len;
5225}
5226
5227static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5228 enabled, 0644, show_enabled, store_enabled
5229);
5230
5231static struct attribute *lru_gen_attrs[] = {
Yu Zhao430499c2022-09-18 02:00:08 -06005232 &lru_gen_min_ttl_attr.attr,
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005233 &lru_gen_enabled_attr.attr,
5234 NULL
5235};
5236
5237static struct attribute_group lru_gen_attr_group = {
5238 .name = "lru_gen",
5239 .attrs = lru_gen_attrs,
5240};
5241
5242/******************************************************************************
Yu Zhao4983c522022-09-18 02:00:09 -06005243 * debugfs interface
5244 ******************************************************************************/
5245
5246static void *lru_gen_seq_start(struct seq_file *m, loff_t *pos)
5247{
5248 struct mem_cgroup *memcg;
5249 loff_t nr_to_skip = *pos;
5250
5251 m->private = kvmalloc(PATH_MAX, GFP_KERNEL);
5252 if (!m->private)
5253 return ERR_PTR(-ENOMEM);
5254
5255 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5256 do {
5257 int nid;
5258
5259 for_each_node_state(nid, N_MEMORY) {
5260 if (!nr_to_skip--)
5261 return get_lruvec(memcg, nid);
5262 }
5263 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5264
5265 return NULL;
5266}
5267
5268static void lru_gen_seq_stop(struct seq_file *m, void *v)
5269{
5270 if (!IS_ERR_OR_NULL(v))
5271 mem_cgroup_iter_break(NULL, lruvec_memcg(v));
5272
5273 kvfree(m->private);
5274 m->private = NULL;
5275}
5276
5277static void *lru_gen_seq_next(struct seq_file *m, void *v, loff_t *pos)
5278{
5279 int nid = lruvec_pgdat(v)->node_id;
5280 struct mem_cgroup *memcg = lruvec_memcg(v);
5281
5282 ++*pos;
5283
5284 nid = next_memory_node(nid);
5285 if (nid == MAX_NUMNODES) {
5286 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5287 if (!memcg)
5288 return NULL;
5289
5290 nid = first_memory_node;
5291 }
5292
5293 return get_lruvec(memcg, nid);
5294}
5295
5296static void lru_gen_seq_show_full(struct seq_file *m, struct lruvec *lruvec,
5297 unsigned long max_seq, unsigned long *min_seq,
5298 unsigned long seq)
5299{
5300 int i;
5301 int type, tier;
5302 int hist = lru_hist_from_seq(seq);
5303 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5304
5305 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
5306 seq_printf(m, " %10d", tier);
5307 for (type = 0; type < ANON_AND_FILE; type++) {
5308 const char *s = " ";
5309 unsigned long n[3] = {};
5310
5311 if (seq == max_seq) {
5312 s = "RT ";
5313 n[0] = READ_ONCE(lrugen->avg_refaulted[type][tier]);
5314 n[1] = READ_ONCE(lrugen->avg_total[type][tier]);
5315 } else if (seq == min_seq[type] || NR_HIST_GENS > 1) {
5316 s = "rep";
5317 n[0] = atomic_long_read(&lrugen->refaulted[hist][type][tier]);
5318 n[1] = atomic_long_read(&lrugen->evicted[hist][type][tier]);
5319 if (tier)
5320 n[2] = READ_ONCE(lrugen->protected[hist][type][tier - 1]);
5321 }
5322
5323 for (i = 0; i < 3; i++)
5324 seq_printf(m, " %10lu%c", n[i], s[i]);
5325 }
5326 seq_putc(m, '\n');
5327 }
5328
5329 seq_puts(m, " ");
5330 for (i = 0; i < NR_MM_STATS; i++) {
5331 const char *s = " ";
5332 unsigned long n = 0;
5333
5334 if (seq == max_seq && NR_HIST_GENS == 1) {
5335 s = "LOYNFA";
5336 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5337 } else if (seq != max_seq && NR_HIST_GENS > 1) {
5338 s = "loynfa";
5339 n = READ_ONCE(lruvec->mm_state.stats[hist][i]);
5340 }
5341
5342 seq_printf(m, " %10lu%c", n, s[i]);
5343 }
5344 seq_putc(m, '\n');
5345}
5346
5347static int lru_gen_seq_show(struct seq_file *m, void *v)
5348{
5349 unsigned long seq;
5350 bool full = !debugfs_real_fops(m->file)->write;
5351 struct lruvec *lruvec = v;
5352 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5353 int nid = lruvec_pgdat(lruvec)->node_id;
5354 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
5355 DEFINE_MAX_SEQ(lruvec);
5356 DEFINE_MIN_SEQ(lruvec);
5357
5358 if (nid == first_memory_node) {
5359 const char *path = memcg ? m->private : "";
5360
5361#ifdef CONFIG_MEMCG
5362 if (memcg)
5363 cgroup_path(memcg->css.cgroup, m->private, PATH_MAX);
5364#endif
5365 seq_printf(m, "memcg %5hu %s\n", mem_cgroup_id(memcg), path);
5366 }
5367
5368 seq_printf(m, " node %5d\n", nid);
5369
5370 if (!full)
5371 seq = min_seq[LRU_GEN_ANON];
5372 else if (max_seq >= MAX_NR_GENS)
5373 seq = max_seq - MAX_NR_GENS + 1;
5374 else
5375 seq = 0;
5376
5377 for (; seq <= max_seq; seq++) {
5378 int type, zone;
5379 int gen = lru_gen_from_seq(seq);
5380 unsigned long birth = READ_ONCE(lruvec->lrugen.timestamps[gen]);
5381
5382 seq_printf(m, " %10lu %10u", seq, jiffies_to_msecs(jiffies - birth));
5383
5384 for (type = 0; type < ANON_AND_FILE; type++) {
5385 unsigned long size = 0;
5386 char mark = full && seq < min_seq[type] ? 'x' : ' ';
5387
5388 for (zone = 0; zone < MAX_NR_ZONES; zone++)
5389 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
5390
5391 seq_printf(m, " %10lu%c", size, mark);
5392 }
5393
5394 seq_putc(m, '\n');
5395
5396 if (full)
5397 lru_gen_seq_show_full(m, lruvec, max_seq, min_seq, seq);
5398 }
5399
5400 return 0;
5401}
5402
5403static const struct seq_operations lru_gen_seq_ops = {
5404 .start = lru_gen_seq_start,
5405 .stop = lru_gen_seq_stop,
5406 .next = lru_gen_seq_next,
5407 .show = lru_gen_seq_show,
5408};
5409
5410static int run_aging(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5411 bool can_swap, bool force_scan)
5412{
5413 DEFINE_MAX_SEQ(lruvec);
5414 DEFINE_MIN_SEQ(lruvec);
5415
5416 if (seq < max_seq)
5417 return 0;
5418
5419 if (seq > max_seq)
5420 return -EINVAL;
5421
5422 if (!force_scan && min_seq[!can_swap] + MAX_NR_GENS - 1 <= max_seq)
5423 return -ERANGE;
5424
5425 try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, force_scan);
5426
5427 return 0;
5428}
5429
5430static int run_eviction(struct lruvec *lruvec, unsigned long seq, struct scan_control *sc,
5431 int swappiness, unsigned long nr_to_reclaim)
5432{
5433 DEFINE_MAX_SEQ(lruvec);
5434
5435 if (seq + MIN_NR_GENS > max_seq)
5436 return -EINVAL;
5437
5438 sc->nr_reclaimed = 0;
5439
5440 while (!signal_pending(current)) {
5441 DEFINE_MIN_SEQ(lruvec);
5442
5443 if (seq < min_seq[!swappiness])
5444 return 0;
5445
5446 if (sc->nr_reclaimed >= nr_to_reclaim)
5447 return 0;
5448
5449 if (!evict_pages(lruvec, sc, swappiness, NULL))
5450 return 0;
5451
5452 cond_resched();
5453 }
5454
5455 return -EINTR;
5456}
5457
5458static int run_cmd(char cmd, int memcg_id, int nid, unsigned long seq,
5459 struct scan_control *sc, int swappiness, unsigned long opt)
5460{
5461 struct lruvec *lruvec;
5462 int err = -EINVAL;
5463 struct mem_cgroup *memcg = NULL;
5464
5465 if (nid < 0 || nid >= MAX_NUMNODES || !node_state(nid, N_MEMORY))
5466 return -EINVAL;
5467
5468 if (!mem_cgroup_disabled()) {
5469 rcu_read_lock();
5470 memcg = mem_cgroup_from_id(memcg_id);
5471#ifdef CONFIG_MEMCG
5472 if (memcg && !css_tryget(&memcg->css))
5473 memcg = NULL;
5474#endif
5475 rcu_read_unlock();
5476
5477 if (!memcg)
5478 return -EINVAL;
5479 }
5480
5481 if (memcg_id != mem_cgroup_id(memcg))
5482 goto done;
5483
5484 lruvec = get_lruvec(memcg, nid);
5485
5486 if (swappiness < 0)
5487 swappiness = get_swappiness(lruvec, sc);
5488 else if (swappiness > 200)
5489 goto done;
5490
5491 switch (cmd) {
5492 case '+':
5493 err = run_aging(lruvec, seq, sc, swappiness, opt);
5494 break;
5495 case '-':
5496 err = run_eviction(lruvec, seq, sc, swappiness, opt);
5497 break;
5498 }
5499done:
5500 mem_cgroup_put(memcg);
5501
5502 return err;
5503}
5504
5505static ssize_t lru_gen_seq_write(struct file *file, const char __user *src,
5506 size_t len, loff_t *pos)
5507{
5508 void *buf;
5509 char *cur, *next;
5510 unsigned int flags;
5511 struct blk_plug plug;
5512 int err = -EINVAL;
5513 struct scan_control sc = {
5514 .may_writepage = true,
5515 .may_unmap = true,
5516 .may_swap = true,
5517 .reclaim_idx = MAX_NR_ZONES - 1,
5518 .gfp_mask = GFP_KERNEL,
5519 };
5520
5521 buf = kvmalloc(len + 1, GFP_KERNEL);
5522 if (!buf)
5523 return -ENOMEM;
5524
5525 if (copy_from_user(buf, src, len)) {
5526 kvfree(buf);
5527 return -EFAULT;
5528 }
5529
5530 set_task_reclaim_state(current, &sc.reclaim_state);
5531 flags = memalloc_noreclaim_save();
5532 blk_start_plug(&plug);
5533 if (!set_mm_walk(NULL)) {
5534 err = -ENOMEM;
5535 goto done;
5536 }
5537
5538 next = buf;
5539 next[len] = '\0';
5540
5541 while ((cur = strsep(&next, ",;\n"))) {
5542 int n;
5543 int end;
5544 char cmd;
5545 unsigned int memcg_id;
5546 unsigned int nid;
5547 unsigned long seq;
5548 unsigned int swappiness = -1;
5549 unsigned long opt = -1;
5550
5551 cur = skip_spaces(cur);
5552 if (!*cur)
5553 continue;
5554
5555 n = sscanf(cur, "%c %u %u %lu %n %u %n %lu %n", &cmd, &memcg_id, &nid,
5556 &seq, &end, &swappiness, &end, &opt, &end);
5557 if (n < 4 || cur[end]) {
5558 err = -EINVAL;
5559 break;
5560 }
5561
5562 err = run_cmd(cmd, memcg_id, nid, seq, &sc, swappiness, opt);
5563 if (err)
5564 break;
5565 }
5566done:
5567 clear_mm_walk();
5568 blk_finish_plug(&plug);
5569 memalloc_noreclaim_restore(flags);
5570 set_task_reclaim_state(current, NULL);
5571
5572 kvfree(buf);
5573
5574 return err ? : len;
5575}
5576
5577static int lru_gen_seq_open(struct inode *inode, struct file *file)
5578{
5579 return seq_open(file, &lru_gen_seq_ops);
5580}
5581
5582static const struct file_operations lru_gen_rw_fops = {
5583 .open = lru_gen_seq_open,
5584 .read = seq_read,
5585 .write = lru_gen_seq_write,
5586 .llseek = seq_lseek,
5587 .release = seq_release,
5588};
5589
5590static const struct file_operations lru_gen_ro_fops = {
5591 .open = lru_gen_seq_open,
5592 .read = seq_read,
5593 .llseek = seq_lseek,
5594 .release = seq_release,
5595};
5596
5597/******************************************************************************
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005598 * initialization
5599 ******************************************************************************/
5600
5601void lru_gen_init_lruvec(struct lruvec *lruvec)
5602{
Yu Zhao430499c2022-09-18 02:00:08 -06005603 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005604 int gen, type, zone;
5605 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5606
5607 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005608 lrugen->enabled = lru_gen_enabled();
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005609
Yu Zhao430499c2022-09-18 02:00:08 -06005610 for (i = 0; i <= MIN_NR_GENS + 1; i++)
5611 lrugen->timestamps[i] = jiffies;
5612
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005613 for_each_gen_type_zone(gen, type, zone)
5614 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005615
5616 lruvec->mm_state.seq = MIN_NR_GENS;
5617 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005618}
5619
5620#ifdef CONFIG_MEMCG
5621void lru_gen_init_memcg(struct mem_cgroup *memcg)
5622{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005623 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5624 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005625}
5626
5627void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5628{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005629 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005630 int nid;
5631
5632 for_each_node(nid) {
5633 struct lruvec *lruvec = get_lruvec(memcg, nid);
5634
5635 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
5636 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06005637
5638 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5639 bitmap_free(lruvec->mm_state.filters[i]);
5640 lruvec->mm_state.filters[i] = NULL;
5641 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005642 }
5643}
5644#endif
5645
5646static int __init init_lru_gen(void)
5647{
5648 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5649 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
5650
Yu Zhaobaeb9a02022-09-18 02:00:07 -06005651 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5652 pr_err("lru_gen: failed to create sysfs group\n");
5653
Yu Zhao4983c522022-09-18 02:00:09 -06005654 debugfs_create_file("lru_gen", 0644, NULL, NULL, &lru_gen_rw_fops);
5655 debugfs_create_file("lru_gen_full", 0444, NULL, NULL, &lru_gen_ro_fops);
5656
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005657 return 0;
5658};
5659late_initcall(init_lru_gen);
5660
Yu Zhao37397872022-09-18 02:00:03 -06005661#else /* !CONFIG_LRU_GEN */
5662
5663static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5664{
5665}
5666
5667static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5668{
5669}
5670
Yu Zhaod5b2fa12022-09-18 02:00:02 -06005671#endif /* CONFIG_LRU_GEN */
5672
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005673static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005674{
5675 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005676 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005677 unsigned long nr_to_scan;
5678 enum lru_list lru;
5679 unsigned long nr_reclaimed = 0;
5680 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5681 struct blk_plug plug;
Mel Gorman1a501902014-06-04 16:10:49 -07005682 bool scan_adjusted;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005683
Yu Zhao37397872022-09-18 02:00:03 -06005684 if (lru_gen_enabled()) {
5685 lru_gen_shrink_lruvec(lruvec, sc);
5686 return;
5687 }
5688
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005689 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005690
Mel Gormane82e0562013-07-03 15:01:44 -07005691 /* Record the original scan target for proportional adjustments later */
5692 memcpy(targets, nr, sizeof(nr));
5693
Mel Gorman1a501902014-06-04 16:10:49 -07005694 /*
5695 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5696 * event that can occur when there is little memory pressure e.g.
5697 * multiple streaming readers/writers. Hence, we do not abort scanning
5698 * when the requested number of pages are reclaimed when scanning at
5699 * DEF_PRIORITY on the assumption that the fact we are direct
5700 * reclaiming implies that kswapd is not keeping up and it is best to
5701 * do a batch of work at once. For memcg reclaim one check is made to
5702 * abort proportional reclaim if either the file or anon lru has already
5703 * dropped to zero at the first pass.
5704 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005705 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
Mel Gorman1a501902014-06-04 16:10:49 -07005706 sc->priority == DEF_PRIORITY);
5707
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005708 blk_start_plug(&plug);
5709 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5710 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005711 unsigned long nr_anon, nr_file, percentage;
5712 unsigned long nr_scanned;
5713
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005714 for_each_evictable_lru(lru) {
5715 if (nr[lru]) {
5716 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5717 nr[lru] -= nr_to_scan;
5718
5719 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005720 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005721 }
5722 }
Mel Gormane82e0562013-07-03 15:01:44 -07005723
Michal Hockobd041732016-12-02 17:26:48 -08005724 cond_resched();
5725
Mel Gormane82e0562013-07-03 15:01:44 -07005726 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
5727 continue;
5728
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005729 /*
Mel Gormane82e0562013-07-03 15:01:44 -07005730 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07005731 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07005732 * proportionally what was requested by get_scan_count(). We
5733 * stop reclaiming one LRU and reduce the amount scanning
5734 * proportional to the original scan target.
5735 */
5736 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5737 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5738
Mel Gorman1a501902014-06-04 16:10:49 -07005739 /*
5740 * It's just vindictive to attack the larger once the smaller
5741 * has gone to zero. And given the way we stop scanning the
5742 * smaller below, this makes sure that we only make one nudge
5743 * towards proportionality once we've got nr_to_reclaim.
5744 */
5745 if (!nr_file || !nr_anon)
5746 break;
5747
Mel Gormane82e0562013-07-03 15:01:44 -07005748 if (nr_file > nr_anon) {
5749 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5750 targets[LRU_ACTIVE_ANON] + 1;
5751 lru = LRU_BASE;
5752 percentage = nr_anon * 100 / scan_target;
5753 } else {
5754 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5755 targets[LRU_ACTIVE_FILE] + 1;
5756 lru = LRU_FILE;
5757 percentage = nr_file * 100 / scan_target;
5758 }
5759
5760 /* Stop scanning the smaller of the LRU */
5761 nr[lru] = 0;
5762 nr[lru + LRU_ACTIVE] = 0;
5763
5764 /*
5765 * Recalculate the other LRU scan count based on its original
5766 * scan target and the percentage scanning already complete
5767 */
5768 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5769 nr_scanned = targets[lru] - nr[lru];
5770 nr[lru] = targets[lru] * (100 - percentage) / 100;
5771 nr[lru] -= min(nr[lru], nr_scanned);
5772
5773 lru += LRU_ACTIVE;
5774 nr_scanned = targets[lru] - nr[lru];
5775 nr[lru] = targets[lru] * (100 - percentage) / 100;
5776 nr[lru] -= min(nr[lru], nr_scanned);
5777
5778 scan_adjusted = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005779 }
5780 blk_finish_plug(&plug);
5781 sc->nr_reclaimed += nr_reclaimed;
5782
5783 /*
5784 * Even if we did not try to evict anon pages at all, we want to
5785 * rebalance the anon lru active/inactive ratio.
5786 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005787 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5788 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005789 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5790 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005791}
5792
Mel Gorman23b9da52012-05-29 15:06:20 -07005793/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005794static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005795{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005796 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005797 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005798 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005799 return true;
5800
5801 return false;
5802}
5803
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005804/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005805 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5806 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5807 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005808 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005809 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005810 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005811static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005812 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005813 struct scan_control *sc)
5814{
5815 unsigned long pages_for_compaction;
5816 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005817 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005818
5819 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005820 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005821 return false;
5822
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005823 /*
5824 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5825 * number of pages that were scanned. This will return to the caller
5826 * with the risk reclaim/compaction and the resulting allocation attempt
5827 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5828 * allocations through requiring that the full LRU list has been scanned
5829 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5830 * scan, but that approximation was wrong, and there were corner cases
5831 * where always a non-zero amount of pages were scanned.
5832 */
5833 if (!nr_reclaimed)
5834 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005835
Mel Gorman3e7d3442011-01-13 15:45:56 -08005836 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005837 for (z = 0; z <= sc->reclaim_idx; z++) {
5838 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005839 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005840 continue;
5841
5842 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005843 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005844 case COMPACT_CONTINUE:
5845 return false;
5846 default:
5847 /* check next zone */
5848 ;
5849 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005850 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005851
5852 /*
5853 * If we have not reclaimed enough pages for compaction and the
5854 * inactive lists are large enough, continue reclaiming
5855 */
5856 pages_for_compaction = compact_gap(sc->order);
5857 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005858 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005859 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5860
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005861 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005862}
5863
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005864static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005865{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005866 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005867 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005868
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005869 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005870 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005871 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005872 unsigned long reclaimed;
5873 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005874 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08005875
Xunlei Pange3336ca2020-09-04 16:35:27 -07005876 /*
5877 * This loop can become CPU-bound when target memcgs
5878 * aren't eligible for reclaim - either because they
5879 * don't have any reclaimable pages, or because their
5880 * memory is explicitly protected. Avoid soft lockups.
5881 */
5882 cond_resched();
5883
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005884 trace_android_vh_shrink_node_memcgs(memcg, &skip);
5885 if (skip)
5886 continue;
5887
Chris Down45c7f7e2020-08-06 23:22:05 -07005888 mem_cgroup_calculate_protection(target_memcg, memcg);
5889
5890 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005891 /*
5892 * Hard protection.
5893 * If there is no reclaimable memory, OOM.
5894 */
5895 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005896 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005897 /*
5898 * Soft protection.
5899 * Respect the protection only as long as
5900 * there is an unprotected supply
5901 * of reclaimable memory from other cgroups.
5902 */
5903 if (!sc->memcg_low_reclaim) {
5904 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005905 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005906 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005907 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005908 }
5909
Johannes Weinerd2af3392019-11-30 17:55:43 -08005910 reclaimed = sc->nr_reclaimed;
5911 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005912
5913 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005914
Johannes Weinerd2af3392019-11-30 17:55:43 -08005915 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5916 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005917
Johannes Weinerd2af3392019-11-30 17:55:43 -08005918 /* Record the group's reclaim efficiency */
5919 vmpressure(sc->gfp_mask, memcg, false,
5920 sc->nr_scanned - scanned,
5921 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005922
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005923 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5924}
5925
Liu Song6c9e09072020-01-30 22:14:08 -08005926static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005927{
5928 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005929 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005930 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005931 bool reclaimable = false;
5932
Johannes Weiner1b051172019-11-30 17:55:52 -08005933 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5934
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005935again:
5936 memset(&sc->nr, 0, sizeof(sc->nr));
5937
5938 nr_reclaimed = sc->nr_reclaimed;
5939 nr_scanned = sc->nr_scanned;
5940
Yu Zhao6d313442022-09-18 02:00:00 -06005941 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005942
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005943 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005944
Johannes Weinerd2af3392019-11-30 17:55:43 -08005945 if (reclaim_state) {
5946 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5947 reclaim_state->reclaimed_slab = 0;
5948 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005949
Johannes Weinerd2af3392019-11-30 17:55:43 -08005950 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005951 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005952 sc->nr_scanned - nr_scanned,
5953 sc->nr_reclaimed - nr_reclaimed);
5954
5955 if (sc->nr_reclaimed - nr_reclaimed)
5956 reclaimable = true;
5957
5958 if (current_is_kswapd()) {
5959 /*
5960 * If reclaim is isolating dirty pages under writeback,
5961 * it implies that the long-lived page allocation rate
5962 * is exceeding the page laundering rate. Either the
5963 * global limits are not being effective at throttling
5964 * processes due to the page distribution throughout
5965 * zones or there is heavy usage of a slow backing
5966 * device. The only option is to throttle from reclaim
5967 * context which is not ideal as there is no guarantee
5968 * the dirtying process is throttled in the same way
5969 * balance_dirty_pages() manages.
5970 *
5971 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5972 * count the number of pages under pages flagged for
5973 * immediate reclaim and stall if any are encountered
5974 * in the nr_immediate check below.
5975 */
5976 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5977 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005978
Johannes Weinerd2af3392019-11-30 17:55:43 -08005979 /* Allow kswapd to start writing pages during reclaim.*/
5980 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5981 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005982
5983 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005984 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005985 * reclaim and under writeback (nr_immediate), it
5986 * implies that pages are cycling through the LRU
5987 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005988 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005989 if (sc->nr.immediate)
5990 congestion_wait(BLK_RW_ASYNC, HZ/10);
5991 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005992
Johannes Weinerd2af3392019-11-30 17:55:43 -08005993 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005994 * Tag a node/memcg as congested if all the dirty pages
5995 * scanned were backed by a congested BDI and
5996 * wait_iff_congested will stall.
5997 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005998 * Legacy memcg will stall in page writeback so avoid forcibly
5999 * stalling in wait_iff_congested().
6000 */
Johannes Weiner1b051172019-11-30 17:55:52 -08006001 if ((current_is_kswapd() ||
6002 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08006003 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08006004 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08006005
6006 /*
6007 * Stall direct reclaim for IO completions if underlying BDIs
6008 * and node is congested. Allow kswapd to continue until it
6009 * starts encountering unqueued dirty pages or cycling through
6010 * the LRU too quickly.
6011 */
Johannes Weiner1b051172019-11-30 17:55:52 -08006012 if (!current_is_kswapd() && current_may_throttle() &&
6013 !sc->hibernation_mode &&
6014 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08006015 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
6016
6017 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
6018 sc))
6019 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07006020
Johannes Weinerc73322d2017-05-03 14:51:51 -07006021 /*
6022 * Kswapd gives up on balancing particular nodes after too
6023 * many failures to reclaim anything from them and goes to
6024 * sleep. On reclaim progress, reset the failure counter. A
6025 * successful direct reclaim run will revive a dormant kswapd.
6026 */
6027 if (reclaimable)
6028 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006029}
6030
Vlastimil Babka53853e22014-10-09 15:27:02 -07006031/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006032 * Returns true if compaction should go ahead for a costly-order request, or
6033 * the allocation would already succeed without compaction. Return false if we
6034 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07006035 */
Mel Gorman4f588332016-07-28 15:46:38 -07006036static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006037{
Mel Gorman31483b62016-07-28 15:45:46 -07006038 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006039 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006040
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006041 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
6042 if (suitable == COMPACT_SUCCESS)
6043 /* Allocation should succeed already. Don't reclaim. */
6044 return true;
6045 if (suitable == COMPACT_SKIPPED)
6046 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006047 return false;
6048
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07006049 /*
6050 * Compaction is already possible, but it takes time to run and there
6051 * are potentially other callers using the pages just freed. So proceed
6052 * with reclaim to make a buffer of free pages available to give
6053 * compaction a reasonable chance of completing and allocating the page.
6054 * Note that we won't actually reclaim the whole buffer in one attempt
6055 * as the target watermark in should_continue_reclaim() is lower. But if
6056 * we are already above the high+gap watermark, don't reclaim at all.
6057 */
6058 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
6059
6060 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08006061}
6062
Linus Torvalds1da177e2005-04-16 15:20:36 -07006063/*
6064 * This is the direct reclaim path, for page-allocating processes. We only
6065 * try to reclaim pages from zones which will satisfy the caller's allocation
6066 * request.
6067 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07006068 * If a zone is deemed to be full of pinned pages then just give it a light
6069 * scan then give up on it.
6070 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07006071static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006072{
Mel Gormandd1a2392008-04-28 02:12:17 -07006073 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07006074 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07006075 unsigned long nr_soft_reclaimed;
6076 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07006077 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07006078 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006079
Mel Gormancc715d92012-03-21 16:34:00 -07006080 /*
6081 * If the number of buffer_heads in the machine exceeds the maximum
6082 * allowed level, force direct reclaim to scan the highmem zone as
6083 * highmem pages could be pinning lowmem pages storing buffer_heads
6084 */
Weijie Yang619d0d762014-04-07 15:36:59 -07006085 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07006086 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07006087 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07006088 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07006089 }
Mel Gormancc715d92012-03-21 16:34:00 -07006090
Mel Gormand4debc62010-08-09 17:19:29 -07006091 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07006092 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07006093 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006094 * Take care memory controller reclaiming has small influence
6095 * to global LRU.
6096 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08006097 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04006098 if (!cpuset_zone_allowed(zone,
6099 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006100 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006101
Johannes Weiner0b064962014-08-06 16:06:12 -07006102 /*
6103 * If we already have plenty of memory free for
6104 * compaction in this zone, don't free any more.
6105 * Even though compaction is invoked for any
6106 * non-zero order, only frequent costly order
6107 * reclamation is disruptive enough to become a
6108 * noticeable problem, like transparent huge
6109 * page allocations.
6110 */
6111 if (IS_ENABLED(CONFIG_COMPACTION) &&
6112 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07006113 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07006114 sc->compaction_ready = true;
6115 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07006116 }
Johannes Weiner0b064962014-08-06 16:06:12 -07006117
Andrew Morton0608f432013-09-24 15:27:41 -07006118 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07006119 * Shrink each node in the zonelist once. If the
6120 * zonelist is ordered by zone (not the default) then a
6121 * node may be shrunk multiple times but in that case
6122 * the user prefers lower zones being preserved.
6123 */
6124 if (zone->zone_pgdat == last_pgdat)
6125 continue;
6126
6127 /*
Andrew Morton0608f432013-09-24 15:27:41 -07006128 * This steals pages from memory cgroups over softlimit
6129 * and returns the number of reclaimed pages and
6130 * scanned pages. This works for global memory pressure
6131 * and balancing, not for a memcg's limit.
6132 */
6133 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006134 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07006135 sc->order, sc->gfp_mask,
6136 &nr_soft_scanned);
6137 sc->nr_reclaimed += nr_soft_reclaimed;
6138 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07006139 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08006140 }
Nick Piggin408d8542006-09-25 23:31:27 -07006141
Mel Gorman79dafcd2016-07-28 15:45:53 -07006142 /* See comment about same check for global reclaim above */
6143 if (zone->zone_pgdat == last_pgdat)
6144 continue;
6145 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07006146 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006147 }
Mel Gormane0c23272011-10-31 17:09:33 -07006148
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07006149 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07006150 * Restore to original mask to avoid the impact on the caller if we
6151 * promoted it to __GFP_HIGHMEM.
6152 */
6153 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006154}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006155
Johannes Weinerb9107182019-11-30 17:55:59 -08006156static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006157{
Johannes Weinerb9107182019-11-30 17:55:59 -08006158 struct lruvec *target_lruvec;
6159 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006160
Yu Zhao37397872022-09-18 02:00:03 -06006161 if (lru_gen_enabled())
6162 return;
6163
Johannes Weinerb9107182019-11-30 17:55:59 -08006164 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07006165 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
6166 target_lruvec->refaults[0] = refaults;
6167 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
6168 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006169}
6170
Linus Torvalds1da177e2005-04-16 15:20:36 -07006171/*
6172 * This is the main entry point to direct page reclaim.
6173 *
6174 * If a full scan of the inactive list fails to free enough memory then we
6175 * are "out of memory" and something needs to be killed.
6176 *
6177 * If the caller is !__GFP_FS then the probability of a failure is reasonably
6178 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02006179 * caller can't do much about. We kick the writeback threads and take explicit
6180 * naps in the hope that some of these pages can be written. But if the
6181 * allocating task holds filesystem locks which prevent writeout this might not
6182 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07006183 *
6184 * returns: 0, if no pages reclaimed
6185 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07006186 */
Mel Gormandac1d272008-04-28 02:12:12 -07006187static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006188 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006189{
Johannes Weiner241994ed2015-02-11 15:26:06 -08006190 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006191 pg_data_t *last_pgdat;
6192 struct zoneref *z;
6193 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006194retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07006195 delayacct_freepages_start();
6196
Johannes Weinerb5ead352019-11-30 17:55:40 -08006197 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07006198 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006199
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006200 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07006201 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
6202 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08006203 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07006204 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07006205
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006206 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07006207 break;
6208
6209 if (sc->compaction_ready)
6210 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006211
6212 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08006213 * If we're getting trouble reclaiming, start doing
6214 * writepage even in laptop mode.
6215 */
6216 if (sc->priority < DEF_PRIORITY - 2)
6217 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07006218 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006219
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006220 last_pgdat = NULL;
6221 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
6222 sc->nodemask) {
6223 if (zone->zone_pgdat == last_pgdat)
6224 continue;
6225 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08006226
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006227 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08006228
6229 if (cgroup_reclaim(sc)) {
6230 struct lruvec *lruvec;
6231
6232 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
6233 zone->zone_pgdat);
6234 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
6235 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006236 }
6237
Keika Kobayashi873b4772008-07-25 01:48:52 -07006238 delayacct_freepages_end();
6239
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006240 if (sc->nr_reclaimed)
6241 return sc->nr_reclaimed;
6242
Mel Gorman0cee34f2012-01-12 17:19:49 -08006243 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07006244 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08006245 return 1;
6246
Johannes Weinerb91ac372019-11-30 17:56:02 -08006247 /*
6248 * We make inactive:active ratio decisions based on the node's
6249 * composition of memory, but a restrictive reclaim_idx or a
6250 * memory.low cgroup setting can exempt large amounts of
6251 * memory from reclaim. Neither of which are very common, so
6252 * instead of doing costly eligibility calculations of the
6253 * entire cgroup subtree up front, we assume the estimates are
6254 * good, and retry with forcible deactivation if that fails.
6255 */
6256 if (sc->skipped_deactivate) {
6257 sc->priority = initial_priority;
6258 sc->force_deactivate = 1;
6259 sc->skipped_deactivate = 0;
6260 goto retry;
6261 }
6262
Johannes Weiner241994ed2015-02-11 15:26:06 -08006263 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07006264 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08006265 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006266 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07006267 sc->memcg_low_reclaim = 1;
6268 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08006269 goto retry;
6270 }
6271
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07006272 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006273}
6274
Johannes Weinerc73322d2017-05-03 14:51:51 -07006275static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07006276{
6277 struct zone *zone;
6278 unsigned long pfmemalloc_reserve = 0;
6279 unsigned long free_pages = 0;
6280 int i;
6281 bool wmark_ok;
6282
Johannes Weinerc73322d2017-05-03 14:51:51 -07006283 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6284 return true;
6285
Mel Gorman55150612012-07-31 16:44:35 -07006286 for (i = 0; i <= ZONE_NORMAL; i++) {
6287 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07006288 if (!managed_zone(zone))
6289 continue;
6290
6291 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07006292 continue;
6293
Mel Gorman55150612012-07-31 16:44:35 -07006294 pfmemalloc_reserve += min_wmark_pages(zone);
6295 free_pages += zone_page_state(zone, NR_FREE_PAGES);
6296 }
6297
Mel Gorman675becc2014-06-04 16:07:35 -07006298 /* If there are no reserves (unexpected config) then do not throttle */
6299 if (!pfmemalloc_reserve)
6300 return true;
6301
Mel Gorman55150612012-07-31 16:44:35 -07006302 wmark_ok = free_pages > pfmemalloc_reserve / 2;
6303
6304 /* kswapd must be awake if processes are being throttled */
6305 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006306 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
6307 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006308
Mel Gorman55150612012-07-31 16:44:35 -07006309 wake_up_interruptible(&pgdat->kswapd_wait);
6310 }
6311
6312 return wmark_ok;
6313}
6314
6315/*
6316 * Throttle direct reclaimers if backing storage is backed by the network
6317 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
6318 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08006319 * when the low watermark is reached.
6320 *
6321 * Returns true if a fatal signal was delivered during throttling. If this
6322 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07006323 */
Mel Gorman50694c22012-11-26 16:29:48 -08006324static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07006325 nodemask_t *nodemask)
6326{
Mel Gorman675becc2014-06-04 16:07:35 -07006327 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07006328 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07006329 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07006330
6331 /*
6332 * Kernel threads should not be throttled as they may be indirectly
6333 * responsible for cleaning pages necessary for reclaim to make forward
6334 * progress. kjournald for example may enter direct reclaim while
6335 * committing a transaction where throttling it could forcing other
6336 * processes to block on log_wait_commit().
6337 */
6338 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08006339 goto out;
6340
6341 /*
6342 * If a fatal signal is pending, this process should not throttle.
6343 * It should return quickly so it can exit and free its memory
6344 */
6345 if (fatal_signal_pending(current))
6346 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006347
Mel Gorman675becc2014-06-04 16:07:35 -07006348 /*
6349 * Check if the pfmemalloc reserves are ok by finding the first node
6350 * with a usable ZONE_NORMAL or lower zone. The expectation is that
6351 * GFP_KERNEL will be required for allocating network buffers when
6352 * swapping over the network so ZONE_HIGHMEM is unusable.
6353 *
6354 * Throttling is based on the first usable node and throttled processes
6355 * wait on a queue until kswapd makes progress and wakes them. There
6356 * is an affinity then between processes waking up and where reclaim
6357 * progress has been made assuming the process wakes on the same node.
6358 * More importantly, processes running on remote nodes will not compete
6359 * for remote pfmemalloc reserves and processes on different nodes
6360 * should make reasonable progress.
6361 */
6362 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08006363 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07006364 if (zone_idx(zone) > ZONE_NORMAL)
6365 continue;
6366
6367 /* Throttle based on the first usable node */
6368 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07006369 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07006370 goto out;
6371 break;
6372 }
6373
6374 /* If no zone was usable by the allocation flags then do not throttle */
6375 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08006376 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07006377
Mel Gorman68243e72012-07-31 16:44:39 -07006378 /* Account for the throttling */
6379 count_vm_event(PGSCAN_DIRECT_THROTTLE);
6380
Mel Gorman55150612012-07-31 16:44:35 -07006381 /*
6382 * If the caller cannot enter the filesystem, it's possible that it
6383 * is due to the caller holding an FS lock or performing a journal
6384 * transaction in the case of a filesystem like ext[3|4]. In this case,
6385 * it is not safe to block on pfmemalloc_wait as kswapd could be
6386 * blocked waiting on the same lock. Instead, throttle for up to a
6387 * second before continuing.
6388 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07006389 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07006390 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07006391 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07006392 else
6393 /* Throttle until kswapd wakes the process */
6394 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
6395 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08006396
Mel Gorman50694c22012-11-26 16:29:48 -08006397 if (fatal_signal_pending(current))
6398 return true;
6399
6400out:
6401 return false;
Mel Gorman55150612012-07-31 16:44:35 -07006402}
6403
Mel Gormandac1d272008-04-28 02:12:12 -07006404unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07006405 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08006406{
Mel Gorman33906bc2010-08-09 17:19:16 -07006407 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006408 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08006409 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006410 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07006411 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07006412 .order = order,
6413 .nodemask = nodemask,
6414 .priority = DEF_PRIORITY,
6415 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006416 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07006417 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08006418 };
6419
Mel Gorman55150612012-07-31 16:44:35 -07006420 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07006421 * scan_control uses s8 fields for order, priority, and reclaim_idx.
6422 * Confirm they are large enough for max values.
6423 */
6424 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
6425 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
6426 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
6427
6428 /*
Mel Gorman50694c22012-11-26 16:29:48 -08006429 * Do not enter reclaim if fatal signal was delivered while throttled.
6430 * 1 is returned so that the page allocator does not OOM kill at this
6431 * point.
Mel Gorman55150612012-07-31 16:44:35 -07006432 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006433 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07006434 return 1;
6435
Andrew Morton1732d2b012019-07-16 16:26:15 -07006436 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006437 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07006438
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006439 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07006440
6441 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006442 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07006443
6444 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006445}
6446
Andrew Mortonc255a452012-07-31 16:43:02 -07006447#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08006448
Michal Hockod2e5fb92019-08-30 16:04:50 -07006449/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07006450unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006451 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07006452 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07006453 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07006454{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006455 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07006456 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07006457 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07006458 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07006459 .may_writepage = !laptop_mode,
6460 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07006461 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07006462 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07006463 };
Ying Han0ae5e892011-05-26 16:25:25 -07006464
Michal Hockod2e5fb92019-08-30 16:04:50 -07006465 WARN_ON_ONCE(!current->reclaim_state);
6466
Balbir Singh4e416952009-09-23 15:56:39 -07006467 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
6468 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006469
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006470 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07006471 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006472
Balbir Singh4e416952009-09-23 15:56:39 -07006473 /*
6474 * NOTE: Although we can get the priority field, using it
6475 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07006476 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07006477 * will pick up pages from other mem cgroup's as well. We hack
6478 * the priority and make it zero.
6479 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08006480 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006481
6482 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
6483
Ying Han0ae5e892011-05-26 16:25:25 -07006484 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07006485
Balbir Singh4e416952009-09-23 15:56:39 -07006486 return sc.nr_reclaimed;
6487}
6488
Johannes Weiner72835c82012-01-12 17:18:32 -08006489unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006490 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08006491 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006492 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08006493{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006494 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006495 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08006496 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006497 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07006498 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07006499 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07006500 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07006501 .target_mem_cgroup = memcg,
6502 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08006503 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006504 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07006505 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07006506 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08006507 /*
6508 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
6509 * equal pressure on all the nodes. This is based on the assumption that
6510 * the reclaim does not bail out early.
6511 */
6512 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08006513
Andrew Morton1732d2b012019-07-16 16:26:15 -07006514 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07006515 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006516 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07006517
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006518 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07006519
Vlastimil Babka499118e2017-05-08 15:59:50 -07006520 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006521 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006522 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07006523
6524 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006525}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006526EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006527#endif
6528
Yu Zhao37397872022-09-18 02:00:03 -06006529static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006530{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006531 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006532 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006533
Yu Zhao37397872022-09-18 02:00:03 -06006534 if (lru_gen_enabled()) {
6535 lru_gen_age_node(pgdat, sc);
6536 return;
6537 }
6538
Dave Hansen2f368a92021-09-02 14:59:23 -07006539 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006540 return;
6541
Johannes Weinerb91ac372019-11-30 17:56:02 -08006542 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6543 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6544 return;
6545
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006546 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6547 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006548 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6549 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6550 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006551 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6552 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006553}
6554
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006555static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006556{
6557 int i;
6558 struct zone *zone;
6559
6560 /*
6561 * Check for watermark boosts top-down as the higher zones
6562 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006563 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006564 * start prematurely when there is no boosting and a lower
6565 * zone is balanced.
6566 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006567 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006568 zone = pgdat->node_zones + i;
6569 if (!managed_zone(zone))
6570 continue;
6571
6572 if (zone->watermark_boost)
6573 return true;
6574 }
6575
6576 return false;
6577}
6578
Mel Gormane716f2e2017-05-03 14:53:45 -07006579/*
6580 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006581 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006582 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006583static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006584{
Mel Gormane716f2e2017-05-03 14:53:45 -07006585 int i;
6586 unsigned long mark = -1;
6587 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006588
Mel Gorman1c308442018-12-28 00:35:52 -08006589 /*
6590 * Check watermarks bottom-up as lower zones are more likely to
6591 * meet watermarks.
6592 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006593 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006594 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006595
Mel Gormane716f2e2017-05-03 14:53:45 -07006596 if (!managed_zone(zone))
6597 continue;
6598
6599 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006600 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006601 return true;
6602 }
6603
6604 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006605 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006606 * need balancing by definition. This can happen if a zone-restricted
6607 * allocation tries to wake a remote kswapd.
6608 */
6609 if (mark == -1)
6610 return true;
6611
6612 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006613}
6614
Mel Gorman631b6e02017-05-03 14:53:41 -07006615/* Clear pgdat state for congested, dirty or under writeback. */
6616static void clear_pgdat_congested(pg_data_t *pgdat)
6617{
Johannes Weiner1b051172019-11-30 17:55:52 -08006618 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6619
6620 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006621 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6622 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6623}
6624
Mel Gorman1741c872011-01-13 15:46:21 -08006625/*
Mel Gorman55150612012-07-31 16:44:35 -07006626 * Prepare kswapd for sleeping. This verifies that there are no processes
6627 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6628 *
6629 * Returns true if kswapd is ready to sleep
6630 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006631static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6632 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006633{
Mel Gorman55150612012-07-31 16:44:35 -07006634 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006635 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006636 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006637 * race between when kswapd checks the watermarks and a process gets
6638 * throttled. There is also a potential race if processes get
6639 * throttled, kswapd wakes, a large process exits thereby balancing the
6640 * zones, which causes kswapd to exit balance_pgdat() before reaching
6641 * the wake up checks. If kswapd is going to sleep, no process should
6642 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6643 * the wake up is premature, processes will wake kswapd and get
6644 * throttled again. The difference from wake ups in balance_pgdat() is
6645 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006646 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006647 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6648 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006649
Johannes Weinerc73322d2017-05-03 14:51:51 -07006650 /* Hopeless node, leave it to direct reclaim */
6651 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6652 return true;
6653
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006654 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006655 clear_pgdat_congested(pgdat);
6656 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006657 }
6658
Shantanu Goel333b0a42017-05-03 14:53:38 -07006659 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006660}
6661
Linus Torvalds1da177e2005-04-16 15:20:36 -07006662/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006663 * kswapd shrinks a node of pages that are at or below the highest usable
6664 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006665 *
6666 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006667 * reclaim or if the lack of progress was due to pages under writeback.
6668 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006669 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006670static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006671 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006672{
Mel Gorman1d82de62016-07-28 15:45:43 -07006673 struct zone *zone;
6674 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006675
Mel Gorman1d82de62016-07-28 15:45:43 -07006676 /* Reclaim a number of pages proportional to the number of zones */
6677 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006678 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006679 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006680 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006681 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006682
Mel Gorman1d82de62016-07-28 15:45:43 -07006683 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006684 }
6685
Mel Gorman1d82de62016-07-28 15:45:43 -07006686 /*
6687 * Historically care was taken to put equal pressure on all zones but
6688 * now pressure is applied based on node LRU order.
6689 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006690 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006691
6692 /*
6693 * Fragmentation may mean that the system cannot be rebalanced for
6694 * high-order allocations. If twice the allocation size has been
6695 * reclaimed then recheck watermarks only at order-0 to prevent
6696 * excessive reclaim. Assume that a process requested a high-order
6697 * can direct reclaim/compact.
6698 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006699 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006700 sc->order = 0;
6701
Mel Gormanb8e83b92013-07-03 15:01:45 -07006702 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006703}
6704
Mel Gormanc49c2c42021-06-28 19:42:21 -07006705/* Page allocator PCP high watermark is lowered if reclaim is active. */
6706static inline void
6707update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6708{
6709 int i;
6710 struct zone *zone;
6711
6712 for (i = 0; i <= highest_zoneidx; i++) {
6713 zone = pgdat->node_zones + i;
6714
6715 if (!managed_zone(zone))
6716 continue;
6717
6718 if (active)
6719 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6720 else
6721 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6722 }
6723}
6724
6725static inline void
6726set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6727{
6728 update_reclaim_active(pgdat, highest_zoneidx, true);
6729}
6730
6731static inline void
6732clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6733{
6734 update_reclaim_active(pgdat, highest_zoneidx, false);
6735}
6736
Mel Gorman75485362013-07-03 15:01:42 -07006737/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006738 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6739 * that are eligible for use by the caller until at least one zone is
6740 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006741 *
Mel Gorman1d82de62016-07-28 15:45:43 -07006742 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006743 *
6744 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07006745 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08006746 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07006747 * or lower is eligible for reclaim until at least one usable zone is
6748 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006749 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006750static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006751{
Linus Torvalds1da177e2005-04-16 15:20:36 -07006752 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07006753 unsigned long nr_soft_reclaimed;
6754 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07006755 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08006756 unsigned long nr_boost_reclaim;
6757 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6758 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07006759 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08006760 struct scan_control sc = {
6761 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07006762 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006763 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08006764 };
Omar Sandoval93781322018-06-07 17:07:02 -07006765
Andrew Morton1732d2b012019-07-16 16:26:15 -07006766 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07006767 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006768 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006769
Christoph Lameterf8891e52006-06-30 01:55:45 -07006770 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006771
Mel Gorman1c308442018-12-28 00:35:52 -08006772 /*
6773 * Account for the reclaim boost. Note that the zone boost is left in
6774 * place so that parallel allocations that are near the watermark will
6775 * stall or direct reclaim until kswapd is finished.
6776 */
6777 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006778 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006779 zone = pgdat->node_zones + i;
6780 if (!managed_zone(zone))
6781 continue;
6782
6783 nr_boost_reclaim += zone->watermark_boost;
6784 zone_boosts[i] = zone->watermark_boost;
6785 }
6786 boosted = nr_boost_reclaim;
6787
6788restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006789 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006790 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006791 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006792 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006793 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006794 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006795 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006796
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006797 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006798
Mel Gorman86c79f62016-07-28 15:45:59 -07006799 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006800 * If the number of buffer_heads exceeds the maximum allowed
6801 * then consider reclaiming from all zones. This has a dual
6802 * purpose -- on 64-bit systems it is expected that
6803 * buffer_heads are stripped during active rotation. On 32-bit
6804 * systems, highmem pages can pin lowmem memory and shrinking
6805 * buffers can relieve lowmem pressure. Reclaim may still not
6806 * go ahead if all eligible zones for the original allocation
6807 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006808 */
6809 if (buffer_heads_over_limit) {
6810 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6811 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006812 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006813 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006814
Mel Gorman970a39a2016-07-28 15:46:35 -07006815 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006816 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006817 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006818 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006819
Mel Gorman86c79f62016-07-28 15:45:59 -07006820 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006821 * If the pgdat is imbalanced then ignore boosting and preserve
6822 * the watermarks for a later time and restart. Note that the
6823 * zone watermarks will be still reset at the end of balancing
6824 * on the grounds that the normal reclaim should be enough to
6825 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006826 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006827 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006828 if (!balanced && nr_boost_reclaim) {
6829 nr_boost_reclaim = 0;
6830 goto restart;
6831 }
6832
6833 /*
6834 * If boosting is not active then only reclaim if there are no
6835 * eligible zones. Note that sc.reclaim_idx is not used as
6836 * buffer_heads_over_limit may have adjusted it.
6837 */
6838 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006839 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006840
Mel Gorman1c308442018-12-28 00:35:52 -08006841 /* Limit the priority of boosting to avoid reclaim writeback */
6842 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6843 raise_priority = false;
6844
6845 /*
6846 * Do not writeback or swap pages for boosted reclaim. The
6847 * intent is to relieve pressure not issue sub-optimal IO
6848 * from reclaim context. If no pages are reclaimed, the
6849 * reclaim will be aborted.
6850 */
6851 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6852 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006853
Linus Torvalds1da177e2005-04-16 15:20:36 -07006854 /*
Yu Zhao37397872022-09-18 02:00:03 -06006855 * Do some background aging, to give pages a chance to be
6856 * referenced before reclaiming. All pages are rotated
6857 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07006858 */
Yu Zhao37397872022-09-18 02:00:03 -06006859 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006860
6861 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006862 * If we're getting trouble reclaiming, start doing writepage
6863 * even in laptop mode.
6864 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006865 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006866 sc.may_writepage = 1;
6867
Mel Gorman1d82de62016-07-28 15:45:43 -07006868 /* Call soft limit reclaim before calling shrink_node. */
6869 sc.nr_scanned = 0;
6870 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006871 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006872 sc.gfp_mask, &nr_soft_scanned);
6873 sc.nr_reclaimed += nr_soft_reclaimed;
6874
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006875 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006876 * There should be no need to raise the scanning priority if
6877 * enough pages are already being scanned that that high
6878 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006879 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006880 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006881 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006882
6883 /*
6884 * If the low watermark is met there is no need for processes
6885 * to be throttled on pfmemalloc_wait as they should not be
6886 * able to safely make forward progress. Wake them
6887 */
6888 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006889 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006890 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006891
Mel Gormanb8e83b92013-07-03 15:01:45 -07006892 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006893 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006894 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006895 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006896 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006897 break;
6898
6899 /*
6900 * Raise priority if scanning rate is too low or there was no
6901 * progress in reclaiming pages
6902 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006903 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006904 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6905
6906 /*
6907 * If reclaim made no progress for a boost, stop reclaim as
6908 * IO cannot be queued and it could be an infinite loop in
6909 * extreme circumstances.
6910 */
6911 if (nr_boost_reclaim && !nr_reclaimed)
6912 break;
6913
Johannes Weinerc73322d2017-05-03 14:51:51 -07006914 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006915 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006916 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006917
Johannes Weinerc73322d2017-05-03 14:51:51 -07006918 if (!sc.nr_reclaimed)
6919 pgdat->kswapd_failures++;
6920
Mel Gormanb8e83b92013-07-03 15:01:45 -07006921out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006922 clear_reclaim_active(pgdat, highest_zoneidx);
6923
Mel Gorman1c308442018-12-28 00:35:52 -08006924 /* If reclaim was boosted, account for the reclaim done in this pass */
6925 if (boosted) {
6926 unsigned long flags;
6927
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006928 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006929 if (!zone_boosts[i])
6930 continue;
6931
6932 /* Increments are under the zone lock */
6933 zone = pgdat->node_zones + i;
6934 spin_lock_irqsave(&zone->lock, flags);
6935 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6936 spin_unlock_irqrestore(&zone->lock, flags);
6937 }
6938
6939 /*
6940 * As there is now likely space, wakeup kcompact to defragment
6941 * pageblocks.
6942 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006943 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006944 }
6945
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006946 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006947 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006948 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006949 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006950
Mel Gorman0abdee22011-01-13 15:46:22 -08006951 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006952 * Return the order kswapd stopped reclaiming at as
6953 * prepare_kswapd_sleep() takes it into account. If another caller
6954 * entered the allocator slow path while kswapd was awake, order will
6955 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006956 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006957 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006958}
6959
Mel Gormane716f2e2017-05-03 14:53:45 -07006960/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006961 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6962 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6963 * not a valid index then either kswapd runs for first time or kswapd couldn't
6964 * sleep after previous reclaim attempt (node is still unbalanced). In that
6965 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006966 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006967static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6968 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006969{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006970 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006971
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006972 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006973}
6974
Mel Gorman38087d92016-07-28 15:45:49 -07006975static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006976 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006977{
6978 long remaining = 0;
6979 DEFINE_WAIT(wait);
6980
6981 if (freezing(current) || kthread_should_stop())
6982 return;
6983
6984 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6985
Shantanu Goel333b0a42017-05-03 14:53:38 -07006986 /*
6987 * Try to sleep for a short interval. Note that kcompactd will only be
6988 * woken if it is possible to sleep for a short interval. This is
6989 * deliberate on the assumption that if reclaim cannot keep an
6990 * eligible zone balanced that it's also unlikely that compaction will
6991 * succeed.
6992 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006993 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006994 /*
6995 * Compaction records what page blocks it recently failed to
6996 * isolate pages from and skips them in the future scanning.
6997 * When kswapd is going to sleep, it is reasonable to assume
6998 * that pages and compaction may succeed so reset the cache.
6999 */
7000 reset_isolation_suitable(pgdat);
7001
7002 /*
7003 * We have freed the memory, now we should compact it to make
7004 * allocation of the requested order possible.
7005 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007006 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07007007
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007008 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07007009
7010 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007011 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07007012 * order. The values will either be from a wakeup request or
7013 * the previous request that slept prematurely.
7014 */
7015 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007016 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
7017 kswapd_highest_zoneidx(pgdat,
7018 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07007019
7020 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
7021 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07007022 }
7023
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007024 finish_wait(&pgdat->kswapd_wait, &wait);
7025 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
7026 }
7027
7028 /*
7029 * After a short sleep, check if it was a premature sleep. If not, then
7030 * go fully to sleep until explicitly woken up.
7031 */
Mel Gormand9f21d42016-07-28 15:46:41 -07007032 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007033 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007034 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
7035
7036 /*
7037 * vmstat counters are not perfectly accurate and the estimated
7038 * value for counters such as NR_FREE_PAGES can deviate from the
7039 * true value by nr_online_cpus * threshold. To avoid the zone
7040 * watermarks being breached while under pressure, we reduce the
7041 * per-cpu vmstat threshold while kswapd is awake and restore
7042 * them before going back to sleep.
7043 */
7044 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07007045
7046 if (!kthread_should_stop())
7047 schedule();
7048
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08007049 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
7050 } else {
7051 if (remaining)
7052 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
7053 else
7054 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
7055 }
7056 finish_wait(&pgdat->kswapd_wait, &wait);
7057}
7058
Linus Torvalds1da177e2005-04-16 15:20:36 -07007059/*
7060 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07007061 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007062 *
7063 * This basically trickles out pages so that we have _some_
7064 * free memory available even if there is no other activity
7065 * that frees anything up. This is needed for things like routing
7066 * etc, where we otherwise might have all activity going on in
7067 * asynchronous contexts that cannot page things out.
7068 *
7069 * If there are applications that are active memory-allocators
7070 * (most normal use), this basically shouldn't matter.
7071 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307072int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007073{
Mel Gormane716f2e2017-05-03 14:53:45 -07007074 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007075 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07007076 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007077 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10307078 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007079
Rusty Russell174596a2009-01-01 10:12:29 +10307080 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07007081 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007082
7083 /*
7084 * Tell the memory management that we're a "memory allocator",
7085 * and that if we need more memory we should get access to it
7086 * regardless (see "__alloc_pages()"). "kswapd" should
7087 * never get caught in the normal page freeing logic.
7088 *
7089 * (Kswapd normally doesn't need memory anyway, but sometimes
7090 * you need a small amount of memory in order to be able to
7091 * page out something else, and this flag essentially protects
7092 * us from recursively trying to free more memory as we're
7093 * trying to free the first piece of memory in the first place).
7094 */
Christoph Lameter930d9152006-01-08 01:00:47 -08007095 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07007096 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07007097
Qian Cai5644e1fb2020-04-01 21:10:12 -07007098 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007099 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007100 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08007101 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07007102
Qian Cai5644e1fb2020-04-01 21:10:12 -07007103 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007104 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7105 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07007106
Mel Gorman38087d92016-07-28 15:45:49 -07007107kswapd_try_sleep:
7108 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007109 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07007110
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007111 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08007112 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007113 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
7114 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007115 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007116 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007117
David Rientjes8fe23e02009-12-14 17:58:33 -08007118 ret = try_to_freeze();
7119 if (kthread_should_stop())
7120 break;
7121
7122 /*
7123 * We can speed up thawing tasks if we don't call balance_pgdat
7124 * after returning from the refrigerator
7125 */
Mel Gorman38087d92016-07-28 15:45:49 -07007126 if (ret)
7127 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07007128
Mel Gorman38087d92016-07-28 15:45:49 -07007129 /*
7130 * Reclaim begins at the requested order but if a high-order
7131 * reclaim fails then kswapd falls back to reclaiming for
7132 * order-0. If that happens, kswapd will consider sleeping
7133 * for the order it finished reclaiming at (reclaim_order)
7134 * but kcompactd is woken to compact for the original
7135 * request (alloc_order).
7136 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007137 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07007138 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007139 reclaim_order = balance_pgdat(pgdat, alloc_order,
7140 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07007141 if (reclaim_order < alloc_order)
7142 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007143 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08007144
Johannes Weiner71abdc12014-06-06 14:35:35 -07007145 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07007146
Linus Torvalds1da177e2005-04-16 15:20:36 -07007147 return 0;
7148}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05307149EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007150
7151/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07007152 * A zone is low on free memory or too fragmented for high-order memory. If
7153 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
7154 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
7155 * has failed or is not needed, still wake up kcompactd if only compaction is
7156 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07007157 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07007158void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007159 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007160{
7161 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07007162 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007163
Mel Gorman6aa303d2016-09-01 16:14:55 -07007164 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007165 return;
7166
David Rientjes5ecd9d42018-04-05 16:25:16 -07007167 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007168 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07007169
Qian Cai5644e1fb2020-04-01 21:10:12 -07007170 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007171 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007172
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007173 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
7174 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07007175
7176 if (READ_ONCE(pgdat->kswapd_order) < order)
7177 WRITE_ONCE(pgdat->kswapd_order, order);
7178
Con Kolivas8d0986e2005-09-13 01:25:07 -07007179 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07007180 return;
Mel Gormane1a55632016-07-28 15:46:26 -07007181
David Rientjes5ecd9d42018-04-05 16:25:16 -07007182 /* Hopeless node, leave it to direct reclaim if possible */
7183 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007184 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
7185 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07007186 /*
7187 * There may be plenty of free memory available, but it's too
7188 * fragmented for high-order allocations. Wake up kcompactd
7189 * and rely on compaction_suitable() to determine if it's
7190 * needed. If it fails, it will defer subsequent attempts to
7191 * ratelimit its work.
7192 */
7193 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007194 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07007195 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07007196 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07007197
Joonsoo Kim97a225e2020-06-03 15:59:01 -07007198 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07007199 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07007200 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007201}
7202
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007203#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07007204/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007205 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007206 * freed pages.
7207 *
7208 * Rather than trying to age LRUs the aim is to preserve the overall
7209 * LRU order by reclaiming preferentially
7210 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07007211 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007212unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07007213{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007214 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007215 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07007216 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07007217 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007218 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07007219 .may_writepage = 1,
7220 .may_unmap = 1,
7221 .may_swap = 1,
7222 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07007223 };
Ying Hana09ed5e2011-05-24 17:12:26 -07007224 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007225 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007226 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007227
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01007228 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07007229 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07007230 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08007231
Vladimir Davydov3115cd92014-04-03 14:47:22 -07007232 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007233
Andrew Morton1732d2b012019-07-16 16:26:15 -07007234 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007235 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007236 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07007237
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08007238 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07007239}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02007240#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07007241
Yasunori Goto3218ae12006-06-27 02:53:33 -07007242/*
7243 * This kswapd start function will be called by init and node-hot-add.
7244 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
7245 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07007246void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007247{
7248 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307249 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007250
7251 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07007252 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007253
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307254 trace_android_vh_kswapd_per_node(nid, &skip, true);
7255 if (skip)
7256 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007257 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
7258 if (IS_ERR(pgdat->kswapd)) {
7259 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02007260 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07007261 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07007262 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07007263 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07007264}
7265
David Rientjes8fe23e02009-12-14 17:58:33 -08007266/*
Jiang Liud8adde12012-07-11 14:01:52 -07007267 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07007268 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08007269 */
7270void kswapd_stop(int nid)
7271{
7272 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307273 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08007274
Charan Teja Reddyd831f072021-02-05 17:47:57 +05307275 trace_android_vh_kswapd_per_node(nid, &skip, false);
7276 if (skip)
7277 return;
Jiang Liud8adde12012-07-11 14:01:52 -07007278 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08007279 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07007280 NODE_DATA(nid)->kswapd = NULL;
7281 }
David Rientjes8fe23e02009-12-14 17:58:33 -08007282}
7283
Linus Torvalds1da177e2005-04-16 15:20:36 -07007284static int __init kswapd_init(void)
7285{
Wei Yang6b700b52020-04-01 21:10:09 -07007286 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08007287
Linus Torvalds1da177e2005-04-16 15:20:36 -07007288 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08007289 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07007290 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07007291 return 0;
7292}
7293
7294module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007295
7296#ifdef CONFIG_NUMA
7297/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007298 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08007299 *
Mel Gormana5f5f912016-07-28 15:46:32 -07007300 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08007301 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007302 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007303int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007304
Dave Hansen51998362021-02-24 12:09:15 -08007305/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007306 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08007307 * of a node considered for each zone_reclaim. 4 scans 1/16th of
7308 * a zone.
7309 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007310#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08007311
Christoph Lameter9eeff232006-01-18 17:42:31 -08007312/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007313 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07007314 * occur.
7315 */
7316int sysctl_min_unmapped_ratio = 1;
7317
7318/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07007319 * If the number of slab pages in a zone grows beyond this percentage then
7320 * slab reclaim needs to occur.
7321 */
7322int sysctl_min_slab_ratio = 5;
7323
Mel Gorman11fb9982016-07-28 15:46:20 -07007324static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007325{
Mel Gorman11fb9982016-07-28 15:46:20 -07007326 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
7327 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
7328 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007329
7330 /*
7331 * It's possible for there to be more file mapped pages than
7332 * accounted for by the pages on the file LRU lists because
7333 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
7334 */
7335 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
7336}
7337
7338/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07007339static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07007340{
Alexandru Moised031a152015-11-05 18:48:08 -08007341 unsigned long nr_pagecache_reclaimable;
7342 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07007343
7344 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007345 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07007346 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07007347 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07007348 * a better estimate
7349 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007350 if (node_reclaim_mode & RECLAIM_UNMAP)
7351 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007352 else
Mel Gormana5f5f912016-07-28 15:46:32 -07007353 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007354
7355 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07007356 if (!(node_reclaim_mode & RECLAIM_WRITE))
7357 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07007358
7359 /* Watch for any possible underflows due to delta */
7360 if (unlikely(delta > nr_pagecache_reclaimable))
7361 delta = nr_pagecache_reclaimable;
7362
7363 return nr_pagecache_reclaimable - delta;
7364}
7365
Christoph Lameter0ff38492006-09-25 23:31:52 -07007366/*
Mel Gormana5f5f912016-07-28 15:46:32 -07007367 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08007368 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007369static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08007370{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08007371 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08007372 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007373 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07007374 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08007375 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08007376 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007377 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07007378 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07007379 .priority = NODE_RECLAIM_PRIORITY,
7380 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
7381 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07007382 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07007383 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08007384 };
Johannes Weiner57f29762021-08-19 19:04:27 -07007385 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007386
Yafang Shao132bb8c2019-05-13 17:17:53 -07007387 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
7388 sc.gfp_mask);
7389
Christoph Lameter9eeff232006-01-18 17:42:31 -08007390 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07007391 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07007392 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08007393 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007394 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08007395 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07007396 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08007397 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07007398 noreclaim_flag = memalloc_noreclaim_save();
7399 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07007400 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08007401
Mel Gormana5f5f912016-07-28 15:46:32 -07007402 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07007403 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07007404 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07007405 * priorities until we have enough memory freed.
7406 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07007407 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07007408 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07007409 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07007410 }
Christoph Lameterc84db232006-02-01 03:05:29 -08007411
Andrew Morton1732d2b012019-07-16 16:26:15 -07007412 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07007413 current->flags &= ~PF_SWAPWRITE;
7414 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07007415 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07007416 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07007417
7418 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
7419
Rik van Riela79311c2009-01-06 14:40:01 -08007420 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08007421}
Andrew Morton179e9632006-03-22 00:08:18 -08007422
Mel Gormana5f5f912016-07-28 15:46:32 -07007423int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08007424{
David Rientjesd773ed62007-10-16 23:26:01 -07007425 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007426
7427 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007428 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07007429 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07007430 *
Christoph Lameter96146342006-07-03 00:24:13 -07007431 * A small portion of unmapped file backed pages is needed for
7432 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07007433 * thrown out if the node is overallocated. So we do not reclaim
7434 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07007435 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08007436 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007437 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07007438 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
7439 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07007440 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08007441
7442 /*
David Rientjesd773ed62007-10-16 23:26:01 -07007443 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08007444 */
Mel Gormand0164ad2015-11-06 16:28:21 -08007445 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07007446 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08007447
7448 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07007449 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08007450 * have associated processors. This will favor the local processor
7451 * over remote processors and spread off node memory allocations
7452 * as wide as possible.
7453 */
Mel Gormana5f5f912016-07-28 15:46:32 -07007454 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
7455 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07007456
Mel Gormana5f5f912016-07-28 15:46:32 -07007457 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
7458 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07007459
Mel Gormana5f5f912016-07-28 15:46:32 -07007460 ret = __node_reclaim(pgdat, gfp_mask, order);
7461 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07007462
Mel Gorman24cf725182009-06-16 15:33:23 -07007463 if (!ret)
7464 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
7465
David Rientjesd773ed62007-10-16 23:26:01 -07007466 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08007467}
Christoph Lameter9eeff232006-01-18 17:42:31 -08007468#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07007469
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007470/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007471 * check_move_unevictable_pages - check pages for evictability and move to
7472 * appropriate zone lru list
7473 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007474 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007475 * Checks pages for evictability, if an evictable page is in the unevictable
7476 * lru list, moves it to the appropriate evictable lru list. This function
7477 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007478 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007479void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007480{
Alex Shi6168d0d2020-12-15 12:34:29 -08007481 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08007482 int pgscanned = 0;
7483 int pgrescued = 0;
7484 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007485
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007486 for (i = 0; i < pvec->nr; i++) {
7487 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007488 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07007489
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007490 if (PageTransTail(page))
7491 continue;
7492
7493 nr_pages = thp_nr_pages(page);
7494 pgscanned += nr_pages;
7495
Alex Shid25b5bd2020-12-15 12:34:16 -08007496 /* block memcg migration during page moving between lru */
7497 if (!TestClearPageLRU(page))
7498 continue;
7499
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08007500 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007501 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08007502 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08007503 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08007504 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07007505 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08007506 }
Alex Shid25b5bd2020-12-15 12:34:16 -08007507 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07007508 }
Hugh Dickins24513262012-01-20 14:34:21 -08007509
Alex Shi6168d0d2020-12-15 12:34:29 -08007510 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08007511 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
7512 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08007513 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08007514 } else if (pgscanned) {
7515 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08007516 }
Hugh Dickins850465792012-01-20 14:34:19 -08007517}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00007518EXPORT_SYMBOL_GPL(check_move_unevictable_pages);