blob: 4524543dcc04831b277678513b5b4ba174c70df0 [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001// SPDX-License-Identifier: GPL-2.0
Linus Torvalds1da177e2005-04-16 15:20:36 -07002/*
Linus Torvalds1da177e2005-04-16 15:20:36 -07003 * Copyright (C) 1991, 1992, 1993, 1994 Linus Torvalds
4 *
5 * Swap reorganised 29.12.95, Stephen Tweedie.
6 * kswapd added: 7.1.96 sct
7 * Removed kswapd_ctl limits, and swap out as many pages as needed
8 * to bring the system back to freepages.high: 2.4.97, Rik van Riel.
9 * Zone aware kswapd started 02/00, Kanoj Sarcar (kanoj@sgi.com).
10 * Multiqueue VM started 5.8.00, Rik van Riel.
11 */
12
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070013#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
Linus Torvalds1da177e2005-04-16 15:20:36 -070015#include <linux/mm.h>
Ingo Molnar5b3cc152017-02-02 20:43:54 +010016#include <linux/sched/mm.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070017#include <linux/module.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090018#include <linux/gfp.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070019#include <linux/kernel_stat.h>
20#include <linux/swap.h>
21#include <linux/pagemap.h>
22#include <linux/init.h>
23#include <linux/highmem.h>
Anton Vorontsov70ddf632013-04-29 15:08:31 -070024#include <linux/vmpressure.h>
Andrew Mortone129b5c2006-09-27 01:50:00 -070025#include <linux/vmstat.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070026#include <linux/file.h>
27#include <linux/writeback.h>
28#include <linux/blkdev.h>
29#include <linux/buffer_head.h> /* for try_to_release_page(),
30 buffer_heads_over_limit */
31#include <linux/mm_inline.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070032#include <linux/backing-dev.h>
33#include <linux/rmap.h>
34#include <linux/topology.h>
35#include <linux/cpu.h>
36#include <linux/cpuset.h>
Mel Gorman3e7d3442011-01-13 15:45:56 -080037#include <linux/compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070038#include <linux/notifier.h>
39#include <linux/rwsem.h>
Rafael J. Wysocki248a0302006-03-22 00:09:04 -080040#include <linux/delay.h>
Yasunori Goto3218ae12006-06-27 02:53:33 -070041#include <linux/kthread.h>
Nigel Cunningham7dfb7102006-12-06 20:34:23 -080042#include <linux/freezer.h>
Balbir Singh66e17072008-02-07 00:13:56 -080043#include <linux/memcontrol.h>
Dave Hansen26aa2d12021-09-02 14:59:16 -070044#include <linux/migrate.h>
Keika Kobayashi873b4772008-07-25 01:48:52 -070045#include <linux/delayacct.h>
Lee Schermerhornaf936a12008-10-18 20:26:53 -070046#include <linux/sysctl.h>
KOSAKI Motohiro929bea72011-04-14 15:22:12 -070047#include <linux/oom.h>
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +000048#include <linux/pagevec.h>
Linus Torvalds268bb0c2011-05-20 12:50:29 -070049#include <linux/prefetch.h>
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -070050#include <linux/printk.h>
Ross Zwislerf9fe48b2016-01-22 15:10:40 -080051#include <linux/dax.h>
Johannes Weinereb414682018-10-26 15:06:27 -070052#include <linux/psi.h>
Yu Zhao5280d762022-01-27 19:23:01 -070053#include <linux/pagewalk.h>
54#include <linux/shmem_fs.h>
Yu Zhao76f7f072022-01-27 19:52:09 -070055#include <linux/ctype.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070056
57#include <asm/tlbflush.h>
58#include <asm/div64.h>
59
60#include <linux/swapops.h>
Rafael Aquini117aad12013-09-30 13:45:16 -070061#include <linux/balloon_compaction.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070062
Nick Piggin0f8053a2006-03-22 00:08:33 -080063#include "internal.h"
64
Mel Gorman33906bc2010-08-09 17:19:16 -070065#define CREATE_TRACE_POINTS
66#include <trace/events/vmscan.h>
67
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -070068#undef CREATE_TRACE_POINTS
69#include <trace/hooks/vmscan.h>
70
Linus Torvalds1da177e2005-04-16 15:20:36 -070071struct scan_control {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -080072 /* How many pages shrink_list() should reclaim */
73 unsigned long nr_to_reclaim;
74
Johannes Weineree814fe2014-08-06 16:06:19 -070075 /*
76 * Nodemask of nodes allowed by the caller. If NULL, all nodes
77 * are scanned.
78 */
79 nodemask_t *nodemask;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -070080
KOSAKI Motohiro5f53e762010-05-24 14:32:37 -070081 /*
Johannes Weinerf16015f2012-01-12 17:17:52 -080082 * The memory cgroup that hit its limit and as a result is the
83 * primary target of this reclaim invocation.
84 */
85 struct mem_cgroup *target_mem_cgroup;
Balbir Singh66e17072008-02-07 00:13:56 -080086
Johannes Weiner7cf111b2020-06-03 16:03:06 -070087 /*
88 * Scan pressure balancing between anon and file LRUs
89 */
90 unsigned long anon_cost;
91 unsigned long file_cost;
92
Johannes Weinerb91ac372019-11-30 17:56:02 -080093 /* Can active pages be deactivated as part of reclaim? */
94#define DEACTIVATE_ANON 1
95#define DEACTIVATE_FILE 2
96 unsigned int may_deactivate:2;
97 unsigned int force_deactivate:1;
98 unsigned int skipped_deactivate:1;
99
Johannes Weiner1276ad62017-02-24 14:56:11 -0800100 /* Writepage batching in laptop mode; RECLAIM_WRITE */
Johannes Weineree814fe2014-08-06 16:06:19 -0700101 unsigned int may_writepage:1;
102
103 /* Can mapped pages be reclaimed? */
104 unsigned int may_unmap:1;
105
106 /* Can pages be swapped as part of reclaim? */
107 unsigned int may_swap:1;
108
Yisheng Xied6622f62017-05-03 14:53:57 -0700109 /*
Johannes Weinerf56ce412021-08-19 19:04:21 -0700110 * Cgroup memory below memory.low is protected as long as we
111 * don't threaten to OOM. If any cgroup is reclaimed at
112 * reduced force or passed over entirely due to its memory.low
113 * setting (memcg_low_skipped), and nothing is reclaimed as a
114 * result, then go back for one more cycle that reclaims the protected
115 * memory (memcg_low_reclaim) to avert OOM.
Yisheng Xied6622f62017-05-03 14:53:57 -0700116 */
117 unsigned int memcg_low_reclaim:1;
118 unsigned int memcg_low_skipped:1;
Johannes Weiner241994ed2015-02-11 15:26:06 -0800119
Johannes Weineree814fe2014-08-06 16:06:19 -0700120 unsigned int hibernation_mode:1;
121
122 /* One of the zones is ready for compaction */
123 unsigned int compaction_ready:1;
124
Johannes Weinerb91ac372019-11-30 17:56:02 -0800125 /* There is easily reclaimable cold cache in the current node */
126 unsigned int cache_trim_mode:1;
127
Johannes Weiner53138ce2019-11-30 17:55:56 -0800128 /* The file pages on the current node are dangerously low */
129 unsigned int file_is_tiny:1;
130
Dave Hansen26aa2d12021-09-02 14:59:16 -0700131 /* Always discard instead of demoting to lower tier memory */
132 unsigned int no_demotion:1;
133
Yu Zhao4d905e92022-01-27 19:59:54 -0700134#ifdef CONFIG_LRU_GEN
135 /* help make better choices when multiple memcgs are available */
136 unsigned int memcgs_need_aging:1;
137 unsigned int memcgs_need_swapping:1;
138 unsigned int memcgs_avoid_swapping:1;
139#endif
140
Greg Thelenbb451fd2018-08-17 15:45:19 -0700141 /* Allocation order */
142 s8 order;
143
144 /* Scan (total_size >> priority) pages at once */
145 s8 priority;
146
147 /* The highest zone to isolate pages for reclaim from */
148 s8 reclaim_idx;
149
150 /* This context's GFP mask */
151 gfp_t gfp_mask;
152
Johannes Weineree814fe2014-08-06 16:06:19 -0700153 /* Incremented by the number of inactive pages that were scanned */
154 unsigned long nr_scanned;
155
156 /* Number of pages freed so far during a call to shrink_zones() */
157 unsigned long nr_reclaimed;
Andrey Ryabinind108c772018-04-10 16:27:59 -0700158
159 struct {
160 unsigned int dirty;
161 unsigned int unqueued_dirty;
162 unsigned int congested;
163 unsigned int writeback;
164 unsigned int immediate;
165 unsigned int file_taken;
166 unsigned int taken;
167 } nr;
Yafang Shaoe5ca8072019-07-16 16:26:09 -0700168
169 /* for recording the reclaimed slab by now */
170 struct reclaim_state reclaim_state;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700171};
172
Linus Torvalds1da177e2005-04-16 15:20:36 -0700173#ifdef ARCH_HAS_PREFETCHW
174#define prefetchw_prev_lru_page(_page, _base, _field) \
175 do { \
176 if ((_page)->lru.prev != _base) { \
177 struct page *prev; \
178 \
179 prev = lru_to_page(&(_page->lru)); \
180 prefetchw(&prev->_field); \
181 } \
182 } while (0)
183#else
184#define prefetchw_prev_lru_page(_page, _base, _field) do { } while (0)
185#endif
186
187/*
Johannes Weinerc8439662020-06-03 16:02:37 -0700188 * From 0 .. 200. Higher means more swappy.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700189 */
190int vm_swappiness = 60;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700191
Yang Shi0a432dc2019-09-23 15:38:12 -0700192static void set_task_reclaim_state(struct task_struct *task,
193 struct reclaim_state *rs)
194{
195 /* Check for an overwrite */
196 WARN_ON_ONCE(rs && task->reclaim_state);
197
198 /* Check for the nulling of an already-nulled member */
199 WARN_ON_ONCE(!rs && !task->reclaim_state);
200
201 task->reclaim_state = rs;
202}
203
Linus Torvalds1da177e2005-04-16 15:20:36 -0700204static LIST_HEAD(shrinker_list);
205static DECLARE_RWSEM(shrinker_rwsem);
206
Yang Shi0a432dc2019-09-23 15:38:12 -0700207#ifdef CONFIG_MEMCG
Yang Shia2fb1262021-05-04 18:36:17 -0700208static int shrinker_nr_max;
Yang Shi2bfd3632021-05-04 18:36:11 -0700209
Yang Shi3c6f17e2021-05-04 18:36:33 -0700210/* The shrinker_info is expanded in a batch of BITS_PER_LONG */
Yang Shia2fb1262021-05-04 18:36:17 -0700211static inline int shrinker_map_size(int nr_items)
212{
213 return (DIV_ROUND_UP(nr_items, BITS_PER_LONG) * sizeof(unsigned long));
214}
Yang Shi2bfd3632021-05-04 18:36:11 -0700215
Yang Shi3c6f17e2021-05-04 18:36:33 -0700216static inline int shrinker_defer_size(int nr_items)
217{
218 return (round_up(nr_items, BITS_PER_LONG) * sizeof(atomic_long_t));
219}
220
Yang Shi468ab842021-05-04 18:36:26 -0700221static struct shrinker_info *shrinker_info_protected(struct mem_cgroup *memcg,
222 int nid)
223{
224 return rcu_dereference_protected(memcg->nodeinfo[nid]->shrinker_info,
225 lockdep_is_held(&shrinker_rwsem));
226}
227
Yang Shie4262c42021-05-04 18:36:23 -0700228static int expand_one_shrinker_info(struct mem_cgroup *memcg,
Yang Shi3c6f17e2021-05-04 18:36:33 -0700229 int map_size, int defer_size,
230 int old_map_size, int old_defer_size)
Yang Shi2bfd3632021-05-04 18:36:11 -0700231{
Yang Shie4262c42021-05-04 18:36:23 -0700232 struct shrinker_info *new, *old;
Yang Shi2bfd3632021-05-04 18:36:11 -0700233 struct mem_cgroup_per_node *pn;
234 int nid;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700235 int size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700236
Yang Shi2bfd3632021-05-04 18:36:11 -0700237 for_each_node(nid) {
238 pn = memcg->nodeinfo[nid];
Yang Shi468ab842021-05-04 18:36:26 -0700239 old = shrinker_info_protected(memcg, nid);
Yang Shi2bfd3632021-05-04 18:36:11 -0700240 /* Not yet online memcg */
241 if (!old)
242 return 0;
243
244 new = kvmalloc_node(sizeof(*new) + size, GFP_KERNEL, nid);
245 if (!new)
246 return -ENOMEM;
247
Yang Shi3c6f17e2021-05-04 18:36:33 -0700248 new->nr_deferred = (atomic_long_t *)(new + 1);
249 new->map = (void *)new->nr_deferred + defer_size;
250
251 /* map: set all old bits, clear all new bits */
252 memset(new->map, (int)0xff, old_map_size);
253 memset((void *)new->map + old_map_size, 0, map_size - old_map_size);
254 /* nr_deferred: copy old values, clear all new values */
255 memcpy(new->nr_deferred, old->nr_deferred, old_defer_size);
256 memset((void *)new->nr_deferred + old_defer_size, 0,
257 defer_size - old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700258
Yang Shie4262c42021-05-04 18:36:23 -0700259 rcu_assign_pointer(pn->shrinker_info, new);
Yang Shi72673e82021-05-04 18:36:20 -0700260 kvfree_rcu(old, rcu);
Yang Shi2bfd3632021-05-04 18:36:11 -0700261 }
262
263 return 0;
264}
265
Yang Shie4262c42021-05-04 18:36:23 -0700266void free_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700267{
268 struct mem_cgroup_per_node *pn;
Yang Shie4262c42021-05-04 18:36:23 -0700269 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700270 int nid;
271
Yang Shi2bfd3632021-05-04 18:36:11 -0700272 for_each_node(nid) {
273 pn = memcg->nodeinfo[nid];
Yang Shie4262c42021-05-04 18:36:23 -0700274 info = rcu_dereference_protected(pn->shrinker_info, true);
275 kvfree(info);
276 rcu_assign_pointer(pn->shrinker_info, NULL);
Yang Shi2bfd3632021-05-04 18:36:11 -0700277 }
278}
279
Yang Shie4262c42021-05-04 18:36:23 -0700280int alloc_shrinker_info(struct mem_cgroup *memcg)
Yang Shi2bfd3632021-05-04 18:36:11 -0700281{
Yang Shie4262c42021-05-04 18:36:23 -0700282 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700283 int nid, size, ret = 0;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700284 int map_size, defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700285
Yang Shid27cf2a2021-05-04 18:36:14 -0700286 down_write(&shrinker_rwsem);
Yang Shi3c6f17e2021-05-04 18:36:33 -0700287 map_size = shrinker_map_size(shrinker_nr_max);
288 defer_size = shrinker_defer_size(shrinker_nr_max);
289 size = map_size + defer_size;
Yang Shi2bfd3632021-05-04 18:36:11 -0700290 for_each_node(nid) {
Yang Shie4262c42021-05-04 18:36:23 -0700291 info = kvzalloc_node(sizeof(*info) + size, GFP_KERNEL, nid);
292 if (!info) {
293 free_shrinker_info(memcg);
Yang Shi2bfd3632021-05-04 18:36:11 -0700294 ret = -ENOMEM;
295 break;
296 }
Yang Shi3c6f17e2021-05-04 18:36:33 -0700297 info->nr_deferred = (atomic_long_t *)(info + 1);
298 info->map = (void *)info->nr_deferred + defer_size;
Yang Shie4262c42021-05-04 18:36:23 -0700299 rcu_assign_pointer(memcg->nodeinfo[nid]->shrinker_info, info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700300 }
Yang Shid27cf2a2021-05-04 18:36:14 -0700301 up_write(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700302
303 return ret;
304}
305
Yang Shi3c6f17e2021-05-04 18:36:33 -0700306static inline bool need_expand(int nr_max)
307{
308 return round_up(nr_max, BITS_PER_LONG) >
309 round_up(shrinker_nr_max, BITS_PER_LONG);
310}
311
Yang Shie4262c42021-05-04 18:36:23 -0700312static int expand_shrinker_info(int new_id)
Yang Shi2bfd3632021-05-04 18:36:11 -0700313{
Yang Shi3c6f17e2021-05-04 18:36:33 -0700314 int ret = 0;
Yang Shia2fb1262021-05-04 18:36:17 -0700315 int new_nr_max = new_id + 1;
Yang Shi3c6f17e2021-05-04 18:36:33 -0700316 int map_size, defer_size = 0;
317 int old_map_size, old_defer_size = 0;
Yang Shi2bfd3632021-05-04 18:36:11 -0700318 struct mem_cgroup *memcg;
319
Yang Shi3c6f17e2021-05-04 18:36:33 -0700320 if (!need_expand(new_nr_max))
Yang Shia2fb1262021-05-04 18:36:17 -0700321 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700322
Yang Shi2bfd3632021-05-04 18:36:11 -0700323 if (!root_mem_cgroup)
Yang Shid27cf2a2021-05-04 18:36:14 -0700324 goto out;
325
326 lockdep_assert_held(&shrinker_rwsem);
Yang Shi2bfd3632021-05-04 18:36:11 -0700327
Yang Shi3c6f17e2021-05-04 18:36:33 -0700328 map_size = shrinker_map_size(new_nr_max);
329 defer_size = shrinker_defer_size(new_nr_max);
330 old_map_size = shrinker_map_size(shrinker_nr_max);
331 old_defer_size = shrinker_defer_size(shrinker_nr_max);
332
Yang Shi2bfd3632021-05-04 18:36:11 -0700333 memcg = mem_cgroup_iter(NULL, NULL, NULL);
334 do {
Yang Shi3c6f17e2021-05-04 18:36:33 -0700335 ret = expand_one_shrinker_info(memcg, map_size, defer_size,
336 old_map_size, old_defer_size);
Yang Shi2bfd3632021-05-04 18:36:11 -0700337 if (ret) {
338 mem_cgroup_iter_break(NULL, memcg);
Yang Shid27cf2a2021-05-04 18:36:14 -0700339 goto out;
Yang Shi2bfd3632021-05-04 18:36:11 -0700340 }
341 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Yang Shid27cf2a2021-05-04 18:36:14 -0700342out:
Yang Shi2bfd3632021-05-04 18:36:11 -0700343 if (!ret)
Yang Shia2fb1262021-05-04 18:36:17 -0700344 shrinker_nr_max = new_nr_max;
Yang Shid27cf2a2021-05-04 18:36:14 -0700345
Yang Shi2bfd3632021-05-04 18:36:11 -0700346 return ret;
347}
348
349void set_shrinker_bit(struct mem_cgroup *memcg, int nid, int shrinker_id)
350{
351 if (shrinker_id >= 0 && memcg && !mem_cgroup_is_root(memcg)) {
Yang Shie4262c42021-05-04 18:36:23 -0700352 struct shrinker_info *info;
Yang Shi2bfd3632021-05-04 18:36:11 -0700353
354 rcu_read_lock();
Yang Shie4262c42021-05-04 18:36:23 -0700355 info = rcu_dereference(memcg->nodeinfo[nid]->shrinker_info);
Yang Shi2bfd3632021-05-04 18:36:11 -0700356 /* Pairs with smp mb in shrink_slab() */
357 smp_mb__before_atomic();
Yang Shie4262c42021-05-04 18:36:23 -0700358 set_bit(shrinker_id, info->map);
Yang Shi2bfd3632021-05-04 18:36:11 -0700359 rcu_read_unlock();
360 }
361}
362
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700363static DEFINE_IDR(shrinker_idr);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700364
365static int prealloc_memcg_shrinker(struct shrinker *shrinker)
366{
367 int id, ret = -ENOMEM;
368
Yang Shi476b30a2021-05-04 18:36:39 -0700369 if (mem_cgroup_disabled())
370 return -ENOSYS;
371
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700372 down_write(&shrinker_rwsem);
373 /* This may call shrinker, so it must use down_read_trylock() */
Yang Shi41ca6682021-05-04 18:36:29 -0700374 id = idr_alloc(&shrinker_idr, shrinker, 0, 0, GFP_KERNEL);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700375 if (id < 0)
376 goto unlock;
377
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700378 if (id >= shrinker_nr_max) {
Yang Shie4262c42021-05-04 18:36:23 -0700379 if (expand_shrinker_info(id)) {
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700380 idr_remove(&shrinker_idr, id);
381 goto unlock;
382 }
Kirill Tkhai0a4465d2018-08-17 15:47:37 -0700383 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700384 shrinker->id = id;
385 ret = 0;
386unlock:
387 up_write(&shrinker_rwsem);
388 return ret;
389}
390
391static void unregister_memcg_shrinker(struct shrinker *shrinker)
392{
393 int id = shrinker->id;
394
395 BUG_ON(id < 0);
396
Yang Shi41ca6682021-05-04 18:36:29 -0700397 lockdep_assert_held(&shrinker_rwsem);
398
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700399 idr_remove(&shrinker_idr, id);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700400}
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700401
Yang Shi86750832021-05-04 18:36:36 -0700402static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
403 struct mem_cgroup *memcg)
404{
405 struct shrinker_info *info;
406
407 info = shrinker_info_protected(memcg, nid);
408 return atomic_long_xchg(&info->nr_deferred[shrinker->id], 0);
409}
410
411static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
412 struct mem_cgroup *memcg)
413{
414 struct shrinker_info *info;
415
416 info = shrinker_info_protected(memcg, nid);
417 return atomic_long_add_return(nr, &info->nr_deferred[shrinker->id]);
418}
419
Yang Shia1780152021-05-04 18:36:42 -0700420void reparent_shrinker_deferred(struct mem_cgroup *memcg)
421{
422 int i, nid;
423 long nr;
424 struct mem_cgroup *parent;
425 struct shrinker_info *child_info, *parent_info;
426
427 parent = parent_mem_cgroup(memcg);
428 if (!parent)
429 parent = root_mem_cgroup;
430
431 /* Prevent from concurrent shrinker_info expand */
432 down_read(&shrinker_rwsem);
433 for_each_node(nid) {
434 child_info = shrinker_info_protected(memcg, nid);
435 parent_info = shrinker_info_protected(parent, nid);
436 for (i = 0; i < shrinker_nr_max; i++) {
437 nr = atomic_long_read(&child_info->nr_deferred[i]);
438 atomic_long_add(nr, &parent_info->nr_deferred[i]);
439 }
440 }
441 up_read(&shrinker_rwsem);
442}
443
Johannes Weinerb5ead352019-11-30 17:55:40 -0800444static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800445{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800446 return sc->target_mem_cgroup;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800447}
Tejun Heo97c93412015-05-22 18:23:36 -0400448
449/**
Johannes Weinerb5ead352019-11-30 17:55:40 -0800450 * writeback_throttling_sane - is the usual dirty throttling mechanism available?
Tejun Heo97c93412015-05-22 18:23:36 -0400451 * @sc: scan_control in question
452 *
453 * The normal page dirty throttling mechanism in balance_dirty_pages() is
454 * completely broken with the legacy memcg and direct stalling in
455 * shrink_page_list() is used for throttling instead, which lacks all the
456 * niceties such as fairness, adaptive pausing, bandwidth proportional
457 * allocation and configurability.
458 *
459 * This function tests whether the vmscan currently in progress can assume
460 * that the normal dirty throttling mechanism is operational.
461 */
Johannes Weinerb5ead352019-11-30 17:55:40 -0800462static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400463{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800464 if (!cgroup_reclaim(sc))
Tejun Heo97c93412015-05-22 18:23:36 -0400465 return true;
466#ifdef CONFIG_CGROUP_WRITEBACK
Linus Torvalds69234ac2015-11-05 14:51:32 -0800467 if (cgroup_subsys_on_dfl(memory_cgrp_subsys))
Tejun Heo97c93412015-05-22 18:23:36 -0400468 return true;
469#endif
470 return false;
471}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800472#else
Yang Shi0a432dc2019-09-23 15:38:12 -0700473static int prealloc_memcg_shrinker(struct shrinker *shrinker)
474{
Yang Shi476b30a2021-05-04 18:36:39 -0700475 return -ENOSYS;
Yang Shi0a432dc2019-09-23 15:38:12 -0700476}
477
478static void unregister_memcg_shrinker(struct shrinker *shrinker)
479{
480}
481
Yang Shi86750832021-05-04 18:36:36 -0700482static long xchg_nr_deferred_memcg(int nid, struct shrinker *shrinker,
483 struct mem_cgroup *memcg)
484{
485 return 0;
486}
487
488static long add_nr_deferred_memcg(long nr, int nid, struct shrinker *shrinker,
489 struct mem_cgroup *memcg)
490{
491 return 0;
492}
493
Johannes Weinerb5ead352019-11-30 17:55:40 -0800494static bool cgroup_reclaim(struct scan_control *sc)
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800495{
Johannes Weinerb5ead352019-11-30 17:55:40 -0800496 return false;
Johannes Weiner89b5fae2012-01-12 17:17:50 -0800497}
Tejun Heo97c93412015-05-22 18:23:36 -0400498
Johannes Weinerb5ead352019-11-30 17:55:40 -0800499static bool writeback_throttling_sane(struct scan_control *sc)
Tejun Heo97c93412015-05-22 18:23:36 -0400500{
501 return true;
502}
KAMEZAWA Hiroyuki91a45472008-02-07 00:14:29 -0800503#endif
504
Yang Shi86750832021-05-04 18:36:36 -0700505static long xchg_nr_deferred(struct shrinker *shrinker,
506 struct shrink_control *sc)
507{
508 int nid = sc->nid;
509
510 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
511 nid = 0;
512
513 if (sc->memcg &&
514 (shrinker->flags & SHRINKER_MEMCG_AWARE))
515 return xchg_nr_deferred_memcg(nid, shrinker,
516 sc->memcg);
517
518 return atomic_long_xchg(&shrinker->nr_deferred[nid], 0);
519}
520
521
522static long add_nr_deferred(long nr, struct shrinker *shrinker,
523 struct shrink_control *sc)
524{
525 int nid = sc->nid;
526
527 if (!(shrinker->flags & SHRINKER_NUMA_AWARE))
528 nid = 0;
529
530 if (sc->memcg &&
531 (shrinker->flags & SHRINKER_MEMCG_AWARE))
532 return add_nr_deferred_memcg(nr, nid, shrinker,
533 sc->memcg);
534
535 return atomic_long_add_return(nr, &shrinker->nr_deferred[nid]);
536}
537
Dave Hansen26aa2d12021-09-02 14:59:16 -0700538static bool can_demote(int nid, struct scan_control *sc)
539{
Huang Ying20b51af12021-09-02 14:59:33 -0700540 if (!numa_demotion_enabled)
541 return false;
Dave Hansen3a235692021-09-02 14:59:30 -0700542 if (sc) {
543 if (sc->no_demotion)
544 return false;
545 /* It is pointless to do demotion in memcg reclaim */
546 if (cgroup_reclaim(sc))
547 return false;
548 }
Dave Hansen26aa2d12021-09-02 14:59:16 -0700549 if (next_demotion_node(nid) == NUMA_NO_NODE)
550 return false;
551
Huang Ying20b51af12021-09-02 14:59:33 -0700552 return true;
Dave Hansen26aa2d12021-09-02 14:59:16 -0700553}
554
Keith Buscha2a36482021-09-02 14:59:26 -0700555static inline bool can_reclaim_anon_pages(struct mem_cgroup *memcg,
556 int nid,
557 struct scan_control *sc)
558{
559 if (memcg == NULL) {
560 /*
561 * For non-memcg reclaim, is there
562 * space in any swap device?
563 */
564 if (get_nr_swap_pages() > 0)
565 return true;
566 } else {
567 /* Is the memcg below its swap limit? */
568 if (mem_cgroup_get_nr_swap_pages(memcg) > 0)
569 return true;
570 }
571
572 /*
573 * The page can not be swapped.
574 *
575 * Can it be reclaimed from this node via demotion?
576 */
577 return can_demote(nid, sc);
578}
579
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700580/*
581 * This misses isolated pages which are not accounted for to save counters.
582 * As the data only determines if reclaim or compaction continues, it is
583 * not expected that isolated pages will be a dominating factor.
584 */
585unsigned long zone_reclaimable_pages(struct zone *zone)
586{
587 unsigned long nr;
588
589 nr = zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_FILE) +
590 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -0700591 if (can_reclaim_anon_pages(NULL, zone_to_nid(zone), NULL))
Mel Gorman5a1c84b2016-07-28 15:47:31 -0700592 nr += zone_page_state_snapshot(zone, NR_ZONE_INACTIVE_ANON) +
593 zone_page_state_snapshot(zone, NR_ZONE_ACTIVE_ANON);
594
595 return nr;
596}
597
Michal Hockofd538802017-02-22 15:45:58 -0800598/**
599 * lruvec_lru_size - Returns the number of pages on the given LRU list.
600 * @lruvec: lru vector
601 * @lru: lru to use
602 * @zone_idx: zones to consider (use MAX_NR_ZONES for the whole LRU list)
603 */
Yu Zhao20913392021-02-24 12:08:44 -0800604static unsigned long lruvec_lru_size(struct lruvec *lruvec, enum lru_list lru,
605 int zone_idx)
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800606{
Johannes Weinerde3b0152019-11-30 17:55:31 -0800607 unsigned long size = 0;
Michal Hockofd538802017-02-22 15:45:58 -0800608 int zid;
609
Johannes Weinerde3b0152019-11-30 17:55:31 -0800610 for (zid = 0; zid <= zone_idx && zid < MAX_NR_ZONES; zid++) {
Michal Hockofd538802017-02-22 15:45:58 -0800611 struct zone *zone = &lruvec_pgdat(lruvec)->node_zones[zid];
KOSAKI Motohiroc9f299d2009-01-07 18:08:16 -0800612
Michal Hockofd538802017-02-22 15:45:58 -0800613 if (!managed_zone(zone))
614 continue;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800615
Michal Hockofd538802017-02-22 15:45:58 -0800616 if (!mem_cgroup_disabled())
Johannes Weinerde3b0152019-11-30 17:55:31 -0800617 size += mem_cgroup_get_zone_lru_size(lruvec, lru, zid);
Michal Hockofd538802017-02-22 15:45:58 -0800618 else
Johannes Weinerde3b0152019-11-30 17:55:31 -0800619 size += zone_page_state(zone, NR_ZONE_LRU_BASE + lru);
Michal Hockofd538802017-02-22 15:45:58 -0800620 }
Johannes Weinerde3b0152019-11-30 17:55:31 -0800621 return size;
Michal Hockob4536f0c82017-01-10 16:58:04 -0800622}
623
Linus Torvalds1da177e2005-04-16 15:20:36 -0700624/*
Glauber Costa1d3d4432013-08-28 10:18:04 +1000625 * Add a shrinker callback to be called from the vm.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700626 */
Tetsuo Handa8e049442018-04-04 19:53:07 +0900627int prealloc_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700628{
Yang Shi476b30a2021-05-04 18:36:39 -0700629 unsigned int size;
630 int err;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000631
Yang Shi476b30a2021-05-04 18:36:39 -0700632 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
633 err = prealloc_memcg_shrinker(shrinker);
634 if (err != -ENOSYS)
635 return err;
636
637 shrinker->flags &= ~SHRINKER_MEMCG_AWARE;
638 }
639
640 size = sizeof(*shrinker->nr_deferred);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000641 if (shrinker->flags & SHRINKER_NUMA_AWARE)
642 size *= nr_node_ids;
643
644 shrinker->nr_deferred = kzalloc(size, GFP_KERNEL);
645 if (!shrinker->nr_deferred)
646 return -ENOMEM;
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700647
Tetsuo Handa8e049442018-04-04 19:53:07 +0900648 return 0;
649}
Glauber Costa1d3d4432013-08-28 10:18:04 +1000650
Tetsuo Handa8e049442018-04-04 19:53:07 +0900651void free_prealloced_shrinker(struct shrinker *shrinker)
652{
Yang Shi41ca6682021-05-04 18:36:29 -0700653 if (shrinker->flags & SHRINKER_MEMCG_AWARE) {
654 down_write(&shrinker_rwsem);
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700655 unregister_memcg_shrinker(shrinker);
Yang Shi41ca6682021-05-04 18:36:29 -0700656 up_write(&shrinker_rwsem);
Yang Shi476b30a2021-05-04 18:36:39 -0700657 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700658 }
Kirill Tkhaib4c2b232018-08-17 15:47:29 -0700659
Tetsuo Handa8e049442018-04-04 19:53:07 +0900660 kfree(shrinker->nr_deferred);
661 shrinker->nr_deferred = NULL;
662}
663
664void register_shrinker_prepared(struct shrinker *shrinker)
665{
Rusty Russell8e1f9362007-07-17 04:03:17 -0700666 down_write(&shrinker_rwsem);
667 list_add_tail(&shrinker->list, &shrinker_list);
Yang Shi41ca6682021-05-04 18:36:29 -0700668 shrinker->flags |= SHRINKER_REGISTERED;
Rusty Russell8e1f9362007-07-17 04:03:17 -0700669 up_write(&shrinker_rwsem);
Tetsuo Handa8e049442018-04-04 19:53:07 +0900670}
671
672int register_shrinker(struct shrinker *shrinker)
673{
674 int err = prealloc_shrinker(shrinker);
675
676 if (err)
677 return err;
678 register_shrinker_prepared(shrinker);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000679 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700680}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700681EXPORT_SYMBOL(register_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700682
683/*
684 * Remove one
685 */
Rusty Russell8e1f9362007-07-17 04:03:17 -0700686void unregister_shrinker(struct shrinker *shrinker)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700687{
Yang Shi41ca6682021-05-04 18:36:29 -0700688 if (!(shrinker->flags & SHRINKER_REGISTERED))
Tetsuo Handabb422a72017-12-18 20:31:41 +0900689 return;
Yang Shi41ca6682021-05-04 18:36:29 -0700690
Linus Torvalds1da177e2005-04-16 15:20:36 -0700691 down_write(&shrinker_rwsem);
692 list_del(&shrinker->list);
Yang Shi41ca6682021-05-04 18:36:29 -0700693 shrinker->flags &= ~SHRINKER_REGISTERED;
694 if (shrinker->flags & SHRINKER_MEMCG_AWARE)
695 unregister_memcg_shrinker(shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700696 up_write(&shrinker_rwsem);
Yang Shi41ca6682021-05-04 18:36:29 -0700697
Andrew Vaginae393322013-10-16 13:46:46 -0700698 kfree(shrinker->nr_deferred);
Tetsuo Handabb422a72017-12-18 20:31:41 +0900699 shrinker->nr_deferred = NULL;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700700}
Rusty Russell8e1f9362007-07-17 04:03:17 -0700701EXPORT_SYMBOL(unregister_shrinker);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700702
703#define SHRINK_BATCH 128
Glauber Costa1d3d4432013-08-28 10:18:04 +1000704
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800705static unsigned long do_shrink_slab(struct shrink_control *shrinkctl,
Josef Bacik9092c712018-01-31 16:16:26 -0800706 struct shrinker *shrinker, int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700707{
Glauber Costa1d3d4432013-08-28 10:18:04 +1000708 unsigned long freed = 0;
709 unsigned long long delta;
710 long total_scan;
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700711 long freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000712 long nr;
713 long new_nr;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000714 long batch_size = shrinker->batch ? shrinker->batch
715 : SHRINK_BATCH;
Shaohua Li5f33a082016-12-12 16:41:50 -0800716 long scanned = 0, next_deferred;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000717
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700718 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700719 if (freeable == 0 || freeable == SHRINK_EMPTY)
720 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000721
722 /*
723 * copy the current shrinker scan count into a local variable
724 * and zero it so that other concurrent shrinker invocations
725 * don't also do this scanning work.
726 */
Yang Shi86750832021-05-04 18:36:36 -0700727 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000728
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700729 if (shrinker->seeks) {
730 delta = freeable >> priority;
731 delta *= 4;
732 do_div(delta, shrinker->seeks);
733 } else {
734 /*
735 * These objects don't require any IO to create. Trim
736 * them aggressively under memory pressure to keep
737 * them from causing refetches in the IO caches.
738 */
739 delta = freeable / 2;
740 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700741
Yang Shi18bb4732021-05-04 18:36:45 -0700742 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000743 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700744 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000745
746 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800747 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000748
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800749 /*
750 * Normally, we should not scan less than batch_size objects in one
751 * pass to avoid too frequent shrinker calls, but if the slab has less
752 * than batch_size objects in total and we are really tight on memory,
753 * we will try to reclaim all available objects, otherwise we can end
754 * up failing allocations although there are plenty of reclaimable
755 * objects spread over several slabs with usage less than the
756 * batch_size.
757 *
758 * We detect the "tight on memory" situations by looking at the total
759 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700760 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800761 * scanning at high prio and therefore should try to reclaim as much as
762 * possible.
763 */
764 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700765 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000766 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800767 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000768
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800769 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700770 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000771 ret = shrinker->scan_objects(shrinker, shrinkctl);
772 if (ret == SHRINK_STOP)
773 break;
774 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000775
Chris Wilsond460acb2017-09-06 16:19:26 -0700776 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
777 total_scan -= shrinkctl->nr_scanned;
778 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000779
780 cond_resched();
781 }
782
Yang Shi18bb4732021-05-04 18:36:45 -0700783 /*
784 * The deferred work is increased by any new work (delta) that wasn't
785 * done, decreased by old deferred work that was done now.
786 *
787 * And it is capped to two times of the freeable items.
788 */
789 next_deferred = max_t(long, (nr + delta - scanned), 0);
790 next_deferred = min(next_deferred, (2 * freeable));
791
Glauber Costa1d3d4432013-08-28 10:18:04 +1000792 /*
793 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700794 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000795 */
Yang Shi86750832021-05-04 18:36:36 -0700796 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000797
Yang Shi8efb4b52021-05-04 18:36:08 -0700798 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000799 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700800}
801
Yang Shi0a432dc2019-09-23 15:38:12 -0700802#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700803static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
804 struct mem_cgroup *memcg, int priority)
805{
Yang Shie4262c42021-05-04 18:36:23 -0700806 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700807 unsigned long ret, freed = 0;
808 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700809
Yang Shi0a432dc2019-09-23 15:38:12 -0700810 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700811 return 0;
812
813 if (!down_read_trylock(&shrinker_rwsem))
814 return 0;
815
Yang Shi468ab842021-05-04 18:36:26 -0700816 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700817 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700818 goto unlock;
819
Yang Shie4262c42021-05-04 18:36:23 -0700820 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700821 struct shrink_control sc = {
822 .gfp_mask = gfp_mask,
823 .nid = nid,
824 .memcg = memcg,
825 };
826 struct shrinker *shrinker;
827
828 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700829 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700830 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700831 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700832 continue;
833 }
834
Yang Shi0a432dc2019-09-23 15:38:12 -0700835 /* Call non-slab shrinkers even though kmem is disabled */
836 if (!memcg_kmem_enabled() &&
837 !(shrinker->flags & SHRINKER_NONSLAB))
838 continue;
839
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700840 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700841 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700842 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700843 /*
844 * After the shrinker reported that it had no objects to
845 * free, but before we cleared the corresponding bit in
846 * the memcg shrinker map, a new object might have been
847 * added. To make sure, we have the bit set in this
848 * case, we invoke the shrinker one more time and reset
849 * the bit if it reports that it is not empty anymore.
850 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700851 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700852 *
853 * list_lru_add() shrink_slab_memcg()
854 * list_add_tail() clear_bit()
855 * <MB> <MB>
856 * set_bit() do_shrink_slab()
857 */
858 smp_mb__after_atomic();
859 ret = do_shrink_slab(&sc, shrinker, priority);
860 if (ret == SHRINK_EMPTY)
861 ret = 0;
862 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700863 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700864 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700865 freed += ret;
866
867 if (rwsem_is_contended(&shrinker_rwsem)) {
868 freed = freed ? : 1;
869 break;
870 }
871 }
872unlock:
873 up_read(&shrinker_rwsem);
874 return freed;
875}
Yang Shi0a432dc2019-09-23 15:38:12 -0700876#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700877static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
878 struct mem_cgroup *memcg, int priority)
879{
880 return 0;
881}
Yang Shi0a432dc2019-09-23 15:38:12 -0700882#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700883
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800884/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800885 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800886 * @gfp_mask: allocation context
887 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800888 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800889 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700890 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800891 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700892 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800893 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
894 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700895 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700896 * @memcg specifies the memory cgroup to target. Unaware shrinkers
897 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800898 *
Josef Bacik9092c712018-01-31 16:16:26 -0800899 * @priority is sc->priority, we take the number of objects and >> by priority
900 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700901 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800902 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700903 */
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800904static unsigned long shrink_slab(gfp_t gfp_mask, int nid,
905 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800906 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700907{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700908 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700909 struct shrinker *shrinker;
910
Yang Shifa1e5122019-08-02 21:48:44 -0700911 /*
912 * The root memcg might be allocated even though memcg is disabled
913 * via "cgroup_disable=memory" boot parameter. This could make
914 * mem_cgroup_is_root() return false, then just run memcg slab
915 * shrink, but skip global shrink. This may result in premature
916 * oom.
917 */
918 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700919 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800920
Tetsuo Handae830c632018-04-05 16:23:35 -0700921 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700922 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700923
924 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800925 struct shrink_control sc = {
926 .gfp_mask = gfp_mask,
927 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800928 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800929 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800930
Kirill Tkhai9b996462018-08-17 15:48:21 -0700931 ret = do_shrink_slab(&sc, shrinker, priority);
932 if (ret == SHRINK_EMPTY)
933 ret = 0;
934 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800935 /*
936 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700937 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800938 * by parallel ongoing shrinking.
939 */
940 if (rwsem_is_contended(&shrinker_rwsem)) {
941 freed = freed ? : 1;
942 break;
943 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700944 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800945
Linus Torvalds1da177e2005-04-16 15:20:36 -0700946 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700947out:
948 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000949 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700950}
951
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800952void drop_slab_node(int nid)
953{
954 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700955 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800956
957 do {
958 struct mem_cgroup *memcg = NULL;
959
Chunxin Zang069c4112020-10-13 16:56:46 -0700960 if (fatal_signal_pending(current))
961 return;
962
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800963 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700964 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800965 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800966 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800967 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700968 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800969}
970
971void drop_slab(void)
972{
973 int nid;
974
975 for_each_online_node(nid)
976 drop_slab_node(nid);
977}
978
Linus Torvalds1da177e2005-04-16 15:20:36 -0700979static inline int is_page_cache_freeable(struct page *page)
980{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700981 /*
982 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400983 * that isolated the page, the page cache and optional buffer
984 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700985 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -0700986 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400987 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700988}
989
Yang Shicb165562019-11-30 17:55:28 -0800990static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700991{
Christoph Lameter930d9152006-01-08 01:00:47 -0800992 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700993 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400994 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -0700995 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -0400996 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700997 return 1;
998 return 0;
999}
1000
1001/*
1002 * We detected a synchronous write error writing a page out. Probably
1003 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1004 * fsync(), msync() or close().
1005 *
1006 * The tricky part is that after writepage we cannot touch the mapping: nothing
1007 * prevents it from being freed up. But we have a ref on the page and once
1008 * that page is locked, the mapping is pinned.
1009 *
1010 * We're allowed to run sleeping lock_page() here because we know the caller has
1011 * __GFP_FS.
1012 */
1013static void handle_write_error(struct address_space *mapping,
1014 struct page *page, int error)
1015{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001016 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001017 if (page_mapping(page) == mapping)
1018 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001019 unlock_page(page);
1020}
1021
Christoph Lameter04e62a22006-06-23 02:03:38 -07001022/* possible outcome of pageout() */
1023typedef enum {
1024 /* failed to write page out, page is locked */
1025 PAGE_KEEP,
1026 /* move page to the active list, page is locked */
1027 PAGE_ACTIVATE,
1028 /* page has been sent to the disk successfully, page is unlocked */
1029 PAGE_SUCCESS,
1030 /* page is clean and locked */
1031 PAGE_CLEAN,
1032} pageout_t;
1033
Linus Torvalds1da177e2005-04-16 15:20:36 -07001034/*
Andrew Morton1742f192006-03-22 00:08:21 -08001035 * pageout is called by shrink_page_list() for each dirty page.
1036 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001037 */
Yang Shicb165562019-11-30 17:55:28 -08001038static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001039{
1040 /*
1041 * If the page is dirty, only perform writeback if that write
1042 * will be non-blocking. To prevent this allocation from being
1043 * stalled by pagecache activity. But note that there may be
1044 * stalls if we need to run get_block(). We could test
1045 * PagePrivate for that.
1046 *
Al Viro81742022014-04-03 03:17:43 -04001047 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001048 * this page's queue, we can perform writeback even if that
1049 * will block.
1050 *
1051 * If the page is swapcache, write it back even if that would
1052 * block, for some throttling. This happens by accident, because
1053 * swap_backing_dev_info is bust: it doesn't reflect the
1054 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001055 */
1056 if (!is_page_cache_freeable(page))
1057 return PAGE_KEEP;
1058 if (!mapping) {
1059 /*
1060 * Some data journaling orphaned pages can have
1061 * page->mapping == NULL while being dirty with clean buffers.
1062 */
David Howells266cf652009-04-03 16:42:36 +01001063 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001064 if (try_to_free_buffers(page)) {
1065 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001066 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001067 return PAGE_CLEAN;
1068 }
1069 }
1070 return PAGE_KEEP;
1071 }
1072 if (mapping->a_ops->writepage == NULL)
1073 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001074 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001075 return PAGE_KEEP;
1076
1077 if (clear_page_dirty_for_io(page)) {
1078 int res;
1079 struct writeback_control wbc = {
1080 .sync_mode = WB_SYNC_NONE,
1081 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001082 .range_start = 0,
1083 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001084 .for_reclaim = 1,
1085 };
1086
1087 SetPageReclaim(page);
1088 res = mapping->a_ops->writepage(page, &wbc);
1089 if (res < 0)
1090 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001091 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001092 ClearPageReclaim(page);
1093 return PAGE_ACTIVATE;
1094 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001095
Linus Torvalds1da177e2005-04-16 15:20:36 -07001096 if (!PageWriteback(page)) {
1097 /* synchronous write or broken a_ops? */
1098 ClearPageReclaim(page);
1099 }
yalin wang3aa23852016-01-14 15:18:30 -08001100 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001101 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001102 return PAGE_SUCCESS;
1103 }
1104
1105 return PAGE_CLEAN;
1106}
1107
Andrew Mortona649fd92006-10-17 00:09:36 -07001108/*
Nick Piggine2867812008-07-25 19:45:30 -07001109 * Same as remove_mapping, but if the page is removed from the mapping, it
1110 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001111 */
Johannes Weinera5289102014-04-03 14:47:51 -07001112static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001113 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001114{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001115 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001116 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001117
Nick Piggin28e4d962006-09-25 23:31:23 -07001118 BUG_ON(!PageLocked(page));
1119 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001120
Johannes Weiner30472502021-09-02 14:53:18 -07001121 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001122 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001123 * The non racy check for a busy page.
1124 *
1125 * Must be careful with the order of the tests. When someone has
1126 * a ref to the page, it may be possible that they dirty it then
1127 * drop the reference. So if PageDirty is tested before page_count
1128 * here, then the following race may occur:
1129 *
1130 * get_user_pages(&page);
1131 * [user mapping goes away]
1132 * write_to(page);
1133 * !PageDirty(page) [good]
1134 * SetPageDirty(page);
1135 * put_page(page);
1136 * !page_count(page) [good, discard it]
1137 *
1138 * [oops, our write_to data is lost]
1139 *
1140 * Reversing the order of the tests ensures such a situation cannot
1141 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001142 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001143 *
1144 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001145 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001146 */
William Kucharski906d2782019-10-18 20:20:33 -07001147 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001148 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001149 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001150 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001151 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001152 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001153 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001154 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001155
1156 if (PageSwapCache(page)) {
1157 swp_entry_t swap = { .val = page_private(page) };
Yu Zhaoa1537a62022-01-27 20:32:37 -07001158
1159 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001160 if (reclaimed && !mapping_exiting(mapping))
1161 shadow = workingset_eviction(page, target_memcg);
Yu Zhaoa1537a62022-01-27 20:32:37 -07001162 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001163 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001164 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001165 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001166 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001167 void (*freepage)(struct page *);
1168
1169 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001170 /*
1171 * Remember a shadow entry for reclaimed file cache in
1172 * order to detect refaults, thus thrashing, later on.
1173 *
1174 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001175 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001176 * inode reclaim needs to empty out the radix tree or
1177 * the nodes are lost. Don't plant shadows behind its
1178 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001179 *
1180 * We also don't store shadows for DAX mappings because the
1181 * only page cache pages found in these are zero pages
1182 * covering holes, and because we don't want to mix DAX
1183 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001184 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001185 */
Huang Ying9de4f222020-04-06 20:04:41 -07001186 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001187 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001188 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001189 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001190 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001191
1192 if (freepage != NULL)
1193 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001194 }
1195
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001196 return 1;
1197
1198cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001199 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001200 return 0;
1201}
1202
Linus Torvalds1da177e2005-04-16 15:20:36 -07001203/*
Nick Piggine2867812008-07-25 19:45:30 -07001204 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1205 * someone else has a ref on the page, abort and return 0. If it was
1206 * successfully detached, return 1. Assumes the caller has a single ref on
1207 * this page.
1208 */
1209int remove_mapping(struct address_space *mapping, struct page *page)
1210{
Johannes Weinerb9107182019-11-30 17:55:59 -08001211 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001212 /*
1213 * Unfreezing the refcount with 1 rather than 2 effectively
1214 * drops the pagecache ref for us without requiring another
1215 * atomic operation.
1216 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001217 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001218 return 1;
1219 }
1220 return 0;
1221}
1222
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001223/**
1224 * putback_lru_page - put previously isolated page onto appropriate LRU list
1225 * @page: page to be put back to appropriate lru list
1226 *
1227 * Add previously isolated @page to appropriate LRU list.
1228 * Page may still be unevictable for other reasons.
1229 *
1230 * lru_lock must not be held, interrupts must be enabled.
1231 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001232void putback_lru_page(struct page *page)
1233{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001234 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001235 put_page(page); /* drop ref from isolate */
1236}
1237
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001238enum page_references {
1239 PAGEREF_RECLAIM,
1240 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001241 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001242 PAGEREF_ACTIVATE,
1243};
1244
1245static enum page_references page_check_references(struct page *page,
1246 struct scan_control *sc)
1247{
Johannes Weiner645747462010-03-05 13:42:22 -08001248 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001249 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001250
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001251 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1252 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001253 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001254
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001255 /*
1256 * Mlock lost the isolation race with us. Let try_to_unmap()
1257 * move the page to the unevictable list.
1258 */
1259 if (vm_flags & VM_LOCKED)
1260 return PAGEREF_RECLAIM;
1261
Johannes Weiner645747462010-03-05 13:42:22 -08001262 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001263 /*
1264 * All mapped pages start out with page table
1265 * references from the instantiating fault, so we need
1266 * to look twice if a mapped file page is used more
1267 * than once.
1268 *
1269 * Mark it and spare it for another trip around the
1270 * inactive list. Another page table reference will
1271 * lead to its activation.
1272 *
1273 * Note: the mark is set for activated pages as well
1274 * so that recently deactivated but used pages are
1275 * quickly recovered.
1276 */
1277 SetPageReferenced(page);
1278
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001279 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001280 return PAGEREF_ACTIVATE;
1281
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001282 /*
1283 * Activate file-backed executable pages after first usage.
1284 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001285 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001286 return PAGEREF_ACTIVATE;
1287
Johannes Weiner645747462010-03-05 13:42:22 -08001288 return PAGEREF_KEEP;
1289 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001290
1291 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001292 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001293 return PAGEREF_RECLAIM_CLEAN;
1294
1295 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001296}
1297
Mel Gormane2be15f2013-07-03 15:01:57 -07001298/* Check if a page is dirty or under writeback */
1299static void page_check_dirty_writeback(struct page *page,
1300 bool *dirty, bool *writeback)
1301{
Mel Gormanb4597222013-07-03 15:02:05 -07001302 struct address_space *mapping;
1303
Mel Gormane2be15f2013-07-03 15:01:57 -07001304 /*
1305 * Anonymous pages are not handled by flushers and must be written
1306 * from reclaim context. Do not stall reclaim based on them
1307 */
Huang Ying9de4f222020-04-06 20:04:41 -07001308 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001309 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001310 *dirty = false;
1311 *writeback = false;
1312 return;
1313 }
1314
1315 /* By default assume that the page flags are accurate */
1316 *dirty = PageDirty(page);
1317 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001318
1319 /* Verify dirty/writeback state if the filesystem supports it */
1320 if (!page_has_private(page))
1321 return;
1322
1323 mapping = page_mapping(page);
1324 if (mapping && mapping->a_ops->is_dirty_writeback)
1325 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001326}
1327
Dave Hansen26aa2d12021-09-02 14:59:16 -07001328static struct page *alloc_demote_page(struct page *page, unsigned long node)
1329{
1330 struct migration_target_control mtc = {
1331 /*
1332 * Allocate from 'node', or fail quickly and quietly.
1333 * When this happens, 'page' will likely just be discarded
1334 * instead of migrated.
1335 */
1336 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1337 __GFP_THISNODE | __GFP_NOWARN |
1338 __GFP_NOMEMALLOC | GFP_NOWAIT,
1339 .nid = node
1340 };
1341
1342 return alloc_migration_target(page, (unsigned long)&mtc);
1343}
1344
1345/*
1346 * Take pages on @demote_list and attempt to demote them to
1347 * another node. Pages which are not demoted are left on
1348 * @demote_pages.
1349 */
1350static unsigned int demote_page_list(struct list_head *demote_pages,
1351 struct pglist_data *pgdat)
1352{
1353 int target_nid = next_demotion_node(pgdat->node_id);
1354 unsigned int nr_succeeded;
1355 int err;
1356
1357 if (list_empty(demote_pages))
1358 return 0;
1359
1360 if (target_nid == NUMA_NO_NODE)
1361 return 0;
1362
1363 /* Demotion ignores all cpuset and mempolicy settings */
1364 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1365 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1366 &nr_succeeded);
1367
Yang Shi668e4142021-09-02 14:59:19 -07001368 if (current_is_kswapd())
1369 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1370 else
1371 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1372
Dave Hansen26aa2d12021-09-02 14:59:16 -07001373 return nr_succeeded;
1374}
1375
Nick Piggine2867812008-07-25 19:45:30 -07001376/*
Andrew Morton1742f192006-03-22 00:08:21 -08001377 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001378 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001379static unsigned int shrink_page_list(struct list_head *page_list,
1380 struct pglist_data *pgdat,
1381 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001382 struct reclaim_stat *stat,
1383 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001384{
1385 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001386 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001387 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001388 unsigned int nr_reclaimed = 0;
1389 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001390 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001391
Kirill Tkhai060f0052019-03-05 15:48:15 -08001392 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001393 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001394 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001395
Dave Hansen26aa2d12021-09-02 14:59:16 -07001396retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001397 while (!list_empty(page_list)) {
1398 struct address_space *mapping;
1399 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001400 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001401 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001402 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001403
1404 cond_resched();
1405
1406 page = lru_to_page(page_list);
1407 list_del(&page->lru);
1408
Nick Piggin529ae9a2008-08-02 12:01:03 +02001409 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001410 goto keep;
1411
Sasha Levin309381fea2014-01-23 15:52:54 -08001412 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001413
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001414 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001415
1416 /* Account the number of base pages even though THP */
1417 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001418
Hugh Dickins39b5f292012-10-08 16:33:18 -07001419 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001420 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001421
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001422 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001423 goto keep_locked;
1424
Yu Zhaoafd94c92022-01-27 20:43:22 -07001425 /* page_update_gen() tried to promote this page? */
1426 if (lru_gen_enabled() && !ignore_references &&
1427 page_mapped(page) && PageReferenced(page))
1428 goto keep_locked;
1429
Andy Whitcroftc661b072007-08-22 14:01:26 -07001430 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1431 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1432
Mel Gorman283aba92013-07-03 15:01:51 -07001433 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001434 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001435 * reclaim_congested which affects wait_iff_congested. kswapd
1436 * will stall and start writing pages if the tail of the LRU
1437 * is all dirty unqueued pages.
1438 */
1439 page_check_dirty_writeback(page, &dirty, &writeback);
1440 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001441 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001442
1443 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001444 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001445
Mel Gormand04e8ac2013-07-03 15:02:03 -07001446 /*
1447 * Treat this page as congested if the underlying BDI is or if
1448 * pages are cycling through the LRU so quickly that the
1449 * pages marked for immediate reclaim are making it to the
1450 * end of the LRU a second time.
1451 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001452 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001453 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001454 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001455 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001456 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001457
1458 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001459 * If a page at the tail of the LRU is under writeback, there
1460 * are three cases to consider.
1461 *
1462 * 1) If reclaim is encountering an excessive number of pages
1463 * under writeback and this page is both under writeback and
1464 * PageReclaim then it indicates that pages are being queued
1465 * for IO but are being recycled through the LRU before the
1466 * IO can complete. Waiting on the page itself risks an
1467 * indefinite stall if it is impossible to writeback the
1468 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001469 * note that the LRU is being scanned too quickly and the
1470 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001471 *
Tejun Heo97c93412015-05-22 18:23:36 -04001472 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001473 * not marked for immediate reclaim, or the caller does not
1474 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1475 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001476 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001477 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001478 * Require may_enter_fs because we would wait on fs, which
1479 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001480 * enter reclaim, and deadlock if it waits on a page for
1481 * which it is needed to do the write (loop masks off
1482 * __GFP_IO|__GFP_FS for this reason); but more thought
1483 * would probably show more reasons.
1484 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001485 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001486 * PageReclaim. memcg does not have any dirty pages
1487 * throttling so we could easily OOM just because too many
1488 * pages are in writeback and there is nothing else to
1489 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001490 *
1491 * In cases 1) and 2) we activate the pages to get them out of
1492 * the way while we continue scanning for clean pages on the
1493 * inactive list and refilling from the active list. The
1494 * observation here is that waiting for disk writes is more
1495 * expensive than potentially causing reloads down the line.
1496 * Since they're marked for immediate reclaim, they won't put
1497 * memory pressure on the cache working set any longer than it
1498 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001499 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001500 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001501 /* Case 1 above */
1502 if (current_is_kswapd() &&
1503 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001504 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001505 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001506 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001507
1508 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001509 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001510 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001511 /*
1512 * This is slightly racy - end_page_writeback()
1513 * might have just cleared PageReclaim, then
1514 * setting PageReclaim here end up interpreted
1515 * as PageReadahead - but that does not matter
1516 * enough to care. What we do want is for this
1517 * page to have PageReclaim set next time memcg
1518 * reclaim reaches the tests above, so it will
1519 * then wait_on_page_writeback() to avoid OOM;
1520 * and it's also appropriate in global reclaim.
1521 */
1522 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001523 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001524 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001525
1526 /* Case 3 above */
1527 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001528 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001529 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001530 /* then go back and try same page again */
1531 list_add_tail(&page->lru, page_list);
1532 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001533 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001534 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001535
Minchan Kim8940b342019-09-25 16:49:11 -07001536 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001537 references = page_check_references(page, sc);
1538
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001539 switch (references) {
1540 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001541 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001542 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001543 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001544 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001545 case PAGEREF_RECLAIM:
1546 case PAGEREF_RECLAIM_CLEAN:
1547 ; /* try to reclaim the page below */
1548 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001549
Linus Torvalds1da177e2005-04-16 15:20:36 -07001550 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001551 * Before reclaiming the page, try to relocate
1552 * its contents to another node.
1553 */
1554 if (do_demote_pass &&
1555 (thp_migration_supported() || !PageTransHuge(page))) {
1556 list_add(&page->lru, &demote_pages);
1557 unlock_page(page);
1558 continue;
1559 }
1560
1561 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001562 * Anonymous process memory has backing store?
1563 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001564 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001565 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001566 if (PageAnon(page) && PageSwapBacked(page)) {
1567 if (!PageSwapCache(page)) {
1568 if (!(sc->gfp_mask & __GFP_IO))
1569 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001570 if (page_maybe_dma_pinned(page))
1571 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001572 if (PageTransHuge(page)) {
1573 /* cannot split THP, skip it */
1574 if (!can_split_huge_page(page, NULL))
1575 goto activate_locked;
1576 /*
1577 * Split pages without a PMD map right
1578 * away. Chances are some or all of the
1579 * tail pages can be freed without IO.
1580 */
1581 if (!compound_mapcount(page) &&
1582 split_huge_page_to_list(page,
1583 page_list))
1584 goto activate_locked;
1585 }
1586 if (!add_to_swap(page)) {
1587 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001588 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001589 /* Fallback to swap normal pages */
1590 if (split_huge_page_to_list(page,
1591 page_list))
1592 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001593#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1594 count_vm_event(THP_SWPOUT_FALLBACK);
1595#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001596 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001597 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001598 }
Minchan Kim0f074652017-07-06 15:37:24 -07001599
Kirill Tkhai4b793062020-04-01 21:10:18 -07001600 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001601
1602 /* Adding to swap updated mapping */
1603 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001604 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001605 } else if (unlikely(PageTransHuge(page))) {
1606 /* Split file THP */
1607 if (split_huge_page_to_list(page, page_list))
1608 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001609 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001610
1611 /*
Yang Shi98879b32019-07-11 20:59:30 -07001612 * THP may get split above, need minus tail pages and update
1613 * nr_pages to avoid accounting tail pages twice.
1614 *
1615 * The tail pages that are added into swap cache successfully
1616 * reach here.
1617 */
1618 if ((nr_pages > 1) && !PageTransHuge(page)) {
1619 sc->nr_scanned -= (nr_pages - 1);
1620 nr_pages = 1;
1621 }
1622
1623 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001624 * The page is mapped into the page tables of one or more
1625 * processes. Try to unmap it here.
1626 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001627 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001628 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001629 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001630
1631 if (unlikely(PageTransHuge(page)))
1632 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001633
Yang Shi1fb08ac2021-06-30 18:52:01 -07001634 try_to_unmap(page, flags);
1635 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001636 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001637 if (!was_swapbacked && PageSwapBacked(page))
1638 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001639 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001640 }
1641 }
1642
1643 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001644 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001645 * Only kswapd can writeback filesystem pages
1646 * to avoid risk of stack overflow. But avoid
1647 * injecting inefficient single-page IO into
1648 * flusher writeback as much as possible: only
1649 * write pages when we've encountered many
1650 * dirty pages, and when we've already scanned
1651 * the rest of the LRU for clean pages and see
1652 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001653 */
Huang Ying9de4f222020-04-06 20:04:41 -07001654 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001655 (!current_is_kswapd() || !PageReclaim(page) ||
1656 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001657 /*
1658 * Immediately reclaim when written back.
1659 * Similar in principal to deactivate_page()
1660 * except we already have the page isolated
1661 * and know it's dirty
1662 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001663 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001664 SetPageReclaim(page);
1665
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001666 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001667 }
1668
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001669 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001670 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001671 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001672 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001673 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001674 goto keep_locked;
1675
Mel Gormand950c942015-09-04 15:47:35 -07001676 /*
1677 * Page is dirty. Flush the TLB if a writable entry
1678 * potentially exists to avoid CPU writes after IO
1679 * starts and then write it out here.
1680 */
1681 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001682 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001683 case PAGE_KEEP:
1684 goto keep_locked;
1685 case PAGE_ACTIVATE:
1686 goto activate_locked;
1687 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001688 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001689
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001690 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001691 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001692 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001693 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001694
Linus Torvalds1da177e2005-04-16 15:20:36 -07001695 /*
1696 * A synchronous write - probably a ramdisk. Go
1697 * ahead and try to reclaim the page.
1698 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001699 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001700 goto keep;
1701 if (PageDirty(page) || PageWriteback(page))
1702 goto keep_locked;
1703 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001704 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001705 case PAGE_CLEAN:
1706 ; /* try to free the page below */
1707 }
1708 }
1709
1710 /*
1711 * If the page has buffers, try to free the buffer mappings
1712 * associated with this page. If we succeed we try to free
1713 * the page as well.
1714 *
1715 * We do this even if the page is PageDirty().
1716 * try_to_release_page() does not perform I/O, but it is
1717 * possible for a page to have PageDirty set, but it is actually
1718 * clean (all its buffers are clean). This happens if the
1719 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001720 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001721 * try_to_release_page() will discover that cleanness and will
1722 * drop the buffers and mark the page clean - it can be freed.
1723 *
1724 * Rarely, pages can have buffers and no ->mapping. These are
1725 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001726 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001727 * and if that worked, and the page is no longer mapped into
1728 * process address space (page_count == 1) it can be freed.
1729 * Otherwise, leave the page on the LRU so it is swappable.
1730 */
David Howells266cf652009-04-03 16:42:36 +01001731 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001732 if (!try_to_release_page(page, sc->gfp_mask))
1733 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001734 if (!mapping && page_count(page) == 1) {
1735 unlock_page(page);
1736 if (put_page_testzero(page))
1737 goto free_it;
1738 else {
1739 /*
1740 * rare race with speculative reference.
1741 * the speculative reference will free
1742 * this page shortly, so we may
1743 * increment nr_reclaimed here (and
1744 * leave it off the LRU).
1745 */
1746 nr_reclaimed++;
1747 continue;
1748 }
1749 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001750 }
1751
Shaohua Li802a3a92017-05-03 14:52:32 -07001752 if (PageAnon(page) && !PageSwapBacked(page)) {
1753 /* follow __remove_mapping for reference */
1754 if (!page_ref_freeze(page, 1))
1755 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001756 /*
1757 * The page has only one reference left, which is
1758 * from the isolation. After the caller puts the
1759 * page back on lru and drops the reference, the
1760 * page will be freed anyway. It doesn't matter
1761 * which lru it goes. So we don't bother checking
1762 * PageDirty here.
1763 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001764 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001765 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001766 } else if (!mapping || !__remove_mapping(mapping, page, true,
1767 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001768 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001769
1770 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001771free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001772 /*
1773 * THP may get swapped out in a whole, need account
1774 * all base pages.
1775 */
1776 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001777
1778 /*
1779 * Is there need to periodically free_page_list? It would
1780 * appear not as the counts should be low
1781 */
Yang Shi7ae88532019-09-23 15:38:09 -07001782 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001783 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001784 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001785 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001786 continue;
1787
Yang Shi98879b32019-07-11 20:59:30 -07001788activate_locked_split:
1789 /*
1790 * The tail pages that are failed to add into swap cache
1791 * reach here. Fixup nr_scanned and nr_pages.
1792 */
1793 if (nr_pages > 1) {
1794 sc->nr_scanned -= (nr_pages - 1);
1795 nr_pages = 1;
1796 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001797activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001798 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001799 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1800 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001801 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001802 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001803 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001804 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001805 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001806 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001807 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001808 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001809keep_locked:
1810 unlock_page(page);
1811keep:
1812 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001813 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001814 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001815 /* 'page_list' is always empty here */
1816
1817 /* Migrate pages selected for demotion */
1818 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1819 /* Pages that could not be demoted are still in @demote_pages */
1820 if (!list_empty(&demote_pages)) {
1821 /* Pages which failed to demoted go back on @page_list for retry: */
1822 list_splice_init(&demote_pages, page_list);
1823 do_demote_pass = false;
1824 goto retry;
1825 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001826
Yang Shi98879b32019-07-11 20:59:30 -07001827 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1828
Johannes Weiner747db952014-08-08 14:19:24 -07001829 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001830 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001831 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001832
Linus Torvalds1da177e2005-04-16 15:20:36 -07001833 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001834 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001835
Andrew Morton05ff5132006-03-22 00:08:20 -08001836 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001837}
1838
Maninder Singh730ec8c2020-06-03 16:01:18 -07001839unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001840 struct list_head *page_list)
1841{
1842 struct scan_control sc = {
1843 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001844 .may_unmap = 1,
1845 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001846 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001847 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001848 struct page *page, *next;
1849 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001850 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001851
1852 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001853 if (!PageHuge(page) && page_is_file_lru(page) &&
1854 !PageDirty(page) && !__PageMovable(page) &&
1855 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001856 ClearPageActive(page);
1857 list_move(&page->lru, &clean_pages);
1858 }
1859 }
1860
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001861 /*
1862 * We should be safe here since we are only dealing with file pages and
1863 * we are not kswapd and therefore cannot write dirty file pages. But
1864 * call memalloc_noreclaim_save() anyway, just in case these conditions
1865 * change in the future.
1866 */
1867 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001868 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001869 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001870 memalloc_noreclaim_restore(noreclaim_flag);
1871
Minchan Kim02c6de82012-10-08 16:31:55 -07001872 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001873 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1874 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001875 /*
1876 * Since lazyfree pages are isolated from file LRU from the beginning,
1877 * they will rotate back to anonymous LRU in the end if it failed to
1878 * discard so isolated count will be mismatched.
1879 * Compensate the isolated count for both LRU lists.
1880 */
1881 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1882 stat.nr_lazyfree_fail);
1883 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001884 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001885 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001886}
1887
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001888/*
1889 * Attempt to remove the specified page from its LRU. Only take this page
1890 * if it is of the appropriate PageActive status. Pages which are being
1891 * freed elsewhere are also ignored.
1892 *
1893 * page: page to consider
1894 * mode: one of the LRU isolation modes defined above
1895 *
Alex Shic2135f72021-02-24 12:08:01 -08001896 * returns true on success, false on failure.
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001897 */
Alex Shic2135f72021-02-24 12:08:01 -08001898bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001899{
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001900 /* Only take pages on the LRU. */
1901 if (!PageLRU(page))
Alex Shic2135f72021-02-24 12:08:01 -08001902 return false;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001903
Minchan Kime46a2872012-10-08 16:33:48 -07001904 /* Compaction should not handle unevictable pages but CMA can do so */
1905 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
Alex Shic2135f72021-02-24 12:08:01 -08001906 return false;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001907
Mel Gormanc8244932012-01-12 17:19:38 -08001908 /*
1909 * To minimise LRU disruption, the caller can indicate that it only
1910 * wants to isolate pages it will be able to operate on without
1911 * blocking - clean pages for the most part.
1912 *
Mel Gormanc8244932012-01-12 17:19:38 -08001913 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1914 * that it is possible to migrate without blocking
1915 */
Johannes Weiner1276ad62017-02-24 14:56:11 -08001916 if (mode & ISOLATE_ASYNC_MIGRATE) {
Mel Gormanc8244932012-01-12 17:19:38 -08001917 /* All the caller can do on PageWriteback is block */
1918 if (PageWriteback(page))
Alex Shic2135f72021-02-24 12:08:01 -08001919 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001920
1921 if (PageDirty(page)) {
1922 struct address_space *mapping;
Mel Gorman69d763f2018-01-31 16:19:52 -08001923 bool migrate_dirty;
Mel Gormanc8244932012-01-12 17:19:38 -08001924
Mel Gormanc8244932012-01-12 17:19:38 -08001925 /*
1926 * Only pages without mappings or that have a
1927 * ->migratepage callback are possible to migrate
Mel Gorman69d763f2018-01-31 16:19:52 -08001928 * without blocking. However, we can be racing with
1929 * truncation so it's necessary to lock the page
1930 * to stabilise the mapping as truncation holds
1931 * the page lock until after the page is removed
1932 * from the page cache.
Mel Gormanc8244932012-01-12 17:19:38 -08001933 */
Mel Gorman69d763f2018-01-31 16:19:52 -08001934 if (!trylock_page(page))
Alex Shic2135f72021-02-24 12:08:01 -08001935 return false;
Mel Gorman69d763f2018-01-31 16:19:52 -08001936
Mel Gormanc8244932012-01-12 17:19:38 -08001937 mapping = page_mapping(page);
Hugh Dickins145e1a72018-06-01 16:50:50 -07001938 migrate_dirty = !mapping || mapping->a_ops->migratepage;
Mel Gorman69d763f2018-01-31 16:19:52 -08001939 unlock_page(page);
1940 if (!migrate_dirty)
Alex Shic2135f72021-02-24 12:08:01 -08001941 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001942 }
1943 }
Minchan Kim39deaf82011-10-31 17:06:51 -07001944
Minchan Kimf80c0672011-10-31 17:06:55 -07001945 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
Alex Shic2135f72021-02-24 12:08:01 -08001946 return false;
Minchan Kimf80c0672011-10-31 17:06:55 -07001947
Alex Shic2135f72021-02-24 12:08:01 -08001948 return true;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001949}
1950
Mel Gorman7ee36a12016-07-28 15:47:17 -07001951/*
1952 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001953 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001954 */
1955static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001956 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001957{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001958 int zid;
1959
Mel Gorman7ee36a12016-07-28 15:47:17 -07001960 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1961 if (!nr_zone_taken[zid])
1962 continue;
1963
Wei Yanga892cb62020-06-03 16:01:12 -07001964 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001965 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001966
Mel Gorman7ee36a12016-07-28 15:47:17 -07001967}
1968
Mel Gormanf611fab2021-06-30 18:53:19 -07001969/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001970 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1971 *
1972 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001973 * shrink the lists perform better by taking out a batch of pages
1974 * and working on them outside the LRU lock.
1975 *
1976 * For pagecache intensive workloads, this function is the hottest
1977 * spot in the kernel (apart from copy_*_user functions).
1978 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001979 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001980 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001981 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001982 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001983 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001984 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001985 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001986 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001987 *
1988 * returns how many pages were moved onto *@dst.
1989 */
Andrew Morton69e05942006-03-22 00:08:19 -08001990static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001991 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001992 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08001993 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001994{
Hugh Dickins75b00af2012-05-29 15:07:09 -07001995 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08001996 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07001997 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07001998 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07001999 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002000 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002001 LIST_HEAD(pages_skipped);
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002002 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002003
Yang Shi98879b32019-07-11 20:59:30 -07002004 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002005 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07002006 while (scan < nr_to_scan && !list_empty(src)) {
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002007 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002008
Linus Torvalds1da177e2005-04-16 15:20:36 -07002009 page = lru_to_page(src);
2010 prefetchw_prev_lru_page(page, src, flags);
2011
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002012 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002013 total_scan += nr_pages;
2014
Mel Gormanb2e18752016-07-28 15:45:37 -07002015 if (page_zonenum(page) > sc->reclaim_idx) {
2016 list_move(&page->lru, &pages_skipped);
Yang Shi98879b32019-07-11 20:59:30 -07002017 nr_skipped[page_zonenum(page)] += nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002018 continue;
2019 }
2020
Minchan Kim791b48b2017-05-12 15:47:06 -07002021 /*
2022 * Do not count skipped pages because that makes the function
2023 * return with no isolated pages if the LRU mostly contains
2024 * ineligible pages. This causes the VM to not reclaim any
2025 * pages, triggering a premature OOM.
Yang Shi98879b32019-07-11 20:59:30 -07002026 *
2027 * Account all tail pages of THP. This would not cause
2028 * premature OOM since __isolate_lru_page() returns -EBUSY
2029 * only when the page is being freed somewhere else.
Minchan Kim791b48b2017-05-12 15:47:06 -07002030 */
Yang Shi98879b32019-07-11 20:59:30 -07002031 scan += nr_pages;
Alex Shic2135f72021-02-24 12:08:01 -08002032 if (!__isolate_lru_page_prepare(page, mode)) {
2033 /* It is being freed elsewhere */
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002034 list_move(&page->lru, src);
Alex Shic2135f72021-02-24 12:08:01 -08002035 continue;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002036 }
Alex Shic2135f72021-02-24 12:08:01 -08002037 /*
2038 * Be careful not to clear PageLRU until after we're
2039 * sure the page is not being freed elsewhere -- the
2040 * page release code relies on it.
2041 */
2042 if (unlikely(!get_page_unless_zero(page))) {
2043 list_move(&page->lru, src);
2044 continue;
2045 }
2046
2047 if (!TestClearPageLRU(page)) {
2048 /* Another thread is already isolating this page */
2049 put_page(page);
2050 list_move(&page->lru, src);
2051 continue;
2052 }
2053
2054 nr_taken += nr_pages;
2055 nr_zone_taken[page_zonenum(page)] += nr_pages;
2056 list_move(&page->lru, dst);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002057 }
2058
Mel Gormanb2e18752016-07-28 15:45:37 -07002059 /*
2060 * Splice any skipped pages to the start of the LRU list. Note that
2061 * this disrupts the LRU order when reclaiming for lower zones but
2062 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2063 * scanning would soon rescan the same pages to skip and put the
2064 * system at risk of premature OOM.
2065 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002066 if (!list_empty(&pages_skipped)) {
2067 int zid;
2068
Johannes Weiner3db65812017-05-03 14:52:13 -07002069 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002070 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2071 if (!nr_skipped[zid])
2072 continue;
2073
2074 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002075 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002076 }
2077 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002078 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002079 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Minchan Kim791b48b2017-05-12 15:47:06 -07002080 total_scan, skipped, nr_taken, mode, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002081 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002082 return nr_taken;
2083}
2084
Nick Piggin62695a82008-10-18 20:26:09 -07002085/**
2086 * isolate_lru_page - tries to isolate a page from its LRU list
2087 * @page: page to isolate from its LRU list
2088 *
2089 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2090 * vmstat statistic corresponding to whatever LRU list the page was on.
2091 *
2092 * Returns 0 if the page was removed from an LRU list.
2093 * Returns -EBUSY if the page was not on an LRU list.
2094 *
2095 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002096 * the active list, it will have PageActive set. If it was found on
2097 * the unevictable list, it will have the PageUnevictable bit set. That flag
2098 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002099 *
2100 * The vmstat statistic corresponding to the list on which the page was
2101 * found will be decremented.
2102 *
2103 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002104 *
Nick Piggin62695a82008-10-18 20:26:09 -07002105 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002106 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002107 * without a stable reference).
2108 * (2) the lru_lock must not be held.
2109 * (3) interrupts must be enabled.
2110 */
2111int isolate_lru_page(struct page *page)
2112{
2113 int ret = -EBUSY;
2114
Sasha Levin309381fea2014-01-23 15:52:54 -08002115 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002116 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002117
Alex Shid25b5bd2020-12-15 12:34:16 -08002118 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002119 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002120
Alex Shid25b5bd2020-12-15 12:34:16 -08002121 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002122 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002123 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002124 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002125 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002126 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002127
Nick Piggin62695a82008-10-18 20:26:09 -07002128 return ret;
2129}
2130
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002131/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002132 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002133 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002134 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2135 * the LRU list will go small and be scanned faster than necessary, leading to
2136 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002137 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002138static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002139 struct scan_control *sc)
2140{
2141 unsigned long inactive, isolated;
2142
2143 if (current_is_kswapd())
2144 return 0;
2145
Johannes Weinerb5ead352019-11-30 17:55:40 -08002146 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002147 return 0;
2148
2149 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002150 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2151 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002152 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002153 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2154 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002155 }
2156
Fengguang Wu3cf23842012-12-18 14:23:31 -08002157 /*
2158 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2159 * won't get blocked by normal direct-reclaimers, forming a circular
2160 * deadlock.
2161 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002162 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002163 inactive >>= 3;
2164
Rik van Riel35cd7812009-09-21 17:01:38 -07002165 return isolated > inactive;
2166}
2167
Kirill Tkhaia222f342019-05-13 17:17:00 -07002168/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002169 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2170 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002171 *
2172 * Returns the number of pages moved to the given lruvec.
2173 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002174static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2175 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002176{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002177 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002178 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002179 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002180
Kirill Tkhaia222f342019-05-13 17:17:00 -07002181 while (!list_empty(list)) {
2182 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002183 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002184 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002185 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002186 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002187 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002188 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002189 continue;
2190 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002191
Alex Shi3d06afa2020-12-15 12:33:37 -08002192 /*
2193 * The SetPageLRU needs to be kept here for list integrity.
2194 * Otherwise:
2195 * #0 move_pages_to_lru #1 release_pages
2196 * if !put_page_testzero
2197 * if (put_page_testzero())
2198 * !PageLRU //skip lru_lock
2199 * SetPageLRU()
2200 * list_add(&page->lru,)
2201 * list_add(&page->lru,)
2202 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002203 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002204
Alex Shi3d06afa2020-12-15 12:33:37 -08002205 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002206 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002207
2208 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002209 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002210 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002211 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002212 } else
2213 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002214
2215 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002216 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002217
Alex Shiafca9152020-12-15 12:34:02 -08002218 /*
2219 * All pages were isolated from the same lruvec (and isolation
2220 * inhibits memcg migration).
2221 */
Muchun Song7467c392021-06-28 19:37:59 -07002222 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002223 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002224 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002225 nr_moved += nr_pages;
2226 if (PageActive(page))
2227 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002228 }
Mel Gorman66635622010-08-09 17:19:30 -07002229
Hugh Dickins3f797682012-01-12 17:20:07 -08002230 /*
2231 * To save our caller's stack, now use input list for pages to free.
2232 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002233 list_splice(&pages_to_free, list);
2234
2235 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002236}
2237
2238/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002239 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002240 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002241 * In that case we should only throttle if the backing device it is
2242 * writing to is congested. In other cases it is safe to throttle.
2243 */
2244static int current_may_throttle(void)
2245{
NeilBrowna37b0712020-06-01 21:48:18 -07002246 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002247 current->backing_dev_info == NULL ||
2248 bdi_write_congested(current->backing_dev_info);
2249}
2250
2251/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002252 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002253 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002254 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002255static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002256shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002257 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002258{
2259 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002260 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002261 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002262 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002263 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002264 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002265 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002266 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002267 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002268
Mel Gorman599d0c92016-07-28 15:45:31 -07002269 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002270 if (stalled)
2271 return 0;
2272
2273 /* wait a bit for the reclaimer. */
2274 msleep(100);
2275 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002276
2277 /* We are about to die and free our memory. Return now. */
2278 if (fatal_signal_pending(current))
2279 return SWAP_CLUSTER_MAX;
2280 }
2281
Linus Torvalds1da177e2005-04-16 15:20:36 -07002282 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002283
Alex Shi6168d0d2020-12-15 12:34:29 -08002284 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002285
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002286 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002287 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002288
Mel Gorman599d0c92016-07-28 15:45:31 -07002289 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002290 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002291 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002292 __count_vm_events(item, nr_scanned);
2293 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002294 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2295
Alex Shi6168d0d2020-12-15 12:34:29 -08002296 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002297
Hillf Dantond563c052012-03-21 16:34:02 -07002298 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002299 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002300
Shakeel Butt013339d2020-12-14 19:06:39 -08002301 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002302
Alex Shi6168d0d2020-12-15 12:34:29 -08002303 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002304 move_pages_to_lru(lruvec, &page_list);
2305
2306 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002307 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002308 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002309 __count_vm_events(item, nr_reclaimed);
2310 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002311 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002312 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002313
Alex Shi75cc3c92020-12-15 14:20:50 -08002314 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002315 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002316 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002317
Mel Gorman92df3a72011-10-31 17:07:56 -07002318 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002319 * If dirty pages are scanned that are not queued for IO, it
2320 * implies that flushers are not doing their job. This can
2321 * happen when memory pressure pushes dirty pages to the end of
2322 * the LRU before the dirty limits are breached and the dirty
2323 * data has expired. It can also happen when the proportion of
2324 * dirty pages grows not through writes but through memory
2325 * pressure reclaiming all the clean cache. And in some cases,
2326 * the flushers simply cannot keep up with the allocation
2327 * rate. Nudge the flusher threads in case they are asleep.
2328 */
2329 if (stat.nr_unqueued_dirty == nr_taken)
2330 wakeup_flusher_threads(WB_REASON_VMSCAN);
2331
Andrey Ryabinind108c772018-04-10 16:27:59 -07002332 sc->nr.dirty += stat.nr_dirty;
2333 sc->nr.congested += stat.nr_congested;
2334 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2335 sc->nr.writeback += stat.nr_writeback;
2336 sc->nr.immediate += stat.nr_immediate;
2337 sc->nr.taken += nr_taken;
2338 if (file)
2339 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002340
Mel Gorman599d0c92016-07-28 15:45:31 -07002341 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002342 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002343 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002344}
2345
Hugh Dickins15b44732020-12-15 14:21:31 -08002346/*
2347 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2348 *
2349 * We move them the other way if the page is referenced by one or more
2350 * processes.
2351 *
2352 * If the pages are mostly unmapped, the processing is fast and it is
2353 * appropriate to hold lru_lock across the whole operation. But if
2354 * the pages are mapped, the processing is slow (page_referenced()), so
2355 * we should drop lru_lock around each page. It's impossible to balance
2356 * this, so instead we remove the pages from the LRU while processing them.
2357 * It is safe to rely on PG_active against the non-LRU pages in here because
2358 * nobody will play with that bit on a non-LRU page.
2359 *
2360 * The downside is that we have to touch page->_refcount against each page.
2361 * But we had to alter page->flags anyway.
2362 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002363static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002364 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002365 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002366 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002367{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002368 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002369 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002370 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002371 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002372 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002373 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002374 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002375 unsigned nr_deactivate, nr_activate;
2376 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002377 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002378 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002379
2380 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002381
Alex Shi6168d0d2020-12-15 12:34:29 -08002382 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002383
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002384 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002385 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002386
Mel Gorman599d0c92016-07-28 15:45:31 -07002387 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002388
Shakeel Butt912c0572020-08-06 23:26:32 -07002389 if (!cgroup_reclaim(sc))
2390 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002391 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002392
Alex Shi6168d0d2020-12-15 12:34:29 -08002393 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002394
Linus Torvalds1da177e2005-04-16 15:20:36 -07002395 while (!list_empty(&l_hold)) {
2396 cond_resched();
2397 page = lru_to_page(&l_hold);
2398 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002399
Hugh Dickins39b5f292012-10-08 16:33:18 -07002400 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002401 putback_lru_page(page);
2402 continue;
2403 }
2404
Mel Gormancc715d92012-03-21 16:34:00 -07002405 if (unlikely(buffer_heads_over_limit)) {
2406 if (page_has_private(page) && trylock_page(page)) {
2407 if (page_has_private(page))
2408 try_to_release_page(page, 0);
2409 unlock_page(page);
2410 }
2411 }
2412
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002413 if (page_referenced(page, 0, sc->target_mem_cgroup,
2414 &vm_flags)) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002415 /*
2416 * Identify referenced, file-backed active pages and
2417 * give them one more trip around the active list. So
2418 * that executable code get better chances to stay in
2419 * memory under moderate memory pressure. Anon pages
2420 * are not likely to be evicted by use-once streaming
2421 * IO, plus JVM can create lots of anon VM_EXEC pages,
2422 * so we ignore them here.
2423 */
Huang Ying9de4f222020-04-06 20:04:41 -07002424 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002425 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002426 list_add(&page->lru, &l_active);
2427 continue;
2428 }
2429 }
Rik van Riel7e9cd482008-10-18 20:26:35 -07002430
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002431 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002432 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002433 list_add(&page->lru, &l_inactive);
2434 }
2435
Andrew Mortonb5557492009-01-06 14:40:13 -08002436 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002437 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002438 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002439 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002440
Kirill Tkhaia222f342019-05-13 17:17:00 -07002441 nr_activate = move_pages_to_lru(lruvec, &l_active);
2442 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002443 /* Keep all free pages in l_active list */
2444 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002445
2446 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2447 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2448
Mel Gorman599d0c92016-07-28 15:45:31 -07002449 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002450 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002451
Kirill Tkhaif372d892019-05-13 17:16:57 -07002452 mem_cgroup_uncharge_list(&l_active);
2453 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002454 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2455 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002456}
2457
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002458unsigned long reclaim_pages(struct list_head *page_list)
2459{
Yang Shif661d002020-04-01 21:10:05 -07002460 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002461 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002462 LIST_HEAD(node_page_list);
2463 struct reclaim_stat dummy_stat;
2464 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002465 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002466 struct scan_control sc = {
2467 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002468 .may_writepage = 1,
2469 .may_unmap = 1,
2470 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002471 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002472 };
2473
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002474 noreclaim_flag = memalloc_noreclaim_save();
2475
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002476 while (!list_empty(page_list)) {
2477 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002478 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002479 nid = page_to_nid(page);
2480 INIT_LIST_HEAD(&node_page_list);
2481 }
2482
2483 if (nid == page_to_nid(page)) {
2484 ClearPageActive(page);
2485 list_move(&page->lru, &node_page_list);
2486 continue;
2487 }
2488
2489 nr_reclaimed += shrink_page_list(&node_page_list,
2490 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002491 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002492 while (!list_empty(&node_page_list)) {
2493 page = lru_to_page(&node_page_list);
2494 list_del(&page->lru);
2495 putback_lru_page(page);
2496 }
2497
Yang Shif661d002020-04-01 21:10:05 -07002498 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002499 }
2500
2501 if (!list_empty(&node_page_list)) {
2502 nr_reclaimed += shrink_page_list(&node_page_list,
2503 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002504 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002505 while (!list_empty(&node_page_list)) {
2506 page = lru_to_page(&node_page_list);
2507 list_del(&page->lru);
2508 putback_lru_page(page);
2509 }
2510 }
2511
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002512 memalloc_noreclaim_restore(noreclaim_flag);
2513
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002514 return nr_reclaimed;
2515}
2516
Johannes Weinerb91ac372019-11-30 17:56:02 -08002517static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2518 struct lruvec *lruvec, struct scan_control *sc)
2519{
2520 if (is_active_lru(lru)) {
2521 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2522 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2523 else
2524 sc->skipped_deactivate = 1;
2525 return 0;
2526 }
2527
2528 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2529}
2530
Rik van Riel59dc76b2016-05-20 16:56:31 -07002531/*
2532 * The inactive anon list should be small enough that the VM never has
2533 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002534 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002535 * The inactive file list should be small enough to leave most memory
2536 * to the established workingset on the scan-resistant active list,
2537 * but large enough to avoid thrashing the aggregate readahead window.
2538 *
2539 * Both inactive lists should also be large enough that each inactive
2540 * page has a chance to be referenced again before it is reclaimed.
2541 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002542 * If that fails and refaulting is observed, the inactive list grows.
2543 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002544 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002545 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002546 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2547 *
2548 * total target max
2549 * memory ratio inactive
2550 * -------------------------------------
2551 * 10MB 1 5MB
2552 * 100MB 1 50MB
2553 * 1GB 3 250MB
2554 * 10GB 10 0.9GB
2555 * 100GB 31 3GB
2556 * 1TB 101 10GB
2557 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002558 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002559static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002560{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002561 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002562 unsigned long inactive, active;
2563 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002564 unsigned long gb;
2565
Johannes Weinerb91ac372019-11-30 17:56:02 -08002566 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2567 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002568
Johannes Weinerb91ac372019-11-30 17:56:02 -08002569 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002570 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002571 inactive_ratio = int_sqrt(10 * gb);
2572 else
2573 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002574
Rik van Riel59dc76b2016-05-20 16:56:31 -07002575 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002576}
2577
Johannes Weiner9a265112013-02-22 16:32:17 -08002578enum scan_balance {
2579 SCAN_EQUAL,
2580 SCAN_FRACT,
2581 SCAN_ANON,
2582 SCAN_FILE,
2583};
2584
Yu Zhao3eb07702020-09-27 20:49:08 -06002585static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2586{
2587 unsigned long file;
2588 struct lruvec *target_lruvec;
2589
Yu Zhaoa1537a62022-01-27 20:32:37 -07002590 if (lru_gen_enabled())
2591 return;
2592
Yu Zhao3eb07702020-09-27 20:49:08 -06002593 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2594
2595 /*
2596 * Flush the memory cgroup stats, so that we read accurate per-memcg
2597 * lruvec stats for heuristics.
2598 */
2599 mem_cgroup_flush_stats();
2600
2601 /*
2602 * Determine the scan balance between anon and file LRUs.
2603 */
2604 spin_lock_irq(&target_lruvec->lru_lock);
2605 sc->anon_cost = target_lruvec->anon_cost;
2606 sc->file_cost = target_lruvec->file_cost;
2607 spin_unlock_irq(&target_lruvec->lru_lock);
2608
2609 /*
2610 * Target desirable inactive:active list ratios for the anon
2611 * and file LRU lists.
2612 */
2613 if (!sc->force_deactivate) {
2614 unsigned long refaults;
2615
2616 refaults = lruvec_page_state(target_lruvec,
2617 WORKINGSET_ACTIVATE_ANON);
2618 if (refaults != target_lruvec->refaults[0] ||
2619 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2620 sc->may_deactivate |= DEACTIVATE_ANON;
2621 else
2622 sc->may_deactivate &= ~DEACTIVATE_ANON;
2623
2624 /*
2625 * When refaults are being observed, it means a new
2626 * workingset is being established. Deactivate to get
2627 * rid of any stale active pages quickly.
2628 */
2629 refaults = lruvec_page_state(target_lruvec,
2630 WORKINGSET_ACTIVATE_FILE);
2631 if (refaults != target_lruvec->refaults[1] ||
2632 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2633 sc->may_deactivate |= DEACTIVATE_FILE;
2634 else
2635 sc->may_deactivate &= ~DEACTIVATE_FILE;
2636 } else
2637 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2638
2639 /*
2640 * If we have plenty of inactive file pages that aren't
2641 * thrashing, try to reclaim those first before touching
2642 * anonymous pages.
2643 */
2644 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2645 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2646 sc->cache_trim_mode = 1;
2647 else
2648 sc->cache_trim_mode = 0;
2649
2650 /*
2651 * Prevent the reclaimer from falling into the cache trap: as
2652 * cache pages start out inactive, every cache fault will tip
2653 * the scan balance towards the file LRU. And as the file LRU
2654 * shrinks, so does the window for rotation from references.
2655 * This means we have a runaway feedback loop where a tiny
2656 * thrashing file LRU becomes infinitely more attractive than
2657 * anon pages. Try to detect this based on file LRU size.
2658 */
2659 if (!cgroup_reclaim(sc)) {
2660 unsigned long total_high_wmark = 0;
2661 unsigned long free, anon;
2662 int z;
2663
2664 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2665 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2666 node_page_state(pgdat, NR_INACTIVE_FILE);
2667
2668 for (z = 0; z < MAX_NR_ZONES; z++) {
2669 struct zone *zone = &pgdat->node_zones[z];
2670
2671 if (!managed_zone(zone))
2672 continue;
2673
2674 total_high_wmark += high_wmark_pages(zone);
2675 }
2676
2677 /*
2678 * Consider anon: if that's low too, this isn't a
2679 * runaway file reclaim problem, but rather just
2680 * extreme pressure. Reclaim as per usual then.
2681 */
2682 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2683
2684 sc->file_is_tiny =
2685 file + free <= total_high_wmark &&
2686 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2687 anon >> sc->priority;
2688 }
2689}
2690
Linus Torvalds1da177e2005-04-16 15:20:36 -07002691/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002692 * Determine how aggressively the anon and file LRU lists should be
2693 * scanned. The relative value of each set of LRU lists is determined
2694 * by looking at the fraction of the pages scanned we did rotate back
2695 * onto the active list instead of evict.
2696 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002697 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2698 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002699 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002700static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2701 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002702{
Keith Buscha2a36482021-09-02 14:59:26 -07002703 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002704 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002705 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002706 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002707 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002708 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002709 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002710 unsigned long ap, fp;
2711 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002712 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002713
2714 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002715 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002716 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002717 goto out;
2718 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002719
Johannes Weiner10316b32013-02-22 16:32:14 -08002720 /*
2721 * Global reclaim will swap to prevent OOM even with no
2722 * swappiness, but memcg users want to use this knob to
2723 * disable swapping for individual groups completely when
2724 * using the memory controller's swap limit feature would be
2725 * too expensive.
2726 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002727 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002728 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002729 goto out;
2730 }
2731
2732 /*
2733 * Do not apply any pressure balancing cleverness when the
2734 * system is close to OOM, scan both anon and file equally
2735 * (unless the swappiness setting disagrees with swapping).
2736 */
Johannes Weiner02695172014-08-06 16:06:17 -07002737 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002738 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002739 goto out;
2740 }
2741
Johannes Weiner11d16c22013-02-22 16:32:15 -08002742 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002743 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002744 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002745 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002746 scan_balance = SCAN_ANON;
2747 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002748 }
2749
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002750 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2751
Johannes Weiner62376252014-05-06 12:50:07 -07002752 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002753 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002754 * anything from the anonymous working right now. But when balancing
2755 * anon and page cache files for reclaim, allow swapping of anon pages
2756 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002757 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002758 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002759 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002760 goto out;
2761 }
2762
Johannes Weiner9a265112013-02-22 16:32:17 -08002763 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002764 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002765 * Calculate the pressure balance between anon and file pages.
2766 *
2767 * The amount of pressure we put on each LRU is inversely
2768 * proportional to the cost of reclaiming each list, as
2769 * determined by the share of pages that are refaulting, times
2770 * the relative IO cost of bringing back a swapped out
2771 * anonymous page vs reloading a filesystem page (swappiness).
2772 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002773 * Although we limit that influence to ensure no list gets
2774 * left behind completely: at least a third of the pressure is
2775 * applied, before swappiness.
2776 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002777 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002778 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002779 total_cost = sc->anon_cost + sc->file_cost;
2780 anon_cost = total_cost + sc->anon_cost;
2781 file_cost = total_cost + sc->file_cost;
2782 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002783
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002784 ap = swappiness * (total_cost + 1);
2785 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002786
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002787 fp = (200 - swappiness) * (total_cost + 1);
2788 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002789
Shaohua Li76a33fc2010-05-24 14:32:36 -07002790 fraction[0] = ap;
2791 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002792 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002793out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002794 for_each_evictable_lru(lru) {
2795 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002796 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002797 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002798 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002799
Chris Down9783aa92019-10-06 17:58:32 -07002800 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002801 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2802 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002803
Johannes Weinerf56ce412021-08-19 19:04:21 -07002804 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002805 /*
2806 * Scale a cgroup's reclaim pressure by proportioning
2807 * its current usage to its memory.low or memory.min
2808 * setting.
2809 *
2810 * This is important, as otherwise scanning aggression
2811 * becomes extremely binary -- from nothing as we
2812 * approach the memory protection threshold, to totally
2813 * nominal as we exceed it. This results in requiring
2814 * setting extremely liberal protection thresholds. It
2815 * also means we simply get no protection at all if we
2816 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002817 *
2818 * If there is any protection in place, we reduce scan
2819 * pressure by how much of the total memory used is
2820 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002821 *
Chris Down9de7ca42019-10-06 17:58:35 -07002822 * There is one special case: in the first reclaim pass,
2823 * we skip over all groups that are within their low
2824 * protection. If that fails to reclaim enough pages to
2825 * satisfy the reclaim goal, we come back and override
2826 * the best-effort low protection. However, we still
2827 * ideally want to honor how well-behaved groups are in
2828 * that case instead of simply punishing them all
2829 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002830 * memory they are using, reducing the scan pressure
2831 * again by how much of the total memory used is under
2832 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002833 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002834 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002835 unsigned long protection;
2836
2837 /* memory.low scaling, make sure we retry before OOM */
2838 if (!sc->memcg_low_reclaim && low > min) {
2839 protection = low;
2840 sc->memcg_low_skipped = 1;
2841 } else {
2842 protection = min;
2843 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002844
2845 /* Avoid TOCTOU with earlier protection check */
2846 cgroup_size = max(cgroup_size, protection);
2847
2848 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002849 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002850
2851 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002852 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002853 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002854 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002855 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002856 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002857 } else {
2858 scan = lruvec_size;
2859 }
2860
2861 scan >>= sc->priority;
2862
Johannes Weiner688035f2017-05-03 14:52:07 -07002863 /*
2864 * If the cgroup's already been deleted, make sure to
2865 * scrape out the remaining cache.
2866 */
2867 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002868 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002869
Johannes Weiner688035f2017-05-03 14:52:07 -07002870 switch (scan_balance) {
2871 case SCAN_EQUAL:
2872 /* Scan lists relative to size */
2873 break;
2874 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002875 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002876 * Scan types proportional to swappiness and
2877 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002878 * Make sure we don't miss the last page on
2879 * the offlined memory cgroups because of a
2880 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002881 */
Gavin Shan76073c62020-02-20 20:04:24 -08002882 scan = mem_cgroup_online(memcg) ?
2883 div64_u64(scan * fraction[file], denominator) :
2884 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002885 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002886 break;
2887 case SCAN_FILE:
2888 case SCAN_ANON:
2889 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002890 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002891 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002892 break;
2893 default:
2894 /* Look ma, no brain */
2895 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002896 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002897
Johannes Weiner688035f2017-05-03 14:52:07 -07002898 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002899 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002900}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002901
Dave Hansen2f368a92021-09-02 14:59:23 -07002902/*
2903 * Anonymous LRU management is a waste if there is
2904 * ultimately no way to reclaim the memory.
2905 */
2906static bool can_age_anon_pages(struct pglist_data *pgdat,
2907 struct scan_control *sc)
2908{
2909 /* Aging the anon LRU is valuable if swap is present: */
2910 if (total_swap_pages > 0)
2911 return true;
2912
2913 /* Also valuable if anon pages can be demoted: */
2914 return can_demote(pgdat->node_id, sc);
2915}
2916
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002917#ifdef CONFIG_LRU_GEN
2918
Yu Zhao76f7f072022-01-27 19:52:09 -07002919#ifdef CONFIG_LRU_GEN_ENABLED
2920DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2921#else
2922DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2923#endif
2924
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002925/******************************************************************************
2926 * shorthand helpers
2927 ******************************************************************************/
2928
Yu Zhaoa1537a62022-01-27 20:32:37 -07002929#define DEFINE_MAX_SEQ(lruvec) \
2930 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2931
2932#define DEFINE_MIN_SEQ(lruvec) \
2933 unsigned long min_seq[ANON_AND_FILE] = { \
2934 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2935 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2936 }
2937
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002938#define for_each_gen_type_zone(gen, type, zone) \
2939 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2940 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2941 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2942
Yu Zhaoa1537a62022-01-27 20:32:37 -07002943static int page_lru_gen(struct page *page)
2944{
2945 unsigned long flags = READ_ONCE(page->flags);
2946
2947 return ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
2948}
2949
2950static int page_lru_tier(struct page *page)
2951{
2952 int refs;
2953 unsigned long flags = READ_ONCE(page->flags);
2954
2955 refs = (flags & LRU_REFS_FLAGS) == LRU_REFS_FLAGS ?
2956 ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) + 1 : 0;
2957
2958 return lru_tier_from_refs(refs);
2959}
2960
Yu Zhao76f7f072022-01-27 19:52:09 -07002961static bool get_cap(int cap)
2962{
2963#ifdef CONFIG_LRU_GEN_ENABLED
2964 return static_branch_likely(&lru_gen_caps[cap]);
2965#else
2966 return static_branch_unlikely(&lru_gen_caps[cap]);
2967#endif
2968}
2969
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002970static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
2971{
2972 struct pglist_data *pgdat = NODE_DATA(nid);
2973
2974#ifdef CONFIG_MEMCG
2975 if (memcg) {
2976 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2977
2978 /* for hotadd_new_pgdat() */
2979 if (!lruvec->pgdat)
2980 lruvec->pgdat = pgdat;
2981
2982 return lruvec;
2983 }
2984#endif
2985 VM_BUG_ON(!mem_cgroup_disabled());
2986
2987 return pgdat ? &pgdat->__lruvec : NULL;
2988}
2989
Yu Zhaoa1537a62022-01-27 20:32:37 -07002990static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
2991{
2992 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
2993 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
2994
2995 if (!can_demote(pgdat->node_id, sc) &&
2996 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
2997 return 0;
2998
2999 return mem_cgroup_swappiness(memcg);
3000}
3001
3002static int get_nr_gens(struct lruvec *lruvec, int type)
3003{
3004 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3005}
3006
3007static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3008{
3009 /* see the comment on lru_gen_struct */
3010 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3011 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3012 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3013}
3014
3015/******************************************************************************
Yu Zhao5280d762022-01-27 19:23:01 -07003016 * mm_struct list
3017 ******************************************************************************/
3018
3019static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3020{
3021 static struct lru_gen_mm_list mm_list = {
3022 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3023 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3024 };
3025
3026#ifdef CONFIG_MEMCG
3027 if (memcg)
3028 return &memcg->mm_list;
3029#endif
3030 VM_BUG_ON(!mem_cgroup_disabled());
3031
3032 return &mm_list;
3033}
3034
3035void lru_gen_add_mm(struct mm_struct *mm)
3036{
3037 int nid;
3038 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3039 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3040
3041 VM_BUG_ON_MM(!list_empty(&mm->lru_gen.list), mm);
3042#ifdef CONFIG_MEMCG
3043 VM_BUG_ON_MM(mm->lru_gen.memcg, mm);
3044 mm->lru_gen.memcg = memcg;
3045#endif
3046 spin_lock(&mm_list->lock);
3047
3048 for_each_node_state(nid, N_MEMORY) {
3049 struct lruvec *lruvec = get_lruvec(memcg, nid);
3050
3051 if (!lruvec)
3052 continue;
3053
3054 if (lruvec->mm_state.tail == &mm_list->fifo)
3055 lruvec->mm_state.tail = &mm->lru_gen.list;
3056 }
3057
3058 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3059
3060 spin_unlock(&mm_list->lock);
3061}
3062
3063void lru_gen_del_mm(struct mm_struct *mm)
3064{
3065 int nid;
3066 struct lru_gen_mm_list *mm_list;
3067 struct mem_cgroup *memcg = NULL;
3068
3069 if (list_empty(&mm->lru_gen.list))
3070 return;
3071
3072#ifdef CONFIG_MEMCG
3073 memcg = mm->lru_gen.memcg;
3074#endif
3075 mm_list = get_mm_list(memcg);
3076
3077 spin_lock(&mm_list->lock);
3078
3079 for_each_node(nid) {
3080 struct lruvec *lruvec = get_lruvec(memcg, nid);
3081
3082 if (!lruvec)
3083 continue;
3084
3085 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3086 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3087
3088 if (lruvec->mm_state.head != &mm->lru_gen.list)
3089 continue;
3090
3091 lruvec->mm_state.head = lruvec->mm_state.head->next;
3092 if (lruvec->mm_state.head == &mm_list->fifo)
3093 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3094 }
3095
3096 list_del_init(&mm->lru_gen.list);
3097
3098 spin_unlock(&mm_list->lock);
3099
3100#ifdef CONFIG_MEMCG
3101 mem_cgroup_put(mm->lru_gen.memcg);
3102 mm->lru_gen.memcg = NULL;
3103#endif
3104}
3105
3106#ifdef CONFIG_MEMCG
3107void lru_gen_migrate_mm(struct mm_struct *mm)
3108{
3109 struct mem_cgroup *memcg;
3110
3111 lockdep_assert_held(&mm->owner->alloc_lock);
3112
3113 /* for mm_update_next_owner() */
3114 if (mem_cgroup_disabled())
3115 return;
3116
3117 rcu_read_lock();
3118 memcg = mem_cgroup_from_task(mm->owner);
3119 rcu_read_unlock();
3120 if (memcg == mm->lru_gen.memcg)
3121 return;
3122
3123 VM_BUG_ON_MM(!mm->lru_gen.memcg, mm);
3124 VM_BUG_ON_MM(list_empty(&mm->lru_gen.list), mm);
3125
3126 lru_gen_del_mm(mm);
3127 lru_gen_add_mm(mm);
3128}
3129#endif
3130
3131/*
3132 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3133 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3134 * bits in a bitmap, k is the number of hash functions and n is the number of
3135 * inserted items.
3136 *
3137 * Page table walkers use one of the two filters to reduce their search space.
3138 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3139 * aging uses the double-buffering technique to flip to the other filter each
3140 * time it produces a new generation. For non-leaf entries that have enough
3141 * leaf entries, the aging carries them over to the next generation in
3142 * walk_pmd_range(); the eviction also report them when walking the rmap
3143 * in lru_gen_look_around().
3144 *
3145 * For future optimizations:
3146 * 1. It's not necessary to keep both filters all the time. The spare one can be
3147 * freed after the RCU grace period and reallocated if needed again.
3148 * 2. And when reallocating, it's worth scaling its size according to the number
3149 * of inserted entries in the other filter, to reduce the memory overhead on
3150 * small systems and false positives on large systems.
3151 * 3. Jenkins' hash function is an alternative to Knuth's.
3152 */
3153#define BLOOM_FILTER_SHIFT 15
3154
3155static inline int filter_gen_from_seq(unsigned long seq)
3156{
3157 return seq % NR_BLOOM_FILTERS;
3158}
3159
3160static void get_item_key(void *item, int *key)
3161{
3162 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3163
3164 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3165
3166 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3167 key[1] = hash >> BLOOM_FILTER_SHIFT;
3168}
3169
3170static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3171{
3172 unsigned long *filter;
3173 int gen = filter_gen_from_seq(seq);
3174
3175 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3176
3177 filter = lruvec->mm_state.filters[gen];
3178 if (filter) {
3179 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3180 return;
3181 }
3182
3183 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT), GFP_ATOMIC);
3184 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3185}
3186
3187static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3188{
3189 int key[2];
3190 unsigned long *filter;
3191 int gen = filter_gen_from_seq(seq);
3192
3193 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3194 if (!filter)
3195 return;
3196
3197 get_item_key(item, key);
3198
3199 if (!test_bit(key[0], filter))
3200 set_bit(key[0], filter);
3201 if (!test_bit(key[1], filter))
3202 set_bit(key[1], filter);
3203}
3204
3205static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3206{
3207 int key[2];
3208 unsigned long *filter;
3209 int gen = filter_gen_from_seq(seq);
3210
3211 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3212 if (!filter)
3213 return true;
3214
3215 get_item_key(item, key);
3216
3217 return test_bit(key[0], filter) && test_bit(key[1], filter);
3218}
3219
3220static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3221{
3222 int i;
3223 int hist;
3224
3225 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3226
3227 if (walk) {
3228 hist = lru_hist_from_seq(walk->max_seq);
3229
3230 for (i = 0; i < NR_MM_STATS; i++) {
3231 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3232 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3233 walk->mm_stats[i] = 0;
3234 }
3235 }
3236
3237 if (NR_HIST_GENS > 1 && last) {
3238 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3239
3240 for (i = 0; i < NR_MM_STATS; i++)
3241 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3242 }
3243}
3244
3245static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3246{
3247 int type;
3248 unsigned long size = 0;
3249 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3250
3251 if (!walk->full_scan && cpumask_empty(mm_cpumask(mm)) &&
3252 !node_isset(pgdat->node_id, mm->lru_gen.nodes))
3253 return true;
3254
3255 node_clear(pgdat->node_id, mm->lru_gen.nodes);
3256
3257 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3258 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3259 get_mm_counter(mm, MM_ANONPAGES) +
3260 get_mm_counter(mm, MM_SHMEMPAGES);
3261 }
3262
3263 if (size < MIN_LRU_BATCH)
3264 return true;
3265
3266 if (mm_is_oom_victim(mm))
3267 return true;
3268
3269 return !mmget_not_zero(mm);
3270}
3271
3272static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3273 struct mm_struct **iter)
3274{
3275 bool first = false;
3276 bool last = true;
3277 struct mm_struct *mm = NULL;
3278 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3279 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3280 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3281
3282 /*
3283 * There are four interesting cases for this page table walker:
3284 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3285 * there is nothing to be done.
3286 * 2. It's the first of the current generation, and it needs to reset
3287 * the Bloom filter for the next generation.
3288 * 3. It reaches the end of mm_list, and it needs to increment
3289 * mm_state->seq; the iteration is done.
3290 * 4. It's the last of the current generation, and it needs to reset the
3291 * mm stats counters for the next generation.
3292 */
3293 if (*iter)
3294 mmput_async(*iter);
3295 else if (walk->max_seq <= READ_ONCE(mm_state->seq))
3296 return false;
3297
3298 spin_lock(&mm_list->lock);
3299
3300 VM_BUG_ON(mm_state->seq + 1 < walk->max_seq);
3301 VM_BUG_ON(*iter && mm_state->seq > walk->max_seq);
3302 VM_BUG_ON(*iter && !mm_state->nr_walkers);
3303
3304 if (walk->max_seq <= mm_state->seq) {
3305 if (!*iter)
3306 last = false;
3307 goto done;
3308 }
3309
3310 if (!mm_state->nr_walkers) {
3311 VM_BUG_ON(mm_state->head && mm_state->head != &mm_list->fifo);
3312
3313 mm_state->head = mm_list->fifo.next;
3314 first = true;
3315 }
3316
3317 while (!mm && mm_state->head != &mm_list->fifo) {
3318 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3319
3320 mm_state->head = mm_state->head->next;
3321
3322 /* full scan for those added after the last iteration */
3323 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3324 mm_state->tail = mm_state->head;
3325 walk->full_scan = true;
3326 }
3327
3328 if (should_skip_mm(mm, walk))
3329 mm = NULL;
3330 }
3331
3332 if (mm_state->head == &mm_list->fifo)
3333 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3334done:
3335 if (*iter && !mm)
3336 mm_state->nr_walkers--;
3337 if (!*iter && mm)
3338 mm_state->nr_walkers++;
3339
3340 if (mm_state->nr_walkers)
3341 last = false;
3342
3343 if (mm && first)
3344 reset_bloom_filter(lruvec, walk->max_seq + 1);
3345
3346 if (*iter || last)
3347 reset_mm_stats(lruvec, walk, last);
3348
3349 spin_unlock(&mm_list->lock);
3350
3351 *iter = mm;
3352
3353 return last;
3354}
3355
3356static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3357{
3358 bool success = false;
3359 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3360 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3361 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3362
3363 if (max_seq <= READ_ONCE(mm_state->seq))
3364 return false;
3365
3366 spin_lock(&mm_list->lock);
3367
3368 VM_BUG_ON(mm_state->seq + 1 < max_seq);
3369
3370 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3371 VM_BUG_ON(mm_state->head && mm_state->head != &mm_list->fifo);
3372
3373 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3374 reset_mm_stats(lruvec, NULL, true);
3375 success = true;
3376 }
3377
3378 spin_unlock(&mm_list->lock);
3379
3380 return success;
3381}
3382
3383/******************************************************************************
Yu Zhaoa1537a62022-01-27 20:32:37 -07003384 * refault feedback loop
3385 ******************************************************************************/
3386
3387/*
3388 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3389 *
3390 * The P term is refaulted/(evicted+protected) from a tier in the generation
3391 * currently being evicted; the I term is the exponential moving average of the
3392 * P term over the generations previously evicted, using the smoothing factor
3393 * 1/2; the D term isn't supported.
3394 *
3395 * The setpoint (SP) is always the first tier of one type; the process variable
3396 * (PV) is either any tier of the other type or any other tier of the same
3397 * type.
3398 *
3399 * The error is the difference between the SP and the PV; the correction is
3400 * turn off protection when SP>PV or turn on protection when SP<PV.
3401 *
3402 * For future optimizations:
3403 * 1. The D term may discount the other two terms over time so that long-lived
3404 * generations can resist stale information.
3405 */
3406struct ctrl_pos {
3407 unsigned long refaulted;
3408 unsigned long total;
3409 int gain;
3410};
3411
3412static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3413 struct ctrl_pos *pos)
3414{
3415 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3416 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3417
3418 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3419 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3420 pos->total = lrugen->avg_total[type][tier] +
3421 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3422 if (tier)
3423 pos->total += lrugen->protected[hist][type][tier - 1];
3424 pos->gain = gain;
3425}
3426
3427static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3428{
3429 int hist, tier;
3430 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3431 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3432 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3433
3434 lockdep_assert_held(&lruvec->lru_lock);
3435
3436 if (!carryover && !clear)
3437 return;
3438
3439 hist = lru_hist_from_seq(seq);
3440
3441 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3442 if (carryover) {
3443 unsigned long sum;
3444
3445 sum = lrugen->avg_refaulted[type][tier] +
3446 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3447 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3448
3449 sum = lrugen->avg_total[type][tier] +
3450 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3451 if (tier)
3452 sum += lrugen->protected[hist][type][tier - 1];
3453 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3454 }
3455
3456 if (clear) {
3457 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3458 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3459 if (tier)
3460 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3461 }
3462 }
3463}
3464
3465static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3466{
3467 /*
3468 * Return true if the PV has a limited number of refaults or a lower
3469 * refaulted/total than the SP.
3470 */
3471 return pv->refaulted < MIN_LRU_BATCH ||
3472 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3473 (sp->refaulted + 1) * pv->total * pv->gain;
3474}
3475
3476/******************************************************************************
3477 * the aging
3478 ******************************************************************************/
3479
Yu Zhaoafd94c92022-01-27 20:43:22 -07003480static int page_update_gen(struct page *page, int gen)
3481{
3482 unsigned long old_flags, new_flags;
3483
3484 VM_BUG_ON(gen >= MAX_NR_GENS);
3485 VM_BUG_ON(!rcu_read_lock_held());
3486
3487 do {
3488 new_flags = old_flags = READ_ONCE(page->flags);
3489
3490 /* for shrink_page_list() */
3491 if (!(new_flags & LRU_GEN_MASK)) {
3492 new_flags |= BIT(PG_referenced);
3493 continue;
3494 }
3495
3496 new_flags &= ~LRU_GEN_MASK;
3497 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3498 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3499 } while (new_flags != old_flags &&
3500 cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3501
3502 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3503}
3504
Yu Zhaoa1537a62022-01-27 20:32:37 -07003505static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3506{
3507 unsigned long old_flags, new_flags;
3508 int type = page_is_file_lru(page);
3509 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3510 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3511
3512 do {
3513 new_flags = old_flags = READ_ONCE(page->flags);
3514 VM_BUG_ON_PAGE(!(new_flags & LRU_GEN_MASK), page);
3515
Yu Zhaoafd94c92022-01-27 20:43:22 -07003516 new_gen = ((new_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3517 /* page_update_gen() has promoted this page? */
3518 if (new_gen >= 0 && new_gen != old_gen)
3519 return new_gen;
3520
Yu Zhaoa1537a62022-01-27 20:32:37 -07003521 new_gen = (old_gen + 1) % MAX_NR_GENS;
3522
3523 new_flags &= ~LRU_GEN_MASK;
3524 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3525 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3526 /* for end_page_writeback() */
3527 if (reclaiming)
3528 new_flags |= BIT(PG_reclaim);
3529 } while (cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3530
3531 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3532
3533 return new_gen;
3534}
3535
Yu Zhao5280d762022-01-27 19:23:01 -07003536static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3537 int old_gen, int new_gen)
3538{
3539 int type = page_is_file_lru(page);
3540 int zone = page_zonenum(page);
3541 int delta = thp_nr_pages(page);
3542
3543 VM_BUG_ON(old_gen >= MAX_NR_GENS);
3544 VM_BUG_ON(new_gen >= MAX_NR_GENS);
3545
3546 walk->batched++;
3547
3548 walk->nr_pages[old_gen][type][zone] -= delta;
3549 walk->nr_pages[new_gen][type][zone] += delta;
3550}
3551
3552static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3553{
3554 int gen, type, zone;
3555 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3556
3557 walk->batched = 0;
3558
3559 for_each_gen_type_zone(gen, type, zone) {
3560 enum lru_list lru = type * LRU_INACTIVE_FILE;
3561 int delta = walk->nr_pages[gen][type][zone];
3562
3563 if (!delta)
3564 continue;
3565
3566 walk->nr_pages[gen][type][zone] = 0;
3567 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3568 lrugen->nr_pages[gen][type][zone] + delta);
3569
3570 if (lru_gen_is_active(lruvec, gen))
3571 lru += LRU_ACTIVE;
3572 __update_lru_size(lruvec, lru, zone, delta);
3573 }
3574}
3575
3576static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *walk)
3577{
3578 struct address_space *mapping;
3579 struct vm_area_struct *vma = walk->vma;
3580 struct lru_gen_mm_walk *priv = walk->private;
3581
3582 if (!vma_is_accessible(vma) || is_vm_hugetlb_page(vma) ||
3583 (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ)) ||
3584 vma == get_gate_vma(vma->vm_mm))
3585 return true;
3586
3587 if (vma_is_anonymous(vma))
3588 return !priv->can_swap;
3589
3590 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3591 return true;
3592
3593 mapping = vma->vm_file->f_mapping;
3594 if (mapping_unevictable(mapping))
3595 return true;
3596
3597 /* check readpage to exclude special mappings like dax, etc. */
3598 return shmem_mapping(mapping) ? !priv->can_swap : !mapping->a_ops->readpage;
3599}
3600
3601/*
3602 * Some userspace memory allocators map many single-page VMAs. Instead of
3603 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3604 * table to reduce zigzags and improve cache performance.
3605 */
3606static bool get_next_vma(struct mm_walk *walk, unsigned long mask, unsigned long size,
3607 unsigned long *start, unsigned long *end)
3608{
3609 unsigned long next = round_up(*end, size);
3610
3611 VM_BUG_ON(mask & size);
3612 VM_BUG_ON(*start >= *end);
3613 VM_BUG_ON((next & mask) != (*start & mask));
3614
3615 while (walk->vma) {
3616 if (next >= walk->vma->vm_end) {
3617 walk->vma = walk->vma->vm_next;
3618 continue;
3619 }
3620
3621 if ((next & mask) != (walk->vma->vm_start & mask))
3622 return false;
3623
3624 if (should_skip_vma(walk->vma->vm_start, walk->vma->vm_end, walk)) {
3625 walk->vma = walk->vma->vm_next;
3626 continue;
3627 }
3628
3629 *start = max(next, walk->vma->vm_start);
3630 next = (next | ~mask) + 1;
3631 /* rounded-up boundaries can wrap to 0 */
3632 *end = next && next < walk->vma->vm_end ? next : walk->vma->vm_end;
3633
3634 return true;
3635 }
3636
3637 return false;
3638}
3639
3640static bool suitable_to_scan(int total, int young)
3641{
3642 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3643
3644 /* suitable if the average number of young PTEs per cacheline is >=1 */
3645 return young * n >= total;
3646}
3647
3648static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3649 struct mm_walk *walk)
3650{
3651 int i;
3652 pte_t *pte;
3653 spinlock_t *ptl;
3654 unsigned long addr;
3655 int total = 0;
3656 int young = 0;
3657 struct lru_gen_mm_walk *priv = walk->private;
3658 struct mem_cgroup *memcg = lruvec_memcg(priv->lruvec);
3659 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3660 int old_gen, new_gen = lru_gen_from_seq(priv->max_seq);
3661
3662 VM_BUG_ON(pmd_leaf(*pmd));
3663
3664 ptl = pte_lockptr(walk->mm, pmd);
3665 if (!spin_trylock(ptl))
3666 return false;
3667
3668 arch_enter_lazy_mmu_mode();
3669
3670 pte = pte_offset_map(pmd, start & PMD_MASK);
3671restart:
3672 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3673 struct page *page;
3674 unsigned long pfn = pte_pfn(pte[i]);
3675
3676 VM_BUG_ON(addr < walk->vma->vm_start || addr >= walk->vma->vm_end);
3677
3678 total++;
3679 priv->mm_stats[MM_PTE_TOTAL]++;
3680
3681 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
3682 continue;
3683
3684 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
3685 continue;
3686
3687 if (!pte_young(pte[i])) {
3688 priv->mm_stats[MM_PTE_OLD]++;
3689 continue;
3690 }
3691
3692 VM_BUG_ON(!pfn_valid(pfn));
3693 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3694 continue;
3695
3696 page = compound_head(pfn_to_page(pfn));
3697 if (page_to_nid(page) != pgdat->node_id)
3698 continue;
3699
3700 if (page_memcg_rcu(page) != memcg)
3701 continue;
3702
3703 if (!ptep_test_and_clear_young(walk->vma, addr, pte + i))
3704 continue;
3705
3706 young++;
3707 priv->mm_stats[MM_PTE_YOUNG]++;
3708
3709 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3710 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3711 set_page_dirty(page);
3712
3713 old_gen = page_update_gen(page, new_gen);
3714 if (old_gen >= 0 && old_gen != new_gen)
3715 update_batch_size(priv, page, old_gen, new_gen);
3716 }
3717
3718 if (i < PTRS_PER_PTE && get_next_vma(walk, PMD_MASK, PAGE_SIZE, &start, &end))
3719 goto restart;
3720
3721 pte_unmap(pte);
3722
3723 arch_leave_lazy_mmu_mode();
3724 spin_unlock(ptl);
3725
3726 return suitable_to_scan(total, young);
3727}
3728
3729#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3730static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3731 struct mm_walk *walk, unsigned long *start)
3732{
3733 int i;
3734 pmd_t *pmd;
3735 spinlock_t *ptl;
3736 struct lru_gen_mm_walk *priv = walk->private;
3737 struct mem_cgroup *memcg = lruvec_memcg(priv->lruvec);
3738 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3739 int old_gen, new_gen = lru_gen_from_seq(priv->max_seq);
3740
3741 VM_BUG_ON(pud_leaf(*pud));
3742
3743 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3744 if (*start == -1) {
3745 *start = next;
3746 return;
3747 }
3748
3749 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3750 if (i && i <= MIN_LRU_BATCH) {
3751 __set_bit(i - 1, priv->bitmap);
3752 return;
3753 }
3754
3755 pmd = pmd_offset(pud, *start);
3756
3757 ptl = pmd_lockptr(walk->mm, pmd);
3758 if (!spin_trylock(ptl))
3759 goto done;
3760
3761 arch_enter_lazy_mmu_mode();
3762
3763 do {
3764 struct page *page;
3765 unsigned long pfn = pmd_pfn(pmd[i]);
3766 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3767
3768 VM_BUG_ON(addr < vma->vm_start || addr >= vma->vm_end);
3769
3770 if (!pmd_present(pmd[i]) || is_huge_zero_pmd(pmd[i]))
3771 goto next;
3772
3773 if (WARN_ON_ONCE(pmd_devmap(pmd[i])))
3774 goto next;
3775
3776 if (!pmd_trans_huge(pmd[i])) {
Yu Zhao76f7f072022-01-27 19:52:09 -07003777 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3778 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao5280d762022-01-27 19:23:01 -07003779 pmdp_test_and_clear_young(vma, addr, pmd + i);
3780 goto next;
3781 }
3782
3783 VM_BUG_ON(!pfn_valid(pfn));
3784 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3785 goto next;
3786
3787 page = pfn_to_page(pfn);
3788 VM_BUG_ON_PAGE(PageTail(page), page);
3789 if (page_to_nid(page) != pgdat->node_id)
3790 goto next;
3791
3792 if (page_memcg_rcu(page) != memcg)
3793 goto next;
3794
3795 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3796 goto next;
3797
3798 priv->mm_stats[MM_PTE_YOUNG]++;
3799
3800 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3801 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3802 set_page_dirty(page);
3803
3804 old_gen = page_update_gen(page, new_gen);
3805 if (old_gen >= 0 && old_gen != new_gen)
3806 update_batch_size(priv, page, old_gen, new_gen);
3807next:
3808 i = i > MIN_LRU_BATCH ? 0 :
3809 find_next_bit(priv->bitmap, MIN_LRU_BATCH, i) + 1;
3810 } while (i <= MIN_LRU_BATCH);
3811
3812 arch_leave_lazy_mmu_mode();
3813 spin_unlock(ptl);
3814done:
3815 *start = -1;
3816 bitmap_zero(priv->bitmap, MIN_LRU_BATCH);
3817}
3818#else
3819static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3820 struct mm_walk *walk, unsigned long *start)
3821{
3822}
3823#endif
3824
3825static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3826 struct mm_walk *walk)
3827{
3828 int i;
3829 pmd_t *pmd;
3830 unsigned long next;
3831 unsigned long addr;
3832 struct vm_area_struct *vma;
3833 unsigned long pos = -1;
3834 struct lru_gen_mm_walk *priv = walk->private;
3835
3836 VM_BUG_ON(pud_leaf(*pud));
3837
3838 /*
3839 * Finish an entire PMD in two passes: the first only reaches to PTE
3840 * tables to avoid taking the PMD lock; the second, if necessary, takes
3841 * the PMD lock to clear the accessed bit in PMD entries.
3842 */
3843 pmd = pmd_offset(pud, start & PUD_MASK);
3844restart:
3845 /* walk_pte_range() may call get_next_vma() */
3846 vma = walk->vma;
3847 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3848 pmd_t val = pmd_read_atomic(pmd + i);
3849
3850 /* for pmd_read_atomic() */
3851 barrier();
3852
3853 next = pmd_addr_end(addr, end);
3854
3855 if (!pmd_present(val)) {
3856 priv->mm_stats[MM_PTE_TOTAL]++;
3857 continue;
3858 }
3859
3860#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3861 if (pmd_trans_huge(val)) {
3862 unsigned long pfn = pmd_pfn(val);
3863 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3864
3865 priv->mm_stats[MM_PTE_TOTAL]++;
3866
3867 if (is_huge_zero_pmd(val))
3868 continue;
3869
3870 if (!pmd_young(val)) {
3871 priv->mm_stats[MM_PTE_OLD]++;
3872 continue;
3873 }
3874
3875 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3876 continue;
3877
3878 walk_pmd_range_locked(pud, addr, vma, walk, &pos);
3879 continue;
3880 }
3881#endif
3882 priv->mm_stats[MM_PMD_TOTAL]++;
3883
3884#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
Yu Zhao76f7f072022-01-27 19:52:09 -07003885 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3886 if (!pmd_young(val))
3887 continue;
Yu Zhao5280d762022-01-27 19:23:01 -07003888
Yu Zhao76f7f072022-01-27 19:52:09 -07003889 walk_pmd_range_locked(pud, addr, vma, walk, &pos);
3890 }
Yu Zhao5280d762022-01-27 19:23:01 -07003891#endif
3892 if (!priv->full_scan && !test_bloom_filter(priv->lruvec, priv->max_seq, pmd + i))
3893 continue;
3894
3895 priv->mm_stats[MM_PMD_FOUND]++;
3896
3897 if (!walk_pte_range(&val, addr, next, walk))
3898 continue;
3899
3900 priv->mm_stats[MM_PMD_ADDED]++;
3901
3902 /* carry over to the next generation */
3903 update_bloom_filter(priv->lruvec, priv->max_seq + 1, pmd + i);
3904 }
3905
3906 walk_pmd_range_locked(pud, -1, vma, walk, &pos);
3907
3908 if (i < PTRS_PER_PMD && get_next_vma(walk, PUD_MASK, PMD_SIZE, &start, &end))
3909 goto restart;
3910}
3911
3912static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3913 struct mm_walk *walk)
3914{
3915 int i;
3916 pud_t *pud;
3917 unsigned long addr;
3918 unsigned long next;
3919 struct lru_gen_mm_walk *priv = walk->private;
3920
3921 VM_BUG_ON(p4d_leaf(*p4d));
3922
3923 pud = pud_offset(p4d, start & P4D_MASK);
3924restart:
3925 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3926 pud_t val = READ_ONCE(pud[i]);
3927
3928 next = pud_addr_end(addr, end);
3929
3930 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3931 continue;
3932
3933 walk_pmd_range(&val, addr, next, walk);
3934
3935 if (priv->batched >= MAX_LRU_BATCH) {
3936 end = (addr | ~PUD_MASK) + 1;
3937 goto done;
3938 }
3939 }
3940
3941 if (i < PTRS_PER_PUD && get_next_vma(walk, P4D_MASK, PUD_SIZE, &start, &end))
3942 goto restart;
3943
3944 end = round_up(end, P4D_SIZE);
3945done:
3946 /* rounded-up boundaries can wrap to 0 */
3947 priv->next_addr = end && walk->vma ? max(end, walk->vma->vm_start) : 0;
3948
3949 return -EAGAIN;
3950}
3951
3952static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3953{
3954 static const struct mm_walk_ops mm_walk_ops = {
3955 .test_walk = should_skip_vma,
3956 .p4d_entry = walk_pud_range,
3957 };
3958
3959 int err;
3960 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3961
3962 walk->next_addr = FIRST_USER_ADDRESS;
3963
3964 do {
3965 err = -EBUSY;
3966
3967 /* page_update_gen() requires stable page_memcg() */
3968 if (!mem_cgroup_trylock_pages(memcg))
3969 break;
3970
3971 /* the caller might be holding the lock for write */
3972 if (mmap_read_trylock(mm)) {
3973 unsigned long start = walk->next_addr;
3974 unsigned long end = mm->highest_vm_end;
3975
3976 err = walk_page_range(mm, start, end, &mm_walk_ops, walk);
3977
3978 mmap_read_unlock(mm);
3979
3980 if (walk->batched) {
3981 spin_lock_irq(&lruvec->lru_lock);
3982 reset_batch_size(lruvec, walk);
3983 spin_unlock_irq(&lruvec->lru_lock);
3984 }
3985 }
3986
3987 mem_cgroup_unlock_pages();
3988
3989 cond_resched();
3990 } while (err == -EAGAIN && walk->next_addr && !mm_is_oom_victim(mm));
3991}
3992
3993static struct lru_gen_mm_walk *alloc_mm_walk(void)
3994{
3995 if (current->reclaim_state && current->reclaim_state->mm_walk)
3996 return current->reclaim_state->mm_walk;
3997
3998 return kzalloc(sizeof(struct lru_gen_mm_walk),
3999 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4000}
4001
4002static void free_mm_walk(struct lru_gen_mm_walk *walk)
4003{
4004 if (!current->reclaim_state || !current->reclaim_state->mm_walk)
4005 kfree(walk);
4006}
4007
Yu Zhaoa1537a62022-01-27 20:32:37 -07004008static void inc_min_seq(struct lruvec *lruvec)
4009{
4010 int type;
4011 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4012
4013 VM_BUG_ON(!seq_is_valid(lruvec));
4014
4015 for (type = 0; type < ANON_AND_FILE; type++) {
4016 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4017 continue;
4018
4019 reset_ctrl_pos(lruvec, type, true);
4020 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4021 }
4022}
4023
4024static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4025{
4026 int gen, type, zone;
4027 bool success = false;
4028 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4029 DEFINE_MIN_SEQ(lruvec);
4030
4031 VM_BUG_ON(!seq_is_valid(lruvec));
4032
4033 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4034 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4035 gen = lru_gen_from_seq(min_seq[type]);
4036
4037 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4038 if (!list_empty(&lrugen->lists[gen][type][zone]))
4039 goto next;
4040 }
4041
4042 min_seq[type]++;
4043 }
4044next:
4045 ;
4046 }
4047
4048 /* see the comment on lru_gen_struct */
4049 if (can_swap) {
4050 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4051 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4052 }
4053
4054 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4055 if (min_seq[type] == lrugen->min_seq[type])
4056 continue;
4057
4058 reset_ctrl_pos(lruvec, type, true);
4059 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4060 success = true;
4061 }
4062
4063 return success;
4064}
4065
Yu Zhao5280d762022-01-27 19:23:01 -07004066static void inc_max_seq(struct lruvec *lruvec)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004067{
4068 int prev, next;
4069 int type, zone;
4070 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4071
4072 spin_lock_irq(&lruvec->lru_lock);
4073
4074 VM_BUG_ON(!seq_is_valid(lruvec));
4075
Yu Zhaoa1537a62022-01-27 20:32:37 -07004076 inc_min_seq(lruvec);
4077
4078 /*
4079 * Update the active/inactive LRU sizes for compatibility. Both sides of
4080 * the current max_seq need to be covered, since max_seq+1 can overlap
4081 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4082 * overlap, cold/hot inversion happens. This can be solved by moving
4083 * pages from min_seq to min_seq+1 but is omitted for simplicity.
4084 */
4085 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4086 next = lru_gen_from_seq(lrugen->max_seq + 1);
4087
4088 for (type = 0; type < ANON_AND_FILE; type++) {
4089 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4090 enum lru_list lru = type * LRU_INACTIVE_FILE;
4091 long delta = lrugen->nr_pages[prev][type][zone] -
4092 lrugen->nr_pages[next][type][zone];
4093
4094 if (!delta)
4095 continue;
4096
4097 __update_lru_size(lruvec, lru, zone, delta);
4098 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4099 }
4100 }
4101
4102 for (type = 0; type < ANON_AND_FILE; type++)
4103 reset_ctrl_pos(lruvec, type, false);
4104
4105 /* make sure preceding modifications appear */
4106 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao5280d762022-01-27 19:23:01 -07004107
Yu Zhaoa1537a62022-01-27 20:32:37 -07004108 spin_unlock_irq(&lruvec->lru_lock);
4109}
4110
Yu Zhao5280d762022-01-27 19:23:01 -07004111static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4112 struct scan_control *sc, bool can_swap, bool full_scan)
4113{
4114 bool success;
4115 struct lru_gen_mm_walk *walk;
4116 struct mm_struct *mm = NULL;
4117 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4118
4119 VM_BUG_ON(max_seq > READ_ONCE(lrugen->max_seq));
4120
4121 /*
4122 * If the hardware doesn't automatically set the accessed bit, fallback
4123 * to lru_gen_look_around(), which only clears the accessed bit in a
4124 * handful of PTEs. Spreading the work out over a period of time usually
4125 * is less efficient, but it avoids bursty page faults.
4126 */
Yu Zhao76f7f072022-01-27 19:52:09 -07004127 if (!full_scan && (!arch_has_hw_pte_young() || !get_cap(LRU_GEN_MM_WALK))) {
Yu Zhao5280d762022-01-27 19:23:01 -07004128 success = iterate_mm_list_nowalk(lruvec, max_seq);
4129 goto done;
4130 }
4131
4132 walk = alloc_mm_walk();
4133 if (!walk) {
4134 success = iterate_mm_list_nowalk(lruvec, max_seq);
4135 goto done;
4136 }
4137
4138 walk->lruvec = lruvec;
4139 walk->max_seq = max_seq;
4140 walk->can_swap = can_swap;
4141 walk->full_scan = full_scan;
4142
4143 do {
4144 success = iterate_mm_list(lruvec, walk, &mm);
4145 if (mm)
4146 walk_mm(lruvec, mm, walk);
4147
4148 cond_resched();
4149 } while (mm);
4150
4151 free_mm_walk(walk);
4152done:
4153 if (!success) {
4154 if (!current_is_kswapd() && !sc->priority)
4155 wait_event_killable(lruvec->mm_state.wait,
4156 max_seq < READ_ONCE(lrugen->max_seq));
4157
4158 return max_seq < READ_ONCE(lrugen->max_seq);
4159 }
4160
4161 VM_BUG_ON(max_seq != READ_ONCE(lrugen->max_seq));
4162
4163 inc_max_seq(lruvec);
4164 /* either this sees any waiters or they will see updated max_seq */
4165 if (wq_has_sleeper(&lruvec->mm_state.wait))
4166 wake_up_all(&lruvec->mm_state.wait);
4167
4168 wakeup_flusher_threads(WB_REASON_VMSCAN);
4169
4170 return true;
4171}
4172
Yu Zhaoa1537a62022-01-27 20:32:37 -07004173static long get_nr_evictable(struct lruvec *lruvec, unsigned long max_seq,
4174 unsigned long *min_seq, bool can_swap, bool *need_aging)
4175{
4176 int gen, type, zone;
4177 long old = 0;
4178 long young = 0;
4179 long total = 0;
4180 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4181
4182 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4183 unsigned long seq;
4184
4185 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4186 long size = 0;
4187
4188 gen = lru_gen_from_seq(seq);
4189
4190 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4191 size += READ_ONCE(lrugen->nr_pages[gen][type][zone]);
4192
4193 total += size;
4194 if (seq == max_seq)
4195 young += size;
4196 if (seq + MIN_NR_GENS == max_seq)
4197 old += size;
4198 }
4199 }
4200
4201 /*
4202 * The aging and the eviction is a typical producer-consumer model. The
4203 * aging tries to be lazy to reduce the unnecessary overhead. On the
4204 * other hand, the eviction stalls when the number of generations
4205 * reaches MIN_NR_GENS. So ideally, there should be MIN_NR_GENS+1
4206 * generations, hence the first two if's.
4207 *
4208 * In addition, it's ideal to spread pages out evenly, meaning
4209 * 1/(MIN_NR_GENS+1) of the total number of pages for each generation. A
4210 * reasonable range for this average portion would [1/MIN_NR_GENS,
4211 * 1/(MIN_NR_GENS+2)]. From the consumer's POV, the eviction only cares
4212 * about the lower bound of cold pages, i.e., 1/(MIN_NR_GENS+2), whereas
4213 * from the producer's POV, the aging only cares about the upper bound
4214 * of hot pages, i.e., 1/MIN_NR_GENS.
4215 */
4216 if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS > max_seq)
4217 *need_aging = true;
4218 else if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS < max_seq)
4219 *need_aging = false;
4220 else if (young * MIN_NR_GENS > total)
4221 *need_aging = true;
4222 else if (old * (MIN_NR_GENS + 2) < total)
4223 *need_aging = true;
4224 else
4225 *need_aging = false;
4226
4227 return total > 0 ? total : 0;
4228}
4229
4230static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4231{
4232 bool need_aging;
4233 long nr_to_scan;
4234 int swappiness = get_swappiness(lruvec, sc);
4235 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4236 DEFINE_MAX_SEQ(lruvec);
4237 DEFINE_MIN_SEQ(lruvec);
4238
4239 mem_cgroup_calculate_protection(NULL, memcg);
4240
4241 if (mem_cgroup_below_min(memcg))
4242 return;
4243
4244 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, swappiness, &need_aging);
4245 if (!nr_to_scan)
4246 return;
4247
4248 nr_to_scan >>= sc->priority;
4249
4250 if (!mem_cgroup_online(memcg))
4251 nr_to_scan++;
4252
4253 if (nr_to_scan && need_aging && (!mem_cgroup_below_low(memcg) || sc->memcg_low_reclaim))
Yu Zhao5280d762022-01-27 19:23:01 -07004254 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004255}
4256
4257static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4258{
4259 struct mem_cgroup *memcg;
4260
4261 VM_BUG_ON(!current_is_kswapd());
4262
Yu Zhao4d905e92022-01-27 19:59:54 -07004263 /*
4264 * To reduce the chance of going into the aging path or swapping, which
4265 * can be costly, optimistically skip them unless their corresponding
4266 * flags were cleared in the eviction path. This improves the overall
4267 * performance when multiple memcgs are available.
4268 */
4269 if (!sc->memcgs_need_aging) {
4270 sc->memcgs_need_aging = true;
4271 sc->memcgs_avoid_swapping = !sc->memcgs_need_swapping;
4272 sc->memcgs_need_swapping = true;
4273 return;
4274 }
4275
4276 sc->memcgs_need_swapping = true;
4277 sc->memcgs_avoid_swapping = true;
4278
Yu Zhao5280d762022-01-27 19:23:01 -07004279 current->reclaim_state->mm_walk = &pgdat->mm_walk;
4280
Yu Zhaoa1537a62022-01-27 20:32:37 -07004281 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4282 do {
4283 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4284
4285 age_lruvec(lruvec, sc);
4286
4287 cond_resched();
4288 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao5280d762022-01-27 19:23:01 -07004289
4290 current->reclaim_state->mm_walk = NULL;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004291}
4292
Yu Zhaoafd94c92022-01-27 20:43:22 -07004293/*
4294 * This function exploits spatial locality when shrink_page_list() walks the
4295 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages.
Yu Zhao5280d762022-01-27 19:23:01 -07004296 * If the scan was done cacheline efficiently, it adds the PMD entry pointing
4297 * to the PTE table to the Bloom filter. This process is a feedback loop from
4298 * the eviction to the aging.
Yu Zhaoafd94c92022-01-27 20:43:22 -07004299 */
4300void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4301{
4302 int i;
4303 pte_t *pte;
4304 unsigned long start;
4305 unsigned long end;
4306 unsigned long addr;
4307 struct page *page;
Yu Zhao5280d762022-01-27 19:23:01 -07004308 struct lru_gen_mm_walk *walk;
4309 int young = 0;
Yu Zhaoafd94c92022-01-27 20:43:22 -07004310 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4311 struct mem_cgroup *memcg = page_memcg(pvmw->page);
4312 struct pglist_data *pgdat = page_pgdat(pvmw->page);
4313 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4314 DEFINE_MAX_SEQ(lruvec);
4315 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4316
4317 lockdep_assert_held(pvmw->ptl);
4318 VM_BUG_ON_PAGE(PageLRU(pvmw->page), pvmw->page);
4319
4320 if (spin_is_contended(pvmw->ptl))
4321 return;
4322
4323 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4324 end = pmd_addr_end(pvmw->address, pvmw->vma->vm_end);
4325
4326 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4327 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4328 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4329 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4330 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4331 else {
4332 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4333 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4334 }
4335 }
4336
4337 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4338
4339 rcu_read_lock();
4340 arch_enter_lazy_mmu_mode();
4341
4342 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4343 unsigned long pfn = pte_pfn(pte[i]);
4344
4345 VM_BUG_ON(addr < pvmw->vma->vm_start || addr >= pvmw->vma->vm_end);
4346
4347 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
4348 continue;
4349
4350 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
4351 continue;
4352
4353 if (!pte_young(pte[i]))
4354 continue;
4355
4356 VM_BUG_ON(!pfn_valid(pfn));
4357 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
4358 continue;
4359
4360 page = compound_head(pfn_to_page(pfn));
4361 if (page_to_nid(page) != pgdat->node_id)
4362 continue;
4363
4364 if (page_memcg_rcu(page) != memcg)
4365 continue;
4366
4367 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4368 continue;
4369
Yu Zhao5280d762022-01-27 19:23:01 -07004370 young++;
4371
Yu Zhaoafd94c92022-01-27 20:43:22 -07004372 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4373 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
4374 set_page_dirty(page);
4375
4376 old_gen = page_lru_gen(page);
4377 if (old_gen < 0)
4378 SetPageReferenced(page);
4379 else if (old_gen != new_gen)
4380 __set_bit(i, bitmap);
4381 }
4382
4383 arch_leave_lazy_mmu_mode();
4384 rcu_read_unlock();
4385
Yu Zhao5280d762022-01-27 19:23:01 -07004386 /* feedback from rmap walkers to page table walkers */
4387 if (suitable_to_scan(i, young))
4388 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4389
4390 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4391
4392 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhaoafd94c92022-01-27 20:43:22 -07004393 for_each_set_bit(i, bitmap, MIN_LRU_BATCH)
4394 activate_page(pte_page(pte[i]));
4395 return;
4396 }
4397
4398 /* page_update_gen() requires stable page_memcg() */
4399 if (!mem_cgroup_trylock_pages(memcg))
4400 return;
4401
Yu Zhao5280d762022-01-27 19:23:01 -07004402 if (!walk) {
4403 spin_lock_irq(&lruvec->lru_lock);
4404 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4405 }
Yu Zhaoafd94c92022-01-27 20:43:22 -07004406
4407 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4408 page = compound_head(pte_page(pte[i]));
4409 if (page_memcg_rcu(page) != memcg)
4410 continue;
4411
4412 old_gen = page_update_gen(page, new_gen);
4413 if (old_gen < 0 || old_gen == new_gen)
4414 continue;
4415
Yu Zhao5280d762022-01-27 19:23:01 -07004416 if (walk)
4417 update_batch_size(walk, page, old_gen, new_gen);
4418 else
4419 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhaoafd94c92022-01-27 20:43:22 -07004420 }
4421
Yu Zhao5280d762022-01-27 19:23:01 -07004422 if (!walk)
4423 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhaoafd94c92022-01-27 20:43:22 -07004424
4425 mem_cgroup_unlock_pages();
4426}
4427
Yu Zhaoa1537a62022-01-27 20:32:37 -07004428/******************************************************************************
4429 * the eviction
4430 ******************************************************************************/
4431
4432static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4433{
4434 bool success;
4435 int gen = page_lru_gen(page);
4436 int type = page_is_file_lru(page);
4437 int zone = page_zonenum(page);
4438 int tier = page_lru_tier(page);
4439 int delta = thp_nr_pages(page);
4440 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4441
4442 VM_BUG_ON_PAGE(gen >= MAX_NR_GENS, page);
4443
4444 if (!page_evictable(page)) {
4445 success = lru_gen_del_page(lruvec, page, true);
4446 VM_BUG_ON_PAGE(!success, page);
4447 SetPageUnevictable(page);
4448 add_page_to_lru_list(page, lruvec);
4449 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4450 return true;
4451 }
4452
4453 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4454 success = lru_gen_del_page(lruvec, page, true);
4455 VM_BUG_ON_PAGE(!success, page);
4456 SetPageSwapBacked(page);
4457 add_page_to_lru_list_tail(page, lruvec);
4458 return true;
4459 }
4460
Yu Zhaoafd94c92022-01-27 20:43:22 -07004461 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4462 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4463 return true;
4464 }
4465
Yu Zhaoa1537a62022-01-27 20:32:37 -07004466 if (tier > tier_idx) {
4467 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4468
4469 gen = page_inc_gen(lruvec, page, false);
4470 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4471
4472 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4473 lrugen->protected[hist][type][tier - 1] + delta);
4474 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4475 return true;
4476 }
4477
4478 if (PageLocked(page) || PageWriteback(page) ||
4479 (type == LRU_GEN_FILE && PageDirty(page))) {
4480 gen = page_inc_gen(lruvec, page, true);
4481 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4482 return true;
4483 }
4484
4485 return false;
4486}
4487
4488static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4489{
4490 bool success;
4491
4492 if (!sc->may_unmap && page_mapped(page))
4493 return false;
4494
4495 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4496 (PageDirty(page) || (PageAnon(page) && !PageSwapCache(page))))
4497 return false;
4498
4499 if (!get_page_unless_zero(page))
4500 return false;
4501
4502 if (!TestClearPageLRU(page)) {
4503 put_page(page);
4504 return false;
4505 }
4506
4507 success = lru_gen_del_page(lruvec, page, true);
4508 VM_BUG_ON_PAGE(!success, page);
4509
4510 return true;
4511}
4512
4513static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4514 int type, int tier, struct list_head *list)
4515{
4516 int gen, zone;
4517 enum vm_event_item item;
4518 int sorted = 0;
4519 int scanned = 0;
4520 int isolated = 0;
4521 int remaining = MAX_LRU_BATCH;
4522 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4523 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4524
4525 VM_BUG_ON(!list_empty(list));
4526
4527 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4528 return 0;
4529
4530 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4531
4532 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4533 LIST_HEAD(moved);
4534 int skipped = 0;
4535 struct list_head *head = &lrugen->lists[gen][type][zone];
4536
4537 while (!list_empty(head)) {
4538 struct page *page = lru_to_page(head);
4539 int delta = thp_nr_pages(page);
4540
4541 VM_BUG_ON_PAGE(PageTail(page), page);
4542 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4543 VM_BUG_ON_PAGE(PageActive(page), page);
4544 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4545 VM_BUG_ON_PAGE(page_zonenum(page) != zone, page);
4546
4547 prefetchw_prev_lru_page(page, head, flags);
4548
4549 scanned += delta;
4550
4551 if (sort_page(lruvec, page, tier))
4552 sorted += delta;
4553 else if (isolate_page(lruvec, page, sc)) {
4554 list_add(&page->lru, list);
4555 isolated += delta;
4556 } else {
4557 list_move(&page->lru, &moved);
4558 skipped += delta;
4559 }
4560
4561 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4562 break;
4563 }
4564
4565 if (skipped) {
4566 list_splice(&moved, head);
4567 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4568 }
4569
4570 if (!remaining || isolated >= MIN_LRU_BATCH)
4571 break;
4572 }
4573
4574 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4575 if (!cgroup_reclaim(sc)) {
4576 __count_vm_events(item, isolated);
4577 __count_vm_events(PGREFILL, sorted);
4578 }
4579 __count_memcg_events(memcg, item, isolated);
4580 __count_memcg_events(memcg, PGREFILL, sorted);
4581 __count_vm_events(PGSCAN_ANON + type, isolated);
4582
4583 /*
4584 * There might not be eligible pages due to reclaim_idx, may_unmap and
4585 * may_writepage. Check the remaining to prevent livelock if there is no
4586 * progress.
4587 */
4588 return isolated || !remaining ? scanned : 0;
4589}
4590
4591static int get_tier_idx(struct lruvec *lruvec, int type)
4592{
4593 int tier;
4594 struct ctrl_pos sp, pv;
4595
4596 /*
4597 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4598 * This value is chosen because any other tier would have at least twice
4599 * as many refaults as the first tier.
4600 */
4601 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4602 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4603 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4604 if (!positive_ctrl_err(&sp, &pv))
4605 break;
4606 }
4607
4608 return tier - 1;
4609}
4610
4611static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4612{
4613 int type, tier;
4614 struct ctrl_pos sp, pv;
4615 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4616
4617 /*
4618 * Compare the first tier of anon with that of file to determine which
4619 * type to scan. Also need to compare other tiers of the selected type
4620 * with the first tier of the other type to determine the last tier (of
4621 * the selected type) to evict.
4622 */
4623 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4624 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4625 type = positive_ctrl_err(&sp, &pv);
4626
4627 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4628 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4629 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4630 if (!positive_ctrl_err(&sp, &pv))
4631 break;
4632 }
4633
4634 *tier_idx = tier - 1;
4635
4636 return type;
4637}
4638
4639static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4640 int *type_scanned, struct list_head *list)
4641{
4642 int i;
4643 int type;
4644 int scanned;
4645 int tier = -1;
4646 DEFINE_MIN_SEQ(lruvec);
4647
4648 VM_BUG_ON(!seq_is_valid(lruvec));
4649
4650 /*
4651 * Try to make the obvious choice first. When anon and file are both
4652 * available from the same generation, interpret swappiness 1 as file
4653 * first and 200 as anon first.
4654 */
4655 if (!swappiness)
4656 type = LRU_GEN_FILE;
4657 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4658 type = LRU_GEN_ANON;
4659 else if (swappiness == 1)
4660 type = LRU_GEN_FILE;
4661 else if (swappiness == 200)
4662 type = LRU_GEN_ANON;
4663 else
4664 type = get_type_to_scan(lruvec, swappiness, &tier);
4665
4666 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4667 if (tier < 0)
4668 tier = get_tier_idx(lruvec, type);
4669
4670 scanned = scan_pages(lruvec, sc, type, tier, list);
4671 if (scanned)
4672 break;
4673
4674 type = !type;
4675 tier = -1;
4676 }
4677
4678 *type_scanned = type;
4679
4680 return scanned;
4681}
4682
Yu Zhao4d905e92022-01-27 19:59:54 -07004683static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4684 bool *swapped)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004685{
4686 int type;
4687 int scanned;
4688 int reclaimed;
4689 LIST_HEAD(list);
4690 struct page *page;
4691 enum vm_event_item item;
4692 struct reclaim_stat stat;
Yu Zhao5280d762022-01-27 19:23:01 -07004693 struct lru_gen_mm_walk *walk;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004694 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4695 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4696
4697 spin_lock_irq(&lruvec->lru_lock);
4698
4699 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4700
4701 if (try_to_inc_min_seq(lruvec, swappiness))
4702 scanned++;
4703
4704 if (get_nr_gens(lruvec, LRU_GEN_FILE) == MIN_NR_GENS)
4705 scanned = 0;
4706
4707 spin_unlock_irq(&lruvec->lru_lock);
4708
4709 if (list_empty(&list))
4710 return scanned;
4711
4712 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4713
4714 /*
4715 * To avoid livelock, don't add rejected pages back to the same lists
4716 * they were isolated from. See lru_gen_add_page().
4717 */
4718 list_for_each_entry(page, &list, lru) {
4719 ClearPageReferenced(page);
4720 ClearPageWorkingset(page);
4721
4722 if (PageReclaim(page) && (PageDirty(page) || PageWriteback(page)))
4723 ClearPageActive(page);
4724 else if (page_is_file_lru(page) || PageSwapCache(page))
4725 SetPageActive(page);
4726 }
4727
4728 spin_lock_irq(&lruvec->lru_lock);
4729
4730 move_pages_to_lru(lruvec, &list);
4731
Yu Zhao5280d762022-01-27 19:23:01 -07004732 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4733 if (walk && walk->batched)
4734 reset_batch_size(lruvec, walk);
4735
Yu Zhaoa1537a62022-01-27 20:32:37 -07004736 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4737 if (!cgroup_reclaim(sc))
4738 __count_vm_events(item, reclaimed);
4739 __count_memcg_events(memcg, item, reclaimed);
4740 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4741
4742 spin_unlock_irq(&lruvec->lru_lock);
4743
4744 mem_cgroup_uncharge_list(&list);
4745 free_unref_page_list(&list);
4746
4747 sc->nr_reclaimed += reclaimed;
4748
Yu Zhao4d905e92022-01-27 19:59:54 -07004749 if (type == LRU_GEN_ANON && swapped)
4750 *swapped = true;
4751
Yu Zhaoa1537a62022-01-27 20:32:37 -07004752 return scanned;
4753}
4754
4755static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
4756{
4757 bool need_aging;
4758 long nr_to_scan;
4759 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4760 DEFINE_MAX_SEQ(lruvec);
4761 DEFINE_MIN_SEQ(lruvec);
4762
4763 if (mem_cgroup_below_min(memcg) ||
4764 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4765 return 0;
4766
4767 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, can_swap, &need_aging);
4768 if (!nr_to_scan)
4769 return 0;
4770
4771 /* reset the priority if the target has been met */
4772 nr_to_scan >>= sc->nr_reclaimed < sc->nr_to_reclaim ? sc->priority : DEF_PRIORITY;
4773
4774 if (!mem_cgroup_online(memcg))
4775 nr_to_scan++;
4776
4777 if (!nr_to_scan)
4778 return 0;
4779
Yu Zhao4d905e92022-01-27 19:59:54 -07004780 if (!need_aging) {
4781 sc->memcgs_need_aging = false;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004782 return nr_to_scan;
Yu Zhao4d905e92022-01-27 19:59:54 -07004783 }
Yu Zhaoa1537a62022-01-27 20:32:37 -07004784
4785 /* leave the work to lru_gen_age_node() */
4786 if (current_is_kswapd())
4787 return 0;
4788
4789 /* try other memcgs before going to the aging path */
4790 if (!cgroup_reclaim(sc) && !sc->force_deactivate) {
4791 sc->skipped_deactivate = true;
4792 return 0;
4793 }
4794
Yu Zhao5280d762022-01-27 19:23:01 -07004795 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
4796 return nr_to_scan;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004797
Yu Zhao5280d762022-01-27 19:23:01 -07004798 return min_seq[LRU_GEN_FILE] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004799}
4800
4801static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4802{
4803 struct blk_plug plug;
4804 long scanned = 0;
Yu Zhao4d905e92022-01-27 19:59:54 -07004805 bool swapped = false;
4806 unsigned long reclaimed = sc->nr_reclaimed;
Yu Zhao5280d762022-01-27 19:23:01 -07004807 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004808
4809 lru_add_drain();
4810
4811 blk_start_plug(&plug);
4812
Yu Zhao5280d762022-01-27 19:23:01 -07004813 if (current_is_kswapd())
4814 current->reclaim_state->mm_walk = &pgdat->mm_walk;
4815
Yu Zhaoa1537a62022-01-27 20:32:37 -07004816 while (true) {
4817 int delta;
4818 int swappiness;
4819 long nr_to_scan;
4820
4821 if (sc->may_swap)
4822 swappiness = get_swappiness(lruvec, sc);
4823 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4824 swappiness = 1;
4825 else
4826 swappiness = 0;
4827
4828 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
4829 if (!nr_to_scan)
4830 break;
4831
Yu Zhao4d905e92022-01-27 19:59:54 -07004832 delta = evict_pages(lruvec, sc, swappiness, &swapped);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004833 if (!delta)
4834 break;
4835
Yu Zhao4d905e92022-01-27 19:59:54 -07004836 if (sc->memcgs_avoid_swapping && swappiness < 200 && swapped)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004837 break;
4838
Yu Zhao4d905e92022-01-27 19:59:54 -07004839 scanned += delta;
4840 if (scanned >= nr_to_scan) {
4841 if (!swapped && sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH)
4842 sc->memcgs_need_swapping = false;
4843 break;
4844 }
4845
Yu Zhaoa1537a62022-01-27 20:32:37 -07004846 cond_resched();
4847 }
4848
Yu Zhao5280d762022-01-27 19:23:01 -07004849 if (current_is_kswapd())
4850 current->reclaim_state->mm_walk = NULL;
4851
Yu Zhaoa1537a62022-01-27 20:32:37 -07004852 blk_finish_plug(&plug);
4853}
4854
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004855/******************************************************************************
Yu Zhao76f7f072022-01-27 19:52:09 -07004856 * state change
4857 ******************************************************************************/
4858
4859static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
4860{
4861 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4862
4863 if (lrugen->enabled) {
4864 enum lru_list lru;
4865
4866 for_each_evictable_lru(lru) {
4867 if (!list_empty(&lruvec->lists[lru]))
4868 return false;
4869 }
4870 } else {
4871 int gen, type, zone;
4872
4873 for_each_gen_type_zone(gen, type, zone) {
4874 if (!list_empty(&lrugen->lists[gen][type][zone]))
4875 return false;
4876
4877 /* unlikely but not a bug when reset_batch_size() is pending */
4878 VM_WARN_ON(lrugen->nr_pages[gen][type][zone]);
4879 }
4880 }
4881
4882 return true;
4883}
4884
4885static bool fill_evictable(struct lruvec *lruvec)
4886{
4887 enum lru_list lru;
4888 int remaining = MAX_LRU_BATCH;
4889
4890 for_each_evictable_lru(lru) {
4891 int type = is_file_lru(lru);
4892 bool active = is_active_lru(lru);
4893 struct list_head *head = &lruvec->lists[lru];
4894
4895 while (!list_empty(head)) {
4896 bool success;
4897 struct page *page = lru_to_page(head);
4898
4899 VM_BUG_ON_PAGE(PageTail(page), page);
4900 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4901 VM_BUG_ON_PAGE(PageActive(page) != active, page);
4902 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4903 VM_BUG_ON_PAGE(page_lru_gen(page) < MAX_NR_GENS, page);
4904
4905 prefetchw_prev_lru_page(page, head, flags);
4906
4907 del_page_from_lru_list(page, lruvec);
4908 success = lru_gen_add_page(lruvec, page, false);
4909 VM_BUG_ON(!success);
4910
4911 if (!--remaining)
4912 return false;
4913 }
4914 }
4915
4916 return true;
4917}
4918
4919static bool drain_evictable(struct lruvec *lruvec)
4920{
4921 int gen, type, zone;
4922 int remaining = MAX_LRU_BATCH;
4923
4924 for_each_gen_type_zone(gen, type, zone) {
4925 struct list_head *head = &lruvec->lrugen.lists[gen][type][zone];
4926
4927 while (!list_empty(head)) {
4928 bool success;
4929 struct page *page = lru_to_page(head);
4930
4931 VM_BUG_ON_PAGE(PageTail(page), page);
4932 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4933 VM_BUG_ON_PAGE(PageActive(page), page);
4934 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4935 VM_BUG_ON_PAGE(page_zonenum(page) != zone, page);
4936
4937 prefetchw_prev_lru_page(page, head, flags);
4938
4939 success = lru_gen_del_page(lruvec, page, false);
4940 VM_BUG_ON(!success);
4941 add_page_to_lru_list(page, lruvec);
4942
4943 if (!--remaining)
4944 return false;
4945 }
4946 }
4947
4948 return true;
4949}
4950
4951static void lru_gen_change_state(bool enable)
4952{
4953 static DEFINE_MUTEX(state_mutex);
4954
4955 struct mem_cgroup *memcg;
4956
4957 cgroup_lock();
4958 cpus_read_lock();
4959 get_online_mems();
4960 mutex_lock(&state_mutex);
4961
4962 if (enable == lru_gen_enabled())
4963 goto unlock;
4964
4965 if (enable)
4966 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
4967 else
4968 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
4969
4970 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4971 do {
4972 int nid;
4973
4974 for_each_node(nid) {
4975 struct lruvec *lruvec = get_lruvec(memcg, nid);
4976
4977 if (!lruvec)
4978 continue;
4979
4980 spin_lock_irq(&lruvec->lru_lock);
4981
4982 VM_BUG_ON(!seq_is_valid(lruvec));
4983 VM_BUG_ON(!state_is_valid(lruvec));
4984
4985 lruvec->lrugen.enabled = enable;
4986
4987 while (!(enable ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
4988 spin_unlock_irq(&lruvec->lru_lock);
4989 cond_resched();
4990 spin_lock_irq(&lruvec->lru_lock);
4991 }
4992
4993 spin_unlock_irq(&lruvec->lru_lock);
4994 }
4995
4996 cond_resched();
4997 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
4998unlock:
4999 mutex_unlock(&state_mutex);
5000 put_online_mems();
5001 cpus_read_unlock();
5002 cgroup_unlock();
5003}
5004
5005/******************************************************************************
5006 * sysfs interface
5007 ******************************************************************************/
5008
5009static ssize_t show_enable(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5010{
5011 unsigned int caps = 0;
5012
5013 if (get_cap(LRU_GEN_CORE))
5014 caps |= BIT(LRU_GEN_CORE);
5015
5016 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5017 caps |= BIT(LRU_GEN_MM_WALK);
5018
5019 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
5020 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5021
5022 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5023}
5024
5025static ssize_t store_enable(struct kobject *kobj, struct kobj_attribute *attr,
5026 const char *buf, size_t len)
5027{
5028 int i;
5029 unsigned int caps;
5030
5031 if (tolower(*buf) == 'n')
5032 caps = 0;
5033 else if (tolower(*buf) == 'y')
5034 caps = -1;
5035 else if (kstrtouint(buf, 0, &caps))
5036 return -EINVAL;
5037
5038 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5039 bool enable = caps & BIT(i);
5040
5041 if (i == LRU_GEN_CORE)
5042 lru_gen_change_state(enable);
5043 else if (enable)
5044 static_branch_enable(&lru_gen_caps[i]);
5045 else
5046 static_branch_disable(&lru_gen_caps[i]);
5047 }
5048
5049 return len;
5050}
5051
5052static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5053 enabled, 0644, show_enable, store_enable
5054);
5055
5056static struct attribute *lru_gen_attrs[] = {
5057 &lru_gen_enabled_attr.attr,
5058 NULL
5059};
5060
5061static struct attribute_group lru_gen_attr_group = {
5062 .name = "lru_gen",
5063 .attrs = lru_gen_attrs,
5064};
5065
5066/******************************************************************************
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005067 * initialization
5068 ******************************************************************************/
5069
5070void lru_gen_init_lruvec(struct lruvec *lruvec)
5071{
5072 int gen, type, zone;
5073 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5074
5075 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhao76f7f072022-01-27 19:52:09 -07005076 lrugen->enabled = lru_gen_enabled();
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005077
5078 for_each_gen_type_zone(gen, type, zone)
5079 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao5280d762022-01-27 19:23:01 -07005080
5081 lruvec->mm_state.seq = MIN_NR_GENS;
5082 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005083}
5084
5085#ifdef CONFIG_MEMCG
5086void lru_gen_init_memcg(struct mem_cgroup *memcg)
5087{
Yu Zhao5280d762022-01-27 19:23:01 -07005088 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5089 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005090}
5091
5092void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5093{
Yu Zhao5280d762022-01-27 19:23:01 -07005094 int i;
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005095 int nid;
5096
5097 for_each_node(nid) {
5098 struct lruvec *lruvec = get_lruvec(memcg, nid);
5099
5100 VM_BUG_ON(memchr_inv(lruvec->lrugen.nr_pages, 0,
5101 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao5280d762022-01-27 19:23:01 -07005102
5103 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5104 bitmap_free(lruvec->mm_state.filters[i]);
5105 lruvec->mm_state.filters[i] = NULL;
5106 }
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005107 }
5108}
5109#endif
5110
5111static int __init init_lru_gen(void)
5112{
5113 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5114 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
Yu Zhao5280d762022-01-27 19:23:01 -07005115 BUILD_BUG_ON(sizeof(MM_STAT_CODES) != NR_MM_STATS + 1);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005116
Yu Zhao76f7f072022-01-27 19:52:09 -07005117 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5118 pr_err("lru_gen: failed to create sysfs group\n");
5119
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005120 return 0;
5121};
5122late_initcall(init_lru_gen);
5123
Yu Zhaoa1537a62022-01-27 20:32:37 -07005124#else
5125
5126static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5127{
5128}
5129
5130static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5131{
5132}
5133
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005134#endif /* CONFIG_LRU_GEN */
5135
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005136static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005137{
5138 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005139 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005140 unsigned long nr_to_scan;
5141 enum lru_list lru;
5142 unsigned long nr_reclaimed = 0;
5143 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5144 struct blk_plug plug;
Mel Gorman1a501902014-06-04 16:10:49 -07005145 bool scan_adjusted;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005146
Yu Zhaoa1537a62022-01-27 20:32:37 -07005147 if (lru_gen_enabled()) {
5148 lru_gen_shrink_lruvec(lruvec, sc);
5149 return;
5150 }
5151
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005152 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005153
Mel Gormane82e0562013-07-03 15:01:44 -07005154 /* Record the original scan target for proportional adjustments later */
5155 memcpy(targets, nr, sizeof(nr));
5156
Mel Gorman1a501902014-06-04 16:10:49 -07005157 /*
5158 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5159 * event that can occur when there is little memory pressure e.g.
5160 * multiple streaming readers/writers. Hence, we do not abort scanning
5161 * when the requested number of pages are reclaimed when scanning at
5162 * DEF_PRIORITY on the assumption that the fact we are direct
5163 * reclaiming implies that kswapd is not keeping up and it is best to
5164 * do a batch of work at once. For memcg reclaim one check is made to
5165 * abort proportional reclaim if either the file or anon lru has already
5166 * dropped to zero at the first pass.
5167 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005168 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
Mel Gorman1a501902014-06-04 16:10:49 -07005169 sc->priority == DEF_PRIORITY);
5170
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005171 blk_start_plug(&plug);
5172 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5173 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005174 unsigned long nr_anon, nr_file, percentage;
5175 unsigned long nr_scanned;
5176
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005177 for_each_evictable_lru(lru) {
5178 if (nr[lru]) {
5179 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5180 nr[lru] -= nr_to_scan;
5181
5182 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005183 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005184 }
5185 }
Mel Gormane82e0562013-07-03 15:01:44 -07005186
Michal Hockobd041732016-12-02 17:26:48 -08005187 cond_resched();
5188
Mel Gormane82e0562013-07-03 15:01:44 -07005189 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
5190 continue;
5191
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005192 /*
Mel Gormane82e0562013-07-03 15:01:44 -07005193 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07005194 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07005195 * proportionally what was requested by get_scan_count(). We
5196 * stop reclaiming one LRU and reduce the amount scanning
5197 * proportional to the original scan target.
5198 */
5199 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5200 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5201
Mel Gorman1a501902014-06-04 16:10:49 -07005202 /*
5203 * It's just vindictive to attack the larger once the smaller
5204 * has gone to zero. And given the way we stop scanning the
5205 * smaller below, this makes sure that we only make one nudge
5206 * towards proportionality once we've got nr_to_reclaim.
5207 */
5208 if (!nr_file || !nr_anon)
5209 break;
5210
Mel Gormane82e0562013-07-03 15:01:44 -07005211 if (nr_file > nr_anon) {
5212 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5213 targets[LRU_ACTIVE_ANON] + 1;
5214 lru = LRU_BASE;
5215 percentage = nr_anon * 100 / scan_target;
5216 } else {
5217 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5218 targets[LRU_ACTIVE_FILE] + 1;
5219 lru = LRU_FILE;
5220 percentage = nr_file * 100 / scan_target;
5221 }
5222
5223 /* Stop scanning the smaller of the LRU */
5224 nr[lru] = 0;
5225 nr[lru + LRU_ACTIVE] = 0;
5226
5227 /*
5228 * Recalculate the other LRU scan count based on its original
5229 * scan target and the percentage scanning already complete
5230 */
5231 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5232 nr_scanned = targets[lru] - nr[lru];
5233 nr[lru] = targets[lru] * (100 - percentage) / 100;
5234 nr[lru] -= min(nr[lru], nr_scanned);
5235
5236 lru += LRU_ACTIVE;
5237 nr_scanned = targets[lru] - nr[lru];
5238 nr[lru] = targets[lru] * (100 - percentage) / 100;
5239 nr[lru] -= min(nr[lru], nr_scanned);
5240
5241 scan_adjusted = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005242 }
5243 blk_finish_plug(&plug);
5244 sc->nr_reclaimed += nr_reclaimed;
5245
5246 /*
5247 * Even if we did not try to evict anon pages at all, we want to
5248 * rebalance the anon lru active/inactive ratio.
5249 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005250 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5251 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005252 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5253 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005254}
5255
Mel Gorman23b9da52012-05-29 15:06:20 -07005256/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005257static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005258{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005259 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005260 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005261 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005262 return true;
5263
5264 return false;
5265}
5266
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005267/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005268 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5269 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5270 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005271 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005272 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005273 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005274static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005275 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005276 struct scan_control *sc)
5277{
5278 unsigned long pages_for_compaction;
5279 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005280 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005281
5282 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005283 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005284 return false;
5285
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005286 /*
5287 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5288 * number of pages that were scanned. This will return to the caller
5289 * with the risk reclaim/compaction and the resulting allocation attempt
5290 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5291 * allocations through requiring that the full LRU list has been scanned
5292 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5293 * scan, but that approximation was wrong, and there were corner cases
5294 * where always a non-zero amount of pages were scanned.
5295 */
5296 if (!nr_reclaimed)
5297 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005298
Mel Gorman3e7d3442011-01-13 15:45:56 -08005299 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005300 for (z = 0; z <= sc->reclaim_idx; z++) {
5301 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005302 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005303 continue;
5304
5305 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005306 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005307 case COMPACT_CONTINUE:
5308 return false;
5309 default:
5310 /* check next zone */
5311 ;
5312 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005313 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005314
5315 /*
5316 * If we have not reclaimed enough pages for compaction and the
5317 * inactive lists are large enough, continue reclaiming
5318 */
5319 pages_for_compaction = compact_gap(sc->order);
5320 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005321 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005322 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5323
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005324 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005325}
5326
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005327static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005328{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005329 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005330 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005331
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005332 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005333 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005334 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005335 unsigned long reclaimed;
5336 unsigned long scanned;
Johannes Weiner56600482012-01-12 17:17:59 -08005337
Xunlei Pange3336ca2020-09-04 16:35:27 -07005338 /*
5339 * This loop can become CPU-bound when target memcgs
5340 * aren't eligible for reclaim - either because they
5341 * don't have any reclaimable pages, or because their
5342 * memory is explicitly protected. Avoid soft lockups.
5343 */
5344 cond_resched();
5345
Chris Down45c7f7e2020-08-06 23:22:05 -07005346 mem_cgroup_calculate_protection(target_memcg, memcg);
5347
5348 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005349 /*
5350 * Hard protection.
5351 * If there is no reclaimable memory, OOM.
5352 */
5353 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005354 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005355 /*
5356 * Soft protection.
5357 * Respect the protection only as long as
5358 * there is an unprotected supply
5359 * of reclaimable memory from other cgroups.
5360 */
5361 if (!sc->memcg_low_reclaim) {
5362 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005363 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005364 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005365 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005366 }
5367
Johannes Weinerd2af3392019-11-30 17:55:43 -08005368 reclaimed = sc->nr_reclaimed;
5369 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005370
5371 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005372
Johannes Weinerd2af3392019-11-30 17:55:43 -08005373 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5374 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005375
Johannes Weinerd2af3392019-11-30 17:55:43 -08005376 /* Record the group's reclaim efficiency */
5377 vmpressure(sc->gfp_mask, memcg, false,
5378 sc->nr_scanned - scanned,
5379 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005380
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005381 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5382}
5383
Liu Song6c9e09072020-01-30 22:14:08 -08005384static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005385{
5386 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005387 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005388 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005389 bool reclaimable = false;
5390
Johannes Weiner1b051172019-11-30 17:55:52 -08005391 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5392
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005393again:
5394 memset(&sc->nr, 0, sizeof(sc->nr));
5395
5396 nr_reclaimed = sc->nr_reclaimed;
5397 nr_scanned = sc->nr_scanned;
5398
Yu Zhao3eb07702020-09-27 20:49:08 -06005399 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005400
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005401 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005402
Johannes Weinerd2af3392019-11-30 17:55:43 -08005403 if (reclaim_state) {
5404 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5405 reclaim_state->reclaimed_slab = 0;
5406 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005407
Johannes Weinerd2af3392019-11-30 17:55:43 -08005408 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005409 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005410 sc->nr_scanned - nr_scanned,
5411 sc->nr_reclaimed - nr_reclaimed);
5412
5413 if (sc->nr_reclaimed - nr_reclaimed)
5414 reclaimable = true;
5415
5416 if (current_is_kswapd()) {
5417 /*
5418 * If reclaim is isolating dirty pages under writeback,
5419 * it implies that the long-lived page allocation rate
5420 * is exceeding the page laundering rate. Either the
5421 * global limits are not being effective at throttling
5422 * processes due to the page distribution throughout
5423 * zones or there is heavy usage of a slow backing
5424 * device. The only option is to throttle from reclaim
5425 * context which is not ideal as there is no guarantee
5426 * the dirtying process is throttled in the same way
5427 * balance_dirty_pages() manages.
5428 *
5429 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5430 * count the number of pages under pages flagged for
5431 * immediate reclaim and stall if any are encountered
5432 * in the nr_immediate check below.
5433 */
5434 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5435 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005436
Johannes Weinerd2af3392019-11-30 17:55:43 -08005437 /* Allow kswapd to start writing pages during reclaim.*/
5438 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5439 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005440
5441 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005442 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005443 * reclaim and under writeback (nr_immediate), it
5444 * implies that pages are cycling through the LRU
5445 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005446 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005447 if (sc->nr.immediate)
5448 congestion_wait(BLK_RW_ASYNC, HZ/10);
5449 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005450
Johannes Weinerd2af3392019-11-30 17:55:43 -08005451 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005452 * Tag a node/memcg as congested if all the dirty pages
5453 * scanned were backed by a congested BDI and
5454 * wait_iff_congested will stall.
5455 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005456 * Legacy memcg will stall in page writeback so avoid forcibly
5457 * stalling in wait_iff_congested().
5458 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005459 if ((current_is_kswapd() ||
5460 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005461 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005462 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005463
5464 /*
5465 * Stall direct reclaim for IO completions if underlying BDIs
5466 * and node is congested. Allow kswapd to continue until it
5467 * starts encountering unqueued dirty pages or cycling through
5468 * the LRU too quickly.
5469 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005470 if (!current_is_kswapd() && current_may_throttle() &&
5471 !sc->hibernation_mode &&
5472 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005473 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5474
5475 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5476 sc))
5477 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005478
Johannes Weinerc73322d2017-05-03 14:51:51 -07005479 /*
5480 * Kswapd gives up on balancing particular nodes after too
5481 * many failures to reclaim anything from them and goes to
5482 * sleep. On reclaim progress, reset the failure counter. A
5483 * successful direct reclaim run will revive a dormant kswapd.
5484 */
5485 if (reclaimable)
5486 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005487}
5488
Vlastimil Babka53853e22014-10-09 15:27:02 -07005489/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005490 * Returns true if compaction should go ahead for a costly-order request, or
5491 * the allocation would already succeed without compaction. Return false if we
5492 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07005493 */
Mel Gorman4f588332016-07-28 15:46:38 -07005494static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005495{
Mel Gorman31483b62016-07-28 15:45:46 -07005496 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005497 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005498
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005499 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
5500 if (suitable == COMPACT_SUCCESS)
5501 /* Allocation should succeed already. Don't reclaim. */
5502 return true;
5503 if (suitable == COMPACT_SKIPPED)
5504 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005505 return false;
5506
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005507 /*
5508 * Compaction is already possible, but it takes time to run and there
5509 * are potentially other callers using the pages just freed. So proceed
5510 * with reclaim to make a buffer of free pages available to give
5511 * compaction a reasonable chance of completing and allocating the page.
5512 * Note that we won't actually reclaim the whole buffer in one attempt
5513 * as the target watermark in should_continue_reclaim() is lower. But if
5514 * we are already above the high+gap watermark, don't reclaim at all.
5515 */
5516 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
5517
5518 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005519}
5520
Linus Torvalds1da177e2005-04-16 15:20:36 -07005521/*
5522 * This is the direct reclaim path, for page-allocating processes. We only
5523 * try to reclaim pages from zones which will satisfy the caller's allocation
5524 * request.
5525 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07005526 * If a zone is deemed to be full of pinned pages then just give it a light
5527 * scan then give up on it.
5528 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07005529static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005530{
Mel Gormandd1a2392008-04-28 02:12:17 -07005531 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07005532 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07005533 unsigned long nr_soft_reclaimed;
5534 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07005535 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07005536 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005537
Mel Gormancc715d92012-03-21 16:34:00 -07005538 /*
5539 * If the number of buffer_heads in the machine exceeds the maximum
5540 * allowed level, force direct reclaim to scan the highmem zone as
5541 * highmem pages could be pinning lowmem pages storing buffer_heads
5542 */
Weijie Yang619d0d762014-04-07 15:36:59 -07005543 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07005544 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07005545 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07005546 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07005547 }
Mel Gormancc715d92012-03-21 16:34:00 -07005548
Mel Gormand4debc62010-08-09 17:19:29 -07005549 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07005550 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07005551 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005552 * Take care memory controller reclaiming has small influence
5553 * to global LRU.
5554 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005555 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04005556 if (!cpuset_zone_allowed(zone,
5557 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005558 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005559
Johannes Weiner0b064962014-08-06 16:06:12 -07005560 /*
5561 * If we already have plenty of memory free for
5562 * compaction in this zone, don't free any more.
5563 * Even though compaction is invoked for any
5564 * non-zero order, only frequent costly order
5565 * reclamation is disruptive enough to become a
5566 * noticeable problem, like transparent huge
5567 * page allocations.
5568 */
5569 if (IS_ENABLED(CONFIG_COMPACTION) &&
5570 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07005571 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07005572 sc->compaction_ready = true;
5573 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07005574 }
Johannes Weiner0b064962014-08-06 16:06:12 -07005575
Andrew Morton0608f432013-09-24 15:27:41 -07005576 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07005577 * Shrink each node in the zonelist once. If the
5578 * zonelist is ordered by zone (not the default) then a
5579 * node may be shrunk multiple times but in that case
5580 * the user prefers lower zones being preserved.
5581 */
5582 if (zone->zone_pgdat == last_pgdat)
5583 continue;
5584
5585 /*
Andrew Morton0608f432013-09-24 15:27:41 -07005586 * This steals pages from memory cgroups over softlimit
5587 * and returns the number of reclaimed pages and
5588 * scanned pages. This works for global memory pressure
5589 * and balancing, not for a memcg's limit.
5590 */
5591 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07005592 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07005593 sc->order, sc->gfp_mask,
5594 &nr_soft_scanned);
5595 sc->nr_reclaimed += nr_soft_reclaimed;
5596 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07005597 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005598 }
Nick Piggin408d8542006-09-25 23:31:27 -07005599
Mel Gorman79dafcd2016-07-28 15:45:53 -07005600 /* See comment about same check for global reclaim above */
5601 if (zone->zone_pgdat == last_pgdat)
5602 continue;
5603 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07005604 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005605 }
Mel Gormane0c23272011-10-31 17:09:33 -07005606
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005607 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07005608 * Restore to original mask to avoid the impact on the caller if we
5609 * promoted it to __GFP_HIGHMEM.
5610 */
5611 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005612}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005613
Johannes Weinerb9107182019-11-30 17:55:59 -08005614static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005615{
Johannes Weinerb9107182019-11-30 17:55:59 -08005616 struct lruvec *target_lruvec;
5617 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005618
Yu Zhaoa1537a62022-01-27 20:32:37 -07005619 if (lru_gen_enabled())
5620 return;
5621
Johannes Weinerb9107182019-11-30 17:55:59 -08005622 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07005623 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
5624 target_lruvec->refaults[0] = refaults;
5625 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
5626 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005627}
5628
Linus Torvalds1da177e2005-04-16 15:20:36 -07005629/*
5630 * This is the main entry point to direct page reclaim.
5631 *
5632 * If a full scan of the inactive list fails to free enough memory then we
5633 * are "out of memory" and something needs to be killed.
5634 *
5635 * If the caller is !__GFP_FS then the probability of a failure is reasonably
5636 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02005637 * caller can't do much about. We kick the writeback threads and take explicit
5638 * naps in the hope that some of these pages can be written. But if the
5639 * allocating task holds filesystem locks which prevent writeout this might not
5640 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07005641 *
5642 * returns: 0, if no pages reclaimed
5643 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07005644 */
Mel Gormandac1d272008-04-28 02:12:12 -07005645static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005646 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005647{
Johannes Weiner241994ed2015-02-11 15:26:06 -08005648 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005649 pg_data_t *last_pgdat;
5650 struct zoneref *z;
5651 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005652retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07005653 delayacct_freepages_start();
5654
Johannes Weinerb5ead352019-11-30 17:55:40 -08005655 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07005656 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005657
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005658 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005659 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
5660 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08005661 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07005662 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07005663
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005664 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07005665 break;
5666
5667 if (sc->compaction_ready)
5668 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005669
5670 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08005671 * If we're getting trouble reclaiming, start doing
5672 * writepage even in laptop mode.
5673 */
5674 if (sc->priority < DEF_PRIORITY - 2)
5675 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07005676 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005677
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005678 last_pgdat = NULL;
5679 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
5680 sc->nodemask) {
5681 if (zone->zone_pgdat == last_pgdat)
5682 continue;
5683 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08005684
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005685 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08005686
5687 if (cgroup_reclaim(sc)) {
5688 struct lruvec *lruvec;
5689
5690 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
5691 zone->zone_pgdat);
5692 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
5693 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005694 }
5695
Keika Kobayashi873b4772008-07-25 01:48:52 -07005696 delayacct_freepages_end();
5697
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005698 if (sc->nr_reclaimed)
5699 return sc->nr_reclaimed;
5700
Mel Gorman0cee34f2012-01-12 17:19:49 -08005701 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07005702 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08005703 return 1;
5704
Johannes Weinerb91ac372019-11-30 17:56:02 -08005705 /*
5706 * We make inactive:active ratio decisions based on the node's
5707 * composition of memory, but a restrictive reclaim_idx or a
5708 * memory.low cgroup setting can exempt large amounts of
5709 * memory from reclaim. Neither of which are very common, so
5710 * instead of doing costly eligibility calculations of the
5711 * entire cgroup subtree up front, we assume the estimates are
5712 * good, and retry with forcible deactivation if that fails.
5713 */
5714 if (sc->skipped_deactivate) {
5715 sc->priority = initial_priority;
5716 sc->force_deactivate = 1;
5717 sc->skipped_deactivate = 0;
5718 goto retry;
5719 }
5720
Johannes Weiner241994ed2015-02-11 15:26:06 -08005721 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07005722 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08005723 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08005724 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07005725 sc->memcg_low_reclaim = 1;
5726 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005727 goto retry;
5728 }
5729
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005730 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005731}
5732
Johannes Weinerc73322d2017-05-03 14:51:51 -07005733static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07005734{
5735 struct zone *zone;
5736 unsigned long pfmemalloc_reserve = 0;
5737 unsigned long free_pages = 0;
5738 int i;
5739 bool wmark_ok;
5740
Johannes Weinerc73322d2017-05-03 14:51:51 -07005741 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
5742 return true;
5743
Mel Gorman55150612012-07-31 16:44:35 -07005744 for (i = 0; i <= ZONE_NORMAL; i++) {
5745 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07005746 if (!managed_zone(zone))
5747 continue;
5748
5749 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07005750 continue;
5751
Mel Gorman55150612012-07-31 16:44:35 -07005752 pfmemalloc_reserve += min_wmark_pages(zone);
5753 free_pages += zone_page_state(zone, NR_FREE_PAGES);
5754 }
5755
Mel Gorman675becc2014-06-04 16:07:35 -07005756 /* If there are no reserves (unexpected config) then do not throttle */
5757 if (!pfmemalloc_reserve)
5758 return true;
5759
Mel Gorman55150612012-07-31 16:44:35 -07005760 wmark_ok = free_pages > pfmemalloc_reserve / 2;
5761
5762 /* kswapd must be awake if processes are being throttled */
5763 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005764 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
5765 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005766
Mel Gorman55150612012-07-31 16:44:35 -07005767 wake_up_interruptible(&pgdat->kswapd_wait);
5768 }
5769
5770 return wmark_ok;
5771}
5772
5773/*
5774 * Throttle direct reclaimers if backing storage is backed by the network
5775 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
5776 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08005777 * when the low watermark is reached.
5778 *
5779 * Returns true if a fatal signal was delivered during throttling. If this
5780 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07005781 */
Mel Gorman50694c22012-11-26 16:29:48 -08005782static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07005783 nodemask_t *nodemask)
5784{
Mel Gorman675becc2014-06-04 16:07:35 -07005785 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07005786 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07005787 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07005788
5789 /*
5790 * Kernel threads should not be throttled as they may be indirectly
5791 * responsible for cleaning pages necessary for reclaim to make forward
5792 * progress. kjournald for example may enter direct reclaim while
5793 * committing a transaction where throttling it could forcing other
5794 * processes to block on log_wait_commit().
5795 */
5796 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08005797 goto out;
5798
5799 /*
5800 * If a fatal signal is pending, this process should not throttle.
5801 * It should return quickly so it can exit and free its memory
5802 */
5803 if (fatal_signal_pending(current))
5804 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005805
Mel Gorman675becc2014-06-04 16:07:35 -07005806 /*
5807 * Check if the pfmemalloc reserves are ok by finding the first node
5808 * with a usable ZONE_NORMAL or lower zone. The expectation is that
5809 * GFP_KERNEL will be required for allocating network buffers when
5810 * swapping over the network so ZONE_HIGHMEM is unusable.
5811 *
5812 * Throttling is based on the first usable node and throttled processes
5813 * wait on a queue until kswapd makes progress and wakes them. There
5814 * is an affinity then between processes waking up and where reclaim
5815 * progress has been made assuming the process wakes on the same node.
5816 * More importantly, processes running on remote nodes will not compete
5817 * for remote pfmemalloc reserves and processes on different nodes
5818 * should make reasonable progress.
5819 */
5820 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08005821 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07005822 if (zone_idx(zone) > ZONE_NORMAL)
5823 continue;
5824
5825 /* Throttle based on the first usable node */
5826 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07005827 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07005828 goto out;
5829 break;
5830 }
5831
5832 /* If no zone was usable by the allocation flags then do not throttle */
5833 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08005834 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005835
Mel Gorman68243e72012-07-31 16:44:39 -07005836 /* Account for the throttling */
5837 count_vm_event(PGSCAN_DIRECT_THROTTLE);
5838
Mel Gorman55150612012-07-31 16:44:35 -07005839 /*
5840 * If the caller cannot enter the filesystem, it's possible that it
5841 * is due to the caller holding an FS lock or performing a journal
5842 * transaction in the case of a filesystem like ext[3|4]. In this case,
5843 * it is not safe to block on pfmemalloc_wait as kswapd could be
5844 * blocked waiting on the same lock. Instead, throttle for up to a
5845 * second before continuing.
5846 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07005847 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07005848 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07005849 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07005850 else
5851 /* Throttle until kswapd wakes the process */
5852 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
5853 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08005854
Mel Gorman50694c22012-11-26 16:29:48 -08005855 if (fatal_signal_pending(current))
5856 return true;
5857
5858out:
5859 return false;
Mel Gorman55150612012-07-31 16:44:35 -07005860}
5861
Mel Gormandac1d272008-04-28 02:12:12 -07005862unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07005863 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08005864{
Mel Gorman33906bc2010-08-09 17:19:16 -07005865 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005866 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08005867 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005868 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07005869 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07005870 .order = order,
5871 .nodemask = nodemask,
5872 .priority = DEF_PRIORITY,
5873 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005874 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07005875 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08005876 };
5877
Mel Gorman55150612012-07-31 16:44:35 -07005878 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07005879 * scan_control uses s8 fields for order, priority, and reclaim_idx.
5880 * Confirm they are large enough for max values.
5881 */
5882 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
5883 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
5884 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
5885
5886 /*
Mel Gorman50694c22012-11-26 16:29:48 -08005887 * Do not enter reclaim if fatal signal was delivered while throttled.
5888 * 1 is returned so that the page allocator does not OOM kill at this
5889 * point.
Mel Gorman55150612012-07-31 16:44:35 -07005890 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005891 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07005892 return 1;
5893
Andrew Morton1732d2b012019-07-16 16:26:15 -07005894 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005895 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07005896
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005897 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07005898
5899 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005900 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07005901
5902 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005903}
5904
Andrew Mortonc255a452012-07-31 16:43:02 -07005905#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08005906
Michal Hockod2e5fb92019-08-30 16:04:50 -07005907/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005908unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005909 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07005910 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07005911 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07005912{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005913 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07005914 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07005915 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07005916 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005917 .may_writepage = !laptop_mode,
5918 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07005919 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07005920 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07005921 };
Ying Han0ae5e892011-05-26 16:25:25 -07005922
Michal Hockod2e5fb92019-08-30 16:04:50 -07005923 WARN_ON_ONCE(!current->reclaim_state);
5924
Balbir Singh4e416952009-09-23 15:56:39 -07005925 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
5926 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005927
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005928 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07005929 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005930
Balbir Singh4e416952009-09-23 15:56:39 -07005931 /*
5932 * NOTE: Although we can get the priority field, using it
5933 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07005934 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07005935 * will pick up pages from other mem cgroup's as well. We hack
5936 * the priority and make it zero.
5937 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005938 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005939
5940 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
5941
Ying Han0ae5e892011-05-26 16:25:25 -07005942 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07005943
Balbir Singh4e416952009-09-23 15:56:39 -07005944 return sc.nr_reclaimed;
5945}
5946
Johannes Weiner72835c82012-01-12 17:18:32 -08005947unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005948 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08005949 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005950 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08005951{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005952 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07005953 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08005954 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005955 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07005956 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07005957 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07005958 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07005959 .target_mem_cgroup = memcg,
5960 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08005961 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005962 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005963 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07005964 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08005965 /*
5966 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
5967 * equal pressure on all the nodes. This is based on the assumption that
5968 * the reclaim does not bail out early.
5969 */
5970 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08005971
Andrew Morton1732d2b012019-07-16 16:26:15 -07005972 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005973 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07005974 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07005975
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005976 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07005977
Vlastimil Babka499118e2017-05-08 15:59:50 -07005978 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005979 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005980 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005981
5982 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005983}
5984#endif
5985
Mel Gorman1d82de62016-07-28 15:45:43 -07005986static void age_active_anon(struct pglist_data *pgdat,
Mel Gormanef8f2322016-07-28 15:46:05 -07005987 struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005988{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005989 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08005990 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005991
Yu Zhaoa1537a62022-01-27 20:32:37 -07005992 if (lru_gen_enabled()) {
5993 lru_gen_age_node(pgdat, sc);
5994 return;
5995 }
5996
Dave Hansen2f368a92021-09-02 14:59:23 -07005997 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08005998 return;
5999
Johannes Weinerb91ac372019-11-30 17:56:02 -08006000 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6001 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6002 return;
6003
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006004 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6005 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006006 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6007 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6008 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006009 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6010 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006011}
6012
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006013static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006014{
6015 int i;
6016 struct zone *zone;
6017
6018 /*
6019 * Check for watermark boosts top-down as the higher zones
6020 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006021 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006022 * start prematurely when there is no boosting and a lower
6023 * zone is balanced.
6024 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006025 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006026 zone = pgdat->node_zones + i;
6027 if (!managed_zone(zone))
6028 continue;
6029
6030 if (zone->watermark_boost)
6031 return true;
6032 }
6033
6034 return false;
6035}
6036
Mel Gormane716f2e2017-05-03 14:53:45 -07006037/*
6038 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006039 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006040 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006041static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006042{
Mel Gormane716f2e2017-05-03 14:53:45 -07006043 int i;
6044 unsigned long mark = -1;
6045 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006046
Mel Gorman1c308442018-12-28 00:35:52 -08006047 /*
6048 * Check watermarks bottom-up as lower zones are more likely to
6049 * meet watermarks.
6050 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006051 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006052 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006053
Mel Gormane716f2e2017-05-03 14:53:45 -07006054 if (!managed_zone(zone))
6055 continue;
6056
6057 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006058 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006059 return true;
6060 }
6061
6062 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006063 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006064 * need balancing by definition. This can happen if a zone-restricted
6065 * allocation tries to wake a remote kswapd.
6066 */
6067 if (mark == -1)
6068 return true;
6069
6070 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006071}
6072
Mel Gorman631b6e02017-05-03 14:53:41 -07006073/* Clear pgdat state for congested, dirty or under writeback. */
6074static void clear_pgdat_congested(pg_data_t *pgdat)
6075{
Johannes Weiner1b051172019-11-30 17:55:52 -08006076 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6077
6078 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006079 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6080 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6081}
6082
Mel Gorman1741c872011-01-13 15:46:21 -08006083/*
Mel Gorman55150612012-07-31 16:44:35 -07006084 * Prepare kswapd for sleeping. This verifies that there are no processes
6085 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6086 *
6087 * Returns true if kswapd is ready to sleep
6088 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006089static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6090 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006091{
Mel Gorman55150612012-07-31 16:44:35 -07006092 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006093 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006094 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006095 * race between when kswapd checks the watermarks and a process gets
6096 * throttled. There is also a potential race if processes get
6097 * throttled, kswapd wakes, a large process exits thereby balancing the
6098 * zones, which causes kswapd to exit balance_pgdat() before reaching
6099 * the wake up checks. If kswapd is going to sleep, no process should
6100 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6101 * the wake up is premature, processes will wake kswapd and get
6102 * throttled again. The difference from wake ups in balance_pgdat() is
6103 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006104 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006105 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6106 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006107
Johannes Weinerc73322d2017-05-03 14:51:51 -07006108 /* Hopeless node, leave it to direct reclaim */
6109 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6110 return true;
6111
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006112 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006113 clear_pgdat_congested(pgdat);
6114 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006115 }
6116
Shantanu Goel333b0a42017-05-03 14:53:38 -07006117 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006118}
6119
Linus Torvalds1da177e2005-04-16 15:20:36 -07006120/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006121 * kswapd shrinks a node of pages that are at or below the highest usable
6122 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006123 *
6124 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006125 * reclaim or if the lack of progress was due to pages under writeback.
6126 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006127 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006128static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006129 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006130{
Mel Gorman1d82de62016-07-28 15:45:43 -07006131 struct zone *zone;
6132 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006133
Mel Gorman1d82de62016-07-28 15:45:43 -07006134 /* Reclaim a number of pages proportional to the number of zones */
6135 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006136 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006137 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006138 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006139 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006140
Mel Gorman1d82de62016-07-28 15:45:43 -07006141 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006142 }
6143
Mel Gorman1d82de62016-07-28 15:45:43 -07006144 /*
6145 * Historically care was taken to put equal pressure on all zones but
6146 * now pressure is applied based on node LRU order.
6147 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006148 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006149
6150 /*
6151 * Fragmentation may mean that the system cannot be rebalanced for
6152 * high-order allocations. If twice the allocation size has been
6153 * reclaimed then recheck watermarks only at order-0 to prevent
6154 * excessive reclaim. Assume that a process requested a high-order
6155 * can direct reclaim/compact.
6156 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006157 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006158 sc->order = 0;
6159
Mel Gormanb8e83b92013-07-03 15:01:45 -07006160 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006161}
6162
Mel Gormanc49c2c42021-06-28 19:42:21 -07006163/* Page allocator PCP high watermark is lowered if reclaim is active. */
6164static inline void
6165update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6166{
6167 int i;
6168 struct zone *zone;
6169
6170 for (i = 0; i <= highest_zoneidx; i++) {
6171 zone = pgdat->node_zones + i;
6172
6173 if (!managed_zone(zone))
6174 continue;
6175
6176 if (active)
6177 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6178 else
6179 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6180 }
6181}
6182
6183static inline void
6184set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6185{
6186 update_reclaim_active(pgdat, highest_zoneidx, true);
6187}
6188
6189static inline void
6190clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6191{
6192 update_reclaim_active(pgdat, highest_zoneidx, false);
6193}
6194
Mel Gorman75485362013-07-03 15:01:42 -07006195/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006196 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6197 * that are eligible for use by the caller until at least one zone is
6198 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006199 *
Mel Gorman1d82de62016-07-28 15:45:43 -07006200 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006201 *
6202 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07006203 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08006204 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07006205 * or lower is eligible for reclaim until at least one usable zone is
6206 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006207 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006208static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006209{
Linus Torvalds1da177e2005-04-16 15:20:36 -07006210 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07006211 unsigned long nr_soft_reclaimed;
6212 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07006213 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08006214 unsigned long nr_boost_reclaim;
6215 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6216 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07006217 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08006218 struct scan_control sc = {
6219 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07006220 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006221 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08006222 };
Omar Sandoval93781322018-06-07 17:07:02 -07006223
Andrew Morton1732d2b012019-07-16 16:26:15 -07006224 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07006225 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006226 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006227
Christoph Lameterf8891e52006-06-30 01:55:45 -07006228 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006229
Mel Gorman1c308442018-12-28 00:35:52 -08006230 /*
6231 * Account for the reclaim boost. Note that the zone boost is left in
6232 * place so that parallel allocations that are near the watermark will
6233 * stall or direct reclaim until kswapd is finished.
6234 */
6235 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006236 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006237 zone = pgdat->node_zones + i;
6238 if (!managed_zone(zone))
6239 continue;
6240
6241 nr_boost_reclaim += zone->watermark_boost;
6242 zone_boosts[i] = zone->watermark_boost;
6243 }
6244 boosted = nr_boost_reclaim;
6245
6246restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006247 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006248 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006249 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006250 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006251 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006252 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006253 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006254
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006255 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006256
Mel Gorman86c79f62016-07-28 15:45:59 -07006257 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006258 * If the number of buffer_heads exceeds the maximum allowed
6259 * then consider reclaiming from all zones. This has a dual
6260 * purpose -- on 64-bit systems it is expected that
6261 * buffer_heads are stripped during active rotation. On 32-bit
6262 * systems, highmem pages can pin lowmem memory and shrinking
6263 * buffers can relieve lowmem pressure. Reclaim may still not
6264 * go ahead if all eligible zones for the original allocation
6265 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006266 */
6267 if (buffer_heads_over_limit) {
6268 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6269 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006270 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006271 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006272
Mel Gorman970a39a2016-07-28 15:46:35 -07006273 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006274 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006275 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006276 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006277
Mel Gorman86c79f62016-07-28 15:45:59 -07006278 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006279 * If the pgdat is imbalanced then ignore boosting and preserve
6280 * the watermarks for a later time and restart. Note that the
6281 * zone watermarks will be still reset at the end of balancing
6282 * on the grounds that the normal reclaim should be enough to
6283 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006284 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006285 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006286 if (!balanced && nr_boost_reclaim) {
6287 nr_boost_reclaim = 0;
6288 goto restart;
6289 }
6290
6291 /*
6292 * If boosting is not active then only reclaim if there are no
6293 * eligible zones. Note that sc.reclaim_idx is not used as
6294 * buffer_heads_over_limit may have adjusted it.
6295 */
6296 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006297 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006298
Mel Gorman1c308442018-12-28 00:35:52 -08006299 /* Limit the priority of boosting to avoid reclaim writeback */
6300 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6301 raise_priority = false;
6302
6303 /*
6304 * Do not writeback or swap pages for boosted reclaim. The
6305 * intent is to relieve pressure not issue sub-optimal IO
6306 * from reclaim context. If no pages are reclaimed, the
6307 * reclaim will be aborted.
6308 */
6309 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6310 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006311
Linus Torvalds1da177e2005-04-16 15:20:36 -07006312 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006313 * Do some background aging of the anon list, to give
6314 * pages a chance to be referenced before reclaiming. All
6315 * pages are rotated regardless of classzone as this is
6316 * about consistent aging.
6317 */
Mel Gormanef8f2322016-07-28 15:46:05 -07006318 age_active_anon(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006319
6320 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006321 * If we're getting trouble reclaiming, start doing writepage
6322 * even in laptop mode.
6323 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006324 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006325 sc.may_writepage = 1;
6326
Mel Gorman1d82de62016-07-28 15:45:43 -07006327 /* Call soft limit reclaim before calling shrink_node. */
6328 sc.nr_scanned = 0;
6329 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006330 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006331 sc.gfp_mask, &nr_soft_scanned);
6332 sc.nr_reclaimed += nr_soft_reclaimed;
6333
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006334 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006335 * There should be no need to raise the scanning priority if
6336 * enough pages are already being scanned that that high
6337 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006338 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006339 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006340 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006341
6342 /*
6343 * If the low watermark is met there is no need for processes
6344 * to be throttled on pfmemalloc_wait as they should not be
6345 * able to safely make forward progress. Wake them
6346 */
6347 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006348 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006349 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006350
Mel Gormanb8e83b92013-07-03 15:01:45 -07006351 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006352 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006353 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006354 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006355 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006356 break;
6357
6358 /*
6359 * Raise priority if scanning rate is too low or there was no
6360 * progress in reclaiming pages
6361 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006362 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006363 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6364
6365 /*
6366 * If reclaim made no progress for a boost, stop reclaim as
6367 * IO cannot be queued and it could be an infinite loop in
6368 * extreme circumstances.
6369 */
6370 if (nr_boost_reclaim && !nr_reclaimed)
6371 break;
6372
Johannes Weinerc73322d2017-05-03 14:51:51 -07006373 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006374 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006375 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006376
Johannes Weinerc73322d2017-05-03 14:51:51 -07006377 if (!sc.nr_reclaimed)
6378 pgdat->kswapd_failures++;
6379
Mel Gormanb8e83b92013-07-03 15:01:45 -07006380out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006381 clear_reclaim_active(pgdat, highest_zoneidx);
6382
Mel Gorman1c308442018-12-28 00:35:52 -08006383 /* If reclaim was boosted, account for the reclaim done in this pass */
6384 if (boosted) {
6385 unsigned long flags;
6386
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006387 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006388 if (!zone_boosts[i])
6389 continue;
6390
6391 /* Increments are under the zone lock */
6392 zone = pgdat->node_zones + i;
6393 spin_lock_irqsave(&zone->lock, flags);
6394 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6395 spin_unlock_irqrestore(&zone->lock, flags);
6396 }
6397
6398 /*
6399 * As there is now likely space, wakeup kcompact to defragment
6400 * pageblocks.
6401 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006402 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006403 }
6404
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006405 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006406 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006407 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006408 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006409
Mel Gorman0abdee22011-01-13 15:46:22 -08006410 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006411 * Return the order kswapd stopped reclaiming at as
6412 * prepare_kswapd_sleep() takes it into account. If another caller
6413 * entered the allocator slow path while kswapd was awake, order will
6414 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006415 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006416 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006417}
6418
Mel Gormane716f2e2017-05-03 14:53:45 -07006419/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006420 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6421 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6422 * not a valid index then either kswapd runs for first time or kswapd couldn't
6423 * sleep after previous reclaim attempt (node is still unbalanced). In that
6424 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006425 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006426static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6427 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006428{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006429 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006430
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006431 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006432}
6433
Mel Gorman38087d92016-07-28 15:45:49 -07006434static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006435 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006436{
6437 long remaining = 0;
6438 DEFINE_WAIT(wait);
6439
6440 if (freezing(current) || kthread_should_stop())
6441 return;
6442
6443 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6444
Shantanu Goel333b0a42017-05-03 14:53:38 -07006445 /*
6446 * Try to sleep for a short interval. Note that kcompactd will only be
6447 * woken if it is possible to sleep for a short interval. This is
6448 * deliberate on the assumption that if reclaim cannot keep an
6449 * eligible zone balanced that it's also unlikely that compaction will
6450 * succeed.
6451 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006452 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006453 /*
6454 * Compaction records what page blocks it recently failed to
6455 * isolate pages from and skips them in the future scanning.
6456 * When kswapd is going to sleep, it is reasonable to assume
6457 * that pages and compaction may succeed so reset the cache.
6458 */
6459 reset_isolation_suitable(pgdat);
6460
6461 /*
6462 * We have freed the memory, now we should compact it to make
6463 * allocation of the requested order possible.
6464 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006465 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006466
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006467 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006468
6469 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006470 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006471 * order. The values will either be from a wakeup request or
6472 * the previous request that slept prematurely.
6473 */
6474 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006475 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6476 kswapd_highest_zoneidx(pgdat,
6477 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006478
6479 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6480 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006481 }
6482
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006483 finish_wait(&pgdat->kswapd_wait, &wait);
6484 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6485 }
6486
6487 /*
6488 * After a short sleep, check if it was a premature sleep. If not, then
6489 * go fully to sleep until explicitly woken up.
6490 */
Mel Gormand9f21d42016-07-28 15:46:41 -07006491 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006492 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006493 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6494
6495 /*
6496 * vmstat counters are not perfectly accurate and the estimated
6497 * value for counters such as NR_FREE_PAGES can deviate from the
6498 * true value by nr_online_cpus * threshold. To avoid the zone
6499 * watermarks being breached while under pressure, we reduce the
6500 * per-cpu vmstat threshold while kswapd is awake and restore
6501 * them before going back to sleep.
6502 */
6503 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07006504
6505 if (!kthread_should_stop())
6506 schedule();
6507
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006508 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
6509 } else {
6510 if (remaining)
6511 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
6512 else
6513 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
6514 }
6515 finish_wait(&pgdat->kswapd_wait, &wait);
6516}
6517
Linus Torvalds1da177e2005-04-16 15:20:36 -07006518/*
6519 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006520 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006521 *
6522 * This basically trickles out pages so that we have _some_
6523 * free memory available even if there is no other activity
6524 * that frees anything up. This is needed for things like routing
6525 * etc, where we otherwise might have all activity going on in
6526 * asynchronous contexts that cannot page things out.
6527 *
6528 * If there are applications that are active memory-allocators
6529 * (most normal use), this basically shouldn't matter.
6530 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306531int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006532{
Mel Gormane716f2e2017-05-03 14:53:45 -07006533 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006534 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07006535 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006536 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10306537 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006538
Rusty Russell174596a2009-01-01 10:12:29 +10306539 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07006540 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006541
6542 /*
6543 * Tell the memory management that we're a "memory allocator",
6544 * and that if we need more memory we should get access to it
6545 * regardless (see "__alloc_pages()"). "kswapd" should
6546 * never get caught in the normal page freeing logic.
6547 *
6548 * (Kswapd normally doesn't need memory anyway, but sometimes
6549 * you need a small amount of memory in order to be able to
6550 * page out something else, and this flag essentially protects
6551 * us from recursively trying to free more memory as we're
6552 * trying to free the first piece of memory in the first place).
6553 */
Christoph Lameter930d9152006-01-08 01:00:47 -08006554 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07006555 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07006556
Qian Cai5644e1fb2020-04-01 21:10:12 -07006557 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006558 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006559 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08006560 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07006561
Qian Cai5644e1fb2020-04-01 21:10:12 -07006562 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006563 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6564 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07006565
Mel Gorman38087d92016-07-28 15:45:49 -07006566kswapd_try_sleep:
6567 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006568 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07006569
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006570 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08006571 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006572 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6573 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006574 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006575 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006576
David Rientjes8fe23e02009-12-14 17:58:33 -08006577 ret = try_to_freeze();
6578 if (kthread_should_stop())
6579 break;
6580
6581 /*
6582 * We can speed up thawing tasks if we don't call balance_pgdat
6583 * after returning from the refrigerator
6584 */
Mel Gorman38087d92016-07-28 15:45:49 -07006585 if (ret)
6586 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07006587
Mel Gorman38087d92016-07-28 15:45:49 -07006588 /*
6589 * Reclaim begins at the requested order but if a high-order
6590 * reclaim fails then kswapd falls back to reclaiming for
6591 * order-0. If that happens, kswapd will consider sleeping
6592 * for the order it finished reclaiming at (reclaim_order)
6593 * but kcompactd is woken to compact for the original
6594 * request (alloc_order).
6595 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006596 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07006597 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006598 reclaim_order = balance_pgdat(pgdat, alloc_order,
6599 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07006600 if (reclaim_order < alloc_order)
6601 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006602 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08006603
Johannes Weiner71abdc12014-06-06 14:35:35 -07006604 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07006605
Linus Torvalds1da177e2005-04-16 15:20:36 -07006606 return 0;
6607}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306608EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006609
6610/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07006611 * A zone is low on free memory or too fragmented for high-order memory. If
6612 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
6613 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
6614 * has failed or is not needed, still wake up kcompactd if only compaction is
6615 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006616 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07006617void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006618 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006619{
6620 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07006621 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006622
Mel Gorman6aa303d2016-09-01 16:14:55 -07006623 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006624 return;
6625
David Rientjes5ecd9d42018-04-05 16:25:16 -07006626 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006627 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07006628
Qian Cai5644e1fb2020-04-01 21:10:12 -07006629 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006630 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006631
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006632 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
6633 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006634
6635 if (READ_ONCE(pgdat->kswapd_order) < order)
6636 WRITE_ONCE(pgdat->kswapd_order, order);
6637
Con Kolivas8d0986e2005-09-13 01:25:07 -07006638 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006639 return;
Mel Gormane1a55632016-07-28 15:46:26 -07006640
David Rientjes5ecd9d42018-04-05 16:25:16 -07006641 /* Hopeless node, leave it to direct reclaim if possible */
6642 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006643 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
6644 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07006645 /*
6646 * There may be plenty of free memory available, but it's too
6647 * fragmented for high-order allocations. Wake up kcompactd
6648 * and rely on compaction_suitable() to determine if it's
6649 * needed. If it fails, it will defer subsequent attempts to
6650 * ratelimit its work.
6651 */
6652 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006653 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07006654 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07006655 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07006656
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006657 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07006658 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07006659 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006660}
6661
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006662#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07006663/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006664 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006665 * freed pages.
6666 *
6667 * Rather than trying to age LRUs the aim is to preserve the overall
6668 * LRU order by reclaiming preferentially
6669 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07006670 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006671unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006672{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006673 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006674 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07006675 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07006676 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006677 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07006678 .may_writepage = 1,
6679 .may_unmap = 1,
6680 .may_swap = 1,
6681 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07006682 };
Ying Hana09ed5e2011-05-24 17:12:26 -07006683 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006684 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006685 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006686
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01006687 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07006688 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07006689 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08006690
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006691 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006692
Andrew Morton1732d2b012019-07-16 16:26:15 -07006693 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006694 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006695 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006696
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006697 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006698}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006699#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07006700
Yasunori Goto3218ae12006-06-27 02:53:33 -07006701/*
6702 * This kswapd start function will be called by init and node-hot-add.
6703 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
6704 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07006705void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006706{
6707 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306708 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006709
6710 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07006711 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006712
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306713 trace_android_vh_kswapd_per_node(nid, &skip, true);
6714 if (skip)
6715 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006716 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
6717 if (IS_ERR(pgdat->kswapd)) {
6718 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02006719 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07006720 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07006721 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006722 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07006723}
6724
David Rientjes8fe23e02009-12-14 17:58:33 -08006725/*
Jiang Liud8adde12012-07-11 14:01:52 -07006726 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07006727 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08006728 */
6729void kswapd_stop(int nid)
6730{
6731 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306732 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08006733
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306734 trace_android_vh_kswapd_per_node(nid, &skip, false);
6735 if (skip)
6736 return;
Jiang Liud8adde12012-07-11 14:01:52 -07006737 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08006738 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07006739 NODE_DATA(nid)->kswapd = NULL;
6740 }
David Rientjes8fe23e02009-12-14 17:58:33 -08006741}
6742
Linus Torvalds1da177e2005-04-16 15:20:36 -07006743static int __init kswapd_init(void)
6744{
Wei Yang6b700b52020-04-01 21:10:09 -07006745 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08006746
Linus Torvalds1da177e2005-04-16 15:20:36 -07006747 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08006748 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006749 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006750 return 0;
6751}
6752
6753module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006754
6755#ifdef CONFIG_NUMA
6756/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006757 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08006758 *
Mel Gormana5f5f912016-07-28 15:46:32 -07006759 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08006760 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006761 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006762int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006763
Dave Hansen51998362021-02-24 12:09:15 -08006764/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006765 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08006766 * of a node considered for each zone_reclaim. 4 scans 1/16th of
6767 * a zone.
6768 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006769#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08006770
Christoph Lameter9eeff232006-01-18 17:42:31 -08006771/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006772 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07006773 * occur.
6774 */
6775int sysctl_min_unmapped_ratio = 1;
6776
6777/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07006778 * If the number of slab pages in a zone grows beyond this percentage then
6779 * slab reclaim needs to occur.
6780 */
6781int sysctl_min_slab_ratio = 5;
6782
Mel Gorman11fb9982016-07-28 15:46:20 -07006783static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006784{
Mel Gorman11fb9982016-07-28 15:46:20 -07006785 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
6786 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
6787 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006788
6789 /*
6790 * It's possible for there to be more file mapped pages than
6791 * accounted for by the pages on the file LRU lists because
6792 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
6793 */
6794 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
6795}
6796
6797/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07006798static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006799{
Alexandru Moised031a152015-11-05 18:48:08 -08006800 unsigned long nr_pagecache_reclaimable;
6801 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07006802
6803 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006804 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07006805 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07006806 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07006807 * a better estimate
6808 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006809 if (node_reclaim_mode & RECLAIM_UNMAP)
6810 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006811 else
Mel Gormana5f5f912016-07-28 15:46:32 -07006812 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006813
6814 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07006815 if (!(node_reclaim_mode & RECLAIM_WRITE))
6816 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006817
6818 /* Watch for any possible underflows due to delta */
6819 if (unlikely(delta > nr_pagecache_reclaimable))
6820 delta = nr_pagecache_reclaimable;
6821
6822 return nr_pagecache_reclaimable - delta;
6823}
6824
Christoph Lameter0ff38492006-09-25 23:31:52 -07006825/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006826 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006827 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006828static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006829{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08006830 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08006831 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006832 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006833 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08006834 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08006835 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006836 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07006837 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07006838 .priority = NODE_RECLAIM_PRIORITY,
6839 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
6840 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07006841 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006842 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08006843 };
Johannes Weiner57f29762021-08-19 19:04:27 -07006844 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006845
Yafang Shao132bb8c2019-05-13 17:17:53 -07006846 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
6847 sc.gfp_mask);
6848
Christoph Lameter9eeff232006-01-18 17:42:31 -08006849 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07006850 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07006851 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08006852 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006853 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08006854 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006855 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08006856 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07006857 noreclaim_flag = memalloc_noreclaim_save();
6858 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07006859 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08006860
Mel Gormana5f5f912016-07-28 15:46:32 -07006861 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07006862 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07006863 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07006864 * priorities until we have enough memory freed.
6865 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07006866 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07006867 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006868 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07006869 }
Christoph Lameterc84db232006-02-01 03:05:29 -08006870
Andrew Morton1732d2b012019-07-16 16:26:15 -07006871 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006872 current->flags &= ~PF_SWAPWRITE;
6873 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006874 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07006875 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07006876
6877 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
6878
Rik van Riela79311c2009-01-06 14:40:01 -08006879 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006880}
Andrew Morton179e9632006-03-22 00:08:18 -08006881
Mel Gormana5f5f912016-07-28 15:46:32 -07006882int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08006883{
David Rientjesd773ed62007-10-16 23:26:01 -07006884 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006885
6886 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006887 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07006888 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07006889 *
Christoph Lameter96146342006-07-03 00:24:13 -07006890 * A small portion of unmapped file backed pages is needed for
6891 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07006892 * thrown out if the node is overallocated. So we do not reclaim
6893 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07006894 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08006895 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006896 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07006897 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
6898 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07006899 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08006900
6901 /*
David Rientjesd773ed62007-10-16 23:26:01 -07006902 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08006903 */
Mel Gormand0164ad2015-11-06 16:28:21 -08006904 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07006905 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08006906
6907 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006908 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08006909 * have associated processors. This will favor the local processor
6910 * over remote processors and spread off node memory allocations
6911 * as wide as possible.
6912 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006913 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
6914 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07006915
Mel Gormana5f5f912016-07-28 15:46:32 -07006916 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
6917 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07006918
Mel Gormana5f5f912016-07-28 15:46:32 -07006919 ret = __node_reclaim(pgdat, gfp_mask, order);
6920 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07006921
Mel Gorman24cf725182009-06-16 15:33:23 -07006922 if (!ret)
6923 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
6924
David Rientjesd773ed62007-10-16 23:26:01 -07006925 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006926}
Christoph Lameter9eeff232006-01-18 17:42:31 -08006927#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07006928
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006929/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006930 * check_move_unevictable_pages - check pages for evictability and move to
6931 * appropriate zone lru list
6932 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006933 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006934 * Checks pages for evictability, if an evictable page is in the unevictable
6935 * lru list, moves it to the appropriate evictable lru list. This function
6936 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006937 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006938void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006939{
Alex Shi6168d0d2020-12-15 12:34:29 -08006940 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08006941 int pgscanned = 0;
6942 int pgrescued = 0;
6943 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006944
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006945 for (i = 0; i < pvec->nr; i++) {
6946 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006947 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07006948
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006949 if (PageTransTail(page))
6950 continue;
6951
6952 nr_pages = thp_nr_pages(page);
6953 pgscanned += nr_pages;
6954
Alex Shid25b5bd2020-12-15 12:34:16 -08006955 /* block memcg migration during page moving between lru */
6956 if (!TestClearPageLRU(page))
6957 continue;
6958
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08006959 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08006960 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08006961 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08006962 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08006963 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006964 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08006965 }
Alex Shid25b5bd2020-12-15 12:34:16 -08006966 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006967 }
Hugh Dickins24513262012-01-20 14:34:21 -08006968
Alex Shi6168d0d2020-12-15 12:34:29 -08006969 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08006970 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
6971 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08006972 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08006973 } else if (pgscanned) {
6974 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08006975 }
Hugh Dickins850465792012-01-20 14:34:19 -08006976}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006977EXPORT_SYMBOL_GPL(check_move_unevictable_pages);