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