blob: 8abf8845dc54ff5d3dd1583208d935436fda3c92 [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>
Linus Torvalds1da177e2005-04-16 15:20:36 -070053
54#include <asm/tlbflush.h>
55#include <asm/div64.h>
56
57#include <linux/swapops.h>
Rafael Aquini117aad12013-09-30 13:45:16 -070058#include <linux/balloon_compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070059
Nick Piggin0f8053a2006-03-22 00:08:33 -080060#include "internal.h"
61
Mel Gorman33906bc2010-08-09 17:19:16 -070062#define CREATE_TRACE_POINTS
63#include <trace/events/vmscan.h>
64
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -070065#undef CREATE_TRACE_POINTS
66#include <trace/hooks/vmscan.h>
67
Linus Torvalds1da177e2005-04-16 15:20:36 -070068struct scan_control {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -080069 /* How many pages shrink_list() should reclaim */
70 unsigned long nr_to_reclaim;
71
Johannes Weineree814fe2014-08-06 16:06:19 -070072 /*
73 * Nodemask of nodes allowed by the caller. If NULL, all nodes
74 * are scanned.
75 */
76 nodemask_t *nodemask;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -070077
KOSAKI Motohiro5f53e762010-05-24 14:32:37 -070078 /*
Johannes Weinerf16015f2012-01-12 17:17:52 -080079 * The memory cgroup that hit its limit and as a result is the
80 * primary target of this reclaim invocation.
81 */
82 struct mem_cgroup *target_mem_cgroup;
Balbir Singh66e17072008-02-07 00:13:56 -080083
Johannes Weiner7cf111b2020-06-03 16:03:06 -070084 /*
85 * Scan pressure balancing between anon and file LRUs
86 */
87 unsigned long anon_cost;
88 unsigned long file_cost;
89
Johannes Weinerb91ac372019-11-30 17:56:02 -080090 /* Can active pages be deactivated as part of reclaim? */
91#define DEACTIVATE_ANON 1
92#define DEACTIVATE_FILE 2
93 unsigned int may_deactivate:2;
94 unsigned int force_deactivate:1;
95 unsigned int skipped_deactivate:1;
96
Johannes Weiner1276ad62017-02-24 14:56:11 -080097 /* Writepage batching in laptop mode; RECLAIM_WRITE */
Johannes Weineree814fe2014-08-06 16:06:19 -070098 unsigned int may_writepage:1;
99
100 /* Can mapped pages be reclaimed? */
101 unsigned int may_unmap:1;
102
103 /* Can pages be swapped as part of reclaim? */
104 unsigned int may_swap:1;
105
Yisheng Xied6622f62017-05-03 14:53:57 -0700106 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700107 * Cgroup memory below memory.low is protected as long as we
108 * don't threaten to OOM. If any cgroup is reclaimed at
109 * reduced force or passed over entirely due to its memory.low
110 * setting (memcg_low_skipped), and nothing is reclaimed as a
111 * result, then go back for one more cycle that reclaims the protected
112 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700113 */
114 unsigned int memcg_low_reclaim:1;
115 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800116
Johannes Weineree814fe2014-08-06 16:06:19 -0700117 unsigned int hibernation_mode:1;
118
119 /* One of the zones is ready for compaction */
120 unsigned int compaction_ready:1;
121
Johannes Weinerb91ac372019-11-30 17:56:02 -0800122 /* There is easily reclaimable cold cache in the current node */
123 unsigned int cache_trim_mode:1;
124
Johannes Weiner53138ce2019-11-30 17:55:56 -0800125 /* The file pages on the current node are dangerously low */
126 unsigned int file_is_tiny:1;
127
Dave Hansen26aa2d12021-09-02 14:59:16 -0700128 /* Always discard instead of demoting to lower tier memory */
129 unsigned int no_demotion:1;
130
Greg Thelenbb451fd2018-08-17 15:45:19 -0700131 /* Allocation order */
132 s8 order;
133
134 /* Scan (total_size >> priority) pages at once */
135 s8 priority;
136
137 /* The highest zone to isolate pages for reclaim from */
138 s8 reclaim_idx;
139
140 /* This context's GFP mask */
141 gfp_t gfp_mask;
142
Johannes Weineree814fe2014-08-06 16:06:19 -0700143 /* Incremented by the number of inactive pages that were scanned */
144 unsigned long nr_scanned;
145
146 /* Number of pages freed so far during a call to shrink_zones() */
147 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700148
149 struct {
150 unsigned int dirty;
151 unsigned int unqueued_dirty;
152 unsigned int congested;
153 unsigned int writeback;
154 unsigned int immediate;
155 unsigned int file_taken;
156 unsigned int taken;
157 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700158
159 /* for recording the reclaimed slab by now */
160 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700161};
162
Linus Torvalds1da177e2005-04-16 15:20:36 -0700163#ifdef ARCH_HAS_PREFETCHW
164#define prefetchw_prev_lru_page(_page, _base, _field) \
165 do { \
166 if ((_page)->lru.prev != _base) { \
167 struct page *prev; \
168 \
169 prev = lru_to_page(&(_page->lru)); \
170 prefetchw(&prev->_field); \
171 } \
172 } while (0)
173#else
174#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
175#endif
176
177/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700178 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700179 */
180int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700181
Yang Shi0a432dc2019-09-23 15:38:12 -0700182static void set_task_reclaim_state(struct task_struct *task,
183 struct reclaim_state *rs)
184{
185 /* Check for an overwrite */
186 WARN_ON_ONCE(rs && task->reclaim_state);
187
188 /* Check for the nulling of an already-nulled member */
189 WARN_ON_ONCE(!rs && !task->reclaim_state);
190
191 task->reclaim_state = rs;
192}
193
Linus Torvalds1da177e2005-04-16 15:20:36 -0700194static LIST_HEAD(shrinker_list);
195static DECLARE_RWSEM(shrinker_rwsem);
196
Yang Shi0a432dc2019-09-23 15:38:12 -0700197#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700198static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700199
Yang Shi3c6f17e2021-05-04 18:36:33 -0700200/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700201static inline int shrinker_map_size(int nr_items)
202{
203 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
204}
Yang Shi2bfd3632021-05-04 18:36:11 -0700205
Yang Shi3c6f17e2021-05-04 18:36:33 -0700206static inline int shrinker_defer_size(int nr_items)
207{
208 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
209}
210
Yang Shi468ab842021-05-04 18:36:26 -0700211static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
212 int nid)
213{
214 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
215 lockdep_is_held(&shrinker_rwsem));
216}
217
Yang Shie4262c42021-05-04 18:36:23 -0700218static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700219 int map_size, int defer_size,
220 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700221{
Yang Shie4262c42021-05-04 18:36:23 -0700222 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700223 struct mem_cgroup_per_node *pn;
224 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700225 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700226
Yang Shi2bfd3632021-05-04 18:36:11 -0700227 for_each_node(nid) {
228 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700229 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700230 /* Not yet online memcg */
231 if (!old)
232 return 0;
233
234 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
235 if (!new)
236 return -ENOMEM;
237
Yang Shi3c6f17e2021-05-04 18:36:33 -0700238 new->nr_deferred = (atomic_long_t *)(new + 1);
239 new->map = (void *)new->nr_deferred + defer_size;
240
241 /* map: set all old bits, clear all new bits */
242 memset(new->map, (int)0xff, old_map_size);
243 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
244 /* nr_deferred: copy old values, clear all new values */
245 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
246 memset((void *)new->nr_deferred + old_defer_size, 0,
247 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700248
Yang Shie4262c42021-05-04 18:36:23 -0700249 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700250 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700251 }
252
253 return 0;
254}
255
Yang Shie4262c42021-05-04 18:36:23 -0700256void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700257{
258 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700259 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700260 int nid;
261
Yang Shi2bfd3632021-05-04 18:36:11 -0700262 for_each_node(nid) {
263 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700264 info = rcu_dereference_protected(pn->shrinker_info, true);
265 kvfree(info);
266 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700267 }
268}
269
Yang Shie4262c42021-05-04 18:36:23 -0700270int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700271{
Yang Shie4262c42021-05-04 18:36:23 -0700272 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700273 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700274 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700275
Yang Shid27cf2a2021-05-04 18:36:14 -0700276 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700277 map_size = shrinker_map_size(shrinker_nr_max);
278 defer_size = shrinker_defer_size(shrinker_nr_max);
279 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700280 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700281 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
282 if (!info) {
283 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700284 ret = -ENOMEM;
285 break;
286 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700287 info->nr_deferred = (atomic_long_t *)(info + 1);
288 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700289 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700290 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700291 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700292
293 return ret;
294}
295
Yang Shi3c6f17e2021-05-04 18:36:33 -0700296static inline bool need_expand(int nr_max)
297{
298 return round_up(nr_max, BITS_PER_LONG) >
299 round_up(shrinker_nr_max, BITS_PER_LONG);
300}
301
Yang Shie4262c42021-05-04 18:36:23 -0700302static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700303{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700304 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700305 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700306 int map_size, defer_size = 0;
307 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700308 struct mem_cgroup *memcg;
309
Yang Shi3c6f17e2021-05-04 18:36:33 -0700310 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700311 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700312
Yang Shi2bfd3632021-05-04 18:36:11 -0700313 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700314 goto out;
315
316 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700317
Yang Shi3c6f17e2021-05-04 18:36:33 -0700318 map_size = shrinker_map_size(new_nr_max);
319 defer_size = shrinker_defer_size(new_nr_max);
320 old_map_size = shrinker_map_size(shrinker_nr_max);
321 old_defer_size = shrinker_defer_size(shrinker_nr_max);
322
Yang Shi2bfd3632021-05-04 18:36:11 -0700323 memcg = mem_cgroup_iter(NULL, NULL, NULL);
324 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700325 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
326 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700327 if (ret) {
328 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700329 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700330 }
331 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700332out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700333 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700334 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700335
Yang Shi2bfd3632021-05-04 18:36:11 -0700336 return ret;
337}
338
339void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
340{
341 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700342 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700343
344 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700345 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700346 /* Pairs with smp mb in shrink_slab() */
347 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700348 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700349 rcu_read_unlock();
350 }
351}
352
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700353static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700354
355static int prealloc_memcg_shrinker(struct shrinker *shrinker)
356{
357 int id, ret = -ENOMEM;
358
Yang Shi476b30a2021-05-04 18:36:39 -0700359 if (mem_cgroup_disabled())
360 return -ENOSYS;
361
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700362 down_write(&shrinker_rwsem);
363 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700364 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700365 if (id < 0)
366 goto unlock;
367
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700368 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700369 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700370 idr_remove(&shrinker_idr, id);
371 goto unlock;
372 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700373 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700374 shrinker->id = id;
375 ret = 0;
376unlock:
377 up_write(&shrinker_rwsem);
378 return ret;
379}
380
381static void unregister_memcg_shrinker(struct shrinker *shrinker)
382{
383 int id = shrinker->id;
384
385 BUG_ON(id < 0);
386
Yang Shi41ca6682021-05-04 18:36:29 -0700387 lockdep_assert_held(&shrinker_rwsem);
388
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700389 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700390}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700391
Yang Shi86750832021-05-04 18:36:36 -0700392static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
393 struct mem_cgroup *memcg)
394{
395 struct shrinker_info *info;
396
397 info = shrinker_info_protected(memcg, nid);
398 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
399}
400
401static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
402 struct mem_cgroup *memcg)
403{
404 struct shrinker_info *info;
405
406 info = shrinker_info_protected(memcg, nid);
407 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
408}
409
Yang Shia1780152021-05-04 18:36:42 -0700410void reparent_shrinker_deferred(struct mem_cgroup *memcg)
411{
412 int i, nid;
413 long nr;
414 struct mem_cgroup *parent;
415 struct shrinker_info *child_info, *parent_info;
416
417 parent = parent_mem_cgroup(memcg);
418 if (!parent)
419 parent = root_mem_cgroup;
420
421 /* Prevent from concurrent shrinker_info expand */
422 down_read(&shrinker_rwsem);
423 for_each_node(nid) {
424 child_info = shrinker_info_protected(memcg, nid);
425 parent_info = shrinker_info_protected(parent, nid);
426 for (i = 0; i < shrinker_nr_max; i++) {
427 nr = atomic_long_read(&child_info->nr_deferred[i]);
428 atomic_long_add(nr, &parent_info->nr_deferred[i]);
429 }
430 }
431 up_read(&shrinker_rwsem);
432}
433
Johannes Weinerb5ead352019-11-30 17:55:40 -0800434static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800435{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800436 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800437}
Tejun Heo97c93412015-05-22 18:23:36 -0400438
439/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800440 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400441 * @sc: scan_control in question
442 *
443 * The normal page dirty throttling mechanism in balance_dirty_pages() is
444 * completely broken with the legacy memcg and direct stalling in
445 * shrink_page_list() is used for throttling instead, which lacks all the
446 * niceties such as fairness, adaptive pausing, bandwidth proportional
447 * allocation and configurability.
448 *
449 * This function tests whether the vmscan currently in progress can assume
450 * that the normal dirty throttling mechanism is operational.
451 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800452static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400453{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800454 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400455 return true;
456#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800457 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400458 return true;
459#endif
460 return false;
461}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800462#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700463static int prealloc_memcg_shrinker(struct shrinker *shrinker)
464{
Yang Shi476b30a2021-05-04 18:36:39 -0700465 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700466}
467
468static void unregister_memcg_shrinker(struct shrinker *shrinker)
469{
470}
471
Yang Shi86750832021-05-04 18:36:36 -0700472static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
473 struct mem_cgroup *memcg)
474{
475 return 0;
476}
477
478static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
479 struct mem_cgroup *memcg)
480{
481 return 0;
482}
483
Johannes Weinerb5ead352019-11-30 17:55:40 -0800484static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800485{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800486 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800487}
Tejun Heo97c93412015-05-22 18:23:36 -0400488
Johannes Weinerb5ead352019-11-30 17:55:40 -0800489static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400490{
491 return true;
492}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800493#endif
494
Yang Shi86750832021-05-04 18:36:36 -0700495static long xchg_nr_deferred(struct shrinker *shrinker,
496 struct shrink_control *sc)
497{
498 int nid = sc->nid;
499
500 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
501 nid = 0;
502
503 if (sc->memcg &&
504 (shrinker->flags & SHRINKER_MEMCG_AWARE))
505 return xchg_nr_deferred_memcg(nid, shrinker,
506 sc->memcg);
507
508 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
509}
510
511
512static long add_nr_deferred(long nr, struct shrinker *shrinker,
513 struct shrink_control *sc)
514{
515 int nid = sc->nid;
516
517 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
518 nid = 0;
519
520 if (sc->memcg &&
521 (shrinker->flags & SHRINKER_MEMCG_AWARE))
522 return add_nr_deferred_memcg(nr, nid, shrinker,
523 sc->memcg);
524
525 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
526}
527
Dave Hansen26aa2d12021-09-02 14:59:16 -0700528static bool can_demote(int nid, struct scan_control *sc)
529{
Huang Ying20b51af12021-09-02 14:59:33 -0700530 if (!numa_demotion_enabled)
531 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700532 if (sc) {
533 if (sc->no_demotion)
534 return false;
535 /* It is pointless to do demotion in memcg reclaim */
536 if (cgroup_reclaim(sc))
537 return false;
538 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700539 if (next_demotion_node(nid) == NUMA_NO_NODE)
540 return false;
541
Huang Ying20b51af12021-09-02 14:59:33 -0700542 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700543}
544
Keith Buscha2a36482021-09-02 14:59:26 -0700545static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
546 int nid,
547 struct scan_control *sc)
548{
549 if (memcg == NULL) {
550 /*
551 * For non-memcg reclaim, is there
552 * space in any swap device?
553 */
554 if (get_nr_swap_pages() > 0)
555 return true;
556 } else {
557 /* Is the memcg below its swap limit? */
558 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
559 return true;
560 }
561
562 /*
563 * The page can not be swapped.
564 *
565 * Can it be reclaimed from this node via demotion?
566 */
567 return can_demote(nid, sc);
568}
569
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700570/*
571 * This misses isolated pages which are not accounted for to save counters.
572 * As the data only determines if reclaim or compaction continues, it is
573 * not expected that isolated pages will be a dominating factor.
574 */
575unsigned long zone_reclaimable_pages(struct zone *zone)
576{
577 unsigned long nr;
578
579 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
580 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700581 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700582 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
583 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
584
585 return nr;
586}
587
Michal Hockofd538802017-02-22 15:45:58 -0800588/**
589 * lruvec_lru_size - Returns the number of pages on the given LRU list.
590 * @lruvec: lru vector
591 * @lru: lru to use
592 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
593 */
Yu Zhao20913392021-02-24 12:08:44 -0800594static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
595 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800596{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800597 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800598 int zid;
599
Johannes Weinerde3b0152019-11-30 17:55:31 -0800600 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800601 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800602
Michal Hockofd538802017-02-22 15:45:58 -0800603 if (!managed_zone(zone))
604 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800605
Michal Hockofd538802017-02-22 15:45:58 -0800606 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800607 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800608 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800609 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800610 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800611 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800612}
613
Linus Torvalds1da177e2005-04-16 15:20:36 -0700614/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000615 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700616 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900617int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700618{
Yang Shi476b30a2021-05-04 18:36:39 -0700619 unsigned int size;
620 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000621
Yang Shi476b30a2021-05-04 18:36:39 -0700622 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
623 err = prealloc_memcg_shrinker(shrinker);
624 if (err != -ENOSYS)
625 return err;
626
627 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
628 }
629
630 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000631 if (shrinker->flags & SHRINKER_NUMA_AWARE)
632 size *= nr_node_ids;
633
634 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
635 if (!shrinker->nr_deferred)
636 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700637
Tetsuo Handa8e049442018-04-04 19:53:07 +0900638 return 0;
639}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000640
Tetsuo Handa8e049442018-04-04 19:53:07 +0900641void free_prealloced_shrinker(struct shrinker *shrinker)
642{
Yang Shi41ca6682021-05-04 18:36:29 -0700643 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
644 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700645 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700646 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700647 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700648 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700649
Tetsuo Handa8e049442018-04-04 19:53:07 +0900650 kfree(shrinker->nr_deferred);
651 shrinker->nr_deferred = NULL;
652}
653
654void register_shrinker_prepared(struct shrinker *shrinker)
655{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700656 down_write(&shrinker_rwsem);
657 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700658 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700659 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900660}
661
662int register_shrinker(struct shrinker *shrinker)
663{
664 int err = prealloc_shrinker(shrinker);
665
666 if (err)
667 return err;
668 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000669 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700670}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700671EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700672
673/*
674 * Remove one
675 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700676void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700677{
Yang Shi41ca6682021-05-04 18:36:29 -0700678 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900679 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700680
Linus Torvalds1da177e2005-04-16 15:20:36 -0700681 down_write(&shrinker_rwsem);
682 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700683 shrinker->flags &= ~SHRINKER_REGISTERED;
684 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
685 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700686 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700687
Andrew Vaginae393322013-10-16 13:46:46 -0700688 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900689 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700690}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700691EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700692
693#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000694
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800695static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800696 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700697{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000698 unsigned long freed = 0;
699 unsigned long long delta;
700 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700701 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000702 long nr;
703 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000704 long batch_size = shrinker->batch ? shrinker->batch
705 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800706 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000707
rongqianfeng8da6ee32021-05-21 10:30:14 +0800708 trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
709
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700710 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700711 if (freeable == 0 || freeable == SHRINK_EMPTY)
712 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000713
714 /*
715 * copy the current shrinker scan count into a local variable
716 * and zero it so that other concurrent shrinker invocations
717 * don't also do this scanning work.
718 */
Yang Shi86750832021-05-04 18:36:36 -0700719 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000720
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700721 if (shrinker->seeks) {
722 delta = freeable >> priority;
723 delta *= 4;
724 do_div(delta, shrinker->seeks);
725 } else {
726 /*
727 * These objects don't require any IO to create. Trim
728 * them aggressively under memory pressure to keep
729 * them from causing refetches in the IO caches.
730 */
731 delta = freeable / 2;
732 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700733
Yang Shi18bb4732021-05-04 18:36:45 -0700734 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000735 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700736 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000737
738 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800739 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000740
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800741 /*
742 * Normally, we should not scan less than batch_size objects in one
743 * pass to avoid too frequent shrinker calls, but if the slab has less
744 * than batch_size objects in total and we are really tight on memory,
745 * we will try to reclaim all available objects, otherwise we can end
746 * up failing allocations although there are plenty of reclaimable
747 * objects spread over several slabs with usage less than the
748 * batch_size.
749 *
750 * We detect the "tight on memory" situations by looking at the total
751 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700752 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800753 * scanning at high prio and therefore should try to reclaim as much as
754 * possible.
755 */
756 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700757 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000758 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800759 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000760
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800761 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700762 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000763 ret = shrinker->scan_objects(shrinker, shrinkctl);
764 if (ret == SHRINK_STOP)
765 break;
766 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000767
Chris Wilsond460acb2017-09-06 16:19:26 -0700768 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
769 total_scan -= shrinkctl->nr_scanned;
770 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000771
772 cond_resched();
773 }
774
Yang Shi18bb4732021-05-04 18:36:45 -0700775 /*
776 * The deferred work is increased by any new work (delta) that wasn't
777 * done, decreased by old deferred work that was done now.
778 *
779 * And it is capped to two times of the freeable items.
780 */
781 next_deferred = max_t(long, (nr + delta - scanned), 0);
782 next_deferred = min(next_deferred, (2 * freeable));
783
Glauber Costa1d3d4432013-08-28 10:18:04 +1000784 /*
785 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700786 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000787 */
Yang Shi86750832021-05-04 18:36:36 -0700788 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000789
Yang Shi8efb4b52021-05-04 18:36:08 -0700790 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000791 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700792}
793
Yang Shi0a432dc2019-09-23 15:38:12 -0700794#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700795static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
796 struct mem_cgroup *memcg, int priority)
797{
Yang Shie4262c42021-05-04 18:36:23 -0700798 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700799 unsigned long ret, freed = 0;
800 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700801
Yang Shi0a432dc2019-09-23 15:38:12 -0700802 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700803 return 0;
804
805 if (!down_read_trylock(&shrinker_rwsem))
806 return 0;
807
Yang Shi468ab842021-05-04 18:36:26 -0700808 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700809 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700810 goto unlock;
811
Yang Shie4262c42021-05-04 18:36:23 -0700812 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700813 struct shrink_control sc = {
814 .gfp_mask = gfp_mask,
815 .nid = nid,
816 .memcg = memcg,
817 };
818 struct shrinker *shrinker;
819
820 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700821 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700822 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700823 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700824 continue;
825 }
826
Yang Shi0a432dc2019-09-23 15:38:12 -0700827 /* Call non-slab shrinkers even though kmem is disabled */
828 if (!memcg_kmem_enabled() &&
829 !(shrinker->flags & SHRINKER_NONSLAB))
830 continue;
831
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700832 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700833 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700834 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700835 /*
836 * After the shrinker reported that it had no objects to
837 * free, but before we cleared the corresponding bit in
838 * the memcg shrinker map, a new object might have been
839 * added. To make sure, we have the bit set in this
840 * case, we invoke the shrinker one more time and reset
841 * the bit if it reports that it is not empty anymore.
842 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700843 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700844 *
845 * list_lru_add() shrink_slab_memcg()
846 * list_add_tail() clear_bit()
847 * <MB> <MB>
848 * set_bit() do_shrink_slab()
849 */
850 smp_mb__after_atomic();
851 ret = do_shrink_slab(&sc, shrinker, priority);
852 if (ret == SHRINK_EMPTY)
853 ret = 0;
854 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700855 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700856 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700857 freed += ret;
858
859 if (rwsem_is_contended(&shrinker_rwsem)) {
860 freed = freed ? : 1;
861 break;
862 }
863 }
864unlock:
865 up_read(&shrinker_rwsem);
866 return freed;
867}
Yang Shi0a432dc2019-09-23 15:38:12 -0700868#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700869static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
870 struct mem_cgroup *memcg, int priority)
871{
872 return 0;
873}
Yang Shi0a432dc2019-09-23 15:38:12 -0700874#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700875
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800876/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800877 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800878 * @gfp_mask: allocation context
879 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800880 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800881 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700882 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800883 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700884 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800885 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
886 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700887 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700888 * @memcg specifies the memory cgroup to target. Unaware shrinkers
889 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800890 *
Josef Bacik9092c712018-01-31 16:16:26 -0800891 * @priority is sc->priority, we take the number of objects and >> by priority
892 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700893 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800894 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700895 */
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800896unsigned long shrink_slab(gfp_t gfp_mask, int nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800897 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800898 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700899{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700900 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700901 struct shrinker *shrinker;
wudean842c68a2021-04-27 17:40:41 +0800902 bool bypass = false;
903
904 trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
905 if (bypass)
906 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700907
Yang Shifa1e5122019-08-02 21:48:44 -0700908 /*
909 * The root memcg might be allocated even though memcg is disabled
910 * via "cgroup_disable=memory" boot parameter. This could make
911 * mem_cgroup_is_root() return false, then just run memcg slab
912 * shrink, but skip global shrink. This may result in premature
913 * oom.
914 */
915 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700916 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800917
Tetsuo Handae830c632018-04-05 16:23:35 -0700918 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700919 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700920
921 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800922 struct shrink_control sc = {
923 .gfp_mask = gfp_mask,
924 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800925 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800926 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800927
Kirill Tkhai9b996462018-08-17 15:48:21 -0700928 ret = do_shrink_slab(&sc, shrinker, priority);
929 if (ret == SHRINK_EMPTY)
930 ret = 0;
931 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800932 /*
933 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700934 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800935 * by parallel ongoing shrinking.
936 */
937 if (rwsem_is_contended(&shrinker_rwsem)) {
938 freed = freed ? : 1;
939 break;
940 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700941 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800942
Linus Torvalds1da177e2005-04-16 15:20:36 -0700943 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700944out:
945 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000946 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700947}
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800948EXPORT_SYMBOL_GPL(shrink_slab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700949
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800950void drop_slab_node(int nid)
951{
952 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700953 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800954
955 do {
956 struct mem_cgroup *memcg = NULL;
957
Chunxin Zang069c4112020-10-13 16:56:46 -0700958 if (fatal_signal_pending(current))
959 return;
960
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800961 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700962 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800963 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800964 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800965 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700966 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800967}
968
969void drop_slab(void)
970{
971 int nid;
972
973 for_each_online_node(nid)
974 drop_slab_node(nid);
975}
976
Linus Torvalds1da177e2005-04-16 15:20:36 -0700977static inline int is_page_cache_freeable(struct page *page)
978{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700979 /*
980 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400981 * that isolated the page, the page cache and optional buffer
982 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700983 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -0700984 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400985 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700986}
987
Yang Shicb165562019-11-30 17:55:28 -0800988static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700989{
Christoph Lameter930d9152006-01-08 01:00:47 -0800990 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700991 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400992 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700993 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400994 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700995 return 1;
996 return 0;
997}
998
999/*
1000 * We detected a synchronous write error writing a page out. Probably
1001 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1002 * fsync(), msync() or close().
1003 *
1004 * The tricky part is that after writepage we cannot touch the mapping: nothing
1005 * prevents it from being freed up. But we have a ref on the page and once
1006 * that page is locked, the mapping is pinned.
1007 *
1008 * We're allowed to run sleeping lock_page() here because we know the caller has
1009 * __GFP_FS.
1010 */
1011static void handle_write_error(struct address_space *mapping,
1012 struct page *page, int error)
1013{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001014 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001015 if (page_mapping(page) == mapping)
1016 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001017 unlock_page(page);
1018}
1019
Christoph Lameter04e62a22006-06-23 02:03:38 -07001020/* possible outcome of pageout() */
1021typedef enum {
1022 /* failed to write page out, page is locked */
1023 PAGE_KEEP,
1024 /* move page to the active list, page is locked */
1025 PAGE_ACTIVATE,
1026 /* page has been sent to the disk successfully, page is unlocked */
1027 PAGE_SUCCESS,
1028 /* page is clean and locked */
1029 PAGE_CLEAN,
1030} pageout_t;
1031
Linus Torvalds1da177e2005-04-16 15:20:36 -07001032/*
Andrew Morton1742f192006-03-22 00:08:21 -08001033 * pageout is called by shrink_page_list() for each dirty page.
1034 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001035 */
Yang Shicb165562019-11-30 17:55:28 -08001036static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001037{
1038 /*
1039 * If the page is dirty, only perform writeback if that write
1040 * will be non-blocking. To prevent this allocation from being
1041 * stalled by pagecache activity. But note that there may be
1042 * stalls if we need to run get_block(). We could test
1043 * PagePrivate for that.
1044 *
Al Viro81742022014-04-03 03:17:43 -04001045 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001046 * this page's queue, we can perform writeback even if that
1047 * will block.
1048 *
1049 * If the page is swapcache, write it back even if that would
1050 * block, for some throttling. This happens by accident, because
1051 * swap_backing_dev_info is bust: it doesn't reflect the
1052 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001053 */
1054 if (!is_page_cache_freeable(page))
1055 return PAGE_KEEP;
1056 if (!mapping) {
1057 /*
1058 * Some data journaling orphaned pages can have
1059 * page->mapping == NULL while being dirty with clean buffers.
1060 */
David Howells266cf652009-04-03 16:42:36 +01001061 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001062 if (try_to_free_buffers(page)) {
1063 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001064 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001065 return PAGE_CLEAN;
1066 }
1067 }
1068 return PAGE_KEEP;
1069 }
1070 if (mapping->a_ops->writepage == NULL)
1071 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001072 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001073 return PAGE_KEEP;
1074
1075 if (clear_page_dirty_for_io(page)) {
1076 int res;
1077 struct writeback_control wbc = {
1078 .sync_mode = WB_SYNC_NONE,
1079 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001080 .range_start = 0,
1081 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001082 .for_reclaim = 1,
1083 };
1084
1085 SetPageReclaim(page);
1086 res = mapping->a_ops->writepage(page, &wbc);
1087 if (res < 0)
1088 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001089 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001090 ClearPageReclaim(page);
1091 return PAGE_ACTIVATE;
1092 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001093
Linus Torvalds1da177e2005-04-16 15:20:36 -07001094 if (!PageWriteback(page)) {
1095 /* synchronous write or broken a_ops? */
1096 ClearPageReclaim(page);
1097 }
yalin wang3aa23852016-01-14 15:18:30 -08001098 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001099 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001100 return PAGE_SUCCESS;
1101 }
1102
1103 return PAGE_CLEAN;
1104}
1105
Andrew Mortona649fd92006-10-17 00:09:36 -07001106/*
Nick Piggine2867812008-07-25 19:45:30 -07001107 * Same as remove_mapping, but if the page is removed from the mapping, it
1108 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001109 */
Johannes Weinera5289102014-04-03 14:47:51 -07001110static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001111 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001112{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001113 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001114 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001115
Nick Piggin28e4d962006-09-25 23:31:23 -07001116 BUG_ON(!PageLocked(page));
1117 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001118
Johannes Weiner30472502021-09-02 14:53:18 -07001119 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001120 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001121 * The non racy check for a busy page.
1122 *
1123 * Must be careful with the order of the tests. When someone has
1124 * a ref to the page, it may be possible that they dirty it then
1125 * drop the reference. So if PageDirty is tested before page_count
1126 * here, then the following race may occur:
1127 *
1128 * get_user_pages(&page);
1129 * [user mapping goes away]
1130 * write_to(page);
1131 * !PageDirty(page) [good]
1132 * SetPageDirty(page);
1133 * put_page(page);
1134 * !page_count(page) [good, discard it]
1135 *
1136 * [oops, our write_to data is lost]
1137 *
1138 * Reversing the order of the tests ensures such a situation cannot
1139 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001140 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001141 *
1142 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001143 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001144 */
William Kucharski906d2782019-10-18 20:20:33 -07001145 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001146 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001147 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001148 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001149 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001150 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001151 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001152 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001153
1154 if (PageSwapCache(page)) {
1155 swp_entry_t swap = { .val = page_private(page) };
Yu Zhao37397872022-09-18 02:00:03 -06001156
1157 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001158 if (reclaimed && !mapping_exiting(mapping))
1159 shadow = workingset_eviction(page, target_memcg);
Yu Zhao37397872022-09-18 02:00:03 -06001160 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001161 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001162 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001163 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001164 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001165 void (*freepage)(struct page *);
1166
1167 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001168 /*
1169 * Remember a shadow entry for reclaimed file cache in
1170 * order to detect refaults, thus thrashing, later on.
1171 *
1172 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001173 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001174 * inode reclaim needs to empty out the radix tree or
1175 * the nodes are lost. Don't plant shadows behind its
1176 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001177 *
1178 * We also don't store shadows for DAX mappings because the
1179 * only page cache pages found in these are zero pages
1180 * covering holes, and because we don't want to mix DAX
1181 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001182 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001183 */
Huang Ying9de4f222020-04-06 20:04:41 -07001184 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001185 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001186 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001187 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001188 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001189
1190 if (freepage != NULL)
1191 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001192 }
1193
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001194 return 1;
1195
1196cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001197 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001198 return 0;
1199}
1200
Linus Torvalds1da177e2005-04-16 15:20:36 -07001201/*
Nick Piggine2867812008-07-25 19:45:30 -07001202 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1203 * someone else has a ref on the page, abort and return 0. If it was
1204 * successfully detached, return 1. Assumes the caller has a single ref on
1205 * this page.
1206 */
1207int remove_mapping(struct address_space *mapping, struct page *page)
1208{
Johannes Weinerb9107182019-11-30 17:55:59 -08001209 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001210 /*
1211 * Unfreezing the refcount with 1 rather than 2 effectively
1212 * drops the pagecache ref for us without requiring another
1213 * atomic operation.
1214 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001215 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001216 return 1;
1217 }
1218 return 0;
1219}
1220
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001221/**
1222 * putback_lru_page - put previously isolated page onto appropriate LRU list
1223 * @page: page to be put back to appropriate lru list
1224 *
1225 * Add previously isolated @page to appropriate LRU list.
1226 * Page may still be unevictable for other reasons.
1227 *
1228 * lru_lock must not be held, interrupts must be enabled.
1229 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001230void putback_lru_page(struct page *page)
1231{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001232 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001233 put_page(page); /* drop ref from isolate */
1234}
1235
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001236enum page_references {
1237 PAGEREF_RECLAIM,
1238 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001239 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001240 PAGEREF_ACTIVATE,
1241};
1242
1243static enum page_references page_check_references(struct page *page,
1244 struct scan_control *sc)
1245{
Johannes Weiner645747462010-03-05 13:42:22 -08001246 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001247 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001248
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001249 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1250 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001251 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001252
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001253 /*
1254 * Mlock lost the isolation race with us. Let try_to_unmap()
1255 * move the page to the unevictable list.
1256 */
1257 if (vm_flags & VM_LOCKED)
1258 return PAGEREF_RECLAIM;
1259
Johannes Weiner645747462010-03-05 13:42:22 -08001260 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001261 /*
1262 * All mapped pages start out with page table
1263 * references from the instantiating fault, so we need
1264 * to look twice if a mapped file page is used more
1265 * than once.
1266 *
1267 * Mark it and spare it for another trip around the
1268 * inactive list. Another page table reference will
1269 * lead to its activation.
1270 *
1271 * Note: the mark is set for activated pages as well
1272 * so that recently deactivated but used pages are
1273 * quickly recovered.
1274 */
1275 SetPageReferenced(page);
1276
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001277 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001278 return PAGEREF_ACTIVATE;
1279
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001280 /*
1281 * Activate file-backed executable pages after first usage.
1282 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001283 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001284 return PAGEREF_ACTIVATE;
1285
Johannes Weiner645747462010-03-05 13:42:22 -08001286 return PAGEREF_KEEP;
1287 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001288
1289 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001290 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001291 return PAGEREF_RECLAIM_CLEAN;
1292
1293 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001294}
1295
Mel Gormane2be15f2013-07-03 15:01:57 -07001296/* Check if a page is dirty or under writeback */
1297static void page_check_dirty_writeback(struct page *page,
1298 bool *dirty, bool *writeback)
1299{
Mel Gormanb4597222013-07-03 15:02:05 -07001300 struct address_space *mapping;
1301
Mel Gormane2be15f2013-07-03 15:01:57 -07001302 /*
1303 * Anonymous pages are not handled by flushers and must be written
1304 * from reclaim context. Do not stall reclaim based on them
1305 */
Huang Ying9de4f222020-04-06 20:04:41 -07001306 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001307 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001308 *dirty = false;
1309 *writeback = false;
1310 return;
1311 }
1312
1313 /* By default assume that the page flags are accurate */
1314 *dirty = PageDirty(page);
1315 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001316
1317 /* Verify dirty/writeback state if the filesystem supports it */
1318 if (!page_has_private(page))
1319 return;
1320
1321 mapping = page_mapping(page);
1322 if (mapping && mapping->a_ops->is_dirty_writeback)
1323 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001324}
1325
Dave Hansen26aa2d12021-09-02 14:59:16 -07001326static struct page *alloc_demote_page(struct page *page, unsigned long node)
1327{
1328 struct migration_target_control mtc = {
1329 /*
1330 * Allocate from 'node', or fail quickly and quietly.
1331 * When this happens, 'page' will likely just be discarded
1332 * instead of migrated.
1333 */
1334 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1335 __GFP_THISNODE | __GFP_NOWARN |
1336 __GFP_NOMEMALLOC | GFP_NOWAIT,
1337 .nid = node
1338 };
1339
1340 return alloc_migration_target(page, (unsigned long)&mtc);
1341}
1342
1343/*
1344 * Take pages on @demote_list and attempt to demote them to
1345 * another node. Pages which are not demoted are left on
1346 * @demote_pages.
1347 */
1348static unsigned int demote_page_list(struct list_head *demote_pages,
1349 struct pglist_data *pgdat)
1350{
1351 int target_nid = next_demotion_node(pgdat->node_id);
1352 unsigned int nr_succeeded;
1353 int err;
1354
1355 if (list_empty(demote_pages))
1356 return 0;
1357
1358 if (target_nid == NUMA_NO_NODE)
1359 return 0;
1360
1361 /* Demotion ignores all cpuset and mempolicy settings */
1362 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1363 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1364 &nr_succeeded);
1365
Yang Shi668e4142021-09-02 14:59:19 -07001366 if (current_is_kswapd())
1367 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1368 else
1369 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1370
Dave Hansen26aa2d12021-09-02 14:59:16 -07001371 return nr_succeeded;
1372}
1373
Nick Piggine2867812008-07-25 19:45:30 -07001374/*
Andrew Morton1742f192006-03-22 00:08:21 -08001375 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001376 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001377static unsigned int shrink_page_list(struct list_head *page_list,
1378 struct pglist_data *pgdat,
1379 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001380 struct reclaim_stat *stat,
1381 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001382{
1383 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001384 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001385 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001386 unsigned int nr_reclaimed = 0;
1387 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001388 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001389
Kirill Tkhai060f0052019-03-05 15:48:15 -08001390 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001391 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001392 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001393
Dave Hansen26aa2d12021-09-02 14:59:16 -07001394retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001395 while (!list_empty(page_list)) {
1396 struct address_space *mapping;
1397 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001398 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001399 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001400 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001401
1402 cond_resched();
1403
1404 page = lru_to_page(page_list);
1405 list_del(&page->lru);
1406
Nick Piggin529ae9a2008-08-02 12:01:03 +02001407 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001408 goto keep;
1409
Sasha Levin309381fea2014-01-23 15:52:54 -08001410 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001411
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001412 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001413
1414 /* Account the number of base pages even though THP */
1415 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001416
Hugh Dickins39b5f292012-10-08 16:33:18 -07001417 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001418 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001419
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001420 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001421 goto keep_locked;
1422
Yu Zhao0182f922022-09-18 02:00:04 -06001423 /* page_update_gen() tried to promote this page? */
1424 if (lru_gen_enabled() && !ignore_references &&
1425 page_mapped(page) && PageReferenced(page))
1426 goto keep_locked;
1427
Andy Whitcroftc661b072007-08-22 14:01:26 -07001428 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1429 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1430
Mel Gorman283aba92013-07-03 15:01:51 -07001431 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001432 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001433 * reclaim_congested which affects wait_iff_congested. kswapd
1434 * will stall and start writing pages if the tail of the LRU
1435 * is all dirty unqueued pages.
1436 */
1437 page_check_dirty_writeback(page, &dirty, &writeback);
1438 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001439 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001440
1441 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001442 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001443
Mel Gormand04e8ac2013-07-03 15:02:03 -07001444 /*
1445 * Treat this page as congested if the underlying BDI is or if
1446 * pages are cycling through the LRU so quickly that the
1447 * pages marked for immediate reclaim are making it to the
1448 * end of the LRU a second time.
1449 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001450 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001451 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001452 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001453 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001454 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001455
1456 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001457 * If a page at the tail of the LRU is under writeback, there
1458 * are three cases to consider.
1459 *
1460 * 1) If reclaim is encountering an excessive number of pages
1461 * under writeback and this page is both under writeback and
1462 * PageReclaim then it indicates that pages are being queued
1463 * for IO but are being recycled through the LRU before the
1464 * IO can complete. Waiting on the page itself risks an
1465 * indefinite stall if it is impossible to writeback the
1466 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001467 * note that the LRU is being scanned too quickly and the
1468 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001469 *
Tejun Heo97c93412015-05-22 18:23:36 -04001470 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001471 * not marked for immediate reclaim, or the caller does not
1472 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1473 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001474 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001475 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001476 * Require may_enter_fs because we would wait on fs, which
1477 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001478 * enter reclaim, and deadlock if it waits on a page for
1479 * which it is needed to do the write (loop masks off
1480 * __GFP_IO|__GFP_FS for this reason); but more thought
1481 * would probably show more reasons.
1482 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001483 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001484 * PageReclaim. memcg does not have any dirty pages
1485 * throttling so we could easily OOM just because too many
1486 * pages are in writeback and there is nothing else to
1487 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001488 *
1489 * In cases 1) and 2) we activate the pages to get them out of
1490 * the way while we continue scanning for clean pages on the
1491 * inactive list and refilling from the active list. The
1492 * observation here is that waiting for disk writes is more
1493 * expensive than potentially causing reloads down the line.
1494 * Since they're marked for immediate reclaim, they won't put
1495 * memory pressure on the cache working set any longer than it
1496 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001497 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001498 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001499 /* Case 1 above */
1500 if (current_is_kswapd() &&
1501 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001502 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001503 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001504 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001505
1506 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001507 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001508 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001509 /*
1510 * This is slightly racy - end_page_writeback()
1511 * might have just cleared PageReclaim, then
1512 * setting PageReclaim here end up interpreted
1513 * as PageReadahead - but that does not matter
1514 * enough to care. What we do want is for this
1515 * page to have PageReclaim set next time memcg
1516 * reclaim reaches the tests above, so it will
1517 * then wait_on_page_writeback() to avoid OOM;
1518 * and it's also appropriate in global reclaim.
1519 */
1520 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001521 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001522 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001523
1524 /* Case 3 above */
1525 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001526 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001527 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001528 /* then go back and try same page again */
1529 list_add_tail(&page->lru, page_list);
1530 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001531 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001532 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001533
Minchan Kim8940b342019-09-25 16:49:11 -07001534 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001535 references = page_check_references(page, sc);
1536
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001537 switch (references) {
1538 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001539 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001540 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001541 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001542 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001543 case PAGEREF_RECLAIM:
1544 case PAGEREF_RECLAIM_CLEAN:
1545 ; /* try to reclaim the page below */
1546 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001547
Linus Torvalds1da177e2005-04-16 15:20:36 -07001548 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001549 * Before reclaiming the page, try to relocate
1550 * its contents to another node.
1551 */
1552 if (do_demote_pass &&
1553 (thp_migration_supported() || !PageTransHuge(page))) {
1554 list_add(&page->lru, &demote_pages);
1555 unlock_page(page);
1556 continue;
1557 }
1558
1559 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001560 * Anonymous process memory has backing store?
1561 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001562 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001563 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001564 if (PageAnon(page) && PageSwapBacked(page)) {
1565 if (!PageSwapCache(page)) {
1566 if (!(sc->gfp_mask & __GFP_IO))
1567 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001568 if (page_maybe_dma_pinned(page))
1569 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001570 if (PageTransHuge(page)) {
1571 /* cannot split THP, skip it */
1572 if (!can_split_huge_page(page, NULL))
1573 goto activate_locked;
1574 /*
1575 * Split pages without a PMD map right
1576 * away. Chances are some or all of the
1577 * tail pages can be freed without IO.
1578 */
1579 if (!compound_mapcount(page) &&
1580 split_huge_page_to_list(page,
1581 page_list))
1582 goto activate_locked;
1583 }
1584 if (!add_to_swap(page)) {
1585 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001586 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001587 /* Fallback to swap normal pages */
1588 if (split_huge_page_to_list(page,
1589 page_list))
1590 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001591#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1592 count_vm_event(THP_SWPOUT_FALLBACK);
1593#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001594 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001595 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001596 }
Minchan Kim0f074652017-07-06 15:37:24 -07001597
Kirill Tkhai4b793062020-04-01 21:10:18 -07001598 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001599
1600 /* Adding to swap updated mapping */
1601 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001602 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001603 } else if (unlikely(PageTransHuge(page))) {
1604 /* Split file THP */
1605 if (split_huge_page_to_list(page, page_list))
1606 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001607 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001608
1609 /*
Yang Shi98879b32019-07-11 20:59:30 -07001610 * THP may get split above, need minus tail pages and update
1611 * nr_pages to avoid accounting tail pages twice.
1612 *
1613 * The tail pages that are added into swap cache successfully
1614 * reach here.
1615 */
1616 if ((nr_pages > 1) && !PageTransHuge(page)) {
1617 sc->nr_scanned -= (nr_pages - 1);
1618 nr_pages = 1;
1619 }
1620
1621 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001622 * The page is mapped into the page tables of one or more
1623 * processes. Try to unmap it here.
1624 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001625 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001626 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001627 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001628
1629 if (unlikely(PageTransHuge(page)))
1630 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001631
Yang Shi1fb08ac2021-06-30 18:52:01 -07001632 try_to_unmap(page, flags);
1633 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001634 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001635 if (!was_swapbacked && PageSwapBacked(page))
1636 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001637 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001638 }
1639 }
1640
1641 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001642 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001643 * Only kswapd can writeback filesystem pages
1644 * to avoid risk of stack overflow. But avoid
1645 * injecting inefficient single-page IO into
1646 * flusher writeback as much as possible: only
1647 * write pages when we've encountered many
1648 * dirty pages, and when we've already scanned
1649 * the rest of the LRU for clean pages and see
1650 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001651 */
Huang Ying9de4f222020-04-06 20:04:41 -07001652 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001653 (!current_is_kswapd() || !PageReclaim(page) ||
1654 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001655 /*
1656 * Immediately reclaim when written back.
1657 * Similar in principal to deactivate_page()
1658 * except we already have the page isolated
1659 * and know it's dirty
1660 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001661 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001662 SetPageReclaim(page);
1663
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001664 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001665 }
1666
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001667 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001668 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001669 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001670 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001671 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001672 goto keep_locked;
1673
Mel Gormand950c942015-09-04 15:47:35 -07001674 /*
1675 * Page is dirty. Flush the TLB if a writable entry
1676 * potentially exists to avoid CPU writes after IO
1677 * starts and then write it out here.
1678 */
1679 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001680 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001681 case PAGE_KEEP:
1682 goto keep_locked;
1683 case PAGE_ACTIVATE:
1684 goto activate_locked;
1685 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001686 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001687
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001688 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001689 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001690 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001691 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001692
Linus Torvalds1da177e2005-04-16 15:20:36 -07001693 /*
1694 * A synchronous write - probably a ramdisk. Go
1695 * ahead and try to reclaim the page.
1696 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001697 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001698 goto keep;
1699 if (PageDirty(page) || PageWriteback(page))
1700 goto keep_locked;
1701 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001702 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001703 case PAGE_CLEAN:
1704 ; /* try to free the page below */
1705 }
1706 }
1707
1708 /*
1709 * If the page has buffers, try to free the buffer mappings
1710 * associated with this page. If we succeed we try to free
1711 * the page as well.
1712 *
1713 * We do this even if the page is PageDirty().
1714 * try_to_release_page() does not perform I/O, but it is
1715 * possible for a page to have PageDirty set, but it is actually
1716 * clean (all its buffers are clean). This happens if the
1717 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001718 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001719 * try_to_release_page() will discover that cleanness and will
1720 * drop the buffers and mark the page clean - it can be freed.
1721 *
1722 * Rarely, pages can have buffers and no ->mapping. These are
1723 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001724 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001725 * and if that worked, and the page is no longer mapped into
1726 * process address space (page_count == 1) it can be freed.
1727 * Otherwise, leave the page on the LRU so it is swappable.
1728 */
David Howells266cf652009-04-03 16:42:36 +01001729 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001730 if (!try_to_release_page(page, sc->gfp_mask))
1731 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001732 if (!mapping && page_count(page) == 1) {
1733 unlock_page(page);
1734 if (put_page_testzero(page))
1735 goto free_it;
1736 else {
1737 /*
1738 * rare race with speculative reference.
1739 * the speculative reference will free
1740 * this page shortly, so we may
1741 * increment nr_reclaimed here (and
1742 * leave it off the LRU).
1743 */
1744 nr_reclaimed++;
1745 continue;
1746 }
1747 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001748 }
1749
Shaohua Li802a3a92017-05-03 14:52:32 -07001750 if (PageAnon(page) && !PageSwapBacked(page)) {
1751 /* follow __remove_mapping for reference */
1752 if (!page_ref_freeze(page, 1))
1753 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001754 /*
1755 * The page has only one reference left, which is
1756 * from the isolation. After the caller puts the
1757 * page back on lru and drops the reference, the
1758 * page will be freed anyway. It doesn't matter
1759 * which lru it goes. So we don't bother checking
1760 * PageDirty here.
1761 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001762 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001763 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001764 } else if (!mapping || !__remove_mapping(mapping, page, true,
1765 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001766 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001767
1768 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001769free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001770 /*
1771 * THP may get swapped out in a whole, need account
1772 * all base pages.
1773 */
1774 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001775
1776 /*
1777 * Is there need to periodically free_page_list? It would
1778 * appear not as the counts should be low
1779 */
Yang Shi7ae88532019-09-23 15:38:09 -07001780 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001781 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001782 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001783 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001784 continue;
1785
Yang Shi98879b32019-07-11 20:59:30 -07001786activate_locked_split:
1787 /*
1788 * The tail pages that are failed to add into swap cache
1789 * reach here. Fixup nr_scanned and nr_pages.
1790 */
1791 if (nr_pages > 1) {
1792 sc->nr_scanned -= (nr_pages - 1);
1793 nr_pages = 1;
1794 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001795activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001796 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001797 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1798 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001799 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001800 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001801 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001802 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001803 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001804 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001805 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001806 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001807keep_locked:
1808 unlock_page(page);
1809keep:
1810 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001811 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001812 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001813 /* 'page_list' is always empty here */
1814
1815 /* Migrate pages selected for demotion */
1816 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1817 /* Pages that could not be demoted are still in @demote_pages */
1818 if (!list_empty(&demote_pages)) {
1819 /* Pages which failed to demoted go back on @page_list for retry: */
1820 list_splice_init(&demote_pages, page_list);
1821 do_demote_pass = false;
1822 goto retry;
1823 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001824
Yang Shi98879b32019-07-11 20:59:30 -07001825 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1826
Johannes Weiner747db952014-08-08 14:19:24 -07001827 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001828 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001829 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001830
Linus Torvalds1da177e2005-04-16 15:20:36 -07001831 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001832 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001833
Andrew Morton05ff5132006-03-22 00:08:20 -08001834 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001835}
1836
Maninder Singh730ec8c2020-06-03 16:01:18 -07001837unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001838 struct list_head *page_list)
1839{
1840 struct scan_control sc = {
1841 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001842 .may_unmap = 1,
1843 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001844 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001845 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001846 struct page *page, *next;
1847 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001848 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001849
1850 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001851 if (!PageHuge(page) && page_is_file_lru(page) &&
1852 !PageDirty(page) && !__PageMovable(page) &&
1853 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001854 ClearPageActive(page);
1855 list_move(&page->lru, &clean_pages);
1856 }
1857 }
1858
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001859 /*
1860 * We should be safe here since we are only dealing with file pages and
1861 * we are not kswapd and therefore cannot write dirty file pages. But
1862 * call memalloc_noreclaim_save() anyway, just in case these conditions
1863 * change in the future.
1864 */
1865 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001866 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001867 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001868 memalloc_noreclaim_restore(noreclaim_flag);
1869
Minchan Kim02c6de82012-10-08 16:31:55 -07001870 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001871 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1872 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001873 /*
1874 * Since lazyfree pages are isolated from file LRU from the beginning,
1875 * they will rotate back to anonymous LRU in the end if it failed to
1876 * discard so isolated count will be mismatched.
1877 * Compensate the isolated count for both LRU lists.
1878 */
1879 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1880 stat.nr_lazyfree_fail);
1881 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001882 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001883 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001884}
1885
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001886/*
1887 * Attempt to remove the specified page from its LRU. Only take this page
1888 * if it is of the appropriate PageActive status. Pages which are being
1889 * freed elsewhere are also ignored.
1890 *
1891 * page: page to consider
1892 * mode: one of the LRU isolation modes defined above
1893 *
Alex Shic2135f72021-02-24 12:08:01 -08001894 * returns true on success, false on failure.
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001895 */
Alex Shic2135f72021-02-24 12:08:01 -08001896bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001897{
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001898 /* Only take pages on the LRU. */
1899 if (!PageLRU(page))
Alex Shic2135f72021-02-24 12:08:01 -08001900 return false;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001901
Minchan Kime46a2872012-10-08 16:33:48 -07001902 /* Compaction should not handle unevictable pages but CMA can do so */
1903 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
Alex Shic2135f72021-02-24 12:08:01 -08001904 return false;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001905
Mel Gormanc8244932012-01-12 17:19:38 -08001906 /*
1907 * To minimise LRU disruption, the caller can indicate that it only
1908 * wants to isolate pages it will be able to operate on without
1909 * blocking - clean pages for the most part.
1910 *
Mel Gormanc8244932012-01-12 17:19:38 -08001911 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1912 * that it is possible to migrate without blocking
1913 */
Johannes Weiner1276ad62017-02-24 14:56:11 -08001914 if (mode & ISOLATE_ASYNC_MIGRATE) {
Mel Gormanc8244932012-01-12 17:19:38 -08001915 /* All the caller can do on PageWriteback is block */
1916 if (PageWriteback(page))
Alex Shic2135f72021-02-24 12:08:01 -08001917 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001918
1919 if (PageDirty(page)) {
1920 struct address_space *mapping;
Mel Gorman69d763f2018-01-31 16:19:52 -08001921 bool migrate_dirty;
Mel Gormanc8244932012-01-12 17:19:38 -08001922
Mel Gormanc8244932012-01-12 17:19:38 -08001923 /*
1924 * Only pages without mappings or that have a
1925 * ->migratepage callback are possible to migrate
Mel Gorman69d763f2018-01-31 16:19:52 -08001926 * without blocking. However, we can be racing with
1927 * truncation so it's necessary to lock the page
1928 * to stabilise the mapping as truncation holds
1929 * the page lock until after the page is removed
1930 * from the page cache.
Mel Gormanc8244932012-01-12 17:19:38 -08001931 */
Mel Gorman69d763f2018-01-31 16:19:52 -08001932 if (!trylock_page(page))
Alex Shic2135f72021-02-24 12:08:01 -08001933 return false;
Mel Gorman69d763f2018-01-31 16:19:52 -08001934
Mel Gormanc8244932012-01-12 17:19:38 -08001935 mapping = page_mapping(page);
Hugh Dickins145e1a72018-06-01 16:50:50 -07001936 migrate_dirty = !mapping || mapping->a_ops->migratepage;
Mel Gorman69d763f2018-01-31 16:19:52 -08001937 unlock_page(page);
1938 if (!migrate_dirty)
Alex Shic2135f72021-02-24 12:08:01 -08001939 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001940 }
1941 }
Minchan Kim39deaf82011-10-31 17:06:51 -07001942
Minchan Kimf80c0672011-10-31 17:06:55 -07001943 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
Alex Shic2135f72021-02-24 12:08:01 -08001944 return false;
Minchan Kimf80c0672011-10-31 17:06:55 -07001945
Alex Shic2135f72021-02-24 12:08:01 -08001946 return true;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001947}
1948
Mel Gorman7ee36a12016-07-28 15:47:17 -07001949/*
1950 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001951 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001952 */
1953static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001954 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001955{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001956 int zid;
1957
Mel Gorman7ee36a12016-07-28 15:47:17 -07001958 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1959 if (!nr_zone_taken[zid])
1960 continue;
1961
Wei Yanga892cb62020-06-03 16:01:12 -07001962 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001963 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001964
Mel Gorman7ee36a12016-07-28 15:47:17 -07001965}
1966
Mel Gormanf611fab2021-06-30 18:53:19 -07001967/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001968 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1969 *
1970 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001971 * shrink the lists perform better by taking out a batch of pages
1972 * and working on them outside the LRU lock.
1973 *
1974 * For pagecache intensive workloads, this function is the hottest
1975 * spot in the kernel (apart from copy_*_user functions).
1976 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001977 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001978 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001979 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001980 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001981 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001982 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001983 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001984 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001985 *
1986 * returns how many pages were moved onto *@dst.
1987 */
Andrew Morton69e05942006-03-22 00:08:19 -08001988static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001989 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001990 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001991 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001992{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001993 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001994 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001995 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001996 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07001997 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001998 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07001999 LIST_HEAD(pages_skipped);
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002000 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002001
Yang Shi98879b32019-07-11 20:59:30 -07002002 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002003 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07002004 while (scan < nr_to_scan && !list_empty(src)) {
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002005 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002006
Linus Torvalds1da177e2005-04-16 15:20:36 -07002007 page = lru_to_page(src);
2008 prefetchw_prev_lru_page(page, src, flags);
2009
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002010 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002011 total_scan += nr_pages;
2012
Mel Gormanb2e18752016-07-28 15:45:37 -07002013 if (page_zonenum(page) > sc->reclaim_idx) {
2014 list_move(&page->lru, &pages_skipped);
Yang Shi98879b32019-07-11 20:59:30 -07002015 nr_skipped[page_zonenum(page)] += nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002016 continue;
2017 }
2018
Minchan Kim791b48b2017-05-12 15:47:06 -07002019 /*
2020 * Do not count skipped pages because that makes the function
2021 * return with no isolated pages if the LRU mostly contains
2022 * ineligible pages. This causes the VM to not reclaim any
2023 * pages, triggering a premature OOM.
Yang Shi98879b32019-07-11 20:59:30 -07002024 *
2025 * Account all tail pages of THP. This would not cause
2026 * premature OOM since __isolate_lru_page() returns -EBUSY
2027 * only when the page is being freed somewhere else.
Minchan Kim791b48b2017-05-12 15:47:06 -07002028 */
Yang Shi98879b32019-07-11 20:59:30 -07002029 scan += nr_pages;
Alex Shic2135f72021-02-24 12:08:01 -08002030 if (!__isolate_lru_page_prepare(page, mode)) {
2031 /* It is being freed elsewhere */
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002032 list_move(&page->lru, src);
Alex Shic2135f72021-02-24 12:08:01 -08002033 continue;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002034 }
Alex Shic2135f72021-02-24 12:08:01 -08002035 /*
2036 * Be careful not to clear PageLRU until after we're
2037 * sure the page is not being freed elsewhere -- the
2038 * page release code relies on it.
2039 */
2040 if (unlikely(!get_page_unless_zero(page))) {
2041 list_move(&page->lru, src);
2042 continue;
2043 }
2044
2045 if (!TestClearPageLRU(page)) {
2046 /* Another thread is already isolating this page */
2047 put_page(page);
2048 list_move(&page->lru, src);
2049 continue;
2050 }
2051
2052 nr_taken += nr_pages;
2053 nr_zone_taken[page_zonenum(page)] += nr_pages;
2054 list_move(&page->lru, dst);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002055 }
2056
Mel Gormanb2e18752016-07-28 15:45:37 -07002057 /*
2058 * Splice any skipped pages to the start of the LRU list. Note that
2059 * this disrupts the LRU order when reclaiming for lower zones but
2060 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2061 * scanning would soon rescan the same pages to skip and put the
2062 * system at risk of premature OOM.
2063 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002064 if (!list_empty(&pages_skipped)) {
2065 int zid;
2066
Johannes Weiner3db65812017-05-03 14:52:13 -07002067 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002068 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2069 if (!nr_skipped[zid])
2070 continue;
2071
2072 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002073 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002074 }
2075 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002076 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002077 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Minchan Kim791b48b2017-05-12 15:47:06 -07002078 total_scan, skipped, nr_taken, mode, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002079 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002080 return nr_taken;
2081}
2082
Nick Piggin62695a82008-10-18 20:26:09 -07002083/**
2084 * isolate_lru_page - tries to isolate a page from its LRU list
2085 * @page: page to isolate from its LRU list
2086 *
2087 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2088 * vmstat statistic corresponding to whatever LRU list the page was on.
2089 *
2090 * Returns 0 if the page was removed from an LRU list.
2091 * Returns -EBUSY if the page was not on an LRU list.
2092 *
2093 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002094 * the active list, it will have PageActive set. If it was found on
2095 * the unevictable list, it will have the PageUnevictable bit set. That flag
2096 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002097 *
2098 * The vmstat statistic corresponding to the list on which the page was
2099 * found will be decremented.
2100 *
2101 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002102 *
Nick Piggin62695a82008-10-18 20:26:09 -07002103 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002104 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002105 * without a stable reference).
2106 * (2) the lru_lock must not be held.
2107 * (3) interrupts must be enabled.
2108 */
2109int isolate_lru_page(struct page *page)
2110{
2111 int ret = -EBUSY;
2112
Sasha Levin309381fea2014-01-23 15:52:54 -08002113 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002114 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002115
Alex Shid25b5bd2020-12-15 12:34:16 -08002116 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002117 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002118
Alex Shid25b5bd2020-12-15 12:34:16 -08002119 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002120 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002121 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002122 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002123 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002124 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002125
Nick Piggin62695a82008-10-18 20:26:09 -07002126 return ret;
2127}
2128
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002129/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002130 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002131 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002132 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2133 * the LRU list will go small and be scanned faster than necessary, leading to
2134 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002135 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002136static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002137 struct scan_control *sc)
2138{
2139 unsigned long inactive, isolated;
2140
2141 if (current_is_kswapd())
2142 return 0;
2143
Johannes Weinerb5ead352019-11-30 17:55:40 -08002144 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002145 return 0;
2146
2147 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002148 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2149 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002150 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002151 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2152 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002153 }
2154
Fengguang Wu3cf23842012-12-18 14:23:31 -08002155 /*
2156 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2157 * won't get blocked by normal direct-reclaimers, forming a circular
2158 * deadlock.
2159 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002160 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002161 inactive >>= 3;
2162
Rik van Riel35cd7812009-09-21 17:01:38 -07002163 return isolated > inactive;
2164}
2165
Kirill Tkhaia222f342019-05-13 17:17:00 -07002166/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002167 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2168 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002169 *
2170 * Returns the number of pages moved to the given lruvec.
2171 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002172static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2173 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002174{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002175 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002176 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002177 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002178
Kirill Tkhaia222f342019-05-13 17:17:00 -07002179 while (!list_empty(list)) {
2180 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002181 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002182 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002183 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002184 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002185 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002186 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002187 continue;
2188 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002189
Alex Shi3d06afa2020-12-15 12:33:37 -08002190 /*
2191 * The SetPageLRU needs to be kept here for list integrity.
2192 * Otherwise:
2193 * #0 move_pages_to_lru #1 release_pages
2194 * if !put_page_testzero
2195 * if (put_page_testzero())
2196 * !PageLRU //skip lru_lock
2197 * SetPageLRU()
2198 * list_add(&page->lru,)
2199 * list_add(&page->lru,)
2200 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002201 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002202
Alex Shi3d06afa2020-12-15 12:33:37 -08002203 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002204 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002205
2206 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002207 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002208 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002209 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002210 } else
2211 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002212
2213 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002214 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002215
Alex Shiafca9152020-12-15 12:34:02 -08002216 /*
2217 * All pages were isolated from the same lruvec (and isolation
2218 * inhibits memcg migration).
2219 */
Muchun Song7467c392021-06-28 19:37:59 -07002220 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002221 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002222 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002223 nr_moved += nr_pages;
2224 if (PageActive(page))
2225 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002226 }
Mel Gorman66635622010-08-09 17:19:30 -07002227
Hugh Dickins3f797682012-01-12 17:20:07 -08002228 /*
2229 * To save our caller's stack, now use input list for pages to free.
2230 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002231 list_splice(&pages_to_free, list);
2232
2233 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002234}
2235
2236/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002237 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002238 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002239 * In that case we should only throttle if the backing device it is
2240 * writing to is congested. In other cases it is safe to throttle.
2241 */
2242static int current_may_throttle(void)
2243{
NeilBrowna37b0712020-06-01 21:48:18 -07002244 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002245 current->backing_dev_info == NULL ||
2246 bdi_write_congested(current->backing_dev_info);
2247}
2248
2249/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002250 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002251 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002252 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002253static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002254shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002255 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002256{
2257 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002258 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002259 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002260 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002261 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002262 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002263 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002264 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002265 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002266
Mel Gorman599d0c92016-07-28 15:45:31 -07002267 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002268 if (stalled)
2269 return 0;
2270
2271 /* wait a bit for the reclaimer. */
2272 msleep(100);
2273 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002274
2275 /* We are about to die and free our memory. Return now. */
2276 if (fatal_signal_pending(current))
2277 return SWAP_CLUSTER_MAX;
2278 }
2279
Linus Torvalds1da177e2005-04-16 15:20:36 -07002280 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002281
Alex Shi6168d0d2020-12-15 12:34:29 -08002282 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002283
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002284 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002285 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002286
Mel Gorman599d0c92016-07-28 15:45:31 -07002287 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002288 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002289 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002290 __count_vm_events(item, nr_scanned);
2291 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002292 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2293
Alex Shi6168d0d2020-12-15 12:34:29 -08002294 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002295
Hillf Dantond563c052012-03-21 16:34:02 -07002296 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002297 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002298
Shakeel Butt013339d2020-12-14 19:06:39 -08002299 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002300
Alex Shi6168d0d2020-12-15 12:34:29 -08002301 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002302 move_pages_to_lru(lruvec, &page_list);
2303
2304 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002305 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002306 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002307 __count_vm_events(item, nr_reclaimed);
2308 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002309 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002310 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002311
Alex Shi75cc3c92020-12-15 14:20:50 -08002312 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002313 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002314 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002315
Mel Gorman92df3a72011-10-31 17:07:56 -07002316 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002317 * If dirty pages are scanned that are not queued for IO, it
2318 * implies that flushers are not doing their job. This can
2319 * happen when memory pressure pushes dirty pages to the end of
2320 * the LRU before the dirty limits are breached and the dirty
2321 * data has expired. It can also happen when the proportion of
2322 * dirty pages grows not through writes but through memory
2323 * pressure reclaiming all the clean cache. And in some cases,
2324 * the flushers simply cannot keep up with the allocation
2325 * rate. Nudge the flusher threads in case they are asleep.
2326 */
2327 if (stat.nr_unqueued_dirty == nr_taken)
2328 wakeup_flusher_threads(WB_REASON_VMSCAN);
2329
Andrey Ryabinind108c772018-04-10 16:27:59 -07002330 sc->nr.dirty += stat.nr_dirty;
2331 sc->nr.congested += stat.nr_congested;
2332 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2333 sc->nr.writeback += stat.nr_writeback;
2334 sc->nr.immediate += stat.nr_immediate;
2335 sc->nr.taken += nr_taken;
2336 if (file)
2337 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002338
Mel Gorman599d0c92016-07-28 15:45:31 -07002339 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002340 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002341 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002342}
2343
Hugh Dickins15b44732020-12-15 14:21:31 -08002344/*
2345 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2346 *
2347 * We move them the other way if the page is referenced by one or more
2348 * processes.
2349 *
2350 * If the pages are mostly unmapped, the processing is fast and it is
2351 * appropriate to hold lru_lock across the whole operation. But if
2352 * the pages are mapped, the processing is slow (page_referenced()), so
2353 * we should drop lru_lock around each page. It's impossible to balance
2354 * this, so instead we remove the pages from the LRU while processing them.
2355 * It is safe to rely on PG_active against the non-LRU pages in here because
2356 * nobody will play with that bit on a non-LRU page.
2357 *
2358 * The downside is that we have to touch page->_refcount against each page.
2359 * But we had to alter page->flags anyway.
2360 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002361static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002362 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002363 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002364 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002365{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002366 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002367 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002368 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002369 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002370 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002371 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002372 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002373 unsigned nr_deactivate, nr_activate;
2374 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002375 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002376 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002377 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002378
2379 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002380
Alex Shi6168d0d2020-12-15 12:34:29 -08002381 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002382
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002383 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002384 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002385
Mel Gorman599d0c92016-07-28 15:45:31 -07002386 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002387
Shakeel Butt912c0572020-08-06 23:26:32 -07002388 if (!cgroup_reclaim(sc))
2389 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002390 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002391
Alex Shi6168d0d2020-12-15 12:34:29 -08002392 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002393
Linus Torvalds1da177e2005-04-16 15:20:36 -07002394 while (!list_empty(&l_hold)) {
2395 cond_resched();
2396 page = lru_to_page(&l_hold);
2397 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002398
Hugh Dickins39b5f292012-10-08 16:33:18 -07002399 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002400 putback_lru_page(page);
2401 continue;
2402 }
2403
Mel Gormancc715d92012-03-21 16:34:00 -07002404 if (unlikely(buffer_heads_over_limit)) {
2405 if (page_has_private(page) && trylock_page(page)) {
2406 if (page_has_private(page))
2407 try_to_release_page(page, 0);
2408 unlock_page(page);
2409 }
2410 }
2411
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002412 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2413 if (bypass)
2414 goto skip_page_referenced;
2415
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002416 if (page_referenced(page, 0, sc->target_mem_cgroup,
2417 &vm_flags)) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002418 /*
2419 * Identify referenced, file-backed active pages and
2420 * give them one more trip around the active list. So
2421 * that executable code get better chances to stay in
2422 * memory under moderate memory pressure. Anon pages
2423 * are not likely to be evicted by use-once streaming
2424 * IO, plus JVM can create lots of anon VM_EXEC pages,
2425 * so we ignore them here.
2426 */
Huang Ying9de4f222020-04-06 20:04:41 -07002427 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002428 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002429 list_add(&page->lru, &l_active);
2430 continue;
2431 }
2432 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002433skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002434 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002435 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002436 list_add(&page->lru, &l_inactive);
2437 }
2438
Andrew Mortonb5557492009-01-06 14:40:13 -08002439 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002440 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002441 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002442 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002443
Kirill Tkhaia222f342019-05-13 17:17:00 -07002444 nr_activate = move_pages_to_lru(lruvec, &l_active);
2445 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002446 /* Keep all free pages in l_active list */
2447 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002448
2449 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2450 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2451
Mel Gorman599d0c92016-07-28 15:45:31 -07002452 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002453 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002454
Kirill Tkhaif372d892019-05-13 17:16:57 -07002455 mem_cgroup_uncharge_list(&l_active);
2456 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002457 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2458 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002459}
2460
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002461unsigned long reclaim_pages(struct list_head *page_list)
2462{
Yang Shif661d002020-04-01 21:10:05 -07002463 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002464 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002465 LIST_HEAD(node_page_list);
2466 struct reclaim_stat dummy_stat;
2467 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002468 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002469 struct scan_control sc = {
2470 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002471 .may_writepage = 1,
2472 .may_unmap = 1,
2473 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002474 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002475 };
2476
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002477 noreclaim_flag = memalloc_noreclaim_save();
2478
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002479 while (!list_empty(page_list)) {
2480 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002481 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002482 nid = page_to_nid(page);
2483 INIT_LIST_HEAD(&node_page_list);
2484 }
2485
2486 if (nid == page_to_nid(page)) {
2487 ClearPageActive(page);
2488 list_move(&page->lru, &node_page_list);
2489 continue;
2490 }
2491
2492 nr_reclaimed += shrink_page_list(&node_page_list,
2493 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002494 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002495 while (!list_empty(&node_page_list)) {
2496 page = lru_to_page(&node_page_list);
2497 list_del(&page->lru);
2498 putback_lru_page(page);
2499 }
2500
Yang Shif661d002020-04-01 21:10:05 -07002501 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002502 }
2503
2504 if (!list_empty(&node_page_list)) {
2505 nr_reclaimed += shrink_page_list(&node_page_list,
2506 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002507 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002508 while (!list_empty(&node_page_list)) {
2509 page = lru_to_page(&node_page_list);
2510 list_del(&page->lru);
2511 putback_lru_page(page);
2512 }
2513 }
2514
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002515 memalloc_noreclaim_restore(noreclaim_flag);
2516
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002517 return nr_reclaimed;
2518}
2519
Johannes Weinerb91ac372019-11-30 17:56:02 -08002520static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2521 struct lruvec *lruvec, struct scan_control *sc)
2522{
2523 if (is_active_lru(lru)) {
2524 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2525 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2526 else
2527 sc->skipped_deactivate = 1;
2528 return 0;
2529 }
2530
2531 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2532}
2533
Rik van Riel59dc76b2016-05-20 16:56:31 -07002534/*
2535 * The inactive anon list should be small enough that the VM never has
2536 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002537 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002538 * The inactive file list should be small enough to leave most memory
2539 * to the established workingset on the scan-resistant active list,
2540 * but large enough to avoid thrashing the aggregate readahead window.
2541 *
2542 * Both inactive lists should also be large enough that each inactive
2543 * page has a chance to be referenced again before it is reclaimed.
2544 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002545 * If that fails and refaulting is observed, the inactive list grows.
2546 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002547 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002548 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002549 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2550 *
2551 * total target max
2552 * memory ratio inactive
2553 * -------------------------------------
2554 * 10MB 1 5MB
2555 * 100MB 1 50MB
2556 * 1GB 3 250MB
2557 * 10GB 10 0.9GB
2558 * 100GB 31 3GB
2559 * 1TB 101 10GB
2560 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002561 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002562static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002563{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002564 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002565 unsigned long inactive, active;
2566 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002567 unsigned long gb;
2568
Johannes Weinerb91ac372019-11-30 17:56:02 -08002569 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2570 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002571
Johannes Weinerb91ac372019-11-30 17:56:02 -08002572 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002573 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002574 inactive_ratio = int_sqrt(10 * gb);
2575 else
2576 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002577
Rik van Riel59dc76b2016-05-20 16:56:31 -07002578 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002579}
2580
Johannes Weiner9a265112013-02-22 16:32:17 -08002581enum scan_balance {
2582 SCAN_EQUAL,
2583 SCAN_FRACT,
2584 SCAN_ANON,
2585 SCAN_FILE,
2586};
2587
Yu Zhao6d313442022-09-18 02:00:00 -06002588static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2589{
2590 unsigned long file;
2591 struct lruvec *target_lruvec;
2592
Yu Zhao37397872022-09-18 02:00:03 -06002593 if (lru_gen_enabled())
2594 return;
2595
Yu Zhao6d313442022-09-18 02:00:00 -06002596 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2597
2598 /*
2599 * Flush the memory cgroup stats, so that we read accurate per-memcg
2600 * lruvec stats for heuristics.
2601 */
2602 mem_cgroup_flush_stats();
2603
2604 /*
2605 * Determine the scan balance between anon and file LRUs.
2606 */
2607 spin_lock_irq(&target_lruvec->lru_lock);
2608 sc->anon_cost = target_lruvec->anon_cost;
2609 sc->file_cost = target_lruvec->file_cost;
2610 spin_unlock_irq(&target_lruvec->lru_lock);
2611
2612 /*
2613 * Target desirable inactive:active list ratios for the anon
2614 * and file LRU lists.
2615 */
2616 if (!sc->force_deactivate) {
2617 unsigned long refaults;
2618
2619 refaults = lruvec_page_state(target_lruvec,
2620 WORKINGSET_ACTIVATE_ANON);
2621 if (refaults != target_lruvec->refaults[0] ||
2622 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2623 sc->may_deactivate |= DEACTIVATE_ANON;
2624 else
2625 sc->may_deactivate &= ~DEACTIVATE_ANON;
2626
2627 /*
2628 * When refaults are being observed, it means a new
2629 * workingset is being established. Deactivate to get
2630 * rid of any stale active pages quickly.
2631 */
2632 refaults = lruvec_page_state(target_lruvec,
2633 WORKINGSET_ACTIVATE_FILE);
2634 if (refaults != target_lruvec->refaults[1] ||
2635 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2636 sc->may_deactivate |= DEACTIVATE_FILE;
2637 else
2638 sc->may_deactivate &= ~DEACTIVATE_FILE;
2639 } else
2640 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2641
2642 /*
2643 * If we have plenty of inactive file pages that aren't
2644 * thrashing, try to reclaim those first before touching
2645 * anonymous pages.
2646 */
2647 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2648 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2649 sc->cache_trim_mode = 1;
2650 else
2651 sc->cache_trim_mode = 0;
2652
2653 /*
2654 * Prevent the reclaimer from falling into the cache trap: as
2655 * cache pages start out inactive, every cache fault will tip
2656 * the scan balance towards the file LRU. And as the file LRU
2657 * shrinks, so does the window for rotation from references.
2658 * This means we have a runaway feedback loop where a tiny
2659 * thrashing file LRU becomes infinitely more attractive than
2660 * anon pages. Try to detect this based on file LRU size.
2661 */
2662 if (!cgroup_reclaim(sc)) {
2663 unsigned long total_high_wmark = 0;
2664 unsigned long free, anon;
2665 int z;
2666
2667 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2668 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2669 node_page_state(pgdat, NR_INACTIVE_FILE);
2670
2671 for (z = 0; z < MAX_NR_ZONES; z++) {
2672 struct zone *zone = &pgdat->node_zones[z];
2673
2674 if (!managed_zone(zone))
2675 continue;
2676
2677 total_high_wmark += high_wmark_pages(zone);
2678 }
2679
2680 /*
2681 * Consider anon: if that's low too, this isn't a
2682 * runaway file reclaim problem, but rather just
2683 * extreme pressure. Reclaim as per usual then.
2684 */
2685 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2686
2687 sc->file_is_tiny =
2688 file + free <= total_high_wmark &&
2689 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2690 anon >> sc->priority;
2691 }
2692}
2693
Linus Torvalds1da177e2005-04-16 15:20:36 -07002694/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002695 * Determine how aggressively the anon and file LRU lists should be
2696 * scanned. The relative value of each set of LRU lists is determined
2697 * by looking at the fraction of the pages scanned we did rotate back
2698 * onto the active list instead of evict.
2699 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002700 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2701 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002702 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002703static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2704 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002705{
Keith Buscha2a36482021-09-02 14:59:26 -07002706 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002707 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002708 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002709 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002710 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002711 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002712 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002713 unsigned long ap, fp;
2714 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002715 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002716
2717 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002718 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002719 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002720 goto out;
2721 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002722
Johannes Weiner10316b32013-02-22 16:32:14 -08002723 /*
2724 * Global reclaim will swap to prevent OOM even with no
2725 * swappiness, but memcg users want to use this knob to
2726 * disable swapping for individual groups completely when
2727 * using the memory controller's swap limit feature would be
2728 * too expensive.
2729 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002730 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002731 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002732 goto out;
2733 }
2734
2735 /*
2736 * Do not apply any pressure balancing cleverness when the
2737 * system is close to OOM, scan both anon and file equally
2738 * (unless the swappiness setting disagrees with swapping).
2739 */
Johannes Weiner02695172014-08-06 16:06:17 -07002740 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002741 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002742 goto out;
2743 }
2744
Johannes Weiner11d16c22013-02-22 16:32:15 -08002745 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002746 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002747 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002748 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002749 scan_balance = SCAN_ANON;
2750 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002751 }
2752
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002753 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2754
Johannes Weiner62376252014-05-06 12:50:07 -07002755 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002756 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002757 * anything from the anonymous working right now. But when balancing
2758 * anon and page cache files for reclaim, allow swapping of anon pages
2759 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002760 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002761 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002762 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002763 goto out;
2764 }
2765
Johannes Weiner9a265112013-02-22 16:32:17 -08002766 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002767 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002768 * Calculate the pressure balance between anon and file pages.
2769 *
2770 * The amount of pressure we put on each LRU is inversely
2771 * proportional to the cost of reclaiming each list, as
2772 * determined by the share of pages that are refaulting, times
2773 * the relative IO cost of bringing back a swapped out
2774 * anonymous page vs reloading a filesystem page (swappiness).
2775 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002776 * Although we limit that influence to ensure no list gets
2777 * left behind completely: at least a third of the pressure is
2778 * applied, before swappiness.
2779 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002780 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002781 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002782 total_cost = sc->anon_cost + sc->file_cost;
2783 anon_cost = total_cost + sc->anon_cost;
2784 file_cost = total_cost + sc->file_cost;
2785 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002786
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002787 ap = swappiness * (total_cost + 1);
2788 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002789
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002790 fp = (200 - swappiness) * (total_cost + 1);
2791 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002792
Shaohua Li76a33fc2010-05-24 14:32:36 -07002793 fraction[0] = ap;
2794 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002795 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002796out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002797 for_each_evictable_lru(lru) {
2798 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002799 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002800 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002801 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002802
Chris Down9783aa92019-10-06 17:58:32 -07002803 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002804 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2805 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002806
Johannes Weinerf56ce412021-08-19 19:04:21 -07002807 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002808 /*
2809 * Scale a cgroup's reclaim pressure by proportioning
2810 * its current usage to its memory.low or memory.min
2811 * setting.
2812 *
2813 * This is important, as otherwise scanning aggression
2814 * becomes extremely binary -- from nothing as we
2815 * approach the memory protection threshold, to totally
2816 * nominal as we exceed it. This results in requiring
2817 * setting extremely liberal protection thresholds. It
2818 * also means we simply get no protection at all if we
2819 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002820 *
2821 * If there is any protection in place, we reduce scan
2822 * pressure by how much of the total memory used is
2823 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002824 *
Chris Down9de7ca42019-10-06 17:58:35 -07002825 * There is one special case: in the first reclaim pass,
2826 * we skip over all groups that are within their low
2827 * protection. If that fails to reclaim enough pages to
2828 * satisfy the reclaim goal, we come back and override
2829 * the best-effort low protection. However, we still
2830 * ideally want to honor how well-behaved groups are in
2831 * that case instead of simply punishing them all
2832 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002833 * memory they are using, reducing the scan pressure
2834 * again by how much of the total memory used is under
2835 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002836 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002837 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002838 unsigned long protection;
2839
2840 /* memory.low scaling, make sure we retry before OOM */
2841 if (!sc->memcg_low_reclaim && low > min) {
2842 protection = low;
2843 sc->memcg_low_skipped = 1;
2844 } else {
2845 protection = min;
2846 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002847
2848 /* Avoid TOCTOU with earlier protection check */
2849 cgroup_size = max(cgroup_size, protection);
2850
2851 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002852 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002853
2854 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002855 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002856 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002857 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002858 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002859 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002860 } else {
2861 scan = lruvec_size;
2862 }
2863
2864 scan >>= sc->priority;
2865
Johannes Weiner688035f2017-05-03 14:52:07 -07002866 /*
2867 * If the cgroup's already been deleted, make sure to
2868 * scrape out the remaining cache.
2869 */
2870 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002871 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002872
Johannes Weiner688035f2017-05-03 14:52:07 -07002873 switch (scan_balance) {
2874 case SCAN_EQUAL:
2875 /* Scan lists relative to size */
2876 break;
2877 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002878 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002879 * Scan types proportional to swappiness and
2880 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002881 * Make sure we don't miss the last page on
2882 * the offlined memory cgroups because of a
2883 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002884 */
Gavin Shan76073c62020-02-20 20:04:24 -08002885 scan = mem_cgroup_online(memcg) ?
2886 div64_u64(scan * fraction[file], denominator) :
2887 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002888 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002889 break;
2890 case SCAN_FILE:
2891 case SCAN_ANON:
2892 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002893 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002894 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002895 break;
2896 default:
2897 /* Look ma, no brain */
2898 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002899 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002900
Johannes Weiner688035f2017-05-03 14:52:07 -07002901 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002902 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002903}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002904
Dave Hansen2f368a92021-09-02 14:59:23 -07002905/*
2906 * Anonymous LRU management is a waste if there is
2907 * ultimately no way to reclaim the memory.
2908 */
2909static bool can_age_anon_pages(struct pglist_data *pgdat,
2910 struct scan_control *sc)
2911{
2912 /* Aging the anon LRU is valuable if swap is present: */
2913 if (total_swap_pages > 0)
2914 return true;
2915
2916 /* Also valuable if anon pages can be demoted: */
2917 return can_demote(pgdat->node_id, sc);
2918}
2919
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002920#ifdef CONFIG_LRU_GEN
2921
2922/******************************************************************************
2923 * shorthand helpers
2924 ******************************************************************************/
2925
Yu Zhao37397872022-09-18 02:00:03 -06002926#define LRU_REFS_FLAGS (BIT(PG_referenced) | BIT(PG_workingset))
2927
2928#define DEFINE_MAX_SEQ(lruvec) \
2929 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2930
2931#define DEFINE_MIN_SEQ(lruvec) \
2932 unsigned long min_seq[ANON_AND_FILE] = { \
2933 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2934 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2935 }
2936
Yu Zhaod5b2fa12022-09-18 02:00:02 -06002937#define for_each_gen_type_zone(gen, type, zone) \
2938 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2939 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2940 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2941
2942static struct lruvec __maybe_unused *get_lruvec(struct mem_cgroup *memcg, int nid)
2943{
2944 struct pglist_data *pgdat = NODE_DATA(nid);
2945
2946#ifdef CONFIG_MEMCG
2947 if (memcg) {
2948 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2949
2950 /* for hotadd_new_pgdat() */
2951 if (!lruvec->pgdat)
2952 lruvec->pgdat = pgdat;
2953
2954 return lruvec;
2955 }
2956#endif
2957 VM_WARN_ON_ONCE(!mem_cgroup_disabled());
2958
2959 return pgdat ? &pgdat->__lruvec : NULL;
2960}
2961
Yu Zhao37397872022-09-18 02:00:03 -06002962static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2963{
2964 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2965 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2966
2967 if (!can_demote(pgdat->node_id, sc) &&
2968 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2969 return 0;
2970
2971 return mem_cgroup_swappiness(memcg);
2972}
2973
2974static int get_nr_gens(struct lruvec *lruvec, int type)
2975{
2976 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2977}
2978
2979static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2980{
2981 /* see the comment on lru_gen_struct */
2982 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2983 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2984 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2985}
2986
2987/******************************************************************************
2988 * refault feedback loop
2989 ******************************************************************************/
2990
2991/*
2992 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
2993 *
2994 * The P term is refaulted/(evicted+protected) from a tier in the generation
2995 * currently being evicted; the I term is the exponential moving average of the
2996 * P term over the generations previously evicted, using the smoothing factor
2997 * 1/2; the D term isn't supported.
2998 *
2999 * The setpoint (SP) is always the first tier of one type; the process variable
3000 * (PV) is either any tier of the other type or any other tier of the same
3001 * type.
3002 *
3003 * The error is the difference between the SP and the PV; the correction is to
3004 * turn off protection when SP>PV or turn on protection when SP<PV.
3005 *
3006 * For future optimizations:
3007 * 1. The D term may discount the other two terms over time so that long-lived
3008 * generations can resist stale information.
3009 */
3010struct ctrl_pos {
3011 unsigned long refaulted;
3012 unsigned long total;
3013 int gain;
3014};
3015
3016static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3017 struct ctrl_pos *pos)
3018{
3019 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3020 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3021
3022 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3023 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3024 pos->total = lrugen->avg_total[type][tier] +
3025 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3026 if (tier)
3027 pos->total += lrugen->protected[hist][type][tier - 1];
3028 pos->gain = gain;
3029}
3030
3031static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3032{
3033 int hist, tier;
3034 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3035 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3036 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3037
3038 lockdep_assert_held(&lruvec->lru_lock);
3039
3040 if (!carryover && !clear)
3041 return;
3042
3043 hist = lru_hist_from_seq(seq);
3044
3045 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3046 if (carryover) {
3047 unsigned long sum;
3048
3049 sum = lrugen->avg_refaulted[type][tier] +
3050 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3051 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3052
3053 sum = lrugen->avg_total[type][tier] +
3054 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3055 if (tier)
3056 sum += lrugen->protected[hist][type][tier - 1];
3057 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3058 }
3059
3060 if (clear) {
3061 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3062 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3063 if (tier)
3064 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3065 }
3066 }
3067}
3068
3069static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3070{
3071 /*
3072 * Return true if the PV has a limited number of refaults or a lower
3073 * refaulted/total than the SP.
3074 */
3075 return pv->refaulted < MIN_LRU_BATCH ||
3076 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3077 (sp->refaulted + 1) * pv->total * pv->gain;
3078}
3079
3080/******************************************************************************
3081 * the aging
3082 ******************************************************************************/
3083
Yu Zhao0182f922022-09-18 02:00:04 -06003084/* promote pages accessed through page tables */
3085static int page_update_gen(struct page *page, int gen)
3086{
3087 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3088
3089 VM_WARN_ON_ONCE(gen >= MAX_NR_GENS);
3090 VM_WARN_ON_ONCE(!rcu_read_lock_held());
3091
3092 do {
3093 /* lru_gen_del_page() has isolated this page? */
3094 if (!(old_flags & LRU_GEN_MASK)) {
3095 /* for shrink_page_list() */
3096 new_flags = old_flags | BIT(PG_referenced);
3097 continue;
3098 }
3099
3100 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3101 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3102 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3103
3104 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3105}
3106
Yu Zhao37397872022-09-18 02:00:03 -06003107/* protect pages accessed multiple times through file descriptors */
3108static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3109{
3110 int type = page_is_file_lru(page);
3111 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3112 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3113 unsigned long new_flags, old_flags = READ_ONCE(page->flags);
3114
3115 VM_WARN_ON_ONCE_PAGE(!(old_flags & LRU_GEN_MASK), page);
3116
3117 do {
Yu Zhao0182f922022-09-18 02:00:04 -06003118 new_gen = ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3119 /* page_update_gen() has promoted this page? */
3120 if (new_gen >= 0 && new_gen != old_gen)
3121 return new_gen;
3122
Yu Zhao37397872022-09-18 02:00:03 -06003123 new_gen = (old_gen + 1) % MAX_NR_GENS;
3124
3125 new_flags = old_flags & ~(LRU_GEN_MASK | LRU_REFS_MASK | LRU_REFS_FLAGS);
3126 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3127 /* for end_page_writeback() */
3128 if (reclaiming)
3129 new_flags |= BIT(PG_reclaim);
3130 } while (!try_cmpxchg(&page->flags, &old_flags, new_flags));
3131
3132 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3133
3134 return new_gen;
3135}
3136
Yu Zhao0182f922022-09-18 02:00:04 -06003137static unsigned long get_pte_pfn(pte_t pte, struct vm_area_struct *vma, unsigned long addr)
3138{
3139 unsigned long pfn = pte_pfn(pte);
3140
3141 VM_WARN_ON_ONCE(addr < vma->vm_start || addr >= vma->vm_end);
3142
3143 if (!pte_present(pte) || is_zero_pfn(pfn))
3144 return -1;
3145
3146 if (WARN_ON_ONCE(pte_devmap(pte) || pte_special(pte)))
3147 return -1;
3148
3149 if (WARN_ON_ONCE(!pfn_valid(pfn)))
3150 return -1;
3151
3152 return pfn;
3153}
3154
3155static struct page *get_pfn_page(unsigned long pfn, struct mem_cgroup *memcg,
3156 struct pglist_data *pgdat)
3157{
3158 struct page *page;
3159
3160 /* try to avoid unnecessary memory loads */
3161 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3162 return NULL;
3163
3164 page = compound_head(pfn_to_page(pfn));
3165 if (page_to_nid(page) != pgdat->node_id)
3166 return NULL;
3167
3168 if (page_memcg_rcu(page) != memcg)
3169 return NULL;
3170
3171 return page;
3172}
3173
Yu Zhao37397872022-09-18 02:00:03 -06003174static void inc_min_seq(struct lruvec *lruvec, int type)
3175{
3176 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3177
3178 reset_ctrl_pos(lruvec, type, true);
3179 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
3180}
3181
3182static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
3183{
3184 int gen, type, zone;
3185 bool success = false;
3186 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3187 DEFINE_MIN_SEQ(lruvec);
3188
3189 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
3190
3191 /* find the oldest populated generation */
3192 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3193 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
3194 gen = lru_gen_from_seq(min_seq[type]);
3195
3196 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3197 if (!list_empty(&lrugen->lists[gen][type][zone]))
3198 goto next;
3199 }
3200
3201 min_seq[type]++;
3202 }
3203next:
3204 ;
3205 }
3206
3207 /* see the comment on lru_gen_struct */
3208 if (can_swap) {
3209 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
3210 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
3211 }
3212
3213 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3214 if (min_seq[type] == lrugen->min_seq[type])
3215 continue;
3216
3217 reset_ctrl_pos(lruvec, type, true);
3218 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
3219 success = true;
3220 }
3221
3222 return success;
3223}
3224
3225static void inc_max_seq(struct lruvec *lruvec, unsigned long max_seq, bool can_swap)
3226{
3227 int prev, next;
3228 int type, zone;
3229 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3230
3231 spin_lock_irq(&lruvec->lru_lock);
3232
3233 VM_WARN_ON_ONCE(!seq_is_valid(lruvec));
3234
3235 if (max_seq != lrugen->max_seq)
3236 goto unlock;
3237
3238 for (type = ANON_AND_FILE - 1; type >= 0; type--) {
3239 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
3240 continue;
3241
3242 VM_WARN_ON_ONCE(type == LRU_GEN_FILE || can_swap);
3243
3244 inc_min_seq(lruvec, type);
3245 }
3246
3247 /*
3248 * Update the active/inactive LRU sizes for compatibility. Both sides of
3249 * the current max_seq need to be covered, since max_seq+1 can overlap
3250 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
3251 * overlap, cold/hot inversion happens.
3252 */
3253 prev = lru_gen_from_seq(lrugen->max_seq - 1);
3254 next = lru_gen_from_seq(lrugen->max_seq + 1);
3255
3256 for (type = 0; type < ANON_AND_FILE; type++) {
3257 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3258 enum lru_list lru = type * LRU_INACTIVE_FILE;
3259 long delta = lrugen->nr_pages[prev][type][zone] -
3260 lrugen->nr_pages[next][type][zone];
3261
3262 if (!delta)
3263 continue;
3264
3265 __update_lru_size(lruvec, lru, zone, delta);
3266 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
3267 }
3268 }
3269
3270 for (type = 0; type < ANON_AND_FILE; type++)
3271 reset_ctrl_pos(lruvec, type, false);
3272
3273 /* make sure preceding modifications appear */
3274 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
3275unlock:
3276 spin_unlock_irq(&lruvec->lru_lock);
3277}
3278
3279static bool should_run_aging(struct lruvec *lruvec, unsigned long max_seq, unsigned long *min_seq,
3280 struct scan_control *sc, bool can_swap, unsigned long *nr_to_scan)
3281{
3282 int gen, type, zone;
3283 unsigned long old = 0;
3284 unsigned long young = 0;
3285 unsigned long total = 0;
3286 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3287 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3288
3289 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3290 unsigned long seq;
3291
3292 for (seq = min_seq[type]; seq <= max_seq; seq++) {
3293 unsigned long size = 0;
3294
3295 gen = lru_gen_from_seq(seq);
3296
3297 for (zone = 0; zone < MAX_NR_ZONES; zone++)
3298 size += max(READ_ONCE(lrugen->nr_pages[gen][type][zone]), 0L);
3299
3300 total += size;
3301 if (seq == max_seq)
3302 young += size;
3303 else if (seq + MIN_NR_GENS == max_seq)
3304 old += size;
3305 }
3306 }
3307
3308 /* try to scrape all its memory if this memcg was deleted */
3309 *nr_to_scan = mem_cgroup_online(memcg) ? (total >> sc->priority) : total;
3310
3311 /*
3312 * The aging tries to be lazy to reduce the overhead, while the eviction
3313 * stalls when the number of generations reaches MIN_NR_GENS. Hence, the
3314 * ideal number of generations is MIN_NR_GENS+1.
3315 */
3316 if (min_seq[!can_swap] + MIN_NR_GENS > max_seq)
3317 return true;
3318 if (min_seq[!can_swap] + MIN_NR_GENS < max_seq)
3319 return false;
3320
3321 /*
3322 * It's also ideal to spread pages out evenly, i.e., 1/(MIN_NR_GENS+1)
3323 * of the total number of pages for each generation. A reasonable range
3324 * for this average portion is [1/MIN_NR_GENS, 1/(MIN_NR_GENS+2)]. The
3325 * aging cares about the upper bound of hot pages, while the eviction
3326 * cares about the lower bound of cold pages.
3327 */
3328 if (young * MIN_NR_GENS > total)
3329 return true;
3330 if (old * (MIN_NR_GENS + 2) < total)
3331 return true;
3332
3333 return false;
3334}
3335
3336static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3337{
3338 bool need_aging;
3339 unsigned long nr_to_scan;
3340 int swappiness = get_swappiness(lruvec, sc);
3341 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3342 DEFINE_MAX_SEQ(lruvec);
3343 DEFINE_MIN_SEQ(lruvec);
3344
3345 VM_WARN_ON_ONCE(sc->memcg_low_reclaim);
3346
3347 mem_cgroup_calculate_protection(NULL, memcg);
3348
3349 if (mem_cgroup_below_min(memcg))
3350 return;
3351
3352 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, swappiness, &nr_to_scan);
3353 if (need_aging)
3354 inc_max_seq(lruvec, max_seq, swappiness);
3355}
3356
3357static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
3358{
3359 struct mem_cgroup *memcg;
3360
3361 VM_WARN_ON_ONCE(!current_is_kswapd());
3362
3363 memcg = mem_cgroup_iter(NULL, NULL, NULL);
3364 do {
3365 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3366
3367 age_lruvec(lruvec, sc);
3368
3369 cond_resched();
3370 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
3371}
3372
Yu Zhao0182f922022-09-18 02:00:04 -06003373/*
3374 * This function exploits spatial locality when shrink_page_list() walks the
3375 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages.
3376 */
3377void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
3378{
3379 int i;
3380 pte_t *pte;
3381 unsigned long start;
3382 unsigned long end;
3383 unsigned long addr;
3384 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3385 struct page *page = pvmw->page;
3386 struct mem_cgroup *memcg = page_memcg(page);
3387 struct pglist_data *pgdat = page_pgdat(page);
3388 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3389 DEFINE_MAX_SEQ(lruvec);
3390 int old_gen, new_gen = lru_gen_from_seq(max_seq);
3391
3392 lockdep_assert_held(pvmw->ptl);
3393 VM_WARN_ON_ONCE_PAGE(PageLRU(page), page);
3394
3395 if (spin_is_contended(pvmw->ptl))
3396 return;
3397
3398 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
3399 end = min(pvmw->address | ~PMD_MASK, pvmw->vma->vm_end - 1) + 1;
3400
3401 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
3402 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
3403 end = start + MIN_LRU_BATCH * PAGE_SIZE;
3404 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
3405 start = end - MIN_LRU_BATCH * PAGE_SIZE;
3406 else {
3407 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
3408 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
3409 }
3410 }
3411
3412 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
3413
3414 rcu_read_lock();
3415 arch_enter_lazy_mmu_mode();
3416
3417 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
3418 unsigned long pfn;
3419
3420 pfn = get_pte_pfn(pte[i], pvmw->vma, addr);
3421 if (pfn == -1)
3422 continue;
3423
3424 if (!pte_young(pte[i]))
3425 continue;
3426
3427 page = get_pfn_page(pfn, memcg, pgdat);
3428 if (!page)
3429 continue;
3430
3431 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
3432 VM_WARN_ON_ONCE(true);
3433
3434 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3435 !(PageAnon(page) && PageSwapBacked(page) &&
3436 !PageSwapCache(page)))
3437 set_page_dirty(page);
3438
3439 old_gen = page_lru_gen(page);
3440 if (old_gen < 0)
3441 SetPageReferenced(page);
3442 else if (old_gen != new_gen)
3443 __set_bit(i, bitmap);
3444 }
3445
3446 arch_leave_lazy_mmu_mode();
3447 rcu_read_unlock();
3448
3449 if (bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
3450 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
3451 page = pte_page(pte[i]);
3452 activate_page(page);
3453 }
3454 return;
3455 }
3456
3457 /* page_update_gen() requires stable page_memcg() */
3458 if (!mem_cgroup_trylock_pages(memcg))
3459 return;
3460
3461 spin_lock_irq(&lruvec->lru_lock);
3462 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
3463
3464 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
3465 page = compound_head(pte_page(pte[i]));
3466 if (page_memcg_rcu(page) != memcg)
3467 continue;
3468
3469 old_gen = page_update_gen(page, new_gen);
3470 if (old_gen < 0 || old_gen == new_gen)
3471 continue;
3472
3473 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3474 }
3475
3476 spin_unlock_irq(&lruvec->lru_lock);
3477
3478 mem_cgroup_unlock_pages();
3479}
3480
Yu Zhao37397872022-09-18 02:00:03 -06003481/******************************************************************************
3482 * the eviction
3483 ******************************************************************************/
3484
3485static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
3486{
3487 bool success;
3488 int gen = page_lru_gen(page);
3489 int type = page_is_file_lru(page);
3490 int zone = page_zonenum(page);
3491 int delta = thp_nr_pages(page);
3492 int refs = page_lru_refs(page);
3493 int tier = lru_tier_from_refs(refs);
3494 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3495
3496 VM_WARN_ON_ONCE_PAGE(gen >= MAX_NR_GENS, page);
3497
3498 /* unevictable */
3499 if (!page_evictable(page)) {
3500 success = lru_gen_del_page(lruvec, page, true);
3501 VM_WARN_ON_ONCE_PAGE(!success, page);
3502 SetPageUnevictable(page);
3503 add_page_to_lru_list(page, lruvec);
3504 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
3505 return true;
3506 }
3507
3508 /* dirty lazyfree */
3509 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
3510 success = lru_gen_del_page(lruvec, page, true);
3511 VM_WARN_ON_ONCE_PAGE(!success, page);
3512 SetPageSwapBacked(page);
3513 add_page_to_lru_list_tail(page, lruvec);
3514 return true;
3515 }
3516
Yu Zhao0182f922022-09-18 02:00:04 -06003517 /* promoted */
3518 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
3519 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
3520 return true;
3521 }
3522
Yu Zhao37397872022-09-18 02:00:03 -06003523 /* protected */
3524 if (tier > tier_idx) {
3525 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3526
3527 gen = page_inc_gen(lruvec, page, false);
3528 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
3529
3530 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
3531 lrugen->protected[hist][type][tier - 1] + delta);
3532 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
3533 return true;
3534 }
3535
3536 /* waiting for writeback */
3537 if (PageLocked(page) || PageWriteback(page) ||
3538 (type == LRU_GEN_FILE && PageDirty(page))) {
3539 gen = page_inc_gen(lruvec, page, true);
3540 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
3541 return true;
3542 }
3543
3544 return false;
3545}
3546
3547static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
3548{
3549 bool success;
3550
3551 /* unmapping inhibited */
3552 if (!sc->may_unmap && page_mapped(page))
3553 return false;
3554
3555 /* swapping inhibited */
3556 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
3557 (PageDirty(page) ||
3558 (PageAnon(page) && !PageSwapCache(page))))
3559 return false;
3560
3561 /* raced with release_pages() */
3562 if (!get_page_unless_zero(page))
3563 return false;
3564
3565 /* raced with another isolation */
3566 if (!TestClearPageLRU(page)) {
3567 put_page(page);
3568 return false;
3569 }
3570
3571 /* see the comment on MAX_NR_TIERS */
3572 if (!PageReferenced(page))
3573 set_mask_bits(&page->flags, LRU_REFS_MASK | LRU_REFS_FLAGS, 0);
3574
3575 /* for shrink_page_list() */
3576 ClearPageReclaim(page);
3577 ClearPageReferenced(page);
3578
3579 success = lru_gen_del_page(lruvec, page, true);
3580 VM_WARN_ON_ONCE_PAGE(!success, page);
3581
3582 return true;
3583}
3584
3585static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
3586 int type, int tier, struct list_head *list)
3587{
3588 int gen, zone;
3589 enum vm_event_item item;
3590 int sorted = 0;
3591 int scanned = 0;
3592 int isolated = 0;
3593 int remaining = MAX_LRU_BATCH;
3594 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3595 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3596
3597 VM_WARN_ON_ONCE(!list_empty(list));
3598
3599 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
3600 return 0;
3601
3602 gen = lru_gen_from_seq(lrugen->min_seq[type]);
3603
3604 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
3605 LIST_HEAD(moved);
3606 int skipped = 0;
3607 struct list_head *head = &lrugen->lists[gen][type][zone];
3608
3609 while (!list_empty(head)) {
3610 struct page *page = lru_to_page(head);
3611 int delta = thp_nr_pages(page);
3612
3613 VM_WARN_ON_ONCE_PAGE(PageUnevictable(page), page);
3614 VM_WARN_ON_ONCE_PAGE(PageActive(page), page);
3615 VM_WARN_ON_ONCE_PAGE(page_is_file_lru(page) != type, page);
3616 VM_WARN_ON_ONCE_PAGE(page_zonenum(page) != zone, page);
3617
3618 scanned += delta;
3619
3620 if (sort_page(lruvec, page, tier))
3621 sorted += delta;
3622 else if (isolate_page(lruvec, page, sc)) {
3623 list_add(&page->lru, list);
3624 isolated += delta;
3625 } else {
3626 list_move(&page->lru, &moved);
3627 skipped += delta;
3628 }
3629
3630 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
3631 break;
3632 }
3633
3634 if (skipped) {
3635 list_splice(&moved, head);
3636 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
3637 }
3638
3639 if (!remaining || isolated >= MIN_LRU_BATCH)
3640 break;
3641 }
3642
3643 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
3644 if (!cgroup_reclaim(sc)) {
3645 __count_vm_events(item, isolated);
3646 __count_vm_events(PGREFILL, sorted);
3647 }
3648 __count_memcg_events(memcg, item, isolated);
3649 __count_memcg_events(memcg, PGREFILL, sorted);
3650 __count_vm_events(PGSCAN_ANON + type, isolated);
3651
3652 /*
3653 * There might not be eligible pages due to reclaim_idx, may_unmap and
3654 * may_writepage. Check the remaining to prevent livelock if it's not
3655 * making progress.
3656 */
3657 return isolated || !remaining ? scanned : 0;
3658}
3659
3660static int get_tier_idx(struct lruvec *lruvec, int type)
3661{
3662 int tier;
3663 struct ctrl_pos sp, pv;
3664
3665 /*
3666 * To leave a margin for fluctuations, use a larger gain factor (1:2).
3667 * This value is chosen because any other tier would have at least twice
3668 * as many refaults as the first tier.
3669 */
3670 read_ctrl_pos(lruvec, type, 0, 1, &sp);
3671 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
3672 read_ctrl_pos(lruvec, type, tier, 2, &pv);
3673 if (!positive_ctrl_err(&sp, &pv))
3674 break;
3675 }
3676
3677 return tier - 1;
3678}
3679
3680static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
3681{
3682 int type, tier;
3683 struct ctrl_pos sp, pv;
3684 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
3685
3686 /*
3687 * Compare the first tier of anon with that of file to determine which
3688 * type to scan. Also need to compare other tiers of the selected type
3689 * with the first tier of the other type to determine the last tier (of
3690 * the selected type) to evict.
3691 */
3692 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
3693 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
3694 type = positive_ctrl_err(&sp, &pv);
3695
3696 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
3697 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
3698 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
3699 if (!positive_ctrl_err(&sp, &pv))
3700 break;
3701 }
3702
3703 *tier_idx = tier - 1;
3704
3705 return type;
3706}
3707
3708static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
3709 int *type_scanned, struct list_head *list)
3710{
3711 int i;
3712 int type;
3713 int scanned;
3714 int tier = -1;
3715 DEFINE_MIN_SEQ(lruvec);
3716
3717 /*
3718 * Try to make the obvious choice first. When anon and file are both
3719 * available from the same generation, interpret swappiness 1 as file
3720 * first and 200 as anon first.
3721 */
3722 if (!swappiness)
3723 type = LRU_GEN_FILE;
3724 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
3725 type = LRU_GEN_ANON;
3726 else if (swappiness == 1)
3727 type = LRU_GEN_FILE;
3728 else if (swappiness == 200)
3729 type = LRU_GEN_ANON;
3730 else
3731 type = get_type_to_scan(lruvec, swappiness, &tier);
3732
3733 for (i = !swappiness; i < ANON_AND_FILE; i++) {
3734 if (tier < 0)
3735 tier = get_tier_idx(lruvec, type);
3736
3737 scanned = scan_pages(lruvec, sc, type, tier, list);
3738 if (scanned)
3739 break;
3740
3741 type = !type;
3742 tier = -1;
3743 }
3744
3745 *type_scanned = type;
3746
3747 return scanned;
3748}
3749
3750static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
3751{
3752 int type;
3753 int scanned;
3754 int reclaimed;
3755 LIST_HEAD(list);
3756 struct page *page;
3757 enum vm_event_item item;
3758 struct reclaim_stat stat;
3759 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3760 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3761
3762 spin_lock_irq(&lruvec->lru_lock);
3763
3764 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
3765
3766 scanned += try_to_inc_min_seq(lruvec, swappiness);
3767
3768 if (get_nr_gens(lruvec, !swappiness) == MIN_NR_GENS)
3769 scanned = 0;
3770
3771 spin_unlock_irq(&lruvec->lru_lock);
3772
3773 if (list_empty(&list))
3774 return scanned;
3775
3776 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
3777
3778 list_for_each_entry(page, &list, lru) {
3779 /* restore LRU_REFS_FLAGS cleared by isolate_page() */
3780 if (PageWorkingset(page))
3781 SetPageReferenced(page);
3782
3783 /* don't add rejected pages to the oldest generation */
3784 if (PageReclaim(page) &&
3785 (PageDirty(page) || PageWriteback(page)))
3786 ClearPageActive(page);
3787 else
3788 SetPageActive(page);
3789 }
3790
3791 spin_lock_irq(&lruvec->lru_lock);
3792
3793 move_pages_to_lru(lruvec, &list);
3794
3795 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
3796 if (!cgroup_reclaim(sc))
3797 __count_vm_events(item, reclaimed);
3798 __count_memcg_events(memcg, item, reclaimed);
3799 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
3800
3801 spin_unlock_irq(&lruvec->lru_lock);
3802
3803 mem_cgroup_uncharge_list(&list);
3804 free_unref_page_list(&list);
3805
3806 sc->nr_reclaimed += reclaimed;
3807
3808 return scanned;
3809}
3810
3811static unsigned long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc,
3812 bool can_swap)
3813{
3814 bool need_aging;
3815 unsigned long nr_to_scan;
3816 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3817 DEFINE_MAX_SEQ(lruvec);
3818 DEFINE_MIN_SEQ(lruvec);
3819
3820 if (mem_cgroup_below_min(memcg) ||
3821 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
3822 return 0;
3823
3824 need_aging = should_run_aging(lruvec, max_seq, min_seq, sc, can_swap, &nr_to_scan);
3825 if (!need_aging)
3826 return nr_to_scan;
3827
3828 /* skip the aging path at the default priority */
3829 if (sc->priority == DEF_PRIORITY)
3830 goto done;
3831
3832 /* leave the work to lru_gen_age_node() */
3833 if (current_is_kswapd())
3834 return 0;
3835
3836 inc_max_seq(lruvec, max_seq, can_swap);
3837done:
3838 return min_seq[!can_swap] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
3839}
3840
3841static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3842{
3843 struct blk_plug plug;
3844 unsigned long scanned = 0;
3845
3846 lru_add_drain();
3847
3848 blk_start_plug(&plug);
3849
3850 while (true) {
3851 int delta;
3852 int swappiness;
3853 unsigned long nr_to_scan;
3854
3855 if (sc->may_swap)
3856 swappiness = get_swappiness(lruvec, sc);
3857 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
3858 swappiness = 1;
3859 else
3860 swappiness = 0;
3861
3862 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
3863 if (!nr_to_scan)
3864 break;
3865
3866 delta = evict_pages(lruvec, sc, swappiness);
3867 if (!delta)
3868 break;
3869
3870 scanned += delta;
3871 if (scanned >= nr_to_scan)
3872 break;
3873
3874 cond_resched();
3875 }
3876
3877 blk_finish_plug(&plug);
3878}
3879
Yu Zhaod5b2fa12022-09-18 02:00:02 -06003880/******************************************************************************
3881 * initialization
3882 ******************************************************************************/
3883
3884void lru_gen_init_lruvec(struct lruvec *lruvec)
3885{
3886 int gen, type, zone;
3887 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3888
3889 lrugen->max_seq = MIN_NR_GENS + 1;
3890
3891 for_each_gen_type_zone(gen, type, zone)
3892 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
3893}
3894
3895#ifdef CONFIG_MEMCG
3896void lru_gen_init_memcg(struct mem_cgroup *memcg)
3897{
3898}
3899
3900void lru_gen_exit_memcg(struct mem_cgroup *memcg)
3901{
3902 int nid;
3903
3904 for_each_node(nid) {
3905 struct lruvec *lruvec = get_lruvec(memcg, nid);
3906
3907 VM_WARN_ON_ONCE(memchr_inv(lruvec->lrugen.nr_pages, 0,
3908 sizeof(lruvec->lrugen.nr_pages)));
3909 }
3910}
3911#endif
3912
3913static int __init init_lru_gen(void)
3914{
3915 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
3916 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
3917
3918 return 0;
3919};
3920late_initcall(init_lru_gen);
3921
Yu Zhao37397872022-09-18 02:00:03 -06003922#else /* !CONFIG_LRU_GEN */
3923
3924static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
3925{
3926}
3927
3928static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3929{
3930}
3931
Yu Zhaod5b2fa12022-09-18 02:00:02 -06003932#endif /* CONFIG_LRU_GEN */
3933
Johannes Weinerafaf07a2019-11-30 17:55:46 -08003934static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003935{
3936 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07003937 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003938 unsigned long nr_to_scan;
3939 enum lru_list lru;
3940 unsigned long nr_reclaimed = 0;
3941 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
3942 struct blk_plug plug;
Mel Gorman1a501902014-06-04 16:10:49 -07003943 bool scan_adjusted;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003944
Yu Zhao37397872022-09-18 02:00:03 -06003945 if (lru_gen_enabled()) {
3946 lru_gen_shrink_lruvec(lruvec, sc);
3947 return;
3948 }
3949
Johannes Weinerafaf07a2019-11-30 17:55:46 -08003950 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003951
Mel Gormane82e0562013-07-03 15:01:44 -07003952 /* Record the original scan target for proportional adjustments later */
3953 memcpy(targets, nr, sizeof(nr));
3954
Mel Gorman1a501902014-06-04 16:10:49 -07003955 /*
3956 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
3957 * event that can occur when there is little memory pressure e.g.
3958 * multiple streaming readers/writers. Hence, we do not abort scanning
3959 * when the requested number of pages are reclaimed when scanning at
3960 * DEF_PRIORITY on the assumption that the fact we are direct
3961 * reclaiming implies that kswapd is not keeping up and it is best to
3962 * do a batch of work at once. For memcg reclaim one check is made to
3963 * abort proportional reclaim if either the file or anon lru has already
3964 * dropped to zero at the first pass.
3965 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08003966 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
Mel Gorman1a501902014-06-04 16:10:49 -07003967 sc->priority == DEF_PRIORITY);
3968
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003969 blk_start_plug(&plug);
3970 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
3971 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07003972 unsigned long nr_anon, nr_file, percentage;
3973 unsigned long nr_scanned;
3974
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003975 for_each_evictable_lru(lru) {
3976 if (nr[lru]) {
3977 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
3978 nr[lru] -= nr_to_scan;
3979
3980 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07003981 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003982 }
3983 }
Mel Gormane82e0562013-07-03 15:01:44 -07003984
Michal Hockobd041732016-12-02 17:26:48 -08003985 cond_resched();
3986
Mel Gormane82e0562013-07-03 15:01:44 -07003987 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
3988 continue;
3989
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003990 /*
Mel Gormane82e0562013-07-03 15:01:44 -07003991 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07003992 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07003993 * proportionally what was requested by get_scan_count(). We
3994 * stop reclaiming one LRU and reduce the amount scanning
3995 * proportional to the original scan target.
3996 */
3997 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
3998 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
3999
Mel Gorman1a501902014-06-04 16:10:49 -07004000 /*
4001 * It's just vindictive to attack the larger once the smaller
4002 * has gone to zero. And given the way we stop scanning the
4003 * smaller below, this makes sure that we only make one nudge
4004 * towards proportionality once we've got nr_to_reclaim.
4005 */
4006 if (!nr_file || !nr_anon)
4007 break;
4008
Mel Gormane82e0562013-07-03 15:01:44 -07004009 if (nr_file > nr_anon) {
4010 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
4011 targets[LRU_ACTIVE_ANON] + 1;
4012 lru = LRU_BASE;
4013 percentage = nr_anon * 100 / scan_target;
4014 } else {
4015 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
4016 targets[LRU_ACTIVE_FILE] + 1;
4017 lru = LRU_FILE;
4018 percentage = nr_file * 100 / scan_target;
4019 }
4020
4021 /* Stop scanning the smaller of the LRU */
4022 nr[lru] = 0;
4023 nr[lru + LRU_ACTIVE] = 0;
4024
4025 /*
4026 * Recalculate the other LRU scan count based on its original
4027 * scan target and the percentage scanning already complete
4028 */
4029 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
4030 nr_scanned = targets[lru] - nr[lru];
4031 nr[lru] = targets[lru] * (100 - percentage) / 100;
4032 nr[lru] -= min(nr[lru], nr_scanned);
4033
4034 lru += LRU_ACTIVE;
4035 nr_scanned = targets[lru] - nr[lru];
4036 nr[lru] = targets[lru] * (100 - percentage) / 100;
4037 nr[lru] -= min(nr[lru], nr_scanned);
4038
4039 scan_adjusted = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004040 }
4041 blk_finish_plug(&plug);
4042 sc->nr_reclaimed += nr_reclaimed;
4043
4044 /*
4045 * Even if we did not try to evict anon pages at all, we want to
4046 * rebalance the anon lru active/inactive ratio.
4047 */
Dave Hansen2f368a92021-09-02 14:59:23 -07004048 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
4049 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004050 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
4051 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004052}
4053
Mel Gorman23b9da52012-05-29 15:06:20 -07004054/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004055static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07004056{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08004057 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07004058 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004059 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07004060 return true;
4061
4062 return false;
4063}
4064
Rik van Riel4f98a2f2008-10-18 20:26:32 -07004065/*
Mel Gorman23b9da52012-05-29 15:06:20 -07004066 * Reclaim/compaction is used for high-order allocation requests. It reclaims
4067 * order-0 pages before compacting the zone. should_continue_reclaim() returns
4068 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07004069 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07004070 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08004071 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07004072static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08004073 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08004074 struct scan_control *sc)
4075{
4076 unsigned long pages_for_compaction;
4077 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07004078 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08004079
4080 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004081 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08004082 return false;
4083
Vlastimil Babka5ee04712019-09-23 15:37:29 -07004084 /*
4085 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
4086 * number of pages that were scanned. This will return to the caller
4087 * with the risk reclaim/compaction and the resulting allocation attempt
4088 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
4089 * allocations through requiring that the full LRU list has been scanned
4090 * first, by assuming that zero delta of sc->nr_scanned means full LRU
4091 * scan, but that approximation was wrong, and there were corner cases
4092 * where always a non-zero amount of pages were scanned.
4093 */
4094 if (!nr_reclaimed)
4095 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08004096
Mel Gorman3e7d3442011-01-13 15:45:56 -08004097 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07004098 for (z = 0; z <= sc->reclaim_idx; z++) {
4099 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07004100 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07004101 continue;
4102
4103 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07004104 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07004105 case COMPACT_CONTINUE:
4106 return false;
4107 default:
4108 /* check next zone */
4109 ;
4110 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08004111 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07004112
4113 /*
4114 * If we have not reclaimed enough pages for compaction and the
4115 * inactive lists are large enough, continue reclaiming
4116 */
4117 pages_for_compaction = compact_gap(sc->order);
4118 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07004119 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07004120 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
4121
Vlastimil Babka5ee04712019-09-23 15:37:29 -07004122 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08004123}
4124
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004125static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08004126{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004127 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08004128 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08004129
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004130 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08004131 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004132 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08004133 unsigned long reclaimed;
4134 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08004135 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08004136
Xunlei Pange3336ca2020-09-04 16:35:27 -07004137 /*
4138 * This loop can become CPU-bound when target memcgs
4139 * aren't eligible for reclaim - either because they
4140 * don't have any reclaimable pages, or because their
4141 * memory is explicitly protected. Avoid soft lockups.
4142 */
4143 cond_resched();
4144
Liujie Xieb7ea1c42022-06-01 15:38:17 +08004145 trace_android_vh_shrink_node_memcgs(memcg, &skip);
4146 if (skip)
4147 continue;
4148
Chris Down45c7f7e2020-08-06 23:22:05 -07004149 mem_cgroup_calculate_protection(target_memcg, memcg);
4150
4151 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08004152 /*
4153 * Hard protection.
4154 * If there is no reclaimable memory, OOM.
4155 */
4156 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07004157 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08004158 /*
4159 * Soft protection.
4160 * Respect the protection only as long as
4161 * there is an unprotected supply
4162 * of reclaimable memory from other cgroups.
4163 */
4164 if (!sc->memcg_low_reclaim) {
4165 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07004166 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08004167 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08004168 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08004169 }
4170
Johannes Weinerd2af3392019-11-30 17:55:43 -08004171 reclaimed = sc->nr_reclaimed;
4172 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004173
4174 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07004175
Johannes Weinerd2af3392019-11-30 17:55:43 -08004176 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
4177 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07004178
Johannes Weinerd2af3392019-11-30 17:55:43 -08004179 /* Record the group's reclaim efficiency */
4180 vmpressure(sc->gfp_mask, memcg, false,
4181 sc->nr_scanned - scanned,
4182 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07004183
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004184 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
4185}
4186
Liu Song6c9e09072020-01-30 22:14:08 -08004187static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004188{
4189 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004190 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08004191 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004192 bool reclaimable = false;
4193
Johannes Weiner1b051172019-11-30 17:55:52 -08004194 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
4195
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004196again:
4197 memset(&sc->nr, 0, sizeof(sc->nr));
4198
4199 nr_reclaimed = sc->nr_reclaimed;
4200 nr_scanned = sc->nr_scanned;
4201
Yu Zhao6d313442022-09-18 02:00:00 -06004202 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08004203
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004204 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07004205
Johannes Weinerd2af3392019-11-30 17:55:43 -08004206 if (reclaim_state) {
4207 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
4208 reclaim_state->reclaimed_slab = 0;
4209 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07004210
Johannes Weinerd2af3392019-11-30 17:55:43 -08004211 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08004212 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08004213 sc->nr_scanned - nr_scanned,
4214 sc->nr_reclaimed - nr_reclaimed);
4215
4216 if (sc->nr_reclaimed - nr_reclaimed)
4217 reclaimable = true;
4218
4219 if (current_is_kswapd()) {
4220 /*
4221 * If reclaim is isolating dirty pages under writeback,
4222 * it implies that the long-lived page allocation rate
4223 * is exceeding the page laundering rate. Either the
4224 * global limits are not being effective at throttling
4225 * processes due to the page distribution throughout
4226 * zones or there is heavy usage of a slow backing
4227 * device. The only option is to throttle from reclaim
4228 * context which is not ideal as there is no guarantee
4229 * the dirtying process is throttled in the same way
4230 * balance_dirty_pages() manages.
4231 *
4232 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
4233 * count the number of pages under pages flagged for
4234 * immediate reclaim and stall if any are encountered
4235 * in the nr_immediate check below.
4236 */
4237 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
4238 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07004239
Johannes Weinerd2af3392019-11-30 17:55:43 -08004240 /* Allow kswapd to start writing pages during reclaim.*/
4241 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
4242 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07004243
4244 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07004245 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08004246 * reclaim and under writeback (nr_immediate), it
4247 * implies that pages are cycling through the LRU
4248 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07004249 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08004250 if (sc->nr.immediate)
4251 congestion_wait(BLK_RW_ASYNC, HZ/10);
4252 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07004253
Johannes Weinerd2af3392019-11-30 17:55:43 -08004254 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08004255 * Tag a node/memcg as congested if all the dirty pages
4256 * scanned were backed by a congested BDI and
4257 * wait_iff_congested will stall.
4258 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08004259 * Legacy memcg will stall in page writeback so avoid forcibly
4260 * stalling in wait_iff_congested().
4261 */
Johannes Weiner1b051172019-11-30 17:55:52 -08004262 if ((current_is_kswapd() ||
4263 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08004264 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08004265 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08004266
4267 /*
4268 * Stall direct reclaim for IO completions if underlying BDIs
4269 * and node is congested. Allow kswapd to continue until it
4270 * starts encountering unqueued dirty pages or cycling through
4271 * the LRU too quickly.
4272 */
Johannes Weiner1b051172019-11-30 17:55:52 -08004273 if (!current_is_kswapd() && current_may_throttle() &&
4274 !sc->hibernation_mode &&
4275 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08004276 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
4277
4278 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
4279 sc))
4280 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07004281
Johannes Weinerc73322d2017-05-03 14:51:51 -07004282 /*
4283 * Kswapd gives up on balancing particular nodes after too
4284 * many failures to reclaim anything from them and goes to
4285 * sleep. On reclaim progress, reset the failure counter. A
4286 * successful direct reclaim run will revive a dormant kswapd.
4287 */
4288 if (reclaimable)
4289 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08004290}
4291
Vlastimil Babka53853e22014-10-09 15:27:02 -07004292/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07004293 * Returns true if compaction should go ahead for a costly-order request, or
4294 * the allocation would already succeed without compaction. Return false if we
4295 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07004296 */
Mel Gorman4f588332016-07-28 15:46:38 -07004297static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08004298{
Mel Gorman31483b62016-07-28 15:45:46 -07004299 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07004300 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08004301
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07004302 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
4303 if (suitable == COMPACT_SUCCESS)
4304 /* Allocation should succeed already. Don't reclaim. */
4305 return true;
4306 if (suitable == COMPACT_SKIPPED)
4307 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08004308 return false;
4309
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07004310 /*
4311 * Compaction is already possible, but it takes time to run and there
4312 * are potentially other callers using the pages just freed. So proceed
4313 * with reclaim to make a buffer of free pages available to give
4314 * compaction a reasonable chance of completing and allocating the page.
4315 * Note that we won't actually reclaim the whole buffer in one attempt
4316 * as the target watermark in should_continue_reclaim() is lower. But if
4317 * we are already above the high+gap watermark, don't reclaim at all.
4318 */
4319 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
4320
4321 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08004322}
4323
Linus Torvalds1da177e2005-04-16 15:20:36 -07004324/*
4325 * This is the direct reclaim path, for page-allocating processes. We only
4326 * try to reclaim pages from zones which will satisfy the caller's allocation
4327 * request.
4328 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07004329 * If a zone is deemed to be full of pinned pages then just give it a light
4330 * scan then give up on it.
4331 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07004332static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07004333{
Mel Gormandd1a2392008-04-28 02:12:17 -07004334 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07004335 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07004336 unsigned long nr_soft_reclaimed;
4337 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07004338 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07004339 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08004340
Mel Gormancc715d92012-03-21 16:34:00 -07004341 /*
4342 * If the number of buffer_heads in the machine exceeds the maximum
4343 * allowed level, force direct reclaim to scan the highmem zone as
4344 * highmem pages could be pinning lowmem pages storing buffer_heads
4345 */
Weijie Yang619d0d762014-04-07 15:36:59 -07004346 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07004347 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07004348 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07004349 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07004350 }
Mel Gormancc715d92012-03-21 16:34:00 -07004351
Mel Gormand4debc62010-08-09 17:19:29 -07004352 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07004353 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07004354 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08004355 * Take care memory controller reclaiming has small influence
4356 * to global LRU.
4357 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08004358 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04004359 if (!cpuset_zone_allowed(zone,
4360 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08004361 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07004362
Johannes Weiner0b064962014-08-06 16:06:12 -07004363 /*
4364 * If we already have plenty of memory free for
4365 * compaction in this zone, don't free any more.
4366 * Even though compaction is invoked for any
4367 * non-zero order, only frequent costly order
4368 * reclamation is disruptive enough to become a
4369 * noticeable problem, like transparent huge
4370 * page allocations.
4371 */
4372 if (IS_ENABLED(CONFIG_COMPACTION) &&
4373 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07004374 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07004375 sc->compaction_ready = true;
4376 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07004377 }
Johannes Weiner0b064962014-08-06 16:06:12 -07004378
Andrew Morton0608f432013-09-24 15:27:41 -07004379 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07004380 * Shrink each node in the zonelist once. If the
4381 * zonelist is ordered by zone (not the default) then a
4382 * node may be shrunk multiple times but in that case
4383 * the user prefers lower zones being preserved.
4384 */
4385 if (zone->zone_pgdat == last_pgdat)
4386 continue;
4387
4388 /*
Andrew Morton0608f432013-09-24 15:27:41 -07004389 * This steals pages from memory cgroups over softlimit
4390 * and returns the number of reclaimed pages and
4391 * scanned pages. This works for global memory pressure
4392 * and balancing, not for a memcg's limit.
4393 */
4394 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07004395 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07004396 sc->order, sc->gfp_mask,
4397 &nr_soft_scanned);
4398 sc->nr_reclaimed += nr_soft_reclaimed;
4399 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07004400 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08004401 }
Nick Piggin408d8542006-09-25 23:31:27 -07004402
Mel Gorman79dafcd2016-07-28 15:45:53 -07004403 /* See comment about same check for global reclaim above */
4404 if (zone->zone_pgdat == last_pgdat)
4405 continue;
4406 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07004407 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004408 }
Mel Gormane0c23272011-10-31 17:09:33 -07004409
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07004410 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07004411 * Restore to original mask to avoid the impact on the caller if we
4412 * promoted it to __GFP_HIGHMEM.
4413 */
4414 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004415}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07004416
Johannes Weinerb9107182019-11-30 17:55:59 -08004417static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004418{
Johannes Weinerb9107182019-11-30 17:55:59 -08004419 struct lruvec *target_lruvec;
4420 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004421
Yu Zhao37397872022-09-18 02:00:03 -06004422 if (lru_gen_enabled())
4423 return;
4424
Johannes Weinerb9107182019-11-30 17:55:59 -08004425 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07004426 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
4427 target_lruvec->refaults[0] = refaults;
4428 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
4429 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004430}
4431
Linus Torvalds1da177e2005-04-16 15:20:36 -07004432/*
4433 * This is the main entry point to direct page reclaim.
4434 *
4435 * If a full scan of the inactive list fails to free enough memory then we
4436 * are "out of memory" and something needs to be killed.
4437 *
4438 * If the caller is !__GFP_FS then the probability of a failure is reasonably
4439 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02004440 * caller can't do much about. We kick the writeback threads and take explicit
4441 * naps in the hope that some of these pages can be written. But if the
4442 * allocating task holds filesystem locks which prevent writeout this might not
4443 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07004444 *
4445 * returns: 0, if no pages reclaimed
4446 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07004447 */
Mel Gormandac1d272008-04-28 02:12:12 -07004448static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07004449 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07004450{
Johannes Weiner241994ed2015-02-11 15:26:06 -08004451 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004452 pg_data_t *last_pgdat;
4453 struct zoneref *z;
4454 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08004455retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07004456 delayacct_freepages_start();
4457
Johannes Weinerb5ead352019-11-30 17:55:40 -08004458 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07004459 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004460
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004461 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07004462 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
4463 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08004464 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07004465 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07004466
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07004467 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07004468 break;
4469
4470 if (sc->compaction_ready)
4471 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004472
4473 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08004474 * If we're getting trouble reclaiming, start doing
4475 * writepage even in laptop mode.
4476 */
4477 if (sc->priority < DEF_PRIORITY - 2)
4478 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07004479 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07004480
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004481 last_pgdat = NULL;
4482 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
4483 sc->nodemask) {
4484 if (zone->zone_pgdat == last_pgdat)
4485 continue;
4486 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08004487
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004488 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08004489
4490 if (cgroup_reclaim(sc)) {
4491 struct lruvec *lruvec;
4492
4493 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
4494 zone->zone_pgdat);
4495 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
4496 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004497 }
4498
Keika Kobayashi873b4772008-07-25 01:48:52 -07004499 delayacct_freepages_end();
4500
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07004501 if (sc->nr_reclaimed)
4502 return sc->nr_reclaimed;
4503
Mel Gorman0cee34f2012-01-12 17:19:49 -08004504 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07004505 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08004506 return 1;
4507
Johannes Weinerb91ac372019-11-30 17:56:02 -08004508 /*
4509 * We make inactive:active ratio decisions based on the node's
4510 * composition of memory, but a restrictive reclaim_idx or a
4511 * memory.low cgroup setting can exempt large amounts of
4512 * memory from reclaim. Neither of which are very common, so
4513 * instead of doing costly eligibility calculations of the
4514 * entire cgroup subtree up front, we assume the estimates are
4515 * good, and retry with forcible deactivation if that fails.
4516 */
4517 if (sc->skipped_deactivate) {
4518 sc->priority = initial_priority;
4519 sc->force_deactivate = 1;
4520 sc->skipped_deactivate = 0;
4521 goto retry;
4522 }
4523
Johannes Weiner241994ed2015-02-11 15:26:06 -08004524 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07004525 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08004526 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08004527 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07004528 sc->memcg_low_reclaim = 1;
4529 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08004530 goto retry;
4531 }
4532
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07004533 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004534}
4535
Johannes Weinerc73322d2017-05-03 14:51:51 -07004536static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07004537{
4538 struct zone *zone;
4539 unsigned long pfmemalloc_reserve = 0;
4540 unsigned long free_pages = 0;
4541 int i;
4542 bool wmark_ok;
4543
Johannes Weinerc73322d2017-05-03 14:51:51 -07004544 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
4545 return true;
4546
Mel Gorman55150612012-07-31 16:44:35 -07004547 for (i = 0; i <= ZONE_NORMAL; i++) {
4548 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07004549 if (!managed_zone(zone))
4550 continue;
4551
4552 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07004553 continue;
4554
Mel Gorman55150612012-07-31 16:44:35 -07004555 pfmemalloc_reserve += min_wmark_pages(zone);
4556 free_pages += zone_page_state(zone, NR_FREE_PAGES);
4557 }
4558
Mel Gorman675becc2014-06-04 16:07:35 -07004559 /* If there are no reserves (unexpected config) then do not throttle */
4560 if (!pfmemalloc_reserve)
4561 return true;
4562
Mel Gorman55150612012-07-31 16:44:35 -07004563 wmark_ok = free_pages > pfmemalloc_reserve / 2;
4564
4565 /* kswapd must be awake if processes are being throttled */
4566 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004567 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
4568 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07004569
Mel Gorman55150612012-07-31 16:44:35 -07004570 wake_up_interruptible(&pgdat->kswapd_wait);
4571 }
4572
4573 return wmark_ok;
4574}
4575
4576/*
4577 * Throttle direct reclaimers if backing storage is backed by the network
4578 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
4579 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08004580 * when the low watermark is reached.
4581 *
4582 * Returns true if a fatal signal was delivered during throttling. If this
4583 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07004584 */
Mel Gorman50694c22012-11-26 16:29:48 -08004585static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07004586 nodemask_t *nodemask)
4587{
Mel Gorman675becc2014-06-04 16:07:35 -07004588 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07004589 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07004590 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07004591
4592 /*
4593 * Kernel threads should not be throttled as they may be indirectly
4594 * responsible for cleaning pages necessary for reclaim to make forward
4595 * progress. kjournald for example may enter direct reclaim while
4596 * committing a transaction where throttling it could forcing other
4597 * processes to block on log_wait_commit().
4598 */
4599 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08004600 goto out;
4601
4602 /*
4603 * If a fatal signal is pending, this process should not throttle.
4604 * It should return quickly so it can exit and free its memory
4605 */
4606 if (fatal_signal_pending(current))
4607 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07004608
Mel Gorman675becc2014-06-04 16:07:35 -07004609 /*
4610 * Check if the pfmemalloc reserves are ok by finding the first node
4611 * with a usable ZONE_NORMAL or lower zone. The expectation is that
4612 * GFP_KERNEL will be required for allocating network buffers when
4613 * swapping over the network so ZONE_HIGHMEM is unusable.
4614 *
4615 * Throttling is based on the first usable node and throttled processes
4616 * wait on a queue until kswapd makes progress and wakes them. There
4617 * is an affinity then between processes waking up and where reclaim
4618 * progress has been made assuming the process wakes on the same node.
4619 * More importantly, processes running on remote nodes will not compete
4620 * for remote pfmemalloc reserves and processes on different nodes
4621 * should make reasonable progress.
4622 */
4623 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08004624 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07004625 if (zone_idx(zone) > ZONE_NORMAL)
4626 continue;
4627
4628 /* Throttle based on the first usable node */
4629 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07004630 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07004631 goto out;
4632 break;
4633 }
4634
4635 /* If no zone was usable by the allocation flags then do not throttle */
4636 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08004637 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07004638
Mel Gorman68243e72012-07-31 16:44:39 -07004639 /* Account for the throttling */
4640 count_vm_event(PGSCAN_DIRECT_THROTTLE);
4641
Mel Gorman55150612012-07-31 16:44:35 -07004642 /*
4643 * If the caller cannot enter the filesystem, it's possible that it
4644 * is due to the caller holding an FS lock or performing a journal
4645 * transaction in the case of a filesystem like ext[3|4]. In this case,
4646 * it is not safe to block on pfmemalloc_wait as kswapd could be
4647 * blocked waiting on the same lock. Instead, throttle for up to a
4648 * second before continuing.
4649 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07004650 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07004651 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07004652 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07004653 else
4654 /* Throttle until kswapd wakes the process */
4655 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
4656 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08004657
Mel Gorman50694c22012-11-26 16:29:48 -08004658 if (fatal_signal_pending(current))
4659 return true;
4660
4661out:
4662 return false;
Mel Gorman55150612012-07-31 16:44:35 -07004663}
4664
Mel Gormandac1d272008-04-28 02:12:12 -07004665unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07004666 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08004667{
Mel Gorman33906bc2010-08-09 17:19:16 -07004668 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08004669 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08004670 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07004671 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07004672 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07004673 .order = order,
4674 .nodemask = nodemask,
4675 .priority = DEF_PRIORITY,
4676 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07004677 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07004678 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08004679 };
4680
Mel Gorman55150612012-07-31 16:44:35 -07004681 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07004682 * scan_control uses s8 fields for order, priority, and reclaim_idx.
4683 * Confirm they are large enough for max values.
4684 */
4685 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
4686 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
4687 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
4688
4689 /*
Mel Gorman50694c22012-11-26 16:29:48 -08004690 * Do not enter reclaim if fatal signal was delivered while throttled.
4691 * 1 is returned so that the page allocator does not OOM kill at this
4692 * point.
Mel Gorman55150612012-07-31 16:44:35 -07004693 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07004694 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07004695 return 1;
4696
Andrew Morton1732d2b012019-07-16 16:26:15 -07004697 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07004698 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07004699
Vladimir Davydov3115cd92014-04-03 14:47:22 -07004700 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07004701
4702 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07004703 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07004704
4705 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08004706}
4707
Andrew Mortonc255a452012-07-31 16:43:02 -07004708#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08004709
Michal Hockod2e5fb92019-08-30 16:04:50 -07004710/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07004711unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07004712 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07004713 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07004714 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07004715{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004716 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07004717 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07004718 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07004719 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07004720 .may_writepage = !laptop_mode,
4721 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07004722 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07004723 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07004724 };
Ying Han0ae5e892011-05-26 16:25:25 -07004725
Michal Hockod2e5fb92019-08-30 16:04:50 -07004726 WARN_ON_ONCE(!current->reclaim_state);
4727
Balbir Singh4e416952009-09-23 15:56:39 -07004728 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
4729 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004730
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004731 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07004732 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004733
Balbir Singh4e416952009-09-23 15:56:39 -07004734 /*
4735 * NOTE: Although we can get the priority field, using it
4736 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07004737 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07004738 * will pick up pages from other mem cgroup's as well. We hack
4739 * the priority and make it zero.
4740 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004741 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004742
4743 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
4744
Ying Han0ae5e892011-05-26 16:25:25 -07004745 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07004746
Balbir Singh4e416952009-09-23 15:56:39 -07004747 return sc.nr_reclaimed;
4748}
4749
Johannes Weiner72835c82012-01-12 17:18:32 -08004750unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07004751 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004752 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07004753 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08004754{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004755 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07004756 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08004757 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07004758 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07004759 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07004760 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07004761 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07004762 .target_mem_cgroup = memcg,
4763 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08004764 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07004765 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07004766 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07004767 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08004768 /*
4769 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
4770 * equal pressure on all the nodes. This is based on the assumption that
4771 * the reclaim does not bail out early.
4772 */
4773 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08004774
Andrew Morton1732d2b012019-07-16 16:26:15 -07004775 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07004776 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07004777 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07004778
Vladimir Davydov3115cd92014-04-03 14:47:22 -07004779 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07004780
Vlastimil Babka499118e2017-05-08 15:59:50 -07004781 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004782 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07004783 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004784
4785 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08004786}
Liujie Xie1ed025b2021-06-25 22:21:35 +08004787EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08004788#endif
4789
Yu Zhao37397872022-09-18 02:00:03 -06004790static void kswapd_age_node(struct pglist_data *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08004791{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08004792 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08004793 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08004794
Yu Zhao37397872022-09-18 02:00:03 -06004795 if (lru_gen_enabled()) {
4796 lru_gen_age_node(pgdat, sc);
4797 return;
4798 }
4799
Dave Hansen2f368a92021-09-02 14:59:23 -07004800 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08004801 return;
4802
Johannes Weinerb91ac372019-11-30 17:56:02 -08004803 lruvec = mem_cgroup_lruvec(NULL, pgdat);
4804 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
4805 return;
4806
Johannes Weinerb95a2f22012-01-12 17:18:06 -08004807 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4808 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08004809 lruvec = mem_cgroup_lruvec(memcg, pgdat);
4810 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
4811 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08004812 memcg = mem_cgroup_iter(NULL, memcg, NULL);
4813 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08004814}
4815
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004816static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08004817{
4818 int i;
4819 struct zone *zone;
4820
4821 /*
4822 * Check for watermark boosts top-down as the higher zones
4823 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07004824 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08004825 * start prematurely when there is no boosting and a lower
4826 * zone is balanced.
4827 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004828 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08004829 zone = pgdat->node_zones + i;
4830 if (!managed_zone(zone))
4831 continue;
4832
4833 if (zone->watermark_boost)
4834 return true;
4835 }
4836
4837 return false;
4838}
4839
Mel Gormane716f2e2017-05-03 14:53:45 -07004840/*
4841 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004842 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07004843 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004844static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08004845{
Mel Gormane716f2e2017-05-03 14:53:45 -07004846 int i;
4847 unsigned long mark = -1;
4848 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08004849
Mel Gorman1c308442018-12-28 00:35:52 -08004850 /*
4851 * Check watermarks bottom-up as lower zones are more likely to
4852 * meet watermarks.
4853 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004854 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07004855 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07004856
Mel Gormane716f2e2017-05-03 14:53:45 -07004857 if (!managed_zone(zone))
4858 continue;
4859
4860 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004861 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07004862 return true;
4863 }
4864
4865 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004866 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07004867 * need balancing by definition. This can happen if a zone-restricted
4868 * allocation tries to wake a remote kswapd.
4869 */
4870 if (mark == -1)
4871 return true;
4872
4873 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08004874}
4875
Mel Gorman631b6e02017-05-03 14:53:41 -07004876/* Clear pgdat state for congested, dirty or under writeback. */
4877static void clear_pgdat_congested(pg_data_t *pgdat)
4878{
Johannes Weiner1b051172019-11-30 17:55:52 -08004879 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
4880
4881 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07004882 clear_bit(PGDAT_DIRTY, &pgdat->flags);
4883 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
4884}
4885
Mel Gorman1741c872011-01-13 15:46:21 -08004886/*
Mel Gorman55150612012-07-31 16:44:35 -07004887 * Prepare kswapd for sleeping. This verifies that there are no processes
4888 * waiting in throttle_direct_reclaim() and that watermarks have been met.
4889 *
4890 * Returns true if kswapd is ready to sleep
4891 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004892static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
4893 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08004894{
Mel Gorman55150612012-07-31 16:44:35 -07004895 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08004896 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07004897 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08004898 * race between when kswapd checks the watermarks and a process gets
4899 * throttled. There is also a potential race if processes get
4900 * throttled, kswapd wakes, a large process exits thereby balancing the
4901 * zones, which causes kswapd to exit balance_pgdat() before reaching
4902 * the wake up checks. If kswapd is going to sleep, no process should
4903 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
4904 * the wake up is premature, processes will wake kswapd and get
4905 * throttled again. The difference from wake ups in balance_pgdat() is
4906 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07004907 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08004908 if (waitqueue_active(&pgdat->pfmemalloc_wait))
4909 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08004910
Johannes Weinerc73322d2017-05-03 14:51:51 -07004911 /* Hopeless node, leave it to direct reclaim */
4912 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
4913 return true;
4914
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004915 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07004916 clear_pgdat_congested(pgdat);
4917 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07004918 }
4919
Shantanu Goel333b0a42017-05-03 14:53:38 -07004920 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08004921}
4922
Linus Torvalds1da177e2005-04-16 15:20:36 -07004923/*
Mel Gorman1d82de62016-07-28 15:45:43 -07004924 * kswapd shrinks a node of pages that are at or below the highest usable
4925 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07004926 *
4927 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07004928 * reclaim or if the lack of progress was due to pages under writeback.
4929 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07004930 */
Mel Gorman1d82de62016-07-28 15:45:43 -07004931static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07004932 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07004933{
Mel Gorman1d82de62016-07-28 15:45:43 -07004934 struct zone *zone;
4935 int z;
Mel Gorman75485362013-07-03 15:01:42 -07004936
Mel Gorman1d82de62016-07-28 15:45:43 -07004937 /* Reclaim a number of pages proportional to the number of zones */
4938 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07004939 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07004940 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07004941 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07004942 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07004943
Mel Gorman1d82de62016-07-28 15:45:43 -07004944 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07004945 }
4946
Mel Gorman1d82de62016-07-28 15:45:43 -07004947 /*
4948 * Historically care was taken to put equal pressure on all zones but
4949 * now pressure is applied based on node LRU order.
4950 */
Mel Gorman970a39a2016-07-28 15:46:35 -07004951 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07004952
4953 /*
4954 * Fragmentation may mean that the system cannot be rebalanced for
4955 * high-order allocations. If twice the allocation size has been
4956 * reclaimed then recheck watermarks only at order-0 to prevent
4957 * excessive reclaim. Assume that a process requested a high-order
4958 * can direct reclaim/compact.
4959 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07004960 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07004961 sc->order = 0;
4962
Mel Gormanb8e83b92013-07-03 15:01:45 -07004963 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07004964}
4965
Mel Gormanc49c2c42021-06-28 19:42:21 -07004966/* Page allocator PCP high watermark is lowered if reclaim is active. */
4967static inline void
4968update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
4969{
4970 int i;
4971 struct zone *zone;
4972
4973 for (i = 0; i <= highest_zoneidx; i++) {
4974 zone = pgdat->node_zones + i;
4975
4976 if (!managed_zone(zone))
4977 continue;
4978
4979 if (active)
4980 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4981 else
4982 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4983 }
4984}
4985
4986static inline void
4987set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4988{
4989 update_reclaim_active(pgdat, highest_zoneidx, true);
4990}
4991
4992static inline void
4993clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4994{
4995 update_reclaim_active(pgdat, highest_zoneidx, false);
4996}
4997
Mel Gorman75485362013-07-03 15:01:42 -07004998/*
Mel Gorman1d82de62016-07-28 15:45:43 -07004999 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
5000 * that are eligible for use by the caller until at least one zone is
5001 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005002 *
Mel Gorman1d82de62016-07-28 15:45:43 -07005003 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005004 *
5005 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07005006 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08005007 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07005008 * or lower is eligible for reclaim until at least one usable zone is
5009 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005010 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005011static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005012{
Linus Torvalds1da177e2005-04-16 15:20:36 -07005013 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07005014 unsigned long nr_soft_reclaimed;
5015 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07005016 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08005017 unsigned long nr_boost_reclaim;
5018 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
5019 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07005020 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08005021 struct scan_control sc = {
5022 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07005023 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005024 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08005025 };
Omar Sandoval93781322018-06-07 17:07:02 -07005026
Andrew Morton1732d2b012019-07-16 16:26:15 -07005027 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07005028 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07005029 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07005030
Christoph Lameterf8891e52006-06-30 01:55:45 -07005031 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005032
Mel Gorman1c308442018-12-28 00:35:52 -08005033 /*
5034 * Account for the reclaim boost. Note that the zone boost is left in
5035 * place so that parallel allocations that are near the watermark will
5036 * stall or direct reclaim until kswapd is finished.
5037 */
5038 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005039 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08005040 zone = pgdat->node_zones + i;
5041 if (!managed_zone(zone))
5042 continue;
5043
5044 nr_boost_reclaim += zone->watermark_boost;
5045 zone_boosts[i] = zone->watermark_boost;
5046 }
5047 boosted = nr_boost_reclaim;
5048
5049restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07005050 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08005051 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005052 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07005053 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07005054 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08005055 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07005056 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07005057
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005058 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005059
Mel Gorman86c79f62016-07-28 15:45:59 -07005060 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07005061 * If the number of buffer_heads exceeds the maximum allowed
5062 * then consider reclaiming from all zones. This has a dual
5063 * purpose -- on 64-bit systems it is expected that
5064 * buffer_heads are stripped during active rotation. On 32-bit
5065 * systems, highmem pages can pin lowmem memory and shrinking
5066 * buffers can relieve lowmem pressure. Reclaim may still not
5067 * go ahead if all eligible zones for the original allocation
5068 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07005069 */
5070 if (buffer_heads_over_limit) {
5071 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
5072 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07005073 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07005074 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005075
Mel Gorman970a39a2016-07-28 15:46:35 -07005076 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08005077 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005078 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07005079 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08005080
Mel Gorman86c79f62016-07-28 15:45:59 -07005081 /*
Mel Gorman1c308442018-12-28 00:35:52 -08005082 * If the pgdat is imbalanced then ignore boosting and preserve
5083 * the watermarks for a later time and restart. Note that the
5084 * zone watermarks will be still reset at the end of balancing
5085 * on the grounds that the normal reclaim should be enough to
5086 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07005087 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005088 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08005089 if (!balanced && nr_boost_reclaim) {
5090 nr_boost_reclaim = 0;
5091 goto restart;
5092 }
5093
5094 /*
5095 * If boosting is not active then only reclaim if there are no
5096 * eligible zones. Note that sc.reclaim_idx is not used as
5097 * buffer_heads_over_limit may have adjusted it.
5098 */
5099 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07005100 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08005101
Mel Gorman1c308442018-12-28 00:35:52 -08005102 /* Limit the priority of boosting to avoid reclaim writeback */
5103 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
5104 raise_priority = false;
5105
5106 /*
5107 * Do not writeback or swap pages for boosted reclaim. The
5108 * intent is to relieve pressure not issue sub-optimal IO
5109 * from reclaim context. If no pages are reclaimed, the
5110 * reclaim will be aborted.
5111 */
5112 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
5113 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08005114
Linus Torvalds1da177e2005-04-16 15:20:36 -07005115 /*
Yu Zhao37397872022-09-18 02:00:03 -06005116 * Do some background aging, to give pages a chance to be
5117 * referenced before reclaiming. All pages are rotated
5118 * regardless of classzone as this is about consistent aging.
Mel Gorman1d82de62016-07-28 15:45:43 -07005119 */
Yu Zhao37397872022-09-18 02:00:03 -06005120 kswapd_age_node(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07005121
5122 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07005123 * If we're getting trouble reclaiming, start doing writepage
5124 * even in laptop mode.
5125 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07005126 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07005127 sc.may_writepage = 1;
5128
Mel Gorman1d82de62016-07-28 15:45:43 -07005129 /* Call soft limit reclaim before calling shrink_node. */
5130 sc.nr_scanned = 0;
5131 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07005132 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07005133 sc.gfp_mask, &nr_soft_scanned);
5134 sc.nr_reclaimed += nr_soft_reclaimed;
5135
Mel Gormanb7ea3c42013-07-03 15:01:53 -07005136 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07005137 * There should be no need to raise the scanning priority if
5138 * enough pages are already being scanned that that high
5139 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005140 */
Mel Gorman970a39a2016-07-28 15:46:35 -07005141 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07005142 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07005143
5144 /*
5145 * If the low watermark is met there is no need for processes
5146 * to be throttled on pfmemalloc_wait as they should not be
5147 * able to safely make forward progress. Wake them
5148 */
5149 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07005150 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08005151 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07005152
Mel Gormanb8e83b92013-07-03 15:01:45 -07005153 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07005154 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07005155 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07005156 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07005157 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07005158 break;
5159
5160 /*
5161 * Raise priority if scanning rate is too low or there was no
5162 * progress in reclaiming pages
5163 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07005164 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08005165 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
5166
5167 /*
5168 * If reclaim made no progress for a boost, stop reclaim as
5169 * IO cannot be queued and it could be an infinite loop in
5170 * extreme circumstances.
5171 */
5172 if (nr_boost_reclaim && !nr_reclaimed)
5173 break;
5174
Johannes Weinerc73322d2017-05-03 14:51:51 -07005175 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07005176 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07005177 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005178
Johannes Weinerc73322d2017-05-03 14:51:51 -07005179 if (!sc.nr_reclaimed)
5180 pgdat->kswapd_failures++;
5181
Mel Gormanb8e83b92013-07-03 15:01:45 -07005182out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07005183 clear_reclaim_active(pgdat, highest_zoneidx);
5184
Mel Gorman1c308442018-12-28 00:35:52 -08005185 /* If reclaim was boosted, account for the reclaim done in this pass */
5186 if (boosted) {
5187 unsigned long flags;
5188
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005189 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08005190 if (!zone_boosts[i])
5191 continue;
5192
5193 /* Increments are under the zone lock */
5194 zone = pgdat->node_zones + i;
5195 spin_lock_irqsave(&zone->lock, flags);
5196 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
5197 spin_unlock_irqrestore(&zone->lock, flags);
5198 }
5199
5200 /*
5201 * As there is now likely space, wakeup kcompact to defragment
5202 * pageblocks.
5203 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005204 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08005205 }
5206
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005207 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07005208 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07005209 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005210 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07005211
Mel Gorman0abdee22011-01-13 15:46:22 -08005212 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07005213 * Return the order kswapd stopped reclaiming at as
5214 * prepare_kswapd_sleep() takes it into account. If another caller
5215 * entered the allocator slow path while kswapd was awake, order will
5216 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08005217 */
Mel Gorman1d82de62016-07-28 15:45:43 -07005218 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005219}
5220
Mel Gormane716f2e2017-05-03 14:53:45 -07005221/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005222 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
5223 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
5224 * not a valid index then either kswapd runs for first time or kswapd couldn't
5225 * sleep after previous reclaim attempt (node is still unbalanced). In that
5226 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07005227 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005228static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
5229 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07005230{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005231 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005232
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005233 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07005234}
5235
Mel Gorman38087d92016-07-28 15:45:49 -07005236static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005237 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005238{
5239 long remaining = 0;
5240 DEFINE_WAIT(wait);
5241
5242 if (freezing(current) || kthread_should_stop())
5243 return;
5244
5245 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
5246
Shantanu Goel333b0a42017-05-03 14:53:38 -07005247 /*
5248 * Try to sleep for a short interval. Note that kcompactd will only be
5249 * woken if it is possible to sleep for a short interval. This is
5250 * deliberate on the assumption that if reclaim cannot keep an
5251 * eligible zone balanced that it's also unlikely that compaction will
5252 * succeed.
5253 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005254 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07005255 /*
5256 * Compaction records what page blocks it recently failed to
5257 * isolate pages from and skips them in the future scanning.
5258 * When kswapd is going to sleep, it is reasonable to assume
5259 * that pages and compaction may succeed so reset the cache.
5260 */
5261 reset_isolation_suitable(pgdat);
5262
5263 /*
5264 * We have freed the memory, now we should compact it to make
5265 * allocation of the requested order possible.
5266 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005267 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07005268
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005269 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07005270
5271 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005272 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07005273 * order. The values will either be from a wakeup request or
5274 * the previous request that slept prematurely.
5275 */
5276 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005277 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
5278 kswapd_highest_zoneidx(pgdat,
5279 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07005280
5281 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
5282 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07005283 }
5284
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005285 finish_wait(&pgdat->kswapd_wait, &wait);
5286 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
5287 }
5288
5289 /*
5290 * After a short sleep, check if it was a premature sleep. If not, then
5291 * go fully to sleep until explicitly woken up.
5292 */
Mel Gormand9f21d42016-07-28 15:46:41 -07005293 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005294 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005295 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
5296
5297 /*
5298 * vmstat counters are not perfectly accurate and the estimated
5299 * value for counters such as NR_FREE_PAGES can deviate from the
5300 * true value by nr_online_cpus * threshold. To avoid the zone
5301 * watermarks being breached while under pressure, we reduce the
5302 * per-cpu vmstat threshold while kswapd is awake and restore
5303 * them before going back to sleep.
5304 */
5305 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07005306
5307 if (!kthread_should_stop())
5308 schedule();
5309
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005310 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
5311 } else {
5312 if (remaining)
5313 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
5314 else
5315 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
5316 }
5317 finish_wait(&pgdat->kswapd_wait, &wait);
5318}
5319
Linus Torvalds1da177e2005-04-16 15:20:36 -07005320/*
5321 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005322 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005323 *
5324 * This basically trickles out pages so that we have _some_
5325 * free memory available even if there is no other activity
5326 * that frees anything up. This is needed for things like routing
5327 * etc, where we otherwise might have all activity going on in
5328 * asynchronous contexts that cannot page things out.
5329 *
5330 * If there are applications that are active memory-allocators
5331 * (most normal use), this basically shouldn't matter.
5332 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05305333int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005334{
Mel Gormane716f2e2017-05-03 14:53:45 -07005335 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005336 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07005337 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005338 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10305339 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005340
Rusty Russell174596a2009-01-01 10:12:29 +10305341 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07005342 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005343
5344 /*
5345 * Tell the memory management that we're a "memory allocator",
5346 * and that if we need more memory we should get access to it
5347 * regardless (see "__alloc_pages()"). "kswapd" should
5348 * never get caught in the normal page freeing logic.
5349 *
5350 * (Kswapd normally doesn't need memory anyway, but sometimes
5351 * you need a small amount of memory in order to be able to
5352 * page out something else, and this flag essentially protects
5353 * us from recursively trying to free more memory as we're
5354 * trying to free the first piece of memory in the first place).
5355 */
Christoph Lameter930d9152006-01-08 01:00:47 -08005356 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07005357 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07005358
Qian Cai5644e1fb2020-04-01 21:10:12 -07005359 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005360 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005361 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08005362 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07005363
Qian Cai5644e1fb2020-04-01 21:10:12 -07005364 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005365 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
5366 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07005367
Mel Gorman38087d92016-07-28 15:45:49 -07005368kswapd_try_sleep:
5369 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005370 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07005371
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005372 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08005373 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005374 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
5375 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005376 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005377 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005378
David Rientjes8fe23e02009-12-14 17:58:33 -08005379 ret = try_to_freeze();
5380 if (kthread_should_stop())
5381 break;
5382
5383 /*
5384 * We can speed up thawing tasks if we don't call balance_pgdat
5385 * after returning from the refrigerator
5386 */
Mel Gorman38087d92016-07-28 15:45:49 -07005387 if (ret)
5388 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07005389
Mel Gorman38087d92016-07-28 15:45:49 -07005390 /*
5391 * Reclaim begins at the requested order but if a high-order
5392 * reclaim fails then kswapd falls back to reclaiming for
5393 * order-0. If that happens, kswapd will consider sleeping
5394 * for the order it finished reclaiming at (reclaim_order)
5395 * but kcompactd is woken to compact for the original
5396 * request (alloc_order).
5397 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005398 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07005399 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005400 reclaim_order = balance_pgdat(pgdat, alloc_order,
5401 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07005402 if (reclaim_order < alloc_order)
5403 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005404 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08005405
Johannes Weiner71abdc12014-06-06 14:35:35 -07005406 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07005407
Linus Torvalds1da177e2005-04-16 15:20:36 -07005408 return 0;
5409}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05305410EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005411
5412/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07005413 * A zone is low on free memory or too fragmented for high-order memory. If
5414 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
5415 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
5416 * has failed or is not needed, still wake up kcompactd if only compaction is
5417 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005418 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07005419void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005420 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005421{
5422 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07005423 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005424
Mel Gorman6aa303d2016-09-01 16:14:55 -07005425 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07005426 return;
5427
David Rientjes5ecd9d42018-04-05 16:25:16 -07005428 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07005429 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07005430
Qian Cai5644e1fb2020-04-01 21:10:12 -07005431 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005432 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005433
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005434 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
5435 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005436
5437 if (READ_ONCE(pgdat->kswapd_order) < order)
5438 WRITE_ONCE(pgdat->kswapd_order, order);
5439
Con Kolivas8d0986e2005-09-13 01:25:07 -07005440 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07005441 return;
Mel Gormane1a55632016-07-28 15:46:26 -07005442
David Rientjes5ecd9d42018-04-05 16:25:16 -07005443 /* Hopeless node, leave it to direct reclaim if possible */
5444 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005445 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
5446 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07005447 /*
5448 * There may be plenty of free memory available, but it's too
5449 * fragmented for high-order allocations. Wake up kcompactd
5450 * and rely on compaction_suitable() to determine if it's
5451 * needed. If it fails, it will defer subsequent attempts to
5452 * ratelimit its work.
5453 */
5454 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005455 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07005456 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07005457 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07005458
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005459 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07005460 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07005461 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005462}
5463
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02005464#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07005465/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005466 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07005467 * freed pages.
5468 *
5469 * Rather than trying to age LRUs the aim is to preserve the overall
5470 * LRU order by reclaiming preferentially
5471 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07005472 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005473unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005474{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07005475 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005476 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07005477 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07005478 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005479 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07005480 .may_writepage = 1,
5481 .may_unmap = 1,
5482 .may_swap = 1,
5483 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07005484 };
Ying Hana09ed5e2011-05-24 17:12:26 -07005485 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005486 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07005487 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005488
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01005489 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07005490 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07005491 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08005492
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005493 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07005494
Andrew Morton1732d2b012019-07-16 16:26:15 -07005495 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07005496 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07005497 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07005498
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005499 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005500}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02005501#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07005502
Yasunori Goto3218ae12006-06-27 02:53:33 -07005503/*
5504 * This kswapd start function will be called by init and node-hot-add.
5505 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
5506 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07005507void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07005508{
5509 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05305510 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07005511
5512 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07005513 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07005514
Charan Teja Reddyd831f072021-02-05 17:47:57 +05305515 trace_android_vh_kswapd_per_node(nid, &skip, true);
5516 if (skip)
5517 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07005518 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
5519 if (IS_ERR(pgdat->kswapd)) {
5520 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02005521 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07005522 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07005523 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07005524 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07005525}
5526
David Rientjes8fe23e02009-12-14 17:58:33 -08005527/*
Jiang Liud8adde12012-07-11 14:01:52 -07005528 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07005529 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08005530 */
5531void kswapd_stop(int nid)
5532{
5533 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05305534 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08005535
Charan Teja Reddyd831f072021-02-05 17:47:57 +05305536 trace_android_vh_kswapd_per_node(nid, &skip, false);
5537 if (skip)
5538 return;
Jiang Liud8adde12012-07-11 14:01:52 -07005539 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08005540 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07005541 NODE_DATA(nid)->kswapd = NULL;
5542 }
David Rientjes8fe23e02009-12-14 17:58:33 -08005543}
5544
Linus Torvalds1da177e2005-04-16 15:20:36 -07005545static int __init kswapd_init(void)
5546{
Wei Yang6b700b52020-04-01 21:10:09 -07005547 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08005548
Linus Torvalds1da177e2005-04-16 15:20:36 -07005549 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08005550 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07005551 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005552 return 0;
5553}
5554
5555module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08005556
5557#ifdef CONFIG_NUMA
5558/*
Mel Gormana5f5f912016-07-28 15:46:32 -07005559 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08005560 *
Mel Gormana5f5f912016-07-28 15:46:32 -07005561 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08005562 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08005563 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005564int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08005565
Dave Hansen51998362021-02-24 12:09:15 -08005566/*
Mel Gormana5f5f912016-07-28 15:46:32 -07005567 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08005568 * of a node considered for each zone_reclaim. 4 scans 1/16th of
5569 * a zone.
5570 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005571#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08005572
Christoph Lameter9eeff232006-01-18 17:42:31 -08005573/*
Mel Gormana5f5f912016-07-28 15:46:32 -07005574 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07005575 * occur.
5576 */
5577int sysctl_min_unmapped_ratio = 1;
5578
5579/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07005580 * If the number of slab pages in a zone grows beyond this percentage then
5581 * slab reclaim needs to occur.
5582 */
5583int sysctl_min_slab_ratio = 5;
5584
Mel Gorman11fb9982016-07-28 15:46:20 -07005585static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07005586{
Mel Gorman11fb9982016-07-28 15:46:20 -07005587 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
5588 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
5589 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07005590
5591 /*
5592 * It's possible for there to be more file mapped pages than
5593 * accounted for by the pages on the file LRU lists because
5594 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
5595 */
5596 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
5597}
5598
5599/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07005600static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07005601{
Alexandru Moised031a152015-11-05 18:48:08 -08005602 unsigned long nr_pagecache_reclaimable;
5603 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07005604
5605 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07005606 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07005607 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07005608 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07005609 * a better estimate
5610 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005611 if (node_reclaim_mode & RECLAIM_UNMAP)
5612 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07005613 else
Mel Gormana5f5f912016-07-28 15:46:32 -07005614 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07005615
5616 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07005617 if (!(node_reclaim_mode & RECLAIM_WRITE))
5618 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07005619
5620 /* Watch for any possible underflows due to delta */
5621 if (unlikely(delta > nr_pagecache_reclaimable))
5622 delta = nr_pagecache_reclaimable;
5623
5624 return nr_pagecache_reclaimable - delta;
5625}
5626
Christoph Lameter0ff38492006-09-25 23:31:52 -07005627/*
Mel Gormana5f5f912016-07-28 15:46:32 -07005628 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08005629 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005630static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08005631{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08005632 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08005633 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08005634 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07005635 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08005636 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08005637 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005638 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07005639 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07005640 .priority = NODE_RECLAIM_PRIORITY,
5641 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
5642 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07005643 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005644 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08005645 };
Johannes Weiner57f29762021-08-19 19:04:27 -07005646 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08005647
Yafang Shao132bb8c2019-05-13 17:17:53 -07005648 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
5649 sc.gfp_mask);
5650
Christoph Lameter9eeff232006-01-18 17:42:31 -08005651 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07005652 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07005653 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08005654 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07005655 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08005656 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07005657 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08005658 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07005659 noreclaim_flag = memalloc_noreclaim_save();
5660 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07005661 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08005662
Mel Gormana5f5f912016-07-28 15:46:32 -07005663 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07005664 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07005665 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07005666 * priorities until we have enough memory freed.
5667 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07005668 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07005669 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005670 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07005671 }
Christoph Lameterc84db232006-02-01 03:05:29 -08005672
Andrew Morton1732d2b012019-07-16 16:26:15 -07005673 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07005674 current->flags &= ~PF_SWAPWRITE;
5675 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07005676 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07005677 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07005678
5679 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
5680
Rik van Riela79311c2009-01-06 14:40:01 -08005681 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08005682}
Andrew Morton179e9632006-03-22 00:08:18 -08005683
Mel Gormana5f5f912016-07-28 15:46:32 -07005684int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08005685{
David Rientjesd773ed62007-10-16 23:26:01 -07005686 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08005687
5688 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07005689 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07005690 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07005691 *
Christoph Lameter96146342006-07-03 00:24:13 -07005692 * A small portion of unmapped file backed pages is needed for
5693 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07005694 * thrown out if the node is overallocated. So we do not reclaim
5695 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07005696 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08005697 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005698 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07005699 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
5700 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07005701 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08005702
5703 /*
David Rientjesd773ed62007-10-16 23:26:01 -07005704 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08005705 */
Mel Gormand0164ad2015-11-06 16:28:21 -08005706 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07005707 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08005708
5709 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07005710 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08005711 * have associated processors. This will favor the local processor
5712 * over remote processors and spread off node memory allocations
5713 * as wide as possible.
5714 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005715 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
5716 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07005717
Mel Gormana5f5f912016-07-28 15:46:32 -07005718 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
5719 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07005720
Mel Gormana5f5f912016-07-28 15:46:32 -07005721 ret = __node_reclaim(pgdat, gfp_mask, order);
5722 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07005723
Mel Gorman24cf725182009-06-16 15:33:23 -07005724 if (!ret)
5725 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
5726
David Rientjesd773ed62007-10-16 23:26:01 -07005727 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08005728}
Christoph Lameter9eeff232006-01-18 17:42:31 -08005729#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07005730
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005731/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005732 * check_move_unevictable_pages - check pages for evictability and move to
5733 * appropriate zone lru list
5734 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005735 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005736 * Checks pages for evictability, if an evictable page is in the unevictable
5737 * lru list, moves it to the appropriate evictable lru list. This function
5738 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005739 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005740void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005741{
Alex Shi6168d0d2020-12-15 12:34:29 -08005742 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08005743 int pgscanned = 0;
5744 int pgrescued = 0;
5745 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005746
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005747 for (i = 0; i < pvec->nr; i++) {
5748 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07005749 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07005750
Hugh Dickins8d8869c2020-09-18 21:20:12 -07005751 if (PageTransTail(page))
5752 continue;
5753
5754 nr_pages = thp_nr_pages(page);
5755 pgscanned += nr_pages;
5756
Alex Shid25b5bd2020-12-15 12:34:16 -08005757 /* block memcg migration during page moving between lru */
5758 if (!TestClearPageLRU(page))
5759 continue;
5760
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08005761 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08005762 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08005763 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08005764 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08005765 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07005766 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08005767 }
Alex Shid25b5bd2020-12-15 12:34:16 -08005768 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005769 }
Hugh Dickins24513262012-01-20 14:34:21 -08005770
Alex Shi6168d0d2020-12-15 12:34:29 -08005771 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08005772 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
5773 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08005774 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08005775 } else if (pgscanned) {
5776 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08005777 }
Hugh Dickins850465792012-01-20 14:34:19 -08005778}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005779EXPORT_SYMBOL_GPL(check_move_unevictable_pages);