blob: 6b1ddca1abe8967ad5e90c9fcb9c680d412e3c03 [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
rongqianfeng8da6ee32021-05-21 10:30:14 +0800718 trace_android_vh_do_shrink_slab(shrinker, shrinkctl, priority);
719
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700720 freeable = shrinker->count_objects(shrinker, shrinkctl);
Kirill Tkhai9b996462018-08-17 15:48:21 -0700721 if (freeable == 0 || freeable == SHRINK_EMPTY)
722 return freeable;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000723
724 /*
725 * copy the current shrinker scan count into a local variable
726 * and zero it so that other concurrent shrinker invocations
727 * don't also do this scanning work.
728 */
Yang Shi86750832021-05-04 18:36:36 -0700729 nr = xchg_nr_deferred(shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000730
Johannes Weiner4b85afb2018-10-26 15:06:42 -0700731 if (shrinker->seeks) {
732 delta = freeable >> priority;
733 delta *= 4;
734 do_div(delta, shrinker->seeks);
735 } else {
736 /*
737 * These objects don't require any IO to create. Trim
738 * them aggressively under memory pressure to keep
739 * them from causing refetches in the IO caches.
740 */
741 delta = freeable / 2;
742 }
Roman Gushchin172b06c32018-09-20 12:22:46 -0700743
Yang Shi18bb4732021-05-04 18:36:45 -0700744 total_scan = nr >> priority;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000745 total_scan += delta;
Yang Shi18bb4732021-05-04 18:36:45 -0700746 total_scan = min(total_scan, (2 * freeable));
Glauber Costa1d3d4432013-08-28 10:18:04 +1000747
748 trace_mm_shrink_slab_start(shrinker, shrinkctl, nr,
Josef Bacik9092c712018-01-31 16:16:26 -0800749 freeable, delta, total_scan, priority);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000750
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800751 /*
752 * Normally, we should not scan less than batch_size objects in one
753 * pass to avoid too frequent shrinker calls, but if the slab has less
754 * than batch_size objects in total and we are really tight on memory,
755 * we will try to reclaim all available objects, otherwise we can end
756 * up failing allocations although there are plenty of reclaimable
757 * objects spread over several slabs with usage less than the
758 * batch_size.
759 *
760 * We detect the "tight on memory" situations by looking at the total
761 * number of objects we want to scan (total_scan). If it is greater
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700762 * than the total number of objects on slab (freeable), we must be
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800763 * scanning at high prio and therefore should try to reclaim as much as
764 * possible.
765 */
766 while (total_scan >= batch_size ||
Vladimir Davydovd5bc5fd2014-04-03 14:47:32 -0700767 total_scan >= freeable) {
Dave Chinnera0b02132013-08-28 10:18:16 +1000768 unsigned long ret;
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800769 unsigned long nr_to_scan = min(batch_size, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000770
Vladimir Davydov0b1fb402014-01-23 15:53:22 -0800771 shrinkctl->nr_to_scan = nr_to_scan;
Chris Wilsond460acb2017-09-06 16:19:26 -0700772 shrinkctl->nr_scanned = nr_to_scan;
Dave Chinnera0b02132013-08-28 10:18:16 +1000773 ret = shrinker->scan_objects(shrinker, shrinkctl);
774 if (ret == SHRINK_STOP)
775 break;
776 freed += ret;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000777
Chris Wilsond460acb2017-09-06 16:19:26 -0700778 count_vm_events(SLABS_SCANNED, shrinkctl->nr_scanned);
779 total_scan -= shrinkctl->nr_scanned;
780 scanned += shrinkctl->nr_scanned;
Glauber Costa1d3d4432013-08-28 10:18:04 +1000781
782 cond_resched();
783 }
784
Yang Shi18bb4732021-05-04 18:36:45 -0700785 /*
786 * The deferred work is increased by any new work (delta) that wasn't
787 * done, decreased by old deferred work that was done now.
788 *
789 * And it is capped to two times of the freeable items.
790 */
791 next_deferred = max_t(long, (nr + delta - scanned), 0);
792 next_deferred = min(next_deferred, (2 * freeable));
793
Glauber Costa1d3d4432013-08-28 10:18:04 +1000794 /*
795 * move the unused scan count back into the shrinker in a
Yang Shi86750832021-05-04 18:36:36 -0700796 * manner that handles concurrent updates.
Glauber Costa1d3d4432013-08-28 10:18:04 +1000797 */
Yang Shi86750832021-05-04 18:36:36 -0700798 new_nr = add_nr_deferred(next_deferred, shrinker, shrinkctl);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000799
Yang Shi8efb4b52021-05-04 18:36:08 -0700800 trace_mm_shrink_slab_end(shrinker, shrinkctl->nid, freed, nr, new_nr, total_scan);
Glauber Costa1d3d4432013-08-28 10:18:04 +1000801 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700802}
803
Yang Shi0a432dc2019-09-23 15:38:12 -0700804#ifdef CONFIG_MEMCG
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700805static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
806 struct mem_cgroup *memcg, int priority)
807{
Yang Shie4262c42021-05-04 18:36:23 -0700808 struct shrinker_info *info;
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700809 unsigned long ret, freed = 0;
810 int i;
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700811
Yang Shi0a432dc2019-09-23 15:38:12 -0700812 if (!mem_cgroup_online(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700813 return 0;
814
815 if (!down_read_trylock(&shrinker_rwsem))
816 return 0;
817
Yang Shi468ab842021-05-04 18:36:26 -0700818 info = shrinker_info_protected(memcg, nid);
Yang Shie4262c42021-05-04 18:36:23 -0700819 if (unlikely(!info))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700820 goto unlock;
821
Yang Shie4262c42021-05-04 18:36:23 -0700822 for_each_set_bit(i, info->map, shrinker_nr_max) {
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700823 struct shrink_control sc = {
824 .gfp_mask = gfp_mask,
825 .nid = nid,
826 .memcg = memcg,
827 };
828 struct shrinker *shrinker;
829
830 shrinker = idr_find(&shrinker_idr, i);
Yang Shi41ca6682021-05-04 18:36:29 -0700831 if (unlikely(!shrinker || !(shrinker->flags & SHRINKER_REGISTERED))) {
Kirill Tkhai7e010df2018-08-17 15:48:34 -0700832 if (!shrinker)
Yang Shie4262c42021-05-04 18:36:23 -0700833 clear_bit(i, info->map);
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700834 continue;
835 }
836
Yang Shi0a432dc2019-09-23 15:38:12 -0700837 /* Call non-slab shrinkers even though kmem is disabled */
838 if (!memcg_kmem_enabled() &&
839 !(shrinker->flags & SHRINKER_NONSLAB))
840 continue;
841
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700842 ret = do_shrink_slab(&sc, shrinker, priority);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700843 if (ret == SHRINK_EMPTY) {
Yang Shie4262c42021-05-04 18:36:23 -0700844 clear_bit(i, info->map);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700845 /*
846 * After the shrinker reported that it had no objects to
847 * free, but before we cleared the corresponding bit in
848 * the memcg shrinker map, a new object might have been
849 * added. To make sure, we have the bit set in this
850 * case, we invoke the shrinker one more time and reset
851 * the bit if it reports that it is not empty anymore.
852 * The memory barrier here pairs with the barrier in
Yang Shi2bfd3632021-05-04 18:36:11 -0700853 * set_shrinker_bit():
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700854 *
855 * list_lru_add() shrink_slab_memcg()
856 * list_add_tail() clear_bit()
857 * <MB> <MB>
858 * set_bit() do_shrink_slab()
859 */
860 smp_mb__after_atomic();
861 ret = do_shrink_slab(&sc, shrinker, priority);
862 if (ret == SHRINK_EMPTY)
863 ret = 0;
864 else
Yang Shi2bfd3632021-05-04 18:36:11 -0700865 set_shrinker_bit(memcg, nid, i);
Kirill Tkhaif90280d2018-08-17 15:48:25 -0700866 }
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700867 freed += ret;
868
869 if (rwsem_is_contended(&shrinker_rwsem)) {
870 freed = freed ? : 1;
871 break;
872 }
873 }
874unlock:
875 up_read(&shrinker_rwsem);
876 return freed;
877}
Yang Shi0a432dc2019-09-23 15:38:12 -0700878#else /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700879static unsigned long shrink_slab_memcg(gfp_t gfp_mask, int nid,
880 struct mem_cgroup *memcg, int priority)
881{
882 return 0;
883}
Yang Shi0a432dc2019-09-23 15:38:12 -0700884#endif /* CONFIG_MEMCG */
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700885
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800886/**
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800887 * shrink_slab - shrink slab caches
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800888 * @gfp_mask: allocation context
889 * @nid: node whose slab caches to target
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800890 * @memcg: memory cgroup whose slab caches to target
Josef Bacik9092c712018-01-31 16:16:26 -0800891 * @priority: the reclaim priority
Linus Torvalds1da177e2005-04-16 15:20:36 -0700892 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800893 * Call the shrink functions to age shrinkable caches.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700894 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800895 * @nid is passed along to shrinkers with SHRINKER_NUMA_AWARE set,
896 * unaware shrinkers will receive a node id of 0 instead.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700897 *
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700898 * @memcg specifies the memory cgroup to target. Unaware shrinkers
899 * are called only if it is the root cgroup.
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800900 *
Josef Bacik9092c712018-01-31 16:16:26 -0800901 * @priority is sc->priority, we take the number of objects and >> by priority
902 * in order to get the scan target.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700903 *
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800904 * Returns the number of reclaimed slab objects.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700905 */
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800906unsigned long shrink_slab(gfp_t gfp_mask, int nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800907 struct mem_cgroup *memcg,
Josef Bacik9092c712018-01-31 16:16:26 -0800908 int priority)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700909{
Kirill Tkhaib8e57ef2018-10-05 15:52:10 -0700910 unsigned long ret, freed = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700911 struct shrinker *shrinker;
wudean842c68a2021-04-27 17:40:41 +0800912 bool bypass = false;
913
914 trace_android_vh_shrink_slab_bypass(gfp_mask, nid, memcg, priority, &bypass);
915 if (bypass)
916 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700917
Yang Shifa1e5122019-08-02 21:48:44 -0700918 /*
919 * The root memcg might be allocated even though memcg is disabled
920 * via "cgroup_disable=memory" boot parameter. This could make
921 * mem_cgroup_is_root() return false, then just run memcg slab
922 * shrink, but skip global shrink. This may result in premature
923 * oom.
924 */
925 if (!mem_cgroup_disabled() && !mem_cgroup_is_root(memcg))
Kirill Tkhaib0dedc42018-08-17 15:48:14 -0700926 return shrink_slab_memcg(gfp_mask, nid, memcg, priority);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800927
Tetsuo Handae830c632018-04-05 16:23:35 -0700928 if (!down_read_trylock(&shrinker_rwsem))
Minchan Kimf06590b2011-05-24 17:11:11 -0700929 goto out;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700930
931 list_for_each_entry(shrinker, &shrinker_list, list) {
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800932 struct shrink_control sc = {
933 .gfp_mask = gfp_mask,
934 .nid = nid,
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800935 .memcg = memcg,
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800936 };
Vladimir Davydovec970972014-01-23 15:53:23 -0800937
Kirill Tkhai9b996462018-08-17 15:48:21 -0700938 ret = do_shrink_slab(&sc, shrinker, priority);
939 if (ret == SHRINK_EMPTY)
940 ret = 0;
941 freed += ret;
Minchan Kime4966122018-01-31 16:16:55 -0800942 /*
943 * Bail out if someone want to register a new shrinker to
Ethon Paul55b65a52020-06-04 16:49:10 -0700944 * prevent the registration from being stalled for long periods
Minchan Kime4966122018-01-31 16:16:55 -0800945 * by parallel ongoing shrinking.
946 */
947 if (rwsem_is_contended(&shrinker_rwsem)) {
948 freed = freed ? : 1;
949 break;
950 }
Linus Torvalds1da177e2005-04-16 15:20:36 -0700951 }
Johannes Weiner6b4f7792014-12-12 16:56:13 -0800952
Linus Torvalds1da177e2005-04-16 15:20:36 -0700953 up_read(&shrinker_rwsem);
Minchan Kimf06590b2011-05-24 17:11:11 -0700954out:
955 cond_resched();
Dave Chinner24f7c6b2013-08-28 10:17:56 +1000956 return freed;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700957}
Peifeng Li8c19c1e2022-02-28 15:25:30 +0800958EXPORT_SYMBOL_GPL(shrink_slab);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700959
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800960void drop_slab_node(int nid)
961{
962 unsigned long freed;
Vlastimil Babka1399af72021-09-02 14:59:53 -0700963 int shift = 0;
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800964
965 do {
966 struct mem_cgroup *memcg = NULL;
967
Chunxin Zang069c4112020-10-13 16:56:46 -0700968 if (fatal_signal_pending(current))
969 return;
970
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800971 freed = 0;
Vladimir Davydovaeed1d322018-08-17 15:48:17 -0700972 memcg = mem_cgroup_iter(NULL, NULL, NULL);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800973 do {
Josef Bacik9092c712018-01-31 16:16:26 -0800974 freed += shrink_slab(GFP_KERNEL, nid, memcg, 0);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800975 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)) != NULL);
Vlastimil Babka1399af72021-09-02 14:59:53 -0700976 } while ((freed >> shift++) > 1);
Vladimir Davydovcb731d62015-02-12 14:58:54 -0800977}
978
979void drop_slab(void)
980{
981 int nid;
982
983 for_each_online_node(nid)
984 drop_slab_node(nid);
985}
986
Linus Torvalds1da177e2005-04-16 15:20:36 -0700987static inline int is_page_cache_freeable(struct page *page)
988{
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700989 /*
990 * A freeable page cache page is referenced only by the caller
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400991 * that isolated the page, the page cache and optional buffer
992 * heads at page->private.
Johannes Weinerceddc3a2009-09-21 17:03:00 -0700993 */
Matthew Wilcox (Oracle)3efe62e2020-10-15 20:05:56 -0700994 int page_cache_pins = thp_nr_pages(page);
Matthew Wilcox67891ff2018-06-10 07:34:39 -0400995 return page_count(page) - page_has_private(page) == 1 + page_cache_pins;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700996}
997
Yang Shicb165562019-11-30 17:55:28 -0800998static int may_write_to_inode(struct inode *inode)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700999{
Christoph Lameter930d9152006-01-08 01:00:47 -08001000 if (current->flags & PF_SWAPWRITE)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001001 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001002 if (!inode_write_congested(inode))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001003 return 1;
Tejun Heo703c2702015-05-22 17:13:44 -04001004 if (inode_to_bdi(inode) == current->backing_dev_info)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001005 return 1;
1006 return 0;
1007}
1008
1009/*
1010 * We detected a synchronous write error writing a page out. Probably
1011 * -ENOSPC. We need to propagate that into the address_space for a subsequent
1012 * fsync(), msync() or close().
1013 *
1014 * The tricky part is that after writepage we cannot touch the mapping: nothing
1015 * prevents it from being freed up. But we have a ref on the page and once
1016 * that page is locked, the mapping is pinned.
1017 *
1018 * We're allowed to run sleeping lock_page() here because we know the caller has
1019 * __GFP_FS.
1020 */
1021static void handle_write_error(struct address_space *mapping,
1022 struct page *page, int error)
1023{
Jens Axboe7eaceac2011-03-10 08:52:07 +01001024 lock_page(page);
Guillaume Chazarain3e9f45b2007-05-08 00:23:25 -07001025 if (page_mapping(page) == mapping)
1026 mapping_set_error(mapping, error);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001027 unlock_page(page);
1028}
1029
Christoph Lameter04e62a22006-06-23 02:03:38 -07001030/* possible outcome of pageout() */
1031typedef enum {
1032 /* failed to write page out, page is locked */
1033 PAGE_KEEP,
1034 /* move page to the active list, page is locked */
1035 PAGE_ACTIVATE,
1036 /* page has been sent to the disk successfully, page is unlocked */
1037 PAGE_SUCCESS,
1038 /* page is clean and locked */
1039 PAGE_CLEAN,
1040} pageout_t;
1041
Linus Torvalds1da177e2005-04-16 15:20:36 -07001042/*
Andrew Morton1742f192006-03-22 00:08:21 -08001043 * pageout is called by shrink_page_list() for each dirty page.
1044 * Calls ->writepage().
Linus Torvalds1da177e2005-04-16 15:20:36 -07001045 */
Yang Shicb165562019-11-30 17:55:28 -08001046static pageout_t pageout(struct page *page, struct address_space *mapping)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001047{
1048 /*
1049 * If the page is dirty, only perform writeback if that write
1050 * will be non-blocking. To prevent this allocation from being
1051 * stalled by pagecache activity. But note that there may be
1052 * stalls if we need to run get_block(). We could test
1053 * PagePrivate for that.
1054 *
Al Viro81742022014-04-03 03:17:43 -04001055 * If this process is currently in __generic_file_write_iter() against
Linus Torvalds1da177e2005-04-16 15:20:36 -07001056 * this page's queue, we can perform writeback even if that
1057 * will block.
1058 *
1059 * If the page is swapcache, write it back even if that would
1060 * block, for some throttling. This happens by accident, because
1061 * swap_backing_dev_info is bust: it doesn't reflect the
1062 * congestion state of the swapdevs. Easy to fix, if needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001063 */
1064 if (!is_page_cache_freeable(page))
1065 return PAGE_KEEP;
1066 if (!mapping) {
1067 /*
1068 * Some data journaling orphaned pages can have
1069 * page->mapping == NULL while being dirty with clean buffers.
1070 */
David Howells266cf652009-04-03 16:42:36 +01001071 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001072 if (try_to_free_buffers(page)) {
1073 ClearPageDirty(page);
Mitchel Humpherysb1de0d12014-06-06 14:38:30 -07001074 pr_info("%s: orphaned page\n", __func__);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001075 return PAGE_CLEAN;
1076 }
1077 }
1078 return PAGE_KEEP;
1079 }
1080 if (mapping->a_ops->writepage == NULL)
1081 return PAGE_ACTIVATE;
Yang Shicb165562019-11-30 17:55:28 -08001082 if (!may_write_to_inode(mapping->host))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001083 return PAGE_KEEP;
1084
1085 if (clear_page_dirty_for_io(page)) {
1086 int res;
1087 struct writeback_control wbc = {
1088 .sync_mode = WB_SYNC_NONE,
1089 .nr_to_write = SWAP_CLUSTER_MAX,
OGAWA Hirofumi111ebb62006-06-23 02:03:26 -07001090 .range_start = 0,
1091 .range_end = LLONG_MAX,
Linus Torvalds1da177e2005-04-16 15:20:36 -07001092 .for_reclaim = 1,
1093 };
1094
1095 SetPageReclaim(page);
1096 res = mapping->a_ops->writepage(page, &wbc);
1097 if (res < 0)
1098 handle_write_error(mapping, page, res);
Zach Brown994fc28c2005-12-15 14:28:17 -08001099 if (res == AOP_WRITEPAGE_ACTIVATE) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001100 ClearPageReclaim(page);
1101 return PAGE_ACTIVATE;
1102 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001103
Linus Torvalds1da177e2005-04-16 15:20:36 -07001104 if (!PageWriteback(page)) {
1105 /* synchronous write or broken a_ops? */
1106 ClearPageReclaim(page);
1107 }
yalin wang3aa23852016-01-14 15:18:30 -08001108 trace_mm_vmscan_writepage(page);
Mel Gormanc4a25632016-07-28 15:46:23 -07001109 inc_node_page_state(page, NR_VMSCAN_WRITE);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001110 return PAGE_SUCCESS;
1111 }
1112
1113 return PAGE_CLEAN;
1114}
1115
Andrew Mortona649fd92006-10-17 00:09:36 -07001116/*
Nick Piggine2867812008-07-25 19:45:30 -07001117 * Same as remove_mapping, but if the page is removed from the mapping, it
1118 * gets returned with a refcount of 0.
Andrew Mortona649fd92006-10-17 00:09:36 -07001119 */
Johannes Weinera5289102014-04-03 14:47:51 -07001120static int __remove_mapping(struct address_space *mapping, struct page *page,
Johannes Weinerb9107182019-11-30 17:55:59 -08001121 bool reclaimed, struct mem_cgroup *target_memcg)
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001122{
Huang Yingbd4c82c22017-09-06 16:22:49 -07001123 int refcount;
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001124 void *shadow = NULL;
Greg Thelenc4843a72015-05-22 17:13:16 -04001125
Nick Piggin28e4d962006-09-25 23:31:23 -07001126 BUG_ON(!PageLocked(page));
1127 BUG_ON(mapping != page_mapping(page));
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001128
Johannes Weiner30472502021-09-02 14:53:18 -07001129 xa_lock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001130 /*
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001131 * The non racy check for a busy page.
1132 *
1133 * Must be careful with the order of the tests. When someone has
1134 * a ref to the page, it may be possible that they dirty it then
1135 * drop the reference. So if PageDirty is tested before page_count
1136 * here, then the following race may occur:
1137 *
1138 * get_user_pages(&page);
1139 * [user mapping goes away]
1140 * write_to(page);
1141 * !PageDirty(page) [good]
1142 * SetPageDirty(page);
1143 * put_page(page);
1144 * !page_count(page) [good, discard it]
1145 *
1146 * [oops, our write_to data is lost]
1147 *
1148 * Reversing the order of the tests ensures such a situation cannot
1149 * escape unnoticed. The smp_rmb is needed to ensure the page->flags
Joonsoo Kim0139aa72016-05-19 17:10:49 -07001150 * load is not satisfied before that of page->_refcount.
Nick Piggin0fd0e6b2006-09-27 01:50:02 -07001151 *
1152 * Note that if SetPageDirty is always performed via set_page_dirty,
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001153 * and thus under the i_pages lock, then this ordering is not required.
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001154 */
William Kucharski906d2782019-10-18 20:20:33 -07001155 refcount = 1 + compound_nr(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001156 if (!page_ref_freeze(page, refcount))
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001157 goto cannot_free;
Jiang Biao1c4c3b92018-08-21 21:53:13 -07001158 /* note: atomic_cmpxchg in page_ref_freeze provides the smp_rmb */
Nick Piggine2867812008-07-25 19:45:30 -07001159 if (unlikely(PageDirty(page))) {
Huang Yingbd4c82c22017-09-06 16:22:49 -07001160 page_ref_unfreeze(page, refcount);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001161 goto cannot_free;
Nick Piggine2867812008-07-25 19:45:30 -07001162 }
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001163
1164 if (PageSwapCache(page)) {
1165 swp_entry_t swap = { .val = page_private(page) };
Yu Zhaoa1537a62022-01-27 20:32:37 -07001166
1167 /* get a shadow entry before mem_cgroup_swapout() clears page_memcg() */
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001168 if (reclaimed && !mapping_exiting(mapping))
1169 shadow = workingset_eviction(page, target_memcg);
Yu Zhaoa1537a62022-01-27 20:32:37 -07001170 mem_cgroup_swapout(page, swap);
Joonsoo Kimaae466b2020-08-11 18:30:50 -07001171 __delete_from_swap_cache(page, swap, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001172 xa_unlock_irq(&mapping->i_pages);
Minchan Kim75f6d6d2017-07-06 15:37:21 -07001173 put_swap_page(page, swap);
Nick Piggine2867812008-07-25 19:45:30 -07001174 } else {
Linus Torvalds6072d132010-12-01 13:35:19 -05001175 void (*freepage)(struct page *);
1176
1177 freepage = mapping->a_ops->freepage;
Johannes Weinera5289102014-04-03 14:47:51 -07001178 /*
1179 * Remember a shadow entry for reclaimed file cache in
1180 * order to detect refaults, thus thrashing, later on.
1181 *
1182 * But don't store shadows in an address space that is
dylan-meiners238c3042020-08-06 23:26:29 -07001183 * already exiting. This is not just an optimization,
Johannes Weinera5289102014-04-03 14:47:51 -07001184 * inode reclaim needs to empty out the radix tree or
1185 * the nodes are lost. Don't plant shadows behind its
1186 * back.
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001187 *
1188 * We also don't store shadows for DAX mappings because the
1189 * only page cache pages found in these are zero pages
1190 * covering holes, and because we don't want to mix DAX
1191 * exceptional entries and shadow exceptional entries in the
Matthew Wilcoxb93b0162018-04-10 16:36:56 -07001192 * same address_space.
Johannes Weinera5289102014-04-03 14:47:51 -07001193 */
Huang Ying9de4f222020-04-06 20:04:41 -07001194 if (reclaimed && page_is_file_lru(page) &&
Ross Zwislerf9fe48b2016-01-22 15:10:40 -08001195 !mapping_exiting(mapping) && !dax_mapping(mapping))
Johannes Weinerb9107182019-11-30 17:55:59 -08001196 shadow = workingset_eviction(page, target_memcg);
Johannes Weiner62cccb82016-03-15 14:57:22 -07001197 __delete_from_page_cache(page, shadow);
Johannes Weiner30472502021-09-02 14:53:18 -07001198 xa_unlock_irq(&mapping->i_pages);
Linus Torvalds6072d132010-12-01 13:35:19 -05001199
1200 if (freepage != NULL)
1201 freepage(page);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001202 }
1203
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001204 return 1;
1205
1206cannot_free:
Johannes Weiner30472502021-09-02 14:53:18 -07001207 xa_unlock_irq(&mapping->i_pages);
Christoph Lameter49d2e9c2006-01-08 01:00:48 -08001208 return 0;
1209}
1210
Linus Torvalds1da177e2005-04-16 15:20:36 -07001211/*
Nick Piggine2867812008-07-25 19:45:30 -07001212 * Attempt to detach a locked page from its ->mapping. If it is dirty or if
1213 * someone else has a ref on the page, abort and return 0. If it was
1214 * successfully detached, return 1. Assumes the caller has a single ref on
1215 * this page.
1216 */
1217int remove_mapping(struct address_space *mapping, struct page *page)
1218{
Johannes Weinerb9107182019-11-30 17:55:59 -08001219 if (__remove_mapping(mapping, page, false, NULL)) {
Nick Piggine2867812008-07-25 19:45:30 -07001220 /*
1221 * Unfreezing the refcount with 1 rather than 2 effectively
1222 * drops the pagecache ref for us without requiring another
1223 * atomic operation.
1224 */
Joonsoo Kimfe896d12016-03-17 14:19:26 -07001225 page_ref_unfreeze(page, 1);
Nick Piggine2867812008-07-25 19:45:30 -07001226 return 1;
1227 }
1228 return 0;
1229}
1230
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001231/**
1232 * putback_lru_page - put previously isolated page onto appropriate LRU list
1233 * @page: page to be put back to appropriate lru list
1234 *
1235 * Add previously isolated @page to appropriate LRU list.
1236 * Page may still be unevictable for other reasons.
1237 *
1238 * lru_lock must not be held, interrupts must be enabled.
1239 */
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001240void putback_lru_page(struct page *page)
1241{
Shakeel Butt9c4e6b12018-02-21 14:45:28 -08001242 lru_cache_add(page);
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001243 put_page(page); /* drop ref from isolate */
1244}
1245
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001246enum page_references {
1247 PAGEREF_RECLAIM,
1248 PAGEREF_RECLAIM_CLEAN,
Johannes Weiner645747462010-03-05 13:42:22 -08001249 PAGEREF_KEEP,
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001250 PAGEREF_ACTIVATE,
1251};
1252
1253static enum page_references page_check_references(struct page *page,
1254 struct scan_control *sc)
1255{
Johannes Weiner645747462010-03-05 13:42:22 -08001256 int referenced_ptes, referenced_page;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001257 unsigned long vm_flags;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001258
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07001259 referenced_ptes = page_referenced(page, 1, sc->target_mem_cgroup,
1260 &vm_flags);
Johannes Weiner645747462010-03-05 13:42:22 -08001261 referenced_page = TestClearPageReferenced(page);
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001262
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001263 /*
1264 * Mlock lost the isolation race with us. Let try_to_unmap()
1265 * move the page to the unevictable list.
1266 */
1267 if (vm_flags & VM_LOCKED)
1268 return PAGEREF_RECLAIM;
1269
Johannes Weiner645747462010-03-05 13:42:22 -08001270 if (referenced_ptes) {
Johannes Weiner645747462010-03-05 13:42:22 -08001271 /*
1272 * All mapped pages start out with page table
1273 * references from the instantiating fault, so we need
1274 * to look twice if a mapped file page is used more
1275 * than once.
1276 *
1277 * Mark it and spare it for another trip around the
1278 * inactive list. Another page table reference will
1279 * lead to its activation.
1280 *
1281 * Note: the mark is set for activated pages as well
1282 * so that recently deactivated but used pages are
1283 * quickly recovered.
1284 */
1285 SetPageReferenced(page);
1286
Konstantin Khlebnikov34dbc672012-01-10 15:06:59 -08001287 if (referenced_page || referenced_ptes > 1)
Johannes Weiner645747462010-03-05 13:42:22 -08001288 return PAGEREF_ACTIVATE;
1289
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001290 /*
1291 * Activate file-backed executable pages after first usage.
1292 */
Joonsoo Kimb5181542020-08-11 18:30:40 -07001293 if ((vm_flags & VM_EXEC) && !PageSwapBacked(page))
Konstantin Khlebnikovc909e992012-01-10 15:07:03 -08001294 return PAGEREF_ACTIVATE;
1295
Johannes Weiner645747462010-03-05 13:42:22 -08001296 return PAGEREF_KEEP;
1297 }
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001298
1299 /* Reclaim if clean, defer dirty pages to writeback */
KOSAKI Motohiro2e302442010-10-26 14:21:46 -07001300 if (referenced_page && !PageSwapBacked(page))
Johannes Weiner645747462010-03-05 13:42:22 -08001301 return PAGEREF_RECLAIM_CLEAN;
1302
1303 return PAGEREF_RECLAIM;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001304}
1305
Mel Gormane2be15f2013-07-03 15:01:57 -07001306/* Check if a page is dirty or under writeback */
1307static void page_check_dirty_writeback(struct page *page,
1308 bool *dirty, bool *writeback)
1309{
Mel Gormanb4597222013-07-03 15:02:05 -07001310 struct address_space *mapping;
1311
Mel Gormane2be15f2013-07-03 15:01:57 -07001312 /*
1313 * Anonymous pages are not handled by flushers and must be written
1314 * from reclaim context. Do not stall reclaim based on them
1315 */
Huang Ying9de4f222020-04-06 20:04:41 -07001316 if (!page_is_file_lru(page) ||
Shaohua Li802a3a92017-05-03 14:52:32 -07001317 (PageAnon(page) && !PageSwapBacked(page))) {
Mel Gormane2be15f2013-07-03 15:01:57 -07001318 *dirty = false;
1319 *writeback = false;
1320 return;
1321 }
1322
1323 /* By default assume that the page flags are accurate */
1324 *dirty = PageDirty(page);
1325 *writeback = PageWriteback(page);
Mel Gormanb4597222013-07-03 15:02:05 -07001326
1327 /* Verify dirty/writeback state if the filesystem supports it */
1328 if (!page_has_private(page))
1329 return;
1330
1331 mapping = page_mapping(page);
1332 if (mapping && mapping->a_ops->is_dirty_writeback)
1333 mapping->a_ops->is_dirty_writeback(page, dirty, writeback);
Mel Gormane2be15f2013-07-03 15:01:57 -07001334}
1335
Dave Hansen26aa2d12021-09-02 14:59:16 -07001336static struct page *alloc_demote_page(struct page *page, unsigned long node)
1337{
1338 struct migration_target_control mtc = {
1339 /*
1340 * Allocate from 'node', or fail quickly and quietly.
1341 * When this happens, 'page' will likely just be discarded
1342 * instead of migrated.
1343 */
1344 .gfp_mask = (GFP_HIGHUSER_MOVABLE & ~__GFP_RECLAIM) |
1345 __GFP_THISNODE | __GFP_NOWARN |
1346 __GFP_NOMEMALLOC | GFP_NOWAIT,
1347 .nid = node
1348 };
1349
1350 return alloc_migration_target(page, (unsigned long)&mtc);
1351}
1352
1353/*
1354 * Take pages on @demote_list and attempt to demote them to
1355 * another node. Pages which are not demoted are left on
1356 * @demote_pages.
1357 */
1358static unsigned int demote_page_list(struct list_head *demote_pages,
1359 struct pglist_data *pgdat)
1360{
1361 int target_nid = next_demotion_node(pgdat->node_id);
1362 unsigned int nr_succeeded;
1363 int err;
1364
1365 if (list_empty(demote_pages))
1366 return 0;
1367
1368 if (target_nid == NUMA_NO_NODE)
1369 return 0;
1370
1371 /* Demotion ignores all cpuset and mempolicy settings */
1372 err = migrate_pages(demote_pages, alloc_demote_page, NULL,
1373 target_nid, MIGRATE_ASYNC, MR_DEMOTION,
1374 &nr_succeeded);
1375
Yang Shi668e4142021-09-02 14:59:19 -07001376 if (current_is_kswapd())
1377 __count_vm_events(PGDEMOTE_KSWAPD, nr_succeeded);
1378 else
1379 __count_vm_events(PGDEMOTE_DIRECT, nr_succeeded);
1380
Dave Hansen26aa2d12021-09-02 14:59:16 -07001381 return nr_succeeded;
1382}
1383
Nick Piggine2867812008-07-25 19:45:30 -07001384/*
Andrew Morton1742f192006-03-22 00:08:21 -08001385 * shrink_page_list() returns the number of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07001386 */
Maninder Singh730ec8c2020-06-03 16:01:18 -07001387static unsigned int shrink_page_list(struct list_head *page_list,
1388 struct pglist_data *pgdat,
1389 struct scan_control *sc,
Maninder Singh730ec8c2020-06-03 16:01:18 -07001390 struct reclaim_stat *stat,
1391 bool ignore_references)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001392{
1393 LIST_HEAD(ret_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001394 LIST_HEAD(free_pages);
Dave Hansen26aa2d12021-09-02 14:59:16 -07001395 LIST_HEAD(demote_pages);
Maninder Singh730ec8c2020-06-03 16:01:18 -07001396 unsigned int nr_reclaimed = 0;
1397 unsigned int pgactivate = 0;
Dave Hansen26aa2d12021-09-02 14:59:16 -07001398 bool do_demote_pass;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001399
Kirill Tkhai060f0052019-03-05 15:48:15 -08001400 memset(stat, 0, sizeof(*stat));
Linus Torvalds1da177e2005-04-16 15:20:36 -07001401 cond_resched();
Dave Hansen26aa2d12021-09-02 14:59:16 -07001402 do_demote_pass = can_demote(pgdat->node_id, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001403
Dave Hansen26aa2d12021-09-02 14:59:16 -07001404retry:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001405 while (!list_empty(page_list)) {
1406 struct address_space *mapping;
1407 struct page *page;
Minchan Kim8940b342019-09-25 16:49:11 -07001408 enum page_references references = PAGEREF_RECLAIM;
Kirill Tkhai4b793062020-04-01 21:10:18 -07001409 bool dirty, writeback, may_enter_fs;
Yang Shi98879b32019-07-11 20:59:30 -07001410 unsigned int nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001411
1412 cond_resched();
1413
1414 page = lru_to_page(page_list);
1415 list_del(&page->lru);
1416
Nick Piggin529ae9a2008-08-02 12:01:03 +02001417 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001418 goto keep;
1419
Sasha Levin309381fea2014-01-23 15:52:54 -08001420 VM_BUG_ON_PAGE(PageActive(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001421
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07001422 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07001423
1424 /* Account the number of base pages even though THP */
1425 sc->nr_scanned += nr_pages;
Christoph Lameter80e43422006-02-11 17:55:53 -08001426
Hugh Dickins39b5f292012-10-08 16:33:18 -07001427 if (unlikely(!page_evictable(page)))
Minchan Kimad6b6702017-05-03 14:54:13 -07001428 goto activate_locked;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001429
Johannes Weinera6dc60f82009-03-31 15:19:30 -07001430 if (!sc->may_unmap && page_mapped(page))
Christoph Lameter80e43422006-02-11 17:55:53 -08001431 goto keep_locked;
1432
Yu Zhaoafd94c92022-01-27 20:43:22 -07001433 /* page_update_gen() tried to promote this page? */
1434 if (lru_gen_enabled() && !ignore_references &&
1435 page_mapped(page) && PageReferenced(page))
1436 goto keep_locked;
1437
Andy Whitcroftc661b072007-08-22 14:01:26 -07001438 may_enter_fs = (sc->gfp_mask & __GFP_FS) ||
1439 (PageSwapCache(page) && (sc->gfp_mask & __GFP_IO));
1440
Mel Gorman283aba92013-07-03 15:01:51 -07001441 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07001442 * The number of dirty pages determines if a node is marked
Mel Gormane2be15f2013-07-03 15:01:57 -07001443 * reclaim_congested which affects wait_iff_congested. kswapd
1444 * will stall and start writing pages if the tail of the LRU
1445 * is all dirty unqueued pages.
1446 */
1447 page_check_dirty_writeback(page, &dirty, &writeback);
1448 if (dirty || writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001449 stat->nr_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001450
1451 if (dirty && !writeback)
Kirill Tkhai060f0052019-03-05 15:48:15 -08001452 stat->nr_unqueued_dirty++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001453
Mel Gormand04e8ac2013-07-03 15:02:03 -07001454 /*
1455 * Treat this page as congested if the underlying BDI is or if
1456 * pages are cycling through the LRU so quickly that the
1457 * pages marked for immediate reclaim are making it to the
1458 * end of the LRU a second time.
1459 */
Mel Gormane2be15f2013-07-03 15:01:57 -07001460 mapping = page_mapping(page);
Jamie Liu1da58ee2014-12-10 15:43:20 -08001461 if (((dirty || writeback) && mapping &&
Tejun Heo703c2702015-05-22 17:13:44 -04001462 inode_write_congested(mapping->host)) ||
Mel Gormand04e8ac2013-07-03 15:02:03 -07001463 (writeback && PageReclaim(page)))
Kirill Tkhai060f0052019-03-05 15:48:15 -08001464 stat->nr_congested++;
Mel Gormane2be15f2013-07-03 15:01:57 -07001465
1466 /*
Mel Gorman283aba92013-07-03 15:01:51 -07001467 * If a page at the tail of the LRU is under writeback, there
1468 * are three cases to consider.
1469 *
1470 * 1) If reclaim is encountering an excessive number of pages
1471 * under writeback and this page is both under writeback and
1472 * PageReclaim then it indicates that pages are being queued
1473 * for IO but are being recycled through the LRU before the
1474 * IO can complete. Waiting on the page itself risks an
1475 * indefinite stall if it is impossible to writeback the
1476 * page due to IO error or disconnected storage so instead
Mel Gormanb1a6f212013-07-03 15:01:58 -07001477 * note that the LRU is being scanned too quickly and the
1478 * caller can stall after page list has been processed.
Mel Gorman283aba92013-07-03 15:01:51 -07001479 *
Tejun Heo97c93412015-05-22 18:23:36 -04001480 * 2) Global or new memcg reclaim encounters a page that is
Michal Hockoecf5fc62015-08-04 14:36:58 -07001481 * not marked for immediate reclaim, or the caller does not
1482 * have __GFP_FS (or __GFP_IO if it's simply going to swap,
1483 * not to fs). In this case mark the page for immediate
Tejun Heo97c93412015-05-22 18:23:36 -04001484 * reclaim and continue scanning.
Mel Gorman283aba92013-07-03 15:01:51 -07001485 *
Michal Hockoecf5fc62015-08-04 14:36:58 -07001486 * Require may_enter_fs because we would wait on fs, which
1487 * may not have submitted IO yet. And the loop driver might
Mel Gorman283aba92013-07-03 15:01:51 -07001488 * enter reclaim, and deadlock if it waits on a page for
1489 * which it is needed to do the write (loop masks off
1490 * __GFP_IO|__GFP_FS for this reason); but more thought
1491 * would probably show more reasons.
1492 *
Hugh Dickins7fadc822015-09-08 15:03:46 -07001493 * 3) Legacy memcg encounters a page that is already marked
Mel Gorman283aba92013-07-03 15:01:51 -07001494 * PageReclaim. memcg does not have any dirty pages
1495 * throttling so we could easily OOM just because too many
1496 * pages are in writeback and there is nothing else to
1497 * reclaim. Wait for the writeback to complete.
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001498 *
1499 * In cases 1) and 2) we activate the pages to get them out of
1500 * the way while we continue scanning for clean pages on the
1501 * inactive list and refilling from the active list. The
1502 * observation here is that waiting for disk writes is more
1503 * expensive than potentially causing reloads down the line.
1504 * Since they're marked for immediate reclaim, they won't put
1505 * memory pressure on the cache working set any longer than it
1506 * takes to write them to disk.
Mel Gorman283aba92013-07-03 15:01:51 -07001507 */
Andy Whitcroftc661b072007-08-22 14:01:26 -07001508 if (PageWriteback(page)) {
Mel Gorman283aba92013-07-03 15:01:51 -07001509 /* Case 1 above */
1510 if (current_is_kswapd() &&
1511 PageReclaim(page) &&
Mel Gorman599d0c92016-07-28 15:45:31 -07001512 test_bit(PGDAT_WRITEBACK, &pgdat->flags)) {
Kirill Tkhai060f0052019-03-05 15:48:15 -08001513 stat->nr_immediate++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001514 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001515
1516 /* Case 2 above */
Johannes Weinerb5ead352019-11-30 17:55:40 -08001517 } else if (writeback_throttling_sane(sc) ||
Michal Hockoecf5fc62015-08-04 14:36:58 -07001518 !PageReclaim(page) || !may_enter_fs) {
Hugh Dickinsc3b94f42012-07-31 16:45:59 -07001519 /*
1520 * This is slightly racy - end_page_writeback()
1521 * might have just cleared PageReclaim, then
1522 * setting PageReclaim here end up interpreted
1523 * as PageReadahead - but that does not matter
1524 * enough to care. What we do want is for this
1525 * page to have PageReclaim set next time memcg
1526 * reclaim reaches the tests above, so it will
1527 * then wait_on_page_writeback() to avoid OOM;
1528 * and it's also appropriate in global reclaim.
1529 */
1530 SetPageReclaim(page);
Kirill Tkhai060f0052019-03-05 15:48:15 -08001531 stat->nr_writeback++;
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001532 goto activate_locked;
Mel Gorman283aba92013-07-03 15:01:51 -07001533
1534 /* Case 3 above */
1535 } else {
Hugh Dickins7fadc822015-09-08 15:03:46 -07001536 unlock_page(page);
Mel Gorman283aba92013-07-03 15:01:51 -07001537 wait_on_page_writeback(page);
Hugh Dickins7fadc822015-09-08 15:03:46 -07001538 /* then go back and try same page again */
1539 list_add_tail(&page->lru, page_list);
1540 continue;
Michal Hockoe62e3842012-07-31 16:45:55 -07001541 }
Andy Whitcroftc661b072007-08-22 14:01:26 -07001542 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001543
Minchan Kim8940b342019-09-25 16:49:11 -07001544 if (!ignore_references)
Minchan Kim02c6de82012-10-08 16:31:55 -07001545 references = page_check_references(page, sc);
1546
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001547 switch (references) {
1548 case PAGEREF_ACTIVATE:
Linus Torvalds1da177e2005-04-16 15:20:36 -07001549 goto activate_locked;
Johannes Weiner645747462010-03-05 13:42:22 -08001550 case PAGEREF_KEEP:
Yang Shi98879b32019-07-11 20:59:30 -07001551 stat->nr_ref_keep += nr_pages;
Johannes Weiner645747462010-03-05 13:42:22 -08001552 goto keep_locked;
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001553 case PAGEREF_RECLAIM:
1554 case PAGEREF_RECLAIM_CLEAN:
1555 ; /* try to reclaim the page below */
1556 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001557
Linus Torvalds1da177e2005-04-16 15:20:36 -07001558 /*
Dave Hansen26aa2d12021-09-02 14:59:16 -07001559 * Before reclaiming the page, try to relocate
1560 * its contents to another node.
1561 */
1562 if (do_demote_pass &&
1563 (thp_migration_supported() || !PageTransHuge(page))) {
1564 list_add(&page->lru, &demote_pages);
1565 unlock_page(page);
1566 continue;
1567 }
1568
1569 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001570 * Anonymous process memory has backing store?
1571 * Try to allocate it some swap space here.
Shaohua Li802a3a92017-05-03 14:52:32 -07001572 * Lazyfree page could be freed directly
Linus Torvalds1da177e2005-04-16 15:20:36 -07001573 */
Huang Yingbd4c82c22017-09-06 16:22:49 -07001574 if (PageAnon(page) && PageSwapBacked(page)) {
1575 if (!PageSwapCache(page)) {
1576 if (!(sc->gfp_mask & __GFP_IO))
1577 goto keep_locked;
Linus Torvaldsfeb889f2021-01-16 15:34:57 -08001578 if (page_maybe_dma_pinned(page))
1579 goto keep_locked;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001580 if (PageTransHuge(page)) {
1581 /* cannot split THP, skip it */
1582 if (!can_split_huge_page(page, NULL))
1583 goto activate_locked;
1584 /*
1585 * Split pages without a PMD map right
1586 * away. Chances are some or all of the
1587 * tail pages can be freed without IO.
1588 */
1589 if (!compound_mapcount(page) &&
1590 split_huge_page_to_list(page,
1591 page_list))
1592 goto activate_locked;
1593 }
1594 if (!add_to_swap(page)) {
1595 if (!PageTransHuge(page))
Yang Shi98879b32019-07-11 20:59:30 -07001596 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001597 /* Fallback to swap normal pages */
1598 if (split_huge_page_to_list(page,
1599 page_list))
1600 goto activate_locked;
Huang Yingfe490cc2017-09-06 16:22:52 -07001601#ifdef CONFIG_TRANSPARENT_HUGEPAGE
1602 count_vm_event(THP_SWPOUT_FALLBACK);
1603#endif
Huang Yingbd4c82c22017-09-06 16:22:49 -07001604 if (!add_to_swap(page))
Yang Shi98879b32019-07-11 20:59:30 -07001605 goto activate_locked_split;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001606 }
Minchan Kim0f074652017-07-06 15:37:24 -07001607
Kirill Tkhai4b793062020-04-01 21:10:18 -07001608 may_enter_fs = true;
Huang Yingbd4c82c22017-09-06 16:22:49 -07001609
1610 /* Adding to swap updated mapping */
1611 mapping = page_mapping(page);
Minchan Kim0f074652017-07-06 15:37:24 -07001612 }
Kirill A. Shutemov7751b2d2016-07-26 15:25:56 -07001613 } else if (unlikely(PageTransHuge(page))) {
1614 /* Split file THP */
1615 if (split_huge_page_to_list(page, page_list))
1616 goto keep_locked;
Mel Gormane2be15f2013-07-03 15:01:57 -07001617 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001618
1619 /*
Yang Shi98879b32019-07-11 20:59:30 -07001620 * THP may get split above, need minus tail pages and update
1621 * nr_pages to avoid accounting tail pages twice.
1622 *
1623 * The tail pages that are added into swap cache successfully
1624 * reach here.
1625 */
1626 if ((nr_pages > 1) && !PageTransHuge(page)) {
1627 sc->nr_scanned -= (nr_pages - 1);
1628 nr_pages = 1;
1629 }
1630
1631 /*
Linus Torvalds1da177e2005-04-16 15:20:36 -07001632 * The page is mapped into the page tables of one or more
1633 * processes. Try to unmap it here.
1634 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001635 if (page_mapped(page)) {
Shakeel Butt013339d2020-12-14 19:06:39 -08001636 enum ttu_flags flags = TTU_BATCH_FLUSH;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001637 bool was_swapbacked = PageSwapBacked(page);
Huang Yingbd4c82c22017-09-06 16:22:49 -07001638
1639 if (unlikely(PageTransHuge(page)))
1640 flags |= TTU_SPLIT_HUGE_PMD;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001641
Yang Shi1fb08ac2021-06-30 18:52:01 -07001642 try_to_unmap(page, flags);
1643 if (page_mapped(page)) {
Yang Shi98879b32019-07-11 20:59:30 -07001644 stat->nr_unmap_fail += nr_pages;
Jaewon Kim1f318a92020-06-03 16:01:15 -07001645 if (!was_swapbacked && PageSwapBacked(page))
1646 stat->nr_lazyfree_fail += nr_pages;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001647 goto activate_locked;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001648 }
1649 }
1650
1651 if (PageDirty(page)) {
Mel Gormanee728862011-10-31 17:07:38 -07001652 /*
Johannes Weiner4eda4822017-02-24 14:56:20 -08001653 * Only kswapd can writeback filesystem pages
1654 * to avoid risk of stack overflow. But avoid
1655 * injecting inefficient single-page IO into
1656 * flusher writeback as much as possible: only
1657 * write pages when we've encountered many
1658 * dirty pages, and when we've already scanned
1659 * the rest of the LRU for clean pages and see
1660 * the same dirty pages again (PageReclaim).
Mel Gormanee728862011-10-31 17:07:38 -07001661 */
Huang Ying9de4f222020-04-06 20:04:41 -07001662 if (page_is_file_lru(page) &&
Johannes Weiner4eda4822017-02-24 14:56:20 -08001663 (!current_is_kswapd() || !PageReclaim(page) ||
1664 !test_bit(PGDAT_DIRTY, &pgdat->flags))) {
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001665 /*
1666 * Immediately reclaim when written back.
1667 * Similar in principal to deactivate_page()
1668 * except we already have the page isolated
1669 * and know it's dirty
1670 */
Mel Gormanc4a25632016-07-28 15:46:23 -07001671 inc_node_page_state(page, NR_VMSCAN_IMMEDIATE);
Mel Gorman49ea7eb2011-10-31 17:07:59 -07001672 SetPageReclaim(page);
1673
Johannes Weinerc55e8d02017-02-24 14:56:23 -08001674 goto activate_locked;
Mel Gormanee728862011-10-31 17:07:38 -07001675 }
1676
Johannes Weinerdfc8d632010-03-05 13:42:19 -08001677 if (references == PAGEREF_RECLAIM_CLEAN)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001678 goto keep_locked;
Andrew Morton4dd4b922008-03-24 12:29:52 -07001679 if (!may_enter_fs)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001680 goto keep_locked;
Christoph Lameter52a83632006-02-01 03:05:28 -08001681 if (!sc->may_writepage)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001682 goto keep_locked;
1683
Mel Gormand950c942015-09-04 15:47:35 -07001684 /*
1685 * Page is dirty. Flush the TLB if a writable entry
1686 * potentially exists to avoid CPU writes after IO
1687 * starts and then write it out here.
1688 */
1689 try_to_unmap_flush_dirty();
Yang Shicb165562019-11-30 17:55:28 -08001690 switch (pageout(page, mapping)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001691 case PAGE_KEEP:
1692 goto keep_locked;
1693 case PAGE_ACTIVATE:
1694 goto activate_locked;
1695 case PAGE_SUCCESS:
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07001696 stat->nr_pageout += thp_nr_pages(page);
Johannes Weiner96f8bf42020-06-03 16:03:09 -07001697
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001698 if (PageWriteback(page))
Mel Gorman41ac1992012-05-29 15:06:19 -07001699 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001700 if (PageDirty(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001701 goto keep;
KOSAKI Motohiro7d3579e2010-10-26 14:21:42 -07001702
Linus Torvalds1da177e2005-04-16 15:20:36 -07001703 /*
1704 * A synchronous write - probably a ramdisk. Go
1705 * ahead and try to reclaim the page.
1706 */
Nick Piggin529ae9a2008-08-02 12:01:03 +02001707 if (!trylock_page(page))
Linus Torvalds1da177e2005-04-16 15:20:36 -07001708 goto keep;
1709 if (PageDirty(page) || PageWriteback(page))
1710 goto keep_locked;
1711 mapping = page_mapping(page);
Gustavo A. R. Silva01359eb2020-12-14 19:15:00 -08001712 fallthrough;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001713 case PAGE_CLEAN:
1714 ; /* try to free the page below */
1715 }
1716 }
1717
1718 /*
1719 * If the page has buffers, try to free the buffer mappings
1720 * associated with this page. If we succeed we try to free
1721 * the page as well.
1722 *
1723 * We do this even if the page is PageDirty().
1724 * try_to_release_page() does not perform I/O, but it is
1725 * possible for a page to have PageDirty set, but it is actually
1726 * clean (all its buffers are clean). This happens if the
1727 * buffers were written out directly, with submit_bh(). ext3
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001728 * will do this, as well as the blockdev mapping.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001729 * try_to_release_page() will discover that cleanness and will
1730 * drop the buffers and mark the page clean - it can be freed.
1731 *
1732 * Rarely, pages can have buffers and no ->mapping. These are
1733 * the pages which were not successfully invalidated in
Yang Shid12b8952020-12-14 19:13:02 -08001734 * truncate_cleanup_page(). We try to drop those buffers here
Linus Torvalds1da177e2005-04-16 15:20:36 -07001735 * and if that worked, and the page is no longer mapped into
1736 * process address space (page_count == 1) it can be freed.
1737 * Otherwise, leave the page on the LRU so it is swappable.
1738 */
David Howells266cf652009-04-03 16:42:36 +01001739 if (page_has_private(page)) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001740 if (!try_to_release_page(page, sc->gfp_mask))
1741 goto activate_locked;
Nick Piggine2867812008-07-25 19:45:30 -07001742 if (!mapping && page_count(page) == 1) {
1743 unlock_page(page);
1744 if (put_page_testzero(page))
1745 goto free_it;
1746 else {
1747 /*
1748 * rare race with speculative reference.
1749 * the speculative reference will free
1750 * this page shortly, so we may
1751 * increment nr_reclaimed here (and
1752 * leave it off the LRU).
1753 */
1754 nr_reclaimed++;
1755 continue;
1756 }
1757 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001758 }
1759
Shaohua Li802a3a92017-05-03 14:52:32 -07001760 if (PageAnon(page) && !PageSwapBacked(page)) {
1761 /* follow __remove_mapping for reference */
1762 if (!page_ref_freeze(page, 1))
1763 goto keep_locked;
Miaohe Lind17be2d2021-09-02 14:59:39 -07001764 /*
1765 * The page has only one reference left, which is
1766 * from the isolation. After the caller puts the
1767 * page back on lru and drops the reference, the
1768 * page will be freed anyway. It doesn't matter
1769 * which lru it goes. So we don't bother checking
1770 * PageDirty here.
1771 */
Shaohua Li802a3a92017-05-03 14:52:32 -07001772 count_vm_event(PGLAZYFREED);
Roman Gushchin22621852017-07-06 15:40:25 -07001773 count_memcg_page_event(page, PGLAZYFREED);
Johannes Weinerb9107182019-11-30 17:55:59 -08001774 } else if (!mapping || !__remove_mapping(mapping, page, true,
1775 sc->target_mem_cgroup))
Shaohua Li802a3a92017-05-03 14:52:32 -07001776 goto keep_locked;
Hugh Dickins9a1ea432018-12-28 00:36:14 -08001777
1778 unlock_page(page);
Nick Piggine2867812008-07-25 19:45:30 -07001779free_it:
Yang Shi98879b32019-07-11 20:59:30 -07001780 /*
1781 * THP may get swapped out in a whole, need account
1782 * all base pages.
1783 */
1784 nr_reclaimed += nr_pages;
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001785
1786 /*
1787 * Is there need to periodically free_page_list? It would
1788 * appear not as the counts should be low
1789 */
Yang Shi7ae88532019-09-23 15:38:09 -07001790 if (unlikely(PageTransHuge(page)))
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07001791 destroy_compound_page(page);
Yang Shi7ae88532019-09-23 15:38:09 -07001792 else
Huang Yingbd4c82c22017-09-06 16:22:49 -07001793 list_add(&page->lru, &free_pages);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001794 continue;
1795
Yang Shi98879b32019-07-11 20:59:30 -07001796activate_locked_split:
1797 /*
1798 * The tail pages that are failed to add into swap cache
1799 * reach here. Fixup nr_scanned and nr_pages.
1800 */
1801 if (nr_pages > 1) {
1802 sc->nr_scanned -= (nr_pages - 1);
1803 nr_pages = 1;
1804 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001805activate_locked:
Rik van Riel68a223942008-10-18 20:26:23 -07001806 /* Not a candidate for swapping, so reclaim swap space. */
Minchan Kimad6b6702017-05-03 14:54:13 -07001807 if (PageSwapCache(page) && (mem_cgroup_swap_full(page) ||
1808 PageMlocked(page)))
Hugh Dickinsa2c43ee2009-01-06 14:39:36 -08001809 try_to_free_swap(page);
Sasha Levin309381fea2014-01-23 15:52:54 -08001810 VM_BUG_ON_PAGE(PageActive(page), page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001811 if (!PageMlocked(page)) {
Huang Ying9de4f222020-04-06 20:04:41 -07001812 int type = page_is_file_lru(page);
Minchan Kimad6b6702017-05-03 14:54:13 -07001813 SetPageActive(page);
Yang Shi98879b32019-07-11 20:59:30 -07001814 stat->nr_activate[type] += nr_pages;
Roman Gushchin22621852017-07-06 15:40:25 -07001815 count_memcg_page_event(page, PGACTIVATE);
Minchan Kimad6b6702017-05-03 14:54:13 -07001816 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001817keep_locked:
1818 unlock_page(page);
1819keep:
1820 list_add(&page->lru, &ret_pages);
Sasha Levin309381fea2014-01-23 15:52:54 -08001821 VM_BUG_ON_PAGE(PageLRU(page) || PageUnevictable(page), page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001822 }
Dave Hansen26aa2d12021-09-02 14:59:16 -07001823 /* 'page_list' is always empty here */
1824
1825 /* Migrate pages selected for demotion */
1826 nr_reclaimed += demote_page_list(&demote_pages, pgdat);
1827 /* Pages that could not be demoted are still in @demote_pages */
1828 if (!list_empty(&demote_pages)) {
1829 /* Pages which failed to demoted go back on @page_list for retry: */
1830 list_splice_init(&demote_pages, page_list);
1831 do_demote_pass = false;
1832 goto retry;
1833 }
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001834
Yang Shi98879b32019-07-11 20:59:30 -07001835 pgactivate = stat->nr_activate[0] + stat->nr_activate[1];
1836
Johannes Weiner747db952014-08-08 14:19:24 -07001837 mem_cgroup_uncharge_list(&free_pages);
Mel Gorman72b252a2015-09-04 15:47:32 -07001838 try_to_unmap_flush();
Mel Gorman2d4894b2017-11-15 17:37:59 -08001839 free_unref_page_list(&free_pages);
Mel Gormanabe4c3b2010-08-09 17:19:31 -07001840
Linus Torvalds1da177e2005-04-16 15:20:36 -07001841 list_splice(&ret_pages, page_list);
Kirill Tkhai886cf192019-05-13 17:16:51 -07001842 count_vm_events(PGACTIVATE, pgactivate);
Johannes Weiner0a31bc92014-08-08 14:19:22 -07001843
Andrew Morton05ff5132006-03-22 00:08:20 -08001844 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001845}
1846
Maninder Singh730ec8c2020-06-03 16:01:18 -07001847unsigned int reclaim_clean_pages_from_list(struct zone *zone,
Minchan Kim02c6de82012-10-08 16:31:55 -07001848 struct list_head *page_list)
1849{
1850 struct scan_control sc = {
1851 .gfp_mask = GFP_KERNEL,
Minchan Kim02c6de82012-10-08 16:31:55 -07001852 .may_unmap = 1,
1853 };
Jaewon Kim1f318a92020-06-03 16:01:15 -07001854 struct reclaim_stat stat;
Maninder Singh730ec8c2020-06-03 16:01:18 -07001855 unsigned int nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001856 struct page *page, *next;
1857 LIST_HEAD(clean_pages);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001858 unsigned int noreclaim_flag;
Minchan Kim02c6de82012-10-08 16:31:55 -07001859
1860 list_for_each_entry_safe(page, next, page_list, lru) {
Oscar Salvadorae37c7f2021-05-04 18:35:29 -07001861 if (!PageHuge(page) && page_is_file_lru(page) &&
1862 !PageDirty(page) && !__PageMovable(page) &&
1863 !PageUnevictable(page)) {
Minchan Kim02c6de82012-10-08 16:31:55 -07001864 ClearPageActive(page);
1865 list_move(&page->lru, &clean_pages);
1866 }
1867 }
1868
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001869 /*
1870 * We should be safe here since we are only dealing with file pages and
1871 * we are not kswapd and therefore cannot write dirty file pages. But
1872 * call memalloc_noreclaim_save() anyway, just in case these conditions
1873 * change in the future.
1874 */
1875 noreclaim_flag = memalloc_noreclaim_save();
Jaewon Kim1f318a92020-06-03 16:01:15 -07001876 nr_reclaimed = shrink_page_list(&clean_pages, zone->zone_pgdat, &sc,
Shakeel Butt013339d2020-12-14 19:06:39 -08001877 &stat, true);
Yu Zhao2d2b8d22021-06-30 18:49:48 -07001878 memalloc_noreclaim_restore(noreclaim_flag);
1879
Minchan Kim02c6de82012-10-08 16:31:55 -07001880 list_splice(&clean_pages, page_list);
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001881 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
1882 -(long)nr_reclaimed);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001883 /*
1884 * Since lazyfree pages are isolated from file LRU from the beginning,
1885 * they will rotate back to anonymous LRU in the end if it failed to
1886 * discard so isolated count will be mismatched.
1887 * Compensate the isolated count for both LRU lists.
1888 */
1889 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_ANON,
1890 stat.nr_lazyfree_fail);
1891 mod_node_page_state(zone->zone_pgdat, NR_ISOLATED_FILE,
Nicholas Piggin2da9f632020-11-13 22:51:46 -08001892 -(long)stat.nr_lazyfree_fail);
Jaewon Kim1f318a92020-06-03 16:01:15 -07001893 return nr_reclaimed;
Minchan Kim02c6de82012-10-08 16:31:55 -07001894}
1895
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001896/*
1897 * Attempt to remove the specified page from its LRU. Only take this page
1898 * if it is of the appropriate PageActive status. Pages which are being
1899 * freed elsewhere are also ignored.
1900 *
1901 * page: page to consider
1902 * mode: one of the LRU isolation modes defined above
1903 *
Alex Shic2135f72021-02-24 12:08:01 -08001904 * returns true on success, false on failure.
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001905 */
Alex Shic2135f72021-02-24 12:08:01 -08001906bool __isolate_lru_page_prepare(struct page *page, isolate_mode_t mode)
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001907{
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001908 /* Only take pages on the LRU. */
1909 if (!PageLRU(page))
Alex Shic2135f72021-02-24 12:08:01 -08001910 return false;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001911
Minchan Kime46a2872012-10-08 16:33:48 -07001912 /* Compaction should not handle unevictable pages but CMA can do so */
1913 if (PageUnevictable(page) && !(mode & ISOLATE_UNEVICTABLE))
Alex Shic2135f72021-02-24 12:08:01 -08001914 return false;
Lee Schermerhorn894bc312008-10-18 20:26:39 -07001915
Mel Gormanc8244932012-01-12 17:19:38 -08001916 /*
1917 * To minimise LRU disruption, the caller can indicate that it only
1918 * wants to isolate pages it will be able to operate on without
1919 * blocking - clean pages for the most part.
1920 *
Mel Gormanc8244932012-01-12 17:19:38 -08001921 * ISOLATE_ASYNC_MIGRATE is used to indicate that it only wants to pages
1922 * that it is possible to migrate without blocking
1923 */
Johannes Weiner1276ad62017-02-24 14:56:11 -08001924 if (mode & ISOLATE_ASYNC_MIGRATE) {
Mel Gormanc8244932012-01-12 17:19:38 -08001925 /* All the caller can do on PageWriteback is block */
1926 if (PageWriteback(page))
Alex Shic2135f72021-02-24 12:08:01 -08001927 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001928
1929 if (PageDirty(page)) {
1930 struct address_space *mapping;
Mel Gorman69d763f2018-01-31 16:19:52 -08001931 bool migrate_dirty;
Mel Gormanc8244932012-01-12 17:19:38 -08001932
Mel Gormanc8244932012-01-12 17:19:38 -08001933 /*
1934 * Only pages without mappings or that have a
1935 * ->migratepage callback are possible to migrate
Mel Gorman69d763f2018-01-31 16:19:52 -08001936 * without blocking. However, we can be racing with
1937 * truncation so it's necessary to lock the page
1938 * to stabilise the mapping as truncation holds
1939 * the page lock until after the page is removed
1940 * from the page cache.
Mel Gormanc8244932012-01-12 17:19:38 -08001941 */
Mel Gorman69d763f2018-01-31 16:19:52 -08001942 if (!trylock_page(page))
Alex Shic2135f72021-02-24 12:08:01 -08001943 return false;
Mel Gorman69d763f2018-01-31 16:19:52 -08001944
Mel Gormanc8244932012-01-12 17:19:38 -08001945 mapping = page_mapping(page);
Hugh Dickins145e1a72018-06-01 16:50:50 -07001946 migrate_dirty = !mapping || mapping->a_ops->migratepage;
Mel Gorman69d763f2018-01-31 16:19:52 -08001947 unlock_page(page);
1948 if (!migrate_dirty)
Alex Shic2135f72021-02-24 12:08:01 -08001949 return false;
Mel Gormanc8244932012-01-12 17:19:38 -08001950 }
1951 }
Minchan Kim39deaf82011-10-31 17:06:51 -07001952
Minchan Kimf80c0672011-10-31 17:06:55 -07001953 if ((mode & ISOLATE_UNMAPPED) && page_mapped(page))
Alex Shic2135f72021-02-24 12:08:01 -08001954 return false;
Minchan Kimf80c0672011-10-31 17:06:55 -07001955
Alex Shic2135f72021-02-24 12:08:01 -08001956 return true;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07001957}
1958
Mel Gorman7ee36a12016-07-28 15:47:17 -07001959/*
1960 * Update LRU sizes after isolating pages. The LRU size updates must
Ethon Paul55b65a52020-06-04 16:49:10 -07001961 * be complete before mem_cgroup_update_lru_size due to a sanity check.
Mel Gorman7ee36a12016-07-28 15:47:17 -07001962 */
1963static __always_inline void update_lru_sizes(struct lruvec *lruvec,
Michal Hockob4536f0c82017-01-10 16:58:04 -08001964 enum lru_list lru, unsigned long *nr_zone_taken)
Mel Gorman7ee36a12016-07-28 15:47:17 -07001965{
Mel Gorman7ee36a12016-07-28 15:47:17 -07001966 int zid;
1967
Mel Gorman7ee36a12016-07-28 15:47:17 -07001968 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
1969 if (!nr_zone_taken[zid])
1970 continue;
1971
Wei Yanga892cb62020-06-03 16:01:12 -07001972 update_lru_size(lruvec, lru, zid, -nr_zone_taken[zid]);
Mel Gorman7ee36a12016-07-28 15:47:17 -07001973 }
Mel Gorman7ee36a12016-07-28 15:47:17 -07001974
Mel Gorman7ee36a12016-07-28 15:47:17 -07001975}
1976
Mel Gormanf611fab2021-06-30 18:53:19 -07001977/*
Hugh Dickins15b44732020-12-15 14:21:31 -08001978 * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
1979 *
1980 * lruvec->lru_lock is heavily contended. Some of the functions that
Linus Torvalds1da177e2005-04-16 15:20:36 -07001981 * shrink the lists perform better by taking out a batch of pages
1982 * and working on them outside the LRU lock.
1983 *
1984 * For pagecache intensive workloads, this function is the hottest
1985 * spot in the kernel (apart from copy_*_user functions).
1986 *
Hugh Dickins15b44732020-12-15 14:21:31 -08001987 * Lru_lock must be held before calling this function.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001988 *
Minchan Kim791b48b2017-05-12 15:47:06 -07001989 * @nr_to_scan: The number of eligible pages to look through on the list.
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001990 * @lruvec: The LRU vector to pull pages from.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001991 * @dst: The temp list to put pages on to.
Hugh Dickinsf6260122012-01-12 17:20:06 -08001992 * @nr_scanned: The number of pages that were scanned.
Rik van Rielfe2c2a12012-03-21 16:33:51 -07001993 * @sc: The scan_control struct for this reclaim session
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07001994 * @lru: LRU list id for isolating
Linus Torvalds1da177e2005-04-16 15:20:36 -07001995 *
1996 * returns how many pages were moved onto *@dst.
1997 */
Andrew Morton69e05942006-03-22 00:08:19 -08001998static unsigned long isolate_lru_pages(unsigned long nr_to_scan,
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07001999 struct lruvec *lruvec, struct list_head *dst,
Rik van Rielfe2c2a12012-03-21 16:33:51 -07002000 unsigned long *nr_scanned, struct scan_control *sc,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002001 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002002{
Hugh Dickins75b00af2012-05-29 15:07:09 -07002003 struct list_head *src = &lruvec->lists[lru];
Andrew Morton69e05942006-03-22 00:08:19 -08002004 unsigned long nr_taken = 0;
Mel Gorman599d0c92016-07-28 15:45:31 -07002005 unsigned long nr_zone_taken[MAX_NR_ZONES] = { 0 };
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002006 unsigned long nr_skipped[MAX_NR_ZONES] = { 0, };
Johannes Weiner3db65812017-05-03 14:52:13 -07002007 unsigned long skipped = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002008 unsigned long scan, total_scan, nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002009 LIST_HEAD(pages_skipped);
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002010 isolate_mode_t mode = (sc->may_unmap ? 0 : ISOLATE_UNMAPPED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002011
Yang Shi98879b32019-07-11 20:59:30 -07002012 total_scan = 0;
Minchan Kim791b48b2017-05-12 15:47:06 -07002013 scan = 0;
Yang Shi98879b32019-07-11 20:59:30 -07002014 while (scan < nr_to_scan && !list_empty(src)) {
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002015 struct page *page;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002016
Linus Torvalds1da177e2005-04-16 15:20:36 -07002017 page = lru_to_page(src);
2018 prefetchw_prev_lru_page(page, src, flags);
2019
Matthew Wilcox (Oracle)d8c65462019-09-23 15:34:30 -07002020 nr_pages = compound_nr(page);
Yang Shi98879b32019-07-11 20:59:30 -07002021 total_scan += nr_pages;
2022
Mel Gormanb2e18752016-07-28 15:45:37 -07002023 if (page_zonenum(page) > sc->reclaim_idx) {
2024 list_move(&page->lru, &pages_skipped);
Yang Shi98879b32019-07-11 20:59:30 -07002025 nr_skipped[page_zonenum(page)] += nr_pages;
Mel Gormanb2e18752016-07-28 15:45:37 -07002026 continue;
2027 }
2028
Minchan Kim791b48b2017-05-12 15:47:06 -07002029 /*
2030 * Do not count skipped pages because that makes the function
2031 * return with no isolated pages if the LRU mostly contains
2032 * ineligible pages. This causes the VM to not reclaim any
2033 * pages, triggering a premature OOM.
Yang Shi98879b32019-07-11 20:59:30 -07002034 *
2035 * Account all tail pages of THP. This would not cause
2036 * premature OOM since __isolate_lru_page() returns -EBUSY
2037 * only when the page is being freed somewhere else.
Minchan Kim791b48b2017-05-12 15:47:06 -07002038 */
Yang Shi98879b32019-07-11 20:59:30 -07002039 scan += nr_pages;
Alex Shic2135f72021-02-24 12:08:01 -08002040 if (!__isolate_lru_page_prepare(page, mode)) {
2041 /* It is being freed elsewhere */
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002042 list_move(&page->lru, src);
Alex Shic2135f72021-02-24 12:08:01 -08002043 continue;
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002044 }
Alex Shic2135f72021-02-24 12:08:01 -08002045 /*
2046 * Be careful not to clear PageLRU until after we're
2047 * sure the page is not being freed elsewhere -- the
2048 * page release code relies on it.
2049 */
2050 if (unlikely(!get_page_unless_zero(page))) {
2051 list_move(&page->lru, src);
2052 continue;
2053 }
2054
2055 if (!TestClearPageLRU(page)) {
2056 /* Another thread is already isolating this page */
2057 put_page(page);
2058 list_move(&page->lru, src);
2059 continue;
2060 }
2061
2062 nr_taken += nr_pages;
2063 nr_zone_taken[page_zonenum(page)] += nr_pages;
2064 list_move(&page->lru, dst);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002065 }
2066
Mel Gormanb2e18752016-07-28 15:45:37 -07002067 /*
2068 * Splice any skipped pages to the start of the LRU list. Note that
2069 * this disrupts the LRU order when reclaiming for lower zones but
2070 * we cannot splice to the tail. If we did then the SWAP_CLUSTER_MAX
2071 * scanning would soon rescan the same pages to skip and put the
2072 * system at risk of premature OOM.
2073 */
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002074 if (!list_empty(&pages_skipped)) {
2075 int zid;
2076
Johannes Weiner3db65812017-05-03 14:52:13 -07002077 list_splice(&pages_skipped, src);
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002078 for (zid = 0; zid < MAX_NR_ZONES; zid++) {
2079 if (!nr_skipped[zid])
2080 continue;
2081
2082 __count_zid_vm_events(PGSCAN_SKIP, zid, nr_skipped[zid]);
Michal Hocko1265e3a2017-02-22 15:44:21 -08002083 skipped += nr_skipped[zid];
Mel Gorman7cc30fc2016-07-28 15:46:59 -07002084 }
2085 }
Minchan Kim791b48b2017-05-12 15:47:06 -07002086 *nr_scanned = total_scan;
Michal Hocko1265e3a2017-02-22 15:44:21 -08002087 trace_mm_vmscan_lru_isolate(sc->reclaim_idx, sc->order, nr_to_scan,
Minchan Kim791b48b2017-05-12 15:47:06 -07002088 total_scan, skipped, nr_taken, mode, lru);
Michal Hockob4536f0c82017-01-10 16:58:04 -08002089 update_lru_sizes(lruvec, lru, nr_zone_taken);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002090 return nr_taken;
2091}
2092
Nick Piggin62695a82008-10-18 20:26:09 -07002093/**
2094 * isolate_lru_page - tries to isolate a page from its LRU list
2095 * @page: page to isolate from its LRU list
2096 *
2097 * Isolates a @page from an LRU list, clears PageLRU and adjusts the
2098 * vmstat statistic corresponding to whatever LRU list the page was on.
2099 *
2100 * Returns 0 if the page was removed from an LRU list.
2101 * Returns -EBUSY if the page was not on an LRU list.
2102 *
2103 * The returned page will have PageLRU() cleared. If it was found on
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002104 * the active list, it will have PageActive set. If it was found on
2105 * the unevictable list, it will have the PageUnevictable bit set. That flag
2106 * may need to be cleared by the caller before letting the page go.
Nick Piggin62695a82008-10-18 20:26:09 -07002107 *
2108 * The vmstat statistic corresponding to the list on which the page was
2109 * found will be decremented.
2110 *
2111 * Restrictions:
Mike Rapoporta5d09be2018-02-06 15:42:19 -08002112 *
Nick Piggin62695a82008-10-18 20:26:09 -07002113 * (1) Must be called with an elevated refcount on the page. This is a
Hui Su01c47762020-10-13 16:56:49 -07002114 * fundamental difference from isolate_lru_pages (which is called
Nick Piggin62695a82008-10-18 20:26:09 -07002115 * without a stable reference).
2116 * (2) the lru_lock must not be held.
2117 * (3) interrupts must be enabled.
2118 */
2119int isolate_lru_page(struct page *page)
2120{
2121 int ret = -EBUSY;
2122
Sasha Levin309381fea2014-01-23 15:52:54 -08002123 VM_BUG_ON_PAGE(!page_count(page), page);
Kirill A. Shutemovcf2a82e2016-02-05 15:36:36 -08002124 WARN_RATELIMIT(PageTail(page), "trying to isolate tail page");
Konstantin Khlebnikov0c917312011-05-24 17:12:21 -07002125
Alex Shid25b5bd2020-12-15 12:34:16 -08002126 if (TestClearPageLRU(page)) {
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002127 struct lruvec *lruvec;
Nick Piggin62695a82008-10-18 20:26:09 -07002128
Alex Shid25b5bd2020-12-15 12:34:16 -08002129 get_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002130 lruvec = lock_page_lruvec_irq(page);
Yu Zhao46ae6b22021-02-24 12:08:25 -08002131 del_page_from_lru_list(page, lruvec);
Alex Shi6168d0d2020-12-15 12:34:29 -08002132 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08002133 ret = 0;
Nick Piggin62695a82008-10-18 20:26:09 -07002134 }
Alex Shid25b5bd2020-12-15 12:34:16 -08002135
Nick Piggin62695a82008-10-18 20:26:09 -07002136 return ret;
2137}
2138
Andy Whitcroft5ad333e2007-07-17 04:03:16 -07002139/*
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002140 * A direct reclaimer may isolate SWAP_CLUSTER_MAX pages from the LRU list and
Xianting Tian178821b2019-11-30 17:56:05 -08002141 * then get rescheduled. When there are massive number of tasks doing page
Fengguang Wud37dd5d2012-12-18 14:23:28 -08002142 * allocation, such sleeping direct reclaimers may keep piling up on each CPU,
2143 * the LRU list will go small and be scanned faster than necessary, leading to
2144 * unnecessary swapping, thrashing and OOM.
Rik van Riel35cd7812009-09-21 17:01:38 -07002145 */
Mel Gorman599d0c92016-07-28 15:45:31 -07002146static int too_many_isolated(struct pglist_data *pgdat, int file,
Rik van Riel35cd7812009-09-21 17:01:38 -07002147 struct scan_control *sc)
2148{
2149 unsigned long inactive, isolated;
2150
2151 if (current_is_kswapd())
2152 return 0;
2153
Johannes Weinerb5ead352019-11-30 17:55:40 -08002154 if (!writeback_throttling_sane(sc))
Rik van Riel35cd7812009-09-21 17:01:38 -07002155 return 0;
2156
2157 if (file) {
Mel Gorman599d0c92016-07-28 15:45:31 -07002158 inactive = node_page_state(pgdat, NR_INACTIVE_FILE);
2159 isolated = node_page_state(pgdat, NR_ISOLATED_FILE);
Rik van Riel35cd7812009-09-21 17:01:38 -07002160 } else {
Mel Gorman599d0c92016-07-28 15:45:31 -07002161 inactive = node_page_state(pgdat, NR_INACTIVE_ANON);
2162 isolated = node_page_state(pgdat, NR_ISOLATED_ANON);
Rik van Riel35cd7812009-09-21 17:01:38 -07002163 }
2164
Fengguang Wu3cf23842012-12-18 14:23:31 -08002165 /*
2166 * GFP_NOIO/GFP_NOFS callers are allowed to isolate more pages, so they
2167 * won't get blocked by normal direct-reclaimers, forming a circular
2168 * deadlock.
2169 */
Mel Gormand0164ad2015-11-06 16:28:21 -08002170 if ((sc->gfp_mask & (__GFP_IO | __GFP_FS)) == (__GFP_IO | __GFP_FS))
Fengguang Wu3cf23842012-12-18 14:23:31 -08002171 inactive >>= 3;
2172
Rik van Riel35cd7812009-09-21 17:01:38 -07002173 return isolated > inactive;
2174}
2175
Kirill Tkhaia222f342019-05-13 17:17:00 -07002176/*
Hugh Dickins15b44732020-12-15 14:21:31 -08002177 * move_pages_to_lru() moves pages from private @list to appropriate LRU list.
2178 * On return, @list is reused as a list of pages to be freed by the caller.
Kirill Tkhaia222f342019-05-13 17:17:00 -07002179 *
2180 * Returns the number of pages moved to the given lruvec.
2181 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002182static unsigned int move_pages_to_lru(struct lruvec *lruvec,
2183 struct list_head *list)
Mel Gorman66635622010-08-09 17:19:30 -07002184{
Kirill Tkhaia222f342019-05-13 17:17:00 -07002185 int nr_pages, nr_moved = 0;
Hugh Dickins3f797682012-01-12 17:20:07 -08002186 LIST_HEAD(pages_to_free);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002187 struct page *page;
Mel Gorman66635622010-08-09 17:19:30 -07002188
Kirill Tkhaia222f342019-05-13 17:17:00 -07002189 while (!list_empty(list)) {
2190 page = lru_to_page(list);
Sasha Levin309381fea2014-01-23 15:52:54 -08002191 VM_BUG_ON_PAGE(PageLRU(page), page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002192 list_del(&page->lru);
Hugh Dickins39b5f292012-10-08 16:33:18 -07002193 if (unlikely(!page_evictable(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002194 spin_unlock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002195 putback_lru_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002196 spin_lock_irq(&lruvec->lru_lock);
Mel Gorman66635622010-08-09 17:19:30 -07002197 continue;
2198 }
Hugh Dickinsfa9add62012-05-29 15:07:09 -07002199
Alex Shi3d06afa2020-12-15 12:33:37 -08002200 /*
2201 * The SetPageLRU needs to be kept here for list integrity.
2202 * Otherwise:
2203 * #0 move_pages_to_lru #1 release_pages
2204 * if !put_page_testzero
2205 * if (put_page_testzero())
2206 * !PageLRU //skip lru_lock
2207 * SetPageLRU()
2208 * list_add(&page->lru,)
2209 * list_add(&page->lru,)
2210 */
Linus Torvalds7a608572011-01-17 14:42:19 -08002211 SetPageLRU(page);
Kirill Tkhaia222f342019-05-13 17:17:00 -07002212
Alex Shi3d06afa2020-12-15 12:33:37 -08002213 if (unlikely(put_page_testzero(page))) {
Yu Zhao87560172021-02-24 12:08:28 -08002214 __clear_page_lru_flags(page);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002215
2216 if (unlikely(PageCompound(page))) {
Alex Shi6168d0d2020-12-15 12:34:29 -08002217 spin_unlock_irq(&lruvec->lru_lock);
Matthew Wilcox (Oracle)ff45fc32020-06-03 16:01:09 -07002218 destroy_compound_page(page);
Alex Shi6168d0d2020-12-15 12:34:29 -08002219 spin_lock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002220 } else
2221 list_add(&page->lru, &pages_to_free);
Alex Shi3d06afa2020-12-15 12:33:37 -08002222
2223 continue;
Mel Gorman66635622010-08-09 17:19:30 -07002224 }
Alex Shi3d06afa2020-12-15 12:33:37 -08002225
Alex Shiafca9152020-12-15 12:34:02 -08002226 /*
2227 * All pages were isolated from the same lruvec (and isolation
2228 * inhibits memcg migration).
2229 */
Muchun Song7467c392021-06-28 19:37:59 -07002230 VM_BUG_ON_PAGE(!page_matches_lruvec(page, lruvec), page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08002231 add_page_to_lru_list(page, lruvec);
Alex Shi3d06afa2020-12-15 12:33:37 -08002232 nr_pages = thp_nr_pages(page);
Alex Shi3d06afa2020-12-15 12:33:37 -08002233 nr_moved += nr_pages;
2234 if (PageActive(page))
2235 workingset_age_nonresident(lruvec, nr_pages);
Mel Gorman66635622010-08-09 17:19:30 -07002236 }
Mel Gorman66635622010-08-09 17:19:30 -07002237
Hugh Dickins3f797682012-01-12 17:20:07 -08002238 /*
2239 * To save our caller's stack, now use input list for pages to free.
2240 */
Kirill Tkhaia222f342019-05-13 17:17:00 -07002241 list_splice(&pages_to_free, list);
2242
2243 return nr_moved;
Mel Gorman66635622010-08-09 17:19:30 -07002244}
2245
2246/*
NeilBrown399ba0b2014-06-04 16:07:42 -07002247 * If a kernel thread (such as nfsd for loop-back mounts) services
NeilBrowna37b0712020-06-01 21:48:18 -07002248 * a backing device by writing to the page cache it sets PF_LOCAL_THROTTLE.
NeilBrown399ba0b2014-06-04 16:07:42 -07002249 * In that case we should only throttle if the backing device it is
2250 * writing to is congested. In other cases it is safe to throttle.
2251 */
2252static int current_may_throttle(void)
2253{
NeilBrowna37b0712020-06-01 21:48:18 -07002254 return !(current->flags & PF_LOCAL_THROTTLE) ||
NeilBrown399ba0b2014-06-04 16:07:42 -07002255 current->backing_dev_info == NULL ||
2256 bdi_write_congested(current->backing_dev_info);
2257}
2258
2259/*
Mel Gormanb2e18752016-07-28 15:45:37 -07002260 * shrink_inactive_list() is a helper for shrink_node(). It returns the number
Andrew Morton1742f192006-03-22 00:08:21 -08002261 * of reclaimed pages
Linus Torvalds1da177e2005-04-16 15:20:36 -07002262 */
Muchun Song9ef56b72021-06-28 19:38:09 -07002263static unsigned long
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002264shrink_inactive_list(unsigned long nr_to_scan, struct lruvec *lruvec,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002265 struct scan_control *sc, enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002266{
2267 LIST_HEAD(page_list);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002268 unsigned long nr_scanned;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002269 unsigned int nr_reclaimed = 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002270 unsigned long nr_taken;
Kirill Tkhai060f0052019-03-05 15:48:15 -08002271 struct reclaim_stat stat;
Johannes Weiner497a6c12020-06-03 16:02:34 -07002272 bool file = is_file_lru(lru);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002273 enum vm_event_item item;
Mel Gorman599d0c92016-07-28 15:45:31 -07002274 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Michal Hockodb73ee02017-09-06 16:21:11 -07002275 bool stalled = false;
KOSAKI Motohiro78dc5832009-06-16 15:31:40 -07002276
Mel Gorman599d0c92016-07-28 15:45:31 -07002277 while (unlikely(too_many_isolated(pgdat, file, sc))) {
Michal Hockodb73ee02017-09-06 16:21:11 -07002278 if (stalled)
2279 return 0;
2280
2281 /* wait a bit for the reclaimer. */
2282 msleep(100);
2283 stalled = true;
Rik van Riel35cd7812009-09-21 17:01:38 -07002284
2285 /* We are about to die and free our memory. Return now. */
2286 if (fatal_signal_pending(current))
2287 return SWAP_CLUSTER_MAX;
2288 }
2289
Linus Torvalds1da177e2005-04-16 15:20:36 -07002290 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002291
Alex Shi6168d0d2020-12-15 12:34:29 -08002292 spin_lock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002293
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002294 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &page_list,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002295 &nr_scanned, sc, lru);
Konstantin Khlebnikov95d918f2012-05-29 15:06:59 -07002296
Mel Gorman599d0c92016-07-28 15:45:31 -07002297 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002298 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002299 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002300 __count_vm_events(item, nr_scanned);
2301 __count_memcg_events(lruvec_memcg(lruvec), item, nr_scanned);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002302 __count_vm_events(PGSCAN_ANON + file, nr_scanned);
2303
Alex Shi6168d0d2020-12-15 12:34:29 -08002304 spin_unlock_irq(&lruvec->lru_lock);
KOSAKI Motohiroa7312862009-09-21 17:01:37 -07002305
Hillf Dantond563c052012-03-21 16:34:02 -07002306 if (nr_taken == 0)
Mel Gorman66635622010-08-09 17:19:30 -07002307 return 0;
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002308
Shakeel Butt013339d2020-12-14 19:06:39 -08002309 nr_reclaimed = shrink_page_list(&page_list, pgdat, sc, &stat, false);
KOSAKI Motohiroe247dbc2010-08-09 17:19:28 -07002310
Alex Shi6168d0d2020-12-15 12:34:29 -08002311 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002312 move_pages_to_lru(lruvec, &page_list);
2313
2314 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002315 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
Johannes Weinerb5ead352019-11-30 17:55:40 -08002316 if (!cgroup_reclaim(sc))
Kirill Tkhaif46b7912019-05-13 17:22:33 -07002317 __count_vm_events(item, nr_reclaimed);
2318 __count_memcg_events(lruvec_memcg(lruvec), item, nr_reclaimed);
Johannes Weiner497a6c12020-06-03 16:02:34 -07002319 __count_vm_events(PGSTEAL_ANON + file, nr_reclaimed);
Alex Shi6168d0d2020-12-15 12:34:29 -08002320 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins3f797682012-01-12 17:20:07 -08002321
Alex Shi75cc3c92020-12-15 14:20:50 -08002322 lru_note_cost(lruvec, file, stat.nr_pageout);
Johannes Weiner747db952014-08-08 14:19:24 -07002323 mem_cgroup_uncharge_list(&page_list);
Mel Gorman2d4894b2017-11-15 17:37:59 -08002324 free_unref_page_list(&page_list);
Mel Gormane11da5b2010-10-26 14:21:40 -07002325
Mel Gorman92df3a72011-10-31 17:07:56 -07002326 /*
Andrey Ryabinin1c610d52018-03-22 16:17:42 -07002327 * If dirty pages are scanned that are not queued for IO, it
2328 * implies that flushers are not doing their job. This can
2329 * happen when memory pressure pushes dirty pages to the end of
2330 * the LRU before the dirty limits are breached and the dirty
2331 * data has expired. It can also happen when the proportion of
2332 * dirty pages grows not through writes but through memory
2333 * pressure reclaiming all the clean cache. And in some cases,
2334 * the flushers simply cannot keep up with the allocation
2335 * rate. Nudge the flusher threads in case they are asleep.
2336 */
2337 if (stat.nr_unqueued_dirty == nr_taken)
2338 wakeup_flusher_threads(WB_REASON_VMSCAN);
2339
Andrey Ryabinind108c772018-04-10 16:27:59 -07002340 sc->nr.dirty += stat.nr_dirty;
2341 sc->nr.congested += stat.nr_congested;
2342 sc->nr.unqueued_dirty += stat.nr_unqueued_dirty;
2343 sc->nr.writeback += stat.nr_writeback;
2344 sc->nr.immediate += stat.nr_immediate;
2345 sc->nr.taken += nr_taken;
2346 if (file)
2347 sc->nr.file_taken += nr_taken;
Mel Gorman8e950282013-07-03 15:02:02 -07002348
Mel Gorman599d0c92016-07-28 15:45:31 -07002349 trace_mm_vmscan_lru_shrink_inactive(pgdat->node_id,
Steven Rostedtd51d1e62018-04-10 16:28:07 -07002350 nr_scanned, nr_reclaimed, &stat, sc->priority, file);
Andrew Morton05ff5132006-03-22 00:08:20 -08002351 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002352}
2353
Hugh Dickins15b44732020-12-15 14:21:31 -08002354/*
2355 * shrink_active_list() moves pages from the active LRU to the inactive LRU.
2356 *
2357 * We move them the other way if the page is referenced by one or more
2358 * processes.
2359 *
2360 * If the pages are mostly unmapped, the processing is fast and it is
2361 * appropriate to hold lru_lock across the whole operation. But if
2362 * the pages are mapped, the processing is slow (page_referenced()), so
2363 * we should drop lru_lock around each page. It's impossible to balance
2364 * this, so instead we remove the pages from the LRU while processing them.
2365 * It is safe to rely on PG_active against the non-LRU pages in here because
2366 * nobody will play with that bit on a non-LRU page.
2367 *
2368 * The downside is that we have to touch page->_refcount against each page.
2369 * But we had to alter page->flags anyway.
2370 */
Hugh Dickinsf6260122012-01-12 17:20:06 -08002371static void shrink_active_list(unsigned long nr_to_scan,
Konstantin Khlebnikov1a93be02012-05-29 15:07:01 -07002372 struct lruvec *lruvec,
Johannes Weinerf16015f2012-01-12 17:17:52 -08002373 struct scan_control *sc,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07002374 enum lru_list lru)
Linus Torvalds1da177e2005-04-16 15:20:36 -07002375{
KOSAKI Motohiro44c241f2009-09-21 17:01:35 -07002376 unsigned long nr_taken;
Hugh Dickinsf6260122012-01-12 17:20:06 -08002377 unsigned long nr_scanned;
Wu Fengguang6fe6b7e2009-06-16 15:33:05 -07002378 unsigned long vm_flags;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002379 LIST_HEAD(l_hold); /* The pages which were snipped off */
Wu Fengguang8cab4752009-06-16 15:33:12 -07002380 LIST_HEAD(l_active);
Christoph Lameterb69408e2008-10-18 20:26:14 -07002381 LIST_HEAD(l_inactive);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002382 struct page *page;
Michal Hocko9d998b42017-02-22 15:44:18 -08002383 unsigned nr_deactivate, nr_activate;
2384 unsigned nr_rotated = 0;
Konstantin Khlebnikov3cb99452012-05-29 15:06:53 -07002385 int file = is_file_lru(lru);
Mel Gorman599d0c92016-07-28 15:45:31 -07002386 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002387 bool bypass = false;
Linus Torvalds1da177e2005-04-16 15:20:36 -07002388
2389 lru_add_drain();
Minchan Kimf80c0672011-10-31 17:06:55 -07002390
Alex Shi6168d0d2020-12-15 12:34:29 -08002391 spin_lock_irq(&lruvec->lru_lock);
Johannes Weiner925b7672012-01-12 17:18:15 -08002392
Konstantin Khlebnikov5dc35972012-05-29 15:06:58 -07002393 nr_taken = isolate_lru_pages(nr_to_scan, lruvec, &l_hold,
Kirill Tkhaia9e7c392019-03-05 15:46:55 -08002394 &nr_scanned, sc, lru);
Johannes Weiner89b5fae2012-01-12 17:17:50 -08002395
Mel Gorman599d0c92016-07-28 15:45:31 -07002396 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, nr_taken);
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08002397
Shakeel Butt912c0572020-08-06 23:26:32 -07002398 if (!cgroup_reclaim(sc))
2399 __count_vm_events(PGREFILL, nr_scanned);
Yafang Shao2fa26902019-05-13 17:23:02 -07002400 __count_memcg_events(lruvec_memcg(lruvec), PGREFILL, nr_scanned);
Hugh Dickins9d5e6a92016-05-19 17:12:38 -07002401
Alex Shi6168d0d2020-12-15 12:34:29 -08002402 spin_unlock_irq(&lruvec->lru_lock);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002403
Linus Torvalds1da177e2005-04-16 15:20:36 -07002404 while (!list_empty(&l_hold)) {
2405 cond_resched();
2406 page = lru_to_page(&l_hold);
2407 list_del(&page->lru);
Rik van Riel7e9cd482008-10-18 20:26:35 -07002408
Hugh Dickins39b5f292012-10-08 16:33:18 -07002409 if (unlikely(!page_evictable(page))) {
Lee Schermerhorn894bc312008-10-18 20:26:39 -07002410 putback_lru_page(page);
2411 continue;
2412 }
2413
Mel Gormancc715d92012-03-21 16:34:00 -07002414 if (unlikely(buffer_heads_over_limit)) {
2415 if (page_has_private(page) && trylock_page(page)) {
2416 if (page_has_private(page))
2417 try_to_release_page(page, 0);
2418 unlock_page(page);
2419 }
2420 }
2421
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002422 trace_android_vh_page_referenced_check_bypass(page, nr_to_scan, lru, &bypass);
2423 if (bypass)
2424 goto skip_page_referenced;
2425
Johannes Weinerc3ac9a82012-05-29 15:06:25 -07002426 if (page_referenced(page, 0, sc->target_mem_cgroup,
2427 &vm_flags)) {
Wu Fengguang8cab4752009-06-16 15:33:12 -07002428 /*
2429 * Identify referenced, file-backed active pages and
2430 * give them one more trip around the active list. So
2431 * that executable code get better chances to stay in
2432 * memory under moderate memory pressure. Anon pages
2433 * are not likely to be evicted by use-once streaming
2434 * IO, plus JVM can create lots of anon VM_EXEC pages,
2435 * so we ignore them here.
2436 */
Huang Ying9de4f222020-04-06 20:04:41 -07002437 if ((vm_flags & VM_EXEC) && page_is_file_lru(page)) {
Matthew Wilcox (Oracle)6c357842020-08-14 17:30:37 -07002438 nr_rotated += thp_nr_pages(page);
Wu Fengguang8cab4752009-06-16 15:33:12 -07002439 list_add(&page->lru, &l_active);
2440 continue;
2441 }
2442 }
Liujie Xie6f98ceb2022-02-23 10:32:01 +08002443skip_page_referenced:
KOSAKI Motohiro5205e562009-09-21 17:01:44 -07002444 ClearPageActive(page); /* we are de-activating */
Johannes Weiner1899ad12018-10-26 15:06:04 -07002445 SetPageWorkingset(page);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002446 list_add(&page->lru, &l_inactive);
2447 }
2448
Andrew Mortonb5557492009-01-06 14:40:13 -08002449 /*
Wu Fengguang8cab4752009-06-16 15:33:12 -07002450 * Move pages back to the lru list.
Andrew Mortonb5557492009-01-06 14:40:13 -08002451 */
Alex Shi6168d0d2020-12-15 12:34:29 -08002452 spin_lock_irq(&lruvec->lru_lock);
Rik van Riel556adec2008-10-18 20:26:34 -07002453
Kirill Tkhaia222f342019-05-13 17:17:00 -07002454 nr_activate = move_pages_to_lru(lruvec, &l_active);
2455 nr_deactivate = move_pages_to_lru(lruvec, &l_inactive);
Kirill Tkhaif372d892019-05-13 17:16:57 -07002456 /* Keep all free pages in l_active list */
2457 list_splice(&l_inactive, &l_active);
Kirill Tkhai9851ac12019-05-13 17:16:54 -07002458
2459 __count_vm_events(PGDEACTIVATE, nr_deactivate);
2460 __count_memcg_events(lruvec_memcg(lruvec), PGDEACTIVATE, nr_deactivate);
2461
Mel Gorman599d0c92016-07-28 15:45:31 -07002462 __mod_node_page_state(pgdat, NR_ISOLATED_ANON + file, -nr_taken);
Alex Shi6168d0d2020-12-15 12:34:29 -08002463 spin_unlock_irq(&lruvec->lru_lock);
Hugh Dickins2bcf8872012-01-12 17:19:56 -08002464
Kirill Tkhaif372d892019-05-13 17:16:57 -07002465 mem_cgroup_uncharge_list(&l_active);
2466 free_unref_page_list(&l_active);
Michal Hocko9d998b42017-02-22 15:44:18 -08002467 trace_mm_vmscan_lru_shrink_active(pgdat->node_id, nr_taken, nr_activate,
2468 nr_deactivate, nr_rotated, sc->priority, file);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002469}
2470
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002471unsigned long reclaim_pages(struct list_head *page_list)
2472{
Yang Shif661d002020-04-01 21:10:05 -07002473 int nid = NUMA_NO_NODE;
Maninder Singh730ec8c2020-06-03 16:01:18 -07002474 unsigned int nr_reclaimed = 0;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002475 LIST_HEAD(node_page_list);
2476 struct reclaim_stat dummy_stat;
2477 struct page *page;
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002478 unsigned int noreclaim_flag;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002479 struct scan_control sc = {
2480 .gfp_mask = GFP_KERNEL,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002481 .may_writepage = 1,
2482 .may_unmap = 1,
2483 .may_swap = 1,
Dave Hansen26aa2d12021-09-02 14:59:16 -07002484 .no_demotion = 1,
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002485 };
2486
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002487 noreclaim_flag = memalloc_noreclaim_save();
2488
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002489 while (!list_empty(page_list)) {
2490 page = lru_to_page(page_list);
Yang Shif661d002020-04-01 21:10:05 -07002491 if (nid == NUMA_NO_NODE) {
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002492 nid = page_to_nid(page);
2493 INIT_LIST_HEAD(&node_page_list);
2494 }
2495
2496 if (nid == page_to_nid(page)) {
2497 ClearPageActive(page);
2498 list_move(&page->lru, &node_page_list);
2499 continue;
2500 }
2501
2502 nr_reclaimed += shrink_page_list(&node_page_list,
2503 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002504 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002505 while (!list_empty(&node_page_list)) {
2506 page = lru_to_page(&node_page_list);
2507 list_del(&page->lru);
2508 putback_lru_page(page);
2509 }
2510
Yang Shif661d002020-04-01 21:10:05 -07002511 nid = NUMA_NO_NODE;
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002512 }
2513
2514 if (!list_empty(&node_page_list)) {
2515 nr_reclaimed += shrink_page_list(&node_page_list,
2516 NODE_DATA(nid),
Shakeel Butt013339d2020-12-14 19:06:39 -08002517 &sc, &dummy_stat, false);
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002518 while (!list_empty(&node_page_list)) {
2519 page = lru_to_page(&node_page_list);
2520 list_del(&page->lru);
2521 putback_lru_page(page);
2522 }
2523 }
2524
Yu Zhao2d2b8d22021-06-30 18:49:48 -07002525 memalloc_noreclaim_restore(noreclaim_flag);
2526
Minchan Kim1a4e58c2019-09-25 16:49:15 -07002527 return nr_reclaimed;
2528}
2529
Johannes Weinerb91ac372019-11-30 17:56:02 -08002530static unsigned long shrink_list(enum lru_list lru, unsigned long nr_to_scan,
2531 struct lruvec *lruvec, struct scan_control *sc)
2532{
2533 if (is_active_lru(lru)) {
2534 if (sc->may_deactivate & (1 << is_file_lru(lru)))
2535 shrink_active_list(nr_to_scan, lruvec, sc, lru);
2536 else
2537 sc->skipped_deactivate = 1;
2538 return 0;
2539 }
2540
2541 return shrink_inactive_list(nr_to_scan, lruvec, sc, lru);
2542}
2543
Rik van Riel59dc76b2016-05-20 16:56:31 -07002544/*
2545 * The inactive anon list should be small enough that the VM never has
2546 * to do too much work.
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002547 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002548 * The inactive file list should be small enough to leave most memory
2549 * to the established workingset on the scan-resistant active list,
2550 * but large enough to avoid thrashing the aggregate readahead window.
2551 *
2552 * Both inactive lists should also be large enough that each inactive
2553 * page has a chance to be referenced again before it is reclaimed.
2554 *
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002555 * If that fails and refaulting is observed, the inactive list grows.
2556 *
Rik van Riel59dc76b2016-05-20 16:56:31 -07002557 * The inactive_ratio is the target ratio of ACTIVE to INACTIVE pages
Andrey Ryabinin3a50d142017-11-15 17:34:15 -08002558 * on this LRU, maintained by the pageout code. An inactive_ratio
Rik van Riel59dc76b2016-05-20 16:56:31 -07002559 * of 3 means 3:1 or 25% of the pages are kept on the inactive list.
2560 *
2561 * total target max
2562 * memory ratio inactive
2563 * -------------------------------------
2564 * 10MB 1 5MB
2565 * 100MB 1 50MB
2566 * 1GB 3 250MB
2567 * 10GB 10 0.9GB
2568 * 100GB 31 3GB
2569 * 1TB 101 10GB
2570 * 10TB 320 32GB
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002571 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002572static bool inactive_is_low(struct lruvec *lruvec, enum lru_list inactive_lru)
KOSAKI Motohiro14797e22009-01-07 18:08:18 -08002573{
Johannes Weinerb91ac372019-11-30 17:56:02 -08002574 enum lru_list active_lru = inactive_lru + LRU_ACTIVE;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07002575 unsigned long inactive, active;
2576 unsigned long inactive_ratio;
Rik van Riel59dc76b2016-05-20 16:56:31 -07002577 unsigned long gb;
2578
Johannes Weinerb91ac372019-11-30 17:56:02 -08002579 inactive = lruvec_page_state(lruvec, NR_LRU_BASE + inactive_lru);
2580 active = lruvec_page_state(lruvec, NR_LRU_BASE + active_lru);
Mel Gormanf8d1a312016-07-28 15:47:34 -07002581
Johannes Weinerb91ac372019-11-30 17:56:02 -08002582 gb = (inactive + active) >> (30 - PAGE_SHIFT);
Joonsoo Kim40025702020-08-11 18:30:54 -07002583 if (gb)
Johannes Weinerb91ac372019-11-30 17:56:02 -08002584 inactive_ratio = int_sqrt(10 * gb);
2585 else
2586 inactive_ratio = 1;
Michal Hockofd538802017-02-22 15:45:58 -08002587
Rik van Riel59dc76b2016-05-20 16:56:31 -07002588 return inactive * inactive_ratio < active;
Rik van Rielb39415b2009-12-14 17:59:48 -08002589}
2590
Johannes Weiner9a265112013-02-22 16:32:17 -08002591enum scan_balance {
2592 SCAN_EQUAL,
2593 SCAN_FRACT,
2594 SCAN_ANON,
2595 SCAN_FILE,
2596};
2597
Yu Zhao3eb07702020-09-27 20:49:08 -06002598static void prepare_scan_count(pg_data_t *pgdat, struct scan_control *sc)
2599{
2600 unsigned long file;
2601 struct lruvec *target_lruvec;
2602
Yu Zhaoa1537a62022-01-27 20:32:37 -07002603 if (lru_gen_enabled())
2604 return;
2605
Yu Zhao3eb07702020-09-27 20:49:08 -06002606 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
2607
2608 /*
2609 * Flush the memory cgroup stats, so that we read accurate per-memcg
2610 * lruvec stats for heuristics.
2611 */
2612 mem_cgroup_flush_stats();
2613
2614 /*
2615 * Determine the scan balance between anon and file LRUs.
2616 */
2617 spin_lock_irq(&target_lruvec->lru_lock);
2618 sc->anon_cost = target_lruvec->anon_cost;
2619 sc->file_cost = target_lruvec->file_cost;
2620 spin_unlock_irq(&target_lruvec->lru_lock);
2621
2622 /*
2623 * Target desirable inactive:active list ratios for the anon
2624 * and file LRU lists.
2625 */
2626 if (!sc->force_deactivate) {
2627 unsigned long refaults;
2628
2629 refaults = lruvec_page_state(target_lruvec,
2630 WORKINGSET_ACTIVATE_ANON);
2631 if (refaults != target_lruvec->refaults[0] ||
2632 inactive_is_low(target_lruvec, LRU_INACTIVE_ANON))
2633 sc->may_deactivate |= DEACTIVATE_ANON;
2634 else
2635 sc->may_deactivate &= ~DEACTIVATE_ANON;
2636
2637 /*
2638 * When refaults are being observed, it means a new
2639 * workingset is being established. Deactivate to get
2640 * rid of any stale active pages quickly.
2641 */
2642 refaults = lruvec_page_state(target_lruvec,
2643 WORKINGSET_ACTIVATE_FILE);
2644 if (refaults != target_lruvec->refaults[1] ||
2645 inactive_is_low(target_lruvec, LRU_INACTIVE_FILE))
2646 sc->may_deactivate |= DEACTIVATE_FILE;
2647 else
2648 sc->may_deactivate &= ~DEACTIVATE_FILE;
2649 } else
2650 sc->may_deactivate = DEACTIVATE_ANON | DEACTIVATE_FILE;
2651
2652 /*
2653 * If we have plenty of inactive file pages that aren't
2654 * thrashing, try to reclaim those first before touching
2655 * anonymous pages.
2656 */
2657 file = lruvec_page_state(target_lruvec, NR_INACTIVE_FILE);
2658 if (file >> sc->priority && !(sc->may_deactivate & DEACTIVATE_FILE))
2659 sc->cache_trim_mode = 1;
2660 else
2661 sc->cache_trim_mode = 0;
2662
2663 /*
2664 * Prevent the reclaimer from falling into the cache trap: as
2665 * cache pages start out inactive, every cache fault will tip
2666 * the scan balance towards the file LRU. And as the file LRU
2667 * shrinks, so does the window for rotation from references.
2668 * This means we have a runaway feedback loop where a tiny
2669 * thrashing file LRU becomes infinitely more attractive than
2670 * anon pages. Try to detect this based on file LRU size.
2671 */
2672 if (!cgroup_reclaim(sc)) {
2673 unsigned long total_high_wmark = 0;
2674 unsigned long free, anon;
2675 int z;
2676
2677 free = sum_zone_node_page_state(pgdat->node_id, NR_FREE_PAGES);
2678 file = node_page_state(pgdat, NR_ACTIVE_FILE) +
2679 node_page_state(pgdat, NR_INACTIVE_FILE);
2680
2681 for (z = 0; z < MAX_NR_ZONES; z++) {
2682 struct zone *zone = &pgdat->node_zones[z];
2683
2684 if (!managed_zone(zone))
2685 continue;
2686
2687 total_high_wmark += high_wmark_pages(zone);
2688 }
2689
2690 /*
2691 * Consider anon: if that's low too, this isn't a
2692 * runaway file reclaim problem, but rather just
2693 * extreme pressure. Reclaim as per usual then.
2694 */
2695 anon = node_page_state(pgdat, NR_INACTIVE_ANON);
2696
2697 sc->file_is_tiny =
2698 file + free <= total_high_wmark &&
2699 !(sc->may_deactivate & DEACTIVATE_ANON) &&
2700 anon >> sc->priority;
2701 }
2702}
2703
Linus Torvalds1da177e2005-04-16 15:20:36 -07002704/*
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002705 * Determine how aggressively the anon and file LRU lists should be
2706 * scanned. The relative value of each set of LRU lists is determined
2707 * by looking at the fraction of the pages scanned we did rotate back
2708 * onto the active list instead of evict.
2709 *
Wanpeng Libe7bd592012-06-14 20:41:02 +08002710 * nr[0] = anon inactive pages to scan; nr[1] = anon active pages to scan
2711 * nr[2] = file inactive pages to scan; nr[3] = file active pages to scan
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002712 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002713static void get_scan_count(struct lruvec *lruvec, struct scan_control *sc,
2714 unsigned long *nr)
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002715{
Keith Buscha2a36482021-09-02 14:59:26 -07002716 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Johannes Weinerafaf07a2019-11-30 17:55:46 -08002717 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002718 unsigned long anon_cost, file_cost, total_cost;
Vladimir Davydov33377672016-01-20 15:02:59 -08002719 int swappiness = mem_cgroup_swappiness(memcg);
Yu Zhaoed017372020-10-15 20:09:55 -07002720 u64 fraction[ANON_AND_FILE];
Johannes Weiner9a265112013-02-22 16:32:17 -08002721 u64 denominator = 0; /* gcc */
Johannes Weiner9a265112013-02-22 16:32:17 -08002722 enum scan_balance scan_balance;
Johannes Weiner9a265112013-02-22 16:32:17 -08002723 unsigned long ap, fp;
2724 enum lru_list lru;
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002725 bool balance_anon_file_reclaim = false;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002726
2727 /* If we have no swap space, do not bother scanning anon pages. */
Keith Buscha2a36482021-09-02 14:59:26 -07002728 if (!sc->may_swap || !can_reclaim_anon_pages(memcg, pgdat->node_id, sc)) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002729 scan_balance = SCAN_FILE;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002730 goto out;
2731 }
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002732
Johannes Weiner10316b32013-02-22 16:32:14 -08002733 /*
2734 * Global reclaim will swap to prevent OOM even with no
2735 * swappiness, but memcg users want to use this knob to
2736 * disable swapping for individual groups completely when
2737 * using the memory controller's swap limit feature would be
2738 * too expensive.
2739 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08002740 if (cgroup_reclaim(sc) && !swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002741 scan_balance = SCAN_FILE;
Johannes Weiner10316b32013-02-22 16:32:14 -08002742 goto out;
2743 }
2744
2745 /*
2746 * Do not apply any pressure balancing cleverness when the
2747 * system is close to OOM, scan both anon and file equally
2748 * (unless the swappiness setting disagrees with swapping).
2749 */
Johannes Weiner02695172014-08-06 16:06:17 -07002750 if (!sc->priority && swappiness) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002751 scan_balance = SCAN_EQUAL;
Johannes Weiner10316b32013-02-22 16:32:14 -08002752 goto out;
2753 }
2754
Johannes Weiner11d16c22013-02-22 16:32:15 -08002755 /*
Johannes Weiner53138ce2019-11-30 17:55:56 -08002756 * If the system is almost out of file pages, force-scan anon.
Johannes Weiner62376252014-05-06 12:50:07 -07002757 */
Johannes Weinerb91ac372019-11-30 17:56:02 -08002758 if (sc->file_is_tiny) {
Johannes Weiner53138ce2019-11-30 17:55:56 -08002759 scan_balance = SCAN_ANON;
2760 goto out;
Johannes Weiner62376252014-05-06 12:50:07 -07002761 }
2762
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002763 trace_android_rvh_set_balance_anon_file_reclaim(&balance_anon_file_reclaim);
2764
Johannes Weiner62376252014-05-06 12:50:07 -07002765 /*
Johannes Weinerb91ac372019-11-30 17:56:02 -08002766 * If there is enough inactive page cache, we do not reclaim
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002767 * anything from the anonymous working right now. But when balancing
2768 * anon and page cache files for reclaim, allow swapping of anon pages
2769 * even if there are a number of inactive file cache pages.
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002770 */
Sudarshan Rajagopalan55b46b62021-06-01 04:05:01 -07002771 if (!balance_anon_file_reclaim && sc->cache_trim_mode) {
Johannes Weiner9a265112013-02-22 16:32:17 -08002772 scan_balance = SCAN_FILE;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002773 goto out;
2774 }
2775
Johannes Weiner9a265112013-02-22 16:32:17 -08002776 scan_balance = SCAN_FRACT;
Johannes Weiner7c5bd702013-02-22 16:32:10 -08002777 /*
Johannes Weiner314b57f2020-06-03 16:03:03 -07002778 * Calculate the pressure balance between anon and file pages.
2779 *
2780 * The amount of pressure we put on each LRU is inversely
2781 * proportional to the cost of reclaiming each list, as
2782 * determined by the share of pages that are refaulting, times
2783 * the relative IO cost of bringing back a swapped out
2784 * anonymous page vs reloading a filesystem page (swappiness).
2785 *
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002786 * Although we limit that influence to ensure no list gets
2787 * left behind completely: at least a third of the pressure is
2788 * applied, before swappiness.
2789 *
Johannes Weiner314b57f2020-06-03 16:03:03 -07002790 * With swappiness at 100, anon and file have equal IO cost.
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002791 */
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002792 total_cost = sc->anon_cost + sc->file_cost;
2793 anon_cost = total_cost + sc->anon_cost;
2794 file_cost = total_cost + sc->file_cost;
2795 total_cost = anon_cost + file_cost;
KOSAKI Motohiro58c37f62010-08-09 17:19:51 -07002796
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002797 ap = swappiness * (total_cost + 1);
2798 ap /= anon_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002799
Johannes Weinerd483a5d2020-06-03 16:03:13 -07002800 fp = (200 - swappiness) * (total_cost + 1);
2801 fp /= file_cost + 1;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002802
Shaohua Li76a33fc2010-05-24 14:32:36 -07002803 fraction[0] = ap;
2804 fraction[1] = fp;
Johannes Weinera4fe1632020-06-03 16:02:50 -07002805 denominator = ap + fp;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002806out:
Johannes Weiner688035f2017-05-03 14:52:07 -07002807 for_each_evictable_lru(lru) {
2808 int file = is_file_lru(lru);
Chris Down9783aa92019-10-06 17:58:32 -07002809 unsigned long lruvec_size;
Johannes Weinerf56ce412021-08-19 19:04:21 -07002810 unsigned long low, min;
Johannes Weiner688035f2017-05-03 14:52:07 -07002811 unsigned long scan;
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002812
Chris Down9783aa92019-10-06 17:58:32 -07002813 lruvec_size = lruvec_lru_size(lruvec, lru, sc->reclaim_idx);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002814 mem_cgroup_protection(sc->target_mem_cgroup, memcg,
2815 &min, &low);
Chris Down9783aa92019-10-06 17:58:32 -07002816
Johannes Weinerf56ce412021-08-19 19:04:21 -07002817 if (min || low) {
Chris Down9783aa92019-10-06 17:58:32 -07002818 /*
2819 * Scale a cgroup's reclaim pressure by proportioning
2820 * its current usage to its memory.low or memory.min
2821 * setting.
2822 *
2823 * This is important, as otherwise scanning aggression
2824 * becomes extremely binary -- from nothing as we
2825 * approach the memory protection threshold, to totally
2826 * nominal as we exceed it. This results in requiring
2827 * setting extremely liberal protection thresholds. It
2828 * also means we simply get no protection at all if we
2829 * set it too low, which is not ideal.
Chris Down1bc63fb2019-10-06 17:58:38 -07002830 *
2831 * If there is any protection in place, we reduce scan
2832 * pressure by how much of the total memory used is
2833 * within protection thresholds.
Chris Down9783aa92019-10-06 17:58:32 -07002834 *
Chris Down9de7ca42019-10-06 17:58:35 -07002835 * There is one special case: in the first reclaim pass,
2836 * we skip over all groups that are within their low
2837 * protection. If that fails to reclaim enough pages to
2838 * satisfy the reclaim goal, we come back and override
2839 * the best-effort low protection. However, we still
2840 * ideally want to honor how well-behaved groups are in
2841 * that case instead of simply punishing them all
2842 * equally. As such, we reclaim them based on how much
Chris Down1bc63fb2019-10-06 17:58:38 -07002843 * memory they are using, reducing the scan pressure
2844 * again by how much of the total memory used is under
2845 * hard protection.
Chris Down9783aa92019-10-06 17:58:32 -07002846 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002847 unsigned long cgroup_size = mem_cgroup_size(memcg);
Johannes Weinerf56ce412021-08-19 19:04:21 -07002848 unsigned long protection;
2849
2850 /* memory.low scaling, make sure we retry before OOM */
2851 if (!sc->memcg_low_reclaim && low > min) {
2852 protection = low;
2853 sc->memcg_low_skipped = 1;
2854 } else {
2855 protection = min;
2856 }
Chris Down1bc63fb2019-10-06 17:58:38 -07002857
2858 /* Avoid TOCTOU with earlier protection check */
2859 cgroup_size = max(cgroup_size, protection);
2860
2861 scan = lruvec_size - lruvec_size * protection /
Rik van Riel32d4f4b2021-09-08 18:10:08 -07002862 (cgroup_size + 1);
Chris Down9783aa92019-10-06 17:58:32 -07002863
2864 /*
Chris Down1bc63fb2019-10-06 17:58:38 -07002865 * Minimally target SWAP_CLUSTER_MAX pages to keep
Ethon Paul55b65a52020-06-04 16:49:10 -07002866 * reclaim moving forwards, avoiding decrementing
Chris Down9de7ca42019-10-06 17:58:35 -07002867 * sc->priority further than desirable.
Chris Down9783aa92019-10-06 17:58:32 -07002868 */
Chris Down1bc63fb2019-10-06 17:58:38 -07002869 scan = max(scan, SWAP_CLUSTER_MAX);
Chris Down9783aa92019-10-06 17:58:32 -07002870 } else {
2871 scan = lruvec_size;
2872 }
2873
2874 scan >>= sc->priority;
2875
Johannes Weiner688035f2017-05-03 14:52:07 -07002876 /*
2877 * If the cgroup's already been deleted, make sure to
2878 * scrape out the remaining cache.
2879 */
2880 if (!scan && !mem_cgroup_online(memcg))
Chris Down9783aa92019-10-06 17:58:32 -07002881 scan = min(lruvec_size, SWAP_CLUSTER_MAX);
Johannes Weiner9a265112013-02-22 16:32:17 -08002882
Johannes Weiner688035f2017-05-03 14:52:07 -07002883 switch (scan_balance) {
2884 case SCAN_EQUAL:
2885 /* Scan lists relative to size */
2886 break;
2887 case SCAN_FRACT:
Johannes Weiner9a265112013-02-22 16:32:17 -08002888 /*
Johannes Weiner688035f2017-05-03 14:52:07 -07002889 * Scan types proportional to swappiness and
2890 * their relative recent reclaim efficiency.
Gavin Shan76073c62020-02-20 20:04:24 -08002891 * Make sure we don't miss the last page on
2892 * the offlined memory cgroups because of a
2893 * round-off error.
Johannes Weiner9a265112013-02-22 16:32:17 -08002894 */
Gavin Shan76073c62020-02-20 20:04:24 -08002895 scan = mem_cgroup_online(memcg) ?
2896 div64_u64(scan * fraction[file], denominator) :
2897 DIV64_U64_ROUND_UP(scan * fraction[file],
Roman Gushchin68600f62018-10-26 15:03:27 -07002898 denominator);
Johannes Weiner688035f2017-05-03 14:52:07 -07002899 break;
2900 case SCAN_FILE:
2901 case SCAN_ANON:
2902 /* Scan one type exclusively */
Mateusz Noseke072bff2020-04-01 21:10:15 -07002903 if ((scan_balance == SCAN_FILE) != file)
Johannes Weiner688035f2017-05-03 14:52:07 -07002904 scan = 0;
Johannes Weiner688035f2017-05-03 14:52:07 -07002905 break;
2906 default:
2907 /* Look ma, no brain */
2908 BUG();
Johannes Weiner9a265112013-02-22 16:32:17 -08002909 }
Johannes Weiner688035f2017-05-03 14:52:07 -07002910
Johannes Weiner688035f2017-05-03 14:52:07 -07002911 nr[lru] = scan;
Shaohua Li76a33fc2010-05-24 14:32:36 -07002912 }
Wu Fengguang6e08a362009-06-16 15:32:29 -07002913}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07002914
Dave Hansen2f368a92021-09-02 14:59:23 -07002915/*
2916 * Anonymous LRU management is a waste if there is
2917 * ultimately no way to reclaim the memory.
2918 */
2919static bool can_age_anon_pages(struct pglist_data *pgdat,
2920 struct scan_control *sc)
2921{
2922 /* Aging the anon LRU is valuable if swap is present: */
2923 if (total_swap_pages > 0)
2924 return true;
2925
2926 /* Also valuable if anon pages can be demoted: */
2927 return can_demote(pgdat->node_id, sc);
2928}
2929
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002930#ifdef CONFIG_LRU_GEN
2931
Yu Zhao76f7f072022-01-27 19:52:09 -07002932#ifdef CONFIG_LRU_GEN_ENABLED
2933DEFINE_STATIC_KEY_ARRAY_TRUE(lru_gen_caps, NR_LRU_GEN_CAPS);
2934#else
2935DEFINE_STATIC_KEY_ARRAY_FALSE(lru_gen_caps, NR_LRU_GEN_CAPS);
2936#endif
2937
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002938/******************************************************************************
2939 * shorthand helpers
2940 ******************************************************************************/
2941
Yu Zhaoa1537a62022-01-27 20:32:37 -07002942#define DEFINE_MAX_SEQ(lruvec) \
2943 unsigned long max_seq = READ_ONCE((lruvec)->lrugen.max_seq)
2944
2945#define DEFINE_MIN_SEQ(lruvec) \
2946 unsigned long min_seq[ANON_AND_FILE] = { \
2947 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_ANON]), \
2948 READ_ONCE((lruvec)->lrugen.min_seq[LRU_GEN_FILE]), \
2949 }
2950
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002951#define for_each_gen_type_zone(gen, type, zone) \
2952 for ((gen) = 0; (gen) < MAX_NR_GENS; (gen)++) \
2953 for ((type) = 0; (type) < ANON_AND_FILE; (type)++) \
2954 for ((zone) = 0; (zone) < MAX_NR_ZONES; (zone)++)
2955
Yu Zhaoa1537a62022-01-27 20:32:37 -07002956static int page_lru_gen(struct page *page)
2957{
2958 unsigned long flags = READ_ONCE(page->flags);
2959
2960 return ((flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
2961}
2962
2963static int page_lru_tier(struct page *page)
2964{
2965 int refs;
2966 unsigned long flags = READ_ONCE(page->flags);
2967
2968 refs = (flags & LRU_REFS_FLAGS) == LRU_REFS_FLAGS ?
2969 ((flags & LRU_REFS_MASK) >> LRU_REFS_PGOFF) + 1 : 0;
2970
2971 return lru_tier_from_refs(refs);
2972}
2973
Yu Zhao76f7f072022-01-27 19:52:09 -07002974static bool get_cap(int cap)
2975{
2976#ifdef CONFIG_LRU_GEN_ENABLED
2977 return static_branch_likely(&lru_gen_caps[cap]);
2978#else
2979 return static_branch_unlikely(&lru_gen_caps[cap]);
2980#endif
2981}
2982
Yu Zhaof88ed5a2021-01-25 21:12:33 -07002983static struct lruvec *get_lruvec(struct mem_cgroup *memcg, int nid)
2984{
2985 struct pglist_data *pgdat = NODE_DATA(nid);
2986
2987#ifdef CONFIG_MEMCG
2988 if (memcg) {
2989 struct lruvec *lruvec = &memcg->nodeinfo[nid]->lruvec;
2990
2991 /* for hotadd_new_pgdat() */
2992 if (!lruvec->pgdat)
2993 lruvec->pgdat = pgdat;
2994
2995 return lruvec;
2996 }
2997#endif
2998 VM_BUG_ON(!mem_cgroup_disabled());
2999
3000 return pgdat ? &pgdat->__lruvec : NULL;
3001}
3002
Yu Zhaoa1537a62022-01-27 20:32:37 -07003003static int get_swappiness(struct lruvec *lruvec, struct scan_control *sc)
3004{
3005 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3006 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
3007
3008 if (!can_demote(pgdat->node_id, sc) &&
3009 mem_cgroup_get_nr_swap_pages(memcg) < MIN_LRU_BATCH)
3010 return 0;
3011
3012 return mem_cgroup_swappiness(memcg);
3013}
3014
3015static int get_nr_gens(struct lruvec *lruvec, int type)
3016{
3017 return lruvec->lrugen.max_seq - lruvec->lrugen.min_seq[type] + 1;
3018}
3019
3020static bool __maybe_unused seq_is_valid(struct lruvec *lruvec)
3021{
3022 /* see the comment on lru_gen_struct */
3023 return get_nr_gens(lruvec, LRU_GEN_FILE) >= MIN_NR_GENS &&
3024 get_nr_gens(lruvec, LRU_GEN_FILE) <= get_nr_gens(lruvec, LRU_GEN_ANON) &&
3025 get_nr_gens(lruvec, LRU_GEN_ANON) <= MAX_NR_GENS;
3026}
3027
3028/******************************************************************************
Yu Zhao5280d762022-01-27 19:23:01 -07003029 * mm_struct list
3030 ******************************************************************************/
3031
3032static struct lru_gen_mm_list *get_mm_list(struct mem_cgroup *memcg)
3033{
3034 static struct lru_gen_mm_list mm_list = {
3035 .fifo = LIST_HEAD_INIT(mm_list.fifo),
3036 .lock = __SPIN_LOCK_UNLOCKED(mm_list.lock),
3037 };
3038
3039#ifdef CONFIG_MEMCG
3040 if (memcg)
3041 return &memcg->mm_list;
3042#endif
3043 VM_BUG_ON(!mem_cgroup_disabled());
3044
3045 return &mm_list;
3046}
3047
3048void lru_gen_add_mm(struct mm_struct *mm)
3049{
3050 int nid;
3051 struct mem_cgroup *memcg = get_mem_cgroup_from_mm(mm);
3052 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3053
3054 VM_BUG_ON_MM(!list_empty(&mm->lru_gen.list), mm);
3055#ifdef CONFIG_MEMCG
3056 VM_BUG_ON_MM(mm->lru_gen.memcg, mm);
3057 mm->lru_gen.memcg = memcg;
3058#endif
3059 spin_lock(&mm_list->lock);
3060
3061 for_each_node_state(nid, N_MEMORY) {
3062 struct lruvec *lruvec = get_lruvec(memcg, nid);
3063
3064 if (!lruvec)
3065 continue;
3066
3067 if (lruvec->mm_state.tail == &mm_list->fifo)
3068 lruvec->mm_state.tail = &mm->lru_gen.list;
3069 }
3070
3071 list_add_tail(&mm->lru_gen.list, &mm_list->fifo);
3072
3073 spin_unlock(&mm_list->lock);
3074}
3075
3076void lru_gen_del_mm(struct mm_struct *mm)
3077{
3078 int nid;
3079 struct lru_gen_mm_list *mm_list;
3080 struct mem_cgroup *memcg = NULL;
3081
3082 if (list_empty(&mm->lru_gen.list))
3083 return;
3084
3085#ifdef CONFIG_MEMCG
3086 memcg = mm->lru_gen.memcg;
3087#endif
3088 mm_list = get_mm_list(memcg);
3089
3090 spin_lock(&mm_list->lock);
3091
3092 for_each_node(nid) {
3093 struct lruvec *lruvec = get_lruvec(memcg, nid);
3094
3095 if (!lruvec)
3096 continue;
3097
3098 if (lruvec->mm_state.tail == &mm->lru_gen.list)
3099 lruvec->mm_state.tail = lruvec->mm_state.tail->next;
3100
3101 if (lruvec->mm_state.head != &mm->lru_gen.list)
3102 continue;
3103
3104 lruvec->mm_state.head = lruvec->mm_state.head->next;
3105 if (lruvec->mm_state.head == &mm_list->fifo)
3106 WRITE_ONCE(lruvec->mm_state.seq, lruvec->mm_state.seq + 1);
3107 }
3108
3109 list_del_init(&mm->lru_gen.list);
3110
3111 spin_unlock(&mm_list->lock);
3112
3113#ifdef CONFIG_MEMCG
3114 mem_cgroup_put(mm->lru_gen.memcg);
3115 mm->lru_gen.memcg = NULL;
3116#endif
3117}
3118
3119#ifdef CONFIG_MEMCG
3120void lru_gen_migrate_mm(struct mm_struct *mm)
3121{
3122 struct mem_cgroup *memcg;
3123
3124 lockdep_assert_held(&mm->owner->alloc_lock);
3125
3126 /* for mm_update_next_owner() */
3127 if (mem_cgroup_disabled())
3128 return;
3129
3130 rcu_read_lock();
3131 memcg = mem_cgroup_from_task(mm->owner);
3132 rcu_read_unlock();
3133 if (memcg == mm->lru_gen.memcg)
3134 return;
3135
3136 VM_BUG_ON_MM(!mm->lru_gen.memcg, mm);
3137 VM_BUG_ON_MM(list_empty(&mm->lru_gen.list), mm);
3138
3139 lru_gen_del_mm(mm);
3140 lru_gen_add_mm(mm);
3141}
3142#endif
3143
3144/*
3145 * Bloom filters with m=1<<15, k=2 and the false positive rates of ~1/5 when
3146 * n=10,000 and ~1/2 when n=20,000, where, conventionally, m is the number of
3147 * bits in a bitmap, k is the number of hash functions and n is the number of
3148 * inserted items.
3149 *
3150 * Page table walkers use one of the two filters to reduce their search space.
3151 * To get rid of non-leaf entries that no longer have enough leaf entries, the
3152 * aging uses the double-buffering technique to flip to the other filter each
3153 * time it produces a new generation. For non-leaf entries that have enough
3154 * leaf entries, the aging carries them over to the next generation in
3155 * walk_pmd_range(); the eviction also report them when walking the rmap
3156 * in lru_gen_look_around().
3157 *
3158 * For future optimizations:
3159 * 1. It's not necessary to keep both filters all the time. The spare one can be
3160 * freed after the RCU grace period and reallocated if needed again.
3161 * 2. And when reallocating, it's worth scaling its size according to the number
3162 * of inserted entries in the other filter, to reduce the memory overhead on
3163 * small systems and false positives on large systems.
3164 * 3. Jenkins' hash function is an alternative to Knuth's.
3165 */
3166#define BLOOM_FILTER_SHIFT 15
3167
3168static inline int filter_gen_from_seq(unsigned long seq)
3169{
3170 return seq % NR_BLOOM_FILTERS;
3171}
3172
3173static void get_item_key(void *item, int *key)
3174{
3175 u32 hash = hash_ptr(item, BLOOM_FILTER_SHIFT * 2);
3176
3177 BUILD_BUG_ON(BLOOM_FILTER_SHIFT * 2 > BITS_PER_TYPE(u32));
3178
3179 key[0] = hash & (BIT(BLOOM_FILTER_SHIFT) - 1);
3180 key[1] = hash >> BLOOM_FILTER_SHIFT;
3181}
3182
3183static void reset_bloom_filter(struct lruvec *lruvec, unsigned long seq)
3184{
3185 unsigned long *filter;
3186 int gen = filter_gen_from_seq(seq);
3187
3188 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3189
3190 filter = lruvec->mm_state.filters[gen];
3191 if (filter) {
3192 bitmap_clear(filter, 0, BIT(BLOOM_FILTER_SHIFT));
3193 return;
3194 }
3195
3196 filter = bitmap_zalloc(BIT(BLOOM_FILTER_SHIFT), GFP_ATOMIC);
3197 WRITE_ONCE(lruvec->mm_state.filters[gen], filter);
3198}
3199
3200static void update_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3201{
3202 int key[2];
3203 unsigned long *filter;
3204 int gen = filter_gen_from_seq(seq);
3205
3206 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3207 if (!filter)
3208 return;
3209
3210 get_item_key(item, key);
3211
3212 if (!test_bit(key[0], filter))
3213 set_bit(key[0], filter);
3214 if (!test_bit(key[1], filter))
3215 set_bit(key[1], filter);
3216}
3217
3218static bool test_bloom_filter(struct lruvec *lruvec, unsigned long seq, void *item)
3219{
3220 int key[2];
3221 unsigned long *filter;
3222 int gen = filter_gen_from_seq(seq);
3223
3224 filter = READ_ONCE(lruvec->mm_state.filters[gen]);
3225 if (!filter)
3226 return true;
3227
3228 get_item_key(item, key);
3229
3230 return test_bit(key[0], filter) && test_bit(key[1], filter);
3231}
3232
3233static void reset_mm_stats(struct lruvec *lruvec, struct lru_gen_mm_walk *walk, bool last)
3234{
3235 int i;
3236 int hist;
3237
3238 lockdep_assert_held(&get_mm_list(lruvec_memcg(lruvec))->lock);
3239
3240 if (walk) {
3241 hist = lru_hist_from_seq(walk->max_seq);
3242
3243 for (i = 0; i < NR_MM_STATS; i++) {
3244 WRITE_ONCE(lruvec->mm_state.stats[hist][i],
3245 lruvec->mm_state.stats[hist][i] + walk->mm_stats[i]);
3246 walk->mm_stats[i] = 0;
3247 }
3248 }
3249
3250 if (NR_HIST_GENS > 1 && last) {
3251 hist = lru_hist_from_seq(lruvec->mm_state.seq + 1);
3252
3253 for (i = 0; i < NR_MM_STATS; i++)
3254 WRITE_ONCE(lruvec->mm_state.stats[hist][i], 0);
3255 }
3256}
3257
3258static bool should_skip_mm(struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3259{
3260 int type;
3261 unsigned long size = 0;
3262 struct pglist_data *pgdat = lruvec_pgdat(walk->lruvec);
3263
3264 if (!walk->full_scan && cpumask_empty(mm_cpumask(mm)) &&
3265 !node_isset(pgdat->node_id, mm->lru_gen.nodes))
3266 return true;
3267
3268 node_clear(pgdat->node_id, mm->lru_gen.nodes);
3269
3270 for (type = !walk->can_swap; type < ANON_AND_FILE; type++) {
3271 size += type ? get_mm_counter(mm, MM_FILEPAGES) :
3272 get_mm_counter(mm, MM_ANONPAGES) +
3273 get_mm_counter(mm, MM_SHMEMPAGES);
3274 }
3275
3276 if (size < MIN_LRU_BATCH)
3277 return true;
3278
3279 if (mm_is_oom_victim(mm))
3280 return true;
3281
3282 return !mmget_not_zero(mm);
3283}
3284
3285static bool iterate_mm_list(struct lruvec *lruvec, struct lru_gen_mm_walk *walk,
3286 struct mm_struct **iter)
3287{
3288 bool first = false;
3289 bool last = true;
3290 struct mm_struct *mm = NULL;
3291 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3292 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3293 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3294
3295 /*
3296 * There are four interesting cases for this page table walker:
3297 * 1. It tries to start a new iteration of mm_list with a stale max_seq;
3298 * there is nothing to be done.
3299 * 2. It's the first of the current generation, and it needs to reset
3300 * the Bloom filter for the next generation.
3301 * 3. It reaches the end of mm_list, and it needs to increment
3302 * mm_state->seq; the iteration is done.
3303 * 4. It's the last of the current generation, and it needs to reset the
3304 * mm stats counters for the next generation.
3305 */
3306 if (*iter)
3307 mmput_async(*iter);
3308 else if (walk->max_seq <= READ_ONCE(mm_state->seq))
3309 return false;
3310
3311 spin_lock(&mm_list->lock);
3312
3313 VM_BUG_ON(mm_state->seq + 1 < walk->max_seq);
3314 VM_BUG_ON(*iter && mm_state->seq > walk->max_seq);
3315 VM_BUG_ON(*iter && !mm_state->nr_walkers);
3316
3317 if (walk->max_seq <= mm_state->seq) {
3318 if (!*iter)
3319 last = false;
3320 goto done;
3321 }
3322
3323 if (!mm_state->nr_walkers) {
3324 VM_BUG_ON(mm_state->head && mm_state->head != &mm_list->fifo);
3325
3326 mm_state->head = mm_list->fifo.next;
3327 first = true;
3328 }
3329
3330 while (!mm && mm_state->head != &mm_list->fifo) {
3331 mm = list_entry(mm_state->head, struct mm_struct, lru_gen.list);
3332
3333 mm_state->head = mm_state->head->next;
3334
3335 /* full scan for those added after the last iteration */
3336 if (!mm_state->tail || mm_state->tail == &mm->lru_gen.list) {
3337 mm_state->tail = mm_state->head;
3338 walk->full_scan = true;
3339 }
3340
3341 if (should_skip_mm(mm, walk))
3342 mm = NULL;
3343 }
3344
3345 if (mm_state->head == &mm_list->fifo)
3346 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3347done:
3348 if (*iter && !mm)
3349 mm_state->nr_walkers--;
3350 if (!*iter && mm)
3351 mm_state->nr_walkers++;
3352
3353 if (mm_state->nr_walkers)
3354 last = false;
3355
3356 if (mm && first)
3357 reset_bloom_filter(lruvec, walk->max_seq + 1);
3358
3359 if (*iter || last)
3360 reset_mm_stats(lruvec, walk, last);
3361
3362 spin_unlock(&mm_list->lock);
3363
3364 *iter = mm;
3365
3366 return last;
3367}
3368
3369static bool iterate_mm_list_nowalk(struct lruvec *lruvec, unsigned long max_seq)
3370{
3371 bool success = false;
3372 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3373 struct lru_gen_mm_list *mm_list = get_mm_list(memcg);
3374 struct lru_gen_mm_state *mm_state = &lruvec->mm_state;
3375
3376 if (max_seq <= READ_ONCE(mm_state->seq))
3377 return false;
3378
3379 spin_lock(&mm_list->lock);
3380
3381 VM_BUG_ON(mm_state->seq + 1 < max_seq);
3382
3383 if (max_seq > mm_state->seq && !mm_state->nr_walkers) {
3384 VM_BUG_ON(mm_state->head && mm_state->head != &mm_list->fifo);
3385
3386 WRITE_ONCE(mm_state->seq, mm_state->seq + 1);
3387 reset_mm_stats(lruvec, NULL, true);
3388 success = true;
3389 }
3390
3391 spin_unlock(&mm_list->lock);
3392
3393 return success;
3394}
3395
3396/******************************************************************************
Yu Zhaoa1537a62022-01-27 20:32:37 -07003397 * refault feedback loop
3398 ******************************************************************************/
3399
3400/*
3401 * A feedback loop based on Proportional-Integral-Derivative (PID) controller.
3402 *
3403 * The P term is refaulted/(evicted+protected) from a tier in the generation
3404 * currently being evicted; the I term is the exponential moving average of the
3405 * P term over the generations previously evicted, using the smoothing factor
3406 * 1/2; the D term isn't supported.
3407 *
3408 * The setpoint (SP) is always the first tier of one type; the process variable
3409 * (PV) is either any tier of the other type or any other tier of the same
3410 * type.
3411 *
3412 * The error is the difference between the SP and the PV; the correction is
3413 * turn off protection when SP>PV or turn on protection when SP<PV.
3414 *
3415 * For future optimizations:
3416 * 1. The D term may discount the other two terms over time so that long-lived
3417 * generations can resist stale information.
3418 */
3419struct ctrl_pos {
3420 unsigned long refaulted;
3421 unsigned long total;
3422 int gain;
3423};
3424
3425static void read_ctrl_pos(struct lruvec *lruvec, int type, int tier, int gain,
3426 struct ctrl_pos *pos)
3427{
3428 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3429 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
3430
3431 pos->refaulted = lrugen->avg_refaulted[type][tier] +
3432 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3433 pos->total = lrugen->avg_total[type][tier] +
3434 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3435 if (tier)
3436 pos->total += lrugen->protected[hist][type][tier - 1];
3437 pos->gain = gain;
3438}
3439
3440static void reset_ctrl_pos(struct lruvec *lruvec, int type, bool carryover)
3441{
3442 int hist, tier;
3443 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3444 bool clear = carryover ? NR_HIST_GENS == 1 : NR_HIST_GENS > 1;
3445 unsigned long seq = carryover ? lrugen->min_seq[type] : lrugen->max_seq + 1;
3446
3447 lockdep_assert_held(&lruvec->lru_lock);
3448
3449 if (!carryover && !clear)
3450 return;
3451
3452 hist = lru_hist_from_seq(seq);
3453
3454 for (tier = 0; tier < MAX_NR_TIERS; tier++) {
3455 if (carryover) {
3456 unsigned long sum;
3457
3458 sum = lrugen->avg_refaulted[type][tier] +
3459 atomic_long_read(&lrugen->refaulted[hist][type][tier]);
3460 WRITE_ONCE(lrugen->avg_refaulted[type][tier], sum / 2);
3461
3462 sum = lrugen->avg_total[type][tier] +
3463 atomic_long_read(&lrugen->evicted[hist][type][tier]);
3464 if (tier)
3465 sum += lrugen->protected[hist][type][tier - 1];
3466 WRITE_ONCE(lrugen->avg_total[type][tier], sum / 2);
3467 }
3468
3469 if (clear) {
3470 atomic_long_set(&lrugen->refaulted[hist][type][tier], 0);
3471 atomic_long_set(&lrugen->evicted[hist][type][tier], 0);
3472 if (tier)
3473 WRITE_ONCE(lrugen->protected[hist][type][tier - 1], 0);
3474 }
3475 }
3476}
3477
3478static bool positive_ctrl_err(struct ctrl_pos *sp, struct ctrl_pos *pv)
3479{
3480 /*
3481 * Return true if the PV has a limited number of refaults or a lower
3482 * refaulted/total than the SP.
3483 */
3484 return pv->refaulted < MIN_LRU_BATCH ||
3485 pv->refaulted * (sp->total + MIN_LRU_BATCH) * sp->gain <=
3486 (sp->refaulted + 1) * pv->total * pv->gain;
3487}
3488
3489/******************************************************************************
3490 * the aging
3491 ******************************************************************************/
3492
Yu Zhaoafd94c92022-01-27 20:43:22 -07003493static int page_update_gen(struct page *page, int gen)
3494{
3495 unsigned long old_flags, new_flags;
3496
3497 VM_BUG_ON(gen >= MAX_NR_GENS);
3498 VM_BUG_ON(!rcu_read_lock_held());
3499
3500 do {
3501 new_flags = old_flags = READ_ONCE(page->flags);
3502
3503 /* for shrink_page_list() */
3504 if (!(new_flags & LRU_GEN_MASK)) {
3505 new_flags |= BIT(PG_referenced);
3506 continue;
3507 }
3508
3509 new_flags &= ~LRU_GEN_MASK;
3510 new_flags |= (gen + 1UL) << LRU_GEN_PGOFF;
3511 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3512 } while (new_flags != old_flags &&
3513 cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3514
3515 return ((old_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3516}
3517
Yu Zhaoa1537a62022-01-27 20:32:37 -07003518static int page_inc_gen(struct lruvec *lruvec, struct page *page, bool reclaiming)
3519{
3520 unsigned long old_flags, new_flags;
3521 int type = page_is_file_lru(page);
3522 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3523 int new_gen, old_gen = lru_gen_from_seq(lrugen->min_seq[type]);
3524
3525 do {
3526 new_flags = old_flags = READ_ONCE(page->flags);
3527 VM_BUG_ON_PAGE(!(new_flags & LRU_GEN_MASK), page);
3528
Yu Zhaoafd94c92022-01-27 20:43:22 -07003529 new_gen = ((new_flags & LRU_GEN_MASK) >> LRU_GEN_PGOFF) - 1;
3530 /* page_update_gen() has promoted this page? */
3531 if (new_gen >= 0 && new_gen != old_gen)
3532 return new_gen;
3533
Yu Zhaoa1537a62022-01-27 20:32:37 -07003534 new_gen = (old_gen + 1) % MAX_NR_GENS;
3535
3536 new_flags &= ~LRU_GEN_MASK;
3537 new_flags |= (new_gen + 1UL) << LRU_GEN_PGOFF;
3538 new_flags &= ~(LRU_REFS_MASK | LRU_REFS_FLAGS);
3539 /* for end_page_writeback() */
3540 if (reclaiming)
3541 new_flags |= BIT(PG_reclaim);
3542 } while (cmpxchg(&page->flags, old_flags, new_flags) != old_flags);
3543
3544 lru_gen_update_size(lruvec, page, old_gen, new_gen);
3545
3546 return new_gen;
3547}
3548
Yu Zhao5280d762022-01-27 19:23:01 -07003549static void update_batch_size(struct lru_gen_mm_walk *walk, struct page *page,
3550 int old_gen, int new_gen)
3551{
3552 int type = page_is_file_lru(page);
3553 int zone = page_zonenum(page);
3554 int delta = thp_nr_pages(page);
3555
3556 VM_BUG_ON(old_gen >= MAX_NR_GENS);
3557 VM_BUG_ON(new_gen >= MAX_NR_GENS);
3558
3559 walk->batched++;
3560
3561 walk->nr_pages[old_gen][type][zone] -= delta;
3562 walk->nr_pages[new_gen][type][zone] += delta;
3563}
3564
3565static void reset_batch_size(struct lruvec *lruvec, struct lru_gen_mm_walk *walk)
3566{
3567 int gen, type, zone;
3568 struct lru_gen_struct *lrugen = &lruvec->lrugen;
3569
3570 walk->batched = 0;
3571
3572 for_each_gen_type_zone(gen, type, zone) {
3573 enum lru_list lru = type * LRU_INACTIVE_FILE;
3574 int delta = walk->nr_pages[gen][type][zone];
3575
3576 if (!delta)
3577 continue;
3578
3579 walk->nr_pages[gen][type][zone] = 0;
3580 WRITE_ONCE(lrugen->nr_pages[gen][type][zone],
3581 lrugen->nr_pages[gen][type][zone] + delta);
3582
3583 if (lru_gen_is_active(lruvec, gen))
3584 lru += LRU_ACTIVE;
3585 __update_lru_size(lruvec, lru, zone, delta);
3586 }
3587}
3588
3589static int should_skip_vma(unsigned long start, unsigned long end, struct mm_walk *walk)
3590{
3591 struct address_space *mapping;
3592 struct vm_area_struct *vma = walk->vma;
3593 struct lru_gen_mm_walk *priv = walk->private;
3594
3595 if (!vma_is_accessible(vma) || is_vm_hugetlb_page(vma) ||
3596 (vma->vm_flags & (VM_LOCKED | VM_SPECIAL | VM_SEQ_READ | VM_RAND_READ)) ||
3597 vma == get_gate_vma(vma->vm_mm))
3598 return true;
3599
3600 if (vma_is_anonymous(vma))
3601 return !priv->can_swap;
3602
3603 if (WARN_ON_ONCE(!vma->vm_file || !vma->vm_file->f_mapping))
3604 return true;
3605
3606 mapping = vma->vm_file->f_mapping;
3607 if (mapping_unevictable(mapping))
3608 return true;
3609
3610 /* check readpage to exclude special mappings like dax, etc. */
3611 return shmem_mapping(mapping) ? !priv->can_swap : !mapping->a_ops->readpage;
3612}
3613
3614/*
3615 * Some userspace memory allocators map many single-page VMAs. Instead of
3616 * returning back to the PGD table for each of such VMAs, finish an entire PMD
3617 * table to reduce zigzags and improve cache performance.
3618 */
3619static bool get_next_vma(struct mm_walk *walk, unsigned long mask, unsigned long size,
3620 unsigned long *start, unsigned long *end)
3621{
3622 unsigned long next = round_up(*end, size);
3623
3624 VM_BUG_ON(mask & size);
3625 VM_BUG_ON(*start >= *end);
3626 VM_BUG_ON((next & mask) != (*start & mask));
3627
3628 while (walk->vma) {
3629 if (next >= walk->vma->vm_end) {
3630 walk->vma = walk->vma->vm_next;
3631 continue;
3632 }
3633
3634 if ((next & mask) != (walk->vma->vm_start & mask))
3635 return false;
3636
3637 if (should_skip_vma(walk->vma->vm_start, walk->vma->vm_end, walk)) {
3638 walk->vma = walk->vma->vm_next;
3639 continue;
3640 }
3641
3642 *start = max(next, walk->vma->vm_start);
3643 next = (next | ~mask) + 1;
3644 /* rounded-up boundaries can wrap to 0 */
3645 *end = next && next < walk->vma->vm_end ? next : walk->vma->vm_end;
3646
3647 return true;
3648 }
3649
3650 return false;
3651}
3652
3653static bool suitable_to_scan(int total, int young)
3654{
3655 int n = clamp_t(int, cache_line_size() / sizeof(pte_t), 2, 8);
3656
3657 /* suitable if the average number of young PTEs per cacheline is >=1 */
3658 return young * n >= total;
3659}
3660
3661static bool walk_pte_range(pmd_t *pmd, unsigned long start, unsigned long end,
3662 struct mm_walk *walk)
3663{
3664 int i;
3665 pte_t *pte;
3666 spinlock_t *ptl;
3667 unsigned long addr;
3668 int total = 0;
3669 int young = 0;
3670 struct lru_gen_mm_walk *priv = walk->private;
3671 struct mem_cgroup *memcg = lruvec_memcg(priv->lruvec);
3672 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3673 int old_gen, new_gen = lru_gen_from_seq(priv->max_seq);
3674
3675 VM_BUG_ON(pmd_leaf(*pmd));
3676
3677 ptl = pte_lockptr(walk->mm, pmd);
3678 if (!spin_trylock(ptl))
3679 return false;
3680
3681 arch_enter_lazy_mmu_mode();
3682
3683 pte = pte_offset_map(pmd, start & PMD_MASK);
3684restart:
3685 for (i = pte_index(start), addr = start; addr != end; i++, addr += PAGE_SIZE) {
3686 struct page *page;
3687 unsigned long pfn = pte_pfn(pte[i]);
3688
3689 VM_BUG_ON(addr < walk->vma->vm_start || addr >= walk->vma->vm_end);
3690
3691 total++;
3692 priv->mm_stats[MM_PTE_TOTAL]++;
3693
3694 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
3695 continue;
3696
3697 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
3698 continue;
3699
3700 if (!pte_young(pte[i])) {
3701 priv->mm_stats[MM_PTE_OLD]++;
3702 continue;
3703 }
3704
3705 VM_BUG_ON(!pfn_valid(pfn));
3706 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3707 continue;
3708
3709 page = compound_head(pfn_to_page(pfn));
3710 if (page_to_nid(page) != pgdat->node_id)
3711 continue;
3712
3713 if (page_memcg_rcu(page) != memcg)
3714 continue;
3715
3716 if (!ptep_test_and_clear_young(walk->vma, addr, pte + i))
3717 continue;
3718
3719 young++;
3720 priv->mm_stats[MM_PTE_YOUNG]++;
3721
3722 if (pte_dirty(pte[i]) && !PageDirty(page) &&
3723 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3724 set_page_dirty(page);
3725
3726 old_gen = page_update_gen(page, new_gen);
3727 if (old_gen >= 0 && old_gen != new_gen)
3728 update_batch_size(priv, page, old_gen, new_gen);
3729 }
3730
3731 if (i < PTRS_PER_PTE && get_next_vma(walk, PMD_MASK, PAGE_SIZE, &start, &end))
3732 goto restart;
3733
3734 pte_unmap(pte);
3735
3736 arch_leave_lazy_mmu_mode();
3737 spin_unlock(ptl);
3738
3739 return suitable_to_scan(total, young);
3740}
3741
3742#if defined(CONFIG_TRANSPARENT_HUGEPAGE) || defined(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG)
3743static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3744 struct mm_walk *walk, unsigned long *start)
3745{
3746 int i;
3747 pmd_t *pmd;
3748 spinlock_t *ptl;
3749 struct lru_gen_mm_walk *priv = walk->private;
3750 struct mem_cgroup *memcg = lruvec_memcg(priv->lruvec);
3751 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3752 int old_gen, new_gen = lru_gen_from_seq(priv->max_seq);
3753
3754 VM_BUG_ON(pud_leaf(*pud));
3755
3756 /* try to batch at most 1+MIN_LRU_BATCH+1 entries */
3757 if (*start == -1) {
3758 *start = next;
3759 return;
3760 }
3761
3762 i = next == -1 ? 0 : pmd_index(next) - pmd_index(*start);
3763 if (i && i <= MIN_LRU_BATCH) {
3764 __set_bit(i - 1, priv->bitmap);
3765 return;
3766 }
3767
3768 pmd = pmd_offset(pud, *start);
3769
3770 ptl = pmd_lockptr(walk->mm, pmd);
3771 if (!spin_trylock(ptl))
3772 goto done;
3773
3774 arch_enter_lazy_mmu_mode();
3775
3776 do {
3777 struct page *page;
3778 unsigned long pfn = pmd_pfn(pmd[i]);
3779 unsigned long addr = i ? (*start & PMD_MASK) + i * PMD_SIZE : *start;
3780
3781 VM_BUG_ON(addr < vma->vm_start || addr >= vma->vm_end);
3782
3783 if (!pmd_present(pmd[i]) || is_huge_zero_pmd(pmd[i]))
3784 goto next;
3785
3786 if (WARN_ON_ONCE(pmd_devmap(pmd[i])))
3787 goto next;
3788
3789 if (!pmd_trans_huge(pmd[i])) {
Yu Zhao76f7f072022-01-27 19:52:09 -07003790 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) &&
3791 get_cap(LRU_GEN_NONLEAF_YOUNG))
Yu Zhao5280d762022-01-27 19:23:01 -07003792 pmdp_test_and_clear_young(vma, addr, pmd + i);
3793 goto next;
3794 }
3795
3796 VM_BUG_ON(!pfn_valid(pfn));
3797 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3798 goto next;
3799
3800 page = pfn_to_page(pfn);
3801 VM_BUG_ON_PAGE(PageTail(page), page);
3802 if (page_to_nid(page) != pgdat->node_id)
3803 goto next;
3804
3805 if (page_memcg_rcu(page) != memcg)
3806 goto next;
3807
3808 if (!pmdp_test_and_clear_young(vma, addr, pmd + i))
3809 goto next;
3810
3811 priv->mm_stats[MM_PTE_YOUNG]++;
3812
3813 if (pmd_dirty(pmd[i]) && !PageDirty(page) &&
3814 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
3815 set_page_dirty(page);
3816
3817 old_gen = page_update_gen(page, new_gen);
3818 if (old_gen >= 0 && old_gen != new_gen)
3819 update_batch_size(priv, page, old_gen, new_gen);
3820next:
3821 i = i > MIN_LRU_BATCH ? 0 :
3822 find_next_bit(priv->bitmap, MIN_LRU_BATCH, i) + 1;
3823 } while (i <= MIN_LRU_BATCH);
3824
3825 arch_leave_lazy_mmu_mode();
3826 spin_unlock(ptl);
3827done:
3828 *start = -1;
3829 bitmap_zero(priv->bitmap, MIN_LRU_BATCH);
3830}
3831#else
3832static void walk_pmd_range_locked(pud_t *pud, unsigned long next, struct vm_area_struct *vma,
3833 struct mm_walk *walk, unsigned long *start)
3834{
3835}
3836#endif
3837
3838static void walk_pmd_range(pud_t *pud, unsigned long start, unsigned long end,
3839 struct mm_walk *walk)
3840{
3841 int i;
3842 pmd_t *pmd;
3843 unsigned long next;
3844 unsigned long addr;
3845 struct vm_area_struct *vma;
3846 unsigned long pos = -1;
3847 struct lru_gen_mm_walk *priv = walk->private;
3848
3849 VM_BUG_ON(pud_leaf(*pud));
3850
3851 /*
3852 * Finish an entire PMD in two passes: the first only reaches to PTE
3853 * tables to avoid taking the PMD lock; the second, if necessary, takes
3854 * the PMD lock to clear the accessed bit in PMD entries.
3855 */
3856 pmd = pmd_offset(pud, start & PUD_MASK);
3857restart:
3858 /* walk_pte_range() may call get_next_vma() */
3859 vma = walk->vma;
3860 for (i = pmd_index(start), addr = start; addr != end; i++, addr = next) {
3861 pmd_t val = pmd_read_atomic(pmd + i);
3862
3863 /* for pmd_read_atomic() */
3864 barrier();
3865
3866 next = pmd_addr_end(addr, end);
3867
3868 if (!pmd_present(val)) {
3869 priv->mm_stats[MM_PTE_TOTAL]++;
3870 continue;
3871 }
3872
3873#ifdef CONFIG_TRANSPARENT_HUGEPAGE
3874 if (pmd_trans_huge(val)) {
3875 unsigned long pfn = pmd_pfn(val);
3876 struct pglist_data *pgdat = lruvec_pgdat(priv->lruvec);
3877
3878 priv->mm_stats[MM_PTE_TOTAL]++;
3879
3880 if (is_huge_zero_pmd(val))
3881 continue;
3882
3883 if (!pmd_young(val)) {
3884 priv->mm_stats[MM_PTE_OLD]++;
3885 continue;
3886 }
3887
3888 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
3889 continue;
3890
3891 walk_pmd_range_locked(pud, addr, vma, walk, &pos);
3892 continue;
3893 }
3894#endif
3895 priv->mm_stats[MM_PMD_TOTAL]++;
3896
3897#ifdef CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG
Yu Zhao76f7f072022-01-27 19:52:09 -07003898 if (get_cap(LRU_GEN_NONLEAF_YOUNG)) {
3899 if (!pmd_young(val))
3900 continue;
Yu Zhao5280d762022-01-27 19:23:01 -07003901
Yu Zhao76f7f072022-01-27 19:52:09 -07003902 walk_pmd_range_locked(pud, addr, vma, walk, &pos);
3903 }
Yu Zhao5280d762022-01-27 19:23:01 -07003904#endif
3905 if (!priv->full_scan && !test_bloom_filter(priv->lruvec, priv->max_seq, pmd + i))
3906 continue;
3907
3908 priv->mm_stats[MM_PMD_FOUND]++;
3909
3910 if (!walk_pte_range(&val, addr, next, walk))
3911 continue;
3912
3913 priv->mm_stats[MM_PMD_ADDED]++;
3914
3915 /* carry over to the next generation */
3916 update_bloom_filter(priv->lruvec, priv->max_seq + 1, pmd + i);
3917 }
3918
3919 walk_pmd_range_locked(pud, -1, vma, walk, &pos);
3920
3921 if (i < PTRS_PER_PMD && get_next_vma(walk, PUD_MASK, PMD_SIZE, &start, &end))
3922 goto restart;
3923}
3924
3925static int walk_pud_range(p4d_t *p4d, unsigned long start, unsigned long end,
3926 struct mm_walk *walk)
3927{
3928 int i;
3929 pud_t *pud;
3930 unsigned long addr;
3931 unsigned long next;
3932 struct lru_gen_mm_walk *priv = walk->private;
3933
3934 VM_BUG_ON(p4d_leaf(*p4d));
3935
3936 pud = pud_offset(p4d, start & P4D_MASK);
3937restart:
3938 for (i = pud_index(start), addr = start; addr != end; i++, addr = next) {
3939 pud_t val = READ_ONCE(pud[i]);
3940
3941 next = pud_addr_end(addr, end);
3942
3943 if (!pud_present(val) || WARN_ON_ONCE(pud_leaf(val)))
3944 continue;
3945
3946 walk_pmd_range(&val, addr, next, walk);
3947
3948 if (priv->batched >= MAX_LRU_BATCH) {
3949 end = (addr | ~PUD_MASK) + 1;
3950 goto done;
3951 }
3952 }
3953
3954 if (i < PTRS_PER_PUD && get_next_vma(walk, P4D_MASK, PUD_SIZE, &start, &end))
3955 goto restart;
3956
3957 end = round_up(end, P4D_SIZE);
3958done:
3959 /* rounded-up boundaries can wrap to 0 */
3960 priv->next_addr = end && walk->vma ? max(end, walk->vma->vm_start) : 0;
3961
3962 return -EAGAIN;
3963}
3964
3965static void walk_mm(struct lruvec *lruvec, struct mm_struct *mm, struct lru_gen_mm_walk *walk)
3966{
3967 static const struct mm_walk_ops mm_walk_ops = {
3968 .test_walk = should_skip_vma,
3969 .p4d_entry = walk_pud_range,
3970 };
3971
3972 int err;
3973 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
3974
3975 walk->next_addr = FIRST_USER_ADDRESS;
3976
3977 do {
3978 err = -EBUSY;
3979
3980 /* page_update_gen() requires stable page_memcg() */
3981 if (!mem_cgroup_trylock_pages(memcg))
3982 break;
3983
3984 /* the caller might be holding the lock for write */
3985 if (mmap_read_trylock(mm)) {
3986 unsigned long start = walk->next_addr;
3987 unsigned long end = mm->highest_vm_end;
3988
3989 err = walk_page_range(mm, start, end, &mm_walk_ops, walk);
3990
3991 mmap_read_unlock(mm);
3992
3993 if (walk->batched) {
3994 spin_lock_irq(&lruvec->lru_lock);
3995 reset_batch_size(lruvec, walk);
3996 spin_unlock_irq(&lruvec->lru_lock);
3997 }
3998 }
3999
4000 mem_cgroup_unlock_pages();
4001
4002 cond_resched();
4003 } while (err == -EAGAIN && walk->next_addr && !mm_is_oom_victim(mm));
4004}
4005
4006static struct lru_gen_mm_walk *alloc_mm_walk(void)
4007{
4008 if (current->reclaim_state && current->reclaim_state->mm_walk)
4009 return current->reclaim_state->mm_walk;
4010
4011 return kzalloc(sizeof(struct lru_gen_mm_walk),
4012 __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
4013}
4014
4015static void free_mm_walk(struct lru_gen_mm_walk *walk)
4016{
4017 if (!current->reclaim_state || !current->reclaim_state->mm_walk)
4018 kfree(walk);
4019}
4020
Yu Zhaoa1537a62022-01-27 20:32:37 -07004021static void inc_min_seq(struct lruvec *lruvec)
4022{
4023 int type;
4024 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4025
4026 VM_BUG_ON(!seq_is_valid(lruvec));
4027
4028 for (type = 0; type < ANON_AND_FILE; type++) {
4029 if (get_nr_gens(lruvec, type) != MAX_NR_GENS)
4030 continue;
4031
4032 reset_ctrl_pos(lruvec, type, true);
4033 WRITE_ONCE(lrugen->min_seq[type], lrugen->min_seq[type] + 1);
4034 }
4035}
4036
4037static bool try_to_inc_min_seq(struct lruvec *lruvec, bool can_swap)
4038{
4039 int gen, type, zone;
4040 bool success = false;
4041 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4042 DEFINE_MIN_SEQ(lruvec);
4043
4044 VM_BUG_ON(!seq_is_valid(lruvec));
4045
4046 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4047 while (min_seq[type] + MIN_NR_GENS <= lrugen->max_seq) {
4048 gen = lru_gen_from_seq(min_seq[type]);
4049
4050 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4051 if (!list_empty(&lrugen->lists[gen][type][zone]))
4052 goto next;
4053 }
4054
4055 min_seq[type]++;
4056 }
4057next:
4058 ;
4059 }
4060
4061 /* see the comment on lru_gen_struct */
4062 if (can_swap) {
4063 min_seq[LRU_GEN_ANON] = min(min_seq[LRU_GEN_ANON], min_seq[LRU_GEN_FILE]);
4064 min_seq[LRU_GEN_FILE] = max(min_seq[LRU_GEN_ANON], lrugen->min_seq[LRU_GEN_FILE]);
4065 }
4066
4067 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4068 if (min_seq[type] == lrugen->min_seq[type])
4069 continue;
4070
4071 reset_ctrl_pos(lruvec, type, true);
4072 WRITE_ONCE(lrugen->min_seq[type], min_seq[type]);
4073 success = true;
4074 }
4075
4076 return success;
4077}
4078
Yu Zhao5280d762022-01-27 19:23:01 -07004079static void inc_max_seq(struct lruvec *lruvec)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004080{
4081 int prev, next;
4082 int type, zone;
4083 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4084
4085 spin_lock_irq(&lruvec->lru_lock);
4086
4087 VM_BUG_ON(!seq_is_valid(lruvec));
4088
Yu Zhaoa1537a62022-01-27 20:32:37 -07004089 inc_min_seq(lruvec);
4090
4091 /*
4092 * Update the active/inactive LRU sizes for compatibility. Both sides of
4093 * the current max_seq need to be covered, since max_seq+1 can overlap
4094 * with min_seq[LRU_GEN_ANON] if swapping is constrained. And if they do
4095 * overlap, cold/hot inversion happens. This can be solved by moving
4096 * pages from min_seq to min_seq+1 but is omitted for simplicity.
4097 */
4098 prev = lru_gen_from_seq(lrugen->max_seq - 1);
4099 next = lru_gen_from_seq(lrugen->max_seq + 1);
4100
4101 for (type = 0; type < ANON_AND_FILE; type++) {
4102 for (zone = 0; zone < MAX_NR_ZONES; zone++) {
4103 enum lru_list lru = type * LRU_INACTIVE_FILE;
4104 long delta = lrugen->nr_pages[prev][type][zone] -
4105 lrugen->nr_pages[next][type][zone];
4106
4107 if (!delta)
4108 continue;
4109
4110 __update_lru_size(lruvec, lru, zone, delta);
4111 __update_lru_size(lruvec, lru + LRU_ACTIVE, zone, -delta);
4112 }
4113 }
4114
4115 for (type = 0; type < ANON_AND_FILE; type++)
4116 reset_ctrl_pos(lruvec, type, false);
4117
4118 /* make sure preceding modifications appear */
4119 smp_store_release(&lrugen->max_seq, lrugen->max_seq + 1);
Yu Zhao5280d762022-01-27 19:23:01 -07004120
Yu Zhaoa1537a62022-01-27 20:32:37 -07004121 spin_unlock_irq(&lruvec->lru_lock);
4122}
4123
Yu Zhao5280d762022-01-27 19:23:01 -07004124static bool try_to_inc_max_seq(struct lruvec *lruvec, unsigned long max_seq,
4125 struct scan_control *sc, bool can_swap, bool full_scan)
4126{
4127 bool success;
4128 struct lru_gen_mm_walk *walk;
4129 struct mm_struct *mm = NULL;
4130 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4131
4132 VM_BUG_ON(max_seq > READ_ONCE(lrugen->max_seq));
4133
4134 /*
4135 * If the hardware doesn't automatically set the accessed bit, fallback
4136 * to lru_gen_look_around(), which only clears the accessed bit in a
4137 * handful of PTEs. Spreading the work out over a period of time usually
4138 * is less efficient, but it avoids bursty page faults.
4139 */
Yu Zhao76f7f072022-01-27 19:52:09 -07004140 if (!full_scan && (!arch_has_hw_pte_young() || !get_cap(LRU_GEN_MM_WALK))) {
Yu Zhao5280d762022-01-27 19:23:01 -07004141 success = iterate_mm_list_nowalk(lruvec, max_seq);
4142 goto done;
4143 }
4144
4145 walk = alloc_mm_walk();
4146 if (!walk) {
4147 success = iterate_mm_list_nowalk(lruvec, max_seq);
4148 goto done;
4149 }
4150
4151 walk->lruvec = lruvec;
4152 walk->max_seq = max_seq;
4153 walk->can_swap = can_swap;
4154 walk->full_scan = full_scan;
4155
4156 do {
4157 success = iterate_mm_list(lruvec, walk, &mm);
4158 if (mm)
4159 walk_mm(lruvec, mm, walk);
4160
4161 cond_resched();
4162 } while (mm);
4163
4164 free_mm_walk(walk);
4165done:
4166 if (!success) {
4167 if (!current_is_kswapd() && !sc->priority)
4168 wait_event_killable(lruvec->mm_state.wait,
4169 max_seq < READ_ONCE(lrugen->max_seq));
4170
4171 return max_seq < READ_ONCE(lrugen->max_seq);
4172 }
4173
4174 VM_BUG_ON(max_seq != READ_ONCE(lrugen->max_seq));
4175
4176 inc_max_seq(lruvec);
4177 /* either this sees any waiters or they will see updated max_seq */
4178 if (wq_has_sleeper(&lruvec->mm_state.wait))
4179 wake_up_all(&lruvec->mm_state.wait);
4180
4181 wakeup_flusher_threads(WB_REASON_VMSCAN);
4182
4183 return true;
4184}
4185
Yu Zhaoa1537a62022-01-27 20:32:37 -07004186static long get_nr_evictable(struct lruvec *lruvec, unsigned long max_seq,
4187 unsigned long *min_seq, bool can_swap, bool *need_aging)
4188{
4189 int gen, type, zone;
4190 long old = 0;
4191 long young = 0;
4192 long total = 0;
4193 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4194
4195 for (type = !can_swap; type < ANON_AND_FILE; type++) {
4196 unsigned long seq;
4197
4198 for (seq = min_seq[type]; seq <= max_seq; seq++) {
4199 long size = 0;
4200
4201 gen = lru_gen_from_seq(seq);
4202
4203 for (zone = 0; zone < MAX_NR_ZONES; zone++)
4204 size += READ_ONCE(lrugen->nr_pages[gen][type][zone]);
4205
4206 total += size;
4207 if (seq == max_seq)
4208 young += size;
4209 if (seq + MIN_NR_GENS == max_seq)
4210 old += size;
4211 }
4212 }
4213
4214 /*
4215 * The aging and the eviction is a typical producer-consumer model. The
4216 * aging tries to be lazy to reduce the unnecessary overhead. On the
4217 * other hand, the eviction stalls when the number of generations
4218 * reaches MIN_NR_GENS. So ideally, there should be MIN_NR_GENS+1
4219 * generations, hence the first two if's.
4220 *
4221 * In addition, it's ideal to spread pages out evenly, meaning
4222 * 1/(MIN_NR_GENS+1) of the total number of pages for each generation. A
4223 * reasonable range for this average portion would [1/MIN_NR_GENS,
4224 * 1/(MIN_NR_GENS+2)]. From the consumer's POV, the eviction only cares
4225 * about the lower bound of cold pages, i.e., 1/(MIN_NR_GENS+2), whereas
4226 * from the producer's POV, the aging only cares about the upper bound
4227 * of hot pages, i.e., 1/MIN_NR_GENS.
4228 */
4229 if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS > max_seq)
4230 *need_aging = true;
4231 else if (min_seq[LRU_GEN_FILE] + MIN_NR_GENS < max_seq)
4232 *need_aging = false;
4233 else if (young * MIN_NR_GENS > total)
4234 *need_aging = true;
4235 else if (old * (MIN_NR_GENS + 2) < total)
4236 *need_aging = true;
4237 else
4238 *need_aging = false;
4239
4240 return total > 0 ? total : 0;
4241}
4242
Kalesh Singh657801d2022-11-07 15:57:15 -08004243static void age_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004244{
4245 bool need_aging;
4246 long nr_to_scan;
4247 int swappiness = get_swappiness(lruvec, sc);
4248 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4249 DEFINE_MAX_SEQ(lruvec);
4250 DEFINE_MIN_SEQ(lruvec);
4251
4252 mem_cgroup_calculate_protection(NULL, memcg);
4253
4254 if (mem_cgroup_below_min(memcg))
Kalesh Singh657801d2022-11-07 15:57:15 -08004255 return;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004256
4257 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, swappiness, &need_aging);
4258 if (!nr_to_scan)
Kalesh Singh657801d2022-11-07 15:57:15 -08004259 return;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004260
4261 nr_to_scan >>= sc->priority;
4262
4263 if (!mem_cgroup_online(memcg))
4264 nr_to_scan++;
4265
4266 if (nr_to_scan && need_aging && (!mem_cgroup_below_low(memcg) || sc->memcg_low_reclaim))
Yu Zhao5280d762022-01-27 19:23:01 -07004267 try_to_inc_max_seq(lruvec, max_seq, sc, swappiness, false);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004268}
4269
4270static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
4271{
4272 struct mem_cgroup *memcg;
4273
4274 VM_BUG_ON(!current_is_kswapd());
4275
Yu Zhao4d905e92022-01-27 19:59:54 -07004276 /*
4277 * To reduce the chance of going into the aging path or swapping, which
4278 * can be costly, optimistically skip them unless their corresponding
4279 * flags were cleared in the eviction path. This improves the overall
4280 * performance when multiple memcgs are available.
4281 */
4282 if (!sc->memcgs_need_aging) {
4283 sc->memcgs_need_aging = true;
4284 sc->memcgs_avoid_swapping = !sc->memcgs_need_swapping;
4285 sc->memcgs_need_swapping = true;
4286 return;
4287 }
4288
4289 sc->memcgs_need_swapping = true;
4290 sc->memcgs_avoid_swapping = true;
4291
Yu Zhao5280d762022-01-27 19:23:01 -07004292 current->reclaim_state->mm_walk = &pgdat->mm_walk;
4293
Yu Zhaoa1537a62022-01-27 20:32:37 -07004294 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4295 do {
4296 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4297
Kalesh Singh657801d2022-11-07 15:57:15 -08004298 age_lruvec(lruvec, sc);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004299
4300 cond_resched();
4301 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
Yu Zhao5280d762022-01-27 19:23:01 -07004302
4303 current->reclaim_state->mm_walk = NULL;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004304}
4305
Yu Zhaoafd94c92022-01-27 20:43:22 -07004306/*
4307 * This function exploits spatial locality when shrink_page_list() walks the
4308 * rmap. It scans the adjacent PTEs of a young PTE and promotes hot pages.
Yu Zhao5280d762022-01-27 19:23:01 -07004309 * If the scan was done cacheline efficiently, it adds the PMD entry pointing
4310 * to the PTE table to the Bloom filter. This process is a feedback loop from
4311 * the eviction to the aging.
Yu Zhaoafd94c92022-01-27 20:43:22 -07004312 */
4313void lru_gen_look_around(struct page_vma_mapped_walk *pvmw)
4314{
4315 int i;
4316 pte_t *pte;
4317 unsigned long start;
4318 unsigned long end;
4319 unsigned long addr;
4320 struct page *page;
Yu Zhao5280d762022-01-27 19:23:01 -07004321 struct lru_gen_mm_walk *walk;
4322 int young = 0;
Yu Zhaoafd94c92022-01-27 20:43:22 -07004323 unsigned long bitmap[BITS_TO_LONGS(MIN_LRU_BATCH)] = {};
4324 struct mem_cgroup *memcg = page_memcg(pvmw->page);
4325 struct pglist_data *pgdat = page_pgdat(pvmw->page);
4326 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
4327 DEFINE_MAX_SEQ(lruvec);
4328 int old_gen, new_gen = lru_gen_from_seq(max_seq);
4329
4330 lockdep_assert_held(pvmw->ptl);
4331 VM_BUG_ON_PAGE(PageLRU(pvmw->page), pvmw->page);
4332
4333 if (spin_is_contended(pvmw->ptl))
4334 return;
4335
4336 start = max(pvmw->address & PMD_MASK, pvmw->vma->vm_start);
4337 end = pmd_addr_end(pvmw->address, pvmw->vma->vm_end);
4338
4339 if (end - start > MIN_LRU_BATCH * PAGE_SIZE) {
4340 if (pvmw->address - start < MIN_LRU_BATCH * PAGE_SIZE / 2)
4341 end = start + MIN_LRU_BATCH * PAGE_SIZE;
4342 else if (end - pvmw->address < MIN_LRU_BATCH * PAGE_SIZE / 2)
4343 start = end - MIN_LRU_BATCH * PAGE_SIZE;
4344 else {
4345 start = pvmw->address - MIN_LRU_BATCH * PAGE_SIZE / 2;
4346 end = pvmw->address + MIN_LRU_BATCH * PAGE_SIZE / 2;
4347 }
4348 }
4349
4350 pte = pvmw->pte - (pvmw->address - start) / PAGE_SIZE;
4351
4352 rcu_read_lock();
4353 arch_enter_lazy_mmu_mode();
4354
4355 for (i = 0, addr = start; addr != end; i++, addr += PAGE_SIZE) {
4356 unsigned long pfn = pte_pfn(pte[i]);
4357
4358 VM_BUG_ON(addr < pvmw->vma->vm_start || addr >= pvmw->vma->vm_end);
4359
4360 if (!pte_present(pte[i]) || is_zero_pfn(pfn))
4361 continue;
4362
4363 if (WARN_ON_ONCE(pte_devmap(pte[i]) || pte_special(pte[i])))
4364 continue;
4365
4366 if (!pte_young(pte[i]))
4367 continue;
4368
4369 VM_BUG_ON(!pfn_valid(pfn));
4370 if (pfn < pgdat->node_start_pfn || pfn >= pgdat_end_pfn(pgdat))
4371 continue;
4372
4373 page = compound_head(pfn_to_page(pfn));
4374 if (page_to_nid(page) != pgdat->node_id)
4375 continue;
4376
4377 if (page_memcg_rcu(page) != memcg)
4378 continue;
4379
4380 if (!ptep_test_and_clear_young(pvmw->vma, addr, pte + i))
4381 continue;
4382
Yu Zhao5280d762022-01-27 19:23:01 -07004383 young++;
4384
Yu Zhaoafd94c92022-01-27 20:43:22 -07004385 if (pte_dirty(pte[i]) && !PageDirty(page) &&
4386 !(PageAnon(page) && PageSwapBacked(page) && !PageSwapCache(page)))
4387 set_page_dirty(page);
4388
4389 old_gen = page_lru_gen(page);
4390 if (old_gen < 0)
4391 SetPageReferenced(page);
4392 else if (old_gen != new_gen)
4393 __set_bit(i, bitmap);
4394 }
4395
4396 arch_leave_lazy_mmu_mode();
4397 rcu_read_unlock();
4398
Yu Zhao5280d762022-01-27 19:23:01 -07004399 /* feedback from rmap walkers to page table walkers */
4400 if (suitable_to_scan(i, young))
4401 update_bloom_filter(lruvec, max_seq, pvmw->pmd);
4402
4403 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4404
4405 if (!walk && bitmap_weight(bitmap, MIN_LRU_BATCH) < PAGEVEC_SIZE) {
Yu Zhaoafd94c92022-01-27 20:43:22 -07004406 for_each_set_bit(i, bitmap, MIN_LRU_BATCH)
4407 activate_page(pte_page(pte[i]));
4408 return;
4409 }
4410
4411 /* page_update_gen() requires stable page_memcg() */
4412 if (!mem_cgroup_trylock_pages(memcg))
4413 return;
4414
Yu Zhao5280d762022-01-27 19:23:01 -07004415 if (!walk) {
4416 spin_lock_irq(&lruvec->lru_lock);
4417 new_gen = lru_gen_from_seq(lruvec->lrugen.max_seq);
4418 }
Yu Zhaoafd94c92022-01-27 20:43:22 -07004419
4420 for_each_set_bit(i, bitmap, MIN_LRU_BATCH) {
4421 page = compound_head(pte_page(pte[i]));
4422 if (page_memcg_rcu(page) != memcg)
4423 continue;
4424
4425 old_gen = page_update_gen(page, new_gen);
4426 if (old_gen < 0 || old_gen == new_gen)
4427 continue;
4428
Yu Zhao5280d762022-01-27 19:23:01 -07004429 if (walk)
4430 update_batch_size(walk, page, old_gen, new_gen);
4431 else
4432 lru_gen_update_size(lruvec, page, old_gen, new_gen);
Yu Zhaoafd94c92022-01-27 20:43:22 -07004433 }
4434
Yu Zhao5280d762022-01-27 19:23:01 -07004435 if (!walk)
4436 spin_unlock_irq(&lruvec->lru_lock);
Yu Zhaoafd94c92022-01-27 20:43:22 -07004437
4438 mem_cgroup_unlock_pages();
4439}
4440
Yu Zhaoa1537a62022-01-27 20:32:37 -07004441/******************************************************************************
4442 * the eviction
4443 ******************************************************************************/
4444
4445static bool sort_page(struct lruvec *lruvec, struct page *page, int tier_idx)
4446{
4447 bool success;
4448 int gen = page_lru_gen(page);
4449 int type = page_is_file_lru(page);
4450 int zone = page_zonenum(page);
4451 int tier = page_lru_tier(page);
4452 int delta = thp_nr_pages(page);
4453 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4454
4455 VM_BUG_ON_PAGE(gen >= MAX_NR_GENS, page);
4456
4457 if (!page_evictable(page)) {
4458 success = lru_gen_del_page(lruvec, page, true);
4459 VM_BUG_ON_PAGE(!success, page);
4460 SetPageUnevictable(page);
4461 add_page_to_lru_list(page, lruvec);
4462 __count_vm_events(UNEVICTABLE_PGCULLED, delta);
4463 return true;
4464 }
4465
4466 if (type == LRU_GEN_FILE && PageAnon(page) && PageDirty(page)) {
4467 success = lru_gen_del_page(lruvec, page, true);
4468 VM_BUG_ON_PAGE(!success, page);
4469 SetPageSwapBacked(page);
4470 add_page_to_lru_list_tail(page, lruvec);
4471 return true;
4472 }
4473
Yu Zhaoafd94c92022-01-27 20:43:22 -07004474 if (gen != lru_gen_from_seq(lrugen->min_seq[type])) {
4475 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4476 return true;
4477 }
4478
Yu Zhaoa1537a62022-01-27 20:32:37 -07004479 if (tier > tier_idx) {
4480 int hist = lru_hist_from_seq(lrugen->min_seq[type]);
4481
4482 gen = page_inc_gen(lruvec, page, false);
4483 list_move_tail(&page->lru, &lrugen->lists[gen][type][zone]);
4484
4485 WRITE_ONCE(lrugen->protected[hist][type][tier - 1],
4486 lrugen->protected[hist][type][tier - 1] + delta);
4487 __mod_lruvec_state(lruvec, WORKINGSET_ACTIVATE_BASE + type, delta);
4488 return true;
4489 }
4490
4491 if (PageLocked(page) || PageWriteback(page) ||
4492 (type == LRU_GEN_FILE && PageDirty(page))) {
4493 gen = page_inc_gen(lruvec, page, true);
4494 list_move(&page->lru, &lrugen->lists[gen][type][zone]);
4495 return true;
4496 }
4497
4498 return false;
4499}
4500
4501static bool isolate_page(struct lruvec *lruvec, struct page *page, struct scan_control *sc)
4502{
4503 bool success;
4504
4505 if (!sc->may_unmap && page_mapped(page))
4506 return false;
4507
4508 if (!(sc->may_writepage && (sc->gfp_mask & __GFP_IO)) &&
4509 (PageDirty(page) || (PageAnon(page) && !PageSwapCache(page))))
4510 return false;
4511
4512 if (!get_page_unless_zero(page))
4513 return false;
4514
4515 if (!TestClearPageLRU(page)) {
4516 put_page(page);
4517 return false;
4518 }
4519
4520 success = lru_gen_del_page(lruvec, page, true);
4521 VM_BUG_ON_PAGE(!success, page);
4522
4523 return true;
4524}
4525
4526static int scan_pages(struct lruvec *lruvec, struct scan_control *sc,
4527 int type, int tier, struct list_head *list)
4528{
4529 int gen, zone;
4530 enum vm_event_item item;
4531 int sorted = 0;
4532 int scanned = 0;
4533 int isolated = 0;
4534 int remaining = MAX_LRU_BATCH;
4535 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4536 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4537
4538 VM_BUG_ON(!list_empty(list));
4539
4540 if (get_nr_gens(lruvec, type) == MIN_NR_GENS)
4541 return 0;
4542
4543 gen = lru_gen_from_seq(lrugen->min_seq[type]);
4544
4545 for (zone = sc->reclaim_idx; zone >= 0; zone--) {
4546 LIST_HEAD(moved);
4547 int skipped = 0;
4548 struct list_head *head = &lrugen->lists[gen][type][zone];
4549
4550 while (!list_empty(head)) {
4551 struct page *page = lru_to_page(head);
4552 int delta = thp_nr_pages(page);
4553
4554 VM_BUG_ON_PAGE(PageTail(page), page);
4555 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4556 VM_BUG_ON_PAGE(PageActive(page), page);
4557 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4558 VM_BUG_ON_PAGE(page_zonenum(page) != zone, page);
4559
4560 prefetchw_prev_lru_page(page, head, flags);
4561
4562 scanned += delta;
4563
4564 if (sort_page(lruvec, page, tier))
4565 sorted += delta;
4566 else if (isolate_page(lruvec, page, sc)) {
4567 list_add(&page->lru, list);
4568 isolated += delta;
4569 } else {
4570 list_move(&page->lru, &moved);
4571 skipped += delta;
4572 }
4573
4574 if (!--remaining || max(isolated, skipped) >= MIN_LRU_BATCH)
4575 break;
4576 }
4577
4578 if (skipped) {
4579 list_splice(&moved, head);
4580 __count_zid_vm_events(PGSCAN_SKIP, zone, skipped);
4581 }
4582
4583 if (!remaining || isolated >= MIN_LRU_BATCH)
4584 break;
4585 }
4586
4587 item = current_is_kswapd() ? PGSCAN_KSWAPD : PGSCAN_DIRECT;
4588 if (!cgroup_reclaim(sc)) {
4589 __count_vm_events(item, isolated);
4590 __count_vm_events(PGREFILL, sorted);
4591 }
4592 __count_memcg_events(memcg, item, isolated);
4593 __count_memcg_events(memcg, PGREFILL, sorted);
4594 __count_vm_events(PGSCAN_ANON + type, isolated);
4595
4596 /*
4597 * There might not be eligible pages due to reclaim_idx, may_unmap and
4598 * may_writepage. Check the remaining to prevent livelock if there is no
4599 * progress.
4600 */
4601 return isolated || !remaining ? scanned : 0;
4602}
4603
4604static int get_tier_idx(struct lruvec *lruvec, int type)
4605{
4606 int tier;
4607 struct ctrl_pos sp, pv;
4608
4609 /*
4610 * To leave a margin for fluctuations, use a larger gain factor (1:2).
4611 * This value is chosen because any other tier would have at least twice
4612 * as many refaults as the first tier.
4613 */
4614 read_ctrl_pos(lruvec, type, 0, 1, &sp);
4615 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4616 read_ctrl_pos(lruvec, type, tier, 2, &pv);
4617 if (!positive_ctrl_err(&sp, &pv))
4618 break;
4619 }
4620
4621 return tier - 1;
4622}
4623
4624static int get_type_to_scan(struct lruvec *lruvec, int swappiness, int *tier_idx)
4625{
4626 int type, tier;
4627 struct ctrl_pos sp, pv;
4628 int gain[ANON_AND_FILE] = { swappiness, 200 - swappiness };
4629
4630 /*
4631 * Compare the first tier of anon with that of file to determine which
4632 * type to scan. Also need to compare other tiers of the selected type
4633 * with the first tier of the other type to determine the last tier (of
4634 * the selected type) to evict.
4635 */
4636 read_ctrl_pos(lruvec, LRU_GEN_ANON, 0, gain[LRU_GEN_ANON], &sp);
4637 read_ctrl_pos(lruvec, LRU_GEN_FILE, 0, gain[LRU_GEN_FILE], &pv);
4638 type = positive_ctrl_err(&sp, &pv);
4639
4640 read_ctrl_pos(lruvec, !type, 0, gain[!type], &sp);
4641 for (tier = 1; tier < MAX_NR_TIERS; tier++) {
4642 read_ctrl_pos(lruvec, type, tier, gain[type], &pv);
4643 if (!positive_ctrl_err(&sp, &pv))
4644 break;
4645 }
4646
4647 *tier_idx = tier - 1;
4648
4649 return type;
4650}
4651
4652static int isolate_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4653 int *type_scanned, struct list_head *list)
4654{
4655 int i;
4656 int type;
4657 int scanned;
4658 int tier = -1;
4659 DEFINE_MIN_SEQ(lruvec);
4660
4661 VM_BUG_ON(!seq_is_valid(lruvec));
4662
4663 /*
4664 * Try to make the obvious choice first. When anon and file are both
4665 * available from the same generation, interpret swappiness 1 as file
4666 * first and 200 as anon first.
4667 */
4668 if (!swappiness)
4669 type = LRU_GEN_FILE;
4670 else if (min_seq[LRU_GEN_ANON] < min_seq[LRU_GEN_FILE])
4671 type = LRU_GEN_ANON;
4672 else if (swappiness == 1)
4673 type = LRU_GEN_FILE;
4674 else if (swappiness == 200)
4675 type = LRU_GEN_ANON;
4676 else
4677 type = get_type_to_scan(lruvec, swappiness, &tier);
4678
4679 for (i = !swappiness; i < ANON_AND_FILE; i++) {
4680 if (tier < 0)
4681 tier = get_tier_idx(lruvec, type);
4682
4683 scanned = scan_pages(lruvec, sc, type, tier, list);
4684 if (scanned)
4685 break;
4686
4687 type = !type;
4688 tier = -1;
4689 }
4690
4691 *type_scanned = type;
4692
4693 return scanned;
4694}
4695
Yu Zhao4d905e92022-01-27 19:59:54 -07004696static int evict_pages(struct lruvec *lruvec, struct scan_control *sc, int swappiness,
4697 bool *swapped)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004698{
4699 int type;
4700 int scanned;
4701 int reclaimed;
4702 LIST_HEAD(list);
4703 struct page *page;
4704 enum vm_event_item item;
4705 struct reclaim_stat stat;
Yu Zhao5280d762022-01-27 19:23:01 -07004706 struct lru_gen_mm_walk *walk;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004707 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4708 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
4709
4710 spin_lock_irq(&lruvec->lru_lock);
4711
4712 scanned = isolate_pages(lruvec, sc, swappiness, &type, &list);
4713
4714 if (try_to_inc_min_seq(lruvec, swappiness))
4715 scanned++;
4716
4717 if (get_nr_gens(lruvec, LRU_GEN_FILE) == MIN_NR_GENS)
4718 scanned = 0;
4719
4720 spin_unlock_irq(&lruvec->lru_lock);
4721
4722 if (list_empty(&list))
4723 return scanned;
4724
4725 reclaimed = shrink_page_list(&list, pgdat, sc, &stat, false);
4726
4727 /*
4728 * To avoid livelock, don't add rejected pages back to the same lists
4729 * they were isolated from. See lru_gen_add_page().
4730 */
4731 list_for_each_entry(page, &list, lru) {
4732 ClearPageReferenced(page);
4733 ClearPageWorkingset(page);
4734
4735 if (PageReclaim(page) && (PageDirty(page) || PageWriteback(page)))
4736 ClearPageActive(page);
4737 else if (page_is_file_lru(page) || PageSwapCache(page))
4738 SetPageActive(page);
4739 }
4740
4741 spin_lock_irq(&lruvec->lru_lock);
4742
4743 move_pages_to_lru(lruvec, &list);
4744
Yu Zhao5280d762022-01-27 19:23:01 -07004745 walk = current->reclaim_state ? current->reclaim_state->mm_walk : NULL;
4746 if (walk && walk->batched)
4747 reset_batch_size(lruvec, walk);
4748
Yu Zhaoa1537a62022-01-27 20:32:37 -07004749 item = current_is_kswapd() ? PGSTEAL_KSWAPD : PGSTEAL_DIRECT;
4750 if (!cgroup_reclaim(sc))
4751 __count_vm_events(item, reclaimed);
4752 __count_memcg_events(memcg, item, reclaimed);
4753 __count_vm_events(PGSTEAL_ANON + type, reclaimed);
4754
4755 spin_unlock_irq(&lruvec->lru_lock);
4756
4757 mem_cgroup_uncharge_list(&list);
4758 free_unref_page_list(&list);
4759
4760 sc->nr_reclaimed += reclaimed;
4761
Yu Zhao4d905e92022-01-27 19:59:54 -07004762 if (type == LRU_GEN_ANON && swapped)
4763 *swapped = true;
4764
Yu Zhaoa1537a62022-01-27 20:32:37 -07004765 return scanned;
4766}
4767
4768static long get_nr_to_scan(struct lruvec *lruvec, struct scan_control *sc, bool can_swap)
4769{
4770 bool need_aging;
4771 long nr_to_scan;
4772 struct mem_cgroup *memcg = lruvec_memcg(lruvec);
4773 DEFINE_MAX_SEQ(lruvec);
4774 DEFINE_MIN_SEQ(lruvec);
4775
4776 if (mem_cgroup_below_min(memcg) ||
4777 (mem_cgroup_below_low(memcg) && !sc->memcg_low_reclaim))
4778 return 0;
4779
4780 nr_to_scan = get_nr_evictable(lruvec, max_seq, min_seq, can_swap, &need_aging);
4781 if (!nr_to_scan)
4782 return 0;
4783
4784 /* reset the priority if the target has been met */
4785 nr_to_scan >>= sc->nr_reclaimed < sc->nr_to_reclaim ? sc->priority : DEF_PRIORITY;
4786
4787 if (!mem_cgroup_online(memcg))
4788 nr_to_scan++;
4789
4790 if (!nr_to_scan)
4791 return 0;
4792
Yu Zhao4d905e92022-01-27 19:59:54 -07004793 if (!need_aging) {
4794 sc->memcgs_need_aging = false;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004795 return nr_to_scan;
Yu Zhao4d905e92022-01-27 19:59:54 -07004796 }
Yu Zhaoa1537a62022-01-27 20:32:37 -07004797
4798 /* leave the work to lru_gen_age_node() */
4799 if (current_is_kswapd())
4800 return 0;
4801
4802 /* try other memcgs before going to the aging path */
4803 if (!cgroup_reclaim(sc) && !sc->force_deactivate) {
4804 sc->skipped_deactivate = true;
4805 return 0;
4806 }
4807
Yu Zhao5280d762022-01-27 19:23:01 -07004808 if (try_to_inc_max_seq(lruvec, max_seq, sc, can_swap, false))
4809 return nr_to_scan;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004810
Yu Zhao5280d762022-01-27 19:23:01 -07004811 return min_seq[LRU_GEN_FILE] + MIN_NR_GENS <= max_seq ? nr_to_scan : 0;
Yu Zhaoa1537a62022-01-27 20:32:37 -07004812}
4813
4814static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
4815{
4816 struct blk_plug plug;
4817 long scanned = 0;
Yu Zhao4d905e92022-01-27 19:59:54 -07004818 bool swapped = false;
4819 unsigned long reclaimed = sc->nr_reclaimed;
Yu Zhao5280d762022-01-27 19:23:01 -07004820 struct pglist_data *pgdat = lruvec_pgdat(lruvec);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004821
4822 lru_add_drain();
4823
4824 blk_start_plug(&plug);
4825
Yu Zhao5280d762022-01-27 19:23:01 -07004826 if (current_is_kswapd())
4827 current->reclaim_state->mm_walk = &pgdat->mm_walk;
4828
Yu Zhaoa1537a62022-01-27 20:32:37 -07004829 while (true) {
4830 int delta;
4831 int swappiness;
4832 long nr_to_scan;
4833
4834 if (sc->may_swap)
4835 swappiness = get_swappiness(lruvec, sc);
4836 else if (!cgroup_reclaim(sc) && get_swappiness(lruvec, sc))
4837 swappiness = 1;
4838 else
4839 swappiness = 0;
4840
4841 nr_to_scan = get_nr_to_scan(lruvec, sc, swappiness);
4842 if (!nr_to_scan)
4843 break;
4844
Yu Zhao4d905e92022-01-27 19:59:54 -07004845 delta = evict_pages(lruvec, sc, swappiness, &swapped);
Yu Zhaoa1537a62022-01-27 20:32:37 -07004846 if (!delta)
4847 break;
4848
Yu Zhao4d905e92022-01-27 19:59:54 -07004849 if (sc->memcgs_avoid_swapping && swappiness < 200 && swapped)
Yu Zhaoa1537a62022-01-27 20:32:37 -07004850 break;
4851
Yu Zhao4d905e92022-01-27 19:59:54 -07004852 scanned += delta;
4853 if (scanned >= nr_to_scan) {
4854 if (!swapped && sc->nr_reclaimed - reclaimed >= MIN_LRU_BATCH)
4855 sc->memcgs_need_swapping = false;
4856 break;
4857 }
4858
Yu Zhaoa1537a62022-01-27 20:32:37 -07004859 cond_resched();
4860 }
4861
Yu Zhao5280d762022-01-27 19:23:01 -07004862 if (current_is_kswapd())
4863 current->reclaim_state->mm_walk = NULL;
4864
Yu Zhaoa1537a62022-01-27 20:32:37 -07004865 blk_finish_plug(&plug);
4866}
4867
Yu Zhaof88ed5a2021-01-25 21:12:33 -07004868/******************************************************************************
Yu Zhao76f7f072022-01-27 19:52:09 -07004869 * state change
4870 ******************************************************************************/
4871
4872static bool __maybe_unused state_is_valid(struct lruvec *lruvec)
4873{
4874 struct lru_gen_struct *lrugen = &lruvec->lrugen;
4875
4876 if (lrugen->enabled) {
4877 enum lru_list lru;
4878
4879 for_each_evictable_lru(lru) {
4880 if (!list_empty(&lruvec->lists[lru]))
4881 return false;
4882 }
4883 } else {
4884 int gen, type, zone;
4885
4886 for_each_gen_type_zone(gen, type, zone) {
4887 if (!list_empty(&lrugen->lists[gen][type][zone]))
4888 return false;
4889
4890 /* unlikely but not a bug when reset_batch_size() is pending */
4891 VM_WARN_ON(lrugen->nr_pages[gen][type][zone]);
4892 }
4893 }
4894
4895 return true;
4896}
4897
4898static bool fill_evictable(struct lruvec *lruvec)
4899{
4900 enum lru_list lru;
4901 int remaining = MAX_LRU_BATCH;
4902
4903 for_each_evictable_lru(lru) {
4904 int type = is_file_lru(lru);
4905 bool active = is_active_lru(lru);
4906 struct list_head *head = &lruvec->lists[lru];
4907
4908 while (!list_empty(head)) {
4909 bool success;
4910 struct page *page = lru_to_page(head);
4911
4912 VM_BUG_ON_PAGE(PageTail(page), page);
4913 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4914 VM_BUG_ON_PAGE(PageActive(page) != active, page);
4915 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4916 VM_BUG_ON_PAGE(page_lru_gen(page) < MAX_NR_GENS, page);
4917
4918 prefetchw_prev_lru_page(page, head, flags);
4919
4920 del_page_from_lru_list(page, lruvec);
4921 success = lru_gen_add_page(lruvec, page, false);
4922 VM_BUG_ON(!success);
4923
4924 if (!--remaining)
4925 return false;
4926 }
4927 }
4928
4929 return true;
4930}
4931
4932static bool drain_evictable(struct lruvec *lruvec)
4933{
4934 int gen, type, zone;
4935 int remaining = MAX_LRU_BATCH;
4936
4937 for_each_gen_type_zone(gen, type, zone) {
4938 struct list_head *head = &lruvec->lrugen.lists[gen][type][zone];
4939
4940 while (!list_empty(head)) {
4941 bool success;
4942 struct page *page = lru_to_page(head);
4943
4944 VM_BUG_ON_PAGE(PageTail(page), page);
4945 VM_BUG_ON_PAGE(PageUnevictable(page), page);
4946 VM_BUG_ON_PAGE(PageActive(page), page);
4947 VM_BUG_ON_PAGE(page_is_file_lru(page) != type, page);
4948 VM_BUG_ON_PAGE(page_zonenum(page) != zone, page);
4949
4950 prefetchw_prev_lru_page(page, head, flags);
4951
4952 success = lru_gen_del_page(lruvec, page, false);
4953 VM_BUG_ON(!success);
4954 add_page_to_lru_list(page, lruvec);
4955
4956 if (!--remaining)
4957 return false;
4958 }
4959 }
4960
4961 return true;
4962}
4963
4964static void lru_gen_change_state(bool enable)
4965{
4966 static DEFINE_MUTEX(state_mutex);
4967
4968 struct mem_cgroup *memcg;
4969
4970 cgroup_lock();
4971 cpus_read_lock();
4972 get_online_mems();
4973 mutex_lock(&state_mutex);
4974
4975 if (enable == lru_gen_enabled())
4976 goto unlock;
4977
4978 if (enable)
4979 static_branch_enable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
4980 else
4981 static_branch_disable_cpuslocked(&lru_gen_caps[LRU_GEN_CORE]);
4982
4983 memcg = mem_cgroup_iter(NULL, NULL, NULL);
4984 do {
4985 int nid;
4986
4987 for_each_node(nid) {
4988 struct lruvec *lruvec = get_lruvec(memcg, nid);
4989
4990 if (!lruvec)
4991 continue;
4992
4993 spin_lock_irq(&lruvec->lru_lock);
4994
4995 VM_BUG_ON(!seq_is_valid(lruvec));
4996 VM_BUG_ON(!state_is_valid(lruvec));
4997
4998 lruvec->lrugen.enabled = enable;
4999
5000 while (!(enable ? fill_evictable(lruvec) : drain_evictable(lruvec))) {
5001 spin_unlock_irq(&lruvec->lru_lock);
5002 cond_resched();
5003 spin_lock_irq(&lruvec->lru_lock);
5004 }
5005
5006 spin_unlock_irq(&lruvec->lru_lock);
5007 }
5008
5009 cond_resched();
5010 } while ((memcg = mem_cgroup_iter(NULL, memcg, NULL)));
5011unlock:
5012 mutex_unlock(&state_mutex);
5013 put_online_mems();
5014 cpus_read_unlock();
5015 cgroup_unlock();
5016}
5017
5018/******************************************************************************
5019 * sysfs interface
5020 ******************************************************************************/
5021
5022static ssize_t show_enable(struct kobject *kobj, struct kobj_attribute *attr, char *buf)
5023{
5024 unsigned int caps = 0;
5025
5026 if (get_cap(LRU_GEN_CORE))
5027 caps |= BIT(LRU_GEN_CORE);
5028
5029 if (arch_has_hw_pte_young() && get_cap(LRU_GEN_MM_WALK))
5030 caps |= BIT(LRU_GEN_MM_WALK);
5031
5032 if (IS_ENABLED(CONFIG_ARCH_HAS_NONLEAF_PMD_YOUNG) && get_cap(LRU_GEN_NONLEAF_YOUNG))
5033 caps |= BIT(LRU_GEN_NONLEAF_YOUNG);
5034
5035 return snprintf(buf, PAGE_SIZE, "0x%04x\n", caps);
5036}
5037
5038static ssize_t store_enable(struct kobject *kobj, struct kobj_attribute *attr,
5039 const char *buf, size_t len)
5040{
5041 int i;
5042 unsigned int caps;
5043
5044 if (tolower(*buf) == 'n')
5045 caps = 0;
5046 else if (tolower(*buf) == 'y')
5047 caps = -1;
5048 else if (kstrtouint(buf, 0, &caps))
5049 return -EINVAL;
5050
5051 for (i = 0; i < NR_LRU_GEN_CAPS; i++) {
5052 bool enable = caps & BIT(i);
5053
5054 if (i == LRU_GEN_CORE)
5055 lru_gen_change_state(enable);
5056 else if (enable)
5057 static_branch_enable(&lru_gen_caps[i]);
5058 else
5059 static_branch_disable(&lru_gen_caps[i]);
5060 }
5061
5062 return len;
5063}
5064
5065static struct kobj_attribute lru_gen_enabled_attr = __ATTR(
5066 enabled, 0644, show_enable, store_enable
5067);
5068
5069static struct attribute *lru_gen_attrs[] = {
5070 &lru_gen_enabled_attr.attr,
5071 NULL
5072};
5073
5074static struct attribute_group lru_gen_attr_group = {
5075 .name = "lru_gen",
5076 .attrs = lru_gen_attrs,
5077};
5078
5079/******************************************************************************
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005080 * initialization
5081 ******************************************************************************/
5082
5083void lru_gen_init_lruvec(struct lruvec *lruvec)
5084{
5085 int gen, type, zone;
5086 struct lru_gen_struct *lrugen = &lruvec->lrugen;
5087
5088 lrugen->max_seq = MIN_NR_GENS + 1;
Yu Zhao76f7f072022-01-27 19:52:09 -07005089 lrugen->enabled = lru_gen_enabled();
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005090
5091 for_each_gen_type_zone(gen, type, zone)
5092 INIT_LIST_HEAD(&lrugen->lists[gen][type][zone]);
Yu Zhao5280d762022-01-27 19:23:01 -07005093
5094 lruvec->mm_state.seq = MIN_NR_GENS;
5095 init_waitqueue_head(&lruvec->mm_state.wait);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005096}
5097
5098#ifdef CONFIG_MEMCG
5099void lru_gen_init_memcg(struct mem_cgroup *memcg)
5100{
Yu Zhao5280d762022-01-27 19:23:01 -07005101 INIT_LIST_HEAD(&memcg->mm_list.fifo);
5102 spin_lock_init(&memcg->mm_list.lock);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005103}
5104
5105void lru_gen_exit_memcg(struct mem_cgroup *memcg)
5106{
Yu Zhao5280d762022-01-27 19:23:01 -07005107 int i;
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005108 int nid;
5109
5110 for_each_node(nid) {
5111 struct lruvec *lruvec = get_lruvec(memcg, nid);
5112
5113 VM_BUG_ON(memchr_inv(lruvec->lrugen.nr_pages, 0,
5114 sizeof(lruvec->lrugen.nr_pages)));
Yu Zhao5280d762022-01-27 19:23:01 -07005115
5116 for (i = 0; i < NR_BLOOM_FILTERS; i++) {
5117 bitmap_free(lruvec->mm_state.filters[i]);
5118 lruvec->mm_state.filters[i] = NULL;
5119 }
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005120 }
5121}
5122#endif
5123
5124static int __init init_lru_gen(void)
5125{
5126 BUILD_BUG_ON(MIN_NR_GENS + 1 >= MAX_NR_GENS);
5127 BUILD_BUG_ON(BIT(LRU_GEN_WIDTH) <= MAX_NR_GENS);
Yu Zhao5280d762022-01-27 19:23:01 -07005128 BUILD_BUG_ON(sizeof(MM_STAT_CODES) != NR_MM_STATS + 1);
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005129
Yu Zhao76f7f072022-01-27 19:52:09 -07005130 if (sysfs_create_group(mm_kobj, &lru_gen_attr_group))
5131 pr_err("lru_gen: failed to create sysfs group\n");
5132
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005133 return 0;
5134};
5135late_initcall(init_lru_gen);
5136
Yu Zhaoa1537a62022-01-27 20:32:37 -07005137#else
5138
5139static void lru_gen_age_node(struct pglist_data *pgdat, struct scan_control *sc)
5140{
5141}
5142
5143static void lru_gen_shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
5144{
5145}
5146
Yu Zhaof88ed5a2021-01-25 21:12:33 -07005147#endif /* CONFIG_LRU_GEN */
5148
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005149static void shrink_lruvec(struct lruvec *lruvec, struct scan_control *sc)
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005150{
5151 unsigned long nr[NR_LRU_LISTS];
Mel Gormane82e0562013-07-03 15:01:44 -07005152 unsigned long targets[NR_LRU_LISTS];
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005153 unsigned long nr_to_scan;
5154 enum lru_list lru;
5155 unsigned long nr_reclaimed = 0;
5156 unsigned long nr_to_reclaim = sc->nr_to_reclaim;
5157 struct blk_plug plug;
Mel Gorman1a501902014-06-04 16:10:49 -07005158 bool scan_adjusted;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005159
Yu Zhaoa1537a62022-01-27 20:32:37 -07005160 if (lru_gen_enabled()) {
5161 lru_gen_shrink_lruvec(lruvec, sc);
5162 return;
5163 }
5164
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005165 get_scan_count(lruvec, sc, nr);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005166
Mel Gormane82e0562013-07-03 15:01:44 -07005167 /* Record the original scan target for proportional adjustments later */
5168 memcpy(targets, nr, sizeof(nr));
5169
Mel Gorman1a501902014-06-04 16:10:49 -07005170 /*
5171 * Global reclaiming within direct reclaim at DEF_PRIORITY is a normal
5172 * event that can occur when there is little memory pressure e.g.
5173 * multiple streaming readers/writers. Hence, we do not abort scanning
5174 * when the requested number of pages are reclaimed when scanning at
5175 * DEF_PRIORITY on the assumption that the fact we are direct
5176 * reclaiming implies that kswapd is not keeping up and it is best to
5177 * do a batch of work at once. For memcg reclaim one check is made to
5178 * abort proportional reclaim if either the file or anon lru has already
5179 * dropped to zero at the first pass.
5180 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005181 scan_adjusted = (!cgroup_reclaim(sc) && !current_is_kswapd() &&
Mel Gorman1a501902014-06-04 16:10:49 -07005182 sc->priority == DEF_PRIORITY);
5183
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005184 blk_start_plug(&plug);
5185 while (nr[LRU_INACTIVE_ANON] || nr[LRU_ACTIVE_FILE] ||
5186 nr[LRU_INACTIVE_FILE]) {
Mel Gormane82e0562013-07-03 15:01:44 -07005187 unsigned long nr_anon, nr_file, percentage;
5188 unsigned long nr_scanned;
5189
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005190 for_each_evictable_lru(lru) {
5191 if (nr[lru]) {
5192 nr_to_scan = min(nr[lru], SWAP_CLUSTER_MAX);
5193 nr[lru] -= nr_to_scan;
5194
5195 nr_reclaimed += shrink_list(lru, nr_to_scan,
Johannes Weiner3b991202019-04-18 17:50:34 -07005196 lruvec, sc);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005197 }
5198 }
Mel Gormane82e0562013-07-03 15:01:44 -07005199
Michal Hockobd041732016-12-02 17:26:48 -08005200 cond_resched();
5201
Mel Gormane82e0562013-07-03 15:01:44 -07005202 if (nr_reclaimed < nr_to_reclaim || scan_adjusted)
5203 continue;
5204
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005205 /*
Mel Gormane82e0562013-07-03 15:01:44 -07005206 * For kswapd and memcg, reclaim at least the number of pages
Mel Gorman1a501902014-06-04 16:10:49 -07005207 * requested. Ensure that the anon and file LRUs are scanned
Mel Gormane82e0562013-07-03 15:01:44 -07005208 * proportionally what was requested by get_scan_count(). We
5209 * stop reclaiming one LRU and reduce the amount scanning
5210 * proportional to the original scan target.
5211 */
5212 nr_file = nr[LRU_INACTIVE_FILE] + nr[LRU_ACTIVE_FILE];
5213 nr_anon = nr[LRU_INACTIVE_ANON] + nr[LRU_ACTIVE_ANON];
5214
Mel Gorman1a501902014-06-04 16:10:49 -07005215 /*
5216 * It's just vindictive to attack the larger once the smaller
5217 * has gone to zero. And given the way we stop scanning the
5218 * smaller below, this makes sure that we only make one nudge
5219 * towards proportionality once we've got nr_to_reclaim.
5220 */
5221 if (!nr_file || !nr_anon)
5222 break;
5223
Mel Gormane82e0562013-07-03 15:01:44 -07005224 if (nr_file > nr_anon) {
5225 unsigned long scan_target = targets[LRU_INACTIVE_ANON] +
5226 targets[LRU_ACTIVE_ANON] + 1;
5227 lru = LRU_BASE;
5228 percentage = nr_anon * 100 / scan_target;
5229 } else {
5230 unsigned long scan_target = targets[LRU_INACTIVE_FILE] +
5231 targets[LRU_ACTIVE_FILE] + 1;
5232 lru = LRU_FILE;
5233 percentage = nr_file * 100 / scan_target;
5234 }
5235
5236 /* Stop scanning the smaller of the LRU */
5237 nr[lru] = 0;
5238 nr[lru + LRU_ACTIVE] = 0;
5239
5240 /*
5241 * Recalculate the other LRU scan count based on its original
5242 * scan target and the percentage scanning already complete
5243 */
5244 lru = (lru == LRU_FILE) ? LRU_BASE : LRU_FILE;
5245 nr_scanned = targets[lru] - nr[lru];
5246 nr[lru] = targets[lru] * (100 - percentage) / 100;
5247 nr[lru] -= min(nr[lru], nr_scanned);
5248
5249 lru += LRU_ACTIVE;
5250 nr_scanned = targets[lru] - nr[lru];
5251 nr[lru] = targets[lru] * (100 - percentage) / 100;
5252 nr[lru] -= min(nr[lru], nr_scanned);
5253
5254 scan_adjusted = true;
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005255 }
5256 blk_finish_plug(&plug);
5257 sc->nr_reclaimed += nr_reclaimed;
5258
5259 /*
5260 * Even if we did not try to evict anon pages at all, we want to
5261 * rebalance the anon lru active/inactive ratio.
5262 */
Dave Hansen2f368a92021-09-02 14:59:23 -07005263 if (can_age_anon_pages(lruvec_pgdat(lruvec), sc) &&
5264 inactive_is_low(lruvec, LRU_INACTIVE_ANON))
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005265 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
5266 sc, LRU_ACTIVE_ANON);
Johannes Weiner9b4f98c2013-02-22 16:32:19 -08005267}
5268
Mel Gorman23b9da52012-05-29 15:06:20 -07005269/* Use reclaim/compaction for costly allocs or under memory pressure */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005270static bool in_reclaim_compaction(struct scan_control *sc)
Mel Gorman23b9da52012-05-29 15:06:20 -07005271{
Kirill A. Shutemovd84da3f2012-12-11 16:00:31 -08005272 if (IS_ENABLED(CONFIG_COMPACTION) && sc->order &&
Mel Gorman23b9da52012-05-29 15:06:20 -07005273 (sc->order > PAGE_ALLOC_COSTLY_ORDER ||
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005274 sc->priority < DEF_PRIORITY - 2))
Mel Gorman23b9da52012-05-29 15:06:20 -07005275 return true;
5276
5277 return false;
5278}
5279
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005280/*
Mel Gorman23b9da52012-05-29 15:06:20 -07005281 * Reclaim/compaction is used for high-order allocation requests. It reclaims
5282 * order-0 pages before compacting the zone. should_continue_reclaim() returns
5283 * true if more pages should be reclaimed such that when the page allocator
Qiwu Chendf3a45f2020-06-03 16:01:21 -07005284 * calls try_to_compact_pages() that it will have enough free pages to succeed.
Mel Gorman23b9da52012-05-29 15:06:20 -07005285 * It will give up earlier than that if there is difficulty reclaiming pages.
Mel Gorman3e7d3442011-01-13 15:45:56 -08005286 */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005287static inline bool should_continue_reclaim(struct pglist_data *pgdat,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005288 unsigned long nr_reclaimed,
Mel Gorman3e7d3442011-01-13 15:45:56 -08005289 struct scan_control *sc)
5290{
5291 unsigned long pages_for_compaction;
5292 unsigned long inactive_lru_pages;
Mel Gormana9dd0a82016-07-28 15:46:02 -07005293 int z;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005294
5295 /* If not in reclaim/compaction mode, stop */
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005296 if (!in_reclaim_compaction(sc))
Mel Gorman3e7d3442011-01-13 15:45:56 -08005297 return false;
5298
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005299 /*
5300 * Stop if we failed to reclaim any pages from the last SWAP_CLUSTER_MAX
5301 * number of pages that were scanned. This will return to the caller
5302 * with the risk reclaim/compaction and the resulting allocation attempt
5303 * fails. In the past we have tried harder for __GFP_RETRY_MAYFAIL
5304 * allocations through requiring that the full LRU list has been scanned
5305 * first, by assuming that zero delta of sc->nr_scanned means full LRU
5306 * scan, but that approximation was wrong, and there were corner cases
5307 * where always a non-zero amount of pages were scanned.
5308 */
5309 if (!nr_reclaimed)
5310 return false;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005311
Mel Gorman3e7d3442011-01-13 15:45:56 -08005312 /* If compaction would go ahead or the allocation would succeed, stop */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005313 for (z = 0; z <= sc->reclaim_idx; z++) {
5314 struct zone *zone = &pgdat->node_zones[z];
Mel Gorman6aa303d2016-09-01 16:14:55 -07005315 if (!managed_zone(zone))
Mel Gormana9dd0a82016-07-28 15:46:02 -07005316 continue;
5317
5318 switch (compaction_suitable(zone, sc->order, 0, sc->reclaim_idx)) {
Vlastimil Babkacf378312016-10-07 16:57:41 -07005319 case COMPACT_SUCCESS:
Mel Gormana9dd0a82016-07-28 15:46:02 -07005320 case COMPACT_CONTINUE:
5321 return false;
5322 default:
5323 /* check next zone */
5324 ;
5325 }
Mel Gorman3e7d3442011-01-13 15:45:56 -08005326 }
Hillf Danton1c6c1592019-09-23 15:37:26 -07005327
5328 /*
5329 * If we have not reclaimed enough pages for compaction and the
5330 * inactive lists are large enough, continue reclaiming
5331 */
5332 pages_for_compaction = compact_gap(sc->order);
5333 inactive_lru_pages = node_page_state(pgdat, NR_INACTIVE_FILE);
Keith Buscha2a36482021-09-02 14:59:26 -07005334 if (can_reclaim_anon_pages(NULL, pgdat->node_id, sc))
Hillf Danton1c6c1592019-09-23 15:37:26 -07005335 inactive_lru_pages += node_page_state(pgdat, NR_INACTIVE_ANON);
5336
Vlastimil Babka5ee04712019-09-23 15:37:29 -07005337 return inactive_lru_pages > pages_for_compaction;
Mel Gorman3e7d3442011-01-13 15:45:56 -08005338}
5339
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005340static void shrink_node_memcgs(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08005341{
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005342 struct mem_cgroup *target_memcg = sc->target_mem_cgroup;
Johannes Weinerd2af3392019-11-30 17:55:43 -08005343 struct mem_cgroup *memcg;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005344
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005345 memcg = mem_cgroup_iter(target_memcg, NULL, NULL);
Johannes Weiner56600482012-01-12 17:17:59 -08005346 do {
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005347 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005348 unsigned long reclaimed;
5349 unsigned long scanned;
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005350 bool skip = false;
Johannes Weiner56600482012-01-12 17:17:59 -08005351
Xunlei Pange3336ca2020-09-04 16:35:27 -07005352 /*
5353 * This loop can become CPU-bound when target memcgs
5354 * aren't eligible for reclaim - either because they
5355 * don't have any reclaimable pages, or because their
5356 * memory is explicitly protected. Avoid soft lockups.
5357 */
5358 cond_resched();
5359
Liujie Xieb7ea1c42022-06-01 15:38:17 +08005360 trace_android_vh_shrink_node_memcgs(memcg, &skip);
5361 if (skip)
5362 continue;
5363
Chris Down45c7f7e2020-08-06 23:22:05 -07005364 mem_cgroup_calculate_protection(target_memcg, memcg);
5365
5366 if (mem_cgroup_below_min(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005367 /*
5368 * Hard protection.
5369 * If there is no reclaimable memory, OOM.
5370 */
5371 continue;
Chris Down45c7f7e2020-08-06 23:22:05 -07005372 } else if (mem_cgroup_below_low(memcg)) {
Johannes Weinerd2af3392019-11-30 17:55:43 -08005373 /*
5374 * Soft protection.
5375 * Respect the protection only as long as
5376 * there is an unprotected supply
5377 * of reclaimable memory from other cgroups.
5378 */
5379 if (!sc->memcg_low_reclaim) {
5380 sc->memcg_low_skipped = 1;
Roman Gushchinbf8d5d52018-06-07 17:07:46 -07005381 continue;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005382 }
Johannes Weinerd2af3392019-11-30 17:55:43 -08005383 memcg_memory_event(memcg, MEMCG_LOW);
Johannes Weiner6b4f7792014-12-12 16:56:13 -08005384 }
5385
Johannes Weinerd2af3392019-11-30 17:55:43 -08005386 reclaimed = sc->nr_reclaimed;
5387 scanned = sc->nr_scanned;
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005388
5389 shrink_lruvec(lruvec, sc);
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005390
Johannes Weinerd2af3392019-11-30 17:55:43 -08005391 shrink_slab(sc->gfp_mask, pgdat->node_id, memcg,
5392 sc->priority);
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005393
Johannes Weinerd2af3392019-11-30 17:55:43 -08005394 /* Record the group's reclaim efficiency */
5395 vmpressure(sc->gfp_mask, memcg, false,
5396 sc->nr_scanned - scanned,
5397 sc->nr_reclaimed - reclaimed);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005398
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005399 } while ((memcg = mem_cgroup_iter(target_memcg, memcg, NULL)));
5400}
5401
Liu Song6c9e09072020-01-30 22:14:08 -08005402static void shrink_node(pg_data_t *pgdat, struct scan_control *sc)
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005403{
5404 struct reclaim_state *reclaim_state = current->reclaim_state;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005405 unsigned long nr_reclaimed, nr_scanned;
Johannes Weiner1b051172019-11-30 17:55:52 -08005406 struct lruvec *target_lruvec;
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005407 bool reclaimable = false;
5408
Johannes Weiner1b051172019-11-30 17:55:52 -08005409 target_lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup, pgdat);
5410
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005411again:
5412 memset(&sc->nr, 0, sizeof(sc->nr));
5413
5414 nr_reclaimed = sc->nr_reclaimed;
5415 nr_scanned = sc->nr_scanned;
5416
Yu Zhao3eb07702020-09-27 20:49:08 -06005417 prepare_scan_count(pgdat, sc);
Johannes Weiner53138ce2019-11-30 17:55:56 -08005418
Johannes Weiner0f6a5cf2019-11-30 17:55:49 -08005419 shrink_node_memcgs(pgdat, sc);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005420
Johannes Weinerd2af3392019-11-30 17:55:43 -08005421 if (reclaim_state) {
5422 sc->nr_reclaimed += reclaim_state->reclaimed_slab;
5423 reclaim_state->reclaimed_slab = 0;
5424 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005425
Johannes Weinerd2af3392019-11-30 17:55:43 -08005426 /* Record the subtree's reclaim efficiency */
Johannes Weiner1b051172019-11-30 17:55:52 -08005427 vmpressure(sc->gfp_mask, sc->target_mem_cgroup, true,
Johannes Weinerd2af3392019-11-30 17:55:43 -08005428 sc->nr_scanned - nr_scanned,
5429 sc->nr_reclaimed - nr_reclaimed);
5430
5431 if (sc->nr_reclaimed - nr_reclaimed)
5432 reclaimable = true;
5433
5434 if (current_is_kswapd()) {
5435 /*
5436 * If reclaim is isolating dirty pages under writeback,
5437 * it implies that the long-lived page allocation rate
5438 * is exceeding the page laundering rate. Either the
5439 * global limits are not being effective at throttling
5440 * processes due to the page distribution throughout
5441 * zones or there is heavy usage of a slow backing
5442 * device. The only option is to throttle from reclaim
5443 * context which is not ideal as there is no guarantee
5444 * the dirtying process is throttled in the same way
5445 * balance_dirty_pages() manages.
5446 *
5447 * Once a node is flagged PGDAT_WRITEBACK, kswapd will
5448 * count the number of pages under pages flagged for
5449 * immediate reclaim and stall if any are encountered
5450 * in the nr_immediate check below.
5451 */
5452 if (sc->nr.writeback && sc->nr.writeback == sc->nr.taken)
5453 set_bit(PGDAT_WRITEBACK, &pgdat->flags);
Andrey Ryabinind108c772018-04-10 16:27:59 -07005454
Johannes Weinerd2af3392019-11-30 17:55:43 -08005455 /* Allow kswapd to start writing pages during reclaim.*/
5456 if (sc->nr.unqueued_dirty == sc->nr.file_taken)
5457 set_bit(PGDAT_DIRTY, &pgdat->flags);
Andrey Ryabinine3c1ac52018-04-10 16:28:03 -07005458
5459 /*
Randy Dunlap1eba09c2020-08-11 18:33:26 -07005460 * If kswapd scans pages marked for immediate
Johannes Weinerd2af3392019-11-30 17:55:43 -08005461 * reclaim and under writeback (nr_immediate), it
5462 * implies that pages are cycling through the LRU
5463 * faster than they are written so also forcibly stall.
Andrey Ryabinind108c772018-04-10 16:27:59 -07005464 */
Johannes Weinerd2af3392019-11-30 17:55:43 -08005465 if (sc->nr.immediate)
5466 congestion_wait(BLK_RW_ASYNC, HZ/10);
5467 }
Andrey Ryabinind108c772018-04-10 16:27:59 -07005468
Johannes Weinerd2af3392019-11-30 17:55:43 -08005469 /*
Johannes Weiner1b051172019-11-30 17:55:52 -08005470 * Tag a node/memcg as congested if all the dirty pages
5471 * scanned were backed by a congested BDI and
5472 * wait_iff_congested will stall.
5473 *
Johannes Weinerd2af3392019-11-30 17:55:43 -08005474 * Legacy memcg will stall in page writeback so avoid forcibly
5475 * stalling in wait_iff_congested().
5476 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005477 if ((current_is_kswapd() ||
5478 (cgroup_reclaim(sc) && writeback_throttling_sane(sc))) &&
Johannes Weinerd2af3392019-11-30 17:55:43 -08005479 sc->nr.dirty && sc->nr.dirty == sc->nr.congested)
Johannes Weiner1b051172019-11-30 17:55:52 -08005480 set_bit(LRUVEC_CONGESTED, &target_lruvec->flags);
Johannes Weinerd2af3392019-11-30 17:55:43 -08005481
5482 /*
5483 * Stall direct reclaim for IO completions if underlying BDIs
5484 * and node is congested. Allow kswapd to continue until it
5485 * starts encountering unqueued dirty pages or cycling through
5486 * the LRU too quickly.
5487 */
Johannes Weiner1b051172019-11-30 17:55:52 -08005488 if (!current_is_kswapd() && current_may_throttle() &&
5489 !sc->hibernation_mode &&
5490 test_bit(LRUVEC_CONGESTED, &target_lruvec->flags))
Johannes Weinerd2af3392019-11-30 17:55:43 -08005491 wait_iff_congested(BLK_RW_ASYNC, HZ/10);
5492
5493 if (should_continue_reclaim(pgdat, sc->nr_reclaimed - nr_reclaimed,
5494 sc))
5495 goto again;
Johannes Weiner2344d7e2014-08-06 16:06:15 -07005496
Johannes Weinerc73322d2017-05-03 14:51:51 -07005497 /*
5498 * Kswapd gives up on balancing particular nodes after too
5499 * many failures to reclaim anything from them and goes to
5500 * sleep. On reclaim progress, reset the failure counter. A
5501 * successful direct reclaim run will revive a dormant kswapd.
5502 */
5503 if (reclaimable)
5504 pgdat->kswapd_failures = 0;
Johannes Weinerf16015f2012-01-12 17:17:52 -08005505}
5506
Vlastimil Babka53853e22014-10-09 15:27:02 -07005507/*
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005508 * Returns true if compaction should go ahead for a costly-order request, or
5509 * the allocation would already succeed without compaction. Return false if we
5510 * should reclaim first.
Vlastimil Babka53853e22014-10-09 15:27:02 -07005511 */
Mel Gorman4f588332016-07-28 15:46:38 -07005512static inline bool compaction_ready(struct zone *zone, struct scan_control *sc)
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005513{
Mel Gorman31483b62016-07-28 15:45:46 -07005514 unsigned long watermark;
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005515 enum compact_result suitable;
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005516
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005517 suitable = compaction_suitable(zone, sc->order, 0, sc->reclaim_idx);
5518 if (suitable == COMPACT_SUCCESS)
5519 /* Allocation should succeed already. Don't reclaim. */
5520 return true;
5521 if (suitable == COMPACT_SKIPPED)
5522 /* Compaction cannot yet proceed. Do reclaim. */
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005523 return false;
5524
Vlastimil Babkafdd4c6142016-10-07 16:58:03 -07005525 /*
5526 * Compaction is already possible, but it takes time to run and there
5527 * are potentially other callers using the pages just freed. So proceed
5528 * with reclaim to make a buffer of free pages available to give
5529 * compaction a reasonable chance of completing and allocating the page.
5530 * Note that we won't actually reclaim the whole buffer in one attempt
5531 * as the target watermark in should_continue_reclaim() is lower. But if
5532 * we are already above the high+gap watermark, don't reclaim at all.
5533 */
5534 watermark = high_wmark_pages(zone) + compact_gap(sc->order);
5535
5536 return zone_watermark_ok_safe(zone, 0, watermark, sc->reclaim_idx);
Mel Gormanfe4b1b22012-01-12 17:19:45 -08005537}
5538
Linus Torvalds1da177e2005-04-16 15:20:36 -07005539/*
5540 * This is the direct reclaim path, for page-allocating processes. We only
5541 * try to reclaim pages from zones which will satisfy the caller's allocation
5542 * request.
5543 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07005544 * If a zone is deemed to be full of pinned pages then just give it a light
5545 * scan then give up on it.
5546 */
Michal Hocko0a0337e2016-05-20 16:57:00 -07005547static void shrink_zones(struct zonelist *zonelist, struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005548{
Mel Gormandd1a2392008-04-28 02:12:17 -07005549 struct zoneref *z;
Mel Gorman54a6eb52008-04-28 02:12:16 -07005550 struct zone *zone;
Andrew Morton0608f432013-09-24 15:27:41 -07005551 unsigned long nr_soft_reclaimed;
5552 unsigned long nr_soft_scanned;
Weijie Yang619d0d762014-04-07 15:36:59 -07005553 gfp_t orig_mask;
Mel Gorman79dafcd2016-07-28 15:45:53 -07005554 pg_data_t *last_pgdat = NULL;
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005555
Mel Gormancc715d92012-03-21 16:34:00 -07005556 /*
5557 * If the number of buffer_heads in the machine exceeds the maximum
5558 * allowed level, force direct reclaim to scan the highmem zone as
5559 * highmem pages could be pinning lowmem pages storing buffer_heads
5560 */
Weijie Yang619d0d762014-04-07 15:36:59 -07005561 orig_mask = sc->gfp_mask;
Mel Gormanb2e18752016-07-28 15:45:37 -07005562 if (buffer_heads_over_limit) {
Mel Gormancc715d92012-03-21 16:34:00 -07005563 sc->gfp_mask |= __GFP_HIGHMEM;
Mel Gorman4f588332016-07-28 15:46:38 -07005564 sc->reclaim_idx = gfp_zone(sc->gfp_mask);
Mel Gormanb2e18752016-07-28 15:45:37 -07005565 }
Mel Gormancc715d92012-03-21 16:34:00 -07005566
Mel Gormand4debc62010-08-09 17:19:29 -07005567 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Mel Gormanb2e18752016-07-28 15:45:37 -07005568 sc->reclaim_idx, sc->nodemask) {
Mel Gormanb2e18752016-07-28 15:45:37 -07005569 /*
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005570 * Take care memory controller reclaiming has small influence
5571 * to global LRU.
5572 */
Johannes Weinerb5ead352019-11-30 17:55:40 -08005573 if (!cgroup_reclaim(sc)) {
Vladimir Davydov344736f2014-10-20 15:50:30 +04005574 if (!cpuset_zone_allowed(zone,
5575 GFP_KERNEL | __GFP_HARDWALL))
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005576 continue;
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005577
Johannes Weiner0b064962014-08-06 16:06:12 -07005578 /*
5579 * If we already have plenty of memory free for
5580 * compaction in this zone, don't free any more.
5581 * Even though compaction is invoked for any
5582 * non-zero order, only frequent costly order
5583 * reclamation is disruptive enough to become a
5584 * noticeable problem, like transparent huge
5585 * page allocations.
5586 */
5587 if (IS_ENABLED(CONFIG_COMPACTION) &&
5588 sc->order > PAGE_ALLOC_COSTLY_ORDER &&
Mel Gorman4f588332016-07-28 15:46:38 -07005589 compaction_ready(zone, sc)) {
Johannes Weiner0b064962014-08-06 16:06:12 -07005590 sc->compaction_ready = true;
5591 continue;
Rik van Riele0887c12011-10-31 17:09:31 -07005592 }
Johannes Weiner0b064962014-08-06 16:06:12 -07005593
Andrew Morton0608f432013-09-24 15:27:41 -07005594 /*
Mel Gorman79dafcd2016-07-28 15:45:53 -07005595 * Shrink each node in the zonelist once. If the
5596 * zonelist is ordered by zone (not the default) then a
5597 * node may be shrunk multiple times but in that case
5598 * the user prefers lower zones being preserved.
5599 */
5600 if (zone->zone_pgdat == last_pgdat)
5601 continue;
5602
5603 /*
Andrew Morton0608f432013-09-24 15:27:41 -07005604 * This steals pages from memory cgroups over softlimit
5605 * and returns the number of reclaimed pages and
5606 * scanned pages. This works for global memory pressure
5607 * and balancing, not for a memcg's limit.
5608 */
5609 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07005610 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(zone->zone_pgdat,
Andrew Morton0608f432013-09-24 15:27:41 -07005611 sc->order, sc->gfp_mask,
5612 &nr_soft_scanned);
5613 sc->nr_reclaimed += nr_soft_reclaimed;
5614 sc->nr_scanned += nr_soft_scanned;
KAMEZAWA Hiroyukiac34a1a2011-06-27 16:18:12 -07005615 /* need some check for avoid more shrink_zone() */
KAMEZAWA Hiroyuki1cfb4192008-02-07 00:14:37 -08005616 }
Nick Piggin408d8542006-09-25 23:31:27 -07005617
Mel Gorman79dafcd2016-07-28 15:45:53 -07005618 /* See comment about same check for global reclaim above */
5619 if (zone->zone_pgdat == last_pgdat)
5620 continue;
5621 last_pgdat = zone->zone_pgdat;
Mel Gorman970a39a2016-07-28 15:46:35 -07005622 shrink_node(zone->zone_pgdat, sc);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005623 }
Mel Gormane0c23272011-10-31 17:09:33 -07005624
Vladimir Davydov65ec02c2014-04-03 14:47:20 -07005625 /*
Weijie Yang619d0d762014-04-07 15:36:59 -07005626 * Restore to original mask to avoid the impact on the caller if we
5627 * promoted it to __GFP_HIGHMEM.
5628 */
5629 sc->gfp_mask = orig_mask;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005630}
Rik van Riel4f98a2f2008-10-18 20:26:32 -07005631
Johannes Weinerb9107182019-11-30 17:55:59 -08005632static void snapshot_refaults(struct mem_cgroup *target_memcg, pg_data_t *pgdat)
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005633{
Johannes Weinerb9107182019-11-30 17:55:59 -08005634 struct lruvec *target_lruvec;
5635 unsigned long refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005636
Yu Zhaoa1537a62022-01-27 20:32:37 -07005637 if (lru_gen_enabled())
5638 return;
5639
Johannes Weinerb9107182019-11-30 17:55:59 -08005640 target_lruvec = mem_cgroup_lruvec(target_memcg, pgdat);
Joonsoo Kim170b04b72020-08-11 18:30:43 -07005641 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_ANON);
5642 target_lruvec->refaults[0] = refaults;
5643 refaults = lruvec_page_state(target_lruvec, WORKINGSET_ACTIVATE_FILE);
5644 target_lruvec->refaults[1] = refaults;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005645}
5646
Linus Torvalds1da177e2005-04-16 15:20:36 -07005647/*
5648 * This is the main entry point to direct page reclaim.
5649 *
5650 * If a full scan of the inactive list fails to free enough memory then we
5651 * are "out of memory" and something needs to be killed.
5652 *
5653 * If the caller is !__GFP_FS then the probability of a failure is reasonably
5654 * high - the zone may be full of dirty or under-writeback pages, which this
Jens Axboe5b0830c2009-09-23 19:37:09 +02005655 * caller can't do much about. We kick the writeback threads and take explicit
5656 * naps in the hope that some of these pages can be written. But if the
5657 * allocating task holds filesystem locks which prevent writeout this might not
5658 * work, and the allocation attempt will fail.
Nishanth Aravamudana41f24e2008-04-29 00:58:25 -07005659 *
5660 * returns: 0, if no pages reclaimed
5661 * else, the number of pages reclaimed
Linus Torvalds1da177e2005-04-16 15:20:36 -07005662 */
Mel Gormandac1d272008-04-28 02:12:12 -07005663static unsigned long do_try_to_free_pages(struct zonelist *zonelist,
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005664 struct scan_control *sc)
Linus Torvalds1da177e2005-04-16 15:20:36 -07005665{
Johannes Weiner241994ed2015-02-11 15:26:06 -08005666 int initial_priority = sc->priority;
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005667 pg_data_t *last_pgdat;
5668 struct zoneref *z;
5669 struct zone *zone;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005670retry:
Keika Kobayashi873b4772008-07-25 01:48:52 -07005671 delayacct_freepages_start();
5672
Johannes Weinerb5ead352019-11-30 17:55:40 -08005673 if (!cgroup_reclaim(sc))
Mel Gorman7cc30fc2016-07-28 15:46:59 -07005674 __count_zid_vm_events(ALLOCSTALL, sc->reclaim_idx, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07005675
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005676 do {
Anton Vorontsov70ddf632013-04-29 15:08:31 -07005677 vmpressure_prio(sc->gfp_mask, sc->target_mem_cgroup,
5678 sc->priority);
Balbir Singh66e17072008-02-07 00:13:56 -08005679 sc->nr_scanned = 0;
Michal Hocko0a0337e2016-05-20 16:57:00 -07005680 shrink_zones(zonelist, sc);
Mel Gormane0c23272011-10-31 17:09:33 -07005681
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005682 if (sc->nr_reclaimed >= sc->nr_to_reclaim)
Johannes Weiner0b064962014-08-06 16:06:12 -07005683 break;
5684
5685 if (sc->compaction_ready)
5686 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005687
5688 /*
Minchan Kim0e50ce32013-02-22 16:35:37 -08005689 * If we're getting trouble reclaiming, start doing
5690 * writepage even in laptop mode.
5691 */
5692 if (sc->priority < DEF_PRIORITY - 2)
5693 sc->may_writepage = 1;
Johannes Weiner0b064962014-08-06 16:06:12 -07005694 } while (--sc->priority >= 0);
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005695
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005696 last_pgdat = NULL;
5697 for_each_zone_zonelist_nodemask(zone, z, zonelist, sc->reclaim_idx,
5698 sc->nodemask) {
5699 if (zone->zone_pgdat == last_pgdat)
5700 continue;
5701 last_pgdat = zone->zone_pgdat;
Johannes Weiner1b051172019-11-30 17:55:52 -08005702
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005703 snapshot_refaults(sc->target_mem_cgroup, zone->zone_pgdat);
Johannes Weiner1b051172019-11-30 17:55:52 -08005704
5705 if (cgroup_reclaim(sc)) {
5706 struct lruvec *lruvec;
5707
5708 lruvec = mem_cgroup_lruvec(sc->target_mem_cgroup,
5709 zone->zone_pgdat);
5710 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
5711 }
Johannes Weiner2a2e4882017-05-03 14:55:03 -07005712 }
5713
Keika Kobayashi873b4772008-07-25 01:48:52 -07005714 delayacct_freepages_end();
5715
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005716 if (sc->nr_reclaimed)
5717 return sc->nr_reclaimed;
5718
Mel Gorman0cee34f2012-01-12 17:19:49 -08005719 /* Aborted reclaim to try compaction? don't OOM, then */
Johannes Weiner0b064962014-08-06 16:06:12 -07005720 if (sc->compaction_ready)
Mel Gorman73350842012-01-12 17:19:33 -08005721 return 1;
5722
Johannes Weinerb91ac372019-11-30 17:56:02 -08005723 /*
5724 * We make inactive:active ratio decisions based on the node's
5725 * composition of memory, but a restrictive reclaim_idx or a
5726 * memory.low cgroup setting can exempt large amounts of
5727 * memory from reclaim. Neither of which are very common, so
5728 * instead of doing costly eligibility calculations of the
5729 * entire cgroup subtree up front, we assume the estimates are
5730 * good, and retry with forcible deactivation if that fails.
5731 */
5732 if (sc->skipped_deactivate) {
5733 sc->priority = initial_priority;
5734 sc->force_deactivate = 1;
5735 sc->skipped_deactivate = 0;
5736 goto retry;
5737 }
5738
Johannes Weiner241994ed2015-02-11 15:26:06 -08005739 /* Untapped cgroup reserves? Don't OOM, retry. */
Yisheng Xied6622f62017-05-03 14:53:57 -07005740 if (sc->memcg_low_skipped) {
Johannes Weiner241994ed2015-02-11 15:26:06 -08005741 sc->priority = initial_priority;
Johannes Weinerb91ac372019-11-30 17:56:02 -08005742 sc->force_deactivate = 0;
Yisheng Xied6622f62017-05-03 14:53:57 -07005743 sc->memcg_low_reclaim = 1;
5744 sc->memcg_low_skipped = 0;
Johannes Weiner241994ed2015-02-11 15:26:06 -08005745 goto retry;
5746 }
5747
KOSAKI Motohirobb21c7c2010-06-04 14:15:05 -07005748 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07005749}
5750
Johannes Weinerc73322d2017-05-03 14:51:51 -07005751static bool allow_direct_reclaim(pg_data_t *pgdat)
Mel Gorman55150612012-07-31 16:44:35 -07005752{
5753 struct zone *zone;
5754 unsigned long pfmemalloc_reserve = 0;
5755 unsigned long free_pages = 0;
5756 int i;
5757 bool wmark_ok;
5758
Johannes Weinerc73322d2017-05-03 14:51:51 -07005759 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
5760 return true;
5761
Mel Gorman55150612012-07-31 16:44:35 -07005762 for (i = 0; i <= ZONE_NORMAL; i++) {
5763 zone = &pgdat->node_zones[i];
Johannes Weinerd450abd82017-05-03 14:51:54 -07005764 if (!managed_zone(zone))
5765 continue;
5766
5767 if (!zone_reclaimable_pages(zone))
Mel Gorman675becc2014-06-04 16:07:35 -07005768 continue;
5769
Mel Gorman55150612012-07-31 16:44:35 -07005770 pfmemalloc_reserve += min_wmark_pages(zone);
5771 free_pages += zone_page_state(zone, NR_FREE_PAGES);
5772 }
5773
Mel Gorman675becc2014-06-04 16:07:35 -07005774 /* If there are no reserves (unexpected config) then do not throttle */
5775 if (!pfmemalloc_reserve)
5776 return true;
5777
Mel Gorman55150612012-07-31 16:44:35 -07005778 wmark_ok = free_pages > pfmemalloc_reserve / 2;
5779
5780 /* kswapd must be awake if processes are being throttled */
5781 if (!wmark_ok && waitqueue_active(&pgdat->kswapd_wait)) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07005782 if (READ_ONCE(pgdat->kswapd_highest_zoneidx) > ZONE_NORMAL)
5783 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, ZONE_NORMAL);
Qian Cai5644e1fb2020-04-01 21:10:12 -07005784
Mel Gorman55150612012-07-31 16:44:35 -07005785 wake_up_interruptible(&pgdat->kswapd_wait);
5786 }
5787
5788 return wmark_ok;
5789}
5790
5791/*
5792 * Throttle direct reclaimers if backing storage is backed by the network
5793 * and the PFMEMALLOC reserve for the preferred node is getting dangerously
5794 * depleted. kswapd will continue to make progress and wake the processes
Mel Gorman50694c22012-11-26 16:29:48 -08005795 * when the low watermark is reached.
5796 *
5797 * Returns true if a fatal signal was delivered during throttling. If this
5798 * happens, the page allocator should not consider triggering the OOM killer.
Mel Gorman55150612012-07-31 16:44:35 -07005799 */
Mel Gorman50694c22012-11-26 16:29:48 -08005800static bool throttle_direct_reclaim(gfp_t gfp_mask, struct zonelist *zonelist,
Mel Gorman55150612012-07-31 16:44:35 -07005801 nodemask_t *nodemask)
5802{
Mel Gorman675becc2014-06-04 16:07:35 -07005803 struct zoneref *z;
Mel Gorman55150612012-07-31 16:44:35 -07005804 struct zone *zone;
Mel Gorman675becc2014-06-04 16:07:35 -07005805 pg_data_t *pgdat = NULL;
Mel Gorman55150612012-07-31 16:44:35 -07005806
5807 /*
5808 * Kernel threads should not be throttled as they may be indirectly
5809 * responsible for cleaning pages necessary for reclaim to make forward
5810 * progress. kjournald for example may enter direct reclaim while
5811 * committing a transaction where throttling it could forcing other
5812 * processes to block on log_wait_commit().
5813 */
5814 if (current->flags & PF_KTHREAD)
Mel Gorman50694c22012-11-26 16:29:48 -08005815 goto out;
5816
5817 /*
5818 * If a fatal signal is pending, this process should not throttle.
5819 * It should return quickly so it can exit and free its memory
5820 */
5821 if (fatal_signal_pending(current))
5822 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005823
Mel Gorman675becc2014-06-04 16:07:35 -07005824 /*
5825 * Check if the pfmemalloc reserves are ok by finding the first node
5826 * with a usable ZONE_NORMAL or lower zone. The expectation is that
5827 * GFP_KERNEL will be required for allocating network buffers when
5828 * swapping over the network so ZONE_HIGHMEM is unusable.
5829 *
5830 * Throttling is based on the first usable node and throttled processes
5831 * wait on a queue until kswapd makes progress and wakes them. There
5832 * is an affinity then between processes waking up and where reclaim
5833 * progress has been made assuming the process wakes on the same node.
5834 * More importantly, processes running on remote nodes will not compete
5835 * for remote pfmemalloc reserves and processes on different nodes
5836 * should make reasonable progress.
5837 */
5838 for_each_zone_zonelist_nodemask(zone, z, zonelist,
Michael S. Tsirkin17636fa2015-01-26 12:58:41 -08005839 gfp_zone(gfp_mask), nodemask) {
Mel Gorman675becc2014-06-04 16:07:35 -07005840 if (zone_idx(zone) > ZONE_NORMAL)
5841 continue;
5842
5843 /* Throttle based on the first usable node */
5844 pgdat = zone->zone_pgdat;
Johannes Weinerc73322d2017-05-03 14:51:51 -07005845 if (allow_direct_reclaim(pgdat))
Mel Gorman675becc2014-06-04 16:07:35 -07005846 goto out;
5847 break;
5848 }
5849
5850 /* If no zone was usable by the allocation flags then do not throttle */
5851 if (!pgdat)
Mel Gorman50694c22012-11-26 16:29:48 -08005852 goto out;
Mel Gorman55150612012-07-31 16:44:35 -07005853
Mel Gorman68243e72012-07-31 16:44:39 -07005854 /* Account for the throttling */
5855 count_vm_event(PGSCAN_DIRECT_THROTTLE);
5856
Mel Gorman55150612012-07-31 16:44:35 -07005857 /*
5858 * If the caller cannot enter the filesystem, it's possible that it
5859 * is due to the caller holding an FS lock or performing a journal
5860 * transaction in the case of a filesystem like ext[3|4]. In this case,
5861 * it is not safe to block on pfmemalloc_wait as kswapd could be
5862 * blocked waiting on the same lock. Instead, throttle for up to a
5863 * second before continuing.
5864 */
Miaohe Lin2e786d92021-09-02 14:59:50 -07005865 if (!(gfp_mask & __GFP_FS))
Mel Gorman55150612012-07-31 16:44:35 -07005866 wait_event_interruptible_timeout(pgdat->pfmemalloc_wait,
Johannes Weinerc73322d2017-05-03 14:51:51 -07005867 allow_direct_reclaim(pgdat), HZ);
Miaohe Lin2e786d92021-09-02 14:59:50 -07005868 else
5869 /* Throttle until kswapd wakes the process */
5870 wait_event_killable(zone->zone_pgdat->pfmemalloc_wait,
5871 allow_direct_reclaim(pgdat));
Mel Gorman50694c22012-11-26 16:29:48 -08005872
Mel Gorman50694c22012-11-26 16:29:48 -08005873 if (fatal_signal_pending(current))
5874 return true;
5875
5876out:
5877 return false;
Mel Gorman55150612012-07-31 16:44:35 -07005878}
5879
Mel Gormandac1d272008-04-28 02:12:12 -07005880unsigned long try_to_free_pages(struct zonelist *zonelist, int order,
KAMEZAWA Hiroyuki327c0e92009-03-31 15:23:31 -07005881 gfp_t gfp_mask, nodemask_t *nodemask)
Balbir Singh66e17072008-02-07 00:13:56 -08005882{
Mel Gorman33906bc2010-08-09 17:19:16 -07005883 unsigned long nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005884 struct scan_control sc = {
KOSAKI Motohiro22fba332009-12-14 17:59:10 -08005885 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005886 .gfp_mask = current_gfp_context(gfp_mask),
Mel Gormanb2e18752016-07-28 15:45:37 -07005887 .reclaim_idx = gfp_zone(gfp_mask),
Johannes Weineree814fe2014-08-06 16:06:19 -07005888 .order = order,
5889 .nodemask = nodemask,
5890 .priority = DEF_PRIORITY,
5891 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005892 .may_unmap = 1,
KOSAKI Motohiro2e2e4252009-04-21 12:24:57 -07005893 .may_swap = 1,
Balbir Singh66e17072008-02-07 00:13:56 -08005894 };
5895
Mel Gorman55150612012-07-31 16:44:35 -07005896 /*
Greg Thelenbb451fd2018-08-17 15:45:19 -07005897 * scan_control uses s8 fields for order, priority, and reclaim_idx.
5898 * Confirm they are large enough for max values.
5899 */
5900 BUILD_BUG_ON(MAX_ORDER > S8_MAX);
5901 BUILD_BUG_ON(DEF_PRIORITY > S8_MAX);
5902 BUILD_BUG_ON(MAX_NR_ZONES > S8_MAX);
5903
5904 /*
Mel Gorman50694c22012-11-26 16:29:48 -08005905 * Do not enter reclaim if fatal signal was delivered while throttled.
5906 * 1 is returned so that the page allocator does not OOM kill at this
5907 * point.
Mel Gorman55150612012-07-31 16:44:35 -07005908 */
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07005909 if (throttle_direct_reclaim(sc.gfp_mask, zonelist, nodemask))
Mel Gorman55150612012-07-31 16:44:35 -07005910 return 1;
5911
Andrew Morton1732d2b012019-07-16 16:26:15 -07005912 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005913 trace_mm_vmscan_direct_reclaim_begin(order, sc.gfp_mask);
Mel Gorman33906bc2010-08-09 17:19:16 -07005914
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005915 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Mel Gorman33906bc2010-08-09 17:19:16 -07005916
5917 trace_mm_vmscan_direct_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005918 set_task_reclaim_state(current, NULL);
Mel Gorman33906bc2010-08-09 17:19:16 -07005919
5920 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08005921}
5922
Andrew Mortonc255a452012-07-31 16:43:02 -07005923#ifdef CONFIG_MEMCG
Balbir Singh66e17072008-02-07 00:13:56 -08005924
Michal Hockod2e5fb92019-08-30 16:04:50 -07005925/* Only used by soft limit reclaim. Do not reuse for anything else. */
Mel Gormana9dd0a82016-07-28 15:46:02 -07005926unsigned long mem_cgroup_shrink_node(struct mem_cgroup *memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005927 gfp_t gfp_mask, bool noswap,
Mel Gormanef8f2322016-07-28 15:46:05 -07005928 pg_data_t *pgdat,
Ying Han0ae5e892011-05-26 16:25:25 -07005929 unsigned long *nr_scanned)
Balbir Singh4e416952009-09-23 15:56:39 -07005930{
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005931 struct lruvec *lruvec = mem_cgroup_lruvec(memcg, pgdat);
Balbir Singh4e416952009-09-23 15:56:39 -07005932 struct scan_control sc = {
KOSAKI Motohirob8f5c562010-08-10 18:03:02 -07005933 .nr_to_reclaim = SWAP_CLUSTER_MAX,
Johannes Weineree814fe2014-08-06 16:06:19 -07005934 .target_mem_cgroup = memcg,
Balbir Singh4e416952009-09-23 15:56:39 -07005935 .may_writepage = !laptop_mode,
5936 .may_unmap = 1,
Mel Gormanb2e18752016-07-28 15:45:37 -07005937 .reclaim_idx = MAX_NR_ZONES - 1,
Balbir Singh4e416952009-09-23 15:56:39 -07005938 .may_swap = !noswap,
Balbir Singh4e416952009-09-23 15:56:39 -07005939 };
Ying Han0ae5e892011-05-26 16:25:25 -07005940
Michal Hockod2e5fb92019-08-30 16:04:50 -07005941 WARN_ON_ONCE(!current->reclaim_state);
5942
Balbir Singh4e416952009-09-23 15:56:39 -07005943 sc.gfp_mask = (gfp_mask & GFP_RECLAIM_MASK) |
5944 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005945
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07005946 trace_mm_vmscan_memcg_softlimit_reclaim_begin(sc.order,
Yafang Shao3481c372019-05-13 17:19:14 -07005947 sc.gfp_mask);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005948
Balbir Singh4e416952009-09-23 15:56:39 -07005949 /*
5950 * NOTE: Although we can get the priority field, using it
5951 * here is not a good idea, since it limits the pages we can scan.
Mel Gormana9dd0a82016-07-28 15:46:02 -07005952 * if we don't reclaim here, the shrink_node from balance_pgdat
Balbir Singh4e416952009-09-23 15:56:39 -07005953 * will pick up pages from other mem cgroup's as well. We hack
5954 * the priority and make it zero.
5955 */
Johannes Weinerafaf07a2019-11-30 17:55:46 -08005956 shrink_lruvec(lruvec, &sc);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005957
5958 trace_mm_vmscan_memcg_softlimit_reclaim_end(sc.nr_reclaimed);
5959
Ying Han0ae5e892011-05-26 16:25:25 -07005960 *nr_scanned = sc.nr_scanned;
Yafang Shao0308f7c2019-07-16 16:26:12 -07005961
Balbir Singh4e416952009-09-23 15:56:39 -07005962 return sc.nr_reclaimed;
5963}
5964
Johannes Weiner72835c82012-01-12 17:18:32 -08005965unsigned long try_to_free_mem_cgroup_pages(struct mem_cgroup *memcg,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005966 unsigned long nr_pages,
KOSAKI Motohiroa7885eb2009-01-07 18:08:24 -08005967 gfp_t gfp_mask,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005968 bool may_swap)
Balbir Singh66e17072008-02-07 00:13:56 -08005969{
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005970 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07005971 unsigned int noreclaim_flag;
Balbir Singh66e17072008-02-07 00:13:56 -08005972 struct scan_control sc = {
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005973 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Michal Hocko7dea19f2017-05-03 14:53:15 -07005974 .gfp_mask = (current_gfp_context(gfp_mask) & GFP_RECLAIM_MASK) |
Johannes Weineree814fe2014-08-06 16:06:19 -07005975 (GFP_HIGHUSER_MOVABLE & ~GFP_RECLAIM_MASK),
Mel Gormanb2e18752016-07-28 15:45:37 -07005976 .reclaim_idx = MAX_NR_ZONES - 1,
Johannes Weineree814fe2014-08-06 16:06:19 -07005977 .target_mem_cgroup = memcg,
5978 .priority = DEF_PRIORITY,
Balbir Singh66e17072008-02-07 00:13:56 -08005979 .may_writepage = !laptop_mode,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07005980 .may_unmap = 1,
Johannes Weinerb70a2a22014-10-09 15:28:56 -07005981 .may_swap = may_swap,
Ying Hana09ed5e2011-05-24 17:12:26 -07005982 };
Shakeel Buttfa40d1e2019-11-30 17:50:16 -08005983 /*
5984 * Traverse the ZONELIST_FALLBACK zonelist of the current node to put
5985 * equal pressure on all the nodes. This is based on the assumption that
5986 * the reclaim does not bail out early.
5987 */
5988 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
Balbir Singh66e17072008-02-07 00:13:56 -08005989
Andrew Morton1732d2b012019-07-16 16:26:15 -07005990 set_task_reclaim_state(current, &sc.reclaim_state);
Yafang Shao3481c372019-05-13 17:19:14 -07005991 trace_mm_vmscan_memcg_reclaim_begin(0, sc.gfp_mask);
Vlastimil Babka499118e2017-05-08 15:59:50 -07005992 noreclaim_flag = memalloc_noreclaim_save();
Johannes Weinereb414682018-10-26 15:06:27 -07005993
Vladimir Davydov3115cd92014-04-03 14:47:22 -07005994 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Johannes Weinereb414682018-10-26 15:06:27 -07005995
Vlastimil Babka499118e2017-05-08 15:59:50 -07005996 memalloc_noreclaim_restore(noreclaim_flag);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005997 trace_mm_vmscan_memcg_reclaim_end(nr_reclaimed);
Andrew Morton1732d2b012019-07-16 16:26:15 -07005998 set_task_reclaim_state(current, NULL);
KOSAKI Motohirobdce6d92010-08-09 17:19:56 -07005999
6000 return nr_reclaimed;
Balbir Singh66e17072008-02-07 00:13:56 -08006001}
Liujie Xie1ed025b2021-06-25 22:21:35 +08006002EXPORT_SYMBOL_GPL(try_to_free_mem_cgroup_pages);
Balbir Singh66e17072008-02-07 00:13:56 -08006003#endif
6004
Mel Gorman1d82de62016-07-28 15:45:43 -07006005static void age_active_anon(struct pglist_data *pgdat,
Mel Gormanef8f2322016-07-28 15:46:05 -07006006 struct scan_control *sc)
Johannes Weinerf16015f2012-01-12 17:17:52 -08006007{
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006008 struct mem_cgroup *memcg;
Johannes Weinerb91ac372019-11-30 17:56:02 -08006009 struct lruvec *lruvec;
Johannes Weinerf16015f2012-01-12 17:17:52 -08006010
Yu Zhaoa1537a62022-01-27 20:32:37 -07006011 if (lru_gen_enabled()) {
6012 lru_gen_age_node(pgdat, sc);
6013 return;
6014 }
6015
Dave Hansen2f368a92021-09-02 14:59:23 -07006016 if (!can_age_anon_pages(pgdat, sc))
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006017 return;
6018
Johannes Weinerb91ac372019-11-30 17:56:02 -08006019 lruvec = mem_cgroup_lruvec(NULL, pgdat);
6020 if (!inactive_is_low(lruvec, LRU_INACTIVE_ANON))
6021 return;
6022
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006023 memcg = mem_cgroup_iter(NULL, NULL, NULL);
6024 do {
Johannes Weinerb91ac372019-11-30 17:56:02 -08006025 lruvec = mem_cgroup_lruvec(memcg, pgdat);
6026 shrink_active_list(SWAP_CLUSTER_MAX, lruvec,
6027 sc, LRU_ACTIVE_ANON);
Johannes Weinerb95a2f22012-01-12 17:18:06 -08006028 memcg = mem_cgroup_iter(NULL, memcg, NULL);
6029 } while (memcg);
Johannes Weinerf16015f2012-01-12 17:17:52 -08006030}
6031
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006032static bool pgdat_watermark_boosted(pg_data_t *pgdat, int highest_zoneidx)
Mel Gorman1c308442018-12-28 00:35:52 -08006033{
6034 int i;
6035 struct zone *zone;
6036
6037 /*
6038 * Check for watermark boosts top-down as the higher zones
6039 * are more likely to be boosted. Both watermarks and boosts
Randy Dunlap1eba09c2020-08-11 18:33:26 -07006040 * should not be checked at the same time as reclaim would
Mel Gorman1c308442018-12-28 00:35:52 -08006041 * start prematurely when there is no boosting and a lower
6042 * zone is balanced.
6043 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006044 for (i = highest_zoneidx; i >= 0; i--) {
Mel Gorman1c308442018-12-28 00:35:52 -08006045 zone = pgdat->node_zones + i;
6046 if (!managed_zone(zone))
6047 continue;
6048
6049 if (zone->watermark_boost)
6050 return true;
6051 }
6052
6053 return false;
6054}
6055
Mel Gormane716f2e2017-05-03 14:53:45 -07006056/*
6057 * Returns true if there is an eligible zone balanced for the request order
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006058 * and highest_zoneidx
Mel Gormane716f2e2017-05-03 14:53:45 -07006059 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006060static bool pgdat_balanced(pg_data_t *pgdat, int order, int highest_zoneidx)
Johannes Weiner60cefed2012-11-29 13:54:23 -08006061{
Mel Gormane716f2e2017-05-03 14:53:45 -07006062 int i;
6063 unsigned long mark = -1;
6064 struct zone *zone;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006065
Mel Gorman1c308442018-12-28 00:35:52 -08006066 /*
6067 * Check watermarks bottom-up as lower zones are more likely to
6068 * meet watermarks.
6069 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006070 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006071 zone = pgdat->node_zones + i;
Mel Gorman6256c6b2016-07-28 15:45:56 -07006072
Mel Gormane716f2e2017-05-03 14:53:45 -07006073 if (!managed_zone(zone))
6074 continue;
6075
6076 mark = high_wmark_pages(zone);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006077 if (zone_watermark_ok_safe(zone, order, mark, highest_zoneidx))
Mel Gormane716f2e2017-05-03 14:53:45 -07006078 return true;
6079 }
6080
6081 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006082 * If a node has no populated zone within highest_zoneidx, it does not
Mel Gormane716f2e2017-05-03 14:53:45 -07006083 * need balancing by definition. This can happen if a zone-restricted
6084 * allocation tries to wake a remote kswapd.
6085 */
6086 if (mark == -1)
6087 return true;
6088
6089 return false;
Johannes Weiner60cefed2012-11-29 13:54:23 -08006090}
6091
Mel Gorman631b6e02017-05-03 14:53:41 -07006092/* Clear pgdat state for congested, dirty or under writeback. */
6093static void clear_pgdat_congested(pg_data_t *pgdat)
6094{
Johannes Weiner1b051172019-11-30 17:55:52 -08006095 struct lruvec *lruvec = mem_cgroup_lruvec(NULL, pgdat);
6096
6097 clear_bit(LRUVEC_CONGESTED, &lruvec->flags);
Mel Gorman631b6e02017-05-03 14:53:41 -07006098 clear_bit(PGDAT_DIRTY, &pgdat->flags);
6099 clear_bit(PGDAT_WRITEBACK, &pgdat->flags);
6100}
6101
Mel Gorman1741c872011-01-13 15:46:21 -08006102/*
Mel Gorman55150612012-07-31 16:44:35 -07006103 * Prepare kswapd for sleeping. This verifies that there are no processes
6104 * waiting in throttle_direct_reclaim() and that watermarks have been met.
6105 *
6106 * Returns true if kswapd is ready to sleep
6107 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006108static bool prepare_kswapd_sleep(pg_data_t *pgdat, int order,
6109 int highest_zoneidx)
Mel Gormanf50de2d2009-12-14 17:58:53 -08006110{
Mel Gorman55150612012-07-31 16:44:35 -07006111 /*
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006112 * The throttled processes are normally woken up in balance_pgdat() as
Johannes Weinerc73322d2017-05-03 14:51:51 -07006113 * soon as allow_direct_reclaim() is true. But there is a potential
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006114 * race between when kswapd checks the watermarks and a process gets
6115 * throttled. There is also a potential race if processes get
6116 * throttled, kswapd wakes, a large process exits thereby balancing the
6117 * zones, which causes kswapd to exit balance_pgdat() before reaching
6118 * the wake up checks. If kswapd is going to sleep, no process should
6119 * be sleeping on pfmemalloc_wait, so wake them now if necessary. If
6120 * the wake up is premature, processes will wake kswapd and get
6121 * throttled again. The difference from wake ups in balance_pgdat() is
6122 * that here we are under prepare_to_wait().
Mel Gorman55150612012-07-31 16:44:35 -07006123 */
Vlastimil Babka9e5e3662015-01-08 14:32:40 -08006124 if (waitqueue_active(&pgdat->pfmemalloc_wait))
6125 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gormanf50de2d2009-12-14 17:58:53 -08006126
Johannes Weinerc73322d2017-05-03 14:51:51 -07006127 /* Hopeless node, leave it to direct reclaim */
6128 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES)
6129 return true;
6130
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006131 if (pgdat_balanced(pgdat, order, highest_zoneidx)) {
Mel Gormane716f2e2017-05-03 14:53:45 -07006132 clear_pgdat_congested(pgdat);
6133 return true;
Mel Gorman1d82de62016-07-28 15:45:43 -07006134 }
6135
Shantanu Goel333b0a42017-05-03 14:53:38 -07006136 return false;
Mel Gormanf50de2d2009-12-14 17:58:53 -08006137}
6138
Linus Torvalds1da177e2005-04-16 15:20:36 -07006139/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006140 * kswapd shrinks a node of pages that are at or below the highest usable
6141 * zone that is currently unbalanced.
Mel Gormanb8e83b92013-07-03 15:01:45 -07006142 *
6143 * Returns true if kswapd scanned at least the requested number of pages to
Mel Gorman283aba92013-07-03 15:01:51 -07006144 * reclaim or if the lack of progress was due to pages under writeback.
6145 * This is used to determine if the scanning priority needs to be raised.
Mel Gorman75485362013-07-03 15:01:42 -07006146 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006147static bool kswapd_shrink_node(pg_data_t *pgdat,
Vlastimil Babkaaccf6242016-03-17 14:18:15 -07006148 struct scan_control *sc)
Mel Gorman75485362013-07-03 15:01:42 -07006149{
Mel Gorman1d82de62016-07-28 15:45:43 -07006150 struct zone *zone;
6151 int z;
Mel Gorman75485362013-07-03 15:01:42 -07006152
Mel Gorman1d82de62016-07-28 15:45:43 -07006153 /* Reclaim a number of pages proportional to the number of zones */
6154 sc->nr_to_reclaim = 0;
Mel Gorman970a39a2016-07-28 15:46:35 -07006155 for (z = 0; z <= sc->reclaim_idx; z++) {
Mel Gorman1d82de62016-07-28 15:45:43 -07006156 zone = pgdat->node_zones + z;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006157 if (!managed_zone(zone))
Mel Gorman1d82de62016-07-28 15:45:43 -07006158 continue;
Mel Gorman7c954f62013-07-03 15:01:54 -07006159
Mel Gorman1d82de62016-07-28 15:45:43 -07006160 sc->nr_to_reclaim += max(high_wmark_pages(zone), SWAP_CLUSTER_MAX);
Mel Gorman7c954f62013-07-03 15:01:54 -07006161 }
6162
Mel Gorman1d82de62016-07-28 15:45:43 -07006163 /*
6164 * Historically care was taken to put equal pressure on all zones but
6165 * now pressure is applied based on node LRU order.
6166 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006167 shrink_node(pgdat, sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006168
6169 /*
6170 * Fragmentation may mean that the system cannot be rebalanced for
6171 * high-order allocations. If twice the allocation size has been
6172 * reclaimed then recheck watermarks only at order-0 to prevent
6173 * excessive reclaim. Assume that a process requested a high-order
6174 * can direct reclaim/compact.
6175 */
Vlastimil Babka9861a622016-10-07 16:57:53 -07006176 if (sc->order && sc->nr_reclaimed >= compact_gap(sc->order))
Mel Gorman1d82de62016-07-28 15:45:43 -07006177 sc->order = 0;
6178
Mel Gormanb8e83b92013-07-03 15:01:45 -07006179 return sc->nr_scanned >= sc->nr_to_reclaim;
Mel Gorman75485362013-07-03 15:01:42 -07006180}
6181
Mel Gormanc49c2c42021-06-28 19:42:21 -07006182/* Page allocator PCP high watermark is lowered if reclaim is active. */
6183static inline void
6184update_reclaim_active(pg_data_t *pgdat, int highest_zoneidx, bool active)
6185{
6186 int i;
6187 struct zone *zone;
6188
6189 for (i = 0; i <= highest_zoneidx; i++) {
6190 zone = pgdat->node_zones + i;
6191
6192 if (!managed_zone(zone))
6193 continue;
6194
6195 if (active)
6196 set_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6197 else
6198 clear_bit(ZONE_RECLAIM_ACTIVE, &zone->flags);
6199 }
6200}
6201
6202static inline void
6203set_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6204{
6205 update_reclaim_active(pgdat, highest_zoneidx, true);
6206}
6207
6208static inline void
6209clear_reclaim_active(pg_data_t *pgdat, int highest_zoneidx)
6210{
6211 update_reclaim_active(pgdat, highest_zoneidx, false);
6212}
6213
Mel Gorman75485362013-07-03 15:01:42 -07006214/*
Mel Gorman1d82de62016-07-28 15:45:43 -07006215 * For kswapd, balance_pgdat() will reclaim pages across a node from zones
6216 * that are eligible for use by the caller until at least one zone is
6217 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006218 *
Mel Gorman1d82de62016-07-28 15:45:43 -07006219 * Returns the order kswapd finished reclaiming at.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006220 *
6221 * kswapd scans the zones in the highmem->normal->dma direction. It skips
Mel Gorman41858962009-06-16 15:32:12 -07006222 * zones which have free_pages > high_wmark_pages(zone), but once a zone is
Wei Yang8bb4e7a2019-03-05 15:46:22 -08006223 * found to have free_pages <= high_wmark_pages(zone), any page in that zone
Mel Gorman1d82de62016-07-28 15:45:43 -07006224 * or lower is eligible for reclaim until at least one usable zone is
6225 * balanced.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006226 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006227static int balance_pgdat(pg_data_t *pgdat, int order, int highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006228{
Linus Torvalds1da177e2005-04-16 15:20:36 -07006229 int i;
Andrew Morton0608f432013-09-24 15:27:41 -07006230 unsigned long nr_soft_reclaimed;
6231 unsigned long nr_soft_scanned;
Johannes Weinereb414682018-10-26 15:06:27 -07006232 unsigned long pflags;
Mel Gorman1c308442018-12-28 00:35:52 -08006233 unsigned long nr_boost_reclaim;
6234 unsigned long zone_boosts[MAX_NR_ZONES] = { 0, };
6235 bool boosted;
Mel Gorman1d82de62016-07-28 15:45:43 -07006236 struct zone *zone;
Andrew Morton179e9632006-03-22 00:08:18 -08006237 struct scan_control sc = {
6238 .gfp_mask = GFP_KERNEL,
Johannes Weineree814fe2014-08-06 16:06:19 -07006239 .order = order,
Johannes Weinera6dc60f82009-03-31 15:19:30 -07006240 .may_unmap = 1,
Andrew Morton179e9632006-03-22 00:08:18 -08006241 };
Omar Sandoval93781322018-06-07 17:07:02 -07006242
Andrew Morton1732d2b012019-07-16 16:26:15 -07006243 set_task_reclaim_state(current, &sc.reclaim_state);
Johannes Weinereb414682018-10-26 15:06:27 -07006244 psi_memstall_enter(&pflags);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006245 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006246
Christoph Lameterf8891e52006-06-30 01:55:45 -07006247 count_vm_event(PAGEOUTRUN);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006248
Mel Gorman1c308442018-12-28 00:35:52 -08006249 /*
6250 * Account for the reclaim boost. Note that the zone boost is left in
6251 * place so that parallel allocations that are near the watermark will
6252 * stall or direct reclaim until kswapd is finished.
6253 */
6254 nr_boost_reclaim = 0;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006255 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006256 zone = pgdat->node_zones + i;
6257 if (!managed_zone(zone))
6258 continue;
6259
6260 nr_boost_reclaim += zone->watermark_boost;
6261 zone_boosts[i] = zone->watermark_boost;
6262 }
6263 boosted = nr_boost_reclaim;
6264
6265restart:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006266 set_reclaim_active(pgdat, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006267 sc.priority = DEF_PRIORITY;
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006268 do {
Johannes Weinerc73322d2017-05-03 14:51:51 -07006269 unsigned long nr_reclaimed = sc.nr_reclaimed;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006270 bool raise_priority = true;
Mel Gorman1c308442018-12-28 00:35:52 -08006271 bool balanced;
Omar Sandoval93781322018-06-07 17:07:02 -07006272 bool ret;
Mel Gormanb8e83b92013-07-03 15:01:45 -07006273
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006274 sc.reclaim_idx = highest_zoneidx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006275
Mel Gorman86c79f62016-07-28 15:45:59 -07006276 /*
Mel Gorman84c7a772016-07-28 15:46:44 -07006277 * If the number of buffer_heads exceeds the maximum allowed
6278 * then consider reclaiming from all zones. This has a dual
6279 * purpose -- on 64-bit systems it is expected that
6280 * buffer_heads are stripped during active rotation. On 32-bit
6281 * systems, highmem pages can pin lowmem memory and shrinking
6282 * buffers can relieve lowmem pressure. Reclaim may still not
6283 * go ahead if all eligible zones for the original allocation
6284 * request are balanced to avoid excessive reclaim from kswapd.
Mel Gorman86c79f62016-07-28 15:45:59 -07006285 */
6286 if (buffer_heads_over_limit) {
6287 for (i = MAX_NR_ZONES - 1; i >= 0; i--) {
6288 zone = pgdat->node_zones + i;
Mel Gorman6aa303d2016-09-01 16:14:55 -07006289 if (!managed_zone(zone))
Mel Gorman86c79f62016-07-28 15:45:59 -07006290 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006291
Mel Gorman970a39a2016-07-28 15:46:35 -07006292 sc.reclaim_idx = i;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006293 break;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006294 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07006295 }
Zlatko Calusicdafcb732013-02-22 16:32:34 -08006296
Mel Gorman86c79f62016-07-28 15:45:59 -07006297 /*
Mel Gorman1c308442018-12-28 00:35:52 -08006298 * If the pgdat is imbalanced then ignore boosting and preserve
6299 * the watermarks for a later time and restart. Note that the
6300 * zone watermarks will be still reset at the end of balancing
6301 * on the grounds that the normal reclaim should be enough to
6302 * re-evaluate if boosting is required when kswapd next wakes.
Mel Gorman86c79f62016-07-28 15:45:59 -07006303 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006304 balanced = pgdat_balanced(pgdat, sc.order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006305 if (!balanced && nr_boost_reclaim) {
6306 nr_boost_reclaim = 0;
6307 goto restart;
6308 }
6309
6310 /*
6311 * If boosting is not active then only reclaim if there are no
6312 * eligible zones. Note that sc.reclaim_idx is not used as
6313 * buffer_heads_over_limit may have adjusted it.
6314 */
6315 if (!nr_boost_reclaim && balanced)
Mel Gormane716f2e2017-05-03 14:53:45 -07006316 goto out;
Andrew Mortone1dbeda2006-12-06 20:32:01 -08006317
Mel Gorman1c308442018-12-28 00:35:52 -08006318 /* Limit the priority of boosting to avoid reclaim writeback */
6319 if (nr_boost_reclaim && sc.priority == DEF_PRIORITY - 2)
6320 raise_priority = false;
6321
6322 /*
6323 * Do not writeback or swap pages for boosted reclaim. The
6324 * intent is to relieve pressure not issue sub-optimal IO
6325 * from reclaim context. If no pages are reclaimed, the
6326 * reclaim will be aborted.
6327 */
6328 sc.may_writepage = !laptop_mode && !nr_boost_reclaim;
6329 sc.may_swap = !nr_boost_reclaim;
Mel Gorman1c308442018-12-28 00:35:52 -08006330
Linus Torvalds1da177e2005-04-16 15:20:36 -07006331 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006332 * Do some background aging of the anon list, to give
6333 * pages a chance to be referenced before reclaiming. All
6334 * pages are rotated regardless of classzone as this is
6335 * about consistent aging.
6336 */
Mel Gormanef8f2322016-07-28 15:46:05 -07006337 age_active_anon(pgdat, &sc);
Mel Gorman1d82de62016-07-28 15:45:43 -07006338
6339 /*
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006340 * If we're getting trouble reclaiming, start doing writepage
6341 * even in laptop mode.
6342 */
Johannes Weiner047d72c2017-05-03 14:51:57 -07006343 if (sc.priority < DEF_PRIORITY - 2)
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006344 sc.may_writepage = 1;
6345
Mel Gorman1d82de62016-07-28 15:45:43 -07006346 /* Call soft limit reclaim before calling shrink_node. */
6347 sc.nr_scanned = 0;
6348 nr_soft_scanned = 0;
Mel Gormanef8f2322016-07-28 15:46:05 -07006349 nr_soft_reclaimed = mem_cgroup_soft_limit_reclaim(pgdat, sc.order,
Mel Gorman1d82de62016-07-28 15:45:43 -07006350 sc.gfp_mask, &nr_soft_scanned);
6351 sc.nr_reclaimed += nr_soft_reclaimed;
6352
Mel Gormanb7ea3c42013-07-03 15:01:53 -07006353 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006354 * There should be no need to raise the scanning priority if
6355 * enough pages are already being scanned that that high
6356 * watermark would be met at 100% efficiency.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006357 */
Mel Gorman970a39a2016-07-28 15:46:35 -07006358 if (kswapd_shrink_node(pgdat, &sc))
Mel Gorman1d82de62016-07-28 15:45:43 -07006359 raise_priority = false;
Mel Gorman55150612012-07-31 16:44:35 -07006360
6361 /*
6362 * If the low watermark is met there is no need for processes
6363 * to be throttled on pfmemalloc_wait as they should not be
6364 * able to safely make forward progress. Wake them
6365 */
6366 if (waitqueue_active(&pgdat->pfmemalloc_wait) &&
Johannes Weinerc73322d2017-05-03 14:51:51 -07006367 allow_direct_reclaim(pgdat))
Vlastimil Babkacfc51152015-02-11 15:25:12 -08006368 wake_up_all(&pgdat->pfmemalloc_wait);
Mel Gorman55150612012-07-31 16:44:35 -07006369
Mel Gormanb8e83b92013-07-03 15:01:45 -07006370 /* Check if kswapd should be suspending */
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006371 __fs_reclaim_release(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006372 ret = try_to_freeze();
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006373 __fs_reclaim_acquire(_THIS_IP_);
Omar Sandoval93781322018-06-07 17:07:02 -07006374 if (ret || kthread_should_stop())
Mel Gormanb8e83b92013-07-03 15:01:45 -07006375 break;
6376
6377 /*
6378 * Raise priority if scanning rate is too low or there was no
6379 * progress in reclaiming pages
6380 */
Johannes Weinerc73322d2017-05-03 14:51:51 -07006381 nr_reclaimed = sc.nr_reclaimed - nr_reclaimed;
Mel Gorman1c308442018-12-28 00:35:52 -08006382 nr_boost_reclaim -= min(nr_boost_reclaim, nr_reclaimed);
6383
6384 /*
6385 * If reclaim made no progress for a boost, stop reclaim as
6386 * IO cannot be queued and it could be an infinite loop in
6387 * extreme circumstances.
6388 */
6389 if (nr_boost_reclaim && !nr_reclaimed)
6390 break;
6391
Johannes Weinerc73322d2017-05-03 14:51:51 -07006392 if (raise_priority || !nr_reclaimed)
Mel Gormanb8e83b92013-07-03 15:01:45 -07006393 sc.priority--;
Mel Gorman1d82de62016-07-28 15:45:43 -07006394 } while (sc.priority >= 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006395
Johannes Weinerc73322d2017-05-03 14:51:51 -07006396 if (!sc.nr_reclaimed)
6397 pgdat->kswapd_failures++;
6398
Mel Gormanb8e83b92013-07-03 15:01:45 -07006399out:
Mel Gormanc49c2c42021-06-28 19:42:21 -07006400 clear_reclaim_active(pgdat, highest_zoneidx);
6401
Mel Gorman1c308442018-12-28 00:35:52 -08006402 /* If reclaim was boosted, account for the reclaim done in this pass */
6403 if (boosted) {
6404 unsigned long flags;
6405
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006406 for (i = 0; i <= highest_zoneidx; i++) {
Mel Gorman1c308442018-12-28 00:35:52 -08006407 if (!zone_boosts[i])
6408 continue;
6409
6410 /* Increments are under the zone lock */
6411 zone = pgdat->node_zones + i;
6412 spin_lock_irqsave(&zone->lock, flags);
6413 zone->watermark_boost -= min(zone->watermark_boost, zone_boosts[i]);
6414 spin_unlock_irqrestore(&zone->lock, flags);
6415 }
6416
6417 /*
6418 * As there is now likely space, wakeup kcompact to defragment
6419 * pageblocks.
6420 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006421 wakeup_kcompactd(pgdat, pageblock_order, highest_zoneidx);
Mel Gorman1c308442018-12-28 00:35:52 -08006422 }
6423
Johannes Weiner2a2e4882017-05-03 14:55:03 -07006424 snapshot_refaults(NULL, pgdat);
Matthew Wilcox (Oracle)4f3eaf42021-09-02 14:52:58 -07006425 __fs_reclaim_release(_THIS_IP_);
Johannes Weinereb414682018-10-26 15:06:27 -07006426 psi_memstall_leave(&pflags);
Andrew Morton1732d2b012019-07-16 16:26:15 -07006427 set_task_reclaim_state(current, NULL);
Yafang Shaoe5ca8072019-07-16 16:26:09 -07006428
Mel Gorman0abdee22011-01-13 15:46:22 -08006429 /*
Mel Gorman1d82de62016-07-28 15:45:43 -07006430 * Return the order kswapd stopped reclaiming at as
6431 * prepare_kswapd_sleep() takes it into account. If another caller
6432 * entered the allocator slow path while kswapd was awake, order will
6433 * remain at the higher level.
Mel Gorman0abdee22011-01-13 15:46:22 -08006434 */
Mel Gorman1d82de62016-07-28 15:45:43 -07006435 return sc.order;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006436}
6437
Mel Gormane716f2e2017-05-03 14:53:45 -07006438/*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006439 * The pgdat->kswapd_highest_zoneidx is used to pass the highest zone index to
6440 * be reclaimed by kswapd from the waker. If the value is MAX_NR_ZONES which is
6441 * not a valid index then either kswapd runs for first time or kswapd couldn't
6442 * sleep after previous reclaim attempt (node is still unbalanced). In that
6443 * case return the zone index of the previous kswapd reclaim cycle.
Mel Gormane716f2e2017-05-03 14:53:45 -07006444 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006445static enum zone_type kswapd_highest_zoneidx(pg_data_t *pgdat,
6446 enum zone_type prev_highest_zoneidx)
Mel Gormane716f2e2017-05-03 14:53:45 -07006447{
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006448 enum zone_type curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006449
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006450 return curr_idx == MAX_NR_ZONES ? prev_highest_zoneidx : curr_idx;
Mel Gormane716f2e2017-05-03 14:53:45 -07006451}
6452
Mel Gorman38087d92016-07-28 15:45:49 -07006453static void kswapd_try_to_sleep(pg_data_t *pgdat, int alloc_order, int reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006454 unsigned int highest_zoneidx)
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006455{
6456 long remaining = 0;
6457 DEFINE_WAIT(wait);
6458
6459 if (freezing(current) || kthread_should_stop())
6460 return;
6461
6462 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6463
Shantanu Goel333b0a42017-05-03 14:53:38 -07006464 /*
6465 * Try to sleep for a short interval. Note that kcompactd will only be
6466 * woken if it is possible to sleep for a short interval. This is
6467 * deliberate on the assumption that if reclaim cannot keep an
6468 * eligible zone balanced that it's also unlikely that compaction will
6469 * succeed.
6470 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006471 if (prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006472 /*
6473 * Compaction records what page blocks it recently failed to
6474 * isolate pages from and skips them in the future scanning.
6475 * When kswapd is going to sleep, it is reasonable to assume
6476 * that pages and compaction may succeed so reset the cache.
6477 */
6478 reset_isolation_suitable(pgdat);
6479
6480 /*
6481 * We have freed the memory, now we should compact it to make
6482 * allocation of the requested order possible.
6483 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006484 wakeup_kcompactd(pgdat, alloc_order, highest_zoneidx);
Vlastimil Babkafd901c92016-04-28 16:18:49 -07006485
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006486 remaining = schedule_timeout(HZ/10);
Mel Gorman38087d92016-07-28 15:45:49 -07006487
6488 /*
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006489 * If woken prematurely then reset kswapd_highest_zoneidx and
Mel Gorman38087d92016-07-28 15:45:49 -07006490 * order. The values will either be from a wakeup request or
6491 * the previous request that slept prematurely.
6492 */
6493 if (remaining) {
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006494 WRITE_ONCE(pgdat->kswapd_highest_zoneidx,
6495 kswapd_highest_zoneidx(pgdat,
6496 highest_zoneidx));
Qian Cai5644e1fb2020-04-01 21:10:12 -07006497
6498 if (READ_ONCE(pgdat->kswapd_order) < reclaim_order)
6499 WRITE_ONCE(pgdat->kswapd_order, reclaim_order);
Mel Gorman38087d92016-07-28 15:45:49 -07006500 }
6501
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006502 finish_wait(&pgdat->kswapd_wait, &wait);
6503 prepare_to_wait(&pgdat->kswapd_wait, &wait, TASK_INTERRUPTIBLE);
6504 }
6505
6506 /*
6507 * After a short sleep, check if it was a premature sleep. If not, then
6508 * go fully to sleep until explicitly woken up.
6509 */
Mel Gormand9f21d42016-07-28 15:46:41 -07006510 if (!remaining &&
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006511 prepare_kswapd_sleep(pgdat, reclaim_order, highest_zoneidx)) {
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006512 trace_mm_vmscan_kswapd_sleep(pgdat->node_id);
6513
6514 /*
6515 * vmstat counters are not perfectly accurate and the estimated
6516 * value for counters such as NR_FREE_PAGES can deviate from the
6517 * true value by nr_online_cpus * threshold. To avoid the zone
6518 * watermarks being breached while under pressure, we reduce the
6519 * per-cpu vmstat threshold while kswapd is awake and restore
6520 * them before going back to sleep.
6521 */
6522 set_pgdat_percpu_threshold(pgdat, calculate_normal_threshold);
Aaditya Kumar1c7e7f62012-07-17 15:48:07 -07006523
6524 if (!kthread_should_stop())
6525 schedule();
6526
KOSAKI Motohirof0bc0a62011-01-13 15:45:50 -08006527 set_pgdat_percpu_threshold(pgdat, calculate_pressure_threshold);
6528 } else {
6529 if (remaining)
6530 count_vm_event(KSWAPD_LOW_WMARK_HIT_QUICKLY);
6531 else
6532 count_vm_event(KSWAPD_HIGH_WMARK_HIT_QUICKLY);
6533 }
6534 finish_wait(&pgdat->kswapd_wait, &wait);
6535}
6536
Linus Torvalds1da177e2005-04-16 15:20:36 -07006537/*
6538 * The background pageout daemon, started as a kernel thread
Rik van Riel4f98a2f2008-10-18 20:26:32 -07006539 * from the init process.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006540 *
6541 * This basically trickles out pages so that we have _some_
6542 * free memory available even if there is no other activity
6543 * that frees anything up. This is needed for things like routing
6544 * etc, where we otherwise might have all activity going on in
6545 * asynchronous contexts that cannot page things out.
6546 *
6547 * If there are applications that are active memory-allocators
6548 * (most normal use), this basically shouldn't matter.
6549 */
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306550int kswapd(void *p)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006551{
Mel Gormane716f2e2017-05-03 14:53:45 -07006552 unsigned int alloc_order, reclaim_order;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006553 unsigned int highest_zoneidx = MAX_NR_ZONES - 1;
Zhiyuan Dai68d68ff2021-05-04 18:40:12 -07006554 pg_data_t *pgdat = (pg_data_t *)p;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006555 struct task_struct *tsk = current;
Rusty Russella70f7302009-03-13 14:49:46 +10306556 const struct cpumask *cpumask = cpumask_of_node(pgdat->node_id);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006557
Rusty Russell174596a2009-01-01 10:12:29 +10306558 if (!cpumask_empty(cpumask))
Mike Travisc5f59f02008-04-04 18:11:10 -07006559 set_cpus_allowed_ptr(tsk, cpumask);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006560
6561 /*
6562 * Tell the memory management that we're a "memory allocator",
6563 * and that if we need more memory we should get access to it
6564 * regardless (see "__alloc_pages()"). "kswapd" should
6565 * never get caught in the normal page freeing logic.
6566 *
6567 * (Kswapd normally doesn't need memory anyway, but sometimes
6568 * you need a small amount of memory in order to be able to
6569 * page out something else, and this flag essentially protects
6570 * us from recursively trying to free more memory as we're
6571 * trying to free the first piece of memory in the first place).
6572 */
Christoph Lameter930d9152006-01-08 01:00:47 -08006573 tsk->flags |= PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD;
Rafael J. Wysocki83144182007-07-17 04:03:35 -07006574 set_freezable();
Linus Torvalds1da177e2005-04-16 15:20:36 -07006575
Qian Cai5644e1fb2020-04-01 21:10:12 -07006576 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006577 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006578 for ( ; ; ) {
Jeff Liu6f6313d2012-12-11 16:02:48 -08006579 bool ret;
Christoph Lameter3e1d1d22005-06-24 23:13:50 -07006580
Qian Cai5644e1fb2020-04-01 21:10:12 -07006581 alloc_order = reclaim_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006582 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6583 highest_zoneidx);
Mel Gormane716f2e2017-05-03 14:53:45 -07006584
Mel Gorman38087d92016-07-28 15:45:49 -07006585kswapd_try_sleep:
6586 kswapd_try_to_sleep(pgdat, alloc_order, reclaim_order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006587 highest_zoneidx);
Mel Gorman215ddd62011-07-08 15:39:40 -07006588
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006589 /* Read the new order and highest_zoneidx */
Lukas Bulwahn2b47a242020-12-14 19:12:18 -08006590 alloc_order = READ_ONCE(pgdat->kswapd_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006591 highest_zoneidx = kswapd_highest_zoneidx(pgdat,
6592 highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006593 WRITE_ONCE(pgdat->kswapd_order, 0);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006594 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, MAX_NR_ZONES);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006595
David Rientjes8fe23e02009-12-14 17:58:33 -08006596 ret = try_to_freeze();
6597 if (kthread_should_stop())
6598 break;
6599
6600 /*
6601 * We can speed up thawing tasks if we don't call balance_pgdat
6602 * after returning from the refrigerator
6603 */
Mel Gorman38087d92016-07-28 15:45:49 -07006604 if (ret)
6605 continue;
Mel Gorman1d82de62016-07-28 15:45:43 -07006606
Mel Gorman38087d92016-07-28 15:45:49 -07006607 /*
6608 * Reclaim begins at the requested order but if a high-order
6609 * reclaim fails then kswapd falls back to reclaiming for
6610 * order-0. If that happens, kswapd will consider sleeping
6611 * for the order it finished reclaiming at (reclaim_order)
6612 * but kcompactd is woken to compact for the original
6613 * request (alloc_order).
6614 */
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006615 trace_mm_vmscan_kswapd_wake(pgdat->node_id, highest_zoneidx,
Mel Gormane5146b12016-07-28 15:46:47 -07006616 alloc_order);
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006617 reclaim_order = balance_pgdat(pgdat, alloc_order,
6618 highest_zoneidx);
Mel Gorman38087d92016-07-28 15:45:49 -07006619 if (reclaim_order < alloc_order)
6620 goto kswapd_try_sleep;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006621 }
Takamori Yamaguchib0a8cc52012-11-08 15:53:39 -08006622
Johannes Weiner71abdc12014-06-06 14:35:35 -07006623 tsk->flags &= ~(PF_MEMALLOC | PF_SWAPWRITE | PF_KSWAPD);
Johannes Weiner71abdc12014-06-06 14:35:35 -07006624
Linus Torvalds1da177e2005-04-16 15:20:36 -07006625 return 0;
6626}
Vijayanand Jitta12972dd2022-03-23 12:37:28 +05306627EXPORT_SYMBOL_GPL(kswapd);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006628
6629/*
David Rientjes5ecd9d42018-04-05 16:25:16 -07006630 * A zone is low on free memory or too fragmented for high-order memory. If
6631 * kswapd should reclaim (direct reclaim is deferred), wake it up for the zone's
6632 * pgdat. It will wake up kcompactd after reclaiming memory. If kswapd reclaim
6633 * has failed or is not needed, still wake up kcompactd if only compaction is
6634 * needed.
Linus Torvalds1da177e2005-04-16 15:20:36 -07006635 */
David Rientjes5ecd9d42018-04-05 16:25:16 -07006636void wakeup_kswapd(struct zone *zone, gfp_t gfp_flags, int order,
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006637 enum zone_type highest_zoneidx)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006638{
6639 pg_data_t *pgdat;
Qian Cai5644e1fb2020-04-01 21:10:12 -07006640 enum zone_type curr_idx;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006641
Mel Gorman6aa303d2016-09-01 16:14:55 -07006642 if (!managed_zone(zone))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006643 return;
6644
David Rientjes5ecd9d42018-04-05 16:25:16 -07006645 if (!cpuset_zone_allowed(zone, gfp_flags))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006646 return;
Shakeel Buttdffcac2c2019-07-04 15:14:42 -07006647
Qian Cai5644e1fb2020-04-01 21:10:12 -07006648 pgdat = zone->zone_pgdat;
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006649 curr_idx = READ_ONCE(pgdat->kswapd_highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006650
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006651 if (curr_idx == MAX_NR_ZONES || curr_idx < highest_zoneidx)
6652 WRITE_ONCE(pgdat->kswapd_highest_zoneidx, highest_zoneidx);
Qian Cai5644e1fb2020-04-01 21:10:12 -07006653
6654 if (READ_ONCE(pgdat->kswapd_order) < order)
6655 WRITE_ONCE(pgdat->kswapd_order, order);
6656
Con Kolivas8d0986e2005-09-13 01:25:07 -07006657 if (!waitqueue_active(&pgdat->kswapd_wait))
Linus Torvalds1da177e2005-04-16 15:20:36 -07006658 return;
Mel Gormane1a55632016-07-28 15:46:26 -07006659
David Rientjes5ecd9d42018-04-05 16:25:16 -07006660 /* Hopeless node, leave it to direct reclaim if possible */
6661 if (pgdat->kswapd_failures >= MAX_RECLAIM_RETRIES ||
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006662 (pgdat_balanced(pgdat, order, highest_zoneidx) &&
6663 !pgdat_watermark_boosted(pgdat, highest_zoneidx))) {
David Rientjes5ecd9d42018-04-05 16:25:16 -07006664 /*
6665 * There may be plenty of free memory available, but it's too
6666 * fragmented for high-order allocations. Wake up kcompactd
6667 * and rely on compaction_suitable() to determine if it's
6668 * needed. If it fails, it will defer subsequent attempts to
6669 * ratelimit its work.
6670 */
6671 if (!(gfp_flags & __GFP_DIRECT_RECLAIM))
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006672 wakeup_kcompactd(pgdat, order, highest_zoneidx);
Johannes Weinerc73322d2017-05-03 14:51:51 -07006673 return;
David Rientjes5ecd9d42018-04-05 16:25:16 -07006674 }
Johannes Weinerc73322d2017-05-03 14:51:51 -07006675
Joonsoo Kim97a225e2020-06-03 15:59:01 -07006676 trace_mm_vmscan_wakeup_kswapd(pgdat->node_id, highest_zoneidx, order,
David Rientjes5ecd9d42018-04-05 16:25:16 -07006677 gfp_flags);
Con Kolivas8d0986e2005-09-13 01:25:07 -07006678 wake_up_interruptible(&pgdat->kswapd_wait);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006679}
6680
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006681#ifdef CONFIG_HIBERNATION
Linus Torvalds1da177e2005-04-16 15:20:36 -07006682/*
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006683 * Try to free `nr_to_reclaim' of memory, system-wide, and return the number of
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006684 * freed pages.
6685 *
6686 * Rather than trying to age LRUs the aim is to preserve the overall
6687 * LRU order by reclaiming preferentially
6688 * inactive > active > active referenced > active mapped
Linus Torvalds1da177e2005-04-16 15:20:36 -07006689 */
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006690unsigned long shrink_all_memory(unsigned long nr_to_reclaim)
Linus Torvalds1da177e2005-04-16 15:20:36 -07006691{
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006692 struct scan_control sc = {
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006693 .nr_to_reclaim = nr_to_reclaim,
Johannes Weineree814fe2014-08-06 16:06:19 -07006694 .gfp_mask = GFP_HIGHUSER_MOVABLE,
Mel Gormanb2e18752016-07-28 15:45:37 -07006695 .reclaim_idx = MAX_NR_ZONES - 1,
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006696 .priority = DEF_PRIORITY,
Johannes Weineree814fe2014-08-06 16:06:19 -07006697 .may_writepage = 1,
6698 .may_unmap = 1,
6699 .may_swap = 1,
6700 .hibernation_mode = 1,
Linus Torvalds1da177e2005-04-16 15:20:36 -07006701 };
Ying Hana09ed5e2011-05-24 17:12:26 -07006702 struct zonelist *zonelist = node_zonelist(numa_node_id(), sc.gfp_mask);
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006703 unsigned long nr_reclaimed;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006704 unsigned int noreclaim_flag;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006705
Peter Zijlstrad92a8cf2017-03-03 10:13:38 +01006706 fs_reclaim_acquire(sc.gfp_mask);
Omar Sandoval93781322018-06-07 17:07:02 -07006707 noreclaim_flag = memalloc_noreclaim_save();
Andrew Morton1732d2b012019-07-16 16:26:15 -07006708 set_task_reclaim_state(current, &sc.reclaim_state);
Andrew Morton69e05942006-03-22 00:08:19 -08006709
Vladimir Davydov3115cd92014-04-03 14:47:22 -07006710 nr_reclaimed = do_try_to_free_pages(zonelist, &sc);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006711
Andrew Morton1732d2b012019-07-16 16:26:15 -07006712 set_task_reclaim_state(current, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006713 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006714 fs_reclaim_release(sc.gfp_mask);
Rafael J. Wysockid6277db2006-06-23 02:03:18 -07006715
KOSAKI Motohiro7b517552009-12-14 17:59:12 -08006716 return nr_reclaimed;
Linus Torvalds1da177e2005-04-16 15:20:36 -07006717}
Rafael J. Wysockic6f37f12009-05-24 22:16:31 +02006718#endif /* CONFIG_HIBERNATION */
Linus Torvalds1da177e2005-04-16 15:20:36 -07006719
Yasunori Goto3218ae12006-06-27 02:53:33 -07006720/*
6721 * This kswapd start function will be called by init and node-hot-add.
6722 * On node-hot-add, kswapd will moved to proper cpus if cpus are hot-added.
6723 */
Miaohe Linb87c517a2021-09-02 14:59:46 -07006724void kswapd_run(int nid)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006725{
6726 pg_data_t *pgdat = NODE_DATA(nid);
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306727 bool skip = false;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006728
6729 if (pgdat->kswapd)
Miaohe Linb87c517a2021-09-02 14:59:46 -07006730 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006731
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306732 trace_android_vh_kswapd_per_node(nid, &skip, true);
6733 if (skip)
6734 return;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006735 pgdat->kswapd = kthread_run(kswapd, pgdat, "kswapd%d", nid);
6736 if (IS_ERR(pgdat->kswapd)) {
6737 /* failure at boot is fatal */
Thomas Gleixnerc6202ad2017-05-16 20:42:46 +02006738 BUG_ON(system_state < SYSTEM_RUNNING);
Gavin Shand5dc0ad2012-10-08 16:29:27 -07006739 pr_err("Failed to start kswapd on node %d\n", nid);
Xishi Qiud72515b2013-04-17 15:58:34 -07006740 pgdat->kswapd = NULL;
Yasunori Goto3218ae12006-06-27 02:53:33 -07006741 }
Yasunori Goto3218ae12006-06-27 02:53:33 -07006742}
6743
David Rientjes8fe23e02009-12-14 17:58:33 -08006744/*
Jiang Liud8adde12012-07-11 14:01:52 -07006745 * Called by memory hotplug when all memory in a node is offlined. Caller must
Vladimir Davydovbfc8c902014-06-04 16:07:18 -07006746 * hold mem_hotplug_begin/end().
David Rientjes8fe23e02009-12-14 17:58:33 -08006747 */
6748void kswapd_stop(int nid)
6749{
6750 struct task_struct *kswapd = NODE_DATA(nid)->kswapd;
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306751 bool skip = false;
David Rientjes8fe23e02009-12-14 17:58:33 -08006752
Charan Teja Reddyd831f072021-02-05 17:47:57 +05306753 trace_android_vh_kswapd_per_node(nid, &skip, false);
6754 if (skip)
6755 return;
Jiang Liud8adde12012-07-11 14:01:52 -07006756 if (kswapd) {
David Rientjes8fe23e02009-12-14 17:58:33 -08006757 kthread_stop(kswapd);
Jiang Liud8adde12012-07-11 14:01:52 -07006758 NODE_DATA(nid)->kswapd = NULL;
6759 }
David Rientjes8fe23e02009-12-14 17:58:33 -08006760}
6761
Linus Torvalds1da177e2005-04-16 15:20:36 -07006762static int __init kswapd_init(void)
6763{
Wei Yang6b700b52020-04-01 21:10:09 -07006764 int nid;
Andrew Morton69e05942006-03-22 00:08:19 -08006765
Linus Torvalds1da177e2005-04-16 15:20:36 -07006766 swap_setup();
Lai Jiangshan48fb2e22012-12-12 13:51:43 -08006767 for_each_node_state(nid, N_MEMORY)
Yasunori Goto3218ae12006-06-27 02:53:33 -07006768 kswapd_run(nid);
Linus Torvalds1da177e2005-04-16 15:20:36 -07006769 return 0;
6770}
6771
6772module_init(kswapd_init)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006773
6774#ifdef CONFIG_NUMA
6775/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006776 * Node reclaim mode
Christoph Lameter9eeff232006-01-18 17:42:31 -08006777 *
Mel Gormana5f5f912016-07-28 15:46:32 -07006778 * If non-zero call node_reclaim when the number of free pages falls below
Christoph Lameter9eeff232006-01-18 17:42:31 -08006779 * the watermarks.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006780 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006781int node_reclaim_mode __read_mostly;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006782
Dave Hansen51998362021-02-24 12:09:15 -08006783/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006784 * Priority for NODE_RECLAIM. This determines the fraction of pages
Christoph Lametera92f7122006-02-01 03:05:32 -08006785 * of a node considered for each zone_reclaim. 4 scans 1/16th of
6786 * a zone.
6787 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006788#define NODE_RECLAIM_PRIORITY 4
Christoph Lametera92f7122006-02-01 03:05:32 -08006789
Christoph Lameter9eeff232006-01-18 17:42:31 -08006790/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006791 * Percentage of pages in a zone that must be unmapped for node_reclaim to
Christoph Lameter96146342006-07-03 00:24:13 -07006792 * occur.
6793 */
6794int sysctl_min_unmapped_ratio = 1;
6795
6796/*
Christoph Lameter0ff38492006-09-25 23:31:52 -07006797 * If the number of slab pages in a zone grows beyond this percentage then
6798 * slab reclaim needs to occur.
6799 */
6800int sysctl_min_slab_ratio = 5;
6801
Mel Gorman11fb9982016-07-28 15:46:20 -07006802static inline unsigned long node_unmapped_file_pages(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006803{
Mel Gorman11fb9982016-07-28 15:46:20 -07006804 unsigned long file_mapped = node_page_state(pgdat, NR_FILE_MAPPED);
6805 unsigned long file_lru = node_page_state(pgdat, NR_INACTIVE_FILE) +
6806 node_page_state(pgdat, NR_ACTIVE_FILE);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006807
6808 /*
6809 * It's possible for there to be more file mapped pages than
6810 * accounted for by the pages on the file LRU lists because
6811 * tmpfs pages accounted for as ANON can also be FILE_MAPPED
6812 */
6813 return (file_lru > file_mapped) ? (file_lru - file_mapped) : 0;
6814}
6815
6816/* Work out how many page cache pages we can reclaim in this reclaim_mode */
Mel Gormana5f5f912016-07-28 15:46:32 -07006817static unsigned long node_pagecache_reclaimable(struct pglist_data *pgdat)
Mel Gorman90afa5d2009-06-16 15:33:20 -07006818{
Alexandru Moised031a152015-11-05 18:48:08 -08006819 unsigned long nr_pagecache_reclaimable;
6820 unsigned long delta = 0;
Mel Gorman90afa5d2009-06-16 15:33:20 -07006821
6822 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006823 * If RECLAIM_UNMAP is set, then all file pages are considered
Mel Gorman90afa5d2009-06-16 15:33:20 -07006824 * potentially reclaimable. Otherwise, we have to worry about
Mel Gorman11fb9982016-07-28 15:46:20 -07006825 * pages like swapcache and node_unmapped_file_pages() provides
Mel Gorman90afa5d2009-06-16 15:33:20 -07006826 * a better estimate
6827 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006828 if (node_reclaim_mode & RECLAIM_UNMAP)
6829 nr_pagecache_reclaimable = node_page_state(pgdat, NR_FILE_PAGES);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006830 else
Mel Gormana5f5f912016-07-28 15:46:32 -07006831 nr_pagecache_reclaimable = node_unmapped_file_pages(pgdat);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006832
6833 /* If we can't clean pages, remove dirty pages from consideration */
Mel Gormana5f5f912016-07-28 15:46:32 -07006834 if (!(node_reclaim_mode & RECLAIM_WRITE))
6835 delta += node_page_state(pgdat, NR_FILE_DIRTY);
Mel Gorman90afa5d2009-06-16 15:33:20 -07006836
6837 /* Watch for any possible underflows due to delta */
6838 if (unlikely(delta > nr_pagecache_reclaimable))
6839 delta = nr_pagecache_reclaimable;
6840
6841 return nr_pagecache_reclaimable - delta;
6842}
6843
Christoph Lameter0ff38492006-09-25 23:31:52 -07006844/*
Mel Gormana5f5f912016-07-28 15:46:32 -07006845 * Try to free up some pages from this node through reclaim.
Christoph Lameter9eeff232006-01-18 17:42:31 -08006846 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006847static int __node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Christoph Lameter9eeff232006-01-18 17:42:31 -08006848{
Christoph Lameter7fb2d462006-03-22 00:08:22 -08006849 /* Minimum pages needed in order to stay on node */
Andrew Morton69e05942006-03-22 00:08:19 -08006850 const unsigned long nr_pages = 1 << order;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006851 struct task_struct *p = current;
Vlastimil Babka499118e2017-05-08 15:59:50 -07006852 unsigned int noreclaim_flag;
Andrew Morton179e9632006-03-22 00:08:18 -08006853 struct scan_control sc = {
Andrew Morton62b726c2013-02-22 16:32:24 -08006854 .nr_to_reclaim = max(nr_pages, SWAP_CLUSTER_MAX),
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006855 .gfp_mask = current_gfp_context(gfp_mask),
Johannes Weinerbd2f6192009-03-31 15:19:38 -07006856 .order = order,
Mel Gormana5f5f912016-07-28 15:46:32 -07006857 .priority = NODE_RECLAIM_PRIORITY,
6858 .may_writepage = !!(node_reclaim_mode & RECLAIM_WRITE),
6859 .may_unmap = !!(node_reclaim_mode & RECLAIM_UNMAP),
Johannes Weineree814fe2014-08-06 16:06:19 -07006860 .may_swap = 1,
Nick Desaulniersf2f43e52017-07-06 15:36:50 -07006861 .reclaim_idx = gfp_zone(gfp_mask),
Andrew Morton179e9632006-03-22 00:08:18 -08006862 };
Johannes Weiner57f29762021-08-19 19:04:27 -07006863 unsigned long pflags;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006864
Yafang Shao132bb8c2019-05-13 17:17:53 -07006865 trace_mm_vmscan_node_reclaim_begin(pgdat->node_id, order,
6866 sc.gfp_mask);
6867
Christoph Lameter9eeff232006-01-18 17:42:31 -08006868 cond_resched();
Johannes Weiner57f29762021-08-19 19:04:27 -07006869 psi_memstall_enter(&pflags);
Omar Sandoval93781322018-06-07 17:07:02 -07006870 fs_reclaim_acquire(sc.gfp_mask);
Christoph Lameterd4f77962006-02-24 13:04:22 -08006871 /*
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006872 * We need to be able to allocate from the reserves for RECLAIM_UNMAP
Christoph Lameterd4f77962006-02-24 13:04:22 -08006873 * and we also need to be able to write out pages for RECLAIM_WRITE
Zhihui Zhang95bbc0c2015-06-24 16:56:42 -07006874 * and RECLAIM_UNMAP.
Christoph Lameterd4f77962006-02-24 13:04:22 -08006875 */
Vlastimil Babka499118e2017-05-08 15:59:50 -07006876 noreclaim_flag = memalloc_noreclaim_save();
6877 p->flags |= PF_SWAPWRITE;
Andrew Morton1732d2b012019-07-16 16:26:15 -07006878 set_task_reclaim_state(p, &sc.reclaim_state);
Christoph Lameterc84db232006-02-01 03:05:29 -08006879
Mel Gormana5f5f912016-07-28 15:46:32 -07006880 if (node_pagecache_reclaimable(pgdat) > pgdat->min_unmapped_pages) {
Christoph Lameter0ff38492006-09-25 23:31:52 -07006881 /*
Andrey Ryabinin894befe2018-04-10 16:27:51 -07006882 * Free memory by calling shrink node with increasing
Christoph Lameter0ff38492006-09-25 23:31:52 -07006883 * priorities until we have enough memory freed.
6884 */
Christoph Lameter0ff38492006-09-25 23:31:52 -07006885 do {
Mel Gorman970a39a2016-07-28 15:46:35 -07006886 shrink_node(pgdat, &sc);
Konstantin Khlebnikov9e3b2f82012-05-29 15:06:57 -07006887 } while (sc.nr_reclaimed < nr_pages && --sc.priority >= 0);
Christoph Lameter0ff38492006-09-25 23:31:52 -07006888 }
Christoph Lameterc84db232006-02-01 03:05:29 -08006889
Andrew Morton1732d2b012019-07-16 16:26:15 -07006890 set_task_reclaim_state(p, NULL);
Vlastimil Babka499118e2017-05-08 15:59:50 -07006891 current->flags &= ~PF_SWAPWRITE;
6892 memalloc_noreclaim_restore(noreclaim_flag);
Omar Sandoval93781322018-06-07 17:07:02 -07006893 fs_reclaim_release(sc.gfp_mask);
Johannes Weiner57f29762021-08-19 19:04:27 -07006894 psi_memstall_leave(&pflags);
Yafang Shao132bb8c2019-05-13 17:17:53 -07006895
6896 trace_mm_vmscan_node_reclaim_end(sc.nr_reclaimed);
6897
Rik van Riela79311c2009-01-06 14:40:01 -08006898 return sc.nr_reclaimed >= nr_pages;
Christoph Lameter9eeff232006-01-18 17:42:31 -08006899}
Andrew Morton179e9632006-03-22 00:08:18 -08006900
Mel Gormana5f5f912016-07-28 15:46:32 -07006901int node_reclaim(struct pglist_data *pgdat, gfp_t gfp_mask, unsigned int order)
Andrew Morton179e9632006-03-22 00:08:18 -08006902{
David Rientjesd773ed62007-10-16 23:26:01 -07006903 int ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006904
6905 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006906 * Node reclaim reclaims unmapped file backed pages and
Christoph Lameter0ff38492006-09-25 23:31:52 -07006907 * slab pages if we are over the defined limits.
Christoph Lameter34aa1332006-06-30 01:55:37 -07006908 *
Christoph Lameter96146342006-07-03 00:24:13 -07006909 * A small portion of unmapped file backed pages is needed for
6910 * file I/O otherwise pages read by file I/O will be immediately
Mel Gormana5f5f912016-07-28 15:46:32 -07006911 * thrown out if the node is overallocated. So we do not reclaim
6912 * if less than a specified percentage of the node is used by
Christoph Lameter96146342006-07-03 00:24:13 -07006913 * unmapped file backed pages.
Andrew Morton179e9632006-03-22 00:08:18 -08006914 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006915 if (node_pagecache_reclaimable(pgdat) <= pgdat->min_unmapped_pages &&
Roman Gushchind42f3242020-08-06 23:20:39 -07006916 node_page_state_pages(pgdat, NR_SLAB_RECLAIMABLE_B) <=
6917 pgdat->min_slab_pages)
Mel Gormana5f5f912016-07-28 15:46:32 -07006918 return NODE_RECLAIM_FULL;
Andrew Morton179e9632006-03-22 00:08:18 -08006919
6920 /*
David Rientjesd773ed62007-10-16 23:26:01 -07006921 * Do not scan if the allocation should not be delayed.
Andrew Morton179e9632006-03-22 00:08:18 -08006922 */
Mel Gormand0164ad2015-11-06 16:28:21 -08006923 if (!gfpflags_allow_blocking(gfp_mask) || (current->flags & PF_MEMALLOC))
Mel Gormana5f5f912016-07-28 15:46:32 -07006924 return NODE_RECLAIM_NOSCAN;
Andrew Morton179e9632006-03-22 00:08:18 -08006925
6926 /*
Mel Gormana5f5f912016-07-28 15:46:32 -07006927 * Only run node reclaim on the local node or on nodes that do not
Andrew Morton179e9632006-03-22 00:08:18 -08006928 * have associated processors. This will favor the local processor
6929 * over remote processors and spread off node memory allocations
6930 * as wide as possible.
6931 */
Mel Gormana5f5f912016-07-28 15:46:32 -07006932 if (node_state(pgdat->node_id, N_CPU) && pgdat->node_id != numa_node_id())
6933 return NODE_RECLAIM_NOSCAN;
David Rientjesd773ed62007-10-16 23:26:01 -07006934
Mel Gormana5f5f912016-07-28 15:46:32 -07006935 if (test_and_set_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags))
6936 return NODE_RECLAIM_NOSCAN;
Mel Gormanfa5e0842009-06-16 15:33:22 -07006937
Mel Gormana5f5f912016-07-28 15:46:32 -07006938 ret = __node_reclaim(pgdat, gfp_mask, order);
6939 clear_bit(PGDAT_RECLAIM_LOCKED, &pgdat->flags);
David Rientjesd773ed62007-10-16 23:26:01 -07006940
Mel Gorman24cf725182009-06-16 15:33:23 -07006941 if (!ret)
6942 count_vm_event(PGSCAN_ZONE_RECLAIM_FAILED);
6943
David Rientjesd773ed62007-10-16 23:26:01 -07006944 return ret;
Andrew Morton179e9632006-03-22 00:08:18 -08006945}
Christoph Lameter9eeff232006-01-18 17:42:31 -08006946#endif
Lee Schermerhorn894bc312008-10-18 20:26:39 -07006947
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006948/**
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006949 * check_move_unevictable_pages - check pages for evictability and move to
6950 * appropriate zone lru list
6951 * @pvec: pagevec with lru pages to check
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006952 *
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006953 * Checks pages for evictability, if an evictable page is in the unevictable
6954 * lru list, moves it to the appropriate evictable lru list. This function
6955 * should be only used for lru pages.
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006956 */
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006957void check_move_unevictable_pages(struct pagevec *pvec)
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006958{
Alex Shi6168d0d2020-12-15 12:34:29 -08006959 struct lruvec *lruvec = NULL;
Hugh Dickins24513262012-01-20 14:34:21 -08006960 int pgscanned = 0;
6961 int pgrescued = 0;
6962 int i;
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006963
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006964 for (i = 0; i < pvec->nr; i++) {
6965 struct page *page = pvec->pages[i];
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006966 int nr_pages;
Lee Schermerhornaf936a12008-10-18 20:26:53 -07006967
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006968 if (PageTransTail(page))
6969 continue;
6970
6971 nr_pages = thp_nr_pages(page);
6972 pgscanned += nr_pages;
6973
Alex Shid25b5bd2020-12-15 12:34:16 -08006974 /* block memcg migration during page moving between lru */
6975 if (!TestClearPageLRU(page))
6976 continue;
6977
Alexander Duyck2a5e4e32020-12-15 12:34:33 -08006978 lruvec = relock_page_lruvec_irq(page, lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08006979 if (page_evictable(page) && PageUnevictable(page)) {
Yu Zhao46ae6b22021-02-24 12:08:25 -08006980 del_page_from_lru_list(page, lruvec);
Hugh Dickins24513262012-01-20 14:34:21 -08006981 ClearPageUnevictable(page);
Yu Zhao3a9c9782021-02-24 12:08:17 -08006982 add_page_to_lru_list(page, lruvec);
Hugh Dickins8d8869c2020-09-18 21:20:12 -07006983 pgrescued += nr_pages;
Hugh Dickins24513262012-01-20 14:34:21 -08006984 }
Alex Shid25b5bd2020-12-15 12:34:16 -08006985 SetPageLRU(page);
Lee Schermerhorn89e004ea2008-10-18 20:26:43 -07006986 }
Hugh Dickins24513262012-01-20 14:34:21 -08006987
Alex Shi6168d0d2020-12-15 12:34:29 -08006988 if (lruvec) {
Hugh Dickins24513262012-01-20 14:34:21 -08006989 __count_vm_events(UNEVICTABLE_PGRESCUED, pgrescued);
6990 __count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Alex Shi6168d0d2020-12-15 12:34:29 -08006991 unlock_page_lruvec_irq(lruvec);
Alex Shid25b5bd2020-12-15 12:34:16 -08006992 } else if (pgscanned) {
6993 count_vm_events(UNEVICTABLE_PGSCANNED, pgscanned);
Hugh Dickins24513262012-01-20 14:34:21 -08006994 }
Hugh Dickins850465792012-01-20 14:34:19 -08006995}
Kuo-Hsin Yang64e3d122018-11-06 13:23:24 +00006996EXPORT_SYMBOL_GPL(check_move_unevictable_pages);