blob: 5f4b0873112b320fddaa19b524bc46785cf30517 [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
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700708 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700709 if (freeable == 0 || freeable == SHRINK_EMPTY)
710 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000711
712 /*
713 * copy the current shrinker scan count into a local variable
714 * and zero it so that other concurrent shrinker invocations
715 * don't also do this scanning work.
716 */
Yang Shi86750832021-05-04 18:36:36 -0700717 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000718
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700719 if (shrinker->seeks) {
720 delta = freeable >> priority;
721 delta *= 4;
722 do_div(delta, shrinker->seeks);
723 } else {
724 /*
725 * These objects don't require any IO to create. Trim
726 * them aggressively under memory pressure to keep
727 * them from causing refetches in the IO caches.
728 */
729 delta = freeable / 2;
730 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700731
Yang Shi18bb4732021-05-04 18:36:45 -0700732 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000733 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700734 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000735
736 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800737 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000738
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800739 /*
740 * Normally, we should not scan less than batch_size objects in one
741 * pass to avoid too frequent shrinker calls, but if the slab has less
742 * than batch_size objects in total and we are really tight on memory,
743 * we will try to reclaim all available objects, otherwise we can end
744 * up failing allocations although there are plenty of reclaimable
745 * objects spread over several slabs with usage less than the
746 * batch_size.
747 *
748 * We detect the "tight on memory" situations by looking at the total
749 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700750 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800751 * scanning at high prio and therefore should try to reclaim as much as
752 * possible.
753 */
754 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700755 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000756 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800757 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000758
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800759 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700760 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000761 ret = shrinker->scan_objects(shrinker, shrinkctl);
762 if (ret == SHRINK_STOP)
763 break;
764 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000765
Chris Wilsond460acb2017-09-06 16:19:26 -0700766 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
767 total_scan -= shrinkctl->nr_scanned;
768 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000769
770 cond_resched();
771 }
772
Yang Shi18bb4732021-05-04 18:36:45 -0700773 /*
774 * The deferred work is increased by any new work (delta) that wasn't
775 * done, decreased by old deferred work that was done now.
776 *
777 * And it is capped to two times of the freeable items.
778 */
779 next_deferred = max_t(long, (nr + delta - scanned), 0);
780 next_deferred = min(next_deferred, (2 * freeable));
781
Glauber Costa1d3d4432013-08-28 10:18:04 +1000782 /*
783 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700784 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000785 */
Yang Shi86750832021-05-04 18:36:36 -0700786 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000787
Yang Shi8efb4b52021-05-04 18:36:08 -0700788 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000789 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700790}
791
Yang Shi0a432dc2019-09-23 15:38:12 -0700792#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700793static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
794 struct mem_cgroup *memcg, int priority)
795{
Yang Shie4262c42021-05-04 18:36:23 -0700796 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700797 unsigned long ret, freed = 0;
798 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700799
Yang Shi0a432dc2019-09-23 15:38:12 -0700800 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700801 return 0;
802
803 if (!down_read_trylock(&shrinker_rwsem))
804 return 0;
805
Yang Shi468ab842021-05-04 18:36:26 -0700806 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700807 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700808 goto unlock;
809
Yang Shie4262c42021-05-04 18:36:23 -0700810 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700811 struct shrink_control sc = {
812 .gfp_mask = gfp_mask,
813 .nid = nid,
814 .memcg = memcg,
815 };
816 struct shrinker *shrinker;
817
818 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700819 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700820 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700821 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700822 continue;
823 }
824
Yang Shi0a432dc2019-09-23 15:38:12 -0700825 /* Call non-slab shrinkers even though kmem is disabled */
826 if (!memcg_kmem_enabled() &&
827 !(shrinker->flags & SHRINKER_NONSLAB))
828 continue;
829
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700830 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700831 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700832 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700833 /*
834 * After the shrinker reported that it had no objects to
835 * free, but before we cleared the corresponding bit in
836 * the memcg shrinker map, a new object might have been
837 * added. To make sure, we have the bit set in this
838 * case, we invoke the shrinker one more time and reset
839 * the bit if it reports that it is not empty anymore.
840 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700841 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700842 *
843 * list_lru_add() shrink_slab_memcg()
844 * list_add_tail() clear_bit()
845 * <MB> <MB>
846 * set_bit() do_shrink_slab()
847 */
848 smp_mb__after_atomic();
849 ret = do_shrink_slab(&sc, shrinker, priority);
850 if (ret == SHRINK_EMPTY)
851 ret = 0;
852 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700853 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700854 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700855 freed += ret;
856
857 if (rwsem_is_contended(&shrinker_rwsem)) {
858 freed = freed ? : 1;
859 break;
860 }
861 }
862unlock:
863 up_read(&shrinker_rwsem);
864 return freed;
865}
Yang Shi0a432dc2019-09-23 15:38:12 -0700866#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700867static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
868 struct mem_cgroup *memcg, int priority)
869{
870 return 0;
871}
Yang Shi0a432dc2019-09-23 15:38:12 -0700872#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700873
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800874/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800875 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800876 * @gfp_mask: allocation context
877 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800878 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800879 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700880 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800881 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700882 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800883 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
884 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700885 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700886 * @memcg specifies the memory cgroup to target. Unaware shrinkers
887 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800888 *
Josef Bacik9092c712018-01-31 16:16:26 -0800889 * @priority is sc->priority, we take the number of objects and >> by priority
890 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700891 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800892 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700893 */
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800894static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
895 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800896 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700897{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700898 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700899 struct shrinker *shrinker;
900
Yang Shifa1e5122019-08-02 21:48:44 -0700901 /*
902 * The root memcg might be allocated even though memcg is disabled
903 * via "cgroup_disable=memory" boot parameter. This could make
904 * mem_cgroup_is_root() return false, then just run memcg slab
905 * shrink, but skip global shrink. This may result in premature
906 * oom.
907 */
908 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700909 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800910
Tetsuo Handae830c632018-04-05 16:23:35 -0700911 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700912 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700913
914 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800915 struct shrink_control sc = {
916 .gfp_mask = gfp_mask,
917 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800918 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800919 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800920
Kirill Tkhai9b996462018-08-17 15:48:21 -0700921 ret = do_shrink_slab(&sc, shrinker, priority);
922 if (ret == SHRINK_EMPTY)
923 ret = 0;
924 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800925 /*
926 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700927 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800928 * by parallel ongoing shrinking.
929 */
930 if (rwsem_is_contended(&shrinker_rwsem)) {
931 freed = freed ? : 1;
932 break;
933 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700934 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800935
Linus Torvalds1da177e2005-04-16 15:20:36 -0700936 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700937out:
938 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000939 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700940}
941
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800942void drop_slab_node(int nid)
943{
944 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700945 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800946
947 do {
948 struct mem_cgroup *memcg = NULL;
949
Chunxin Zang069c4112020-10-13 16:56:46 -0700950 if (fatal_signal_pending(current))
951 return;
952
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800953 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700954 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800955 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800956 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800957 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700958 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800959}
960
961void drop_slab(void)
962{
963 int nid;
964
965 for_each_online_node(nid)
966 drop_slab_node(nid);
967}
968
Linus Torvalds1da177e2005-04-16 15:20:36 -0700969static inline int is_page_cache_freeable(struct page *page)
970{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700971 /*
972 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400973 * that isolated the page, the page cache and optional buffer
974 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700975 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -0700976 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400977 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700978}
979
Yang Shicb165562019-11-30 17:55:28 -0800980static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700981{
Christoph Lameter930d9152006-01-08 01:00:47 -0800982 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700983 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400984 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700985 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400986 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700987 return 1;
988 return 0;
989}
990
991/*
992 * We detected a synchronous write error writing a page out. Probably
993 * -ENOSPC. We need to propagate that into the address_space for a subsequent
994 * fsync(), msync() or close().
995 *
996 * The tricky part is that after writepage we cannot touch the mapping: nothing
997 * prevents it from being freed up. But we have a ref on the page and once
998 * that page is locked, the mapping is pinned.
999 *
1000 * We're allowed to run sleeping lock_page() here because we know the caller has
1001 * __GFP_FS.
1002 */
1003static void handle_write_error(struct address_space *mapping,
1004 struct page *page, int error)
1005{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001006 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001007 if (page_mapping(page) == mapping)
1008 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001009 unlock_page(page);
1010}
1011
Christoph Lameter04e62a22006-06-23 02:03:38 -07001012/* possible outcome of pageout() */
1013typedef enum {
1014 /* failed to write page out, page is locked */
1015 PAGE_KEEP,
1016 /* move page to the active list, page is locked */
1017 PAGE_ACTIVATE,
1018 /* page has been sent to the disk successfully, page is unlocked */
1019 PAGE_SUCCESS,
1020 /* page is clean and locked */
1021 PAGE_CLEAN,
1022} pageout_t;
1023
Linus Torvalds1da177e2005-04-16 15:20:36 -07001024/*
Andrew Morton1742f192006-03-22 00:08:21 -08001025 * pageout is called by shrink_page_list() for each dirty page.
1026 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001027 */
Yang Shicb165562019-11-30 17:55:28 -08001028static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001029{
1030 /*
1031 * If the page is dirty, only perform writeback if that write
1032 * will be non-blocking. To prevent this allocation from being
1033 * stalled by pagecache activity. But note that there may be
1034 * stalls if we need to run get_block(). We could test
1035 * PagePrivate for that.
1036 *
Al Viro81742022014-04-03 03:17:43 -04001037 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001038 * this page's queue, we can perform writeback even if that
1039 * will block.
1040 *
1041 * If the page is swapcache, write it back even if that would
1042 * block, for some throttling. This happens by accident, because
1043 * swap_backing_dev_info is bust: it doesn't reflect the
1044 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001045 */
1046 if (!is_page_cache_freeable(page))
1047 return PAGE_KEEP;
1048 if (!mapping) {
1049 /*
1050 * Some data journaling orphaned pages can have
1051 * page->mapping == NULL while being dirty with clean buffers.
1052 */
David Howells266cf652009-04-03 16:42:36 +01001053 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001054 if (try_to_free_buffers(page)) {
1055 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001056 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001057 return PAGE_CLEAN;
1058 }
1059 }
1060 return PAGE_KEEP;
1061 }
1062 if (mapping->a_ops->writepage == NULL)
1063 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001064 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001065 return PAGE_KEEP;
1066
1067 if (clear_page_dirty_for_io(page)) {
1068 int res;
1069 struct writeback_control wbc = {
1070 .sync_mode = WB_SYNC_NONE,
1071 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001072 .range_start = 0,
1073 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001074 .for_reclaim = 1,
1075 };
1076
1077 SetPageReclaim(page);
1078 res = mapping->a_ops->writepage(page, &wbc);
1079 if (res < 0)
1080 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001081 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001082 ClearPageReclaim(page);
1083 return PAGE_ACTIVATE;
1084 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001085
Linus Torvalds1da177e2005-04-16 15:20:36 -07001086 if (!PageWriteback(page)) {
1087 /* synchronous write or broken a_ops? */
1088 ClearPageReclaim(page);
1089 }
yalin wang3aa23852016-01-14 15:18:30 -08001090 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001091 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001092 return PAGE_SUCCESS;
1093 }
1094
1095 return PAGE_CLEAN;
1096}
1097
Andrew Mortona649fd92006-10-17 00:09:36 -07001098/*
Nick Piggine2867812008-07-25 19:45:30 -07001099 * Same as remove_mapping, but if the page is removed from the mapping, it
1100 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001101 */
Johannes Weinera5289102014-04-03 14:47:51 -07001102static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001103 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001104{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001105 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001106 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001107
Nick Piggin28e4d962006-09-25 23:31:23 -07001108 BUG_ON(!PageLocked(page));
1109 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001110
Johannes Weiner30472502021-09-02 14:53:18 -07001111 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001112 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001113 * The non racy check for a busy page.
1114 *
1115 * Must be careful with the order of the tests. When someone has
1116 * a ref to the page, it may be possible that they dirty it then
1117 * drop the reference. So if PageDirty is tested before page_count
1118 * here, then the following race may occur:
1119 *
1120 * get_user_pages(&page);
1121 * [user mapping goes away]
1122 * write_to(page);
1123 * !PageDirty(page) [good]
1124 * SetPageDirty(page);
1125 * put_page(page);
1126 * !page_count(page) [good, discard it]
1127 *
1128 * [oops, our write_to data is lost]
1129 *
1130 * Reversing the order of the tests ensures such a situation cannot
1131 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001132 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001133 *
1134 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001135 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001136 */
William Kucharski906d2782019-10-18 20:20:33 -07001137 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001138 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001139 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001140 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001141 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001142 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001143 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001144 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001145
1146 if (PageSwapCache(page)) {
1147 swp_entry_t swap = { .val = page_private(page) };
Yu Zhaoa1537a62022-01-27 20:32:37 -07001148
1149 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001150 if (reclaimed && !mapping_exiting(mapping))
1151 shadow = workingset_eviction(page, target_memcg);
Yu Zhaoa1537a62022-01-27 20:32:37 -07001152 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001153 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001154 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001155 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001156 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001157 void (*freepage)(struct page *);
1158
1159 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001160 /*
1161 * Remember a shadow entry for reclaimed file cache in
1162 * order to detect refaults, thus thrashing, later on.
1163 *
1164 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001165 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001166 * inode reclaim needs to empty out the radix tree or
1167 * the nodes are lost. Don't plant shadows behind its
1168 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001169 *
1170 * We also don't store shadows for DAX mappings because the
1171 * only page cache pages found in these are zero pages
1172 * covering holes, and because we don't want to mix DAX
1173 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001174 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001175 */
Huang Ying9de4f222020-04-06 20:04:41 -07001176 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001177 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001178 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001179 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001180 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001181
1182 if (freepage != NULL)
1183 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001184 }
1185
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001186 return 1;
1187
1188cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001189 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001190 return 0;
1191}
1192
Linus Torvalds1da177e2005-04-16 15:20:36 -07001193/*
Nick Piggine2867812008-07-25 19:45:30 -07001194 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1195 * someone else has a ref on the page, abort and return 0. If it was
1196 * successfully detached, return 1. Assumes the caller has a single ref on
1197 * this page.
1198 */
1199int remove_mapping(struct address_space *mapping, struct page *page)
1200{
Johannes Weinerb9107182019-11-30 17:55:59 -08001201 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001202 /*
1203 * Unfreezing the refcount with 1 rather than 2 effectively
1204 * drops the pagecache ref for us without requiring another
1205 * atomic operation.
1206 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001207 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001208 return 1;
1209 }
1210 return 0;
1211}
1212
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001213/**
1214 * putback_lru_page - put previously isolated page onto appropriate LRU list
1215 * @page: page to be put back to appropriate lru list
1216 *
1217 * Add previously isolated @page to appropriate LRU list.
1218 * Page may still be unevictable for other reasons.
1219 *
1220 * lru_lock must not be held, interrupts must be enabled.
1221 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001222void putback_lru_page(struct page *page)
1223{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001224 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001225 put_page(page); /* drop ref from isolate */
1226}
1227
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001228enum page_references {
1229 PAGEREF_RECLAIM,
1230 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001231 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001232 PAGEREF_ACTIVATE,
1233};
1234
1235static enum page_references page_check_references(struct page *page,
1236 struct scan_control *sc)
1237{
Johannes Weiner645747462010-03-05 13:42:22 -08001238 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001239 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001240
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001241 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1242 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001243 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001244
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001245 /*
1246 * Mlock lost the isolation race with us. Let try_to_unmap()
1247 * move the page to the unevictable list.
1248 */
1249 if (vm_flags & VM_LOCKED)
1250 return PAGEREF_RECLAIM;
1251
Johannes Weiner645747462010-03-05 13:42:22 -08001252 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001253 /*
1254 * All mapped pages start out with page table
1255 * references from the instantiating fault, so we need
1256 * to look twice if a mapped file page is used more
1257 * than once.
1258 *
1259 * Mark it and spare it for another trip around the
1260 * inactive list. Another page table reference will
1261 * lead to its activation.
1262 *
1263 * Note: the mark is set for activated pages as well
1264 * so that recently deactivated but used pages are
1265 * quickly recovered.
1266 */
1267 SetPageReferenced(page);
1268
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001269 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001270 return PAGEREF_ACTIVATE;
1271
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001272 /*
1273 * Activate file-backed executable pages after first usage.
1274 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001275 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001276 return PAGEREF_ACTIVATE;
1277
Johannes Weiner645747462010-03-05 13:42:22 -08001278 return PAGEREF_KEEP;
1279 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001280
1281 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001282 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001283 return PAGEREF_RECLAIM_CLEAN;
1284
1285 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001286}
1287
Mel Gormane2be15f2013-07-03 15:01:57 -07001288/* Check if a page is dirty or under writeback */
1289static void page_check_dirty_writeback(struct page *page,
1290 bool *dirty, bool *writeback)
1291{
Mel Gormanb4597222013-07-03 15:02:05 -07001292 struct address_space *mapping;
1293
Mel Gormane2be15f2013-07-03 15:01:57 -07001294 /*
1295 * Anonymous pages are not handled by flushers and must be written
1296 * from reclaim context. Do not stall reclaim based on them
1297 */
Huang Ying9de4f222020-04-06 20:04:41 -07001298 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001299 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001300 *dirty = false;
1301 *writeback = false;
1302 return;
1303 }
1304
1305 /* By default assume that the page flags are accurate */
1306 *dirty = PageDirty(page);
1307 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001308
1309 /* Verify dirty/writeback state if the filesystem supports it */
1310 if (!page_has_private(page))
1311 return;
1312
1313 mapping = page_mapping(page);
1314 if (mapping && mapping->a_ops->is_dirty_writeback)
1315 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001316}
1317
Dave Hansen26aa2d12021-09-02 14:59:16 -07001318static struct page *alloc_demote_page(struct page *page, unsigned long node)
1319{
1320 struct migration_target_control mtc = {
1321 /*
1322 * Allocate from 'node', or fail quickly and quietly.
1323 * When this happens, 'page' will likely just be discarded
1324 * instead of migrated.
1325 */
1326 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1327 __GFP_THISNODE | __GFP_NOWARN |
1328 __GFP_NOMEMALLOC | GFP_NOWAIT,
1329 .nid = node
1330 };
1331
1332 return alloc_migration_target(page, (unsigned long)&mtc);
1333}
1334
1335/*
1336 * Take pages on @demote_list and attempt to demote them to
1337 * another node. Pages which are not demoted are left on
1338 * @demote_pages.
1339 */
1340static unsigned int demote_page_list(struct list_head *demote_pages,
1341 struct pglist_data *pgdat)
1342{
1343 int target_nid = next_demotion_node(pgdat->node_id);
1344 unsigned int nr_succeeded;
1345 int err;
1346
1347 if (list_empty(demote_pages))
1348 return 0;
1349
1350 if (target_nid == NUMA_NO_NODE)
1351 return 0;
1352
1353 /* Demotion ignores all cpuset and mempolicy settings */
1354 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1355 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1356 &nr_succeeded);
1357
Yang Shi668e4142021-09-02 14:59:19 -07001358 if (current_is_kswapd())
1359 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1360 else
1361 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1362
Dave Hansen26aa2d12021-09-02 14:59:16 -07001363 return nr_succeeded;
1364}
1365
Nick Piggine2867812008-07-25 19:45:30 -07001366/*
Andrew Morton1742f192006-03-22 00:08:21 -08001367 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001368 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001369static unsigned int shrink_page_list(struct list_head *page_list,
1370 struct pglist_data *pgdat,
1371 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001372 struct reclaim_stat *stat,
1373 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001374{
1375 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001376 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001377 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001378 unsigned int nr_reclaimed = 0;
1379 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001380 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001381
Kirill Tkhai060f0052019-03-05 15:48:15 -08001382 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001383 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001384 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001385
Dave Hansen26aa2d12021-09-02 14:59:16 -07001386retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001387 while (!list_empty(page_list)) {
1388 struct address_space *mapping;
1389 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001390 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001391 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001392 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001393
1394 cond_resched();
1395
1396 page = lru_to_page(page_list);
1397 list_del(&page->lru);
1398
Nick Piggin529ae9a2008-08-02 12:01:03 +02001399 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001400 goto keep;
1401
Sasha Levin309381fea2014-01-23 15:52:54 -08001402 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001403
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001404 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001405
1406 /* Account the number of base pages even though THP */
1407 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001408
Hugh Dickins39b5f292012-10-08 16:33:18 -07001409 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001410 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001411
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001412 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001413 goto keep_locked;
1414
Yu Zhaoafd94c92022-01-27 20:43:22 -07001415 /* page_update_gen() tried to promote this page? */
1416 if (lru_gen_enabled() && !ignore_references &&
1417 page_mapped(page) && PageReferenced(page))
1418 goto keep_locked;
1419
Andy Whitcroftc661b072007-08-22 14:01:26 -07001420 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1421 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1422
Mel Gorman283aba92013-07-03 15:01:51 -07001423 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001424 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001425 * reclaim_congested which affects wait_iff_congested. kswapd
1426 * will stall and start writing pages if the tail of the LRU
1427 * is all dirty unqueued pages.
1428 */
1429 page_check_dirty_writeback(page, &dirty, &writeback);
1430 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001431 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001432
1433 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001434 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001435
Mel Gormand04e8ac2013-07-03 15:02:03 -07001436 /*
1437 * Treat this page as congested if the underlying BDI is or if
1438 * pages are cycling through the LRU so quickly that the
1439 * pages marked for immediate reclaim are making it to the
1440 * end of the LRU a second time.
1441 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001442 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001443 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001444 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001445 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001446 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001447
1448 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001449 * If a page at the tail of the LRU is under writeback, there
1450 * are three cases to consider.
1451 *
1452 * 1) If reclaim is encountering an excessive number of pages
1453 * under writeback and this page is both under writeback and
1454 * PageReclaim then it indicates that pages are being queued
1455 * for IO but are being recycled through the LRU before the
1456 * IO can complete. Waiting on the page itself risks an
1457 * indefinite stall if it is impossible to writeback the
1458 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001459 * note that the LRU is being scanned too quickly and the
1460 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001461 *
Tejun Heo97c93412015-05-22 18:23:36 -04001462 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001463 * not marked for immediate reclaim, or the caller does not
1464 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1465 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001466 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001467 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001468 * Require may_enter_fs because we would wait on fs, which
1469 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001470 * enter reclaim, and deadlock if it waits on a page for
1471 * which it is needed to do the write (loop masks off
1472 * __GFP_IO|__GFP_FS for this reason); but more thought
1473 * would probably show more reasons.
1474 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001475 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001476 * PageReclaim. memcg does not have any dirty pages
1477 * throttling so we could easily OOM just because too many
1478 * pages are in writeback and there is nothing else to
1479 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001480 *
1481 * In cases 1) and 2) we activate the pages to get them out of
1482 * the way while we continue scanning for clean pages on the
1483 * inactive list and refilling from the active list. The
1484 * observation here is that waiting for disk writes is more
1485 * expensive than potentially causing reloads down the line.
1486 * Since they're marked for immediate reclaim, they won't put
1487 * memory pressure on the cache working set any longer than it
1488 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001489 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001490 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001491 /* Case 1 above */
1492 if (current_is_kswapd() &&
1493 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001494 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001495 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001496 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001497
1498 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001499 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001500 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001501 /*
1502 * This is slightly racy - end_page_writeback()
1503 * might have just cleared PageReclaim, then
1504 * setting PageReclaim here end up interpreted
1505 * as PageReadahead - but that does not matter
1506 * enough to care. What we do want is for this
1507 * page to have PageReclaim set next time memcg
1508 * reclaim reaches the tests above, so it will
1509 * then wait_on_page_writeback() to avoid OOM;
1510 * and it's also appropriate in global reclaim.
1511 */
1512 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001513 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001514 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001515
1516 /* Case 3 above */
1517 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001518 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001519 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001520 /* then go back and try same page again */
1521 list_add_tail(&page->lru, page_list);
1522 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001523 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001524 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001525
Minchan Kim8940b342019-09-25 16:49:11 -07001526 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001527 references = page_check_references(page, sc);
1528
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001529 switch (references) {
1530 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001531 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001532 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001533 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001534 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001535 case PAGEREF_RECLAIM:
1536 case PAGEREF_RECLAIM_CLEAN:
1537 ; /* try to reclaim the page below */
1538 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001539
Linus Torvalds1da177e2005-04-16 15:20:36 -07001540 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001541 * Before reclaiming the page, try to relocate
1542 * its contents to another node.
1543 */
1544 if (do_demote_pass &&
1545 (thp_migration_supported() || !PageTransHuge(page))) {
1546 list_add(&page->lru, &demote_pages);
1547 unlock_page(page);
1548 continue;
1549 }
1550
1551 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001552 * Anonymous process memory has backing store?
1553 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001554 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001555 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001556 if (PageAnon(page) && PageSwapBacked(page)) {
1557 if (!PageSwapCache(page)) {
1558 if (!(sc->gfp_mask & __GFP_IO))
1559 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001560 if (page_maybe_dma_pinned(page))
1561 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001562 if (PageTransHuge(page)) {
1563 /* cannot split THP, skip it */
1564 if (!can_split_huge_page(page, NULL))
1565 goto activate_locked;
1566 /*
1567 * Split pages without a PMD map right
1568 * away. Chances are some or all of the
1569 * tail pages can be freed without IO.
1570 */
1571 if (!compound_mapcount(page) &&
1572 split_huge_page_to_list(page,
1573 page_list))
1574 goto activate_locked;
1575 }
1576 if (!add_to_swap(page)) {
1577 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001578 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001579 /* Fallback to swap normal pages */
1580 if (split_huge_page_to_list(page,
1581 page_list))
1582 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001583#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1584 count_vm_event(THP_SWPOUT_FALLBACK);
1585#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001586 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001587 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001588 }
Minchan Kim0f074652017-07-06 15:37:24 -07001589
Kirill Tkhai4b793062020-04-01 21:10:18 -07001590 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001591
1592 /* Adding to swap updated mapping */
1593 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001594 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001595 } else if (unlikely(PageTransHuge(page))) {
1596 /* Split file THP */
1597 if (split_huge_page_to_list(page, page_list))
1598 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001599 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001600
1601 /*
Yang Shi98879b32019-07-11 20:59:30 -07001602 * THP may get split above, need minus tail pages and update
1603 * nr_pages to avoid accounting tail pages twice.
1604 *
1605 * The tail pages that are added into swap cache successfully
1606 * reach here.
1607 */
1608 if ((nr_pages > 1) && !PageTransHuge(page)) {
1609 sc->nr_scanned -= (nr_pages - 1);
1610 nr_pages = 1;
1611 }
1612
1613 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001614 * The page is mapped into the page tables of one or more
1615 * processes. Try to unmap it here.
1616 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001617 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001618 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001619 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001620
1621 if (unlikely(PageTransHuge(page)))
1622 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001623
Yang Shi1fb08ac2021-06-30 18:52:01 -07001624 try_to_unmap(page, flags);
1625 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001626 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001627 if (!was_swapbacked && PageSwapBacked(page))
1628 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001629 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001630 }
1631 }
1632
1633 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001634 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001635 * Only kswapd can writeback filesystem pages
1636 * to avoid risk of stack overflow. But avoid
1637 * injecting inefficient single-page IO into
1638 * flusher writeback as much as possible: only
1639 * write pages when we've encountered many
1640 * dirty pages, and when we've already scanned
1641 * the rest of the LRU for clean pages and see
1642 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001643 */
Huang Ying9de4f222020-04-06 20:04:41 -07001644 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001645 (!current_is_kswapd() || !PageReclaim(page) ||
1646 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001647 /*
1648 * Immediately reclaim when written back.
1649 * Similar in principal to deactivate_page()
1650 * except we already have the page isolated
1651 * and know it's dirty
1652 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001653 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001654 SetPageReclaim(page);
1655
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001656 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001657 }
1658
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001659 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001660 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001661 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001662 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001663 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001664 goto keep_locked;
1665
Mel Gormand950c942015-09-04 15:47:35 -07001666 /*
1667 * Page is dirty. Flush the TLB if a writable entry
1668 * potentially exists to avoid CPU writes after IO
1669 * starts and then write it out here.
1670 */
1671 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001672 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001673 case PAGE_KEEP:
1674 goto keep_locked;
1675 case PAGE_ACTIVATE:
1676 goto activate_locked;
1677 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001678 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001679
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001680 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001681 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001682 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001683 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001684
Linus Torvalds1da177e2005-04-16 15:20:36 -07001685 /*
1686 * A synchronous write - probably a ramdisk. Go
1687 * ahead and try to reclaim the page.
1688 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001689 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001690 goto keep;
1691 if (PageDirty(page) || PageWriteback(page))
1692 goto keep_locked;
1693 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001694 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001695 case PAGE_CLEAN:
1696 ; /* try to free the page below */
1697 }
1698 }
1699
1700 /*
1701 * If the page has buffers, try to free the buffer mappings
1702 * associated with this page. If we succeed we try to free
1703 * the page as well.
1704 *
1705 * We do this even if the page is PageDirty().
1706 * try_to_release_page() does not perform I/O, but it is
1707 * possible for a page to have PageDirty set, but it is actually
1708 * clean (all its buffers are clean). This happens if the
1709 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001710 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001711 * try_to_release_page() will discover that cleanness and will
1712 * drop the buffers and mark the page clean - it can be freed.
1713 *
1714 * Rarely, pages can have buffers and no ->mapping. These are
1715 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001716 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001717 * and if that worked, and the page is no longer mapped into
1718 * process address space (page_count == 1) it can be freed.
1719 * Otherwise, leave the page on the LRU so it is swappable.
1720 */
David Howells266cf652009-04-03 16:42:36 +01001721 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001722 if (!try_to_release_page(page, sc->gfp_mask))
1723 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001724 if (!mapping && page_count(page) == 1) {
1725 unlock_page(page);
1726 if (put_page_testzero(page))
1727 goto free_it;
1728 else {
1729 /*
1730 * rare race with speculative reference.
1731 * the speculative reference will free
1732 * this page shortly, so we may
1733 * increment nr_reclaimed here (and
1734 * leave it off the LRU).
1735 */
1736 nr_reclaimed++;
1737 continue;
1738 }
1739 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001740 }
1741
Shaohua Li802a3a92017-05-03 14:52:32 -07001742 if (PageAnon(page) && !PageSwapBacked(page)) {
1743 /* follow __remove_mapping for reference */
1744 if (!page_ref_freeze(page, 1))
1745 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001746 /*
1747 * The page has only one reference left, which is
1748 * from the isolation. After the caller puts the
1749 * page back on lru and drops the reference, the
1750 * page will be freed anyway. It doesn't matter
1751 * which lru it goes. So we don't bother checking
1752 * PageDirty here.
1753 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001754 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001755 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001756 } else if (!mapping || !__remove_mapping(mapping, page, true,
1757 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001758 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001759
1760 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001761free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001762 /*
1763 * THP may get swapped out in a whole, need account
1764 * all base pages.
1765 */
1766 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001767
1768 /*
1769 * Is there need to periodically free_page_list? It would
1770 * appear not as the counts should be low
1771 */
Yang Shi7ae88532019-09-23 15:38:09 -07001772 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001773 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001774 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001775 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001776 continue;
1777
Yang Shi98879b32019-07-11 20:59:30 -07001778activate_locked_split:
1779 /*
1780 * The tail pages that are failed to add into swap cache
1781 * reach here. Fixup nr_scanned and nr_pages.
1782 */
1783 if (nr_pages > 1) {
1784 sc->nr_scanned -= (nr_pages - 1);
1785 nr_pages = 1;
1786 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001787activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001788 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001789 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1790 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001791 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001792 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001793 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001794 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001795 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001796 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001797 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001798 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001799keep_locked:
1800 unlock_page(page);
1801keep:
1802 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001803 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001804 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001805 /* 'page_list' is always empty here */
1806
1807 /* Migrate pages selected for demotion */
1808 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1809 /* Pages that could not be demoted are still in @demote_pages */
1810 if (!list_empty(&demote_pages)) {
1811 /* Pages which failed to demoted go back on @page_list for retry: */
1812 list_splice_init(&demote_pages, page_list);
1813 do_demote_pass = false;
1814 goto retry;
1815 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001816
Yang Shi98879b32019-07-11 20:59:30 -07001817 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1818
Johannes Weiner747db952014-08-08 14:19:24 -07001819 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001820 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001821 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001822
Linus Torvalds1da177e2005-04-16 15:20:36 -07001823 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001824 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001825
Andrew Morton05ff5132006-03-22 00:08:20 -08001826 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001827}
1828
Maninder Singh730ec8c2020-06-03 16:01:18 -07001829unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001830 struct list_head *page_list)
1831{
1832 struct scan_control sc = {
1833 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001834 .may_unmap = 1,
1835 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001836 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001837 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001838 struct page *page, *next;
1839 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001840 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001841
1842 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001843 if (!PageHuge(page) && page_is_file_lru(page) &&
1844 !PageDirty(page) && !__PageMovable(page) &&
1845 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001846 ClearPageActive(page);
1847 list_move(&page->lru, &clean_pages);
1848 }
1849 }
1850
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001851 /*
1852 * We should be safe here since we are only dealing with file pages and
1853 * we are not kswapd and therefore cannot write dirty file pages. But
1854 * call memalloc_noreclaim_save() anyway, just in case these conditions
1855 * change in the future.
1856 */
1857 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001858 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001859 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001860 memalloc_noreclaim_restore(noreclaim_flag);
1861
Minchan Kim02c6de82012-10-08 16:31:55 -07001862 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001863 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1864 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001865 /*
1866 * Since lazyfree pages are isolated from file LRU from the beginning,
1867 * they will rotate back to anonymous LRU in the end if it failed to
1868 * discard so isolated count will be mismatched.
1869 * Compensate the isolated count for both LRU lists.
1870 */
1871 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1872 stat.nr_lazyfree_fail);
1873 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001874 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001875 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001876}
1877
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001878/*
1879 * Attempt to remove the specified page from its LRU. Only take this page
1880 * if it is of the appropriate PageActive status. Pages which are being
1881 * freed elsewhere are also ignored.
1882 *
1883 * page: page to consider
1884 * mode: one of the LRU isolation modes defined above
1885 *
Alex Shic2135f72021-02-24 12:08:01 -08001886 * returns true on success, false on failure.
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001887 */
Alex Shic2135f72021-02-24 12:08:01 -08001888bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001889{
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001890 /* Only take pages on the LRU. */
1891 if (!PageLRU(page))
Alex Shic2135f72021-02-24 12:08:01 -08001892 return false;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001893
Minchan Kime46a2872012-10-08 16:33:48 -07001894 /* Compaction should not handle unevictable pages but CMA can do so */
1895 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
Alex Shic2135f72021-02-24 12:08:01 -08001896 return false;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001897
Mel Gormanc8244932012-01-12 17:19:38 -08001898 /*
1899 * To minimise LRU disruption, the caller can indicate that it only
1900 * wants to isolate pages it will be able to operate on without
1901 * blocking - clean pages for the most part.
1902 *
Mel Gormanc8244932012-01-12 17:19:38 -08001903 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1904 * that it is possible to migrate without blocking
1905 */
Johannes Weiner1276ad62017-02-24 14:56:11 -08001906 if (mode & ISOLATE_ASYNC_MIGRATE) {
Mel Gormanc8244932012-01-12 17:19:38 -08001907 /* All the caller can do on PageWriteback is block */
1908 if (PageWriteback(page))
Alex Shic2135f72021-02-24 12:08:01 -08001909 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001910
1911 if (PageDirty(page)) {
1912 struct address_space *mapping;
Mel Gorman69d763f2018-01-31 16:19:52 -08001913 bool migrate_dirty;
Mel Gormanc8244932012-01-12 17:19:38 -08001914
Mel Gormanc8244932012-01-12 17:19:38 -08001915 /*
1916 * Only pages without mappings or that have a
1917 * ->migratepage callback are possible to migrate
Mel Gorman69d763f2018-01-31 16:19:52 -08001918 * without blocking. However, we can be racing with
1919 * truncation so it's necessary to lock the page
1920 * to stabilise the mapping as truncation holds
1921 * the page lock until after the page is removed
1922 * from the page cache.
Mel Gormanc8244932012-01-12 17:19:38 -08001923 */
Mel Gorman69d763f2018-01-31 16:19:52 -08001924 if (!trylock_page(page))
Alex Shic2135f72021-02-24 12:08:01 -08001925 return false;
Mel Gorman69d763f2018-01-31 16:19:52 -08001926
Mel Gormanc8244932012-01-12 17:19:38 -08001927 mapping = page_mapping(page);
Hugh Dickins145e1a72018-06-01 16:50:50 -07001928 migrate_dirty = !mapping || mapping->a_ops->migratepage;
Mel Gorman69d763f2018-01-31 16:19:52 -08001929 unlock_page(page);
1930 if (!migrate_dirty)
Alex Shic2135f72021-02-24 12:08:01 -08001931 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001932 }
1933 }
Minchan Kim39deaf82011-10-31 17:06:51 -07001934
Minchan Kimf80c0672011-10-31 17:06:55 -07001935 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
Alex Shic2135f72021-02-24 12:08:01 -08001936 return false;
Minchan Kimf80c0672011-10-31 17:06:55 -07001937
Alex Shic2135f72021-02-24 12:08:01 -08001938 return true;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001939}
1940
Mel Gorman7ee36a12016-07-28 15:47:17 -07001941/*
1942 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001943 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001944 */
1945static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001946 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001947{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001948 int zid;
1949
Mel Gorman7ee36a12016-07-28 15:47:17 -07001950 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1951 if (!nr_zone_taken[zid])
1952 continue;
1953
Wei Yanga892cb62020-06-03 16:01:12 -07001954 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001955 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001956
Mel Gorman7ee36a12016-07-28 15:47:17 -07001957}
1958
Mel Gormanf611fab2021-06-30 18:53:19 -07001959/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001960 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1961 *
1962 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001963 * shrink the lists perform better by taking out a batch of pages
1964 * and working on them outside the LRU lock.
1965 *
1966 * For pagecache intensive workloads, this function is the hottest
1967 * spot in the kernel (apart from copy_*_user functions).
1968 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001969 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001970 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001971 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001972 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001973 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001974 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001975 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001976 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001977 *
1978 * returns how many pages were moved onto *@dst.
1979 */
Andrew Morton69e05942006-03-22 00:08:19 -08001980static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001981 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001982 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001983 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001984{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001985 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001986 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001987 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001988 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07001989 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001990 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07001991 LIST_HEAD(pages_skipped);
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001992 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001993
Yang Shi98879b32019-07-11 20:59:30 -07001994 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07001995 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07001996 while (scan < nr_to_scan && !list_empty(src)) {
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001997 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001998
Linus Torvalds1da177e2005-04-16 15:20:36 -07001999 page = lru_to_page(src);
2000 prefetchw_prev_lru_page(page, src, flags);
2001
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002002 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002003 total_scan += nr_pages;
2004
Mel Gormanb2e18752016-07-28 15:45:37 -07002005 if (page_zonenum(page) > sc->reclaim_idx) {
2006 list_move(&page->lru, &pages_skipped);
Yang Shi98879b32019-07-11 20:59:30 -07002007 nr_skipped[page_zonenum(page)] += nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002008 continue;
2009 }
2010
Minchan Kim791b48b2017-05-12 15:47:06 -07002011 /*
2012 * Do not count skipped pages because that makes the function
2013 * return with no isolated pages if the LRU mostly contains
2014 * ineligible pages. This causes the VM to not reclaim any
2015 * pages, triggering a premature OOM.
Yang Shi98879b32019-07-11 20:59:30 -07002016 *
2017 * Account all tail pages of THP. This would not cause
2018 * premature OOM since __isolate_lru_page() returns -EBUSY
2019 * only when the page is being freed somewhere else.
Minchan Kim791b48b2017-05-12 15:47:06 -07002020 */
Yang Shi98879b32019-07-11 20:59:30 -07002021 scan += nr_pages;
Alex Shic2135f72021-02-24 12:08:01 -08002022 if (!__isolate_lru_page_prepare(page, mode)) {
2023 /* It is being freed elsewhere */
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002024 list_move(&page->lru, src);
Alex Shic2135f72021-02-24 12:08:01 -08002025 continue;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002026 }
Alex Shic2135f72021-02-24 12:08:01 -08002027 /*
2028 * Be careful not to clear PageLRU until after we're
2029 * sure the page is not being freed elsewhere -- the
2030 * page release code relies on it.
2031 */
2032 if (unlikely(!get_page_unless_zero(page))) {
2033 list_move(&page->lru, src);
2034 continue;
2035 }
2036
2037 if (!TestClearPageLRU(page)) {
2038 /* Another thread is already isolating this page */
2039 put_page(page);
2040 list_move(&page->lru, src);
2041 continue;
2042 }
2043
2044 nr_taken += nr_pages;
2045 nr_zone_taken[page_zonenum(page)] += nr_pages;
2046 list_move(&page->lru, dst);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002047 }
2048
Mel Gormanb2e18752016-07-28 15:45:37 -07002049 /*
2050 * Splice any skipped pages to the start of the LRU list. Note that
2051 * this disrupts the LRU order when reclaiming for lower zones but
2052 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2053 * scanning would soon rescan the same pages to skip and put the
2054 * system at risk of premature OOM.
2055 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002056 if (!list_empty(&pages_skipped)) {
2057 int zid;
2058
Johannes Weiner3db65812017-05-03 14:52:13 -07002059 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002060 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2061 if (!nr_skipped[zid])
2062 continue;
2063
2064 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002065 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002066 }
2067 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002068 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002069 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Minchan Kim791b48b2017-05-12 15:47:06 -07002070 total_scan, skipped, nr_taken, mode, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002071 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002072 return nr_taken;
2073}
2074
Nick Piggin62695a82008-10-18 20:26:09 -07002075/**
2076 * isolate_lru_page - tries to isolate a page from its LRU list
2077 * @page: page to isolate from its LRU list
2078 *
2079 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2080 * vmstat statistic corresponding to whatever LRU list the page was on.
2081 *
2082 * Returns 0 if the page was removed from an LRU list.
2083 * Returns -EBUSY if the page was not on an LRU list.
2084 *
2085 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002086 * the active list, it will have PageActive set. If it was found on
2087 * the unevictable list, it will have the PageUnevictable bit set. That flag
2088 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002089 *
2090 * The vmstat statistic corresponding to the list on which the page was
2091 * found will be decremented.
2092 *
2093 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002094 *
Nick Piggin62695a82008-10-18 20:26:09 -07002095 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002096 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002097 * without a stable reference).
2098 * (2) the lru_lock must not be held.
2099 * (3) interrupts must be enabled.
2100 */
2101int isolate_lru_page(struct page *page)
2102{
2103 int ret = -EBUSY;
2104
Sasha Levin309381fea2014-01-23 15:52:54 -08002105 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002106 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002107
Alex Shid25b5bd2020-12-15 12:34:16 -08002108 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002109 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002110
Alex Shid25b5bd2020-12-15 12:34:16 -08002111 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002112 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002113 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002114 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002115 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002116 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002117
Nick Piggin62695a82008-10-18 20:26:09 -07002118 return ret;
2119}
2120
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002121/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002122 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002123 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002124 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2125 * the LRU list will go small and be scanned faster than necessary, leading to
2126 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002127 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002128static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002129 struct scan_control *sc)
2130{
2131 unsigned long inactive, isolated;
2132
2133 if (current_is_kswapd())
2134 return 0;
2135
Johannes Weinerb5ead352019-11-30 17:55:40 -08002136 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002137 return 0;
2138
2139 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002140 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2141 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002142 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002143 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2144 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002145 }
2146
Fengguang Wu3cf23842012-12-18 14:23:31 -08002147 /*
2148 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2149 * won't get blocked by normal direct-reclaimers, forming a circular
2150 * deadlock.
2151 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002152 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002153 inactive >>= 3;
2154
Rik van Riel35cd7812009-09-21 17:01:38 -07002155 return isolated > inactive;
2156}
2157
Kirill Tkhaia222f342019-05-13 17:17:00 -07002158/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002159 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2160 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002161 *
2162 * Returns the number of pages moved to the given lruvec.
2163 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002164static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2165 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002166{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002167 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002168 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002169 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002170
Kirill Tkhaia222f342019-05-13 17:17:00 -07002171 while (!list_empty(list)) {
2172 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002173 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002174 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002175 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002176 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002177 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002178 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002179 continue;
2180 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002181
Alex Shi3d06afa2020-12-15 12:33:37 -08002182 /*
2183 * The SetPageLRU needs to be kept here for list integrity.
2184 * Otherwise:
2185 * #0 move_pages_to_lru #1 release_pages
2186 * if !put_page_testzero
2187 * if (put_page_testzero())
2188 * !PageLRU //skip lru_lock
2189 * SetPageLRU()
2190 * list_add(&page->lru,)
2191 * list_add(&page->lru,)
2192 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002193 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002194
Alex Shi3d06afa2020-12-15 12:33:37 -08002195 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002196 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002197
2198 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002199 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002200 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002201 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002202 } else
2203 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002204
2205 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002206 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002207
Alex Shiafca9152020-12-15 12:34:02 -08002208 /*
2209 * All pages were isolated from the same lruvec (and isolation
2210 * inhibits memcg migration).
2211 */
Muchun Song7467c392021-06-28 19:37:59 -07002212 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002213 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002214 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002215 nr_moved += nr_pages;
2216 if (PageActive(page))
2217 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002218 }
Mel Gorman66635622010-08-09 17:19:30 -07002219
Hugh Dickins3f797682012-01-12 17:20:07 -08002220 /*
2221 * To save our caller's stack, now use input list for pages to free.
2222 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002223 list_splice(&pages_to_free, list);
2224
2225 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002226}
2227
2228/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002229 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002230 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002231 * In that case we should only throttle if the backing device it is
2232 * writing to is congested. In other cases it is safe to throttle.
2233 */
2234static int current_may_throttle(void)
2235{
NeilBrowna37b0712020-06-01 21:48:18 -07002236 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002237 current->backing_dev_info == NULL ||
2238 bdi_write_congested(current->backing_dev_info);
2239}
2240
2241/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002242 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002243 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002244 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002245static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002246shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002247 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002248{
2249 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002250 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002251 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002252 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002253 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002254 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002255 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002256 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002257 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002258
Mel Gorman599d0c92016-07-28 15:45:31 -07002259 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002260 if (stalled)
2261 return 0;
2262
2263 /* wait a bit for the reclaimer. */
2264 msleep(100);
2265 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002266
2267 /* We are about to die and free our memory. Return now. */
2268 if (fatal_signal_pending(current))
2269 return SWAP_CLUSTER_MAX;
2270 }
2271
Linus Torvalds1da177e2005-04-16 15:20:36 -07002272 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002273
Alex Shi6168d0d2020-12-15 12:34:29 -08002274 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002275
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002276 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002277 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002278
Mel Gorman599d0c92016-07-28 15:45:31 -07002279 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002280 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002281 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002282 __count_vm_events(item, nr_scanned);
2283 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002284 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2285
Alex Shi6168d0d2020-12-15 12:34:29 -08002286 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002287
Hillf Dantond563c052012-03-21 16:34:02 -07002288 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002289 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002290
Shakeel Butt013339d2020-12-14 19:06:39 -08002291 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002292
Alex Shi6168d0d2020-12-15 12:34:29 -08002293 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002294 move_pages_to_lru(lruvec, &page_list);
2295
2296 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002297 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002298 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002299 __count_vm_events(item, nr_reclaimed);
2300 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002301 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002302 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002303
Alex Shi75cc3c92020-12-15 14:20:50 -08002304 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002305 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002306 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002307
Mel Gorman92df3a72011-10-31 17:07:56 -07002308 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002309 * If dirty pages are scanned that are not queued for IO, it
2310 * implies that flushers are not doing their job. This can
2311 * happen when memory pressure pushes dirty pages to the end of
2312 * the LRU before the dirty limits are breached and the dirty
2313 * data has expired. It can also happen when the proportion of
2314 * dirty pages grows not through writes but through memory
2315 * pressure reclaiming all the clean cache. And in some cases,
2316 * the flushers simply cannot keep up with the allocation
2317 * rate. Nudge the flusher threads in case they are asleep.
2318 */
2319 if (stat.nr_unqueued_dirty == nr_taken)
2320 wakeup_flusher_threads(WB_REASON_VMSCAN);
2321
Andrey Ryabinind108c772018-04-10 16:27:59 -07002322 sc->nr.dirty += stat.nr_dirty;
2323 sc->nr.congested += stat.nr_congested;
2324 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2325 sc->nr.writeback += stat.nr_writeback;
2326 sc->nr.immediate += stat.nr_immediate;
2327 sc->nr.taken += nr_taken;
2328 if (file)
2329 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002330
Mel Gorman599d0c92016-07-28 15:45:31 -07002331 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002332 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002333 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002334}
2335
Hugh Dickins15b44732020-12-15 14:21:31 -08002336/*
2337 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2338 *
2339 * We move them the other way if the page is referenced by one or more
2340 * processes.
2341 *
2342 * If the pages are mostly unmapped, the processing is fast and it is
2343 * appropriate to hold lru_lock across the whole operation. But if
2344 * the pages are mapped, the processing is slow (page_referenced()), so
2345 * we should drop lru_lock around each page. It's impossible to balance
2346 * this, so instead we remove the pages from the LRU while processing them.
2347 * It is safe to rely on PG_active against the non-LRU pages in here because
2348 * nobody will play with that bit on a non-LRU page.
2349 *
2350 * The downside is that we have to touch page->_refcount against each page.
2351 * But we had to alter page->flags anyway.
2352 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002353static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002354 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002355 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002356 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002357{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002358 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002359 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002360 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002361 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002362 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002363 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002364 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002365 unsigned nr_deactivate, nr_activate;
2366 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002367 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002368 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002369
2370 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002371
Alex Shi6168d0d2020-12-15 12:34:29 -08002372 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002373
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002374 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002375 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002376
Mel Gorman599d0c92016-07-28 15:45:31 -07002377 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002378
Shakeel Butt912c0572020-08-06 23:26:32 -07002379 if (!cgroup_reclaim(sc))
2380 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002381 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002382
Alex Shi6168d0d2020-12-15 12:34:29 -08002383 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002384
Linus Torvalds1da177e2005-04-16 15:20:36 -07002385 while (!list_empty(&l_hold)) {
2386 cond_resched();
2387 page = lru_to_page(&l_hold);
2388 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002389
Hugh Dickins39b5f292012-10-08 16:33:18 -07002390 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002391 putback_lru_page(page);
2392 continue;
2393 }
2394
Mel Gormancc715d92012-03-21 16:34:00 -07002395 if (unlikely(buffer_heads_over_limit)) {
2396 if (page_has_private(page) && trylock_page(page)) {
2397 if (page_has_private(page))
2398 try_to_release_page(page, 0);
2399 unlock_page(page);
2400 }
2401 }
2402
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002403 if (page_referenced(page, 0, sc->target_mem_cgroup,
2404 &vm_flags)) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002405 /*
2406 * Identify referenced, file-backed active pages and
2407 * give them one more trip around the active list. So
2408 * that executable code get better chances to stay in
2409 * memory under moderate memory pressure. Anon pages
2410 * are not likely to be evicted by use-once streaming
2411 * IO, plus JVM can create lots of anon VM_EXEC pages,
2412 * so we ignore them here.
2413 */
Huang Ying9de4f222020-04-06 20:04:41 -07002414 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002415 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002416 list_add(&page->lru, &l_active);
2417 continue;
2418 }
2419 }
Rik van Riel7e9cd482008-10-18 20:26:35 -07002420
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002421 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002422 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002423 list_add(&page->lru, &l_inactive);
2424 }
2425
Andrew Mortonb5557492009-01-06 14:40:13 -08002426 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002427 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002428 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002429 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002430
Kirill Tkhaia222f342019-05-13 17:17:00 -07002431 nr_activate = move_pages_to_lru(lruvec, &l_active);
2432 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002433 /* Keep all free pages in l_active list */
2434 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002435
2436 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2437 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2438
Mel Gorman599d0c92016-07-28 15:45:31 -07002439 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002440 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002441
Kirill Tkhaif372d892019-05-13 17:16:57 -07002442 mem_cgroup_uncharge_list(&l_active);
2443 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002444 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2445 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002446}
2447
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002448unsigned long reclaim_pages(struct list_head *page_list)
2449{
Yang Shif661d002020-04-01 21:10:05 -07002450 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002451 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002452 LIST_HEAD(node_page_list);
2453 struct reclaim_stat dummy_stat;
2454 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002455 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002456 struct scan_control sc = {
2457 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002458 .may_writepage = 1,
2459 .may_unmap = 1,
2460 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002461 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002462 };
2463
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002464 noreclaim_flag = memalloc_noreclaim_save();
2465
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002466 while (!list_empty(page_list)) {
2467 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002468 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002469 nid = page_to_nid(page);
2470 INIT_LIST_HEAD(&node_page_list);
2471 }
2472
2473 if (nid == page_to_nid(page)) {
2474 ClearPageActive(page);
2475 list_move(&page->lru, &node_page_list);
2476 continue;
2477 }
2478
2479 nr_reclaimed += shrink_page_list(&node_page_list,
2480 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002481 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002482 while (!list_empty(&node_page_list)) {
2483 page = lru_to_page(&node_page_list);
2484 list_del(&page->lru);
2485 putback_lru_page(page);
2486 }
2487
Yang Shif661d002020-04-01 21:10:05 -07002488 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002489 }
2490
2491 if (!list_empty(&node_page_list)) {
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 }
2501
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002502 memalloc_noreclaim_restore(noreclaim_flag);
2503
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002504 return nr_reclaimed;
2505}
2506
Johannes Weinerb91ac372019-11-30 17:56:02 -08002507static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2508 struct lruvec *lruvec, struct scan_control *sc)
2509{
2510 if (is_active_lru(lru)) {
2511 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2512 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2513 else
2514 sc->skipped_deactivate = 1;
2515 return 0;
2516 }
2517
2518 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2519}
2520
Rik van Riel59dc76b2016-05-20 16:56:31 -07002521/*
2522 * The inactive anon list should be small enough that the VM never has
2523 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002524 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002525 * The inactive file list should be small enough to leave most memory
2526 * to the established workingset on the scan-resistant active list,
2527 * but large enough to avoid thrashing the aggregate readahead window.
2528 *
2529 * Both inactive lists should also be large enough that each inactive
2530 * page has a chance to be referenced again before it is reclaimed.
2531 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002532 * If that fails and refaulting is observed, the inactive list grows.
2533 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002534 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002535 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002536 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2537 *
2538 * total target max
2539 * memory ratio inactive
2540 * -------------------------------------
2541 * 10MB 1 5MB
2542 * 100MB 1 50MB
2543 * 1GB 3 250MB
2544 * 10GB 10 0.9GB
2545 * 100GB 31 3GB
2546 * 1TB 101 10GB
2547 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002548 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002549static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002550{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002551 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002552 unsigned long inactive, active;
2553 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002554 unsigned long gb;
2555
Johannes Weinerb91ac372019-11-30 17:56:02 -08002556 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2557 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002558
Johannes Weinerb91ac372019-11-30 17:56:02 -08002559 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002560 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002561 inactive_ratio = int_sqrt(10 * gb);
2562 else
2563 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002564
Rik van Riel59dc76b2016-05-20 16:56:31 -07002565 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002566}
2567
Johannes Weiner9a265112013-02-22 16:32:17 -08002568enum scan_balance {
2569 SCAN_EQUAL,
2570 SCAN_FRACT,
2571 SCAN_ANON,
2572 SCAN_FILE,
2573};
2574
Yu Zhao3eb07702020-09-27 20:49:08 -06002575static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2576{
2577 unsigned long file;
2578 struct lruvec *target_lruvec;
2579
Yu Zhaoa1537a62022-01-27 20:32:37 -07002580 if (lru_gen_enabled())
2581 return;
2582
Yu Zhao3eb07702020-09-27 20:49:08 -06002583 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2584
2585 /*
2586 * Flush the memory cgroup stats, so that we read accurate per-memcg
2587 * lruvec stats for heuristics.
2588 */
2589 mem_cgroup_flush_stats();
2590
2591 /*
2592 * Determine the scan balance between anon and file LRUs.
2593 */
2594 spin_lock_irq(&target_lruvec->lru_lock);
2595 sc->anon_cost = target_lruvec->anon_cost;
2596 sc->file_cost = target_lruvec->file_cost;
2597 spin_unlock_irq(&target_lruvec->lru_lock);
2598
2599 /*
2600 * Target desirable inactive:active list ratios for the anon
2601 * and file LRU lists.
2602 */
2603 if (!sc->force_deactivate) {
2604 unsigned long refaults;
2605
2606 refaults = lruvec_page_state(target_lruvec,
2607 WORKINGSET_ACTIVATE_ANON);
2608 if (refaults != target_lruvec->refaults[0] ||
2609 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2610 sc->may_deactivate |= DEACTIVATE_ANON;
2611 else
2612 sc->may_deactivate &= ~DEACTIVATE_ANON;
2613
2614 /*
2615 * When refaults are being observed, it means a new
2616 * workingset is being established. Deactivate to get
2617 * rid of any stale active pages quickly.
2618 */
2619 refaults = lruvec_page_state(target_lruvec,
2620 WORKINGSET_ACTIVATE_FILE);
2621 if (refaults != target_lruvec->refaults[1] ||
2622 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2623 sc->may_deactivate |= DEACTIVATE_FILE;
2624 else
2625 sc->may_deactivate &= ~DEACTIVATE_FILE;
2626 } else
2627 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2628
2629 /*
2630 * If we have plenty of inactive file pages that aren't
2631 * thrashing, try to reclaim those first before touching
2632 * anonymous pages.
2633 */
2634 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2635 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2636 sc->cache_trim_mode = 1;
2637 else
2638 sc->cache_trim_mode = 0;
2639
2640 /*
2641 * Prevent the reclaimer from falling into the cache trap: as
2642 * cache pages start out inactive, every cache fault will tip
2643 * the scan balance towards the file LRU. And as the file LRU
2644 * shrinks, so does the window for rotation from references.
2645 * This means we have a runaway feedback loop where a tiny
2646 * thrashing file LRU becomes infinitely more attractive than
2647 * anon pages. Try to detect this based on file LRU size.
2648 */
2649 if (!cgroup_reclaim(sc)) {
2650 unsigned long total_high_wmark = 0;
2651 unsigned long free, anon;
2652 int z;
2653
2654 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2655 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2656 node_page_state(pgdat, NR_INACTIVE_FILE);
2657
2658 for (z = 0; z < MAX_NR_ZONES; z++) {
2659 struct zone *zone = &pgdat->node_zones[z];
2660
2661 if (!managed_zone(zone))
2662 continue;
2663
2664 total_high_wmark += high_wmark_pages(zone);
2665 }
2666
2667 /*
2668 * Consider anon: if that's low too, this isn't a
2669 * runaway file reclaim problem, but rather just
2670 * extreme pressure. Reclaim as per usual then.
2671 */
2672 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2673
2674 sc->file_is_tiny =
2675 file + free <= total_high_wmark &&
2676 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2677 anon >> sc->priority;
2678 }
2679}
2680
Linus Torvalds1da177e2005-04-16 15:20:36 -07002681/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002682 * Determine how aggressively the anon and file LRU lists should be
2683 * scanned. The relative value of each set of LRU lists is determined
2684 * by looking at the fraction of the pages scanned we did rotate back
2685 * onto the active list instead of evict.
2686 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002687 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2688 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002689 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002690static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2691 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002692{
Keith Buscha2a36482021-09-02 14:59:26 -07002693 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002694 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002695 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002696 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002697 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002698 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002699 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002700 unsigned long ap, fp;
2701 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002702 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002703
2704 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002705 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002706 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002707 goto out;
2708 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002709
Johannes Weiner10316b32013-02-22 16:32:14 -08002710 /*
2711 * Global reclaim will swap to prevent OOM even with no
2712 * swappiness, but memcg users want to use this knob to
2713 * disable swapping for individual groups completely when
2714 * using the memory controller's swap limit feature would be
2715 * too expensive.
2716 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002717 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002718 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002719 goto out;
2720 }
2721
2722 /*
2723 * Do not apply any pressure balancing cleverness when the
2724 * system is close to OOM, scan both anon and file equally
2725 * (unless the swappiness setting disagrees with swapping).
2726 */
Johannes Weiner02695172014-08-06 16:06:17 -07002727 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002728 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002729 goto out;
2730 }
2731
Johannes Weiner11d16c22013-02-22 16:32:15 -08002732 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002733 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002734 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002735 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002736 scan_balance = SCAN_ANON;
2737 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002738 }
2739
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002740 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2741
Johannes Weiner62376252014-05-06 12:50:07 -07002742 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002743 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002744 * anything from the anonymous working right now. But when balancing
2745 * anon and page cache files for reclaim, allow swapping of anon pages
2746 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002747 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002748 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002749 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002750 goto out;
2751 }
2752
Johannes Weiner9a265112013-02-22 16:32:17 -08002753 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002754 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002755 * Calculate the pressure balance between anon and file pages.
2756 *
2757 * The amount of pressure we put on each LRU is inversely
2758 * proportional to the cost of reclaiming each list, as
2759 * determined by the share of pages that are refaulting, times
2760 * the relative IO cost of bringing back a swapped out
2761 * anonymous page vs reloading a filesystem page (swappiness).
2762 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002763 * Although we limit that influence to ensure no list gets
2764 * left behind completely: at least a third of the pressure is
2765 * applied, before swappiness.
2766 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002767 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002768 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002769 total_cost = sc->anon_cost + sc->file_cost;
2770 anon_cost = total_cost + sc->anon_cost;
2771 file_cost = total_cost + sc->file_cost;
2772 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002773
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002774 ap = swappiness * (total_cost + 1);
2775 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002776
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002777 fp = (200 - swappiness) * (total_cost + 1);
2778 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002779
Shaohua Li76a33fc2010-05-24 14:32:36 -07002780 fraction[0] = ap;
2781 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002782 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002783out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002784 for_each_evictable_lru(lru) {
2785 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002786 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002787 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002788 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002789
Chris Down9783aa92019-10-06 17:58:32 -07002790 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002791 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2792 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002793
Johannes Weinerf56ce412021-08-19 19:04:21 -07002794 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002795 /*
2796 * Scale a cgroup's reclaim pressure by proportioning
2797 * its current usage to its memory.low or memory.min
2798 * setting.
2799 *
2800 * This is important, as otherwise scanning aggression
2801 * becomes extremely binary -- from nothing as we
2802 * approach the memory protection threshold, to totally
2803 * nominal as we exceed it. This results in requiring
2804 * setting extremely liberal protection thresholds. It
2805 * also means we simply get no protection at all if we
2806 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002807 *
2808 * If there is any protection in place, we reduce scan
2809 * pressure by how much of the total memory used is
2810 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002811 *
Chris Down9de7ca42019-10-06 17:58:35 -07002812 * There is one special case: in the first reclaim pass,
2813 * we skip over all groups that are within their low
2814 * protection. If that fails to reclaim enough pages to
2815 * satisfy the reclaim goal, we come back and override
2816 * the best-effort low protection. However, we still
2817 * ideally want to honor how well-behaved groups are in
2818 * that case instead of simply punishing them all
2819 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002820 * memory they are using, reducing the scan pressure
2821 * again by how much of the total memory used is under
2822 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002823 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002824 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002825 unsigned long protection;
2826
2827 /* memory.low scaling, make sure we retry before OOM */
2828 if (!sc->memcg_low_reclaim && low > min) {
2829 protection = low;
2830 sc->memcg_low_skipped = 1;
2831 } else {
2832 protection = min;
2833 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002834
2835 /* Avoid TOCTOU with earlier protection check */
2836 cgroup_size = max(cgroup_size, protection);
2837
2838 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002839 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002840
2841 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002842 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002843 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002844 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002845 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002846 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002847 } else {
2848 scan = lruvec_size;
2849 }
2850
2851 scan >>= sc->priority;
2852
Johannes Weiner688035f2017-05-03 14:52:07 -07002853 /*
2854 * If the cgroup's already been deleted, make sure to
2855 * scrape out the remaining cache.
2856 */
2857 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002858 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002859
Johannes Weiner688035f2017-05-03 14:52:07 -07002860 switch (scan_balance) {
2861 case SCAN_EQUAL:
2862 /* Scan lists relative to size */
2863 break;
2864 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002865 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002866 * Scan types proportional to swappiness and
2867 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002868 * Make sure we don't miss the last page on
2869 * the offlined memory cgroups because of a
2870 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002871 */
Gavin Shan76073c62020-02-20 20:04:24 -08002872 scan = mem_cgroup_online(memcg) ?
2873 div64_u64(scan * fraction[file], denominator) :
2874 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002875 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002876 break;
2877 case SCAN_FILE:
2878 case SCAN_ANON:
2879 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002880 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002881 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002882 break;
2883 default:
2884 /* Look ma, no brain */
2885 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002886 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002887
Johannes Weiner688035f2017-05-03 14:52:07 -07002888 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002889 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002890}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002891
Dave Hansen2f368a92021-09-02 14:59:23 -07002892/*
2893 * Anonymous LRU management is a waste if there is
2894 * ultimately no way to reclaim the memory.
2895 */
2896static bool can_age_anon_pages(struct pglist_data *pgdat,
2897 struct scan_control *sc)
2898{
2899 /* Aging the anon LRU is valuable if swap is present: */
2900 if (total_swap_pages > 0)
2901 return true;
2902
2903 /* Also valuable if anon pages can be demoted: */
2904 return can_demote(pgdat->node_id, sc);
2905}
2906
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002907#ifdef CONFIG_LRU_GEN
2908
2909/******************************************************************************
2910 * shorthand helpers
2911 ******************************************************************************/
2912
Yu Zhaoa1537a62022-01-27 20:32:37 -07002913#define DEFINE_MAX_SEQ(lruvec) \
2914 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2915
2916#define DEFINE_MIN_SEQ(lruvec) \
2917 unsigned long min_seq[ANON_AND_FILE] = { \
2918 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2919 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2920 }
2921
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002922#define for_each_gen_type_zone(gen, type, zone) \
2923 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2924 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2925 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2926
Yu Zhaoa1537a62022-01-27 20:32:37 -07002927static int page_lru_gen(struct page *page)
2928{
2929 unsigned long flags = READ_ONCE(page->flags);
2930
2931 return ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
2932}
2933
2934static int page_lru_tier(struct page *page)
2935{
2936 int refs;
2937 unsigned long flags = READ_ONCE(page->flags);
2938
2939 refs = (flags & LRU_REFS_FLAGS) == LRU_REFS_FLAGS ?
2940 ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) + 1 : 0;
2941
2942 return lru_tier_from_refs(refs);
2943}
2944
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002945static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
2946{
2947 struct pglist_data *pgdat = NODE_DATA(nid);
2948
2949#ifdef CONFIG_MEMCG
2950 if (memcg) {
2951 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2952
2953 /* for hotadd_new_pgdat() */
2954 if (!lruvec->pgdat)
2955 lruvec->pgdat = pgdat;
2956
2957 return lruvec;
2958 }
2959#endif
2960 VM_BUG_ON(!mem_cgroup_disabled());
2961
2962 return pgdat ? &pgdat->__lruvec : NULL;
2963}
2964
Yu Zhaoa1537a62022-01-27 20:32:37 -07002965static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2966{
2967 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2968 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2969
2970 if (!can_demote(pgdat->node_id, sc) &&
2971 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2972 return 0;
2973
2974 return mem_cgroup_swappiness(memcg);
2975}
2976
2977static int get_nr_gens(struct lruvec *lruvec, int type)
2978{
2979 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
2980}
2981
2982static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
2983{
2984 /* see the comment on lru_gen_struct */
2985 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
2986 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
2987 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
2988}
2989
2990/******************************************************************************
2991 * refault feedback loop
2992 ******************************************************************************/
2993
2994/*
2995 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
2996 *
2997 * The P term is refaulted/(evicted+protected) from a tier in the generation
2998 * currently being evicted; the I term is the exponential moving average of the
2999 * P term over the generations previously evicted, using the smoothing factor
3000 * 1/2; the D term isn't supported.
3001 *
3002 * The setpoint (SP) is always the first tier of one type; the process variable
3003 * (PV) is either any tier of the other type or any other tier of the same
3004 * type.
3005 *
3006 * The error is the difference between the SP and the PV; the correction is
3007 * turn off protection when SP>PV or turn on protection when SP<PV.
3008 *
3009 * For future optimizations:
3010 * 1. The D term may discount the other two terms over time so that long-lived
3011 * generations can resist stale information.
3012 */
3013struct ctrl_pos {
3014 unsigned long refaulted;
3015 unsigned long total;
3016 int gain;
3017};
3018
3019static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3020 struct ctrl_pos *pos)
3021{
3022 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3023 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3024
3025 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3026 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3027 pos->total = lrugen->avg_total[type][tier] +
3028 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3029 if (tier)
3030 pos->total += lrugen->protected[hist][type][tier - 1];
3031 pos->gain = gain;
3032}
3033
3034static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3035{
3036 int hist, tier;
3037 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3038 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3039 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3040
3041 lockdep_assert_held(&lruvec->lru_lock);
3042
3043 if (!carryover && !clear)
3044 return;
3045
3046 hist = lru_hist_from_seq(seq);
3047
3048 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3049 if (carryover) {
3050 unsigned long sum;
3051
3052 sum = lrugen->avg_refaulted[type][tier] +
3053 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3054 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3055
3056 sum = lrugen->avg_total[type][tier] +
3057 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3058 if (tier)
3059 sum += lrugen->protected[hist][type][tier - 1];
3060 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3061 }
3062
3063 if (clear) {
3064 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3065 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3066 if (tier)
3067 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3068 }
3069 }
3070}
3071
3072static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3073{
3074 /*
3075 * Return true if the PV has a limited number of refaults or a lower
3076 * refaulted/total than the SP.
3077 */
3078 return pv->refaulted < MIN_LRU_BATCH ||
3079 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3080 (sp->refaulted + 1) * pv->total * pv->gain;
3081}
3082
3083/******************************************************************************
3084 * the aging
3085 ******************************************************************************/
3086
Yu Zhaoafd94c92022-01-27 20:43:22 -07003087static int page_update_gen(struct page *page, int gen)
3088{
3089 unsigned long old_flags, new_flags;
3090
3091 VM_BUG_ON(gen >= MAX_NR_GENS);
3092 VM_BUG_ON(!rcu_read_lock_held());
3093
3094 do {
3095 new_flags = old_flags = READ_ONCE(page->flags);
3096
3097 /* for shrink_page_list() */
3098 if (!(new_flags & LRU_GEN_MASK)) {
3099 new_flags |= BIT(PG_referenced);
3100 continue;
3101 }
3102
3103 new_flags &= ~LRU_GEN_MASK;
3104 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3105 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3106 } while (new_flags != old_flags &&
3107 cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3108
3109 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3110}
3111
Yu Zhaoa1537a62022-01-27 20:32:37 -07003112static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3113{
3114 unsigned long old_flags, new_flags;
3115 int type = page_is_file_lru(page);
3116 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3117 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3118
3119 do {
3120 new_flags = old_flags = READ_ONCE(page->flags);
3121 VM_BUG_ON_PAGE(!(new_flags & LRU_GEN_MASK), page);
3122
Yu Zhaoafd94c92022-01-27 20:43:22 -07003123 new_gen = ((new_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3124 /* page_update_gen() has promoted this page? */
3125 if (new_gen >= 0 && new_gen != old_gen)
3126 return new_gen;
3127
Yu Zhaoa1537a62022-01-27 20:32:37 -07003128 new_gen = (old_gen + 1) % MAX_NR_GENS;
3129
3130 new_flags &= ~LRU_GEN_MASK;
3131 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3132 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3133 /* for end_page_writeback() */
3134 if (reclaiming)
3135 new_flags |= BIT(PG_reclaim);
3136 } while (cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3137
3138 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3139
3140 return new_gen;
3141}
3142
3143static void inc_min_seq(struct lruvec *lruvec)
3144{
3145 int type;
3146 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3147
3148 VM_BUG_ON(!seq_is_valid(lruvec));
3149
3150 for (type = 0; type < ANON_AND_FILE; type++) {
3151 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
3152 continue;
3153
3154 reset_ctrl_pos(lruvec, type, true);
3155 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
3156 }
3157}
3158
3159static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
3160{
3161 int gen, type, zone;
3162 bool success = false;
3163 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3164 DEFINE_MIN_SEQ(lruvec);
3165
3166 VM_BUG_ON(!seq_is_valid(lruvec));
3167
3168 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3169 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
3170 gen = lru_gen_from_seq(min_seq[type]);
3171
3172 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3173 if (!list_empty(&lrugen->lists[gen][type][zone]))
3174 goto next;
3175 }
3176
3177 min_seq[type]++;
3178 }
3179next:
3180 ;
3181 }
3182
3183 /* see the comment on lru_gen_struct */
3184 if (can_swap) {
3185 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
3186 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
3187 }
3188
3189 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3190 if (min_seq[type] == lrugen->min_seq[type])
3191 continue;
3192
3193 reset_ctrl_pos(lruvec, type, true);
3194 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
3195 success = true;
3196 }
3197
3198 return success;
3199}
3200
3201static void inc_max_seq(struct lruvec *lruvec, unsigned long max_seq)
3202{
3203 int prev, next;
3204 int type, zone;
3205 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3206
3207 spin_lock_irq(&lruvec->lru_lock);
3208
3209 VM_BUG_ON(!seq_is_valid(lruvec));
3210
3211 if (max_seq != lrugen->max_seq)
3212 goto unlock;
3213
3214 inc_min_seq(lruvec);
3215
3216 /*
3217 * Update the active/inactive LRU sizes for compatibility. Both sides of
3218 * the current max_seq need to be covered, since max_seq+1 can overlap
3219 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
3220 * overlap, cold/hot inversion happens. This can be solved by moving
3221 * pages from min_seq to min_seq+1 but is omitted for simplicity.
3222 */
3223 prev = lru_gen_from_seq(lrugen->max_seq - 1);
3224 next = lru_gen_from_seq(lrugen->max_seq + 1);
3225
3226 for (type = 0; type < ANON_AND_FILE; type++) {
3227 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
3228 enum lru_list lru = type * LRU_INACTIVE_FILE;
3229 long delta = lrugen->nr_pages[prev][type][zone] -
3230 lrugen->nr_pages[next][type][zone];
3231
3232 if (!delta)
3233 continue;
3234
3235 __update_lru_size(lruvec, lru, zone, delta);
3236 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
3237 }
3238 }
3239
3240 for (type = 0; type < ANON_AND_FILE; type++)
3241 reset_ctrl_pos(lruvec, type, false);
3242
3243 /* make sure preceding modifications appear */
3244 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
3245unlock:
3246 spin_unlock_irq(&lruvec->lru_lock);
3247}
3248
3249static long get_nr_evictable(struct lruvec *lruvec, unsigned long max_seq,
3250 unsigned long *min_seq, bool can_swap, bool *need_aging)
3251{
3252 int gen, type, zone;
3253 long old = 0;
3254 long young = 0;
3255 long total = 0;
3256 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3257
3258 for (type = !can_swap; type < ANON_AND_FILE; type++) {
3259 unsigned long seq;
3260
3261 for (seq = min_seq[type]; seq <= max_seq; seq++) {
3262 long size = 0;
3263
3264 gen = lru_gen_from_seq(seq);
3265
3266 for (zone = 0; zone < MAX_NR_ZONES; zone++)
3267 size += READ_ONCE(lrugen->nr_pages[gen][type][zone]);
3268
3269 total += size;
3270 if (seq == max_seq)
3271 young += size;
3272 if (seq + MIN_NR_GENS == max_seq)
3273 old += size;
3274 }
3275 }
3276
3277 /*
3278 * The aging and the eviction is a typical producer-consumer model. The
3279 * aging tries to be lazy to reduce the unnecessary overhead. On the
3280 * other hand, the eviction stalls when the number of generations
3281 * reaches MIN_NR_GENS. So ideally, there should be MIN_NR_GENS+1
3282 * generations, hence the first two if's.
3283 *
3284 * In addition, it's ideal to spread pages out evenly, meaning
3285 * 1/(MIN_NR_GENS+1) of the total number of pages for each generation. A
3286 * reasonable range for this average portion would [1/MIN_NR_GENS,
3287 * 1/(MIN_NR_GENS+2)]. From the consumer's POV, the eviction only cares
3288 * about the lower bound of cold pages, i.e., 1/(MIN_NR_GENS+2), whereas
3289 * from the producer's POV, the aging only cares about the upper bound
3290 * of hot pages, i.e., 1/MIN_NR_GENS.
3291 */
3292 if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS > max_seq)
3293 *need_aging = true;
3294 else if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS < max_seq)
3295 *need_aging = false;
3296 else if (young * MIN_NR_GENS > total)
3297 *need_aging = true;
3298 else if (old * (MIN_NR_GENS + 2) < total)
3299 *need_aging = true;
3300 else
3301 *need_aging = false;
3302
3303 return total > 0 ? total : 0;
3304}
3305
3306static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3307{
3308 bool need_aging;
3309 long nr_to_scan;
3310 int swappiness = get_swappiness(lruvec, sc);
3311 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3312 DEFINE_MAX_SEQ(lruvec);
3313 DEFINE_MIN_SEQ(lruvec);
3314
3315 mem_cgroup_calculate_protection(NULL, memcg);
3316
3317 if (mem_cgroup_below_min(memcg))
3318 return;
3319
3320 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, swappiness, &need_aging);
3321 if (!nr_to_scan)
3322 return;
3323
3324 nr_to_scan >>= sc->priority;
3325
3326 if (!mem_cgroup_online(memcg))
3327 nr_to_scan++;
3328
3329 if (nr_to_scan && need_aging && (!mem_cgroup_below_low(memcg) || sc->memcg_low_reclaim))
3330 inc_max_seq(lruvec, max_seq);
3331}
3332
3333static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
3334{
3335 struct mem_cgroup *memcg;
3336
3337 VM_BUG_ON(!current_is_kswapd());
3338
3339 memcg = mem_cgroup_iter(NULL, NULL, NULL);
3340 do {
3341 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3342
3343 age_lruvec(lruvec, sc);
3344
3345 cond_resched();
3346 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
3347}
3348
Yu Zhaoafd94c92022-01-27 20:43:22 -07003349/*
3350 * This function exploits spatial locality when shrink_page_list() walks the
3351 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages.
3352 */
3353void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
3354{
3355 int i;
3356 pte_t *pte;
3357 unsigned long start;
3358 unsigned long end;
3359 unsigned long addr;
3360 struct page *page;
3361 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
3362 struct mem_cgroup *memcg = page_memcg(pvmw->page);
3363 struct pglist_data *pgdat = page_pgdat(pvmw->page);
3364 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
3365 DEFINE_MAX_SEQ(lruvec);
3366 int old_gen, new_gen = lru_gen_from_seq(max_seq);
3367
3368 lockdep_assert_held(pvmw->ptl);
3369 VM_BUG_ON_PAGE(PageLRU(pvmw->page), pvmw->page);
3370
3371 if (spin_is_contended(pvmw->ptl))
3372 return;
3373
3374 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
3375 end = pmd_addr_end(pvmw->address, pvmw->vma->vm_end);
3376
3377 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
3378 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
3379 end = start + MIN_LRU_BATCH * PAGE_SIZE;
3380 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
3381 start = end - MIN_LRU_BATCH * PAGE_SIZE;
3382 else {
3383 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
3384 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
3385 }
3386 }
3387
3388 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
3389
3390 rcu_read_lock();
3391 arch_enter_lazy_mmu_mode();
3392
3393 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
3394 unsigned long pfn = pte_pfn(pte[i]);
3395
3396 VM_BUG_ON(addr < pvmw->vma->vm_start || addr >= pvmw->vma->vm_end);
3397
3398 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
3399 continue;
3400
3401 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
3402 continue;
3403
3404 if (!pte_young(pte[i]))
3405 continue;
3406
3407 VM_BUG_ON(!pfn_valid(pfn));
3408 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3409 continue;
3410
3411 page = compound_head(pfn_to_page(pfn));
3412 if (page_to_nid(page) != pgdat->node_id)
3413 continue;
3414
3415 if (page_memcg_rcu(page) != memcg)
3416 continue;
3417
3418 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
3419 continue;
3420
3421 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3422 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3423 set_page_dirty(page);
3424
3425 old_gen = page_lru_gen(page);
3426 if (old_gen < 0)
3427 SetPageReferenced(page);
3428 else if (old_gen != new_gen)
3429 __set_bit(i, bitmap);
3430 }
3431
3432 arch_leave_lazy_mmu_mode();
3433 rcu_read_unlock();
3434
3435 if (bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
3436 for_each_set_bit(i, bitmap, MIN_LRU_BATCH)
3437 activate_page(pte_page(pte[i]));
3438 return;
3439 }
3440
3441 /* page_update_gen() requires stable page_memcg() */
3442 if (!mem_cgroup_trylock_pages(memcg))
3443 return;
3444
3445 spin_lock_irq(&lruvec->lru_lock);
3446 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
3447
3448 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
3449 page = compound_head(pte_page(pte[i]));
3450 if (page_memcg_rcu(page) != memcg)
3451 continue;
3452
3453 old_gen = page_update_gen(page, new_gen);
3454 if (old_gen < 0 || old_gen == new_gen)
3455 continue;
3456
3457 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3458 }
3459
3460 spin_unlock_irq(&lruvec->lru_lock);
3461
3462 mem_cgroup_unlock_pages();
3463}
3464
Yu Zhaoa1537a62022-01-27 20:32:37 -07003465/******************************************************************************
3466 * the eviction
3467 ******************************************************************************/
3468
3469static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
3470{
3471 bool success;
3472 int gen = page_lru_gen(page);
3473 int type = page_is_file_lru(page);
3474 int zone = page_zonenum(page);
3475 int tier = page_lru_tier(page);
3476 int delta = thp_nr_pages(page);
3477 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3478
3479 VM_BUG_ON_PAGE(gen >= MAX_NR_GENS, page);
3480
3481 if (!page_evictable(page)) {
3482 success = lru_gen_del_page(lruvec, page, true);
3483 VM_BUG_ON_PAGE(!success, page);
3484 SetPageUnevictable(page);
3485 add_page_to_lru_list(page, lruvec);
3486 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
3487 return true;
3488 }
3489
3490 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
3491 success = lru_gen_del_page(lruvec, page, true);
3492 VM_BUG_ON_PAGE(!success, page);
3493 SetPageSwapBacked(page);
3494 add_page_to_lru_list_tail(page, lruvec);
3495 return true;
3496 }
3497
Yu Zhaoafd94c92022-01-27 20:43:22 -07003498 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
3499 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
3500 return true;
3501 }
3502
Yu Zhaoa1537a62022-01-27 20:32:37 -07003503 if (tier > tier_idx) {
3504 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3505
3506 gen = page_inc_gen(lruvec, page, false);
3507 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
3508
3509 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
3510 lrugen->protected[hist][type][tier - 1] + delta);
3511 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
3512 return true;
3513 }
3514
3515 if (PageLocked(page) || PageWriteback(page) ||
3516 (type == LRU_GEN_FILE && PageDirty(page))) {
3517 gen = page_inc_gen(lruvec, page, true);
3518 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
3519 return true;
3520 }
3521
3522 return false;
3523}
3524
3525static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
3526{
3527 bool success;
3528
3529 if (!sc->may_unmap && page_mapped(page))
3530 return false;
3531
3532 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
3533 (PageDirty(page) || (PageAnon(page) && !PageSwapCache(page))))
3534 return false;
3535
3536 if (!get_page_unless_zero(page))
3537 return false;
3538
3539 if (!TestClearPageLRU(page)) {
3540 put_page(page);
3541 return false;
3542 }
3543
3544 success = lru_gen_del_page(lruvec, page, true);
3545 VM_BUG_ON_PAGE(!success, page);
3546
3547 return true;
3548}
3549
3550static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
3551 int type, int tier, struct list_head *list)
3552{
3553 int gen, zone;
3554 enum vm_event_item item;
3555 int sorted = 0;
3556 int scanned = 0;
3557 int isolated = 0;
3558 int remaining = MAX_LRU_BATCH;
3559 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3560 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3561
3562 VM_BUG_ON(!list_empty(list));
3563
3564 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
3565 return 0;
3566
3567 gen = lru_gen_from_seq(lrugen->min_seq[type]);
3568
3569 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
3570 LIST_HEAD(moved);
3571 int skipped = 0;
3572 struct list_head *head = &lrugen->lists[gen][type][zone];
3573
3574 while (!list_empty(head)) {
3575 struct page *page = lru_to_page(head);
3576 int delta = thp_nr_pages(page);
3577
3578 VM_BUG_ON_PAGE(PageTail(page), page);
3579 VM_BUG_ON_PAGE(PageUnevictable(page), page);
3580 VM_BUG_ON_PAGE(PageActive(page), page);
3581 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
3582 VM_BUG_ON_PAGE(page_zonenum(page) != zone, page);
3583
3584 prefetchw_prev_lru_page(page, head, flags);
3585
3586 scanned += delta;
3587
3588 if (sort_page(lruvec, page, tier))
3589 sorted += delta;
3590 else if (isolate_page(lruvec, page, sc)) {
3591 list_add(&page->lru, list);
3592 isolated += delta;
3593 } else {
3594 list_move(&page->lru, &moved);
3595 skipped += delta;
3596 }
3597
3598 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
3599 break;
3600 }
3601
3602 if (skipped) {
3603 list_splice(&moved, head);
3604 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
3605 }
3606
3607 if (!remaining || isolated >= MIN_LRU_BATCH)
3608 break;
3609 }
3610
3611 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
3612 if (!cgroup_reclaim(sc)) {
3613 __count_vm_events(item, isolated);
3614 __count_vm_events(PGREFILL, sorted);
3615 }
3616 __count_memcg_events(memcg, item, isolated);
3617 __count_memcg_events(memcg, PGREFILL, sorted);
3618 __count_vm_events(PGSCAN_ANON + type, isolated);
3619
3620 /*
3621 * There might not be eligible pages due to reclaim_idx, may_unmap and
3622 * may_writepage. Check the remaining to prevent livelock if there is no
3623 * progress.
3624 */
3625 return isolated || !remaining ? scanned : 0;
3626}
3627
3628static int get_tier_idx(struct lruvec *lruvec, int type)
3629{
3630 int tier;
3631 struct ctrl_pos sp, pv;
3632
3633 /*
3634 * To leave a margin for fluctuations, use a larger gain factor (1:2).
3635 * This value is chosen because any other tier would have at least twice
3636 * as many refaults as the first tier.
3637 */
3638 read_ctrl_pos(lruvec, type, 0, 1, &sp);
3639 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
3640 read_ctrl_pos(lruvec, type, tier, 2, &pv);
3641 if (!positive_ctrl_err(&sp, &pv))
3642 break;
3643 }
3644
3645 return tier - 1;
3646}
3647
3648static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
3649{
3650 int type, tier;
3651 struct ctrl_pos sp, pv;
3652 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
3653
3654 /*
3655 * Compare the first tier of anon with that of file to determine which
3656 * type to scan. Also need to compare other tiers of the selected type
3657 * with the first tier of the other type to determine the last tier (of
3658 * the selected type) to evict.
3659 */
3660 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
3661 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
3662 type = positive_ctrl_err(&sp, &pv);
3663
3664 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
3665 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
3666 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
3667 if (!positive_ctrl_err(&sp, &pv))
3668 break;
3669 }
3670
3671 *tier_idx = tier - 1;
3672
3673 return type;
3674}
3675
3676static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
3677 int *type_scanned, struct list_head *list)
3678{
3679 int i;
3680 int type;
3681 int scanned;
3682 int tier = -1;
3683 DEFINE_MIN_SEQ(lruvec);
3684
3685 VM_BUG_ON(!seq_is_valid(lruvec));
3686
3687 /*
3688 * Try to make the obvious choice first. When anon and file are both
3689 * available from the same generation, interpret swappiness 1 as file
3690 * first and 200 as anon first.
3691 */
3692 if (!swappiness)
3693 type = LRU_GEN_FILE;
3694 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
3695 type = LRU_GEN_ANON;
3696 else if (swappiness == 1)
3697 type = LRU_GEN_FILE;
3698 else if (swappiness == 200)
3699 type = LRU_GEN_ANON;
3700 else
3701 type = get_type_to_scan(lruvec, swappiness, &tier);
3702
3703 for (i = !swappiness; i < ANON_AND_FILE; i++) {
3704 if (tier < 0)
3705 tier = get_tier_idx(lruvec, type);
3706
3707 scanned = scan_pages(lruvec, sc, type, tier, list);
3708 if (scanned)
3709 break;
3710
3711 type = !type;
3712 tier = -1;
3713 }
3714
3715 *type_scanned = type;
3716
3717 return scanned;
3718}
3719
3720static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness)
3721{
3722 int type;
3723 int scanned;
3724 int reclaimed;
3725 LIST_HEAD(list);
3726 struct page *page;
3727 enum vm_event_item item;
3728 struct reclaim_stat stat;
3729 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3730 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3731
3732 spin_lock_irq(&lruvec->lru_lock);
3733
3734 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
3735
3736 if (try_to_inc_min_seq(lruvec, swappiness))
3737 scanned++;
3738
3739 if (get_nr_gens(lruvec, LRU_GEN_FILE) == MIN_NR_GENS)
3740 scanned = 0;
3741
3742 spin_unlock_irq(&lruvec->lru_lock);
3743
3744 if (list_empty(&list))
3745 return scanned;
3746
3747 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
3748
3749 /*
3750 * To avoid livelock, don't add rejected pages back to the same lists
3751 * they were isolated from. See lru_gen_add_page().
3752 */
3753 list_for_each_entry(page, &list, lru) {
3754 ClearPageReferenced(page);
3755 ClearPageWorkingset(page);
3756
3757 if (PageReclaim(page) && (PageDirty(page) || PageWriteback(page)))
3758 ClearPageActive(page);
3759 else if (page_is_file_lru(page) || PageSwapCache(page))
3760 SetPageActive(page);
3761 }
3762
3763 spin_lock_irq(&lruvec->lru_lock);
3764
3765 move_pages_to_lru(lruvec, &list);
3766
3767 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
3768 if (!cgroup_reclaim(sc))
3769 __count_vm_events(item, reclaimed);
3770 __count_memcg_events(memcg, item, reclaimed);
3771 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
3772
3773 spin_unlock_irq(&lruvec->lru_lock);
3774
3775 mem_cgroup_uncharge_list(&list);
3776 free_unref_page_list(&list);
3777
3778 sc->nr_reclaimed += reclaimed;
3779
3780 return scanned;
3781}
3782
3783static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
3784{
3785 bool need_aging;
3786 long nr_to_scan;
3787 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3788 DEFINE_MAX_SEQ(lruvec);
3789 DEFINE_MIN_SEQ(lruvec);
3790
3791 if (mem_cgroup_below_min(memcg) ||
3792 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
3793 return 0;
3794
3795 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, can_swap, &need_aging);
3796 if (!nr_to_scan)
3797 return 0;
3798
3799 /* reset the priority if the target has been met */
3800 nr_to_scan >>= sc->nr_reclaimed < sc->nr_to_reclaim ? sc->priority : DEF_PRIORITY;
3801
3802 if (!mem_cgroup_online(memcg))
3803 nr_to_scan++;
3804
3805 if (!nr_to_scan)
3806 return 0;
3807
3808 if (!need_aging)
3809 return nr_to_scan;
3810
3811 /* leave the work to lru_gen_age_node() */
3812 if (current_is_kswapd())
3813 return 0;
3814
3815 /* try other memcgs before going to the aging path */
3816 if (!cgroup_reclaim(sc) && !sc->force_deactivate) {
3817 sc->skipped_deactivate = true;
3818 return 0;
3819 }
3820
3821 inc_max_seq(lruvec, max_seq);
3822
3823 return nr_to_scan;
3824}
3825
3826static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3827{
3828 struct blk_plug plug;
3829 long scanned = 0;
3830
3831 lru_add_drain();
3832
3833 blk_start_plug(&plug);
3834
3835 while (true) {
3836 int delta;
3837 int swappiness;
3838 long nr_to_scan;
3839
3840 if (sc->may_swap)
3841 swappiness = get_swappiness(lruvec, sc);
3842 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
3843 swappiness = 1;
3844 else
3845 swappiness = 0;
3846
3847 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
3848 if (!nr_to_scan)
3849 break;
3850
3851 delta = evict_pages(lruvec, sc, swappiness);
3852 if (!delta)
3853 break;
3854
3855 scanned += delta;
3856 if (scanned >= nr_to_scan)
3857 break;
3858
3859 cond_resched();
3860 }
3861
3862 blk_finish_plug(&plug);
3863}
3864
Yu Zhaof88ed5a2021-01-25 21:12:33 -07003865/******************************************************************************
3866 * initialization
3867 ******************************************************************************/
3868
3869void lru_gen_init_lruvec(struct lruvec *lruvec)
3870{
3871 int gen, type, zone;
3872 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3873
3874 lrugen->max_seq = MIN_NR_GENS + 1;
3875
3876 for_each_gen_type_zone(gen, type, zone)
3877 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
3878}
3879
3880#ifdef CONFIG_MEMCG
3881void lru_gen_init_memcg(struct mem_cgroup *memcg)
3882{
3883}
3884
3885void lru_gen_exit_memcg(struct mem_cgroup *memcg)
3886{
3887 int nid;
3888
3889 for_each_node(nid) {
3890 struct lruvec *lruvec = get_lruvec(memcg, nid);
3891
3892 VM_BUG_ON(memchr_inv(lruvec->lrugen.nr_pages, 0,
3893 sizeof(lruvec->lrugen.nr_pages)));
3894 }
3895}
3896#endif
3897
3898static int __init init_lru_gen(void)
3899{
3900 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
3901 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
3902
3903 return 0;
3904};
3905late_initcall(init_lru_gen);
3906
Yu Zhaoa1537a62022-01-27 20:32:37 -07003907#else
3908
3909static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
3910{
3911}
3912
3913static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
3914{
3915}
3916
Yu Zhaof88ed5a2021-01-25 21:12:33 -07003917#endif /* CONFIG_LRU_GEN */
3918
Johannes Weinerafaf07a2019-11-30 17:55:46 -08003919static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003920{
3921 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07003922 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003923 unsigned long nr_to_scan;
3924 enum lru_list lru;
3925 unsigned long nr_reclaimed = 0;
3926 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
3927 struct blk_plug plug;
Mel Gorman1a501902014-06-04 16:10:49 -07003928 bool scan_adjusted;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003929
Yu Zhaoa1537a62022-01-27 20:32:37 -07003930 if (lru_gen_enabled()) {
3931 lru_gen_shrink_lruvec(lruvec, sc);
3932 return;
3933 }
3934
Johannes Weinerafaf07a2019-11-30 17:55:46 -08003935 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003936
Mel Gormane82e0562013-07-03 15:01:44 -07003937 /* Record the original scan target for proportional adjustments later */
3938 memcpy(targets, nr, sizeof(nr));
3939
Mel Gorman1a501902014-06-04 16:10:49 -07003940 /*
3941 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
3942 * event that can occur when there is little memory pressure e.g.
3943 * multiple streaming readers/writers. Hence, we do not abort scanning
3944 * when the requested number of pages are reclaimed when scanning at
3945 * DEF_PRIORITY on the assumption that the fact we are direct
3946 * reclaiming implies that kswapd is not keeping up and it is best to
3947 * do a batch of work at once. For memcg reclaim one check is made to
3948 * abort proportional reclaim if either the file or anon lru has already
3949 * dropped to zero at the first pass.
3950 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08003951 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
Mel Gorman1a501902014-06-04 16:10:49 -07003952 sc->priority == DEF_PRIORITY);
3953
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003954 blk_start_plug(&plug);
3955 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
3956 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07003957 unsigned long nr_anon, nr_file, percentage;
3958 unsigned long nr_scanned;
3959
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003960 for_each_evictable_lru(lru) {
3961 if (nr[lru]) {
3962 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
3963 nr[lru] -= nr_to_scan;
3964
3965 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07003966 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003967 }
3968 }
Mel Gormane82e0562013-07-03 15:01:44 -07003969
Michal Hockobd041732016-12-02 17:26:48 -08003970 cond_resched();
3971
Mel Gormane82e0562013-07-03 15:01:44 -07003972 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
3973 continue;
3974
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08003975 /*
Mel Gormane82e0562013-07-03 15:01:44 -07003976 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07003977 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07003978 * proportionally what was requested by get_scan_count(). We
3979 * stop reclaiming one LRU and reduce the amount scanning
3980 * proportional to the original scan target.
3981 */
3982 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
3983 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
3984
Mel Gorman1a501902014-06-04 16:10:49 -07003985 /*
3986 * It's just vindictive to attack the larger once the smaller
3987 * has gone to zero. And given the way we stop scanning the
3988 * smaller below, this makes sure that we only make one nudge
3989 * towards proportionality once we've got nr_to_reclaim.
3990 */
3991 if (!nr_file || !nr_anon)
3992 break;
3993
Mel Gormane82e0562013-07-03 15:01:44 -07003994 if (nr_file > nr_anon) {
3995 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
3996 targets[LRU_ACTIVE_ANON] + 1;
3997 lru = LRU_BASE;
3998 percentage = nr_anon * 100 / scan_target;
3999 } else {
4000 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
4001 targets[LRU_ACTIVE_FILE] + 1;
4002 lru = LRU_FILE;
4003 percentage = nr_file * 100 / scan_target;
4004 }
4005
4006 /* Stop scanning the smaller of the LRU */
4007 nr[lru] = 0;
4008 nr[lru + LRU_ACTIVE] = 0;
4009
4010 /*
4011 * Recalculate the other LRU scan count based on its original
4012 * scan target and the percentage scanning already complete
4013 */
4014 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
4015 nr_scanned = targets[lru] - nr[lru];
4016 nr[lru] = targets[lru] * (100 - percentage) / 100;
4017 nr[lru] -= min(nr[lru], nr_scanned);
4018
4019 lru += LRU_ACTIVE;
4020 nr_scanned = targets[lru] - nr[lru];
4021 nr[lru] = targets[lru] * (100 - percentage) / 100;
4022 nr[lru] -= min(nr[lru], nr_scanned);
4023
4024 scan_adjusted = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004025 }
4026 blk_finish_plug(&plug);
4027 sc->nr_reclaimed += nr_reclaimed;
4028
4029 /*
4030 * Even if we did not try to evict anon pages at all, we want to
4031 * rebalance the anon lru active/inactive ratio.
4032 */
Dave Hansen2f368a92021-09-02 14:59:23 -07004033 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
4034 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004035 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
4036 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08004037}
4038
Mel Gorman23b9da52012-05-29 15:06:20 -07004039/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004040static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07004041{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08004042 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07004043 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004044 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07004045 return true;
4046
4047 return false;
4048}
4049
Rik van Riel4f98a2f2008-10-18 20:26:32 -07004050/*
Mel Gorman23b9da52012-05-29 15:06:20 -07004051 * Reclaim/compaction is used for high-order allocation requests. It reclaims
4052 * order-0 pages before compacting the zone. should_continue_reclaim() returns
4053 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07004054 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07004055 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08004056 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07004057static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08004058 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08004059 struct scan_control *sc)
4060{
4061 unsigned long pages_for_compaction;
4062 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07004063 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08004064
4065 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004066 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08004067 return false;
4068
Vlastimil Babka5ee04712019-09-23 15:37:29 -07004069 /*
4070 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
4071 * number of pages that were scanned. This will return to the caller
4072 * with the risk reclaim/compaction and the resulting allocation attempt
4073 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
4074 * allocations through requiring that the full LRU list has been scanned
4075 * first, by assuming that zero delta of sc->nr_scanned means full LRU
4076 * scan, but that approximation was wrong, and there were corner cases
4077 * where always a non-zero amount of pages were scanned.
4078 */
4079 if (!nr_reclaimed)
4080 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08004081
Mel Gorman3e7d3442011-01-13 15:45:56 -08004082 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07004083 for (z = 0; z <= sc->reclaim_idx; z++) {
4084 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07004085 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07004086 continue;
4087
4088 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07004089 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07004090 case COMPACT_CONTINUE:
4091 return false;
4092 default:
4093 /* check next zone */
4094 ;
4095 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08004096 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07004097
4098 /*
4099 * If we have not reclaimed enough pages for compaction and the
4100 * inactive lists are large enough, continue reclaiming
4101 */
4102 pages_for_compaction = compact_gap(sc->order);
4103 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07004104 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07004105 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
4106
Vlastimil Babka5ee04712019-09-23 15:37:29 -07004107 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08004108}
4109
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004110static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08004111{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004112 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08004113 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08004114
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004115 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08004116 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004117 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08004118 unsigned long reclaimed;
4119 unsigned long scanned;
Johannes Weiner56600482012-01-12 17:17:59 -08004120
Xunlei Pange3336ca2020-09-04 16:35:27 -07004121 /*
4122 * This loop can become CPU-bound when target memcgs
4123 * aren't eligible for reclaim - either because they
4124 * don't have any reclaimable pages, or because their
4125 * memory is explicitly protected. Avoid soft lockups.
4126 */
4127 cond_resched();
4128
Chris Down45c7f7e2020-08-06 23:22:05 -07004129 mem_cgroup_calculate_protection(target_memcg, memcg);
4130
4131 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08004132 /*
4133 * Hard protection.
4134 * If there is no reclaimable memory, OOM.
4135 */
4136 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07004137 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08004138 /*
4139 * Soft protection.
4140 * Respect the protection only as long as
4141 * there is an unprotected supply
4142 * of reclaimable memory from other cgroups.
4143 */
4144 if (!sc->memcg_low_reclaim) {
4145 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07004146 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08004147 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08004148 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08004149 }
4150
Johannes Weinerd2af3392019-11-30 17:55:43 -08004151 reclaimed = sc->nr_reclaimed;
4152 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004153
4154 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07004155
Johannes Weinerd2af3392019-11-30 17:55:43 -08004156 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
4157 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07004158
Johannes Weinerd2af3392019-11-30 17:55:43 -08004159 /* Record the group's reclaim efficiency */
4160 vmpressure(sc->gfp_mask, memcg, false,
4161 sc->nr_scanned - scanned,
4162 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07004163
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004164 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
4165}
4166
Liu Song6c9e09072020-01-30 22:14:08 -08004167static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004168{
4169 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004170 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08004171 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004172 bool reclaimable = false;
4173
Johannes Weiner1b051172019-11-30 17:55:52 -08004174 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
4175
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004176again:
4177 memset(&sc->nr, 0, sizeof(sc->nr));
4178
4179 nr_reclaimed = sc->nr_reclaimed;
4180 nr_scanned = sc->nr_scanned;
4181
Yu Zhao3eb07702020-09-27 20:49:08 -06004182 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08004183
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08004184 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07004185
Johannes Weinerd2af3392019-11-30 17:55:43 -08004186 if (reclaim_state) {
4187 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
4188 reclaim_state->reclaimed_slab = 0;
4189 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07004190
Johannes Weinerd2af3392019-11-30 17:55:43 -08004191 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08004192 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08004193 sc->nr_scanned - nr_scanned,
4194 sc->nr_reclaimed - nr_reclaimed);
4195
4196 if (sc->nr_reclaimed - nr_reclaimed)
4197 reclaimable = true;
4198
4199 if (current_is_kswapd()) {
4200 /*
4201 * If reclaim is isolating dirty pages under writeback,
4202 * it implies that the long-lived page allocation rate
4203 * is exceeding the page laundering rate. Either the
4204 * global limits are not being effective at throttling
4205 * processes due to the page distribution throughout
4206 * zones or there is heavy usage of a slow backing
4207 * device. The only option is to throttle from reclaim
4208 * context which is not ideal as there is no guarantee
4209 * the dirtying process is throttled in the same way
4210 * balance_dirty_pages() manages.
4211 *
4212 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
4213 * count the number of pages under pages flagged for
4214 * immediate reclaim and stall if any are encountered
4215 * in the nr_immediate check below.
4216 */
4217 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
4218 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07004219
Johannes Weinerd2af3392019-11-30 17:55:43 -08004220 /* Allow kswapd to start writing pages during reclaim.*/
4221 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
4222 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07004223
4224 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07004225 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08004226 * reclaim and under writeback (nr_immediate), it
4227 * implies that pages are cycling through the LRU
4228 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07004229 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08004230 if (sc->nr.immediate)
4231 congestion_wait(BLK_RW_ASYNC, HZ/10);
4232 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07004233
Johannes Weinerd2af3392019-11-30 17:55:43 -08004234 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08004235 * Tag a node/memcg as congested if all the dirty pages
4236 * scanned were backed by a congested BDI and
4237 * wait_iff_congested will stall.
4238 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08004239 * Legacy memcg will stall in page writeback so avoid forcibly
4240 * stalling in wait_iff_congested().
4241 */
Johannes Weiner1b051172019-11-30 17:55:52 -08004242 if ((current_is_kswapd() ||
4243 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08004244 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08004245 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08004246
4247 /*
4248 * Stall direct reclaim for IO completions if underlying BDIs
4249 * and node is congested. Allow kswapd to continue until it
4250 * starts encountering unqueued dirty pages or cycling through
4251 * the LRU too quickly.
4252 */
Johannes Weiner1b051172019-11-30 17:55:52 -08004253 if (!current_is_kswapd() && current_may_throttle() &&
4254 !sc->hibernation_mode &&
4255 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08004256 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
4257
4258 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
4259 sc))
4260 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07004261
Johannes Weinerc73322d2017-05-03 14:51:51 -07004262 /*
4263 * Kswapd gives up on balancing particular nodes after too
4264 * many failures to reclaim anything from them and goes to
4265 * sleep. On reclaim progress, reset the failure counter. A
4266 * successful direct reclaim run will revive a dormant kswapd.
4267 */
4268 if (reclaimable)
4269 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08004270}
4271
Vlastimil Babka53853e22014-10-09 15:27:02 -07004272/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07004273 * Returns true if compaction should go ahead for a costly-order request, or
4274 * the allocation would already succeed without compaction. Return false if we
4275 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07004276 */
Mel Gorman4f588332016-07-28 15:46:38 -07004277static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08004278{
Mel Gorman31483b62016-07-28 15:45:46 -07004279 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07004280 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08004281
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07004282 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
4283 if (suitable == COMPACT_SUCCESS)
4284 /* Allocation should succeed already. Don't reclaim. */
4285 return true;
4286 if (suitable == COMPACT_SKIPPED)
4287 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08004288 return false;
4289
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07004290 /*
4291 * Compaction is already possible, but it takes time to run and there
4292 * are potentially other callers using the pages just freed. So proceed
4293 * with reclaim to make a buffer of free pages available to give
4294 * compaction a reasonable chance of completing and allocating the page.
4295 * Note that we won't actually reclaim the whole buffer in one attempt
4296 * as the target watermark in should_continue_reclaim() is lower. But if
4297 * we are already above the high+gap watermark, don't reclaim at all.
4298 */
4299 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
4300
4301 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08004302}
4303
Linus Torvalds1da177e2005-04-16 15:20:36 -07004304/*
4305 * This is the direct reclaim path, for page-allocating processes. We only
4306 * try to reclaim pages from zones which will satisfy the caller's allocation
4307 * request.
4308 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07004309 * If a zone is deemed to be full of pinned pages then just give it a light
4310 * scan then give up on it.
4311 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07004312static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07004313{
Mel Gormandd1a2392008-04-28 02:12:17 -07004314 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07004315 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07004316 unsigned long nr_soft_reclaimed;
4317 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07004318 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07004319 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08004320
Mel Gormancc715d92012-03-21 16:34:00 -07004321 /*
4322 * If the number of buffer_heads in the machine exceeds the maximum
4323 * allowed level, force direct reclaim to scan the highmem zone as
4324 * highmem pages could be pinning lowmem pages storing buffer_heads
4325 */
Weijie Yang619d0d762014-04-07 15:36:59 -07004326 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07004327 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07004328 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07004329 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07004330 }
Mel Gormancc715d92012-03-21 16:34:00 -07004331
Mel Gormand4debc62010-08-09 17:19:29 -07004332 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07004333 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07004334 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08004335 * Take care memory controller reclaiming has small influence
4336 * to global LRU.
4337 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08004338 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04004339 if (!cpuset_zone_allowed(zone,
4340 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08004341 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07004342
Johannes Weiner0b064962014-08-06 16:06:12 -07004343 /*
4344 * If we already have plenty of memory free for
4345 * compaction in this zone, don't free any more.
4346 * Even though compaction is invoked for any
4347 * non-zero order, only frequent costly order
4348 * reclamation is disruptive enough to become a
4349 * noticeable problem, like transparent huge
4350 * page allocations.
4351 */
4352 if (IS_ENABLED(CONFIG_COMPACTION) &&
4353 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07004354 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07004355 sc->compaction_ready = true;
4356 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07004357 }
Johannes Weiner0b064962014-08-06 16:06:12 -07004358
Andrew Morton0608f432013-09-24 15:27:41 -07004359 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07004360 * Shrink each node in the zonelist once. If the
4361 * zonelist is ordered by zone (not the default) then a
4362 * node may be shrunk multiple times but in that case
4363 * the user prefers lower zones being preserved.
4364 */
4365 if (zone->zone_pgdat == last_pgdat)
4366 continue;
4367
4368 /*
Andrew Morton0608f432013-09-24 15:27:41 -07004369 * This steals pages from memory cgroups over softlimit
4370 * and returns the number of reclaimed pages and
4371 * scanned pages. This works for global memory pressure
4372 * and balancing, not for a memcg's limit.
4373 */
4374 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07004375 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07004376 sc->order, sc->gfp_mask,
4377 &nr_soft_scanned);
4378 sc->nr_reclaimed += nr_soft_reclaimed;
4379 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07004380 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08004381 }
Nick Piggin408d8542006-09-25 23:31:27 -07004382
Mel Gorman79dafcd2016-07-28 15:45:53 -07004383 /* See comment about same check for global reclaim above */
4384 if (zone->zone_pgdat == last_pgdat)
4385 continue;
4386 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07004387 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004388 }
Mel Gormane0c23272011-10-31 17:09:33 -07004389
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07004390 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07004391 * Restore to original mask to avoid the impact on the caller if we
4392 * promoted it to __GFP_HIGHMEM.
4393 */
4394 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004395}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07004396
Johannes Weinerb9107182019-11-30 17:55:59 -08004397static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004398{
Johannes Weinerb9107182019-11-30 17:55:59 -08004399 struct lruvec *target_lruvec;
4400 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004401
Yu Zhaoa1537a62022-01-27 20:32:37 -07004402 if (lru_gen_enabled())
4403 return;
4404
Johannes Weinerb9107182019-11-30 17:55:59 -08004405 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07004406 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
4407 target_lruvec->refaults[0] = refaults;
4408 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
4409 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004410}
4411
Linus Torvalds1da177e2005-04-16 15:20:36 -07004412/*
4413 * This is the main entry point to direct page reclaim.
4414 *
4415 * If a full scan of the inactive list fails to free enough memory then we
4416 * are "out of memory" and something needs to be killed.
4417 *
4418 * If the caller is !__GFP_FS then the probability of a failure is reasonably
4419 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02004420 * caller can't do much about. We kick the writeback threads and take explicit
4421 * naps in the hope that some of these pages can be written. But if the
4422 * allocating task holds filesystem locks which prevent writeout this might not
4423 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07004424 *
4425 * returns: 0, if no pages reclaimed
4426 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07004427 */
Mel Gormandac1d272008-04-28 02:12:12 -07004428static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07004429 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07004430{
Johannes Weiner241994ed2015-02-11 15:26:06 -08004431 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004432 pg_data_t *last_pgdat;
4433 struct zoneref *z;
4434 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08004435retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07004436 delayacct_freepages_start();
4437
Johannes Weinerb5ead352019-11-30 17:55:40 -08004438 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07004439 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07004440
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004441 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07004442 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
4443 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08004444 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07004445 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07004446
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07004447 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07004448 break;
4449
4450 if (sc->compaction_ready)
4451 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004452
4453 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08004454 * If we're getting trouble reclaiming, start doing
4455 * writepage even in laptop mode.
4456 */
4457 if (sc->priority < DEF_PRIORITY - 2)
4458 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07004459 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07004460
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004461 last_pgdat = NULL;
4462 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
4463 sc->nodemask) {
4464 if (zone->zone_pgdat == last_pgdat)
4465 continue;
4466 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08004467
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004468 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08004469
4470 if (cgroup_reclaim(sc)) {
4471 struct lruvec *lruvec;
4472
4473 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
4474 zone->zone_pgdat);
4475 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
4476 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07004477 }
4478
Keika Kobayashi873b4772008-07-25 01:48:52 -07004479 delayacct_freepages_end();
4480
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07004481 if (sc->nr_reclaimed)
4482 return sc->nr_reclaimed;
4483
Mel Gorman0cee34f2012-01-12 17:19:49 -08004484 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07004485 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08004486 return 1;
4487
Johannes Weinerb91ac372019-11-30 17:56:02 -08004488 /*
4489 * We make inactive:active ratio decisions based on the node's
4490 * composition of memory, but a restrictive reclaim_idx or a
4491 * memory.low cgroup setting can exempt large amounts of
4492 * memory from reclaim. Neither of which are very common, so
4493 * instead of doing costly eligibility calculations of the
4494 * entire cgroup subtree up front, we assume the estimates are
4495 * good, and retry with forcible deactivation if that fails.
4496 */
4497 if (sc->skipped_deactivate) {
4498 sc->priority = initial_priority;
4499 sc->force_deactivate = 1;
4500 sc->skipped_deactivate = 0;
4501 goto retry;
4502 }
4503
Johannes Weiner241994ed2015-02-11 15:26:06 -08004504 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07004505 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08004506 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08004507 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07004508 sc->memcg_low_reclaim = 1;
4509 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08004510 goto retry;
4511 }
4512
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07004513 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07004514}
4515
Johannes Weinerc73322d2017-05-03 14:51:51 -07004516static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07004517{
4518 struct zone *zone;
4519 unsigned long pfmemalloc_reserve = 0;
4520 unsigned long free_pages = 0;
4521 int i;
4522 bool wmark_ok;
4523
Johannes Weinerc73322d2017-05-03 14:51:51 -07004524 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
4525 return true;
4526
Mel Gorman55150612012-07-31 16:44:35 -07004527 for (i = 0; i <= ZONE_NORMAL; i++) {
4528 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07004529 if (!managed_zone(zone))
4530 continue;
4531
4532 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07004533 continue;
4534
Mel Gorman55150612012-07-31 16:44:35 -07004535 pfmemalloc_reserve += min_wmark_pages(zone);
4536 free_pages += zone_page_state(zone, NR_FREE_PAGES);
4537 }
4538
Mel Gorman675becc2014-06-04 16:07:35 -07004539 /* If there are no reserves (unexpected config) then do not throttle */
4540 if (!pfmemalloc_reserve)
4541 return true;
4542
Mel Gorman55150612012-07-31 16:44:35 -07004543 wmark_ok = free_pages > pfmemalloc_reserve / 2;
4544
4545 /* kswapd must be awake if processes are being throttled */
4546 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004547 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
4548 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07004549
Mel Gorman55150612012-07-31 16:44:35 -07004550 wake_up_interruptible(&pgdat->kswapd_wait);
4551 }
4552
4553 return wmark_ok;
4554}
4555
4556/*
4557 * Throttle direct reclaimers if backing storage is backed by the network
4558 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
4559 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08004560 * when the low watermark is reached.
4561 *
4562 * Returns true if a fatal signal was delivered during throttling. If this
4563 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07004564 */
Mel Gorman50694c22012-11-26 16:29:48 -08004565static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07004566 nodemask_t *nodemask)
4567{
Mel Gorman675becc2014-06-04 16:07:35 -07004568 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07004569 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07004570 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07004571
4572 /*
4573 * Kernel threads should not be throttled as they may be indirectly
4574 * responsible for cleaning pages necessary for reclaim to make forward
4575 * progress. kjournald for example may enter direct reclaim while
4576 * committing a transaction where throttling it could forcing other
4577 * processes to block on log_wait_commit().
4578 */
4579 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08004580 goto out;
4581
4582 /*
4583 * If a fatal signal is pending, this process should not throttle.
4584 * It should return quickly so it can exit and free its memory
4585 */
4586 if (fatal_signal_pending(current))
4587 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07004588
Mel Gorman675becc2014-06-04 16:07:35 -07004589 /*
4590 * Check if the pfmemalloc reserves are ok by finding the first node
4591 * with a usable ZONE_NORMAL or lower zone. The expectation is that
4592 * GFP_KERNEL will be required for allocating network buffers when
4593 * swapping over the network so ZONE_HIGHMEM is unusable.
4594 *
4595 * Throttling is based on the first usable node and throttled processes
4596 * wait on a queue until kswapd makes progress and wakes them. There
4597 * is an affinity then between processes waking up and where reclaim
4598 * progress has been made assuming the process wakes on the same node.
4599 * More importantly, processes running on remote nodes will not compete
4600 * for remote pfmemalloc reserves and processes on different nodes
4601 * should make reasonable progress.
4602 */
4603 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08004604 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07004605 if (zone_idx(zone) > ZONE_NORMAL)
4606 continue;
4607
4608 /* Throttle based on the first usable node */
4609 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07004610 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07004611 goto out;
4612 break;
4613 }
4614
4615 /* If no zone was usable by the allocation flags then do not throttle */
4616 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08004617 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07004618
Mel Gorman68243e72012-07-31 16:44:39 -07004619 /* Account for the throttling */
4620 count_vm_event(PGSCAN_DIRECT_THROTTLE);
4621
Mel Gorman55150612012-07-31 16:44:35 -07004622 /*
4623 * If the caller cannot enter the filesystem, it's possible that it
4624 * is due to the caller holding an FS lock or performing a journal
4625 * transaction in the case of a filesystem like ext[3|4]. In this case,
4626 * it is not safe to block on pfmemalloc_wait as kswapd could be
4627 * blocked waiting on the same lock. Instead, throttle for up to a
4628 * second before continuing.
4629 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07004630 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07004631 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07004632 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07004633 else
4634 /* Throttle until kswapd wakes the process */
4635 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
4636 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08004637
Mel Gorman50694c22012-11-26 16:29:48 -08004638 if (fatal_signal_pending(current))
4639 return true;
4640
4641out:
4642 return false;
Mel Gorman55150612012-07-31 16:44:35 -07004643}
4644
Mel Gormandac1d272008-04-28 02:12:12 -07004645unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07004646 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08004647{
Mel Gorman33906bc2010-08-09 17:19:16 -07004648 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08004649 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08004650 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07004651 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07004652 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07004653 .order = order,
4654 .nodemask = nodemask,
4655 .priority = DEF_PRIORITY,
4656 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07004657 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07004658 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08004659 };
4660
Mel Gorman55150612012-07-31 16:44:35 -07004661 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07004662 * scan_control uses s8 fields for order, priority, and reclaim_idx.
4663 * Confirm they are large enough for max values.
4664 */
4665 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
4666 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
4667 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
4668
4669 /*
Mel Gorman50694c22012-11-26 16:29:48 -08004670 * Do not enter reclaim if fatal signal was delivered while throttled.
4671 * 1 is returned so that the page allocator does not OOM kill at this
4672 * point.
Mel Gorman55150612012-07-31 16:44:35 -07004673 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07004674 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07004675 return 1;
4676
Andrew Morton1732d2b012019-07-16 16:26:15 -07004677 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07004678 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07004679
Vladimir Davydov3115cd92014-04-03 14:47:22 -07004680 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07004681
4682 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07004683 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07004684
4685 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08004686}
4687
Andrew Mortonc255a452012-07-31 16:43:02 -07004688#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08004689
Michal Hockod2e5fb92019-08-30 16:04:50 -07004690/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07004691unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07004692 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07004693 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07004694 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07004695{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004696 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07004697 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07004698 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07004699 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07004700 .may_writepage = !laptop_mode,
4701 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07004702 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07004703 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07004704 };
Ying Han0ae5e892011-05-26 16:25:25 -07004705
Michal Hockod2e5fb92019-08-30 16:04:50 -07004706 WARN_ON_ONCE(!current->reclaim_state);
4707
Balbir Singh4e416952009-09-23 15:56:39 -07004708 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
4709 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004710
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07004711 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07004712 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004713
Balbir Singh4e416952009-09-23 15:56:39 -07004714 /*
4715 * NOTE: Although we can get the priority field, using it
4716 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07004717 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07004718 * will pick up pages from other mem cgroup's as well. We hack
4719 * the priority and make it zero.
4720 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08004721 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004722
4723 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
4724
Ying Han0ae5e892011-05-26 16:25:25 -07004725 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07004726
Balbir Singh4e416952009-09-23 15:56:39 -07004727 return sc.nr_reclaimed;
4728}
4729
Johannes Weiner72835c82012-01-12 17:18:32 -08004730unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07004731 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08004732 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07004733 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08004734{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004735 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07004736 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08004737 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07004738 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07004739 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07004740 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07004741 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07004742 .target_mem_cgroup = memcg,
4743 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08004744 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07004745 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07004746 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07004747 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08004748 /*
4749 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
4750 * equal pressure on all the nodes. This is based on the assumption that
4751 * the reclaim does not bail out early.
4752 */
4753 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08004754
Andrew Morton1732d2b012019-07-16 16:26:15 -07004755 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07004756 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07004757 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07004758
Vladimir Davydov3115cd92014-04-03 14:47:22 -07004759 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07004760
Vlastimil Babka499118e2017-05-08 15:59:50 -07004761 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004762 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07004763 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07004764
4765 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08004766}
4767#endif
4768
Mel Gorman1d82de62016-07-28 15:45:43 -07004769static void age_active_anon(struct pglist_data *pgdat,
Mel Gormanef8f2322016-07-28 15:46:05 -07004770 struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08004771{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08004772 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08004773 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08004774
Yu Zhaoa1537a62022-01-27 20:32:37 -07004775 if (lru_gen_enabled()) {
4776 lru_gen_age_node(pgdat, sc);
4777 return;
4778 }
4779
Dave Hansen2f368a92021-09-02 14:59:23 -07004780 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08004781 return;
4782
Johannes Weinerb91ac372019-11-30 17:56:02 -08004783 lruvec = mem_cgroup_lruvec(NULL, pgdat);
4784 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
4785 return;
4786
Johannes Weinerb95a2f22012-01-12 17:18:06 -08004787 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4788 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08004789 lruvec = mem_cgroup_lruvec(memcg, pgdat);
4790 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
4791 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08004792 memcg = mem_cgroup_iter(NULL, memcg, NULL);
4793 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08004794}
4795
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004796static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08004797{
4798 int i;
4799 struct zone *zone;
4800
4801 /*
4802 * Check for watermark boosts top-down as the higher zones
4803 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07004804 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08004805 * start prematurely when there is no boosting and a lower
4806 * zone is balanced.
4807 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004808 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08004809 zone = pgdat->node_zones + i;
4810 if (!managed_zone(zone))
4811 continue;
4812
4813 if (zone->watermark_boost)
4814 return true;
4815 }
4816
4817 return false;
4818}
4819
Mel Gormane716f2e2017-05-03 14:53:45 -07004820/*
4821 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004822 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07004823 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004824static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08004825{
Mel Gormane716f2e2017-05-03 14:53:45 -07004826 int i;
4827 unsigned long mark = -1;
4828 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08004829
Mel Gorman1c308442018-12-28 00:35:52 -08004830 /*
4831 * Check watermarks bottom-up as lower zones are more likely to
4832 * meet watermarks.
4833 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004834 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07004835 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07004836
Mel Gormane716f2e2017-05-03 14:53:45 -07004837 if (!managed_zone(zone))
4838 continue;
4839
4840 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004841 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07004842 return true;
4843 }
4844
4845 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004846 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07004847 * need balancing by definition. This can happen if a zone-restricted
4848 * allocation tries to wake a remote kswapd.
4849 */
4850 if (mark == -1)
4851 return true;
4852
4853 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08004854}
4855
Mel Gorman631b6e02017-05-03 14:53:41 -07004856/* Clear pgdat state for congested, dirty or under writeback. */
4857static void clear_pgdat_congested(pg_data_t *pgdat)
4858{
Johannes Weiner1b051172019-11-30 17:55:52 -08004859 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
4860
4861 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07004862 clear_bit(PGDAT_DIRTY, &pgdat->flags);
4863 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
4864}
4865
Mel Gorman1741c872011-01-13 15:46:21 -08004866/*
Mel Gorman55150612012-07-31 16:44:35 -07004867 * Prepare kswapd for sleeping. This verifies that there are no processes
4868 * waiting in throttle_direct_reclaim() and that watermarks have been met.
4869 *
4870 * Returns true if kswapd is ready to sleep
4871 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004872static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
4873 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08004874{
Mel Gorman55150612012-07-31 16:44:35 -07004875 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08004876 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07004877 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08004878 * race between when kswapd checks the watermarks and a process gets
4879 * throttled. There is also a potential race if processes get
4880 * throttled, kswapd wakes, a large process exits thereby balancing the
4881 * zones, which causes kswapd to exit balance_pgdat() before reaching
4882 * the wake up checks. If kswapd is going to sleep, no process should
4883 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
4884 * the wake up is premature, processes will wake kswapd and get
4885 * throttled again. The difference from wake ups in balance_pgdat() is
4886 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07004887 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08004888 if (waitqueue_active(&pgdat->pfmemalloc_wait))
4889 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08004890
Johannes Weinerc73322d2017-05-03 14:51:51 -07004891 /* Hopeless node, leave it to direct reclaim */
4892 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
4893 return true;
4894
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004895 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07004896 clear_pgdat_congested(pgdat);
4897 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07004898 }
4899
Shantanu Goel333b0a42017-05-03 14:53:38 -07004900 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08004901}
4902
Linus Torvalds1da177e2005-04-16 15:20:36 -07004903/*
Mel Gorman1d82de62016-07-28 15:45:43 -07004904 * kswapd shrinks a node of pages that are at or below the highest usable
4905 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07004906 *
4907 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07004908 * reclaim or if the lack of progress was due to pages under writeback.
4909 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07004910 */
Mel Gorman1d82de62016-07-28 15:45:43 -07004911static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07004912 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07004913{
Mel Gorman1d82de62016-07-28 15:45:43 -07004914 struct zone *zone;
4915 int z;
Mel Gorman75485362013-07-03 15:01:42 -07004916
Mel Gorman1d82de62016-07-28 15:45:43 -07004917 /* Reclaim a number of pages proportional to the number of zones */
4918 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07004919 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07004920 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07004921 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07004922 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07004923
Mel Gorman1d82de62016-07-28 15:45:43 -07004924 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07004925 }
4926
Mel Gorman1d82de62016-07-28 15:45:43 -07004927 /*
4928 * Historically care was taken to put equal pressure on all zones but
4929 * now pressure is applied based on node LRU order.
4930 */
Mel Gorman970a39a2016-07-28 15:46:35 -07004931 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07004932
4933 /*
4934 * Fragmentation may mean that the system cannot be rebalanced for
4935 * high-order allocations. If twice the allocation size has been
4936 * reclaimed then recheck watermarks only at order-0 to prevent
4937 * excessive reclaim. Assume that a process requested a high-order
4938 * can direct reclaim/compact.
4939 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07004940 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07004941 sc->order = 0;
4942
Mel Gormanb8e83b92013-07-03 15:01:45 -07004943 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07004944}
4945
Mel Gormanc49c2c42021-06-28 19:42:21 -07004946/* Page allocator PCP high watermark is lowered if reclaim is active. */
4947static inline void
4948update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
4949{
4950 int i;
4951 struct zone *zone;
4952
4953 for (i = 0; i <= highest_zoneidx; i++) {
4954 zone = pgdat->node_zones + i;
4955
4956 if (!managed_zone(zone))
4957 continue;
4958
4959 if (active)
4960 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4961 else
4962 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
4963 }
4964}
4965
4966static inline void
4967set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4968{
4969 update_reclaim_active(pgdat, highest_zoneidx, true);
4970}
4971
4972static inline void
4973clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
4974{
4975 update_reclaim_active(pgdat, highest_zoneidx, false);
4976}
4977
Mel Gorman75485362013-07-03 15:01:42 -07004978/*
Mel Gorman1d82de62016-07-28 15:45:43 -07004979 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
4980 * that are eligible for use by the caller until at least one zone is
4981 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07004982 *
Mel Gorman1d82de62016-07-28 15:45:43 -07004983 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07004984 *
4985 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07004986 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08004987 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07004988 * or lower is eligible for reclaim until at least one usable zone is
4989 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07004990 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07004991static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07004992{
Linus Torvalds1da177e2005-04-16 15:20:36 -07004993 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07004994 unsigned long nr_soft_reclaimed;
4995 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07004996 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08004997 unsigned long nr_boost_reclaim;
4998 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
4999 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07005000 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08005001 struct scan_control sc = {
5002 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07005003 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005004 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08005005 };
Omar Sandoval93781322018-06-07 17:07:02 -07005006
Andrew Morton1732d2b012019-07-16 16:26:15 -07005007 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07005008 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07005009 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07005010
Christoph Lameterf8891e52006-06-30 01:55:45 -07005011 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005012
Mel Gorman1c308442018-12-28 00:35:52 -08005013 /*
5014 * Account for the reclaim boost. Note that the zone boost is left in
5015 * place so that parallel allocations that are near the watermark will
5016 * stall or direct reclaim until kswapd is finished.
5017 */
5018 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005019 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08005020 zone = pgdat->node_zones + i;
5021 if (!managed_zone(zone))
5022 continue;
5023
5024 nr_boost_reclaim += zone->watermark_boost;
5025 zone_boosts[i] = zone->watermark_boost;
5026 }
5027 boosted = nr_boost_reclaim;
5028
5029restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07005030 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08005031 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005032 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07005033 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07005034 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08005035 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07005036 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07005037
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005038 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005039
Mel Gorman86c79f62016-07-28 15:45:59 -07005040 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07005041 * If the number of buffer_heads exceeds the maximum allowed
5042 * then consider reclaiming from all zones. This has a dual
5043 * purpose -- on 64-bit systems it is expected that
5044 * buffer_heads are stripped during active rotation. On 32-bit
5045 * systems, highmem pages can pin lowmem memory and shrinking
5046 * buffers can relieve lowmem pressure. Reclaim may still not
5047 * go ahead if all eligible zones for the original allocation
5048 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07005049 */
5050 if (buffer_heads_over_limit) {
5051 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
5052 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07005053 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07005054 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005055
Mel Gorman970a39a2016-07-28 15:46:35 -07005056 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08005057 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005058 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07005059 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08005060
Mel Gorman86c79f62016-07-28 15:45:59 -07005061 /*
Mel Gorman1c308442018-12-28 00:35:52 -08005062 * If the pgdat is imbalanced then ignore boosting and preserve
5063 * the watermarks for a later time and restart. Note that the
5064 * zone watermarks will be still reset at the end of balancing
5065 * on the grounds that the normal reclaim should be enough to
5066 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07005067 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005068 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08005069 if (!balanced && nr_boost_reclaim) {
5070 nr_boost_reclaim = 0;
5071 goto restart;
5072 }
5073
5074 /*
5075 * If boosting is not active then only reclaim if there are no
5076 * eligible zones. Note that sc.reclaim_idx is not used as
5077 * buffer_heads_over_limit may have adjusted it.
5078 */
5079 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07005080 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08005081
Mel Gorman1c308442018-12-28 00:35:52 -08005082 /* Limit the priority of boosting to avoid reclaim writeback */
5083 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
5084 raise_priority = false;
5085
5086 /*
5087 * Do not writeback or swap pages for boosted reclaim. The
5088 * intent is to relieve pressure not issue sub-optimal IO
5089 * from reclaim context. If no pages are reclaimed, the
5090 * reclaim will be aborted.
5091 */
5092 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
5093 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08005094
Linus Torvalds1da177e2005-04-16 15:20:36 -07005095 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07005096 * Do some background aging of the anon list, to give
5097 * pages a chance to be referenced before reclaiming. All
5098 * pages are rotated regardless of classzone as this is
5099 * about consistent aging.
5100 */
Mel Gormanef8f2322016-07-28 15:46:05 -07005101 age_active_anon(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07005102
5103 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07005104 * If we're getting trouble reclaiming, start doing writepage
5105 * even in laptop mode.
5106 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07005107 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07005108 sc.may_writepage = 1;
5109
Mel Gorman1d82de62016-07-28 15:45:43 -07005110 /* Call soft limit reclaim before calling shrink_node. */
5111 sc.nr_scanned = 0;
5112 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07005113 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07005114 sc.gfp_mask, &nr_soft_scanned);
5115 sc.nr_reclaimed += nr_soft_reclaimed;
5116
Mel Gormanb7ea3c42013-07-03 15:01:53 -07005117 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07005118 * There should be no need to raise the scanning priority if
5119 * enough pages are already being scanned that that high
5120 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005121 */
Mel Gorman970a39a2016-07-28 15:46:35 -07005122 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07005123 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07005124
5125 /*
5126 * If the low watermark is met there is no need for processes
5127 * to be throttled on pfmemalloc_wait as they should not be
5128 * able to safely make forward progress. Wake them
5129 */
5130 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07005131 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08005132 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07005133
Mel Gormanb8e83b92013-07-03 15:01:45 -07005134 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07005135 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07005136 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07005137 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07005138 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07005139 break;
5140
5141 /*
5142 * Raise priority if scanning rate is too low or there was no
5143 * progress in reclaiming pages
5144 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07005145 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08005146 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
5147
5148 /*
5149 * If reclaim made no progress for a boost, stop reclaim as
5150 * IO cannot be queued and it could be an infinite loop in
5151 * extreme circumstances.
5152 */
5153 if (nr_boost_reclaim && !nr_reclaimed)
5154 break;
5155
Johannes Weinerc73322d2017-05-03 14:51:51 -07005156 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07005157 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07005158 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005159
Johannes Weinerc73322d2017-05-03 14:51:51 -07005160 if (!sc.nr_reclaimed)
5161 pgdat->kswapd_failures++;
5162
Mel Gormanb8e83b92013-07-03 15:01:45 -07005163out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07005164 clear_reclaim_active(pgdat, highest_zoneidx);
5165
Mel Gorman1c308442018-12-28 00:35:52 -08005166 /* If reclaim was boosted, account for the reclaim done in this pass */
5167 if (boosted) {
5168 unsigned long flags;
5169
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005170 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08005171 if (!zone_boosts[i])
5172 continue;
5173
5174 /* Increments are under the zone lock */
5175 zone = pgdat->node_zones + i;
5176 spin_lock_irqsave(&zone->lock, flags);
5177 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
5178 spin_unlock_irqrestore(&zone->lock, flags);
5179 }
5180
5181 /*
5182 * As there is now likely space, wakeup kcompact to defragment
5183 * pageblocks.
5184 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005185 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08005186 }
5187
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005188 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07005189 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07005190 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005191 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07005192
Mel Gorman0abdee22011-01-13 15:46:22 -08005193 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07005194 * Return the order kswapd stopped reclaiming at as
5195 * prepare_kswapd_sleep() takes it into account. If another caller
5196 * entered the allocator slow path while kswapd was awake, order will
5197 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08005198 */
Mel Gorman1d82de62016-07-28 15:45:43 -07005199 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005200}
5201
Mel Gormane716f2e2017-05-03 14:53:45 -07005202/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005203 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
5204 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
5205 * not a valid index then either kswapd runs for first time or kswapd couldn't
5206 * sleep after previous reclaim attempt (node is still unbalanced). In that
5207 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07005208 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005209static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
5210 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07005211{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005212 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005213
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005214 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07005215}
5216
Mel Gorman38087d92016-07-28 15:45:49 -07005217static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005218 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005219{
5220 long remaining = 0;
5221 DEFINE_WAIT(wait);
5222
5223 if (freezing(current) || kthread_should_stop())
5224 return;
5225
5226 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
5227
Shantanu Goel333b0a42017-05-03 14:53:38 -07005228 /*
5229 * Try to sleep for a short interval. Note that kcompactd will only be
5230 * woken if it is possible to sleep for a short interval. This is
5231 * deliberate on the assumption that if reclaim cannot keep an
5232 * eligible zone balanced that it's also unlikely that compaction will
5233 * succeed.
5234 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005235 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07005236 /*
5237 * Compaction records what page blocks it recently failed to
5238 * isolate pages from and skips them in the future scanning.
5239 * When kswapd is going to sleep, it is reasonable to assume
5240 * that pages and compaction may succeed so reset the cache.
5241 */
5242 reset_isolation_suitable(pgdat);
5243
5244 /*
5245 * We have freed the memory, now we should compact it to make
5246 * allocation of the requested order possible.
5247 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005248 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07005249
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005250 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07005251
5252 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005253 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07005254 * order. The values will either be from a wakeup request or
5255 * the previous request that slept prematurely.
5256 */
5257 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005258 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
5259 kswapd_highest_zoneidx(pgdat,
5260 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07005261
5262 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
5263 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07005264 }
5265
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005266 finish_wait(&pgdat->kswapd_wait, &wait);
5267 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
5268 }
5269
5270 /*
5271 * After a short sleep, check if it was a premature sleep. If not, then
5272 * go fully to sleep until explicitly woken up.
5273 */
Mel Gormand9f21d42016-07-28 15:46:41 -07005274 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005275 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005276 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
5277
5278 /*
5279 * vmstat counters are not perfectly accurate and the estimated
5280 * value for counters such as NR_FREE_PAGES can deviate from the
5281 * true value by nr_online_cpus * threshold. To avoid the zone
5282 * watermarks being breached while under pressure, we reduce the
5283 * per-cpu vmstat threshold while kswapd is awake and restore
5284 * them before going back to sleep.
5285 */
5286 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07005287
5288 if (!kthread_should_stop())
5289 schedule();
5290
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08005291 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
5292 } else {
5293 if (remaining)
5294 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
5295 else
5296 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
5297 }
5298 finish_wait(&pgdat->kswapd_wait, &wait);
5299}
5300
Linus Torvalds1da177e2005-04-16 15:20:36 -07005301/*
5302 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005303 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005304 *
5305 * This basically trickles out pages so that we have _some_
5306 * free memory available even if there is no other activity
5307 * that frees anything up. This is needed for things like routing
5308 * etc, where we otherwise might have all activity going on in
5309 * asynchronous contexts that cannot page things out.
5310 *
5311 * If there are applications that are active memory-allocators
5312 * (most normal use), this basically shouldn't matter.
5313 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05305314int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005315{
Mel Gormane716f2e2017-05-03 14:53:45 -07005316 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005317 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07005318 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005319 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10305320 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005321
Rusty Russell174596a2009-01-01 10:12:29 +10305322 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07005323 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005324
5325 /*
5326 * Tell the memory management that we're a "memory allocator",
5327 * and that if we need more memory we should get access to it
5328 * regardless (see "__alloc_pages()"). "kswapd" should
5329 * never get caught in the normal page freeing logic.
5330 *
5331 * (Kswapd normally doesn't need memory anyway, but sometimes
5332 * you need a small amount of memory in order to be able to
5333 * page out something else, and this flag essentially protects
5334 * us from recursively trying to free more memory as we're
5335 * trying to free the first piece of memory in the first place).
5336 */
Christoph Lameter930d9152006-01-08 01:00:47 -08005337 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07005338 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07005339
Qian Cai5644e1fb2020-04-01 21:10:12 -07005340 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005341 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005342 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08005343 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07005344
Qian Cai5644e1fb2020-04-01 21:10:12 -07005345 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005346 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
5347 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07005348
Mel Gorman38087d92016-07-28 15:45:49 -07005349kswapd_try_sleep:
5350 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005351 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07005352
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005353 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08005354 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005355 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
5356 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005357 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005358 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005359
David Rientjes8fe23e02009-12-14 17:58:33 -08005360 ret = try_to_freeze();
5361 if (kthread_should_stop())
5362 break;
5363
5364 /*
5365 * We can speed up thawing tasks if we don't call balance_pgdat
5366 * after returning from the refrigerator
5367 */
Mel Gorman38087d92016-07-28 15:45:49 -07005368 if (ret)
5369 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07005370
Mel Gorman38087d92016-07-28 15:45:49 -07005371 /*
5372 * Reclaim begins at the requested order but if a high-order
5373 * reclaim fails then kswapd falls back to reclaiming for
5374 * order-0. If that happens, kswapd will consider sleeping
5375 * for the order it finished reclaiming at (reclaim_order)
5376 * but kcompactd is woken to compact for the original
5377 * request (alloc_order).
5378 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005379 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07005380 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005381 reclaim_order = balance_pgdat(pgdat, alloc_order,
5382 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07005383 if (reclaim_order < alloc_order)
5384 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005385 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08005386
Johannes Weiner71abdc12014-06-06 14:35:35 -07005387 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07005388
Linus Torvalds1da177e2005-04-16 15:20:36 -07005389 return 0;
5390}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05305391EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005392
5393/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07005394 * A zone is low on free memory or too fragmented for high-order memory. If
5395 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
5396 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
5397 * has failed or is not needed, still wake up kcompactd if only compaction is
5398 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005399 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07005400void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005401 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005402{
5403 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07005404 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005405
Mel Gorman6aa303d2016-09-01 16:14:55 -07005406 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07005407 return;
5408
David Rientjes5ecd9d42018-04-05 16:25:16 -07005409 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07005410 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07005411
Qian Cai5644e1fb2020-04-01 21:10:12 -07005412 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005413 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005414
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005415 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
5416 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005417
5418 if (READ_ONCE(pgdat->kswapd_order) < order)
5419 WRITE_ONCE(pgdat->kswapd_order, order);
5420
Con Kolivas8d0986e2005-09-13 01:25:07 -07005421 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07005422 return;
Mel Gormane1a55632016-07-28 15:46:26 -07005423
David Rientjes5ecd9d42018-04-05 16:25:16 -07005424 /* Hopeless node, leave it to direct reclaim if possible */
5425 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005426 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
5427 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07005428 /*
5429 * There may be plenty of free memory available, but it's too
5430 * fragmented for high-order allocations. Wake up kcompactd
5431 * and rely on compaction_suitable() to determine if it's
5432 * needed. If it fails, it will defer subsequent attempts to
5433 * ratelimit its work.
5434 */
5435 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005436 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07005437 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07005438 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07005439
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005440 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07005441 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07005442 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005443}
5444
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02005445#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07005446/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005447 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07005448 * freed pages.
5449 *
5450 * Rather than trying to age LRUs the aim is to preserve the overall
5451 * LRU order by reclaiming preferentially
5452 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07005453 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005454unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005455{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07005456 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005457 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07005458 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07005459 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005460 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07005461 .may_writepage = 1,
5462 .may_unmap = 1,
5463 .may_swap = 1,
5464 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07005465 };
Ying Hana09ed5e2011-05-24 17:12:26 -07005466 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005467 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07005468 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005469
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01005470 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07005471 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07005472 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08005473
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005474 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07005475
Andrew Morton1732d2b012019-07-16 16:26:15 -07005476 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07005477 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07005478 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07005479
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08005480 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005481}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02005482#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07005483
Yasunori Goto3218ae12006-06-27 02:53:33 -07005484/*
5485 * This kswapd start function will be called by init and node-hot-add.
5486 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
5487 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07005488void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07005489{
5490 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05305491 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07005492
5493 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07005494 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07005495
Charan Teja Reddyd831f072021-02-05 17:47:57 +05305496 trace_android_vh_kswapd_per_node(nid, &skip, true);
5497 if (skip)
5498 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07005499 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
5500 if (IS_ERR(pgdat->kswapd)) {
5501 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02005502 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07005503 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07005504 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07005505 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07005506}
5507
David Rientjes8fe23e02009-12-14 17:58:33 -08005508/*
Jiang Liud8adde12012-07-11 14:01:52 -07005509 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07005510 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08005511 */
5512void kswapd_stop(int nid)
5513{
5514 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05305515 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08005516
Charan Teja Reddyd831f072021-02-05 17:47:57 +05305517 trace_android_vh_kswapd_per_node(nid, &skip, false);
5518 if (skip)
5519 return;
Jiang Liud8adde12012-07-11 14:01:52 -07005520 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08005521 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07005522 NODE_DATA(nid)->kswapd = NULL;
5523 }
David Rientjes8fe23e02009-12-14 17:58:33 -08005524}
5525
Linus Torvalds1da177e2005-04-16 15:20:36 -07005526static int __init kswapd_init(void)
5527{
Wei Yang6b700b52020-04-01 21:10:09 -07005528 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08005529
Linus Torvalds1da177e2005-04-16 15:20:36 -07005530 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08005531 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07005532 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005533 return 0;
5534}
5535
5536module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08005537
5538#ifdef CONFIG_NUMA
5539/*
Mel Gormana5f5f912016-07-28 15:46:32 -07005540 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08005541 *
Mel Gormana5f5f912016-07-28 15:46:32 -07005542 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08005543 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08005544 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005545int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08005546
Dave Hansen51998362021-02-24 12:09:15 -08005547/*
Mel Gormana5f5f912016-07-28 15:46:32 -07005548 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08005549 * of a node considered for each zone_reclaim. 4 scans 1/16th of
5550 * a zone.
5551 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005552#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08005553
Christoph Lameter9eeff232006-01-18 17:42:31 -08005554/*
Mel Gormana5f5f912016-07-28 15:46:32 -07005555 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07005556 * occur.
5557 */
5558int sysctl_min_unmapped_ratio = 1;
5559
5560/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07005561 * If the number of slab pages in a zone grows beyond this percentage then
5562 * slab reclaim needs to occur.
5563 */
5564int sysctl_min_slab_ratio = 5;
5565
Mel Gorman11fb9982016-07-28 15:46:20 -07005566static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07005567{
Mel Gorman11fb9982016-07-28 15:46:20 -07005568 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
5569 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
5570 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07005571
5572 /*
5573 * It's possible for there to be more file mapped pages than
5574 * accounted for by the pages on the file LRU lists because
5575 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
5576 */
5577 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
5578}
5579
5580/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07005581static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07005582{
Alexandru Moised031a152015-11-05 18:48:08 -08005583 unsigned long nr_pagecache_reclaimable;
5584 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07005585
5586 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07005587 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07005588 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07005589 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07005590 * a better estimate
5591 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005592 if (node_reclaim_mode & RECLAIM_UNMAP)
5593 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07005594 else
Mel Gormana5f5f912016-07-28 15:46:32 -07005595 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07005596
5597 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07005598 if (!(node_reclaim_mode & RECLAIM_WRITE))
5599 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07005600
5601 /* Watch for any possible underflows due to delta */
5602 if (unlikely(delta > nr_pagecache_reclaimable))
5603 delta = nr_pagecache_reclaimable;
5604
5605 return nr_pagecache_reclaimable - delta;
5606}
5607
Christoph Lameter0ff38492006-09-25 23:31:52 -07005608/*
Mel Gormana5f5f912016-07-28 15:46:32 -07005609 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08005610 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005611static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08005612{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08005613 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08005614 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08005615 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07005616 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08005617 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08005618 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005619 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07005620 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07005621 .priority = NODE_RECLAIM_PRIORITY,
5622 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
5623 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07005624 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005625 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08005626 };
Johannes Weiner57f29762021-08-19 19:04:27 -07005627 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08005628
Yafang Shao132bb8c2019-05-13 17:17:53 -07005629 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
5630 sc.gfp_mask);
5631
Christoph Lameter9eeff232006-01-18 17:42:31 -08005632 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07005633 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07005634 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08005635 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07005636 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08005637 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07005638 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08005639 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07005640 noreclaim_flag = memalloc_noreclaim_save();
5641 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07005642 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08005643
Mel Gormana5f5f912016-07-28 15:46:32 -07005644 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07005645 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07005646 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07005647 * priorities until we have enough memory freed.
5648 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07005649 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07005650 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005651 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07005652 }
Christoph Lameterc84db232006-02-01 03:05:29 -08005653
Andrew Morton1732d2b012019-07-16 16:26:15 -07005654 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07005655 current->flags &= ~PF_SWAPWRITE;
5656 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07005657 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07005658 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07005659
5660 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
5661
Rik van Riela79311c2009-01-06 14:40:01 -08005662 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08005663}
Andrew Morton179e9632006-03-22 00:08:18 -08005664
Mel Gormana5f5f912016-07-28 15:46:32 -07005665int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08005666{
David Rientjesd773ed62007-10-16 23:26:01 -07005667 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08005668
5669 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07005670 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07005671 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07005672 *
Christoph Lameter96146342006-07-03 00:24:13 -07005673 * A small portion of unmapped file backed pages is needed for
5674 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07005675 * thrown out if the node is overallocated. So we do not reclaim
5676 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07005677 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08005678 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005679 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07005680 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
5681 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07005682 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08005683
5684 /*
David Rientjesd773ed62007-10-16 23:26:01 -07005685 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08005686 */
Mel Gormand0164ad2015-11-06 16:28:21 -08005687 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07005688 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08005689
5690 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07005691 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08005692 * have associated processors. This will favor the local processor
5693 * over remote processors and spread off node memory allocations
5694 * as wide as possible.
5695 */
Mel Gormana5f5f912016-07-28 15:46:32 -07005696 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
5697 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07005698
Mel Gormana5f5f912016-07-28 15:46:32 -07005699 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
5700 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07005701
Mel Gormana5f5f912016-07-28 15:46:32 -07005702 ret = __node_reclaim(pgdat, gfp_mask, order);
5703 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07005704
Mel Gorman24cf725182009-06-16 15:33:23 -07005705 if (!ret)
5706 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
5707
David Rientjesd773ed62007-10-16 23:26:01 -07005708 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08005709}
Christoph Lameter9eeff232006-01-18 17:42:31 -08005710#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07005711
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005712/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005713 * check_move_unevictable_pages - check pages for evictability and move to
5714 * appropriate zone lru list
5715 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005716 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005717 * Checks pages for evictability, if an evictable page is in the unevictable
5718 * lru list, moves it to the appropriate evictable lru list. This function
5719 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005720 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005721void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005722{
Alex Shi6168d0d2020-12-15 12:34:29 -08005723 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08005724 int pgscanned = 0;
5725 int pgrescued = 0;
5726 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005727
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005728 for (i = 0; i < pvec->nr; i++) {
5729 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07005730 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07005731
Hugh Dickins8d8869c2020-09-18 21:20:12 -07005732 if (PageTransTail(page))
5733 continue;
5734
5735 nr_pages = thp_nr_pages(page);
5736 pgscanned += nr_pages;
5737
Alex Shid25b5bd2020-12-15 12:34:16 -08005738 /* block memcg migration during page moving between lru */
5739 if (!TestClearPageLRU(page))
5740 continue;
5741
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08005742 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08005743 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08005744 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08005745 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08005746 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07005747 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08005748 }
Alex Shid25b5bd2020-12-15 12:34:16 -08005749 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07005750 }
Hugh Dickins24513262012-01-20 14:34:21 -08005751
Alex Shi6168d0d2020-12-15 12:34:29 -08005752 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08005753 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
5754 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08005755 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08005756 } else if (pgscanned) {
5757 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08005758 }
Hugh Dickins850465792012-01-20 14:34:19 -08005759}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00005760EXPORT_SYMBOL_GPL(check_move_unevictable_pages);