blob: df4753fa3342b0520d2dfc5bd2640515c1a24ac7 [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>
Linus Torvalds1da177e2005-04-16 15:20:36 -070055
56#include <asm/tlbflush.h>
57#include <asm/div64.h>
58
59#include <linux/swapops.h>
Rafael Aquini117aad12013-09-30 13:45:16 -070060#include <linux/balloon_compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070061
Nick Piggin0f8053a2006-03-22 00:08:33 -080062#include "internal.h"
63
Mel Gorman33906bc2010-08-09 17:19:16 -070064#define CREATE_TRACE_POINTS
65#include <trace/events/vmscan.h>
66
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -070067#undef CREATE_TRACE_POINTS
68#include <trace/hooks/vmscan.h>
69
Linus Torvalds1da177e2005-04-16 15:20:36 -070070struct scan_control {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -080071 /* How many pages shrink_list() should reclaim */
72 unsigned long nr_to_reclaim;
73
Johannes Weineree814fe2014-08-06 16:06:19 -070074 /*
75 * Nodemask of nodes allowed by the caller. If NULL, all nodes
76 * are scanned.
77 */
78 nodemask_t *nodemask;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -070079
KOSAKI Motohiro5f53e762010-05-24 14:32:37 -070080 /*
Johannes Weinerf16015f2012-01-12 17:17:52 -080081 * The memory cgroup that hit its limit and as a result is the
82 * primary target of this reclaim invocation.
83 */
84 struct mem_cgroup *target_mem_cgroup;
Balbir Singh66e17072008-02-07 00:13:56 -080085
Johannes Weiner7cf111b2020-06-03 16:03:06 -070086 /*
87 * Scan pressure balancing between anon and file LRUs
88 */
89 unsigned long anon_cost;
90 unsigned long file_cost;
91
Johannes Weinerb91ac372019-11-30 17:56:02 -080092 /* Can active pages be deactivated as part of reclaim? */
93#define DEACTIVATE_ANON 1
94#define DEACTIVATE_FILE 2
95 unsigned int may_deactivate:2;
96 unsigned int force_deactivate:1;
97 unsigned int skipped_deactivate:1;
98
Johannes Weiner1276ad62017-02-24 14:56:11 -080099 /* Writepage batching in laptop mode; RECLAIM_WRITE */
Johannes Weineree814fe2014-08-06 16:06:19 -0700100 unsigned int may_writepage:1;
101
102 /* Can mapped pages be reclaimed? */
103 unsigned int may_unmap:1;
104
105 /* Can pages be swapped as part of reclaim? */
106 unsigned int may_swap:1;
107
Yisheng Xied6622f62017-05-03 14:53:57 -0700108 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700109 * Cgroup memory below memory.low is protected as long as we
110 * don't threaten to OOM. If any cgroup is reclaimed at
111 * reduced force or passed over entirely due to its memory.low
112 * setting (memcg_low_skipped), and nothing is reclaimed as a
113 * result, then go back for one more cycle that reclaims the protected
114 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700115 */
116 unsigned int memcg_low_reclaim:1;
117 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800118
Johannes Weineree814fe2014-08-06 16:06:19 -0700119 unsigned int hibernation_mode:1;
120
121 /* One of the zones is ready for compaction */
122 unsigned int compaction_ready:1;
123
Johannes Weinerb91ac372019-11-30 17:56:02 -0800124 /* There is easily reclaimable cold cache in the current node */
125 unsigned int cache_trim_mode:1;
126
Johannes Weiner53138ce2019-11-30 17:55:56 -0800127 /* The file pages on the current node are dangerously low */
128 unsigned int file_is_tiny:1;
129
Dave Hansen26aa2d12021-09-02 14:59:16 -0700130 /* Always discard instead of demoting to lower tier memory */
131 unsigned int no_demotion:1;
132
Yu Zhaoa8a158a2022-09-18 02:00:06 -0600133#ifdef CONFIG_LRU_GEN
134 /* help kswapd make better choices among multiple memcgs */
135 unsigned int memcgs_need_aging:1;
136 unsigned long last_reclaimed;
137#endif
138
Greg Thelenbb451fd2018-08-17 15:45:19 -0700139 /* Allocation order */
140 s8 order;
141
142 /* Scan (total_size >> priority) pages at once */
143 s8 priority;
144
145 /* The highest zone to isolate pages for reclaim from */
146 s8 reclaim_idx;
147
148 /* This context's GFP mask */
149 gfp_t gfp_mask;
150
Johannes Weineree814fe2014-08-06 16:06:19 -0700151 /* Incremented by the number of inactive pages that were scanned */
152 unsigned long nr_scanned;
153
154 /* Number of pages freed so far during a call to shrink_zones() */
155 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700156
157 struct {
158 unsigned int dirty;
159 unsigned int unqueued_dirty;
160 unsigned int congested;
161 unsigned int writeback;
162 unsigned int immediate;
163 unsigned int file_taken;
164 unsigned int taken;
165 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700166
167 /* for recording the reclaimed slab by now */
168 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700169};
170
Linus Torvalds1da177e2005-04-16 15:20:36 -0700171#ifdef ARCH_HAS_PREFETCHW
172#define prefetchw_prev_lru_page(_page, _base, _field) \
173 do { \
174 if ((_page)->lru.prev != _base) { \
175 struct page *prev; \
176 \
177 prev = lru_to_page(&(_page->lru)); \
178 prefetchw(&prev->_field); \
179 } \
180 } while (0)
181#else
182#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
183#endif
184
185/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700186 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700187 */
188int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700189
Yang Shi0a432dc2019-09-23 15:38:12 -0700190static void set_task_reclaim_state(struct task_struct *task,
191 struct reclaim_state *rs)
192{
193 /* Check for an overwrite */
194 WARN_ON_ONCE(rs && task->reclaim_state);
195
196 /* Check for the nulling of an already-nulled member */
197 WARN_ON_ONCE(!rs && !task->reclaim_state);
198
199 task->reclaim_state = rs;
200}
201
Linus Torvalds1da177e2005-04-16 15:20:36 -0700202static LIST_HEAD(shrinker_list);
203static DECLARE_RWSEM(shrinker_rwsem);
204
Yang Shi0a432dc2019-09-23 15:38:12 -0700205#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700206static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700207
Yang Shi3c6f17e2021-05-04 18:36:33 -0700208/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700209static inline int shrinker_map_size(int nr_items)
210{
211 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
212}
Yang Shi2bfd3632021-05-04 18:36:11 -0700213
Yang Shi3c6f17e2021-05-04 18:36:33 -0700214static inline int shrinker_defer_size(int nr_items)
215{
216 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
217}
218
Yang Shi468ab842021-05-04 18:36:26 -0700219static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
220 int nid)
221{
222 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
223 lockdep_is_held(&shrinker_rwsem));
224}
225
Yang Shie4262c42021-05-04 18:36:23 -0700226static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700227 int map_size, int defer_size,
228 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700229{
Yang Shie4262c42021-05-04 18:36:23 -0700230 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700231 struct mem_cgroup_per_node *pn;
232 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700233 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700234
Yang Shi2bfd3632021-05-04 18:36:11 -0700235 for_each_node(nid) {
236 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700237 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700238 /* Not yet online memcg */
239 if (!old)
240 return 0;
241
242 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
243 if (!new)
244 return -ENOMEM;
245
Yang Shi3c6f17e2021-05-04 18:36:33 -0700246 new->nr_deferred = (atomic_long_t *)(new + 1);
247 new->map = (void *)new->nr_deferred + defer_size;
248
249 /* map: set all old bits, clear all new bits */
250 memset(new->map, (int)0xff, old_map_size);
251 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
252 /* nr_deferred: copy old values, clear all new values */
253 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
254 memset((void *)new->nr_deferred + old_defer_size, 0,
255 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700256
Yang Shie4262c42021-05-04 18:36:23 -0700257 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700258 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700259 }
260
261 return 0;
262}
263
Yang Shie4262c42021-05-04 18:36:23 -0700264void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700265{
266 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700267 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700268 int nid;
269
Yang Shi2bfd3632021-05-04 18:36:11 -0700270 for_each_node(nid) {
271 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700272 info = rcu_dereference_protected(pn->shrinker_info, true);
273 kvfree(info);
274 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700275 }
276}
277
Yang Shie4262c42021-05-04 18:36:23 -0700278int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700279{
Yang Shie4262c42021-05-04 18:36:23 -0700280 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700281 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700282 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700283
Yang Shid27cf2a2021-05-04 18:36:14 -0700284 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700285 map_size = shrinker_map_size(shrinker_nr_max);
286 defer_size = shrinker_defer_size(shrinker_nr_max);
287 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700288 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700289 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
290 if (!info) {
291 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700292 ret = -ENOMEM;
293 break;
294 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700295 info->nr_deferred = (atomic_long_t *)(info + 1);
296 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700297 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700298 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700299 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700300
301 return ret;
302}
303
Yang Shi3c6f17e2021-05-04 18:36:33 -0700304static inline bool need_expand(int nr_max)
305{
306 return round_up(nr_max, BITS_PER_LONG) >
307 round_up(shrinker_nr_max, BITS_PER_LONG);
308}
309
Yang Shie4262c42021-05-04 18:36:23 -0700310static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700311{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700312 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700313 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700314 int map_size, defer_size = 0;
315 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700316 struct mem_cgroup *memcg;
317
Yang Shi3c6f17e2021-05-04 18:36:33 -0700318 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700319 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700320
Yang Shi2bfd3632021-05-04 18:36:11 -0700321 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700322 goto out;
323
324 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700325
Yang Shi3c6f17e2021-05-04 18:36:33 -0700326 map_size = shrinker_map_size(new_nr_max);
327 defer_size = shrinker_defer_size(new_nr_max);
328 old_map_size = shrinker_map_size(shrinker_nr_max);
329 old_defer_size = shrinker_defer_size(shrinker_nr_max);
330
Yang Shi2bfd3632021-05-04 18:36:11 -0700331 memcg = mem_cgroup_iter(NULL, NULL, NULL);
332 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700333 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
334 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700335 if (ret) {
336 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700337 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700338 }
339 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700340out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700341 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700342 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700343
Yang Shi2bfd3632021-05-04 18:36:11 -0700344 return ret;
345}
346
347void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
348{
349 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700350 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700351
352 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700353 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700354 /* Pairs with smp mb in shrink_slab() */
355 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700356 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700357 rcu_read_unlock();
358 }
359}
360
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700361static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700362
363static int prealloc_memcg_shrinker(struct shrinker *shrinker)
364{
365 int id, ret = -ENOMEM;
366
Yang Shi476b30a2021-05-04 18:36:39 -0700367 if (mem_cgroup_disabled())
368 return -ENOSYS;
369
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700370 down_write(&shrinker_rwsem);
371 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700372 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700373 if (id < 0)
374 goto unlock;
375
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700376 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700377 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700378 idr_remove(&shrinker_idr, id);
379 goto unlock;
380 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700381 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700382 shrinker->id = id;
383 ret = 0;
384unlock:
385 up_write(&shrinker_rwsem);
386 return ret;
387}
388
389static void unregister_memcg_shrinker(struct shrinker *shrinker)
390{
391 int id = shrinker->id;
392
393 BUG_ON(id < 0);
394
Yang Shi41ca6682021-05-04 18:36:29 -0700395 lockdep_assert_held(&shrinker_rwsem);
396
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700397 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700398}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700399
Yang Shi86750832021-05-04 18:36:36 -0700400static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
401 struct mem_cgroup *memcg)
402{
403 struct shrinker_info *info;
404
405 info = shrinker_info_protected(memcg, nid);
406 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
407}
408
409static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
410 struct mem_cgroup *memcg)
411{
412 struct shrinker_info *info;
413
414 info = shrinker_info_protected(memcg, nid);
415 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
416}
417
Yang Shia1780152021-05-04 18:36:42 -0700418void reparent_shrinker_deferred(struct mem_cgroup *memcg)
419{
420 int i, nid;
421 long nr;
422 struct mem_cgroup *parent;
423 struct shrinker_info *child_info, *parent_info;
424
425 parent = parent_mem_cgroup(memcg);
426 if (!parent)
427 parent = root_mem_cgroup;
428
429 /* Prevent from concurrent shrinker_info expand */
430 down_read(&shrinker_rwsem);
431 for_each_node(nid) {
432 child_info = shrinker_info_protected(memcg, nid);
433 parent_info = shrinker_info_protected(parent, nid);
434 for (i = 0; i < shrinker_nr_max; i++) {
435 nr = atomic_long_read(&child_info->nr_deferred[i]);
436 atomic_long_add(nr, &parent_info->nr_deferred[i]);
437 }
438 }
439 up_read(&shrinker_rwsem);
440}
441
Johannes Weinerb5ead352019-11-30 17:55:40 -0800442static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800443{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800444 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800445}
Tejun Heo97c93412015-05-22 18:23:36 -0400446
447/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800448 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400449 * @sc: scan_control in question
450 *
451 * The normal page dirty throttling mechanism in balance_dirty_pages() is
452 * completely broken with the legacy memcg and direct stalling in
453 * shrink_page_list() is used for throttling instead, which lacks all the
454 * niceties such as fairness, adaptive pausing, bandwidth proportional
455 * allocation and configurability.
456 *
457 * This function tests whether the vmscan currently in progress can assume
458 * that the normal dirty throttling mechanism is operational.
459 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800460static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400461{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800462 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400463 return true;
464#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800465 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400466 return true;
467#endif
468 return false;
469}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800470#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700471static int prealloc_memcg_shrinker(struct shrinker *shrinker)
472{
Yang Shi476b30a2021-05-04 18:36:39 -0700473 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700474}
475
476static void unregister_memcg_shrinker(struct shrinker *shrinker)
477{
478}
479
Yang Shi86750832021-05-04 18:36:36 -0700480static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
481 struct mem_cgroup *memcg)
482{
483 return 0;
484}
485
486static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
487 struct mem_cgroup *memcg)
488{
489 return 0;
490}
491
Johannes Weinerb5ead352019-11-30 17:55:40 -0800492static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800493{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800494 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800495}
Tejun Heo97c93412015-05-22 18:23:36 -0400496
Johannes Weinerb5ead352019-11-30 17:55:40 -0800497static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400498{
499 return true;
500}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800501#endif
502
Yang Shi86750832021-05-04 18:36:36 -0700503static long xchg_nr_deferred(struct shrinker *shrinker,
504 struct shrink_control *sc)
505{
506 int nid = sc->nid;
507
508 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
509 nid = 0;
510
511 if (sc->memcg &&
512 (shrinker->flags & SHRINKER_MEMCG_AWARE))
513 return xchg_nr_deferred_memcg(nid, shrinker,
514 sc->memcg);
515
516 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
517}
518
519
520static long add_nr_deferred(long nr, struct shrinker *shrinker,
521 struct shrink_control *sc)
522{
523 int nid = sc->nid;
524
525 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
526 nid = 0;
527
528 if (sc->memcg &&
529 (shrinker->flags & SHRINKER_MEMCG_AWARE))
530 return add_nr_deferred_memcg(nr, nid, shrinker,
531 sc->memcg);
532
533 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
534}
535
Dave Hansen26aa2d12021-09-02 14:59:16 -0700536static bool can_demote(int nid, struct scan_control *sc)
537{
Huang Ying20b51af12021-09-02 14:59:33 -0700538 if (!numa_demotion_enabled)
539 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700540 if (sc) {
541 if (sc->no_demotion)
542 return false;
543 /* It is pointless to do demotion in memcg reclaim */
544 if (cgroup_reclaim(sc))
545 return false;
546 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700547 if (next_demotion_node(nid) == NUMA_NO_NODE)
548 return false;
549
Huang Ying20b51af12021-09-02 14:59:33 -0700550 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700551}
552
Keith Buscha2a36482021-09-02 14:59:26 -0700553static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
554 int nid,
555 struct scan_control *sc)
556{
557 if (memcg == NULL) {
558 /*
559 * For non-memcg reclaim, is there
560 * space in any swap device?
561 */
562 if (get_nr_swap_pages() > 0)
563 return true;
564 } else {
565 /* Is the memcg below its swap limit? */
566 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
567 return true;
568 }
569
570 /*
571 * The page can not be swapped.
572 *
573 * Can it be reclaimed from this node via demotion?
574 */
575 return can_demote(nid, sc);
576}
577
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700578/*
579 * This misses isolated pages which are not accounted for to save counters.
580 * As the data only determines if reclaim or compaction continues, it is
581 * not expected that isolated pages will be a dominating factor.
582 */
583unsigned long zone_reclaimable_pages(struct zone *zone)
584{
585 unsigned long nr;
586
587 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
588 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700589 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700590 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
591 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
592
593 return nr;
594}
595
Michal Hockofd538802017-02-22 15:45:58 -0800596/**
597 * lruvec_lru_size - Returns the number of pages on the given LRU list.
598 * @lruvec: lru vector
599 * @lru: lru to use
600 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
601 */
Yu Zhao20913392021-02-24 12:08:44 -0800602static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
603 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800604{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800605 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800606 int zid;
607
Johannes Weinerde3b0152019-11-30 17:55:31 -0800608 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800609 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800610
Michal Hockofd538802017-02-22 15:45:58 -0800611 if (!managed_zone(zone))
612 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800613
Michal Hockofd538802017-02-22 15:45:58 -0800614 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800615 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800616 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800617 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800618 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800619 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800620}
621
Linus Torvalds1da177e2005-04-16 15:20:36 -0700622/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000623 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700624 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900625int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700626{
Yang Shi476b30a2021-05-04 18:36:39 -0700627 unsigned int size;
628 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000629
Yang Shi476b30a2021-05-04 18:36:39 -0700630 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
631 err = prealloc_memcg_shrinker(shrinker);
632 if (err != -ENOSYS)
633 return err;
634
635 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
636 }
637
638 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000639 if (shrinker->flags & SHRINKER_NUMA_AWARE)
640 size *= nr_node_ids;
641
642 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
643 if (!shrinker->nr_deferred)
644 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700645
Tetsuo Handa8e049442018-04-04 19:53:07 +0900646 return 0;
647}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000648
Tetsuo Handa8e049442018-04-04 19:53:07 +0900649void free_prealloced_shrinker(struct shrinker *shrinker)
650{
Yang Shi41ca6682021-05-04 18:36:29 -0700651 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
652 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700653 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700654 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700655 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700656 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700657
Tetsuo Handa8e049442018-04-04 19:53:07 +0900658 kfree(shrinker->nr_deferred);
659 shrinker->nr_deferred = NULL;
660}
661
662void register_shrinker_prepared(struct shrinker *shrinker)
663{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700664 down_write(&shrinker_rwsem);
665 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700666 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700667 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900668}
669
670int register_shrinker(struct shrinker *shrinker)
671{
672 int err = prealloc_shrinker(shrinker);
673
674 if (err)
675 return err;
676 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000677 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700678}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700679EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700680
681/*
682 * Remove one
683 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700684void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700685{
Yang Shi41ca6682021-05-04 18:36:29 -0700686 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900687 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700688
Linus Torvalds1da177e2005-04-16 15:20:36 -0700689 down_write(&shrinker_rwsem);
690 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700691 shrinker->flags &= ~SHRINKER_REGISTERED;
692 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
693 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700694 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700695
Andrew Vaginae393322013-10-16 13:46:46 -0700696 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900697 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700698}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700699EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700700
701#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000702
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800703static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800704 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700705{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000706 unsigned long freed = 0;
707 unsigned long long delta;
708 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700709 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000710 long nr;
711 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000712 long batch_size = shrinker->batch ? shrinker->batch
713 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800714 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000715
rongqianfeng8da6ee32021-05-21 10:30:14 +0800716 trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
717
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700718 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700719 if (freeable == 0 || freeable == SHRINK_EMPTY)
720 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000721
722 /*
723 * copy the current shrinker scan count into a local variable
724 * and zero it so that other concurrent shrinker invocations
725 * don't also do this scanning work.
726 */
Yang Shi86750832021-05-04 18:36:36 -0700727 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000728
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700729 if (shrinker->seeks) {
730 delta = freeable >> priority;
731 delta *= 4;
732 do_div(delta, shrinker->seeks);
733 } else {
734 /*
735 * These objects don't require any IO to create. Trim
736 * them aggressively under memory pressure to keep
737 * them from causing refetches in the IO caches.
738 */
739 delta = freeable / 2;
740 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700741
Yang Shi18bb4732021-05-04 18:36:45 -0700742 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000743 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700744 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000745
746 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800747 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000748
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800749 /*
750 * Normally, we should not scan less than batch_size objects in one
751 * pass to avoid too frequent shrinker calls, but if the slab has less
752 * than batch_size objects in total and we are really tight on memory,
753 * we will try to reclaim all available objects, otherwise we can end
754 * up failing allocations although there are plenty of reclaimable
755 * objects spread over several slabs with usage less than the
756 * batch_size.
757 *
758 * We detect the "tight on memory" situations by looking at the total
759 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700760 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800761 * scanning at high prio and therefore should try to reclaim as much as
762 * possible.
763 */
764 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700765 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000766 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800767 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000768
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800769 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700770 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000771 ret = shrinker->scan_objects(shrinker, shrinkctl);
772 if (ret == SHRINK_STOP)
773 break;
774 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000775
Chris Wilsond460acb2017-09-06 16:19:26 -0700776 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
777 total_scan -= shrinkctl->nr_scanned;
778 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000779
780 cond_resched();
781 }
782
Yang Shi18bb4732021-05-04 18:36:45 -0700783 /*
784 * The deferred work is increased by any new work (delta) that wasn't
785 * done, decreased by old deferred work that was done now.
786 *
787 * And it is capped to two times of the freeable items.
788 */
789 next_deferred = max_t(long, (nr + delta - scanned), 0);
790 next_deferred = min(next_deferred, (2 * freeable));
791
Glauber Costa1d3d4432013-08-28 10:18:04 +1000792 /*
793 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700794 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000795 */
Yang Shi86750832021-05-04 18:36:36 -0700796 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000797
Yang Shi8efb4b52021-05-04 18:36:08 -0700798 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000799 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700800}
801
Yang Shi0a432dc2019-09-23 15:38:12 -0700802#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700803static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
804 struct mem_cgroup *memcg, int priority)
805{
Yang Shie4262c42021-05-04 18:36:23 -0700806 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700807 unsigned long ret, freed = 0;
808 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700809
Yang Shi0a432dc2019-09-23 15:38:12 -0700810 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700811 return 0;
812
813 if (!down_read_trylock(&shrinker_rwsem))
814 return 0;
815
Yang Shi468ab842021-05-04 18:36:26 -0700816 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700817 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700818 goto unlock;
819
Yang Shie4262c42021-05-04 18:36:23 -0700820 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700821 struct shrink_control sc = {
822 .gfp_mask = gfp_mask,
823 .nid = nid,
824 .memcg = memcg,
825 };
826 struct shrinker *shrinker;
827
828 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700829 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700830 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700831 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700832 continue;
833 }
834
Yang Shi0a432dc2019-09-23 15:38:12 -0700835 /* Call non-slab shrinkers even though kmem is disabled */
836 if (!memcg_kmem_enabled() &&
837 !(shrinker->flags & SHRINKER_NONSLAB))
838 continue;
839
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700840 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700841 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700842 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700843 /*
844 * After the shrinker reported that it had no objects to
845 * free, but before we cleared the corresponding bit in
846 * the memcg shrinker map, a new object might have been
847 * added. To make sure, we have the bit set in this
848 * case, we invoke the shrinker one more time and reset
849 * the bit if it reports that it is not empty anymore.
850 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700851 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700852 *
853 * list_lru_add() shrink_slab_memcg()
854 * list_add_tail() clear_bit()
855 * <MB> <MB>
856 * set_bit() do_shrink_slab()
857 */
858 smp_mb__after_atomic();
859 ret = do_shrink_slab(&sc, shrinker, priority);
860 if (ret == SHRINK_EMPTY)
861 ret = 0;
862 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700863 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700864 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700865 freed += ret;
866
867 if (rwsem_is_contended(&shrinker_rwsem)) {
868 freed = freed ? : 1;
869 break;
870 }
871 }
872unlock:
873 up_read(&shrinker_rwsem);
874 return freed;
875}
Yang Shi0a432dc2019-09-23 15:38:12 -0700876#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700877static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
878 struct mem_cgroup *memcg, int priority)
879{
880 return 0;
881}
Yang Shi0a432dc2019-09-23 15:38:12 -0700882#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700883
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800884/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800885 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800886 * @gfp_mask: allocation context
887 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800888 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800889 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700890 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800891 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700892 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800893 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
894 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700895 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700896 * @memcg specifies the memory cgroup to target. Unaware shrinkers
897 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800898 *
Josef Bacik9092c712018-01-31 16:16:26 -0800899 * @priority is sc->priority, we take the number of objects and >> by priority
900 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700901 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800902 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700903 */
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800904unsigned long shrink_slab(gfp_t gfp_mask, int nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800905 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800906 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700907{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700908 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700909 struct shrinker *shrinker;
wudean842c68a2021-04-27 17:40:41 +0800910 bool bypass = false;
911
912 trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
913 if (bypass)
914 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700915
Yang Shifa1e5122019-08-02 21:48:44 -0700916 /*
917 * The root memcg might be allocated even though memcg is disabled
918 * via "cgroup_disable=memory" boot parameter. This could make
919 * mem_cgroup_is_root() return false, then just run memcg slab
920 * shrink, but skip global shrink. This may result in premature
921 * oom.
922 */
923 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700924 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800925
Tetsuo Handae830c632018-04-05 16:23:35 -0700926 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700927 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700928
929 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800930 struct shrink_control sc = {
931 .gfp_mask = gfp_mask,
932 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800933 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800934 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800935
Kirill Tkhai9b996462018-08-17 15:48:21 -0700936 ret = do_shrink_slab(&sc, shrinker, priority);
937 if (ret == SHRINK_EMPTY)
938 ret = 0;
939 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800940 /*
941 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700942 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800943 * by parallel ongoing shrinking.
944 */
945 if (rwsem_is_contended(&shrinker_rwsem)) {
946 freed = freed ? : 1;
947 break;
948 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700949 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800950
Linus Torvalds1da177e2005-04-16 15:20:36 -0700951 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700952out:
953 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000954 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700955}
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800956EXPORT_SYMBOL_GPL(shrink_slab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700957
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800958void drop_slab_node(int nid)
959{
960 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700961 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800962
963 do {
964 struct mem_cgroup *memcg = NULL;
965
Chunxin Zang069c4112020-10-13 16:56:46 -0700966 if (fatal_signal_pending(current))
967 return;
968
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800969 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700970 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800971 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800972 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800973 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700974 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800975}
976
977void drop_slab(void)
978{
979 int nid;
980
981 for_each_online_node(nid)
982 drop_slab_node(nid);
983}
984
Linus Torvalds1da177e2005-04-16 15:20:36 -0700985static inline int is_page_cache_freeable(struct page *page)
986{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700987 /*
988 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400989 * that isolated the page, the page cache and optional buffer
990 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700991 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -0700992 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400993 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700994}
995
Yang Shicb165562019-11-30 17:55:28 -0800996static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700997{
Christoph Lameter930d9152006-01-08 01:00:47 -0800998 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700999 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001000 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001001 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001002 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001003 return 1;
1004 return 0;
1005}
1006
1007/*
1008 * We detected a synchronous write error writing a page out. Probably
1009 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1010 * fsync(), msync() or close().
1011 *
1012 * The tricky part is that after writepage we cannot touch the mapping: nothing
1013 * prevents it from being freed up. But we have a ref on the page and once
1014 * that page is locked, the mapping is pinned.
1015 *
1016 * We're allowed to run sleeping lock_page() here because we know the caller has
1017 * __GFP_FS.
1018 */
1019static void handle_write_error(struct address_space *mapping,
1020 struct page *page, int error)
1021{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001022 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001023 if (page_mapping(page) == mapping)
1024 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001025 unlock_page(page);
1026}
1027
Christoph Lameter04e62a22006-06-23 02:03:38 -07001028/* possible outcome of pageout() */
1029typedef enum {
1030 /* failed to write page out, page is locked */
1031 PAGE_KEEP,
1032 /* move page to the active list, page is locked */
1033 PAGE_ACTIVATE,
1034 /* page has been sent to the disk successfully, page is unlocked */
1035 PAGE_SUCCESS,
1036 /* page is clean and locked */
1037 PAGE_CLEAN,
1038} pageout_t;
1039
Linus Torvalds1da177e2005-04-16 15:20:36 -07001040/*
Andrew Morton1742f192006-03-22 00:08:21 -08001041 * pageout is called by shrink_page_list() for each dirty page.
1042 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001043 */
Yang Shicb165562019-11-30 17:55:28 -08001044static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001045{
1046 /*
1047 * If the page is dirty, only perform writeback if that write
1048 * will be non-blocking. To prevent this allocation from being
1049 * stalled by pagecache activity. But note that there may be
1050 * stalls if we need to run get_block(). We could test
1051 * PagePrivate for that.
1052 *
Al Viro81742022014-04-03 03:17:43 -04001053 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001054 * this page's queue, we can perform writeback even if that
1055 * will block.
1056 *
1057 * If the page is swapcache, write it back even if that would
1058 * block, for some throttling. This happens by accident, because
1059 * swap_backing_dev_info is bust: it doesn't reflect the
1060 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001061 */
1062 if (!is_page_cache_freeable(page))
1063 return PAGE_KEEP;
1064 if (!mapping) {
1065 /*
1066 * Some data journaling orphaned pages can have
1067 * page->mapping == NULL while being dirty with clean buffers.
1068 */
David Howells266cf652009-04-03 16:42:36 +01001069 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001070 if (try_to_free_buffers(page)) {
1071 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001072 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001073 return PAGE_CLEAN;
1074 }
1075 }
1076 return PAGE_KEEP;
1077 }
1078 if (mapping->a_ops->writepage == NULL)
1079 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001080 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001081 return PAGE_KEEP;
1082
1083 if (clear_page_dirty_for_io(page)) {
1084 int res;
1085 struct writeback_control wbc = {
1086 .sync_mode = WB_SYNC_NONE,
1087 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001088 .range_start = 0,
1089 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001090 .for_reclaim = 1,
1091 };
1092
1093 SetPageReclaim(page);
1094 res = mapping->a_ops->writepage(page, &wbc);
1095 if (res < 0)
1096 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001097 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001098 ClearPageReclaim(page);
1099 return PAGE_ACTIVATE;
1100 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001101
Linus Torvalds1da177e2005-04-16 15:20:36 -07001102 if (!PageWriteback(page)) {
1103 /* synchronous write or broken a_ops? */
1104 ClearPageReclaim(page);
1105 }
yalin wang3aa23852016-01-14 15:18:30 -08001106 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001107 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001108 return PAGE_SUCCESS;
1109 }
1110
1111 return PAGE_CLEAN;
1112}
1113
Andrew Mortona649fd92006-10-17 00:09:36 -07001114/*
Nick Piggine2867812008-07-25 19:45:30 -07001115 * Same as remove_mapping, but if the page is removed from the mapping, it
1116 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001117 */
Johannes Weinera5289102014-04-03 14:47:51 -07001118static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001119 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001120{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001121 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001122 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001123
Nick Piggin28e4d962006-09-25 23:31:23 -07001124 BUG_ON(!PageLocked(page));
1125 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001126
Johannes Weiner30472502021-09-02 14:53:18 -07001127 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001128 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001129 * The non racy check for a busy page.
1130 *
1131 * Must be careful with the order of the tests. When someone has
1132 * a ref to the page, it may be possible that they dirty it then
1133 * drop the reference. So if PageDirty is tested before page_count
1134 * here, then the following race may occur:
1135 *
1136 * get_user_pages(&page);
1137 * [user mapping goes away]
1138 * write_to(page);
1139 * !PageDirty(page) [good]
1140 * SetPageDirty(page);
1141 * put_page(page);
1142 * !page_count(page) [good, discard it]
1143 *
1144 * [oops, our write_to data is lost]
1145 *
1146 * Reversing the order of the tests ensures such a situation cannot
1147 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001148 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001149 *
1150 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001151 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001152 */
William Kucharski906d2782019-10-18 20:20:33 -07001153 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001154 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001155 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001156 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001157 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001158 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001159 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001160 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001161
1162 if (PageSwapCache(page)) {
1163 swp_entry_t swap = { .val = page_private(page) };
Yu Zhao37397872022-09-18 02:00:03 -06001164
1165 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001166 if (reclaimed && !mapping_exiting(mapping))
1167 shadow = workingset_eviction(page, target_memcg);
Yu Zhao37397872022-09-18 02:00:03 -06001168 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001169 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001170 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001171 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001172 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001173 void (*freepage)(struct page *);
1174
1175 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001176 /*
1177 * Remember a shadow entry for reclaimed file cache in
1178 * order to detect refaults, thus thrashing, later on.
1179 *
1180 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001181 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001182 * inode reclaim needs to empty out the radix tree or
1183 * the nodes are lost. Don't plant shadows behind its
1184 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001185 *
1186 * We also don't store shadows for DAX mappings because the
1187 * only page cache pages found in these are zero pages
1188 * covering holes, and because we don't want to mix DAX
1189 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001190 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001191 */
Huang Ying9de4f222020-04-06 20:04:41 -07001192 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001193 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001194 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001195 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001196 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001197
1198 if (freepage != NULL)
1199 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001200 }
1201
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001202 return 1;
1203
1204cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001205 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001206 return 0;
1207}
1208
Linus Torvalds1da177e2005-04-16 15:20:36 -07001209/*
Nick Piggine2867812008-07-25 19:45:30 -07001210 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1211 * someone else has a ref on the page, abort and return 0. If it was
1212 * successfully detached, return 1. Assumes the caller has a single ref on
1213 * this page.
1214 */
1215int remove_mapping(struct address_space *mapping, struct page *page)
1216{
Johannes Weinerb9107182019-11-30 17:55:59 -08001217 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001218 /*
1219 * Unfreezing the refcount with 1 rather than 2 effectively
1220 * drops the pagecache ref for us without requiring another
1221 * atomic operation.
1222 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001223 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001224 return 1;
1225 }
1226 return 0;
1227}
1228
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001229/**
1230 * putback_lru_page - put previously isolated page onto appropriate LRU list
1231 * @page: page to be put back to appropriate lru list
1232 *
1233 * Add previously isolated @page to appropriate LRU list.
1234 * Page may still be unevictable for other reasons.
1235 *
1236 * lru_lock must not be held, interrupts must be enabled.
1237 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001238void putback_lru_page(struct page *page)
1239{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001240 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001241 put_page(page); /* drop ref from isolate */
1242}
1243
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001244enum page_references {
1245 PAGEREF_RECLAIM,
1246 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001247 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001248 PAGEREF_ACTIVATE,
1249};
1250
1251static enum page_references page_check_references(struct page *page,
1252 struct scan_control *sc)
1253{
Johannes Weiner645747462010-03-05 13:42:22 -08001254 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001255 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001256
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001257 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1258 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001259 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001260
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001261 /*
1262 * Mlock lost the isolation race with us. Let try_to_unmap()
1263 * move the page to the unevictable list.
1264 */
1265 if (vm_flags & VM_LOCKED)
1266 return PAGEREF_RECLAIM;
1267
Johannes Weiner645747462010-03-05 13:42:22 -08001268 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001269 /*
1270 * All mapped pages start out with page table
1271 * references from the instantiating fault, so we need
1272 * to look twice if a mapped file page is used more
1273 * than once.
1274 *
1275 * Mark it and spare it for another trip around the
1276 * inactive list. Another page table reference will
1277 * lead to its activation.
1278 *
1279 * Note: the mark is set for activated pages as well
1280 * so that recently deactivated but used pages are
1281 * quickly recovered.
1282 */
1283 SetPageReferenced(page);
1284
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001285 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001286 return PAGEREF_ACTIVATE;
1287
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001288 /*
1289 * Activate file-backed executable pages after first usage.
1290 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001291 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001292 return PAGEREF_ACTIVATE;
1293
Johannes Weiner645747462010-03-05 13:42:22 -08001294 return PAGEREF_KEEP;
1295 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001296
1297 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001298 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001299 return PAGEREF_RECLAIM_CLEAN;
1300
1301 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001302}
1303
Mel Gormane2be15f2013-07-03 15:01:57 -07001304/* Check if a page is dirty or under writeback */
1305static void page_check_dirty_writeback(struct page *page,
1306 bool *dirty, bool *writeback)
1307{
Mel Gormanb4597222013-07-03 15:02:05 -07001308 struct address_space *mapping;
1309
Mel Gormane2be15f2013-07-03 15:01:57 -07001310 /*
1311 * Anonymous pages are not handled by flushers and must be written
1312 * from reclaim context. Do not stall reclaim based on them
1313 */
Huang Ying9de4f222020-04-06 20:04:41 -07001314 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001315 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001316 *dirty = false;
1317 *writeback = false;
1318 return;
1319 }
1320
1321 /* By default assume that the page flags are accurate */
1322 *dirty = PageDirty(page);
1323 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001324
1325 /* Verify dirty/writeback state if the filesystem supports it */
1326 if (!page_has_private(page))
1327 return;
1328
1329 mapping = page_mapping(page);
1330 if (mapping && mapping->a_ops->is_dirty_writeback)
1331 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001332}
1333
Dave Hansen26aa2d12021-09-02 14:59:16 -07001334static struct page *alloc_demote_page(struct page *page, unsigned long node)
1335{
1336 struct migration_target_control mtc = {
1337 /*
1338 * Allocate from 'node', or fail quickly and quietly.
1339 * When this happens, 'page' will likely just be discarded
1340 * instead of migrated.
1341 */
1342 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1343 __GFP_THISNODE | __GFP_NOWARN |
1344 __GFP_NOMEMALLOC | GFP_NOWAIT,
1345 .nid = node
1346 };
1347
1348 return alloc_migration_target(page, (unsigned long)&mtc);
1349}
1350
1351/*
1352 * Take pages on @demote_list and attempt to demote them to
1353 * another node. Pages which are not demoted are left on
1354 * @demote_pages.
1355 */
1356static unsigned int demote_page_list(struct list_head *demote_pages,
1357 struct pglist_data *pgdat)
1358{
1359 int target_nid = next_demotion_node(pgdat->node_id);
1360 unsigned int nr_succeeded;
1361 int err;
1362
1363 if (list_empty(demote_pages))
1364 return 0;
1365
1366 if (target_nid == NUMA_NO_NODE)
1367 return 0;
1368
1369 /* Demotion ignores all cpuset and mempolicy settings */
1370 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1371 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1372 &nr_succeeded);
1373
Yang Shi668e4142021-09-02 14:59:19 -07001374 if (current_is_kswapd())
1375 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1376 else
1377 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1378
Dave Hansen26aa2d12021-09-02 14:59:16 -07001379 return nr_succeeded;
1380}
1381
Nick Piggine2867812008-07-25 19:45:30 -07001382/*
Andrew Morton1742f192006-03-22 00:08:21 -08001383 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001384 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001385static unsigned int shrink_page_list(struct list_head *page_list,
1386 struct pglist_data *pgdat,
1387 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001388 struct reclaim_stat *stat,
1389 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001390{
1391 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001392 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001393 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001394 unsigned int nr_reclaimed = 0;
1395 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001396 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001397
Kirill Tkhai060f0052019-03-05 15:48:15 -08001398 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001399 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001400 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001401
Dave Hansen26aa2d12021-09-02 14:59:16 -07001402retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001403 while (!list_empty(page_list)) {
1404 struct address_space *mapping;
1405 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001406 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001407 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001408 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001409
1410 cond_resched();
1411
1412 page = lru_to_page(page_list);
1413 list_del(&page->lru);
1414
Nick Piggin529ae9a2008-08-02 12:01:03 +02001415 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001416 goto keep;
1417
Sasha Levin309381fea2014-01-23 15:52:54 -08001418 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001419
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001420 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001421
1422 /* Account the number of base pages even though THP */
1423 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001424
Hugh Dickins39b5f292012-10-08 16:33:18 -07001425 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001426 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001427
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001428 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001429 goto keep_locked;
1430
Yu Zhao0182f922022-09-18 02:00:04 -06001431 /* page_update_gen() tried to promote this page? */
1432 if (lru_gen_enabled() && !ignore_references &&
1433 page_mapped(page) && PageReferenced(page))
1434 goto keep_locked;
1435
Andy Whitcroftc661b072007-08-22 14:01:26 -07001436 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1437 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1438
Mel Gorman283aba92013-07-03 15:01:51 -07001439 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001440 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001441 * reclaim_congested which affects wait_iff_congested. kswapd
1442 * will stall and start writing pages if the tail of the LRU
1443 * is all dirty unqueued pages.
1444 */
1445 page_check_dirty_writeback(page, &dirty, &writeback);
1446 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001447 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001448
1449 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001450 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001451
Mel Gormand04e8ac2013-07-03 15:02:03 -07001452 /*
1453 * Treat this page as congested if the underlying BDI is or if
1454 * pages are cycling through the LRU so quickly that the
1455 * pages marked for immediate reclaim are making it to the
1456 * end of the LRU a second time.
1457 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001458 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001459 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001460 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001461 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001462 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001463
1464 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001465 * If a page at the tail of the LRU is under writeback, there
1466 * are three cases to consider.
1467 *
1468 * 1) If reclaim is encountering an excessive number of pages
1469 * under writeback and this page is both under writeback and
1470 * PageReclaim then it indicates that pages are being queued
1471 * for IO but are being recycled through the LRU before the
1472 * IO can complete. Waiting on the page itself risks an
1473 * indefinite stall if it is impossible to writeback the
1474 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001475 * note that the LRU is being scanned too quickly and the
1476 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001477 *
Tejun Heo97c93412015-05-22 18:23:36 -04001478 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001479 * not marked for immediate reclaim, or the caller does not
1480 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1481 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001482 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001483 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001484 * Require may_enter_fs because we would wait on fs, which
1485 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001486 * enter reclaim, and deadlock if it waits on a page for
1487 * which it is needed to do the write (loop masks off
1488 * __GFP_IO|__GFP_FS for this reason); but more thought
1489 * would probably show more reasons.
1490 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001491 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001492 * PageReclaim. memcg does not have any dirty pages
1493 * throttling so we could easily OOM just because too many
1494 * pages are in writeback and there is nothing else to
1495 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001496 *
1497 * In cases 1) and 2) we activate the pages to get them out of
1498 * the way while we continue scanning for clean pages on the
1499 * inactive list and refilling from the active list. The
1500 * observation here is that waiting for disk writes is more
1501 * expensive than potentially causing reloads down the line.
1502 * Since they're marked for immediate reclaim, they won't put
1503 * memory pressure on the cache working set any longer than it
1504 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001505 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001506 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001507 /* Case 1 above */
1508 if (current_is_kswapd() &&
1509 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001510 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001511 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001512 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001513
1514 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001515 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001516 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001517 /*
1518 * This is slightly racy - end_page_writeback()
1519 * might have just cleared PageReclaim, then
1520 * setting PageReclaim here end up interpreted
1521 * as PageReadahead - but that does not matter
1522 * enough to care. What we do want is for this
1523 * page to have PageReclaim set next time memcg
1524 * reclaim reaches the tests above, so it will
1525 * then wait_on_page_writeback() to avoid OOM;
1526 * and it's also appropriate in global reclaim.
1527 */
1528 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001529 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001530 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001531
1532 /* Case 3 above */
1533 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001534 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001535 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001536 /* then go back and try same page again */
1537 list_add_tail(&page->lru, page_list);
1538 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001539 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001540 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001541
Minchan Kim8940b342019-09-25 16:49:11 -07001542 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001543 references = page_check_references(page, sc);
1544
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001545 switch (references) {
1546 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001547 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001548 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001549 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001550 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001551 case PAGEREF_RECLAIM:
1552 case PAGEREF_RECLAIM_CLEAN:
1553 ; /* try to reclaim the page below */
1554 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001555
Linus Torvalds1da177e2005-04-16 15:20:36 -07001556 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001557 * Before reclaiming the page, try to relocate
1558 * its contents to another node.
1559 */
1560 if (do_demote_pass &&
1561 (thp_migration_supported() || !PageTransHuge(page))) {
1562 list_add(&page->lru, &demote_pages);
1563 unlock_page(page);
1564 continue;
1565 }
1566
1567 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001568 * Anonymous process memory has backing store?
1569 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001570 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001571 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001572 if (PageAnon(page) && PageSwapBacked(page)) {
1573 if (!PageSwapCache(page)) {
1574 if (!(sc->gfp_mask & __GFP_IO))
1575 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001576 if (page_maybe_dma_pinned(page))
1577 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001578 if (PageTransHuge(page)) {
1579 /* cannot split THP, skip it */
1580 if (!can_split_huge_page(page, NULL))
1581 goto activate_locked;
1582 /*
1583 * Split pages without a PMD map right
1584 * away. Chances are some or all of the
1585 * tail pages can be freed without IO.
1586 */
1587 if (!compound_mapcount(page) &&
1588 split_huge_page_to_list(page,
1589 page_list))
1590 goto activate_locked;
1591 }
1592 if (!add_to_swap(page)) {
1593 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001594 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001595 /* Fallback to swap normal pages */
1596 if (split_huge_page_to_list(page,
1597 page_list))
1598 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001599#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1600 count_vm_event(THP_SWPOUT_FALLBACK);
1601#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001602 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001603 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001604 }
Minchan Kim0f074652017-07-06 15:37:24 -07001605
Kirill Tkhai4b793062020-04-01 21:10:18 -07001606 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001607
1608 /* Adding to swap updated mapping */
1609 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001610 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001611 } else if (unlikely(PageTransHuge(page))) {
1612 /* Split file THP */
1613 if (split_huge_page_to_list(page, page_list))
1614 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001615 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001616
1617 /*
Yang Shi98879b32019-07-11 20:59:30 -07001618 * THP may get split above, need minus tail pages and update
1619 * nr_pages to avoid accounting tail pages twice.
1620 *
1621 * The tail pages that are added into swap cache successfully
1622 * reach here.
1623 */
1624 if ((nr_pages > 1) && !PageTransHuge(page)) {
1625 sc->nr_scanned -= (nr_pages - 1);
1626 nr_pages = 1;
1627 }
1628
1629 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001630 * The page is mapped into the page tables of one or more
1631 * processes. Try to unmap it here.
1632 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001633 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001634 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001635 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001636
1637 if (unlikely(PageTransHuge(page)))
1638 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001639
Yang Shi1fb08ac2021-06-30 18:52:01 -07001640 try_to_unmap(page, flags);
1641 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001642 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001643 if (!was_swapbacked && PageSwapBacked(page))
1644 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001645 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001646 }
1647 }
1648
1649 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001650 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001651 * Only kswapd can writeback filesystem pages
1652 * to avoid risk of stack overflow. But avoid
1653 * injecting inefficient single-page IO into
1654 * flusher writeback as much as possible: only
1655 * write pages when we've encountered many
1656 * dirty pages, and when we've already scanned
1657 * the rest of the LRU for clean pages and see
1658 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001659 */
Huang Ying9de4f222020-04-06 20:04:41 -07001660 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001661 (!current_is_kswapd() || !PageReclaim(page) ||
1662 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001663 /*
1664 * Immediately reclaim when written back.
1665 * Similar in principal to deactivate_page()
1666 * except we already have the page isolated
1667 * and know it's dirty
1668 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001669 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001670 SetPageReclaim(page);
1671
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001672 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001673 }
1674
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001675 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001676 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001677 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001678 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001679 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001680 goto keep_locked;
1681
Mel Gormand950c942015-09-04 15:47:35 -07001682 /*
1683 * Page is dirty. Flush the TLB if a writable entry
1684 * potentially exists to avoid CPU writes after IO
1685 * starts and then write it out here.
1686 */
1687 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001688 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001689 case PAGE_KEEP:
1690 goto keep_locked;
1691 case PAGE_ACTIVATE:
1692 goto activate_locked;
1693 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001694 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001695
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001696 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001697 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001698 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001699 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001700
Linus Torvalds1da177e2005-04-16 15:20:36 -07001701 /*
1702 * A synchronous write - probably a ramdisk. Go
1703 * ahead and try to reclaim the page.
1704 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001705 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001706 goto keep;
1707 if (PageDirty(page) || PageWriteback(page))
1708 goto keep_locked;
1709 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001710 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001711 case PAGE_CLEAN:
1712 ; /* try to free the page below */
1713 }
1714 }
1715
1716 /*
1717 * If the page has buffers, try to free the buffer mappings
1718 * associated with this page. If we succeed we try to free
1719 * the page as well.
1720 *
1721 * We do this even if the page is PageDirty().
1722 * try_to_release_page() does not perform I/O, but it is
1723 * possible for a page to have PageDirty set, but it is actually
1724 * clean (all its buffers are clean). This happens if the
1725 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001726 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001727 * try_to_release_page() will discover that cleanness and will
1728 * drop the buffers and mark the page clean - it can be freed.
1729 *
1730 * Rarely, pages can have buffers and no ->mapping. These are
1731 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001732 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001733 * and if that worked, and the page is no longer mapped into
1734 * process address space (page_count == 1) it can be freed.
1735 * Otherwise, leave the page on the LRU so it is swappable.
1736 */
David Howells266cf652009-04-03 16:42:36 +01001737 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001738 if (!try_to_release_page(page, sc->gfp_mask))
1739 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001740 if (!mapping && page_count(page) == 1) {
1741 unlock_page(page);
1742 if (put_page_testzero(page))
1743 goto free_it;
1744 else {
1745 /*
1746 * rare race with speculative reference.
1747 * the speculative reference will free
1748 * this page shortly, so we may
1749 * increment nr_reclaimed here (and
1750 * leave it off the LRU).
1751 */
1752 nr_reclaimed++;
1753 continue;
1754 }
1755 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001756 }
1757
Shaohua Li802a3a92017-05-03 14:52:32 -07001758 if (PageAnon(page) && !PageSwapBacked(page)) {
1759 /* follow __remove_mapping for reference */
1760 if (!page_ref_freeze(page, 1))
1761 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001762 /*
1763 * The page has only one reference left, which is
1764 * from the isolation. After the caller puts the
1765 * page back on lru and drops the reference, the
1766 * page will be freed anyway. It doesn't matter
1767 * which lru it goes. So we don't bother checking
1768 * PageDirty here.
1769 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001770 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001771 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001772 } else if (!mapping || !__remove_mapping(mapping, page, true,
1773 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001774 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001775
1776 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001777free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001778 /*
1779 * THP may get swapped out in a whole, need account
1780 * all base pages.
1781 */
1782 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001783
1784 /*
1785 * Is there need to periodically free_page_list? It would
1786 * appear not as the counts should be low
1787 */
Yang Shi7ae88532019-09-23 15:38:09 -07001788 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001789 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001790 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001791 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001792 continue;
1793
Yang Shi98879b32019-07-11 20:59:30 -07001794activate_locked_split:
1795 /*
1796 * The tail pages that are failed to add into swap cache
1797 * reach here. Fixup nr_scanned and nr_pages.
1798 */
1799 if (nr_pages > 1) {
1800 sc->nr_scanned -= (nr_pages - 1);
1801 nr_pages = 1;
1802 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001803activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001804 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001805 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1806 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001807 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001808 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001809 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001810 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001811 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001812 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001813 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001814 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001815keep_locked:
1816 unlock_page(page);
1817keep:
1818 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001819 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001820 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001821 /* 'page_list' is always empty here */
1822
1823 /* Migrate pages selected for demotion */
1824 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1825 /* Pages that could not be demoted are still in @demote_pages */
1826 if (!list_empty(&demote_pages)) {
1827 /* Pages which failed to demoted go back on @page_list for retry: */
1828 list_splice_init(&demote_pages, page_list);
1829 do_demote_pass = false;
1830 goto retry;
1831 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001832
Yang Shi98879b32019-07-11 20:59:30 -07001833 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1834
Johannes Weiner747db952014-08-08 14:19:24 -07001835 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001836 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001837 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001838
Linus Torvalds1da177e2005-04-16 15:20:36 -07001839 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001840 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001841
Andrew Morton05ff5132006-03-22 00:08:20 -08001842 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001843}
1844
Maninder Singh730ec8c2020-06-03 16:01:18 -07001845unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001846 struct list_head *page_list)
1847{
1848 struct scan_control sc = {
1849 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001850 .may_unmap = 1,
1851 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001852 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001853 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001854 struct page *page, *next;
1855 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001856 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001857
1858 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001859 if (!PageHuge(page) && page_is_file_lru(page) &&
1860 !PageDirty(page) && !__PageMovable(page) &&
1861 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001862 ClearPageActive(page);
1863 list_move(&page->lru, &clean_pages);
1864 }
1865 }
1866
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001867 /*
1868 * We should be safe here since we are only dealing with file pages and
1869 * we are not kswapd and therefore cannot write dirty file pages. But
1870 * call memalloc_noreclaim_save() anyway, just in case these conditions
1871 * change in the future.
1872 */
1873 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001874 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001875 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001876 memalloc_noreclaim_restore(noreclaim_flag);
1877
Minchan Kim02c6de82012-10-08 16:31:55 -07001878 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001879 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1880 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001881 /*
1882 * Since lazyfree pages are isolated from file LRU from the beginning,
1883 * they will rotate back to anonymous LRU in the end if it failed to
1884 * discard so isolated count will be mismatched.
1885 * Compensate the isolated count for both LRU lists.
1886 */
1887 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1888 stat.nr_lazyfree_fail);
1889 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001890 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001891 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001892}
1893
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001894/*
1895 * Attempt to remove the specified page from its LRU. Only take this page
1896 * if it is of the appropriate PageActive status. Pages which are being
1897 * freed elsewhere are also ignored.
1898 *
1899 * page: page to consider
1900 * mode: one of the LRU isolation modes defined above
1901 *
Alex Shic2135f72021-02-24 12:08:01 -08001902 * returns true on success, false on failure.
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001903 */
Alex Shic2135f72021-02-24 12:08:01 -08001904bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001905{
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001906 /* Only take pages on the LRU. */
1907 if (!PageLRU(page))
Alex Shic2135f72021-02-24 12:08:01 -08001908 return false;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001909
Minchan Kime46a2872012-10-08 16:33:48 -07001910 /* Compaction should not handle unevictable pages but CMA can do so */
1911 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
Alex Shic2135f72021-02-24 12:08:01 -08001912 return false;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001913
Mel Gormanc8244932012-01-12 17:19:38 -08001914 /*
1915 * To minimise LRU disruption, the caller can indicate that it only
1916 * wants to isolate pages it will be able to operate on without
1917 * blocking - clean pages for the most part.
1918 *
Mel Gormanc8244932012-01-12 17:19:38 -08001919 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1920 * that it is possible to migrate without blocking
1921 */
Johannes Weiner1276ad62017-02-24 14:56:11 -08001922 if (mode & ISOLATE_ASYNC_MIGRATE) {
Mel Gormanc8244932012-01-12 17:19:38 -08001923 /* All the caller can do on PageWriteback is block */
1924 if (PageWriteback(page))
Alex Shic2135f72021-02-24 12:08:01 -08001925 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001926
1927 if (PageDirty(page)) {
1928 struct address_space *mapping;
Mel Gorman69d763f2018-01-31 16:19:52 -08001929 bool migrate_dirty;
Mel Gormanc8244932012-01-12 17:19:38 -08001930
Mel Gormanc8244932012-01-12 17:19:38 -08001931 /*
1932 * Only pages without mappings or that have a
1933 * ->migratepage callback are possible to migrate
Mel Gorman69d763f2018-01-31 16:19:52 -08001934 * without blocking. However, we can be racing with
1935 * truncation so it's necessary to lock the page
1936 * to stabilise the mapping as truncation holds
1937 * the page lock until after the page is removed
1938 * from the page cache.
Mel Gormanc8244932012-01-12 17:19:38 -08001939 */
Mel Gorman69d763f2018-01-31 16:19:52 -08001940 if (!trylock_page(page))
Alex Shic2135f72021-02-24 12:08:01 -08001941 return false;
Mel Gorman69d763f2018-01-31 16:19:52 -08001942
Mel Gormanc8244932012-01-12 17:19:38 -08001943 mapping = page_mapping(page);
Hugh Dickins145e1a72018-06-01 16:50:50 -07001944 migrate_dirty = !mapping || mapping->a_ops->migratepage;
Mel Gorman69d763f2018-01-31 16:19:52 -08001945 unlock_page(page);
1946 if (!migrate_dirty)
Alex Shic2135f72021-02-24 12:08:01 -08001947 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001948 }
1949 }
Minchan Kim39deaf82011-10-31 17:06:51 -07001950
Minchan Kimf80c0672011-10-31 17:06:55 -07001951 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
Alex Shic2135f72021-02-24 12:08:01 -08001952 return false;
Minchan Kimf80c0672011-10-31 17:06:55 -07001953
Alex Shic2135f72021-02-24 12:08:01 -08001954 return true;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001955}
1956
Mel Gorman7ee36a12016-07-28 15:47:17 -07001957/*
1958 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001959 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001960 */
1961static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001962 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001963{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001964 int zid;
1965
Mel Gorman7ee36a12016-07-28 15:47:17 -07001966 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1967 if (!nr_zone_taken[zid])
1968 continue;
1969
Wei Yanga892cb62020-06-03 16:01:12 -07001970 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001971 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001972
Mel Gorman7ee36a12016-07-28 15:47:17 -07001973}
1974
Mel Gormanf611fab2021-06-30 18:53:19 -07001975/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001976 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1977 *
1978 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001979 * shrink the lists perform better by taking out a batch of pages
1980 * and working on them outside the LRU lock.
1981 *
1982 * For pagecache intensive workloads, this function is the hottest
1983 * spot in the kernel (apart from copy_*_user functions).
1984 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001985 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001986 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001987 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001988 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001989 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001990 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001991 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001992 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001993 *
1994 * returns how many pages were moved onto *@dst.
1995 */
Andrew Morton69e05942006-03-22 00:08:19 -08001996static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001997 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001998 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001999 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002000{
Hugh Dickins75b00af2012-05-29 15:07:09 -07002001 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08002002 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07002003 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002004 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07002005 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002006 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002007 LIST_HEAD(pages_skipped);
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002008 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002009
Yang Shi98879b32019-07-11 20:59:30 -07002010 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002011 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07002012 while (scan < nr_to_scan && !list_empty(src)) {
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002013 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002014
Linus Torvalds1da177e2005-04-16 15:20:36 -07002015 page = lru_to_page(src);
2016 prefetchw_prev_lru_page(page, src, flags);
2017
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002018 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002019 total_scan += nr_pages;
2020
Mel Gormanb2e18752016-07-28 15:45:37 -07002021 if (page_zonenum(page) > sc->reclaim_idx) {
2022 list_move(&page->lru, &pages_skipped);
Yang Shi98879b32019-07-11 20:59:30 -07002023 nr_skipped[page_zonenum(page)] += nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002024 continue;
2025 }
2026
Minchan Kim791b48b2017-05-12 15:47:06 -07002027 /*
2028 * Do not count skipped pages because that makes the function
2029 * return with no isolated pages if the LRU mostly contains
2030 * ineligible pages. This causes the VM to not reclaim any
2031 * pages, triggering a premature OOM.
Yang Shi98879b32019-07-11 20:59:30 -07002032 *
2033 * Account all tail pages of THP. This would not cause
2034 * premature OOM since __isolate_lru_page() returns -EBUSY
2035 * only when the page is being freed somewhere else.
Minchan Kim791b48b2017-05-12 15:47:06 -07002036 */
Yang Shi98879b32019-07-11 20:59:30 -07002037 scan += nr_pages;
Alex Shic2135f72021-02-24 12:08:01 -08002038 if (!__isolate_lru_page_prepare(page, mode)) {
2039 /* It is being freed elsewhere */
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002040 list_move(&page->lru, src);
Alex Shic2135f72021-02-24 12:08:01 -08002041 continue;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002042 }
Alex Shic2135f72021-02-24 12:08:01 -08002043 /*
2044 * Be careful not to clear PageLRU until after we're
2045 * sure the page is not being freed elsewhere -- the
2046 * page release code relies on it.
2047 */
2048 if (unlikely(!get_page_unless_zero(page))) {
2049 list_move(&page->lru, src);
2050 continue;
2051 }
2052
2053 if (!TestClearPageLRU(page)) {
2054 /* Another thread is already isolating this page */
2055 put_page(page);
2056 list_move(&page->lru, src);
2057 continue;
2058 }
2059
2060 nr_taken += nr_pages;
2061 nr_zone_taken[page_zonenum(page)] += nr_pages;
2062 list_move(&page->lru, dst);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002063 }
2064
Mel Gormanb2e18752016-07-28 15:45:37 -07002065 /*
2066 * Splice any skipped pages to the start of the LRU list. Note that
2067 * this disrupts the LRU order when reclaiming for lower zones but
2068 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2069 * scanning would soon rescan the same pages to skip and put the
2070 * system at risk of premature OOM.
2071 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002072 if (!list_empty(&pages_skipped)) {
2073 int zid;
2074
Johannes Weiner3db65812017-05-03 14:52:13 -07002075 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002076 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2077 if (!nr_skipped[zid])
2078 continue;
2079
2080 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002081 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002082 }
2083 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002084 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002085 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Minchan Kim791b48b2017-05-12 15:47:06 -07002086 total_scan, skipped, nr_taken, mode, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002087 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002088 return nr_taken;
2089}
2090
Nick Piggin62695a82008-10-18 20:26:09 -07002091/**
2092 * isolate_lru_page - tries to isolate a page from its LRU list
2093 * @page: page to isolate from its LRU list
2094 *
2095 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2096 * vmstat statistic corresponding to whatever LRU list the page was on.
2097 *
2098 * Returns 0 if the page was removed from an LRU list.
2099 * Returns -EBUSY if the page was not on an LRU list.
2100 *
2101 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002102 * the active list, it will have PageActive set. If it was found on
2103 * the unevictable list, it will have the PageUnevictable bit set. That flag
2104 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002105 *
2106 * The vmstat statistic corresponding to the list on which the page was
2107 * found will be decremented.
2108 *
2109 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002110 *
Nick Piggin62695a82008-10-18 20:26:09 -07002111 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002112 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002113 * without a stable reference).
2114 * (2) the lru_lock must not be held.
2115 * (3) interrupts must be enabled.
2116 */
2117int isolate_lru_page(struct page *page)
2118{
2119 int ret = -EBUSY;
2120
Sasha Levin309381fea2014-01-23 15:52:54 -08002121 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002122 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002123
Alex Shid25b5bd2020-12-15 12:34:16 -08002124 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002125 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002126
Alex Shid25b5bd2020-12-15 12:34:16 -08002127 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002128 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002129 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002130 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002131 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002132 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002133
Nick Piggin62695a82008-10-18 20:26:09 -07002134 return ret;
2135}
2136
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002137/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002138 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002139 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002140 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2141 * the LRU list will go small and be scanned faster than necessary, leading to
2142 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002143 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002144static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002145 struct scan_control *sc)
2146{
2147 unsigned long inactive, isolated;
2148
2149 if (current_is_kswapd())
2150 return 0;
2151
Johannes Weinerb5ead352019-11-30 17:55:40 -08002152 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002153 return 0;
2154
2155 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002156 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2157 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002158 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002159 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2160 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002161 }
2162
Fengguang Wu3cf23842012-12-18 14:23:31 -08002163 /*
2164 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2165 * won't get blocked by normal direct-reclaimers, forming a circular
2166 * deadlock.
2167 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002168 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002169 inactive >>= 3;
2170
Rik van Riel35cd7812009-09-21 17:01:38 -07002171 return isolated > inactive;
2172}
2173
Kirill Tkhaia222f342019-05-13 17:17:00 -07002174/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002175 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2176 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002177 *
2178 * Returns the number of pages moved to the given lruvec.
2179 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002180static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2181 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002182{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002183 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002184 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002185 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002186
Kirill Tkhaia222f342019-05-13 17:17:00 -07002187 while (!list_empty(list)) {
2188 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002189 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002190 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002191 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002192 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002193 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002194 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002195 continue;
2196 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002197
Alex Shi3d06afa2020-12-15 12:33:37 -08002198 /*
2199 * The SetPageLRU needs to be kept here for list integrity.
2200 * Otherwise:
2201 * #0 move_pages_to_lru #1 release_pages
2202 * if !put_page_testzero
2203 * if (put_page_testzero())
2204 * !PageLRU //skip lru_lock
2205 * SetPageLRU()
2206 * list_add(&page->lru,)
2207 * list_add(&page->lru,)
2208 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002209 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002210
Alex Shi3d06afa2020-12-15 12:33:37 -08002211 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002212 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002213
2214 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002215 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002216 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002217 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002218 } else
2219 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002220
2221 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002222 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002223
Alex Shiafca9152020-12-15 12:34:02 -08002224 /*
2225 * All pages were isolated from the same lruvec (and isolation
2226 * inhibits memcg migration).
2227 */
Muchun Song7467c392021-06-28 19:37:59 -07002228 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002229 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002230 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002231 nr_moved += nr_pages;
2232 if (PageActive(page))
2233 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002234 }
Mel Gorman66635622010-08-09 17:19:30 -07002235
Hugh Dickins3f797682012-01-12 17:20:07 -08002236 /*
2237 * To save our caller's stack, now use input list for pages to free.
2238 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002239 list_splice(&pages_to_free, list);
2240
2241 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002242}
2243
2244/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002245 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002246 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002247 * In that case we should only throttle if the backing device it is
2248 * writing to is congested. In other cases it is safe to throttle.
2249 */
2250static int current_may_throttle(void)
2251{
NeilBrowna37b0712020-06-01 21:48:18 -07002252 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002253 current->backing_dev_info == NULL ||
2254 bdi_write_congested(current->backing_dev_info);
2255}
2256
2257/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002258 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002259 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002260 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002261static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002262shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002263 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002264{
2265 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002266 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002267 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002268 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002269 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002270 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002271 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002272 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002273 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002274
Mel Gorman599d0c92016-07-28 15:45:31 -07002275 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002276 if (stalled)
2277 return 0;
2278
2279 /* wait a bit for the reclaimer. */
2280 msleep(100);
2281 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002282
2283 /* We are about to die and free our memory. Return now. */
2284 if (fatal_signal_pending(current))
2285 return SWAP_CLUSTER_MAX;
2286 }
2287
Linus Torvalds1da177e2005-04-16 15:20:36 -07002288 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002289
Alex Shi6168d0d2020-12-15 12:34:29 -08002290 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002291
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002292 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002293 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002294
Mel Gorman599d0c92016-07-28 15:45:31 -07002295 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002296 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002297 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002298 __count_vm_events(item, nr_scanned);
2299 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002300 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2301
Alex Shi6168d0d2020-12-15 12:34:29 -08002302 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002303
Hillf Dantond563c052012-03-21 16:34:02 -07002304 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002305 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002306
Shakeel Butt013339d2020-12-14 19:06:39 -08002307 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002308
Alex Shi6168d0d2020-12-15 12:34:29 -08002309 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002310 move_pages_to_lru(lruvec, &page_list);
2311
2312 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002313 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002314 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002315 __count_vm_events(item, nr_reclaimed);
2316 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002317 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002318 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002319
Alex Shi75cc3c92020-12-15 14:20:50 -08002320 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002321 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002322 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002323
Mel Gorman92df3a72011-10-31 17:07:56 -07002324 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002325 * If dirty pages are scanned that are not queued for IO, it
2326 * implies that flushers are not doing their job. This can
2327 * happen when memory pressure pushes dirty pages to the end of
2328 * the LRU before the dirty limits are breached and the dirty
2329 * data has expired. It can also happen when the proportion of
2330 * dirty pages grows not through writes but through memory
2331 * pressure reclaiming all the clean cache. And in some cases,
2332 * the flushers simply cannot keep up with the allocation
2333 * rate. Nudge the flusher threads in case they are asleep.
2334 */
2335 if (stat.nr_unqueued_dirty == nr_taken)
2336 wakeup_flusher_threads(WB_REASON_VMSCAN);
2337
Andrey Ryabinind108c772018-04-10 16:27:59 -07002338 sc->nr.dirty += stat.nr_dirty;
2339 sc->nr.congested += stat.nr_congested;
2340 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2341 sc->nr.writeback += stat.nr_writeback;
2342 sc->nr.immediate += stat.nr_immediate;
2343 sc->nr.taken += nr_taken;
2344 if (file)
2345 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002346
Mel Gorman599d0c92016-07-28 15:45:31 -07002347 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002348 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002349 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002350}
2351
Hugh Dickins15b44732020-12-15 14:21:31 -08002352/*
2353 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2354 *
2355 * We move them the other way if the page is referenced by one or more
2356 * processes.
2357 *
2358 * If the pages are mostly unmapped, the processing is fast and it is
2359 * appropriate to hold lru_lock across the whole operation. But if
2360 * the pages are mapped, the processing is slow (page_referenced()), so
2361 * we should drop lru_lock around each page. It's impossible to balance
2362 * this, so instead we remove the pages from the LRU while processing them.
2363 * It is safe to rely on PG_active against the non-LRU pages in here because
2364 * nobody will play with that bit on a non-LRU page.
2365 *
2366 * The downside is that we have to touch page->_refcount against each page.
2367 * But we had to alter page->flags anyway.
2368 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002369static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002370 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002371 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002372 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002373{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002374 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002375 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002376 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002377 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002378 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002379 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002380 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002381 unsigned nr_deactivate, nr_activate;
2382 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002383 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002384 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002385 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002386
2387 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002388
Alex Shi6168d0d2020-12-15 12:34:29 -08002389 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002390
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002391 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002392 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002393
Mel Gorman599d0c92016-07-28 15:45:31 -07002394 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002395
Shakeel Butt912c0572020-08-06 23:26:32 -07002396 if (!cgroup_reclaim(sc))
2397 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002398 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002399
Alex Shi6168d0d2020-12-15 12:34:29 -08002400 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002401
Linus Torvalds1da177e2005-04-16 15:20:36 -07002402 while (!list_empty(&l_hold)) {
2403 cond_resched();
2404 page = lru_to_page(&l_hold);
2405 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002406
Hugh Dickins39b5f292012-10-08 16:33:18 -07002407 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002408 putback_lru_page(page);
2409 continue;
2410 }
2411
Mel Gormancc715d92012-03-21 16:34:00 -07002412 if (unlikely(buffer_heads_over_limit)) {
2413 if (page_has_private(page) && trylock_page(page)) {
2414 if (page_has_private(page))
2415 try_to_release_page(page, 0);
2416 unlock_page(page);
2417 }
2418 }
2419
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002420 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2421 if (bypass)
2422 goto skip_page_referenced;
2423
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002424 if (page_referenced(page, 0, sc->target_mem_cgroup,
2425 &vm_flags)) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002426 /*
2427 * Identify referenced, file-backed active pages and
2428 * give them one more trip around the active list. So
2429 * that executable code get better chances to stay in
2430 * memory under moderate memory pressure. Anon pages
2431 * are not likely to be evicted by use-once streaming
2432 * IO, plus JVM can create lots of anon VM_EXEC pages,
2433 * so we ignore them here.
2434 */
Huang Ying9de4f222020-04-06 20:04:41 -07002435 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002436 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002437 list_add(&page->lru, &l_active);
2438 continue;
2439 }
2440 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002441skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002442 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002443 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002444 list_add(&page->lru, &l_inactive);
2445 }
2446
Andrew Mortonb5557492009-01-06 14:40:13 -08002447 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002448 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002449 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002450 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002451
Kirill Tkhaia222f342019-05-13 17:17:00 -07002452 nr_activate = move_pages_to_lru(lruvec, &l_active);
2453 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002454 /* Keep all free pages in l_active list */
2455 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002456
2457 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2458 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2459
Mel Gorman599d0c92016-07-28 15:45:31 -07002460 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002461 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002462
Kirill Tkhaif372d892019-05-13 17:16:57 -07002463 mem_cgroup_uncharge_list(&l_active);
2464 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002465 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2466 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002467}
2468
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002469unsigned long reclaim_pages(struct list_head *page_list)
2470{
Yang Shif661d002020-04-01 21:10:05 -07002471 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002472 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002473 LIST_HEAD(node_page_list);
2474 struct reclaim_stat dummy_stat;
2475 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002476 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002477 struct scan_control sc = {
2478 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002479 .may_writepage = 1,
2480 .may_unmap = 1,
2481 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002482 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002483 };
2484
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002485 noreclaim_flag = memalloc_noreclaim_save();
2486
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002487 while (!list_empty(page_list)) {
2488 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002489 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002490 nid = page_to_nid(page);
2491 INIT_LIST_HEAD(&node_page_list);
2492 }
2493
2494 if (nid == page_to_nid(page)) {
2495 ClearPageActive(page);
2496 list_move(&page->lru, &node_page_list);
2497 continue;
2498 }
2499
2500 nr_reclaimed += shrink_page_list(&node_page_list,
2501 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002502 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002503 while (!list_empty(&node_page_list)) {
2504 page = lru_to_page(&node_page_list);
2505 list_del(&page->lru);
2506 putback_lru_page(page);
2507 }
2508
Yang Shif661d002020-04-01 21:10:05 -07002509 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002510 }
2511
2512 if (!list_empty(&node_page_list)) {
2513 nr_reclaimed += shrink_page_list(&node_page_list,
2514 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002515 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002516 while (!list_empty(&node_page_list)) {
2517 page = lru_to_page(&node_page_list);
2518 list_del(&page->lru);
2519 putback_lru_page(page);
2520 }
2521 }
2522
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002523 memalloc_noreclaim_restore(noreclaim_flag);
2524
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002525 return nr_reclaimed;
2526}
2527
Johannes Weinerb91ac372019-11-30 17:56:02 -08002528static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2529 struct lruvec *lruvec, struct scan_control *sc)
2530{
2531 if (is_active_lru(lru)) {
2532 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2533 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2534 else
2535 sc->skipped_deactivate = 1;
2536 return 0;
2537 }
2538
2539 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2540}
2541
Rik van Riel59dc76b2016-05-20 16:56:31 -07002542/*
2543 * The inactive anon list should be small enough that the VM never has
2544 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002545 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002546 * The inactive file list should be small enough to leave most memory
2547 * to the established workingset on the scan-resistant active list,
2548 * but large enough to avoid thrashing the aggregate readahead window.
2549 *
2550 * Both inactive lists should also be large enough that each inactive
2551 * page has a chance to be referenced again before it is reclaimed.
2552 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002553 * If that fails and refaulting is observed, the inactive list grows.
2554 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002555 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002556 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002557 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2558 *
2559 * total target max
2560 * memory ratio inactive
2561 * -------------------------------------
2562 * 10MB 1 5MB
2563 * 100MB 1 50MB
2564 * 1GB 3 250MB
2565 * 10GB 10 0.9GB
2566 * 100GB 31 3GB
2567 * 1TB 101 10GB
2568 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002569 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002570static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002571{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002572 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002573 unsigned long inactive, active;
2574 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002575 unsigned long gb;
2576
Johannes Weinerb91ac372019-11-30 17:56:02 -08002577 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2578 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002579
Johannes Weinerb91ac372019-11-30 17:56:02 -08002580 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002581 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002582 inactive_ratio = int_sqrt(10 * gb);
2583 else
2584 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002585
Rik van Riel59dc76b2016-05-20 16:56:31 -07002586 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002587}
2588
Johannes Weiner9a265112013-02-22 16:32:17 -08002589enum scan_balance {
2590 SCAN_EQUAL,
2591 SCAN_FRACT,
2592 SCAN_ANON,
2593 SCAN_FILE,
2594};
2595
Yu Zhao6d313442022-09-18 02:00:00 -06002596static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2597{
2598 unsigned long file;
2599 struct lruvec *target_lruvec;
2600
Yu Zhao37397872022-09-18 02:00:03 -06002601 if (lru_gen_enabled())
2602 return;
2603
Yu Zhao6d313442022-09-18 02:00:00 -06002604 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2605
2606 /*
2607 * Flush the memory cgroup stats, so that we read accurate per-memcg
2608 * lruvec stats for heuristics.
2609 */
2610 mem_cgroup_flush_stats();
2611
2612 /*
2613 * Determine the scan balance between anon and file LRUs.
2614 */
2615 spin_lock_irq(&target_lruvec->lru_lock);
2616 sc->anon_cost = target_lruvec->anon_cost;
2617 sc->file_cost = target_lruvec->file_cost;
2618 spin_unlock_irq(&target_lruvec->lru_lock);
2619
2620 /*
2621 * Target desirable inactive:active list ratios for the anon
2622 * and file LRU lists.
2623 */
2624 if (!sc->force_deactivate) {
2625 unsigned long refaults;
2626
2627 refaults = lruvec_page_state(target_lruvec,
2628 WORKINGSET_ACTIVATE_ANON);
2629 if (refaults != target_lruvec->refaults[0] ||
2630 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2631 sc->may_deactivate |= DEACTIVATE_ANON;
2632 else
2633 sc->may_deactivate &= ~DEACTIVATE_ANON;
2634
2635 /*
2636 * When refaults are being observed, it means a new
2637 * workingset is being established. Deactivate to get
2638 * rid of any stale active pages quickly.
2639 */
2640 refaults = lruvec_page_state(target_lruvec,
2641 WORKINGSET_ACTIVATE_FILE);
2642 if (refaults != target_lruvec->refaults[1] ||
2643 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2644 sc->may_deactivate |= DEACTIVATE_FILE;
2645 else
2646 sc->may_deactivate &= ~DEACTIVATE_FILE;
2647 } else
2648 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2649
2650 /*
2651 * If we have plenty of inactive file pages that aren't
2652 * thrashing, try to reclaim those first before touching
2653 * anonymous pages.
2654 */
2655 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2656 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2657 sc->cache_trim_mode = 1;
2658 else
2659 sc->cache_trim_mode = 0;
2660
2661 /*
2662 * Prevent the reclaimer from falling into the cache trap: as
2663 * cache pages start out inactive, every cache fault will tip
2664 * the scan balance towards the file LRU. And as the file LRU
2665 * shrinks, so does the window for rotation from references.
2666 * This means we have a runaway feedback loop where a tiny
2667 * thrashing file LRU becomes infinitely more attractive than
2668 * anon pages. Try to detect this based on file LRU size.
2669 */
2670 if (!cgroup_reclaim(sc)) {
2671 unsigned long total_high_wmark = 0;
2672 unsigned long free, anon;
2673 int z;
2674
2675 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2676 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2677 node_page_state(pgdat, NR_INACTIVE_FILE);
2678
2679 for (z = 0; z < MAX_NR_ZONES; z++) {
2680 struct zone *zone = &pgdat->node_zones[z];
2681
2682 if (!managed_zone(zone))
2683 continue;
2684
2685 total_high_wmark += high_wmark_pages(zone);
2686 }
2687
2688 /*
2689 * Consider anon: if that's low too, this isn't a
2690 * runaway file reclaim problem, but rather just
2691 * extreme pressure. Reclaim as per usual then.
2692 */
2693 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2694
2695 sc->file_is_tiny =
2696 file + free <= total_high_wmark &&
2697 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2698 anon >> sc->priority;
2699 }
2700}
2701
Linus Torvalds1da177e2005-04-16 15:20:36 -07002702/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002703 * Determine how aggressively the anon and file LRU lists should be
2704 * scanned. The relative value of each set of LRU lists is determined
2705 * by looking at the fraction of the pages scanned we did rotate back
2706 * onto the active list instead of evict.
2707 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002708 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2709 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002710 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002711static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2712 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002713{
Keith Buscha2a36482021-09-02 14:59:26 -07002714 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002715 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002716 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002717 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002718 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002719 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002720 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002721 unsigned long ap, fp;
2722 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002723 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002724
2725 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002726 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002727 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002728 goto out;
2729 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002730
Johannes Weiner10316b32013-02-22 16:32:14 -08002731 /*
2732 * Global reclaim will swap to prevent OOM even with no
2733 * swappiness, but memcg users want to use this knob to
2734 * disable swapping for individual groups completely when
2735 * using the memory controller's swap limit feature would be
2736 * too expensive.
2737 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002738 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002739 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002740 goto out;
2741 }
2742
2743 /*
2744 * Do not apply any pressure balancing cleverness when the
2745 * system is close to OOM, scan both anon and file equally
2746 * (unless the swappiness setting disagrees with swapping).
2747 */
Johannes Weiner02695172014-08-06 16:06:17 -07002748 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002749 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002750 goto out;
2751 }
2752
Johannes Weiner11d16c22013-02-22 16:32:15 -08002753 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002754 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002755 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002756 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002757 scan_balance = SCAN_ANON;
2758 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002759 }
2760
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002761 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2762
Johannes Weiner62376252014-05-06 12:50:07 -07002763 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002764 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002765 * anything from the anonymous working right now. But when balancing
2766 * anon and page cache files for reclaim, allow swapping of anon pages
2767 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002768 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002769 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002770 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002771 goto out;
2772 }
2773
Johannes Weiner9a265112013-02-22 16:32:17 -08002774 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002775 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002776 * Calculate the pressure balance between anon and file pages.
2777 *
2778 * The amount of pressure we put on each LRU is inversely
2779 * proportional to the cost of reclaiming each list, as
2780 * determined by the share of pages that are refaulting, times
2781 * the relative IO cost of bringing back a swapped out
2782 * anonymous page vs reloading a filesystem page (swappiness).
2783 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002784 * Although we limit that influence to ensure no list gets
2785 * left behind completely: at least a third of the pressure is
2786 * applied, before swappiness.
2787 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002788 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002789 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002790 total_cost = sc->anon_cost + sc->file_cost;
2791 anon_cost = total_cost + sc->anon_cost;
2792 file_cost = total_cost + sc->file_cost;
2793 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002794
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002795 ap = swappiness * (total_cost + 1);
2796 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002797
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002798 fp = (200 - swappiness) * (total_cost + 1);
2799 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002800
Shaohua Li76a33fc2010-05-24 14:32:36 -07002801 fraction[0] = ap;
2802 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002803 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002804out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002805 for_each_evictable_lru(lru) {
2806 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002807 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002808 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002809 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002810
Chris Down9783aa92019-10-06 17:58:32 -07002811 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002812 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2813 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002814
Johannes Weinerf56ce412021-08-19 19:04:21 -07002815 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002816 /*
2817 * Scale a cgroup's reclaim pressure by proportioning
2818 * its current usage to its memory.low or memory.min
2819 * setting.
2820 *
2821 * This is important, as otherwise scanning aggression
2822 * becomes extremely binary -- from nothing as we
2823 * approach the memory protection threshold, to totally
2824 * nominal as we exceed it. This results in requiring
2825 * setting extremely liberal protection thresholds. It
2826 * also means we simply get no protection at all if we
2827 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002828 *
2829 * If there is any protection in place, we reduce scan
2830 * pressure by how much of the total memory used is
2831 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002832 *
Chris Down9de7ca42019-10-06 17:58:35 -07002833 * There is one special case: in the first reclaim pass,
2834 * we skip over all groups that are within their low
2835 * protection. If that fails to reclaim enough pages to
2836 * satisfy the reclaim goal, we come back and override
2837 * the best-effort low protection. However, we still
2838 * ideally want to honor how well-behaved groups are in
2839 * that case instead of simply punishing them all
2840 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002841 * memory they are using, reducing the scan pressure
2842 * again by how much of the total memory used is under
2843 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002844 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002845 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002846 unsigned long protection;
2847
2848 /* memory.low scaling, make sure we retry before OOM */
2849 if (!sc->memcg_low_reclaim && low > min) {
2850 protection = low;
2851 sc->memcg_low_skipped = 1;
2852 } else {
2853 protection = min;
2854 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002855
2856 /* Avoid TOCTOU with earlier protection check */
2857 cgroup_size = max(cgroup_size, protection);
2858
2859 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002860 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002861
2862 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002863 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002864 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002865 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002866 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002867 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002868 } else {
2869 scan = lruvec_size;
2870 }
2871
2872 scan >>= sc->priority;
2873
Johannes Weiner688035f2017-05-03 14:52:07 -07002874 /*
2875 * If the cgroup's already been deleted, make sure to
2876 * scrape out the remaining cache.
2877 */
2878 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002879 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002880
Johannes Weiner688035f2017-05-03 14:52:07 -07002881 switch (scan_balance) {
2882 case SCAN_EQUAL:
2883 /* Scan lists relative to size */
2884 break;
2885 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002886 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002887 * Scan types proportional to swappiness and
2888 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002889 * Make sure we don't miss the last page on
2890 * the offlined memory cgroups because of a
2891 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002892 */
Gavin Shan76073c62020-02-20 20:04:24 -08002893 scan = mem_cgroup_online(memcg) ?
2894 div64_u64(scan * fraction[file], denominator) :
2895 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002896 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002897 break;
2898 case SCAN_FILE:
2899 case SCAN_ANON:
2900 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002901 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002902 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002903 break;
2904 default:
2905 /* Look ma, no brain */
2906 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002907 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002908
Johannes Weiner688035f2017-05-03 14:52:07 -07002909 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002910 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002911}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002912
Dave Hansen2f368a92021-09-02 14:59:23 -07002913/*
2914 * Anonymous LRU management is a waste if there is
2915 * ultimately no way to reclaim the memory.
2916 */
2917static bool can_age_anon_pages(struct pglist_data *pgdat,
2918 struct scan_control *sc)
2919{
2920 /* Aging the anon LRU is valuable if swap is present: */
2921 if (total_swap_pages > 0)
2922 return true;
2923
2924 /* Also valuable if anon pages can be demoted: */
2925 return can_demote(pgdat->node_id, sc);
2926}
2927
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002928#ifdef CONFIG_LRU_GEN
2929
2930/******************************************************************************
2931 * shorthand helpers
2932 ******************************************************************************/
2933
Yu Zhao37397872022-09-18 02:00:03 -06002934#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2935
2936#define DEFINE_MAX_SEQ(lruvec) \
2937 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2938
2939#define DEFINE_MIN_SEQ(lruvec) \
2940 unsigned long min_seq[ANON_AND_FILE] = { \
2941 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2942 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2943 }
2944
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002945#define for_each_gen_type_zone(gen, type, zone) \
2946 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2947 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2948 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2949
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002950static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002951{
2952 struct pglist_data *pgdat = NODE_DATA(nid);
2953
2954#ifdef CONFIG_MEMCG
2955 if (memcg) {
2956 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2957
2958 /* for hotadd_new_pgdat() */
2959 if (!lruvec->pgdat)
2960 lruvec->pgdat = pgdat;
2961
2962 return lruvec;
2963 }
2964#endif
2965 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2966
2967 return pgdat ? &pgdat->__lruvec : NULL;
2968}
2969
Yu Zhao37397872022-09-18 02:00:03 -06002970static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2971{
2972 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2973 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2974
2975 if (!can_demote(pgdat->node_id, sc) &&
2976 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2977 return 0;
2978
2979 return mem_cgroup_swappiness(memcg);
2980}
2981
2982static int get_nr_gens(struct lruvec *lruvec, int type)
2983{
2984 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2985}
2986
2987static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2988{
2989 /* see the comment on lru_gen_struct */
2990 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2991 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2992 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2993}
2994
2995/******************************************************************************
Yu Zhao7f53b0e2022-09-18 02:00:05 -06002996 * mm_struct list
2997 ******************************************************************************/
2998
2999static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3000{
3001 static struct lru_gen_mm_list mm_list = {
3002 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3003 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3004 };
3005
3006#ifdef CONFIG_MEMCG
3007 if (memcg)
3008 return &memcg->mm_list;
3009#endif
3010 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
3011
3012 return &mm_list;
3013}
3014
3015void lru_gen_add_mm(struct mm_struct *mm)
3016{
3017 int nid;
3018 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3019 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3020
3021 VM_WARN_ON_ONCE(!list_empty(&mm->lru_gen.list));
3022#ifdef CONFIG_MEMCG
3023 VM_WARN_ON_ONCE(mm->lru_gen.memcg);
3024 mm->lru_gen.memcg = memcg;
3025#endif
3026 spin_lock(&mm_list->lock);
3027
3028 for_each_node_state(nid, N_MEMORY) {
3029 struct lruvec *lruvec = get_lruvec(memcg, nid);
3030
3031 if (!lruvec)
3032 continue;
3033
3034 /* the first addition since the last iteration */
3035 if (lruvec->mm_state.tail == &mm_list->fifo)
3036 lruvec->mm_state.tail = &mm->lru_gen.list;
3037 }
3038
3039 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3040
3041 spin_unlock(&mm_list->lock);
3042}
3043
3044void lru_gen_del_mm(struct mm_struct *mm)
3045{
3046 int nid;
3047 struct lru_gen_mm_list *mm_list;
3048 struct mem_cgroup *memcg = NULL;
3049
3050 if (list_empty(&mm->lru_gen.list))
3051 return;
3052
3053#ifdef CONFIG_MEMCG
3054 memcg = mm->lru_gen.memcg;
3055#endif
3056 mm_list = get_mm_list(memcg);
3057
3058 spin_lock(&mm_list->lock);
3059
3060 for_each_node(nid) {
3061 struct lruvec *lruvec = get_lruvec(memcg, nid);
3062
3063 if (!lruvec)
3064 continue;
3065
3066 /* where the last iteration ended (exclusive) */
3067 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3068 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3069
3070 /* where the current iteration continues (inclusive) */
3071 if (lruvec->mm_state.head != &mm->lru_gen.list)
3072 continue;
3073
3074 lruvec->mm_state.head = lruvec->mm_state.head->next;
3075 /* the deletion ends the current iteration */
3076 if (lruvec->mm_state.head == &mm_list->fifo)
3077 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3078 }
3079
3080 list_del_init(&mm->lru_gen.list);
3081
3082 spin_unlock(&mm_list->lock);
3083
3084#ifdef CONFIG_MEMCG
3085 mem_cgroup_put(mm->lru_gen.memcg);
3086 mm->lru_gen.memcg = NULL;
3087#endif
3088}
3089
3090#ifdef CONFIG_MEMCG
3091void lru_gen_migrate_mm(struct mm_struct *mm)
3092{
3093 struct mem_cgroup *memcg;
3094 struct task_struct *task = rcu_dereference_protected(mm->owner, true);
3095
3096 VM_WARN_ON_ONCE(task->mm != mm);
3097 lockdep_assert_held(&task->alloc_lock);
3098
3099 /* for mm_update_next_owner() */
3100 if (mem_cgroup_disabled())
3101 return;
3102
3103 rcu_read_lock();
3104 memcg = mem_cgroup_from_task(task);
3105 rcu_read_unlock();
3106 if (memcg == mm->lru_gen.memcg)
3107 return;
3108
3109 VM_WARN_ON_ONCE(!mm->lru_gen.memcg);
3110 VM_WARN_ON_ONCE(list_empty(&mm->lru_gen.list));
3111
3112 lru_gen_del_mm(mm);
3113 lru_gen_add_mm(mm);
3114}
3115#endif
3116
3117/*
3118 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3119 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3120 * bits in a bitmap, k is the number of hash functions and n is the number of
3121 * inserted items.
3122 *
3123 * Page table walkers use one of the two filters to reduce their search space.
3124 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3125 * aging uses the double-buffering technique to flip to the other filter each
3126 * time it produces a new generation. For non-leaf entries that have enough
3127 * leaf entries, the aging carries them over to the next generation in
3128 * walk_pmd_range(); the eviction also report them when walking the rmap
3129 * in lru_gen_look_around().
3130 *
3131 * For future optimizations:
3132 * 1. It's not necessary to keep both filters all the time. The spare one can be
3133 * freed after the RCU grace period and reallocated if needed again.
3134 * 2. And when reallocating, it's worth scaling its size according to the number
3135 * of inserted entries in the other filter, to reduce the memory overhead on
3136 * small systems and false positives on large systems.
3137 * 3. Jenkins' hash function is an alternative to Knuth's.
3138 */
3139#define BLOOM_FILTER_SHIFT 15
3140
3141static inline int filter_gen_from_seq(unsigned long seq)
3142{
3143 return seq % NR_BLOOM_FILTERS;
3144}
3145
3146static void get_item_key(void *item, int *key)
3147{
3148 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3149
3150 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3151
3152 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3153 key[1] = hash >> BLOOM_FILTER_SHIFT;
3154}
3155
3156static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3157{
3158 unsigned long *filter;
3159 int gen = filter_gen_from_seq(seq);
3160
3161 filter = lruvec->mm_state.filters[gen];
3162 if (filter) {
3163 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3164 return;
3165 }
3166
3167 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT),
3168 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
3169 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3170}
3171
3172static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3173{
3174 int key[2];
3175 unsigned long *filter;
3176 int gen = filter_gen_from_seq(seq);
3177
3178 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3179 if (!filter)
3180 return;
3181
3182 get_item_key(item, key);
3183
3184 if (!test_bit(key[0], filter))
3185 set_bit(key[0], filter);
3186 if (!test_bit(key[1], filter))
3187 set_bit(key[1], filter);
3188}
3189
3190static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3191{
3192 int key[2];
3193 unsigned long *filter;
3194 int gen = filter_gen_from_seq(seq);
3195
3196 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3197 if (!filter)
3198 return true;
3199
3200 get_item_key(item, key);
3201
3202 return test_bit(key[0], filter) && test_bit(key[1], filter);
3203}
3204
3205static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3206{
3207 int i;
3208 int hist;
3209
3210 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3211
3212 if (walk) {
3213 hist = lru_hist_from_seq(walk->max_seq);
3214
3215 for (i = 0; i < NR_MM_STATS; i++) {
3216 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3217 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3218 walk->mm_stats[i] = 0;
3219 }
3220 }
3221
3222 if (NR_HIST_GENS > 1 && last) {
3223 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3224
3225 for (i = 0; i < NR_MM_STATS; i++)
3226 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3227 }
3228}
3229
3230static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3231{
3232 int type;
3233 unsigned long size = 0;
3234 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3235 int key = pgdat->node_id % BITS_PER_TYPE(mm->lru_gen.bitmap);
3236
3237 if (!walk->force_scan && !test_bit(key, &mm->lru_gen.bitmap))
3238 return true;
3239
3240 clear_bit(key, &mm->lru_gen.bitmap);
3241
3242 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3243 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3244 get_mm_counter(mm, MM_ANONPAGES) +
3245 get_mm_counter(mm, MM_SHMEMPAGES);
3246 }
3247
3248 if (size < MIN_LRU_BATCH)
3249 return true;
3250
3251 return !mmget_not_zero(mm);
3252}
3253
3254static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3255 struct mm_struct **iter)
3256{
3257 bool first = false;
3258 bool last = true;
3259 struct mm_struct *mm = NULL;
3260 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3261 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3262 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3263
3264 /*
3265 * There are four interesting cases for this page table walker:
3266 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3267 * there is nothing left to do.
3268 * 2. It's the first of the current generation, and it needs to reset
3269 * the Bloom filter for the next generation.
3270 * 3. It reaches the end of mm_list, and it needs to increment
3271 * mm_state->seq; the iteration is done.
3272 * 4. It's the last of the current generation, and it needs to reset the
3273 * mm stats counters for the next generation.
3274 */
3275 spin_lock(&mm_list->lock);
3276
3277 VM_WARN_ON_ONCE(mm_state->seq + 1 < walk->max_seq);
3278 VM_WARN_ON_ONCE(*iter && mm_state->seq > walk->max_seq);
3279 VM_WARN_ON_ONCE(*iter && !mm_state->nr_walkers);
3280
3281 if (walk->max_seq <= mm_state->seq) {
3282 if (!*iter)
3283 last = false;
3284 goto done;
3285 }
3286
3287 if (!mm_state->nr_walkers) {
3288 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3289
3290 mm_state->head = mm_list->fifo.next;
3291 first = true;
3292 }
3293
3294 while (!mm && mm_state->head != &mm_list->fifo) {
3295 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3296
3297 mm_state->head = mm_state->head->next;
3298
3299 /* force scan for those added after the last iteration */
3300 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3301 mm_state->tail = mm_state->head;
3302 walk->force_scan = true;
3303 }
3304
3305 if (should_skip_mm(mm, walk))
3306 mm = NULL;
3307 }
3308
3309 if (mm_state->head == &mm_list->fifo)
3310 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3311done:
3312 if (*iter && !mm)
3313 mm_state->nr_walkers--;
3314 if (!*iter && mm)
3315 mm_state->nr_walkers++;
3316
3317 if (mm_state->nr_walkers)
3318 last = false;
3319
3320 if (*iter || last)
3321 reset_mm_stats(lruvec, walk, last);
3322
3323 spin_unlock(&mm_list->lock);
3324
3325 if (mm && first)
3326 reset_bloom_filter(lruvec, walk->max_seq + 1);
3327
3328 if (*iter)
3329 mmput_async(*iter);
3330
3331 *iter = mm;
3332
3333 return last;
3334}
3335
3336static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3337{
3338 bool success = false;
3339 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3340 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3341 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3342
3343 spin_lock(&mm_list->lock);
3344
3345 VM_WARN_ON_ONCE(mm_state->seq + 1 < max_seq);
3346
3347 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3348 VM_WARN_ON_ONCE(mm_state->head && mm_state->head != &mm_list->fifo);
3349
3350 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3351 reset_mm_stats(lruvec, NULL, true);
3352 success = true;
3353 }
3354
3355 spin_unlock(&mm_list->lock);
3356
3357 return success;
3358}
3359
3360/******************************************************************************
Yu Zhao37397872022-09-18 02:00:03 -06003361 * refault feedback loop
3362 ******************************************************************************/
3363
3364/*
3365 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3366 *
3367 * The P term is refaulted/(evicted+protected) from a tier in the generation
3368 * currently being evicted; the I term is the exponential moving average of the
3369 * P term over the generations previously evicted, using the smoothing factor
3370 * 1/2; the D term isn't supported.
3371 *
3372 * The setpoint (SP) is always the first tier of one type; the process variable
3373 * (PV) is either any tier of the other type or any other tier of the same
3374 * type.
3375 *
3376 * The error is the difference between the SP and the PV; the correction is to
3377 * turn off protection when SP>PV or turn on protection when SP<PV.
3378 *
3379 * For future optimizations:
3380 * 1. The D term may discount the other two terms over time so that long-lived
3381 * generations can resist stale information.
3382 */
3383struct ctrl_pos {
3384 unsigned long refaulted;
3385 unsigned long total;
3386 int gain;
3387};
3388
3389static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3390 struct ctrl_pos *pos)
3391{
3392 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3393 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3394
3395 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3396 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3397 pos->total = lrugen->avg_total[type][tier] +
3398 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3399 if (tier)
3400 pos->total += lrugen->protected[hist][type][tier - 1];
3401 pos->gain = gain;
3402}
3403
3404static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3405{
3406 int hist, tier;
3407 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3408 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3409 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3410
3411 lockdep_assert_held(&lruvec->lru_lock);
3412
3413 if (!carryover && !clear)
3414 return;
3415
3416 hist = lru_hist_from_seq(seq);
3417
3418 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3419 if (carryover) {
3420 unsigned long sum;
3421
3422 sum = lrugen->avg_refaulted[type][tier] +
3423 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3424 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3425
3426 sum = lrugen->avg_total[type][tier] +
3427 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3428 if (tier)
3429 sum += lrugen->protected[hist][type][tier - 1];
3430 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3431 }
3432
3433 if (clear) {
3434 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3435 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3436 if (tier)
3437 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3438 }
3439 }
3440}
3441
3442static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3443{
3444 /*
3445 * Return true if the PV has a limited number of refaults or a lower
3446 * refaulted/total than the SP.
3447 */
3448 return pv->refaulted < MIN_LRU_BATCH ||
3449 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3450 (sp->refaulted + 1) * pv->total * pv->gain;
3451}
3452
3453/******************************************************************************
3454 * the aging
3455 ******************************************************************************/
3456
Yu Zhao0182f922022-09-18 02:00:04 -06003457/* promote pages accessed through page tables */
3458static int page_update_gen(struct page *page, int gen)
3459{
3460 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3461
3462 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3463 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3464
3465 do {
3466 /* lru_gen_del_page() has isolated this page? */
3467 if (!(old_flags & LRU_GEN_MASK)) {
3468 /* for shrink_page_list() */
3469 new_flags = old_flags | BIT(PG_referenced);
3470 continue;
3471 }
3472
3473 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3474 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3475 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3476
3477 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3478}
3479
Yu Zhao37397872022-09-18 02:00:03 -06003480/* protect pages accessed multiple times through file descriptors */
3481static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3482{
3483 int type = page_is_file_lru(page);
3484 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3485 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3486 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3487
3488 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3489
3490 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003491 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3492 /* page_update_gen() has promoted this page? */
3493 if (new_gen >= 0 && new_gen != old_gen)
3494 return new_gen;
3495
Yu Zhao37397872022-09-18 02:00:03 -06003496 new_gen = (old_gen + 1) % MAX_NR_GENS;
3497
3498 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3499 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3500 /* for end_page_writeback() */
3501 if (reclaiming)
3502 new_flags |= BIT(PG_reclaim);
3503 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3504
3505 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3506
3507 return new_gen;
3508}
3509
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003510static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3511 int old_gen, int new_gen)
3512{
3513 int type = page_is_file_lru(page);
3514 int zone = page_zonenum(page);
3515 int delta = thp_nr_pages(page);
3516
3517 VM_WARN_ON_ONCE(old_gen >= MAX_NR_GENS);
3518 VM_WARN_ON_ONCE(new_gen >= MAX_NR_GENS);
3519
3520 walk->batched++;
3521
3522 walk->nr_pages[old_gen][type][zone] -= delta;
3523 walk->nr_pages[new_gen][type][zone] += delta;
3524}
3525
3526static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3527{
3528 int gen, type, zone;
3529 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3530
3531 walk->batched = 0;
3532
3533 for_each_gen_type_zone(gen, type, zone) {
3534 enum lru_list lru = type * LRU_INACTIVE_FILE;
3535 int delta = walk->nr_pages[gen][type][zone];
3536
3537 if (!delta)
3538 continue;
3539
3540 walk->nr_pages[gen][type][zone] = 0;
3541 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3542 lrugen->nr_pages[gen][type][zone] + delta);
3543
3544 if (lru_gen_is_active(lruvec, gen))
3545 lru += LRU_ACTIVE;
3546 __update_lru_size(lruvec, lru, zone, delta);
3547 }
3548}
3549
3550static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *args)
3551{
3552 struct address_space *mapping;
3553 struct vm_area_struct *vma = args->vma;
3554 struct lru_gen_mm_walk *walk = args->private;
3555
3556 if (!vma_is_accessible(vma))
3557 return true;
3558
3559 if (is_vm_hugetlb_page(vma))
3560 return true;
3561
3562 if (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ))
3563 return true;
3564
3565 if (vma == get_gate_vma(vma->vm_mm))
3566 return true;
3567
3568 if (vma_is_anonymous(vma))
3569 return !walk->can_swap;
3570
3571 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3572 return true;
3573
3574 mapping = vma->vm_file->f_mapping;
3575 if (mapping_unevictable(mapping))
3576 return true;
3577
3578 if (shmem_mapping(mapping))
3579 return !walk->can_swap;
3580
3581 /* to exclude special mappings like dax, etc. */
3582 return !mapping->a_ops->readpage;
3583}
3584
3585/*
3586 * Some userspace memory allocators map many single-page VMAs. Instead of
3587 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3588 * table to reduce zigzags and improve cache performance.
3589 */
3590static bool get_next_vma(unsigned long mask, unsigned long size, struct mm_walk *args,
3591 unsigned long *vm_start, unsigned long *vm_end)
3592{
3593 unsigned long start = round_up(*vm_end, size);
3594 unsigned long end = (start | ~mask) + 1;
3595
3596 VM_WARN_ON_ONCE(mask & size);
3597 VM_WARN_ON_ONCE((start & mask) != (*vm_start & mask));
3598
3599 while (args->vma) {
3600 if (start >= args->vma->vm_end) {
3601 args->vma = args->vma->vm_next;
3602 continue;
3603 }
3604
3605 if (end && end <= args->vma->vm_start)
3606 return false;
3607
3608 if (should_skip_vma(args->vma->vm_start, args->vma->vm_end, args)) {
3609 args->vma = args->vma->vm_next;
3610 continue;
3611 }
3612
3613 *vm_start = max(start, args->vma->vm_start);
3614 *vm_end = min(end - 1, args->vma->vm_end - 1) + 1;
3615
3616 return true;
3617 }
3618
3619 return false;
3620}
3621
Yu Zhao0182f922022-09-18 02:00:04 -06003622static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3623{
3624 unsigned long pfn = pte_pfn(pte);
3625
3626 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3627
3628 if (!pte_present(pte) || is_zero_pfn(pfn))
3629 return -1;
3630
3631 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3632 return -1;
3633
3634 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3635 return -1;
3636
3637 return pfn;
3638}
3639
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003640#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3641static unsigned long get_pmd_pfn(pmd_t pmd, struct vm_area_struct *vma, unsigned long addr)
3642{
3643 unsigned long pfn = pmd_pfn(pmd);
3644
3645 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3646
3647 if (!pmd_present(pmd) || is_huge_zero_pmd(pmd))
3648 return -1;
3649
3650 if (WARN_ON_ONCE(pmd_devmap(pmd)))
3651 return -1;
3652
3653 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3654 return -1;
3655
3656 return pfn;
3657}
3658#endif
3659
Yu Zhao0182f922022-09-18 02:00:04 -06003660static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003661 struct pglist_data *pgdat, bool can_swap)
Yu Zhao0182f922022-09-18 02:00:04 -06003662{
3663 struct page *page;
3664
3665 /* try to avoid unnecessary memory loads */
3666 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3667 return NULL;
3668
3669 page = compound_head(pfn_to_page(pfn));
3670 if (page_to_nid(page) != pgdat->node_id)
3671 return NULL;
3672
3673 if (page_memcg_rcu(page) != memcg)
3674 return NULL;
3675
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003676 /* file VMAs can contain anon pages from COW */
3677 if (!page_is_file_lru(page) && !can_swap)
3678 return NULL;
3679
Yu Zhao0182f922022-09-18 02:00:04 -06003680 return page;
3681}
3682
Yu Zhao7f53b0e2022-09-18 02:00:05 -06003683static bool suitable_to_scan(int total, int young)
3684{
3685 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3686
3687 /* suitable if the average number of young PTEs per cacheline is >=1 */
3688 return young * n >= total;
3689}
3690
3691static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3692 struct mm_walk *args)
3693{
3694 int i;
3695 pte_t *pte;
3696 spinlock_t *ptl;
3697 unsigned long addr;
3698 int total = 0;
3699 int young = 0;
3700 struct lru_gen_mm_walk *walk = args->private;
3701 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3702 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3703 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3704
3705 VM_WARN_ON_ONCE(pmd_leaf(*pmd));
3706
3707 ptl = pte_lockptr(args->mm, pmd);
3708 if (!spin_trylock(ptl))
3709 return false;
3710
3711 arch_enter_lazy_mmu_mode();
3712
3713 pte = pte_offset_map(pmd, start & PMD_MASK);
3714restart:
3715 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3716 unsigned long pfn;
3717 struct page *page;
3718
3719 total++;
3720 walk->mm_stats[MM_LEAF_TOTAL]++;
3721
3722 pfn = get_pte_pfn(pte[i], args->vma, addr);
3723 if (pfn == -1)
3724 continue;
3725
3726 if (!pte_young(pte[i])) {
3727 walk->mm_stats[MM_LEAF_OLD]++;
3728 continue;
3729 }
3730
3731 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3732 if (!page)
3733 continue;
3734
3735 if (!ptep_test_and_clear_young(args->vma, addr, pte + i))
3736 VM_WARN_ON_ONCE(true);
3737
3738 young++;
3739 walk->mm_stats[MM_LEAF_YOUNG]++;
3740
3741 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3742 !(PageAnon(page) && PageSwapBacked(page) &&
3743 !PageSwapCache(page)))
3744 set_page_dirty(page);
3745
3746 old_gen = page_update_gen(page, new_gen);
3747 if (old_gen >= 0 && old_gen != new_gen)
3748 update_batch_size(walk, page, old_gen, new_gen);
3749 }
3750
3751 if (i < PTRS_PER_PTE && get_next_vma(PMD_MASK, PAGE_SIZE, args, &start, &end))
3752 goto restart;
3753
3754 pte_unmap(pte);
3755
3756 arch_leave_lazy_mmu_mode();
3757 spin_unlock(ptl);
3758
3759 return suitable_to_scan(total, young);
3760}
3761
3762#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3763static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3764 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3765{
3766 int i;
3767 pmd_t *pmd;
3768 spinlock_t *ptl;
3769 struct lru_gen_mm_walk *walk = args->private;
3770 struct mem_cgroup *memcg = lruvec_memcg(walk->lruvec);
3771 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3772 int old_gen, new_gen = lru_gen_from_seq(walk->max_seq);
3773
3774 VM_WARN_ON_ONCE(pud_leaf(*pud));
3775
3776 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3777 if (*start == -1) {
3778 *start = next;
3779 return;
3780 }
3781
3782 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3783 if (i && i <= MIN_LRU_BATCH) {
3784 __set_bit(i - 1, bitmap);
3785 return;
3786 }
3787
3788 pmd = pmd_offset(pud, *start);
3789
3790 ptl = pmd_lockptr(args->mm, pmd);
3791 if (!spin_trylock(ptl))
3792 goto done;
3793
3794 arch_enter_lazy_mmu_mode();
3795
3796 do {
3797 unsigned long pfn;
3798 struct page *page;
3799 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3800
3801 pfn = get_pmd_pfn(pmd[i], vma, addr);
3802 if (pfn == -1)
3803 goto next;
3804
3805 if (!pmd_trans_huge(pmd[i])) {
3806 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG))
3807 pmdp_test_and_clear_young(vma, addr, pmd + i);
3808 goto next;
3809 }
3810
3811 page = get_pfn_page(pfn, memcg, pgdat, walk->can_swap);
3812 if (!page)
3813 goto next;
3814
3815 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3816 goto next;
3817
3818 walk->mm_stats[MM_LEAF_YOUNG]++;
3819
3820 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3821 !(PageAnon(page) && PageSwapBacked(page) &&
3822 !PageSwapCache(page)))
3823 set_page_dirty(page);
3824
3825 old_gen = page_update_gen(page, new_gen);
3826 if (old_gen >= 0 && old_gen != new_gen)
3827 update_batch_size(walk, page, old_gen, new_gen);
3828next:
3829 i = i > MIN_LRU_BATCH ? 0 : find_next_bit(bitmap, MIN_LRU_BATCH, i) + 1;
3830 } while (i <= MIN_LRU_BATCH);
3831
3832 arch_leave_lazy_mmu_mode();
3833 spin_unlock(ptl);
3834done:
3835 *start = -1;
3836 bitmap_zero(bitmap, MIN_LRU_BATCH);
3837}
3838#else
3839static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3840 struct mm_walk *args, unsigned long *bitmap, unsigned long *start)
3841{
3842}
3843#endif
3844
3845static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3846 struct mm_walk *args)
3847{
3848 int i;
3849 pmd_t *pmd;
3850 unsigned long next;
3851 unsigned long addr;
3852 struct vm_area_struct *vma;
3853 unsigned long pos = -1;
3854 struct lru_gen_mm_walk *walk = args->private;
3855 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3856
3857 VM_WARN_ON_ONCE(pud_leaf(*pud));
3858
3859 /*
3860 * Finish an entire PMD in two passes: the first only reaches to PTE
3861 * tables to avoid taking the PMD lock; the second, if necessary, takes
3862 * the PMD lock to clear the accessed bit in PMD entries.
3863 */
3864 pmd = pmd_offset(pud, start & PUD_MASK);
3865restart:
3866 /* walk_pte_range() may call get_next_vma() */
3867 vma = args->vma;
3868 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3869 pmd_t val = pmd_read_atomic(pmd + i);
3870
3871 /* for pmd_read_atomic() */
3872 barrier();
3873
3874 next = pmd_addr_end(addr, end);
3875
3876 if (!pmd_present(val) || is_huge_zero_pmd(val)) {
3877 walk->mm_stats[MM_LEAF_TOTAL]++;
3878 continue;
3879 }
3880
3881#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3882 if (pmd_trans_huge(val)) {
3883 unsigned long pfn = pmd_pfn(val);
3884 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3885
3886 walk->mm_stats[MM_LEAF_TOTAL]++;
3887
3888 if (!pmd_young(val)) {
3889 walk->mm_stats[MM_LEAF_OLD]++;
3890 continue;
3891 }
3892
3893 /* try to avoid unnecessary memory loads */
3894 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3895 continue;
3896
3897 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3898 continue;
3899 }
3900#endif
3901 walk->mm_stats[MM_NONLEAF_TOTAL]++;
3902
3903#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
3904 if (!pmd_young(val))
3905 continue;
3906
3907 walk_pmd_range_locked(pud, addr, vma, args, bitmap, &pos);
3908#endif
3909 if (!walk->force_scan && !test_bloom_filter(walk->lruvec, walk->max_seq, pmd + i))
3910 continue;
3911
3912 walk->mm_stats[MM_NONLEAF_FOUND]++;
3913
3914 if (!walk_pte_range(&val, addr, next, args))
3915 continue;
3916
3917 walk->mm_stats[MM_NONLEAF_ADDED]++;
3918
3919 /* carry over to the next generation */
3920 update_bloom_filter(walk->lruvec, walk->max_seq + 1, pmd + i);
3921 }
3922
3923 walk_pmd_range_locked(pud, -1, vma, args, bitmap, &pos);
3924
3925 if (i < PTRS_PER_PMD && get_next_vma(PUD_MASK, PMD_SIZE, args, &start, &end))
3926 goto restart;
3927}
3928
3929static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3930 struct mm_walk *args)
3931{
3932 int i;
3933 pud_t *pud;
3934 unsigned long addr;
3935 unsigned long next;
3936 struct lru_gen_mm_walk *walk = args->private;
3937
3938 VM_WARN_ON_ONCE(p4d_leaf(*p4d));
3939
3940 pud = pud_offset(p4d, start & P4D_MASK);
3941restart:
3942 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3943 pud_t val = READ_ONCE(pud[i]);
3944
3945 next = pud_addr_end(addr, end);
3946
3947 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3948 continue;
3949
3950 walk_pmd_range(&val, addr, next, args);
3951
3952 /* a racy check to curtail the waiting time */
3953 if (wq_has_sleeper(&walk->lruvec->mm_state.wait))
3954 return 1;
3955
3956 if (need_resched() || walk->batched >= MAX_LRU_BATCH) {
3957 end = (addr | ~PUD_MASK) + 1;
3958 goto done;
3959 }
3960 }
3961
3962 if (i < PTRS_PER_PUD && get_next_vma(P4D_MASK, PUD_SIZE, args, &start, &end))
3963 goto restart;
3964
3965 end = round_up(end, P4D_SIZE);
3966done:
3967 if (!end || !args->vma)
3968 return 1;
3969
3970 walk->next_addr = max(end, args->vma->vm_start);
3971
3972 return -EAGAIN;
3973}
3974
3975static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3976{
3977 static const struct mm_walk_ops mm_walk_ops = {
3978 .test_walk = should_skip_vma,
3979 .p4d_entry = walk_pud_range,
3980 };
3981
3982 int err;
3983 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3984
3985 walk->next_addr = FIRST_USER_ADDRESS;
3986
3987 do {
3988 err = -EBUSY;
3989
3990 /* page_update_gen() requires stable page_memcg() */
3991 if (!mem_cgroup_trylock_pages(memcg))
3992 break;
3993
3994 /* the caller might be holding the lock for write */
3995 if (mmap_read_trylock(mm)) {
3996 err = walk_page_range(mm, walk->next_addr, ULONG_MAX, &mm_walk_ops, walk);
3997
3998 mmap_read_unlock(mm);
3999 }
4000
4001 mem_cgroup_unlock_pages();
4002
4003 if (walk->batched) {
4004 spin_lock_irq(&lruvec->lru_lock);
4005 reset_batch_size(lruvec, walk);
4006 spin_unlock_irq(&lruvec->lru_lock);
4007 }
4008
4009 cond_resched();
4010 } while (err == -EAGAIN);
4011}
4012
4013static struct lru_gen_mm_walk *set_mm_walk(struct pglist_data *pgdat)
4014{
4015 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4016
4017 if (pgdat && current_is_kswapd()) {
4018 VM_WARN_ON_ONCE(walk);
4019
4020 walk = &pgdat->mm_walk;
4021 } else if (!pgdat && !walk) {
4022 VM_WARN_ON_ONCE(current_is_kswapd());
4023
4024 walk = kzalloc(sizeof(*walk), __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4025 }
4026
4027 current->reclaim_state->mm_walk = walk;
4028
4029 return walk;
4030}
4031
4032static void clear_mm_walk(void)
4033{
4034 struct lru_gen_mm_walk *walk = current->reclaim_state->mm_walk;
4035
4036 VM_WARN_ON_ONCE(walk && memchr_inv(walk->nr_pages, 0, sizeof(walk->nr_pages)));
4037 VM_WARN_ON_ONCE(walk && memchr_inv(walk->mm_stats, 0, sizeof(walk->mm_stats)));
4038
4039 current->reclaim_state->mm_walk = NULL;
4040
4041 if (!current_is_kswapd())
4042 kfree(walk);
4043}
4044
Yu Zhao37397872022-09-18 02:00:03 -06004045static void inc_min_seq(struct lruvec *lruvec, int type)
4046{
4047 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4048
4049 reset_ctrl_pos(lruvec, type, true);
4050 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4051}
4052
4053static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4054{
4055 int gen, type, zone;
4056 bool success = false;
4057 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4058 DEFINE_MIN_SEQ(lruvec);
4059
4060 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4061
4062 /* find the oldest populated generation */
4063 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4064 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4065 gen = lru_gen_from_seq(min_seq[type]);
4066
4067 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4068 if (!list_empty(&lrugen->lists[gen][type][zone]))
4069 goto next;
4070 }
4071
4072 min_seq[type]++;
4073 }
4074next:
4075 ;
4076 }
4077
4078 /* see the comment on lru_gen_struct */
4079 if (can_swap) {
4080 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4081 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4082 }
4083
4084 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4085 if (min_seq[type] == lrugen->min_seq[type])
4086 continue;
4087
4088 reset_ctrl_pos(lruvec, type, true);
4089 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4090 success = true;
4091 }
4092
4093 return success;
4094}
4095
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004096static void inc_max_seq(struct lruvec *lruvec, bool can_swap)
Yu Zhao37397872022-09-18 02:00:03 -06004097{
4098 int prev, next;
4099 int type, zone;
4100 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4101
4102 spin_lock_irq(&lruvec->lru_lock);
4103
4104 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
4105
Yu Zhao37397872022-09-18 02:00:03 -06004106 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
4107 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4108 continue;
4109
4110 VM_WARN_ON_ONCE(type == LRU_GEN_FILE || can_swap);
4111
4112 inc_min_seq(lruvec, type);
4113 }
4114
4115 /*
4116 * Update the active/inactive LRU sizes for compatibility. Both sides of
4117 * the current max_seq need to be covered, since max_seq+1 can overlap
4118 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4119 * overlap, cold/hot inversion happens.
4120 */
4121 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4122 next = lru_gen_from_seq(lrugen->max_seq + 1);
4123
4124 for (type = 0; type < ANON_AND_FILE; type++) {
4125 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4126 enum lru_list lru = type * LRU_INACTIVE_FILE;
4127 long delta = lrugen->nr_pages[prev][type][zone] -
4128 lrugen->nr_pages[next][type][zone];
4129
4130 if (!delta)
4131 continue;
4132
4133 __update_lru_size(lruvec, lru, zone, delta);
4134 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4135 }
4136 }
4137
4138 for (type = 0; type < ANON_AND_FILE; type++)
4139 reset_ctrl_pos(lruvec, type, false);
4140
4141 /* make sure preceding modifications appear */
4142 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004143
Yu Zhao37397872022-09-18 02:00:03 -06004144 spin_unlock_irq(&lruvec->lru_lock);
4145}
4146
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004147static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4148 struct scan_control *sc, bool can_swap)
4149{
4150 bool success;
4151 struct lru_gen_mm_walk *walk;
4152 struct mm_struct *mm = NULL;
4153 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4154
4155 VM_WARN_ON_ONCE(max_seq > READ_ONCE(lrugen->max_seq));
4156
4157 /* see the comment in iterate_mm_list() */
4158 if (max_seq <= READ_ONCE(lruvec->mm_state.seq)) {
4159 success = false;
4160 goto done;
4161 }
4162
4163 /*
4164 * If the hardware doesn't automatically set the accessed bit, fallback
4165 * to lru_gen_look_around(), which only clears the accessed bit in a
4166 * handful of PTEs. Spreading the work out over a period of time usually
4167 * is less efficient, but it avoids bursty page faults.
4168 */
4169 if (!arch_has_hw_pte_young()) {
4170 success = iterate_mm_list_nowalk(lruvec, max_seq);
4171 goto done;
4172 }
4173
4174 walk = set_mm_walk(NULL);
4175 if (!walk) {
4176 success = iterate_mm_list_nowalk(lruvec, max_seq);
4177 goto done;
4178 }
4179
4180 walk->lruvec = lruvec;
4181 walk->max_seq = max_seq;
4182 walk->can_swap = can_swap;
4183 walk->force_scan = false;
4184
4185 do {
4186 success = iterate_mm_list(lruvec, walk, &mm);
4187 if (mm)
4188 walk_mm(lruvec, mm, walk);
4189
4190 cond_resched();
4191 } while (mm);
4192done:
4193 if (!success) {
4194 if (sc->priority <= DEF_PRIORITY - 2)
4195 wait_event_killable(lruvec->mm_state.wait,
4196 max_seq < READ_ONCE(lrugen->max_seq));
4197
4198 return max_seq < READ_ONCE(lrugen->max_seq);
4199 }
4200
4201 VM_WARN_ON_ONCE(max_seq != READ_ONCE(lrugen->max_seq));
4202
4203 inc_max_seq(lruvec, can_swap);
4204 /* either this sees any waiters or they will see updated max_seq */
4205 if (wq_has_sleeper(&lruvec->mm_state.wait))
4206 wake_up_all(&lruvec->mm_state.wait);
4207
4208 return true;
4209}
4210
Yu Zhao37397872022-09-18 02:00:03 -06004211static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
4212 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
4213{
4214 int gen, type, zone;
4215 unsigned long old = 0;
4216 unsigned long young = 0;
4217 unsigned long total = 0;
4218 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4219 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4220
4221 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4222 unsigned long seq;
4223
4224 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4225 unsigned long size = 0;
4226
4227 gen = lru_gen_from_seq(seq);
4228
4229 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4230 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
4231
4232 total += size;
4233 if (seq == max_seq)
4234 young += size;
4235 else if (seq + MIN_NR_GENS == max_seq)
4236 old += size;
4237 }
4238 }
4239
4240 /* try to scrape all its memory if this memcg was deleted */
4241 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
4242
4243 /*
4244 * The aging tries to be lazy to reduce the overhead, while the eviction
4245 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
4246 * ideal number of generations is MIN_NR_GENS+1.
4247 */
4248 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
4249 return true;
4250 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
4251 return false;
4252
4253 /*
4254 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
4255 * of the total number of pages for each generation. A reasonable range
4256 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
4257 * aging cares about the upper bound of hot pages, while the eviction
4258 * cares about the lower bound of cold pages.
4259 */
4260 if (young * MIN_NR_GENS > total)
4261 return true;
4262 if (old * (MIN_NR_GENS + 2) < total)
4263 return true;
4264
4265 return false;
4266}
4267
4268static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4269{
4270 bool need_aging;
4271 unsigned long nr_to_scan;
4272 int swappiness = get_swappiness(lruvec, sc);
4273 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4274 DEFINE_MAX_SEQ(lruvec);
4275 DEFINE_MIN_SEQ(lruvec);
4276
4277 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
4278
4279 mem_cgroup_calculate_protection(NULL, memcg);
4280
4281 if (mem_cgroup_below_min(memcg))
4282 return;
4283
4284 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
4285 if (need_aging)
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004286 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness);
Yu Zhao37397872022-09-18 02:00:03 -06004287}
4288
4289static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4290{
4291 struct mem_cgroup *memcg;
4292
4293 VM_WARN_ON_ONCE(!current_is_kswapd());
4294
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004295 sc->last_reclaimed = sc->nr_reclaimed;
4296
4297 /*
4298 * To reduce the chance of going into the aging path, which can be
4299 * costly, optimistically skip it if the flag below was cleared in the
4300 * eviction path. This improves the overall performance when multiple
4301 * memcgs are available.
4302 */
4303 if (!sc->memcgs_need_aging) {
4304 sc->memcgs_need_aging = true;
4305 return;
4306 }
4307
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004308 set_mm_walk(pgdat);
4309
Yu Zhao37397872022-09-18 02:00:03 -06004310 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4311 do {
4312 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4313
4314 age_lruvec(lruvec, sc);
4315
4316 cond_resched();
4317 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004318
4319 clear_mm_walk();
Yu Zhao37397872022-09-18 02:00:03 -06004320}
4321
Yu Zhao0182f922022-09-18 02:00:04 -06004322/*
4323 * This function exploits spatial locality when shrink_page_list() walks the
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004324 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages. If
4325 * the scan was done cacheline efficiently, it adds the PMD entry pointing to
4326 * the PTE table to the Bloom filter. This forms a feedback loop between the
4327 * eviction and the aging.
Yu Zhao0182f922022-09-18 02:00:04 -06004328 */
4329void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4330{
4331 int i;
4332 pte_t *pte;
4333 unsigned long start;
4334 unsigned long end;
4335 unsigned long addr;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004336 struct lru_gen_mm_walk *walk;
4337 int young = 0;
Yu Zhao0182f922022-09-18 02:00:04 -06004338 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4339 struct page *page = pvmw->page;
4340 struct mem_cgroup *memcg = page_memcg(page);
4341 struct pglist_data *pgdat = page_pgdat(page);
4342 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4343 DEFINE_MAX_SEQ(lruvec);
4344 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4345
4346 lockdep_assert_held(pvmw->ptl);
4347 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
4348
4349 if (spin_is_contended(pvmw->ptl))
4350 return;
4351
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004352 /* avoid taking the LRU lock under the PTL when possible */
4353 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4354
Yu Zhao0182f922022-09-18 02:00:04 -06004355 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4356 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
4357
4358 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4359 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4360 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4361 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4362 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4363 else {
4364 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4365 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4366 }
4367 }
4368
4369 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4370
4371 rcu_read_lock();
4372 arch_enter_lazy_mmu_mode();
4373
4374 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4375 unsigned long pfn;
4376
4377 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
4378 if (pfn == -1)
4379 continue;
4380
4381 if (!pte_young(pte[i]))
4382 continue;
4383
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004384 page = get_pfn_page(pfn, memcg, pgdat, !walk || walk->can_swap);
Yu Zhao0182f922022-09-18 02:00:04 -06004385 if (!page)
4386 continue;
4387
4388 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4389 VM_WARN_ON_ONCE(true);
4390
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004391 young++;
4392
Yu Zhao0182f922022-09-18 02:00:04 -06004393 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4394 !(PageAnon(page) && PageSwapBacked(page) &&
4395 !PageSwapCache(page)))
4396 set_page_dirty(page);
4397
4398 old_gen = page_lru_gen(page);
4399 if (old_gen < 0)
4400 SetPageReferenced(page);
4401 else if (old_gen != new_gen)
4402 __set_bit(i, bitmap);
4403 }
4404
4405 arch_leave_lazy_mmu_mode();
4406 rcu_read_unlock();
4407
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004408 /* feedback from rmap walkers to page table walkers */
4409 if (suitable_to_scan(i, young))
4410 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4411
4412 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhao0182f922022-09-18 02:00:04 -06004413 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4414 page = pte_page(pte[i]);
4415 activate_page(page);
4416 }
4417 return;
4418 }
4419
4420 /* page_update_gen() requires stable page_memcg() */
4421 if (!mem_cgroup_trylock_pages(memcg))
4422 return;
4423
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004424 if (!walk) {
4425 spin_lock_irq(&lruvec->lru_lock);
4426 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4427 }
Yu Zhao0182f922022-09-18 02:00:04 -06004428
4429 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4430 page = compound_head(pte_page(pte[i]));
4431 if (page_memcg_rcu(page) != memcg)
4432 continue;
4433
4434 old_gen = page_update_gen(page, new_gen);
4435 if (old_gen < 0 || old_gen == new_gen)
4436 continue;
4437
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004438 if (walk)
4439 update_batch_size(walk, page, old_gen, new_gen);
4440 else
4441 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhao0182f922022-09-18 02:00:04 -06004442 }
4443
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004444 if (!walk)
4445 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhao0182f922022-09-18 02:00:04 -06004446
4447 mem_cgroup_unlock_pages();
4448}
4449
Yu Zhao37397872022-09-18 02:00:03 -06004450/******************************************************************************
4451 * the eviction
4452 ******************************************************************************/
4453
4454static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4455{
4456 bool success;
4457 int gen = page_lru_gen(page);
4458 int type = page_is_file_lru(page);
4459 int zone = page_zonenum(page);
4460 int delta = thp_nr_pages(page);
4461 int refs = page_lru_refs(page);
4462 int tier = lru_tier_from_refs(refs);
4463 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4464
4465 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
4466
4467 /* unevictable */
4468 if (!page_evictable(page)) {
4469 success = lru_gen_del_page(lruvec, page, true);
4470 VM_WARN_ON_ONCE_PAGE(!success, page);
4471 SetPageUnevictable(page);
4472 add_page_to_lru_list(page, lruvec);
4473 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4474 return true;
4475 }
4476
4477 /* dirty lazyfree */
4478 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4479 success = lru_gen_del_page(lruvec, page, true);
4480 VM_WARN_ON_ONCE_PAGE(!success, page);
4481 SetPageSwapBacked(page);
4482 add_page_to_lru_list_tail(page, lruvec);
4483 return true;
4484 }
4485
Yu Zhao0182f922022-09-18 02:00:04 -06004486 /* promoted */
4487 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4488 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4489 return true;
4490 }
4491
Yu Zhao37397872022-09-18 02:00:03 -06004492 /* protected */
4493 if (tier > tier_idx) {
4494 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4495
4496 gen = page_inc_gen(lruvec, page, false);
4497 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4498
4499 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4500 lrugen->protected[hist][type][tier - 1] + delta);
4501 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4502 return true;
4503 }
4504
4505 /* waiting for writeback */
4506 if (PageLocked(page) || PageWriteback(page) ||
4507 (type == LRU_GEN_FILE && PageDirty(page))) {
4508 gen = page_inc_gen(lruvec, page, true);
4509 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4510 return true;
4511 }
4512
4513 return false;
4514}
4515
4516static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4517{
4518 bool success;
4519
4520 /* unmapping inhibited */
4521 if (!sc->may_unmap && page_mapped(page))
4522 return false;
4523
4524 /* swapping inhibited */
4525 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4526 (PageDirty(page) ||
4527 (PageAnon(page) && !PageSwapCache(page))))
4528 return false;
4529
4530 /* raced with release_pages() */
4531 if (!get_page_unless_zero(page))
4532 return false;
4533
4534 /* raced with another isolation */
4535 if (!TestClearPageLRU(page)) {
4536 put_page(page);
4537 return false;
4538 }
4539
4540 /* see the comment on MAX_NR_TIERS */
4541 if (!PageReferenced(page))
4542 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
4543
4544 /* for shrink_page_list() */
4545 ClearPageReclaim(page);
4546 ClearPageReferenced(page);
4547
4548 success = lru_gen_del_page(lruvec, page, true);
4549 VM_WARN_ON_ONCE_PAGE(!success, page);
4550
4551 return true;
4552}
4553
4554static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4555 int type, int tier, struct list_head *list)
4556{
4557 int gen, zone;
4558 enum vm_event_item item;
4559 int sorted = 0;
4560 int scanned = 0;
4561 int isolated = 0;
4562 int remaining = MAX_LRU_BATCH;
4563 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4564 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4565
4566 VM_WARN_ON_ONCE(!list_empty(list));
4567
4568 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4569 return 0;
4570
4571 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4572
4573 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4574 LIST_HEAD(moved);
4575 int skipped = 0;
4576 struct list_head *head = &lrugen->lists[gen][type][zone];
4577
4578 while (!list_empty(head)) {
4579 struct page *page = lru_to_page(head);
4580 int delta = thp_nr_pages(page);
4581
4582 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
4583 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
4584 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
4585 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
4586
4587 scanned += delta;
4588
4589 if (sort_page(lruvec, page, tier))
4590 sorted += delta;
4591 else if (isolate_page(lruvec, page, sc)) {
4592 list_add(&page->lru, list);
4593 isolated += delta;
4594 } else {
4595 list_move(&page->lru, &moved);
4596 skipped += delta;
4597 }
4598
4599 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4600 break;
4601 }
4602
4603 if (skipped) {
4604 list_splice(&moved, head);
4605 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4606 }
4607
4608 if (!remaining || isolated >= MIN_LRU_BATCH)
4609 break;
4610 }
4611
4612 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4613 if (!cgroup_reclaim(sc)) {
4614 __count_vm_events(item, isolated);
4615 __count_vm_events(PGREFILL, sorted);
4616 }
4617 __count_memcg_events(memcg, item, isolated);
4618 __count_memcg_events(memcg, PGREFILL, sorted);
4619 __count_vm_events(PGSCAN_ANON + type, isolated);
4620
4621 /*
4622 * There might not be eligible pages due to reclaim_idx, may_unmap and
4623 * may_writepage. Check the remaining to prevent livelock if it's not
4624 * making progress.
4625 */
4626 return isolated || !remaining ? scanned : 0;
4627}
4628
4629static int get_tier_idx(struct lruvec *lruvec, int type)
4630{
4631 int tier;
4632 struct ctrl_pos sp, pv;
4633
4634 /*
4635 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4636 * This value is chosen because any other tier would have at least twice
4637 * as many refaults as the first tier.
4638 */
4639 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4640 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4641 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4642 if (!positive_ctrl_err(&sp, &pv))
4643 break;
4644 }
4645
4646 return tier - 1;
4647}
4648
4649static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4650{
4651 int type, tier;
4652 struct ctrl_pos sp, pv;
4653 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4654
4655 /*
4656 * Compare the first tier of anon with that of file to determine which
4657 * type to scan. Also need to compare other tiers of the selected type
4658 * with the first tier of the other type to determine the last tier (of
4659 * the selected type) to evict.
4660 */
4661 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4662 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4663 type = positive_ctrl_err(&sp, &pv);
4664
4665 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4666 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4667 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4668 if (!positive_ctrl_err(&sp, &pv))
4669 break;
4670 }
4671
4672 *tier_idx = tier - 1;
4673
4674 return type;
4675}
4676
4677static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4678 int *type_scanned, struct list_head *list)
4679{
4680 int i;
4681 int type;
4682 int scanned;
4683 int tier = -1;
4684 DEFINE_MIN_SEQ(lruvec);
4685
4686 /*
4687 * Try to make the obvious choice first. When anon and file are both
4688 * available from the same generation, interpret swappiness 1 as file
4689 * first and 200 as anon first.
4690 */
4691 if (!swappiness)
4692 type = LRU_GEN_FILE;
4693 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4694 type = LRU_GEN_ANON;
4695 else if (swappiness == 1)
4696 type = LRU_GEN_FILE;
4697 else if (swappiness == 200)
4698 type = LRU_GEN_ANON;
4699 else
4700 type = get_type_to_scan(lruvec, swappiness, &tier);
4701
4702 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4703 if (tier < 0)
4704 tier = get_tier_idx(lruvec, type);
4705
4706 scanned = scan_pages(lruvec, sc, type, tier, list);
4707 if (scanned)
4708 break;
4709
4710 type = !type;
4711 tier = -1;
4712 }
4713
4714 *type_scanned = type;
4715
4716 return scanned;
4717}
4718
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004719static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4720 bool *need_swapping)
Yu Zhao37397872022-09-18 02:00:03 -06004721{
4722 int type;
4723 int scanned;
4724 int reclaimed;
4725 LIST_HEAD(list);
4726 struct page *page;
4727 enum vm_event_item item;
4728 struct reclaim_stat stat;
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004729 struct lru_gen_mm_walk *walk;
Yu Zhao37397872022-09-18 02:00:03 -06004730 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4731 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4732
4733 spin_lock_irq(&lruvec->lru_lock);
4734
4735 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4736
4737 scanned += try_to_inc_min_seq(lruvec, swappiness);
4738
4739 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
4740 scanned = 0;
4741
4742 spin_unlock_irq(&lruvec->lru_lock);
4743
4744 if (list_empty(&list))
4745 return scanned;
4746
4747 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4748
4749 list_for_each_entry(page, &list, lru) {
4750 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
4751 if (PageWorkingset(page))
4752 SetPageReferenced(page);
4753
4754 /* don't add rejected pages to the oldest generation */
4755 if (PageReclaim(page) &&
4756 (PageDirty(page) || PageWriteback(page)))
4757 ClearPageActive(page);
4758 else
4759 SetPageActive(page);
4760 }
4761
4762 spin_lock_irq(&lruvec->lru_lock);
4763
4764 move_pages_to_lru(lruvec, &list);
4765
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004766 walk = current->reclaim_state->mm_walk;
4767 if (walk && walk->batched)
4768 reset_batch_size(lruvec, walk);
4769
Yu Zhao37397872022-09-18 02:00:03 -06004770 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4771 if (!cgroup_reclaim(sc))
4772 __count_vm_events(item, reclaimed);
4773 __count_memcg_events(memcg, item, reclaimed);
4774 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4775
4776 spin_unlock_irq(&lruvec->lru_lock);
4777
4778 mem_cgroup_uncharge_list(&list);
4779 free_unref_page_list(&list);
4780
4781 sc->nr_reclaimed += reclaimed;
4782
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004783 if (need_swapping && type == LRU_GEN_ANON)
4784 *need_swapping = true;
4785
Yu Zhao37397872022-09-18 02:00:03 -06004786 return scanned;
4787}
4788
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004789/*
4790 * For future optimizations:
4791 * 1. Defer try_to_inc_max_seq() to workqueues to reduce latency for memcg
4792 * reclaim.
4793 */
Yu Zhao37397872022-09-18 02:00:03 -06004794static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004795 bool can_swap, bool *need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004796{
Yu Zhao37397872022-09-18 02:00:03 -06004797 unsigned long nr_to_scan;
4798 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4799 DEFINE_MAX_SEQ(lruvec);
4800 DEFINE_MIN_SEQ(lruvec);
4801
4802 if (mem_cgroup_below_min(memcg) ||
4803 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4804 return 0;
4805
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004806 *need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
4807 if (!*need_aging)
Yu Zhao37397872022-09-18 02:00:03 -06004808 return nr_to_scan;
4809
4810 /* skip the aging path at the default priority */
4811 if (sc->priority == DEF_PRIORITY)
4812 goto done;
4813
4814 /* leave the work to lru_gen_age_node() */
4815 if (current_is_kswapd())
4816 return 0;
4817
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004818 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap))
4819 return nr_to_scan;
Yu Zhao37397872022-09-18 02:00:03 -06004820done:
4821 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
4822}
4823
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004824static bool should_abort_scan(struct lruvec *lruvec, unsigned long seq,
4825 struct scan_control *sc, bool need_swapping)
4826{
4827 int i;
4828 DEFINE_MAX_SEQ(lruvec);
4829
4830 if (!current_is_kswapd()) {
4831 /* age each memcg at most once to ensure fairness */
4832 if (max_seq - seq > 1)
4833 return true;
4834
4835 /* over-swapping can increase allocation latency */
4836 if (sc->nr_reclaimed >= sc->nr_to_reclaim && need_swapping)
4837 return true;
4838
4839 /* give this thread a chance to exit and free its memory */
4840 if (fatal_signal_pending(current)) {
4841 sc->nr_reclaimed += MIN_LRU_BATCH;
4842 return true;
4843 }
4844
4845 if (cgroup_reclaim(sc))
4846 return false;
4847 } else if (sc->nr_reclaimed - sc->last_reclaimed < sc->nr_to_reclaim)
4848 return false;
4849
4850 /* keep scanning at low priorities to ensure fairness */
4851 if (sc->priority > DEF_PRIORITY - 2)
4852 return false;
4853
4854 /*
4855 * A minimum amount of work was done under global memory pressure. For
4856 * kswapd, it may be overshooting. For direct reclaim, the allocation
4857 * may succeed if all suitable zones are somewhat safe. In either case,
4858 * it's better to stop now, and restart later if necessary.
4859 */
4860 for (i = 0; i <= sc->reclaim_idx; i++) {
4861 unsigned long wmark;
4862 struct zone *zone = lruvec_pgdat(lruvec)->node_zones + i;
4863
4864 if (!managed_zone(zone))
4865 continue;
4866
4867 wmark = current_is_kswapd() ? high_wmark_pages(zone) : low_wmark_pages(zone);
4868 if (wmark > zone_page_state(zone, NR_FREE_PAGES))
4869 return false;
4870 }
4871
4872 sc->nr_reclaimed += MIN_LRU_BATCH;
4873
4874 return true;
4875}
4876
Yu Zhao37397872022-09-18 02:00:03 -06004877static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4878{
4879 struct blk_plug plug;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004880 bool need_aging = false;
4881 bool need_swapping = false;
Yu Zhao37397872022-09-18 02:00:03 -06004882 unsigned long scanned = 0;
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004883 unsigned long reclaimed = sc->nr_reclaimed;
4884 DEFINE_MAX_SEQ(lruvec);
Yu Zhao37397872022-09-18 02:00:03 -06004885
4886 lru_add_drain();
4887
4888 blk_start_plug(&plug);
4889
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004890 set_mm_walk(lruvec_pgdat(lruvec));
4891
Yu Zhao37397872022-09-18 02:00:03 -06004892 while (true) {
4893 int delta;
4894 int swappiness;
4895 unsigned long nr_to_scan;
4896
4897 if (sc->may_swap)
4898 swappiness = get_swappiness(lruvec, sc);
4899 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4900 swappiness = 1;
4901 else
4902 swappiness = 0;
4903
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004904 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness, &need_aging);
Yu Zhao37397872022-09-18 02:00:03 -06004905 if (!nr_to_scan)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004906 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004907
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004908 delta = evict_pages(lruvec, sc, swappiness, &need_swapping);
Yu Zhao37397872022-09-18 02:00:03 -06004909 if (!delta)
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004910 goto done;
Yu Zhao37397872022-09-18 02:00:03 -06004911
4912 scanned += delta;
4913 if (scanned >= nr_to_scan)
4914 break;
4915
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004916 if (should_abort_scan(lruvec, max_seq, sc, need_swapping))
4917 break;
4918
Yu Zhao37397872022-09-18 02:00:03 -06004919 cond_resched();
4920 }
4921
Yu Zhaoa8a158a2022-09-18 02:00:06 -06004922 /* see the comment in lru_gen_age_node() */
4923 if (sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH && !need_aging)
4924 sc->memcgs_need_aging = false;
4925done:
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004926 clear_mm_walk();
4927
Yu Zhao37397872022-09-18 02:00:03 -06004928 blk_finish_plug(&plug);
4929}
4930
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004931/******************************************************************************
4932 * initialization
4933 ******************************************************************************/
4934
4935void lru_gen_init_lruvec(struct lruvec *lruvec)
4936{
4937 int gen, type, zone;
4938 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4939
4940 lrugen->max_seq = MIN_NR_GENS + 1;
4941
4942 for_each_gen_type_zone(gen, type, zone)
4943 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004944
4945 lruvec->mm_state.seq = MIN_NR_GENS;
4946 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004947}
4948
4949#ifdef CONFIG_MEMCG
4950void lru_gen_init_memcg(struct mem_cgroup *memcg)
4951{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004952 INIT_LIST_HEAD(&memcg->mm_list.fifo);
4953 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004954}
4955
4956void lru_gen_exit_memcg(struct mem_cgroup *memcg)
4957{
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004958 int i;
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004959 int nid;
4960
4961 for_each_node(nid) {
4962 struct lruvec *lruvec = get_lruvec(memcg, nid);
4963
4964 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
4965 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao7f53b0e2022-09-18 02:00:05 -06004966
4967 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
4968 bitmap_free(lruvec->mm_state.filters[i]);
4969 lruvec->mm_state.filters[i] = NULL;
4970 }
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004971 }
4972}
4973#endif
4974
4975static int __init init_lru_gen(void)
4976{
4977 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
4978 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
4979
4980 return 0;
4981};
4982late_initcall(init_lru_gen);
4983
Yu Zhao37397872022-09-18 02:00:03 -06004984#else /* !CONFIG_LRU_GEN */
4985
4986static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4987{
4988}
4989
4990static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4991{
4992}
4993
Yu Zhaod5b2fa12022-09-18 02:00:02 -06004994#endif /* CONFIG_LRU_GEN */
4995
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004996static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004997{
4998 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07004999 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005000 unsigned long nr_to_scan;
5001 enum lru_list lru;
5002 unsigned long nr_reclaimed = 0;
5003 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5004 struct blk_plug plug;
Mel Gorman1a501902014-06-04 16:10:49 -07005005 bool scan_adjusted;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005006
Yu Zhao37397872022-09-18 02:00:03 -06005007 if (lru_gen_enabled()) {
5008 lru_gen_shrink_lruvec(lruvec, sc);
5009 return;
5010 }
5011
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005012 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005013
Mel Gormane82e0562013-07-03 15:01:44 -07005014 /* Record the original scan target for proportional adjustments later */
5015 memcpy(targets, nr, sizeof(nr));
5016
Mel Gorman1a501902014-06-04 16:10:49 -07005017 /*
5018 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5019 * event that can occur when there is little memory pressure e.g.
5020 * multiple streaming readers/writers. Hence, we do not abort scanning
5021 * when the requested number of pages are reclaimed when scanning at
5022 * DEF_PRIORITY on the assumption that the fact we are direct
5023 * reclaiming implies that kswapd is not keeping up and it is best to
5024 * do a batch of work at once. For memcg reclaim one check is made to
5025 * abort proportional reclaim if either the file or anon lru has already
5026 * dropped to zero at the first pass.
5027 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005028 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
Mel Gorman1a501902014-06-04 16:10:49 -07005029 sc->priority == DEF_PRIORITY);
5030
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005031 blk_start_plug(&plug);
5032 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5033 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005034 unsigned long nr_anon, nr_file, percentage;
5035 unsigned long nr_scanned;
5036
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005037 for_each_evictable_lru(lru) {
5038 if (nr[lru]) {
5039 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5040 nr[lru] -= nr_to_scan;
5041
5042 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005043 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005044 }
5045 }
Mel Gormane82e0562013-07-03 15:01:44 -07005046
Michal Hockobd041732016-12-02 17:26:48 -08005047 cond_resched();
5048
Mel Gormane82e0562013-07-03 15:01:44 -07005049 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
5050 continue;
5051
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005052 /*
Mel Gormane82e0562013-07-03 15:01:44 -07005053 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07005054 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07005055 * proportionally what was requested by get_scan_count(). We
5056 * stop reclaiming one LRU and reduce the amount scanning
5057 * proportional to the original scan target.
5058 */
5059 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5060 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5061
Mel Gorman1a501902014-06-04 16:10:49 -07005062 /*
5063 * It's just vindictive to attack the larger once the smaller
5064 * has gone to zero. And given the way we stop scanning the
5065 * smaller below, this makes sure that we only make one nudge
5066 * towards proportionality once we've got nr_to_reclaim.
5067 */
5068 if (!nr_file || !nr_anon)
5069 break;
5070
Mel Gormane82e0562013-07-03 15:01:44 -07005071 if (nr_file > nr_anon) {
5072 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5073 targets[LRU_ACTIVE_ANON] + 1;
5074 lru = LRU_BASE;
5075 percentage = nr_anon * 100 / scan_target;
5076 } else {
5077 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5078 targets[LRU_ACTIVE_FILE] + 1;
5079 lru = LRU_FILE;
5080 percentage = nr_file * 100 / scan_target;
5081 }
5082
5083 /* Stop scanning the smaller of the LRU */
5084 nr[lru] = 0;
5085 nr[lru + LRU_ACTIVE] = 0;
5086
5087 /*
5088 * Recalculate the other LRU scan count based on its original
5089 * scan target and the percentage scanning already complete
5090 */
5091 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5092 nr_scanned = targets[lru] - nr[lru];
5093 nr[lru] = targets[lru] * (100 - percentage) / 100;
5094 nr[lru] -= min(nr[lru], nr_scanned);
5095
5096 lru += LRU_ACTIVE;
5097 nr_scanned = targets[lru] - nr[lru];
5098 nr[lru] = targets[lru] * (100 - percentage) / 100;
5099 nr[lru] -= min(nr[lru], nr_scanned);
5100
5101 scan_adjusted = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005102 }
5103 blk_finish_plug(&plug);
5104 sc->nr_reclaimed += nr_reclaimed;
5105
5106 /*
5107 * Even if we did not try to evict anon pages at all, we want to
5108 * rebalance the anon lru active/inactive ratio.
5109 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005110 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5111 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005112 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5113 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005114}
5115
Mel Gorman23b9da52012-05-29 15:06:20 -07005116/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005117static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005118{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005119 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005120 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005121 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005122 return true;
5123
5124 return false;
5125}
5126
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005127/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005128 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5129 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5130 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005131 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005132 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005133 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005134static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005135 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005136 struct scan_control *sc)
5137{
5138 unsigned long pages_for_compaction;
5139 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005140 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005141
5142 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005143 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005144 return false;
5145
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005146 /*
5147 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5148 * number of pages that were scanned. This will return to the caller
5149 * with the risk reclaim/compaction and the resulting allocation attempt
5150 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5151 * allocations through requiring that the full LRU list has been scanned
5152 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5153 * scan, but that approximation was wrong, and there were corner cases
5154 * where always a non-zero amount of pages were scanned.
5155 */
5156 if (!nr_reclaimed)
5157 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005158
Mel Gorman3e7d3442011-01-13 15:45:56 -08005159 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005160 for (z = 0; z <= sc->reclaim_idx; z++) {
5161 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005162 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005163 continue;
5164
5165 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005166 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005167 case COMPACT_CONTINUE:
5168 return false;
5169 default:
5170 /* check next zone */
5171 ;
5172 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005173 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005174
5175 /*
5176 * If we have not reclaimed enough pages for compaction and the
5177 * inactive lists are large enough, continue reclaiming
5178 */
5179 pages_for_compaction = compact_gap(sc->order);
5180 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005181 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005182 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5183
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005184 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005185}
5186
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005187static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005188{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005189 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005190 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005191
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005192 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005193 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005194 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005195 unsigned long reclaimed;
5196 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005197 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08005198
Xunlei Pange3336ca2020-09-04 16:35:27 -07005199 /*
5200 * This loop can become CPU-bound when target memcgs
5201 * aren't eligible for reclaim - either because they
5202 * don't have any reclaimable pages, or because their
5203 * memory is explicitly protected. Avoid soft lockups.
5204 */
5205 cond_resched();
5206
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005207 trace_android_vh_shrink_node_memcgs(memcg, &skip);
5208 if (skip)
5209 continue;
5210
Chris Down45c7f7e2020-08-06 23:22:05 -07005211 mem_cgroup_calculate_protection(target_memcg, memcg);
5212
5213 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005214 /*
5215 * Hard protection.
5216 * If there is no reclaimable memory, OOM.
5217 */
5218 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005219 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005220 /*
5221 * Soft protection.
5222 * Respect the protection only as long as
5223 * there is an unprotected supply
5224 * of reclaimable memory from other cgroups.
5225 */
5226 if (!sc->memcg_low_reclaim) {
5227 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005228 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005229 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005230 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005231 }
5232
Johannes Weinerd2af3392019-11-30 17:55:43 -08005233 reclaimed = sc->nr_reclaimed;
5234 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005235
5236 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005237
Johannes Weinerd2af3392019-11-30 17:55:43 -08005238 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5239 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005240
Johannes Weinerd2af3392019-11-30 17:55:43 -08005241 /* Record the group's reclaim efficiency */
5242 vmpressure(sc->gfp_mask, memcg, false,
5243 sc->nr_scanned - scanned,
5244 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005245
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005246 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5247}
5248
Liu Song6c9e09072020-01-30 22:14:08 -08005249static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005250{
5251 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005252 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005253 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005254 bool reclaimable = false;
5255
Johannes Weiner1b051172019-11-30 17:55:52 -08005256 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5257
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005258again:
5259 memset(&sc->nr, 0, sizeof(sc->nr));
5260
5261 nr_reclaimed = sc->nr_reclaimed;
5262 nr_scanned = sc->nr_scanned;
5263
Yu Zhao6d313442022-09-18 02:00:00 -06005264 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005265
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005266 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005267
Johannes Weinerd2af3392019-11-30 17:55:43 -08005268 if (reclaim_state) {
5269 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5270 reclaim_state->reclaimed_slab = 0;
5271 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005272
Johannes Weinerd2af3392019-11-30 17:55:43 -08005273 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005274 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005275 sc->nr_scanned - nr_scanned,
5276 sc->nr_reclaimed - nr_reclaimed);
5277
5278 if (sc->nr_reclaimed - nr_reclaimed)
5279 reclaimable = true;
5280
5281 if (current_is_kswapd()) {
5282 /*
5283 * If reclaim is isolating dirty pages under writeback,
5284 * it implies that the long-lived page allocation rate
5285 * is exceeding the page laundering rate. Either the
5286 * global limits are not being effective at throttling
5287 * processes due to the page distribution throughout
5288 * zones or there is heavy usage of a slow backing
5289 * device. The only option is to throttle from reclaim
5290 * context which is not ideal as there is no guarantee
5291 * the dirtying process is throttled in the same way
5292 * balance_dirty_pages() manages.
5293 *
5294 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5295 * count the number of pages under pages flagged for
5296 * immediate reclaim and stall if any are encountered
5297 * in the nr_immediate check below.
5298 */
5299 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5300 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005301
Johannes Weinerd2af3392019-11-30 17:55:43 -08005302 /* Allow kswapd to start writing pages during reclaim.*/
5303 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5304 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005305
5306 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005307 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005308 * reclaim and under writeback (nr_immediate), it
5309 * implies that pages are cycling through the LRU
5310 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005311 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005312 if (sc->nr.immediate)
5313 congestion_wait(BLK_RW_ASYNC, HZ/10);
5314 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005315
Johannes Weinerd2af3392019-11-30 17:55:43 -08005316 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005317 * Tag a node/memcg as congested if all the dirty pages
5318 * scanned were backed by a congested BDI and
5319 * wait_iff_congested will stall.
5320 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005321 * Legacy memcg will stall in page writeback so avoid forcibly
5322 * stalling in wait_iff_congested().
5323 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005324 if ((current_is_kswapd() ||
5325 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005326 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005327 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005328
5329 /*
5330 * Stall direct reclaim for IO completions if underlying BDIs
5331 * and node is congested. Allow kswapd to continue until it
5332 * starts encountering unqueued dirty pages or cycling through
5333 * the LRU too quickly.
5334 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005335 if (!current_is_kswapd() && current_may_throttle() &&
5336 !sc->hibernation_mode &&
5337 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005338 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5339
5340 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5341 sc))
5342 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005343
Johannes Weinerc73322d2017-05-03 14:51:51 -07005344 /*
5345 * Kswapd gives up on balancing particular nodes after too
5346 * many failures to reclaim anything from them and goes to
5347 * sleep. On reclaim progress, reset the failure counter. A
5348 * successful direct reclaim run will revive a dormant kswapd.
5349 */
5350 if (reclaimable)
5351 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005352}
5353
Vlastimil Babka53853e22014-10-09 15:27:02 -07005354/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005355 * Returns true if compaction should go ahead for a costly-order request, or
5356 * the allocation would already succeed without compaction. Return false if we
5357 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07005358 */
Mel Gorman4f588332016-07-28 15:46:38 -07005359static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005360{
Mel Gorman31483b62016-07-28 15:45:46 -07005361 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005362 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005363
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005364 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
5365 if (suitable == COMPACT_SUCCESS)
5366 /* Allocation should succeed already. Don't reclaim. */
5367 return true;
5368 if (suitable == COMPACT_SKIPPED)
5369 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005370 return false;
5371
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005372 /*
5373 * Compaction is already possible, but it takes time to run and there
5374 * are potentially other callers using the pages just freed. So proceed
5375 * with reclaim to make a buffer of free pages available to give
5376 * compaction a reasonable chance of completing and allocating the page.
5377 * Note that we won't actually reclaim the whole buffer in one attempt
5378 * as the target watermark in should_continue_reclaim() is lower. But if
5379 * we are already above the high+gap watermark, don't reclaim at all.
5380 */
5381 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
5382
5383 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005384}
5385
Linus Torvalds1da177e2005-04-16 15:20:36 -07005386/*
5387 * This is the direct reclaim path, for page-allocating processes. We only
5388 * try to reclaim pages from zones which will satisfy the caller's allocation
5389 * request.
5390 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07005391 * If a zone is deemed to be full of pinned pages then just give it a light
5392 * scan then give up on it.
5393 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07005394static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005395{
Mel Gormandd1a2392008-04-28 02:12:17 -07005396 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07005397 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07005398 unsigned long nr_soft_reclaimed;
5399 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07005400 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07005401 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005402
Mel Gormancc715d92012-03-21 16:34:00 -07005403 /*
5404 * If the number of buffer_heads in the machine exceeds the maximum
5405 * allowed level, force direct reclaim to scan the highmem zone as
5406 * highmem pages could be pinning lowmem pages storing buffer_heads
5407 */
Weijie Yang619d0d762014-04-07 15:36:59 -07005408 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07005409 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07005410 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07005411 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07005412 }
Mel Gormancc715d92012-03-21 16:34:00 -07005413
Mel Gormand4debc62010-08-09 17:19:29 -07005414 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07005415 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07005416 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005417 * Take care memory controller reclaiming has small influence
5418 * to global LRU.
5419 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005420 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04005421 if (!cpuset_zone_allowed(zone,
5422 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005423 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005424
Johannes Weiner0b064962014-08-06 16:06:12 -07005425 /*
5426 * If we already have plenty of memory free for
5427 * compaction in this zone, don't free any more.
5428 * Even though compaction is invoked for any
5429 * non-zero order, only frequent costly order
5430 * reclamation is disruptive enough to become a
5431 * noticeable problem, like transparent huge
5432 * page allocations.
5433 */
5434 if (IS_ENABLED(CONFIG_COMPACTION) &&
5435 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07005436 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07005437 sc->compaction_ready = true;
5438 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07005439 }
Johannes Weiner0b064962014-08-06 16:06:12 -07005440
Andrew Morton0608f432013-09-24 15:27:41 -07005441 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07005442 * Shrink each node in the zonelist once. If the
5443 * zonelist is ordered by zone (not the default) then a
5444 * node may be shrunk multiple times but in that case
5445 * the user prefers lower zones being preserved.
5446 */
5447 if (zone->zone_pgdat == last_pgdat)
5448 continue;
5449
5450 /*
Andrew Morton0608f432013-09-24 15:27:41 -07005451 * This steals pages from memory cgroups over softlimit
5452 * and returns the number of reclaimed pages and
5453 * scanned pages. This works for global memory pressure
5454 * and balancing, not for a memcg's limit.
5455 */
5456 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07005457 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07005458 sc->order, sc->gfp_mask,
5459 &nr_soft_scanned);
5460 sc->nr_reclaimed += nr_soft_reclaimed;
5461 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07005462 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005463 }
Nick Piggin408d8542006-09-25 23:31:27 -07005464
Mel Gorman79dafcd2016-07-28 15:45:53 -07005465 /* See comment about same check for global reclaim above */
5466 if (zone->zone_pgdat == last_pgdat)
5467 continue;
5468 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07005469 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005470 }
Mel Gormane0c23272011-10-31 17:09:33 -07005471
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005472 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07005473 * Restore to original mask to avoid the impact on the caller if we
5474 * promoted it to __GFP_HIGHMEM.
5475 */
5476 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005477}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005478
Johannes Weinerb9107182019-11-30 17:55:59 -08005479static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005480{
Johannes Weinerb9107182019-11-30 17:55:59 -08005481 struct lruvec *target_lruvec;
5482 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005483
Yu Zhao37397872022-09-18 02:00:03 -06005484 if (lru_gen_enabled())
5485 return;
5486
Johannes Weinerb9107182019-11-30 17:55:59 -08005487 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07005488 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
5489 target_lruvec->refaults[0] = refaults;
5490 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
5491 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005492}
5493
Linus Torvalds1da177e2005-04-16 15:20:36 -07005494/*
5495 * This is the main entry point to direct page reclaim.
5496 *
5497 * If a full scan of the inactive list fails to free enough memory then we
5498 * are "out of memory" and something needs to be killed.
5499 *
5500 * If the caller is !__GFP_FS then the probability of a failure is reasonably
5501 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02005502 * caller can't do much about. We kick the writeback threads and take explicit
5503 * naps in the hope that some of these pages can be written. But if the
5504 * allocating task holds filesystem locks which prevent writeout this might not
5505 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07005506 *
5507 * returns: 0, if no pages reclaimed
5508 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07005509 */
Mel Gormandac1d272008-04-28 02:12:12 -07005510static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005511 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005512{
Johannes Weiner241994ed2015-02-11 15:26:06 -08005513 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005514 pg_data_t *last_pgdat;
5515 struct zoneref *z;
5516 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005517retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07005518 delayacct_freepages_start();
5519
Johannes Weinerb5ead352019-11-30 17:55:40 -08005520 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07005521 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005522
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005523 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005524 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
5525 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08005526 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07005527 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07005528
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005529 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07005530 break;
5531
5532 if (sc->compaction_ready)
5533 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005534
5535 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08005536 * If we're getting trouble reclaiming, start doing
5537 * writepage even in laptop mode.
5538 */
5539 if (sc->priority < DEF_PRIORITY - 2)
5540 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07005541 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005542
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005543 last_pgdat = NULL;
5544 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
5545 sc->nodemask) {
5546 if (zone->zone_pgdat == last_pgdat)
5547 continue;
5548 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08005549
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005550 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08005551
5552 if (cgroup_reclaim(sc)) {
5553 struct lruvec *lruvec;
5554
5555 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
5556 zone->zone_pgdat);
5557 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
5558 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005559 }
5560
Keika Kobayashi873b4772008-07-25 01:48:52 -07005561 delayacct_freepages_end();
5562
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005563 if (sc->nr_reclaimed)
5564 return sc->nr_reclaimed;
5565
Mel Gorman0cee34f2012-01-12 17:19:49 -08005566 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07005567 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08005568 return 1;
5569
Johannes Weinerb91ac372019-11-30 17:56:02 -08005570 /*
5571 * We make inactive:active ratio decisions based on the node's
5572 * composition of memory, but a restrictive reclaim_idx or a
5573 * memory.low cgroup setting can exempt large amounts of
5574 * memory from reclaim. Neither of which are very common, so
5575 * instead of doing costly eligibility calculations of the
5576 * entire cgroup subtree up front, we assume the estimates are
5577 * good, and retry with forcible deactivation if that fails.
5578 */
5579 if (sc->skipped_deactivate) {
5580 sc->priority = initial_priority;
5581 sc->force_deactivate = 1;
5582 sc->skipped_deactivate = 0;
5583 goto retry;
5584 }
5585
Johannes Weiner241994ed2015-02-11 15:26:06 -08005586 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07005587 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08005588 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08005589 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07005590 sc->memcg_low_reclaim = 1;
5591 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005592 goto retry;
5593 }
5594
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005595 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005596}
5597
Johannes Weinerc73322d2017-05-03 14:51:51 -07005598static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07005599{
5600 struct zone *zone;
5601 unsigned long pfmemalloc_reserve = 0;
5602 unsigned long free_pages = 0;
5603 int i;
5604 bool wmark_ok;
5605
Johannes Weinerc73322d2017-05-03 14:51:51 -07005606 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
5607 return true;
5608
Mel Gorman55150612012-07-31 16:44:35 -07005609 for (i = 0; i <= ZONE_NORMAL; i++) {
5610 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07005611 if (!managed_zone(zone))
5612 continue;
5613
5614 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07005615 continue;
5616
Mel Gorman55150612012-07-31 16:44:35 -07005617 pfmemalloc_reserve += min_wmark_pages(zone);
5618 free_pages += zone_page_state(zone, NR_FREE_PAGES);
5619 }
5620
Mel Gorman675becc2014-06-04 16:07:35 -07005621 /* If there are no reserves (unexpected config) then do not throttle */
5622 if (!pfmemalloc_reserve)
5623 return true;
5624
Mel Gorman55150612012-07-31 16:44:35 -07005625 wmark_ok = free_pages > pfmemalloc_reserve / 2;
5626
5627 /* kswapd must be awake if processes are being throttled */
5628 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005629 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
5630 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005631
Mel Gorman55150612012-07-31 16:44:35 -07005632 wake_up_interruptible(&pgdat->kswapd_wait);
5633 }
5634
5635 return wmark_ok;
5636}
5637
5638/*
5639 * Throttle direct reclaimers if backing storage is backed by the network
5640 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
5641 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08005642 * when the low watermark is reached.
5643 *
5644 * Returns true if a fatal signal was delivered during throttling. If this
5645 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07005646 */
Mel Gorman50694c22012-11-26 16:29:48 -08005647static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07005648 nodemask_t *nodemask)
5649{
Mel Gorman675becc2014-06-04 16:07:35 -07005650 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07005651 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07005652 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07005653
5654 /*
5655 * Kernel threads should not be throttled as they may be indirectly
5656 * responsible for cleaning pages necessary for reclaim to make forward
5657 * progress. kjournald for example may enter direct reclaim while
5658 * committing a transaction where throttling it could forcing other
5659 * processes to block on log_wait_commit().
5660 */
5661 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08005662 goto out;
5663
5664 /*
5665 * If a fatal signal is pending, this process should not throttle.
5666 * It should return quickly so it can exit and free its memory
5667 */
5668 if (fatal_signal_pending(current))
5669 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005670
Mel Gorman675becc2014-06-04 16:07:35 -07005671 /*
5672 * Check if the pfmemalloc reserves are ok by finding the first node
5673 * with a usable ZONE_NORMAL or lower zone. The expectation is that
5674 * GFP_KERNEL will be required for allocating network buffers when
5675 * swapping over the network so ZONE_HIGHMEM is unusable.
5676 *
5677 * Throttling is based on the first usable node and throttled processes
5678 * wait on a queue until kswapd makes progress and wakes them. There
5679 * is an affinity then between processes waking up and where reclaim
5680 * progress has been made assuming the process wakes on the same node.
5681 * More importantly, processes running on remote nodes will not compete
5682 * for remote pfmemalloc reserves and processes on different nodes
5683 * should make reasonable progress.
5684 */
5685 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08005686 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07005687 if (zone_idx(zone) > ZONE_NORMAL)
5688 continue;
5689
5690 /* Throttle based on the first usable node */
5691 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07005692 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07005693 goto out;
5694 break;
5695 }
5696
5697 /* If no zone was usable by the allocation flags then do not throttle */
5698 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08005699 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005700
Mel Gorman68243e72012-07-31 16:44:39 -07005701 /* Account for the throttling */
5702 count_vm_event(PGSCAN_DIRECT_THROTTLE);
5703
Mel Gorman55150612012-07-31 16:44:35 -07005704 /*
5705 * If the caller cannot enter the filesystem, it's possible that it
5706 * is due to the caller holding an FS lock or performing a journal
5707 * transaction in the case of a filesystem like ext[3|4]. In this case,
5708 * it is not safe to block on pfmemalloc_wait as kswapd could be
5709 * blocked waiting on the same lock. Instead, throttle for up to a
5710 * second before continuing.
5711 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07005712 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07005713 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07005714 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07005715 else
5716 /* Throttle until kswapd wakes the process */
5717 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
5718 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08005719
Mel Gorman50694c22012-11-26 16:29:48 -08005720 if (fatal_signal_pending(current))
5721 return true;
5722
5723out:
5724 return false;
Mel Gorman55150612012-07-31 16:44:35 -07005725}
5726
Mel Gormandac1d272008-04-28 02:12:12 -07005727unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07005728 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08005729{
Mel Gorman33906bc2010-08-09 17:19:16 -07005730 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005731 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08005732 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005733 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07005734 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07005735 .order = order,
5736 .nodemask = nodemask,
5737 .priority = DEF_PRIORITY,
5738 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005739 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07005740 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08005741 };
5742
Mel Gorman55150612012-07-31 16:44:35 -07005743 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07005744 * scan_control uses s8 fields for order, priority, and reclaim_idx.
5745 * Confirm they are large enough for max values.
5746 */
5747 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
5748 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
5749 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
5750
5751 /*
Mel Gorman50694c22012-11-26 16:29:48 -08005752 * Do not enter reclaim if fatal signal was delivered while throttled.
5753 * 1 is returned so that the page allocator does not OOM kill at this
5754 * point.
Mel Gorman55150612012-07-31 16:44:35 -07005755 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005756 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07005757 return 1;
5758
Andrew Morton1732d2b012019-07-16 16:26:15 -07005759 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005760 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07005761
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005762 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07005763
5764 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005765 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07005766
5767 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005768}
5769
Andrew Mortonc255a452012-07-31 16:43:02 -07005770#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08005771
Michal Hockod2e5fb92019-08-30 16:04:50 -07005772/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005773unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005774 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07005775 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07005776 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07005777{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005778 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07005779 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07005780 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07005781 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005782 .may_writepage = !laptop_mode,
5783 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07005784 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07005785 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07005786 };
Ying Han0ae5e892011-05-26 16:25:25 -07005787
Michal Hockod2e5fb92019-08-30 16:04:50 -07005788 WARN_ON_ONCE(!current->reclaim_state);
5789
Balbir Singh4e416952009-09-23 15:56:39 -07005790 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
5791 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005792
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005793 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07005794 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005795
Balbir Singh4e416952009-09-23 15:56:39 -07005796 /*
5797 * NOTE: Although we can get the priority field, using it
5798 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07005799 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07005800 * will pick up pages from other mem cgroup's as well. We hack
5801 * the priority and make it zero.
5802 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005803 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005804
5805 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
5806
Ying Han0ae5e892011-05-26 16:25:25 -07005807 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07005808
Balbir Singh4e416952009-09-23 15:56:39 -07005809 return sc.nr_reclaimed;
5810}
5811
Johannes Weiner72835c82012-01-12 17:18:32 -08005812unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005813 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08005814 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005815 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08005816{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005817 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07005818 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08005819 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005820 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07005821 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07005822 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07005823 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07005824 .target_mem_cgroup = memcg,
5825 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08005826 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005827 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005828 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07005829 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08005830 /*
5831 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
5832 * equal pressure on all the nodes. This is based on the assumption that
5833 * the reclaim does not bail out early.
5834 */
5835 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08005836
Andrew Morton1732d2b012019-07-16 16:26:15 -07005837 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005838 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07005839 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07005840
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005841 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07005842
Vlastimil Babka499118e2017-05-08 15:59:50 -07005843 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005844 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005845 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005846
5847 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005848}
Liujie Xie1ed025b2021-06-25 22:21:35 +08005849EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08005850#endif
5851
Yu Zhao37397872022-09-18 02:00:03 -06005852static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005853{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005854 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08005855 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005856
Yu Zhao37397872022-09-18 02:00:03 -06005857 if (lru_gen_enabled()) {
5858 lru_gen_age_node(pgdat, sc);
5859 return;
5860 }
5861
Dave Hansen2f368a92021-09-02 14:59:23 -07005862 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005863 return;
5864
Johannes Weinerb91ac372019-11-30 17:56:02 -08005865 lruvec = mem_cgroup_lruvec(NULL, pgdat);
5866 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
5867 return;
5868
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005869 memcg = mem_cgroup_iter(NULL, NULL, NULL);
5870 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08005871 lruvec = mem_cgroup_lruvec(memcg, pgdat);
5872 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5873 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005874 memcg = mem_cgroup_iter(NULL, memcg, NULL);
5875 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08005876}
5877
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005878static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08005879{
5880 int i;
5881 struct zone *zone;
5882
5883 /*
5884 * Check for watermark boosts top-down as the higher zones
5885 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005886 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08005887 * start prematurely when there is no boosting and a lower
5888 * zone is balanced.
5889 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005890 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08005891 zone = pgdat->node_zones + i;
5892 if (!managed_zone(zone))
5893 continue;
5894
5895 if (zone->watermark_boost)
5896 return true;
5897 }
5898
5899 return false;
5900}
5901
Mel Gormane716f2e2017-05-03 14:53:45 -07005902/*
5903 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005904 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07005905 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005906static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08005907{
Mel Gormane716f2e2017-05-03 14:53:45 -07005908 int i;
5909 unsigned long mark = -1;
5910 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08005911
Mel Gorman1c308442018-12-28 00:35:52 -08005912 /*
5913 * Check watermarks bottom-up as lower zones are more likely to
5914 * meet watermarks.
5915 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005916 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07005917 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07005918
Mel Gormane716f2e2017-05-03 14:53:45 -07005919 if (!managed_zone(zone))
5920 continue;
5921
5922 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005923 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07005924 return true;
5925 }
5926
5927 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005928 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07005929 * need balancing by definition. This can happen if a zone-restricted
5930 * allocation tries to wake a remote kswapd.
5931 */
5932 if (mark == -1)
5933 return true;
5934
5935 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08005936}
5937
Mel Gorman631b6e02017-05-03 14:53:41 -07005938/* Clear pgdat state for congested, dirty or under writeback. */
5939static void clear_pgdat_congested(pg_data_t *pgdat)
5940{
Johannes Weiner1b051172019-11-30 17:55:52 -08005941 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
5942
5943 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07005944 clear_bit(PGDAT_DIRTY, &pgdat->flags);
5945 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
5946}
5947
Mel Gorman1741c872011-01-13 15:46:21 -08005948/*
Mel Gorman55150612012-07-31 16:44:35 -07005949 * Prepare kswapd for sleeping. This verifies that there are no processes
5950 * waiting in throttle_direct_reclaim() and that watermarks have been met.
5951 *
5952 * Returns true if kswapd is ready to sleep
5953 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005954static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
5955 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08005956{
Mel Gorman55150612012-07-31 16:44:35 -07005957 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005958 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07005959 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005960 * race between when kswapd checks the watermarks and a process gets
5961 * throttled. There is also a potential race if processes get
5962 * throttled, kswapd wakes, a large process exits thereby balancing the
5963 * zones, which causes kswapd to exit balance_pgdat() before reaching
5964 * the wake up checks. If kswapd is going to sleep, no process should
5965 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
5966 * the wake up is premature, processes will wake kswapd and get
5967 * throttled again. The difference from wake ups in balance_pgdat() is
5968 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07005969 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08005970 if (waitqueue_active(&pgdat->pfmemalloc_wait))
5971 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08005972
Johannes Weinerc73322d2017-05-03 14:51:51 -07005973 /* Hopeless node, leave it to direct reclaim */
5974 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
5975 return true;
5976
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005977 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07005978 clear_pgdat_congested(pgdat);
5979 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07005980 }
5981
Shantanu Goel333b0a42017-05-03 14:53:38 -07005982 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08005983}
5984
Linus Torvalds1da177e2005-04-16 15:20:36 -07005985/*
Mel Gorman1d82de62016-07-28 15:45:43 -07005986 * kswapd shrinks a node of pages that are at or below the highest usable
5987 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07005988 *
5989 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07005990 * reclaim or if the lack of progress was due to pages under writeback.
5991 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07005992 */
Mel Gorman1d82de62016-07-28 15:45:43 -07005993static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07005994 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07005995{
Mel Gorman1d82de62016-07-28 15:45:43 -07005996 struct zone *zone;
5997 int z;
Mel Gorman75485362013-07-03 15:01:42 -07005998
Mel Gorman1d82de62016-07-28 15:45:43 -07005999 /* Reclaim a number of pages proportional to the number of zones */
6000 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006001 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006002 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006003 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006004 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006005
Mel Gorman1d82de62016-07-28 15:45:43 -07006006 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006007 }
6008
Mel Gorman1d82de62016-07-28 15:45:43 -07006009 /*
6010 * Historically care was taken to put equal pressure on all zones but
6011 * now pressure is applied based on node LRU order.
6012 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006013 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006014
6015 /*
6016 * Fragmentation may mean that the system cannot be rebalanced for
6017 * high-order allocations. If twice the allocation size has been
6018 * reclaimed then recheck watermarks only at order-0 to prevent
6019 * excessive reclaim. Assume that a process requested a high-order
6020 * can direct reclaim/compact.
6021 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006022 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006023 sc->order = 0;
6024
Mel Gormanb8e83b92013-07-03 15:01:45 -07006025 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006026}
6027
Mel Gormanc49c2c42021-06-28 19:42:21 -07006028/* Page allocator PCP high watermark is lowered if reclaim is active. */
6029static inline void
6030update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6031{
6032 int i;
6033 struct zone *zone;
6034
6035 for (i = 0; i <= highest_zoneidx; i++) {
6036 zone = pgdat->node_zones + i;
6037
6038 if (!managed_zone(zone))
6039 continue;
6040
6041 if (active)
6042 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6043 else
6044 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6045 }
6046}
6047
6048static inline void
6049set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6050{
6051 update_reclaim_active(pgdat, highest_zoneidx, true);
6052}
6053
6054static inline void
6055clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6056{
6057 update_reclaim_active(pgdat, highest_zoneidx, false);
6058}
6059
Mel Gorman75485362013-07-03 15:01:42 -07006060/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006061 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6062 * that are eligible for use by the caller until at least one zone is
6063 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006064 *
Mel Gorman1d82de62016-07-28 15:45:43 -07006065 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006066 *
6067 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07006068 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08006069 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07006070 * or lower is eligible for reclaim until at least one usable zone is
6071 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006072 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006073static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006074{
Linus Torvalds1da177e2005-04-16 15:20:36 -07006075 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07006076 unsigned long nr_soft_reclaimed;
6077 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07006078 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08006079 unsigned long nr_boost_reclaim;
6080 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6081 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07006082 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08006083 struct scan_control sc = {
6084 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07006085 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006086 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08006087 };
Omar Sandoval93781322018-06-07 17:07:02 -07006088
Andrew Morton1732d2b012019-07-16 16:26:15 -07006089 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07006090 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006091 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006092
Christoph Lameterf8891e52006-06-30 01:55:45 -07006093 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006094
Mel Gorman1c308442018-12-28 00:35:52 -08006095 /*
6096 * Account for the reclaim boost. Note that the zone boost is left in
6097 * place so that parallel allocations that are near the watermark will
6098 * stall or direct reclaim until kswapd is finished.
6099 */
6100 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006101 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006102 zone = pgdat->node_zones + i;
6103 if (!managed_zone(zone))
6104 continue;
6105
6106 nr_boost_reclaim += zone->watermark_boost;
6107 zone_boosts[i] = zone->watermark_boost;
6108 }
6109 boosted = nr_boost_reclaim;
6110
6111restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006112 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006113 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006114 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006115 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006116 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006117 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006118 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006119
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006120 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006121
Mel Gorman86c79f62016-07-28 15:45:59 -07006122 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006123 * If the number of buffer_heads exceeds the maximum allowed
6124 * then consider reclaiming from all zones. This has a dual
6125 * purpose -- on 64-bit systems it is expected that
6126 * buffer_heads are stripped during active rotation. On 32-bit
6127 * systems, highmem pages can pin lowmem memory and shrinking
6128 * buffers can relieve lowmem pressure. Reclaim may still not
6129 * go ahead if all eligible zones for the original allocation
6130 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006131 */
6132 if (buffer_heads_over_limit) {
6133 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6134 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006135 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006136 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006137
Mel Gorman970a39a2016-07-28 15:46:35 -07006138 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006139 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006140 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006141 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006142
Mel Gorman86c79f62016-07-28 15:45:59 -07006143 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006144 * If the pgdat is imbalanced then ignore boosting and preserve
6145 * the watermarks for a later time and restart. Note that the
6146 * zone watermarks will be still reset at the end of balancing
6147 * on the grounds that the normal reclaim should be enough to
6148 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006149 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006150 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006151 if (!balanced && nr_boost_reclaim) {
6152 nr_boost_reclaim = 0;
6153 goto restart;
6154 }
6155
6156 /*
6157 * If boosting is not active then only reclaim if there are no
6158 * eligible zones. Note that sc.reclaim_idx is not used as
6159 * buffer_heads_over_limit may have adjusted it.
6160 */
6161 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006162 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006163
Mel Gorman1c308442018-12-28 00:35:52 -08006164 /* Limit the priority of boosting to avoid reclaim writeback */
6165 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6166 raise_priority = false;
6167
6168 /*
6169 * Do not writeback or swap pages for boosted reclaim. The
6170 * intent is to relieve pressure not issue sub-optimal IO
6171 * from reclaim context. If no pages are reclaimed, the
6172 * reclaim will be aborted.
6173 */
6174 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6175 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006176
Linus Torvalds1da177e2005-04-16 15:20:36 -07006177 /*
Yu Zhao37397872022-09-18 02:00:03 -06006178 * Do some background aging, to give pages a chance to be
6179 * referenced before reclaiming. All pages are rotated
6180 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07006181 */
Yu Zhao37397872022-09-18 02:00:03 -06006182 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006183
6184 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006185 * If we're getting trouble reclaiming, start doing writepage
6186 * even in laptop mode.
6187 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006188 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006189 sc.may_writepage = 1;
6190
Mel Gorman1d82de62016-07-28 15:45:43 -07006191 /* Call soft limit reclaim before calling shrink_node. */
6192 sc.nr_scanned = 0;
6193 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006194 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006195 sc.gfp_mask, &nr_soft_scanned);
6196 sc.nr_reclaimed += nr_soft_reclaimed;
6197
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006198 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006199 * There should be no need to raise the scanning priority if
6200 * enough pages are already being scanned that that high
6201 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006202 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006203 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006204 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006205
6206 /*
6207 * If the low watermark is met there is no need for processes
6208 * to be throttled on pfmemalloc_wait as they should not be
6209 * able to safely make forward progress. Wake them
6210 */
6211 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006212 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006213 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006214
Mel Gormanb8e83b92013-07-03 15:01:45 -07006215 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006216 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006217 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006218 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006219 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006220 break;
6221
6222 /*
6223 * Raise priority if scanning rate is too low or there was no
6224 * progress in reclaiming pages
6225 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006226 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006227 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6228
6229 /*
6230 * If reclaim made no progress for a boost, stop reclaim as
6231 * IO cannot be queued and it could be an infinite loop in
6232 * extreme circumstances.
6233 */
6234 if (nr_boost_reclaim && !nr_reclaimed)
6235 break;
6236
Johannes Weinerc73322d2017-05-03 14:51:51 -07006237 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006238 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006239 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006240
Johannes Weinerc73322d2017-05-03 14:51:51 -07006241 if (!sc.nr_reclaimed)
6242 pgdat->kswapd_failures++;
6243
Mel Gormanb8e83b92013-07-03 15:01:45 -07006244out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006245 clear_reclaim_active(pgdat, highest_zoneidx);
6246
Mel Gorman1c308442018-12-28 00:35:52 -08006247 /* If reclaim was boosted, account for the reclaim done in this pass */
6248 if (boosted) {
6249 unsigned long flags;
6250
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006251 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006252 if (!zone_boosts[i])
6253 continue;
6254
6255 /* Increments are under the zone lock */
6256 zone = pgdat->node_zones + i;
6257 spin_lock_irqsave(&zone->lock, flags);
6258 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6259 spin_unlock_irqrestore(&zone->lock, flags);
6260 }
6261
6262 /*
6263 * As there is now likely space, wakeup kcompact to defragment
6264 * pageblocks.
6265 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006266 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006267 }
6268
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006269 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006270 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006271 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006272 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006273
Mel Gorman0abdee22011-01-13 15:46:22 -08006274 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006275 * Return the order kswapd stopped reclaiming at as
6276 * prepare_kswapd_sleep() takes it into account. If another caller
6277 * entered the allocator slow path while kswapd was awake, order will
6278 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006279 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006280 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006281}
6282
Mel Gormane716f2e2017-05-03 14:53:45 -07006283/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006284 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6285 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6286 * not a valid index then either kswapd runs for first time or kswapd couldn't
6287 * sleep after previous reclaim attempt (node is still unbalanced). In that
6288 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006289 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006290static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6291 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006292{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006293 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006294
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006295 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006296}
6297
Mel Gorman38087d92016-07-28 15:45:49 -07006298static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006299 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006300{
6301 long remaining = 0;
6302 DEFINE_WAIT(wait);
6303
6304 if (freezing(current) || kthread_should_stop())
6305 return;
6306
6307 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6308
Shantanu Goel333b0a42017-05-03 14:53:38 -07006309 /*
6310 * Try to sleep for a short interval. Note that kcompactd will only be
6311 * woken if it is possible to sleep for a short interval. This is
6312 * deliberate on the assumption that if reclaim cannot keep an
6313 * eligible zone balanced that it's also unlikely that compaction will
6314 * succeed.
6315 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006316 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006317 /*
6318 * Compaction records what page blocks it recently failed to
6319 * isolate pages from and skips them in the future scanning.
6320 * When kswapd is going to sleep, it is reasonable to assume
6321 * that pages and compaction may succeed so reset the cache.
6322 */
6323 reset_isolation_suitable(pgdat);
6324
6325 /*
6326 * We have freed the memory, now we should compact it to make
6327 * allocation of the requested order possible.
6328 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006329 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006330
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006331 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006332
6333 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006334 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006335 * order. The values will either be from a wakeup request or
6336 * the previous request that slept prematurely.
6337 */
6338 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006339 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6340 kswapd_highest_zoneidx(pgdat,
6341 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006342
6343 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6344 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006345 }
6346
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006347 finish_wait(&pgdat->kswapd_wait, &wait);
6348 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6349 }
6350
6351 /*
6352 * After a short sleep, check if it was a premature sleep. If not, then
6353 * go fully to sleep until explicitly woken up.
6354 */
Mel Gormand9f21d42016-07-28 15:46:41 -07006355 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006356 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006357 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6358
6359 /*
6360 * vmstat counters are not perfectly accurate and the estimated
6361 * value for counters such as NR_FREE_PAGES can deviate from the
6362 * true value by nr_online_cpus * threshold. To avoid the zone
6363 * watermarks being breached while under pressure, we reduce the
6364 * per-cpu vmstat threshold while kswapd is awake and restore
6365 * them before going back to sleep.
6366 */
6367 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07006368
6369 if (!kthread_should_stop())
6370 schedule();
6371
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006372 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
6373 } else {
6374 if (remaining)
6375 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
6376 else
6377 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
6378 }
6379 finish_wait(&pgdat->kswapd_wait, &wait);
6380}
6381
Linus Torvalds1da177e2005-04-16 15:20:36 -07006382/*
6383 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006384 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006385 *
6386 * This basically trickles out pages so that we have _some_
6387 * free memory available even if there is no other activity
6388 * that frees anything up. This is needed for things like routing
6389 * etc, where we otherwise might have all activity going on in
6390 * asynchronous contexts that cannot page things out.
6391 *
6392 * If there are applications that are active memory-allocators
6393 * (most normal use), this basically shouldn't matter.
6394 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306395int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006396{
Mel Gormane716f2e2017-05-03 14:53:45 -07006397 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006398 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07006399 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006400 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10306401 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006402
Rusty Russell174596a2009-01-01 10:12:29 +10306403 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07006404 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006405
6406 /*
6407 * Tell the memory management that we're a "memory allocator",
6408 * and that if we need more memory we should get access to it
6409 * regardless (see "__alloc_pages()"). "kswapd" should
6410 * never get caught in the normal page freeing logic.
6411 *
6412 * (Kswapd normally doesn't need memory anyway, but sometimes
6413 * you need a small amount of memory in order to be able to
6414 * page out something else, and this flag essentially protects
6415 * us from recursively trying to free more memory as we're
6416 * trying to free the first piece of memory in the first place).
6417 */
Christoph Lameter930d9152006-01-08 01:00:47 -08006418 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07006419 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07006420
Qian Cai5644e1fb2020-04-01 21:10:12 -07006421 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006422 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006423 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08006424 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07006425
Qian Cai5644e1fb2020-04-01 21:10:12 -07006426 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006427 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6428 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07006429
Mel Gorman38087d92016-07-28 15:45:49 -07006430kswapd_try_sleep:
6431 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006432 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07006433
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006434 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08006435 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006436 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6437 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006438 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006439 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006440
David Rientjes8fe23e02009-12-14 17:58:33 -08006441 ret = try_to_freeze();
6442 if (kthread_should_stop())
6443 break;
6444
6445 /*
6446 * We can speed up thawing tasks if we don't call balance_pgdat
6447 * after returning from the refrigerator
6448 */
Mel Gorman38087d92016-07-28 15:45:49 -07006449 if (ret)
6450 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07006451
Mel Gorman38087d92016-07-28 15:45:49 -07006452 /*
6453 * Reclaim begins at the requested order but if a high-order
6454 * reclaim fails then kswapd falls back to reclaiming for
6455 * order-0. If that happens, kswapd will consider sleeping
6456 * for the order it finished reclaiming at (reclaim_order)
6457 * but kcompactd is woken to compact for the original
6458 * request (alloc_order).
6459 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006460 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07006461 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006462 reclaim_order = balance_pgdat(pgdat, alloc_order,
6463 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07006464 if (reclaim_order < alloc_order)
6465 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006466 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08006467
Johannes Weiner71abdc12014-06-06 14:35:35 -07006468 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07006469
Linus Torvalds1da177e2005-04-16 15:20:36 -07006470 return 0;
6471}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306472EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006473
6474/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07006475 * A zone is low on free memory or too fragmented for high-order memory. If
6476 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
6477 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
6478 * has failed or is not needed, still wake up kcompactd if only compaction is
6479 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006480 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07006481void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006482 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006483{
6484 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07006485 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006486
Mel Gorman6aa303d2016-09-01 16:14:55 -07006487 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006488 return;
6489
David Rientjes5ecd9d42018-04-05 16:25:16 -07006490 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006491 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07006492
Qian Cai5644e1fb2020-04-01 21:10:12 -07006493 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006494 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006495
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006496 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
6497 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006498
6499 if (READ_ONCE(pgdat->kswapd_order) < order)
6500 WRITE_ONCE(pgdat->kswapd_order, order);
6501
Con Kolivas8d0986e2005-09-13 01:25:07 -07006502 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006503 return;
Mel Gormane1a55632016-07-28 15:46:26 -07006504
David Rientjes5ecd9d42018-04-05 16:25:16 -07006505 /* Hopeless node, leave it to direct reclaim if possible */
6506 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006507 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
6508 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07006509 /*
6510 * There may be plenty of free memory available, but it's too
6511 * fragmented for high-order allocations. Wake up kcompactd
6512 * and rely on compaction_suitable() to determine if it's
6513 * needed. If it fails, it will defer subsequent attempts to
6514 * ratelimit its work.
6515 */
6516 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006517 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07006518 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07006519 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07006520
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006521 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07006522 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07006523 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006524}
6525
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006526#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07006527/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006528 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006529 * freed pages.
6530 *
6531 * Rather than trying to age LRUs the aim is to preserve the overall
6532 * LRU order by reclaiming preferentially
6533 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07006534 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006535unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006536{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006537 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006538 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07006539 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07006540 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006541 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07006542 .may_writepage = 1,
6543 .may_unmap = 1,
6544 .may_swap = 1,
6545 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07006546 };
Ying Hana09ed5e2011-05-24 17:12:26 -07006547 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006548 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006549 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006550
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01006551 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07006552 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07006553 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08006554
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006555 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006556
Andrew Morton1732d2b012019-07-16 16:26:15 -07006557 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006558 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006559 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006560
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006561 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006562}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006563#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07006564
Yasunori Goto3218ae12006-06-27 02:53:33 -07006565/*
6566 * This kswapd start function will be called by init and node-hot-add.
6567 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
6568 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07006569void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006570{
6571 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306572 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006573
6574 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07006575 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006576
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306577 trace_android_vh_kswapd_per_node(nid, &skip, true);
6578 if (skip)
6579 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006580 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
6581 if (IS_ERR(pgdat->kswapd)) {
6582 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02006583 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07006584 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07006585 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006586 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07006587}
6588
David Rientjes8fe23e02009-12-14 17:58:33 -08006589/*
Jiang Liud8adde12012-07-11 14:01:52 -07006590 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07006591 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08006592 */
6593void kswapd_stop(int nid)
6594{
6595 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306596 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08006597
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306598 trace_android_vh_kswapd_per_node(nid, &skip, false);
6599 if (skip)
6600 return;
Jiang Liud8adde12012-07-11 14:01:52 -07006601 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08006602 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07006603 NODE_DATA(nid)->kswapd = NULL;
6604 }
David Rientjes8fe23e02009-12-14 17:58:33 -08006605}
6606
Linus Torvalds1da177e2005-04-16 15:20:36 -07006607static int __init kswapd_init(void)
6608{
Wei Yang6b700b52020-04-01 21:10:09 -07006609 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08006610
Linus Torvalds1da177e2005-04-16 15:20:36 -07006611 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08006612 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006613 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006614 return 0;
6615}
6616
6617module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006618
6619#ifdef CONFIG_NUMA
6620/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006621 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08006622 *
Mel Gormana5f5f912016-07-28 15:46:32 -07006623 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08006624 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006625 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006626int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006627
Dave Hansen51998362021-02-24 12:09:15 -08006628/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006629 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08006630 * of a node considered for each zone_reclaim. 4 scans 1/16th of
6631 * a zone.
6632 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006633#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08006634
Christoph Lameter9eeff232006-01-18 17:42:31 -08006635/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006636 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07006637 * occur.
6638 */
6639int sysctl_min_unmapped_ratio = 1;
6640
6641/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07006642 * If the number of slab pages in a zone grows beyond this percentage then
6643 * slab reclaim needs to occur.
6644 */
6645int sysctl_min_slab_ratio = 5;
6646
Mel Gorman11fb9982016-07-28 15:46:20 -07006647static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006648{
Mel Gorman11fb9982016-07-28 15:46:20 -07006649 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
6650 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
6651 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006652
6653 /*
6654 * It's possible for there to be more file mapped pages than
6655 * accounted for by the pages on the file LRU lists because
6656 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
6657 */
6658 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
6659}
6660
6661/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07006662static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006663{
Alexandru Moised031a152015-11-05 18:48:08 -08006664 unsigned long nr_pagecache_reclaimable;
6665 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07006666
6667 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006668 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07006669 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07006670 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07006671 * a better estimate
6672 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006673 if (node_reclaim_mode & RECLAIM_UNMAP)
6674 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006675 else
Mel Gormana5f5f912016-07-28 15:46:32 -07006676 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006677
6678 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07006679 if (!(node_reclaim_mode & RECLAIM_WRITE))
6680 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006681
6682 /* Watch for any possible underflows due to delta */
6683 if (unlikely(delta > nr_pagecache_reclaimable))
6684 delta = nr_pagecache_reclaimable;
6685
6686 return nr_pagecache_reclaimable - delta;
6687}
6688
Christoph Lameter0ff38492006-09-25 23:31:52 -07006689/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006690 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006691 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006692static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006693{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08006694 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08006695 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006696 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006697 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08006698 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08006699 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006700 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07006701 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07006702 .priority = NODE_RECLAIM_PRIORITY,
6703 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
6704 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07006705 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006706 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08006707 };
Johannes Weiner57f29762021-08-19 19:04:27 -07006708 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006709
Yafang Shao132bb8c2019-05-13 17:17:53 -07006710 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
6711 sc.gfp_mask);
6712
Christoph Lameter9eeff232006-01-18 17:42:31 -08006713 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07006714 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07006715 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08006716 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006717 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08006718 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006719 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08006720 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07006721 noreclaim_flag = memalloc_noreclaim_save();
6722 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07006723 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08006724
Mel Gormana5f5f912016-07-28 15:46:32 -07006725 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07006726 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07006727 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07006728 * priorities until we have enough memory freed.
6729 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07006730 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07006731 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006732 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07006733 }
Christoph Lameterc84db232006-02-01 03:05:29 -08006734
Andrew Morton1732d2b012019-07-16 16:26:15 -07006735 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006736 current->flags &= ~PF_SWAPWRITE;
6737 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006738 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07006739 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07006740
6741 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
6742
Rik van Riela79311c2009-01-06 14:40:01 -08006743 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006744}
Andrew Morton179e9632006-03-22 00:08:18 -08006745
Mel Gormana5f5f912016-07-28 15:46:32 -07006746int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08006747{
David Rientjesd773ed62007-10-16 23:26:01 -07006748 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006749
6750 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006751 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07006752 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07006753 *
Christoph Lameter96146342006-07-03 00:24:13 -07006754 * A small portion of unmapped file backed pages is needed for
6755 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07006756 * thrown out if the node is overallocated. So we do not reclaim
6757 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07006758 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08006759 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006760 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07006761 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
6762 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07006763 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08006764
6765 /*
David Rientjesd773ed62007-10-16 23:26:01 -07006766 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08006767 */
Mel Gormand0164ad2015-11-06 16:28:21 -08006768 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07006769 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08006770
6771 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006772 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08006773 * have associated processors. This will favor the local processor
6774 * over remote processors and spread off node memory allocations
6775 * as wide as possible.
6776 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006777 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
6778 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07006779
Mel Gormana5f5f912016-07-28 15:46:32 -07006780 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
6781 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07006782
Mel Gormana5f5f912016-07-28 15:46:32 -07006783 ret = __node_reclaim(pgdat, gfp_mask, order);
6784 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07006785
Mel Gorman24cf725182009-06-16 15:33:23 -07006786 if (!ret)
6787 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
6788
David Rientjesd773ed62007-10-16 23:26:01 -07006789 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006790}
Christoph Lameter9eeff232006-01-18 17:42:31 -08006791#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07006792
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006793/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006794 * check_move_unevictable_pages - check pages for evictability and move to
6795 * appropriate zone lru list
6796 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006797 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006798 * Checks pages for evictability, if an evictable page is in the unevictable
6799 * lru list, moves it to the appropriate evictable lru list. This function
6800 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006801 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006802void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006803{
Alex Shi6168d0d2020-12-15 12:34:29 -08006804 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08006805 int pgscanned = 0;
6806 int pgrescued = 0;
6807 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006808
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006809 for (i = 0; i < pvec->nr; i++) {
6810 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006811 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07006812
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006813 if (PageTransTail(page))
6814 continue;
6815
6816 nr_pages = thp_nr_pages(page);
6817 pgscanned += nr_pages;
6818
Alex Shid25b5bd2020-12-15 12:34:16 -08006819 /* block memcg migration during page moving between lru */
6820 if (!TestClearPageLRU(page))
6821 continue;
6822
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08006823 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08006824 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08006825 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08006826 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08006827 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006828 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08006829 }
Alex Shid25b5bd2020-12-15 12:34:16 -08006830 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006831 }
Hugh Dickins24513262012-01-20 14:34:21 -08006832
Alex Shi6168d0d2020-12-15 12:34:29 -08006833 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08006834 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
6835 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08006836 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08006837 } else if (pgscanned) {
6838 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08006839 }
Hugh Dickins850465792012-01-20 14:34:19 -08006840}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006841EXPORT_SYMBOL_GPL(check_move_unevictable_pages);