mm/migrate: add sysfs interface to enable reclaim migration
[linux-block.git] / mm / vmpressure.c
CommitLineData
d2912cb1 1// SPDX-License-Identifier: GPL-2.0-only
70ddf637
AV
2/*
3 * Linux VM pressure
4 *
5 * Copyright 2012 Linaro Ltd.
6 * Anton Vorontsov <anton.vorontsov@linaro.org>
7 *
8 * Based on ideas from Andrew Morton, David Rientjes, KOSAKI Motohiro,
9 * Leonid Moiseichuk, Mel Gorman, Minchan Kim and Pekka Enberg.
70ddf637
AV
10 */
11
12#include <linux/cgroup.h>
13#include <linux/fs.h>
14#include <linux/log2.h>
15#include <linux/sched.h>
16#include <linux/mm.h>
17#include <linux/vmstat.h>
18#include <linux/eventfd.h>
1ff6bbfd 19#include <linux/slab.h>
70ddf637
AV
20#include <linux/swap.h>
21#include <linux/printk.h>
22#include <linux/vmpressure.h>
23
24/*
25 * The window size (vmpressure_win) is the number of scanned pages before
26 * we try to analyze scanned/reclaimed ratio. So the window is used as a
27 * rate-limit tunable for the "low" level notification, and also for
28 * averaging the ratio for medium/critical levels. Using small window
29 * sizes can cause lot of false positives, but too big window size will
30 * delay the notifications.
31 *
32 * As the vmscan reclaimer logic works with chunks which are multiple of
33 * SWAP_CLUSTER_MAX, it makes sense to use it for the window size as well.
34 *
35 * TODO: Make the window size depend on machine size, as we do for vmstat
36 * thresholds. Currently we set it to 512 pages (2MB for 4KB pages).
37 */
38static const unsigned long vmpressure_win = SWAP_CLUSTER_MAX * 16;
39
40/*
41 * These thresholds are used when we account memory pressure through
42 * scanned/reclaimed ratio. The current values were chosen empirically. In
43 * essence, they are percents: the higher the value, the more number
44 * unsuccessful reclaims there were.
45 */
46static const unsigned int vmpressure_level_med = 60;
47static const unsigned int vmpressure_level_critical = 95;
48
49/*
50 * When there are too little pages left to scan, vmpressure() may miss the
51 * critical pressure as number of pages will be less than "window size".
52 * However, in that case the vmscan priority will raise fast as the
53 * reclaimer will try to scan LRUs more deeply.
54 *
55 * The vmscan logic considers these special priorities:
56 *
57 * prio == DEF_PRIORITY (12): reclaimer starts with that value
58 * prio <= DEF_PRIORITY - 2 : kswapd becomes somewhat overwhelmed
59 * prio == 0 : close to OOM, kernel scans every page in an lru
60 *
61 * Any value in this range is acceptable for this tunable (i.e. from 12 to
62 * 0). Current value for the vmpressure_level_critical_prio is chosen
63 * empirically, but the number, in essence, means that we consider
64 * critical level when scanning depth is ~10% of the lru size (vmscan
65 * scans 'lru_size >> prio' pages, so it is actually 12.5%, or one
66 * eights).
67 */
68static const unsigned int vmpressure_level_critical_prio = ilog2(100 / 10);
69
70static struct vmpressure *work_to_vmpressure(struct work_struct *work)
71{
72 return container_of(work, struct vmpressure, work);
73}
74
70ddf637
AV
75static struct vmpressure *vmpressure_parent(struct vmpressure *vmpr)
76{
182446d0
TH
77 struct cgroup_subsys_state *css = vmpressure_to_css(vmpr);
78 struct mem_cgroup *memcg = mem_cgroup_from_css(css);
70ddf637
AV
79
80 memcg = parent_mem_cgroup(memcg);
81 if (!memcg)
82 return NULL;
83 return memcg_to_vmpressure(memcg);
84}
85
86enum vmpressure_levels {
87 VMPRESSURE_LOW = 0,
88 VMPRESSURE_MEDIUM,
89 VMPRESSURE_CRITICAL,
90 VMPRESSURE_NUM_LEVELS,
91};
92
b6bb9811
DR
93enum vmpressure_modes {
94 VMPRESSURE_NO_PASSTHROUGH = 0,
95 VMPRESSURE_HIERARCHY,
96 VMPRESSURE_LOCAL,
97 VMPRESSURE_NUM_MODES,
98};
99
70ddf637
AV
100static const char * const vmpressure_str_levels[] = {
101 [VMPRESSURE_LOW] = "low",
102 [VMPRESSURE_MEDIUM] = "medium",
103 [VMPRESSURE_CRITICAL] = "critical",
104};
105
b6bb9811
DR
106static const char * const vmpressure_str_modes[] = {
107 [VMPRESSURE_NO_PASSTHROUGH] = "default",
108 [VMPRESSURE_HIERARCHY] = "hierarchy",
109 [VMPRESSURE_LOCAL] = "local",
110};
111
70ddf637
AV
112static enum vmpressure_levels vmpressure_level(unsigned long pressure)
113{
114 if (pressure >= vmpressure_level_critical)
115 return VMPRESSURE_CRITICAL;
116 else if (pressure >= vmpressure_level_med)
117 return VMPRESSURE_MEDIUM;
118 return VMPRESSURE_LOW;
119}
120
121static enum vmpressure_levels vmpressure_calc_level(unsigned long scanned,
122 unsigned long reclaimed)
123{
124 unsigned long scale = scanned + reclaimed;
e1587a49 125 unsigned long pressure = 0;
70ddf637 126
e1587a49 127 /*
d7143e31 128 * reclaimed can be greater than scanned for things such as reclaimed
129 * slab pages. shrink_node() just adds reclaimed pages without a
130 * related increment to scanned pages.
e1587a49
VM
131 */
132 if (reclaimed >= scanned)
133 goto out;
70ddf637
AV
134 /*
135 * We calculate the ratio (in percents) of how many pages were
136 * scanned vs. reclaimed in a given time frame (window). Note that
137 * time is in VM reclaimer's "ticks", i.e. number of pages
138 * scanned. This makes it possible to set desired reaction time
139 * and serves as a ratelimit.
140 */
141 pressure = scale - (reclaimed * scale / scanned);
142 pressure = pressure * 100 / scale;
143
e1587a49 144out:
70ddf637
AV
145 pr_debug("%s: %3lu (s: %lu r: %lu)\n", __func__, pressure,
146 scanned, reclaimed);
147
148 return vmpressure_level(pressure);
149}
150
151struct vmpressure_event {
152 struct eventfd_ctx *efd;
153 enum vmpressure_levels level;
b6bb9811 154 enum vmpressure_modes mode;
70ddf637
AV
155 struct list_head node;
156};
157
158static bool vmpressure_event(struct vmpressure *vmpr,
b6bb9811
DR
159 const enum vmpressure_levels level,
160 bool ancestor, bool signalled)
70ddf637
AV
161{
162 struct vmpressure_event *ev;
b6bb9811 163 bool ret = false;
70ddf637 164
70ddf637 165 mutex_lock(&vmpr->events_lock);
70ddf637 166 list_for_each_entry(ev, &vmpr->events, node) {
b6bb9811
DR
167 if (ancestor && ev->mode == VMPRESSURE_LOCAL)
168 continue;
169 if (signalled && ev->mode == VMPRESSURE_NO_PASSTHROUGH)
170 continue;
171 if (level < ev->level)
172 continue;
173 eventfd_signal(ev->efd, 1);
174 ret = true;
70ddf637 175 }
70ddf637
AV
176 mutex_unlock(&vmpr->events_lock);
177
b6bb9811 178 return ret;
70ddf637
AV
179}
180
181static void vmpressure_work_fn(struct work_struct *work)
182{
183 struct vmpressure *vmpr = work_to_vmpressure(work);
184 unsigned long scanned;
185 unsigned long reclaimed;
8e8ae645 186 enum vmpressure_levels level;
b6bb9811
DR
187 bool ancestor = false;
188 bool signalled = false;
70ddf637 189
91b57191 190 spin_lock(&vmpr->sr_lock);
70ddf637
AV
191 /*
192 * Several contexts might be calling vmpressure(), so it is
193 * possible that the work was rescheduled again before the old
194 * work context cleared the counters. In that case we will run
195 * just after the old work returns, but then scanned might be zero
196 * here. No need for any locks here since we don't care if
197 * vmpr->reclaimed is in sync.
198 */
8e8ae645 199 scanned = vmpr->tree_scanned;
91b57191
AM
200 if (!scanned) {
201 spin_unlock(&vmpr->sr_lock);
70ddf637 202 return;
91b57191 203 }
70ddf637 204
8e8ae645
JW
205 reclaimed = vmpr->tree_reclaimed;
206 vmpr->tree_scanned = 0;
207 vmpr->tree_reclaimed = 0;
22f2020f 208 spin_unlock(&vmpr->sr_lock);
70ddf637 209
8e8ae645
JW
210 level = vmpressure_calc_level(scanned, reclaimed);
211
70ddf637 212 do {
b6bb9811
DR
213 if (vmpressure_event(vmpr, level, ancestor, signalled))
214 signalled = true;
215 ancestor = true;
70ddf637
AV
216 } while ((vmpr = vmpressure_parent(vmpr)));
217}
218
219/**
220 * vmpressure() - Account memory pressure through scanned/reclaimed ratio
221 * @gfp: reclaimer's gfp mask
222 * @memcg: cgroup memory controller handle
8e8ae645 223 * @tree: legacy subtree mode
70ddf637
AV
224 * @scanned: number of pages scanned
225 * @reclaimed: number of pages reclaimed
226 *
227 * This function should be called from the vmscan reclaim path to account
228 * "instantaneous" memory pressure (scanned/reclaimed ratio). The raw
229 * pressure index is then further refined and averaged over time.
230 *
8e8ae645
JW
231 * If @tree is set, vmpressure is in traditional userspace reporting
232 * mode: @memcg is considered the pressure root and userspace is
233 * notified of the entire subtree's reclaim efficiency.
234 *
235 * If @tree is not set, reclaim efficiency is recorded for @memcg, and
236 * only in-kernel users are notified.
237 *
70ddf637
AV
238 * This function does not return any value.
239 */
8e8ae645 240void vmpressure(gfp_t gfp, struct mem_cgroup *memcg, bool tree,
70ddf637
AV
241 unsigned long scanned, unsigned long reclaimed)
242{
56cab285
SB
243 struct vmpressure *vmpr;
244
245 if (mem_cgroup_disabled())
246 return;
247
248 vmpr = memcg_to_vmpressure(memcg);
70ddf637
AV
249
250 /*
251 * Here we only want to account pressure that userland is able to
252 * help us with. For example, suppose that DMA zone is under
253 * pressure; if we notify userland about that kind of pressure,
254 * then it will be mostly a waste as it will trigger unnecessary
255 * freeing of memory by userland (since userland is more likely to
256 * have HIGHMEM/MOVABLE pages instead of the DMA fallback). That
257 * is why we include only movable, highmem and FS/IO pages.
258 * Indirect reclaim (kswapd) sets sc->gfp_mask to GFP_KERNEL, so
259 * we account it too.
260 */
261 if (!(gfp & (__GFP_HIGHMEM | __GFP_MOVABLE | __GFP_IO | __GFP_FS)))
262 return;
263
264 /*
265 * If we got here with no pages scanned, then that is an indicator
266 * that reclaimer was unable to find any shrinkable LRUs at the
267 * current scanning depth. But it does not mean that we should
268 * report the critical pressure, yet. If the scanning priority
269 * (scanning depth) goes too high (deep), we will be notified
270 * through vmpressure_prio(). But so far, keep calm.
271 */
272 if (!scanned)
273 return;
274
8e8ae645
JW
275 if (tree) {
276 spin_lock(&vmpr->sr_lock);
3c1da7be 277 scanned = vmpr->tree_scanned += scanned;
8e8ae645 278 vmpr->tree_reclaimed += reclaimed;
8e8ae645 279 spin_unlock(&vmpr->sr_lock);
70ddf637 280
8e8ae645
JW
281 if (scanned < vmpressure_win)
282 return;
283 schedule_work(&vmpr->work);
284 } else {
285 enum vmpressure_levels level;
286
287 /* For now, no users for root-level efficiency */
d8a1c03f 288 if (!memcg || mem_cgroup_is_root(memcg))
8e8ae645
JW
289 return;
290
291 spin_lock(&vmpr->sr_lock);
292 scanned = vmpr->scanned += scanned;
293 reclaimed = vmpr->reclaimed += reclaimed;
294 if (scanned < vmpressure_win) {
295 spin_unlock(&vmpr->sr_lock);
296 return;
297 }
298 vmpr->scanned = vmpr->reclaimed = 0;
299 spin_unlock(&vmpr->sr_lock);
300
301 level = vmpressure_calc_level(scanned, reclaimed);
302
303 if (level > VMPRESSURE_LOW) {
304 /*
305 * Let the socket buffer allocator know that
306 * we are having trouble reclaiming LRU pages.
307 *
308 * For hysteresis keep the pressure state
309 * asserted for a second in which subsequent
310 * pressure events can occur.
311 */
312 memcg->socket_pressure = jiffies + HZ;
313 }
314 }
70ddf637
AV
315}
316
317/**
318 * vmpressure_prio() - Account memory pressure through reclaimer priority level
319 * @gfp: reclaimer's gfp mask
320 * @memcg: cgroup memory controller handle
321 * @prio: reclaimer's priority
322 *
323 * This function should be called from the reclaim path every time when
324 * the vmscan's reclaiming priority (scanning depth) changes.
325 *
326 * This function does not return any value.
327 */
328void vmpressure_prio(gfp_t gfp, struct mem_cgroup *memcg, int prio)
329{
330 /*
331 * We only use prio for accounting critical level. For more info
332 * see comment for vmpressure_level_critical_prio variable above.
333 */
334 if (prio > vmpressure_level_critical_prio)
335 return;
336
337 /*
338 * OK, the prio is below the threshold, updating vmpressure
339 * information before shrinker dives into long shrinking of long
340 * range vmscan. Passing scanned = vmpressure_win, reclaimed = 0
341 * to the vmpressure() basically means that we signal 'critical'
342 * level.
343 */
8e8ae645 344 vmpressure(gfp, memcg, true, vmpressure_win, 0);
70ddf637
AV
345}
346
b6bb9811
DR
347#define MAX_VMPRESSURE_ARGS_LEN (strlen("critical") + strlen("hierarchy") + 2)
348
70ddf637
AV
349/**
350 * vmpressure_register_event() - Bind vmpressure notifications to an eventfd
59b6f873 351 * @memcg: memcg that is interested in vmpressure notifications
70ddf637 352 * @eventfd: eventfd context to link notifications with
b6bb9811 353 * @args: event arguments (pressure level threshold, optional mode)
70ddf637
AV
354 *
355 * This function associates eventfd context with the vmpressure
356 * infrastructure, so that the notifications will be delivered to the
b6bb9811
DR
357 * @eventfd. The @args parameter is a comma-delimited string that denotes a
358 * pressure level threshold (one of vmpressure_str_levels, i.e. "low", "medium",
359 * or "critical") and an optional mode (one of vmpressure_str_modes, i.e.
360 * "hierarchy" or "local").
70ddf637 361 *
347c4a87 362 * To be used as memcg event method.
518a8671
DC
363 *
364 * Return: 0 on success, -ENOMEM on memory failure or -EINVAL if @args could
365 * not be parsed.
70ddf637 366 */
59b6f873 367int vmpressure_register_event(struct mem_cgroup *memcg,
347c4a87 368 struct eventfd_ctx *eventfd, const char *args)
70ddf637 369{
59b6f873 370 struct vmpressure *vmpr = memcg_to_vmpressure(memcg);
70ddf637 371 struct vmpressure_event *ev;
b6bb9811 372 enum vmpressure_modes mode = VMPRESSURE_NO_PASSTHROUGH;
518a8671 373 enum vmpressure_levels level;
b6bb9811
DR
374 char *spec, *spec_orig;
375 char *token;
376 int ret = 0;
377
d62ff365 378 spec_orig = spec = kstrndup(args, MAX_VMPRESSURE_ARGS_LEN, GFP_KERNEL);
565dc842
YS
379 if (!spec)
380 return -ENOMEM;
70ddf637 381
b6bb9811
DR
382 /* Find required level */
383 token = strsep(&spec, ",");
518a8671
DC
384 ret = match_string(vmpressure_str_levels, VMPRESSURE_NUM_LEVELS, token);
385 if (ret < 0)
b6bb9811 386 goto out;
518a8671 387 level = ret;
70ddf637 388
b6bb9811
DR
389 /* Find optional mode */
390 token = strsep(&spec, ",");
391 if (token) {
518a8671
DC
392 ret = match_string(vmpressure_str_modes, VMPRESSURE_NUM_MODES, token);
393 if (ret < 0)
b6bb9811 394 goto out;
518a8671 395 mode = ret;
b6bb9811 396 }
70ddf637
AV
397
398 ev = kzalloc(sizeof(*ev), GFP_KERNEL);
b6bb9811
DR
399 if (!ev) {
400 ret = -ENOMEM;
401 goto out;
402 }
70ddf637
AV
403
404 ev->efd = eventfd;
405 ev->level = level;
b6bb9811 406 ev->mode = mode;
70ddf637
AV
407
408 mutex_lock(&vmpr->events_lock);
409 list_add(&ev->node, &vmpr->events);
410 mutex_unlock(&vmpr->events_lock);
518a8671 411 ret = 0;
b6bb9811
DR
412out:
413 kfree(spec_orig);
414 return ret;
70ddf637
AV
415}
416
417/**
418 * vmpressure_unregister_event() - Unbind eventfd from vmpressure
59b6f873 419 * @memcg: memcg handle
70ddf637
AV
420 * @eventfd: eventfd context that was used to link vmpressure with the @cg
421 *
422 * This function does internal manipulations to detach the @eventfd from
423 * the vmpressure notifications, and then frees internal resources
424 * associated with the @eventfd (but the @eventfd itself is not freed).
425 *
347c4a87 426 * To be used as memcg event method.
70ddf637 427 */
59b6f873 428void vmpressure_unregister_event(struct mem_cgroup *memcg,
70ddf637
AV
429 struct eventfd_ctx *eventfd)
430{
59b6f873 431 struct vmpressure *vmpr = memcg_to_vmpressure(memcg);
70ddf637
AV
432 struct vmpressure_event *ev;
433
434 mutex_lock(&vmpr->events_lock);
435 list_for_each_entry(ev, &vmpr->events, node) {
436 if (ev->efd != eventfd)
437 continue;
438 list_del(&ev->node);
439 kfree(ev);
440 break;
441 }
442 mutex_unlock(&vmpr->events_lock);
443}
444
445/**
446 * vmpressure_init() - Initialize vmpressure control structure
447 * @vmpr: Structure to be initialized
448 *
449 * This function should be called on every allocated vmpressure structure
450 * before any usage.
451 */
452void vmpressure_init(struct vmpressure *vmpr)
453{
22f2020f 454 spin_lock_init(&vmpr->sr_lock);
70ddf637
AV
455 mutex_init(&vmpr->events_lock);
456 INIT_LIST_HEAD(&vmpr->events);
457 INIT_WORK(&vmpr->work, vmpressure_work_fn);
458}
33cb876e
MH
459
460/**
461 * vmpressure_cleanup() - shuts down vmpressure control structure
462 * @vmpr: Structure to be cleaned up
463 *
464 * This function should be called before the structure in which it is
465 * embedded is cleaned up.
466 */
467void vmpressure_cleanup(struct vmpressure *vmpr)
468{
469 /*
470 * Make sure there is no pending work before eventfd infrastructure
471 * goes away.
472 */
473 flush_work(&vmpr->work);
474}