Debian Codegraph @

src/oom/oomd-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include "alloc-util.h"
4 #include "constants.h"
5 #include "dirent-util.h"
6 #include "errno-util.h"
7 #include "fd-util.h"
8 #include "fileio.h"
9 #include "format-util.h"
10 #include "log.h"
11 #include "memstream-util.h"
12 #include "oomd-manager.h"
13 #include "oomd-util.h"
14 #include "parse-util.h"
15 #include "path-util.h"
16 #include "pidref.h"
17 #include "procfs-util.h"
18 #include "sd-bus.h"
19 #include "set.h"
20 #include "signal-util.h"
21 #include "sort-util.h"
22 #include "stdio-util.h"
23 #include "string-util.h"
24 #include "strv.h"
25 #include "time-util.h"
26 #include "varlink-util.h"
27
28 typedef struct OomdKillState {
29 Manager *manager;
30 OomdCGroupContext *ctx;
31 char *reason;
32 /* This holds sd_varlink references */
33 Set *links;
34 } OomdKillState;
35
36 DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(
37 oomd_cgroup_ctx_hash_ops,
38 char,
39 path_hash_func,
40 path_compare,
41 OomdCGroupContext,
42 oomd_cgroup_context_unref);
43
44 static int log_kill(const PidRef *pid, int sig, void *userdata) {
45 log_debug("oomd attempting to kill " PID_FMT " with %s", pid->pid, signal_to_string(sig));
46 return 0;
47 }
48
49 static int increment_oomd_xattr(const char *path, const char *xattr, uint64_t num_procs_killed) {
50 _cleanup_free_ char *value = NULL;
51 char buf[DECIMAL_STR_MAX(uint64_t) + 1];
52 uint64_t curr_count = 0;
53 int r;
54
55 assert(path);
56 assert(xattr);
57
58 r = cg_get_xattr(path, xattr, &value, /* ret_size= */ NULL);
59 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
60 return r;
61
62 if (!isempty(value)) {
63 r = safe_atou64(value, &curr_count);
64 if (r < 0)
65 return r;
66 }
67
68 if (curr_count > UINT64_MAX - num_procs_killed)
69 return -EOVERFLOW;
70
71 xsprintf(buf, "%"PRIu64, curr_count + num_procs_killed);
72 r = cg_set_xattr(path, xattr, buf, strlen(buf), 0);
73 if (r < 0)
74 return r;
75
76 return 0;
77 }
78
79 static OomdCGroupContext *oomd_cgroup_context_free(OomdCGroupContext *ctx) {
80 if (!ctx)
81 return NULL;
82
83 free(ctx->path);
84 strv_free(ctx->rules);
85 return mfree(ctx);
86 }
87
88 DEFINE_TRIVIAL_REF_UNREF_FUNC(OomdCGroupContext, oomd_cgroup_context, oomd_cgroup_context_free);
89
90 int oomd_pressure_above(Hashmap *h, Set **ret) {
91 _cleanup_set_free_ Set *targets = NULL;
92 OomdCGroupContext *ctx;
93 char *key;
94 int r;
95
96 assert(h);
97 assert(ret);
98
99 targets = set_new(NULL);
100 if (!targets)
101 return -ENOMEM;
102
103 HASHMAP_FOREACH_KEY(ctx, key, h) {
104 if (ctx->memory_pressure.avg10 > ctx->mem_pressure_limit) {
105 usec_t diff;
106
107 if (ctx->mem_pressure_limit_hit_start == 0)
108 ctx->mem_pressure_limit_hit_start = now(CLOCK_MONOTONIC);
109
110 diff = now(CLOCK_MONOTONIC) - ctx->mem_pressure_limit_hit_start;
111 if (diff >= ctx->mem_pressure_duration_usec) {
112 r = set_put(targets, ctx);
113 if (r < 0)
114 return -ENOMEM;
115 }
116 } else
117 ctx->mem_pressure_limit_hit_start = 0;
118 }
119
120 if (!set_isempty(targets)) {
121 *ret = TAKE_PTR(targets);
122 return 1;
123 }
124
125 *ret = NULL;
126 return 0;
127 }
128
129 uint64_t oomd_pgscan_rate(const OomdCGroupContext *c) {
130 uint64_t last_pgscan;
131
132 assert(c);
133
134 /* If last_pgscan > pgscan, assume the cgroup was recreated and reset last_pgscan to zero.
135 * pgscan is monotonic and in practice should not decrease (except in the recreation case). */
136 last_pgscan = c->last_pgscan;
137 if (c->last_pgscan > c->pgscan) {
138 log_debug("Last pgscan %"PRIu64" greater than current pgscan %"PRIu64" for %s. Using last pgscan of zero.",
139 c->last_pgscan, c->pgscan, c->path);
140 last_pgscan = 0;
141 }
142
143 return c->pgscan - last_pgscan;
144 }
145
146 bool oomd_mem_available_below(const OomdSystemContext *ctx, int threshold_permyriad) {
147 uint64_t mem_threshold;
148
149 assert(ctx);
150 assert(threshold_permyriad <= 10000);
151
152 mem_threshold = ctx->mem_total * threshold_permyriad / (uint64_t) 10000;
153 return LESS_BY(ctx->mem_total, ctx->mem_used) < mem_threshold;
154 }
155
156 bool oomd_swap_free_below(const OomdSystemContext *ctx, int threshold_permyriad) {
157 uint64_t swap_threshold;
158
159 assert(ctx);
160 assert(threshold_permyriad <= 10000);
161
162 swap_threshold = ctx->swap_total * threshold_permyriad / (uint64_t) 10000;
163 return (ctx->swap_total - ctx->swap_used) < swap_threshold;
164 }
165
166 int oomd_fetch_cgroup_oom_preference(OomdCGroupContext *ctx, const char *prefix) {
167 uid_t uid;
168 int r;
169
170 assert(ctx);
171
172 prefix = empty_to_root(prefix);
173
174 if (!path_startswith(ctx->path, prefix))
175 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
176 "%s is not a descendant of %s", ctx->path, prefix);
177
178 r = cg_get_owner(ctx->path, &uid);
179 if (r < 0)
180 return log_debug_errno(r, "Failed to get owner/group from %s: %m", ctx->path);
181
182 if (uid != 0) {
183 uid_t prefix_uid;
184
185 r = cg_get_owner(prefix, &prefix_uid);
186 if (r < 0)
187 return log_debug_errno(r, "Failed to get owner/group from %s: %m", prefix);
188
189 if (uid != prefix_uid) {
190 ctx->preference = MANAGED_OOM_PREFERENCE_NONE;
191 return 0;
192 }
193 }
194
195 /* Ignore most errors when reading the xattr since it is usually unset and cgroup xattrs are only used
196 * as an optional feature of systemd-oomd (and the system might not even support them). */
197 r = cg_get_xattr_bool(ctx->path, "user.oomd_avoid");
198 if (r == -ENOMEM)
199 return log_oom_debug();
200 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
201 log_debug_errno(r, "Failed to get xattr user.oomd_avoid, ignoring: %m");
202 ctx->preference = r > 0 ? MANAGED_OOM_PREFERENCE_AVOID : ctx->preference;
203
204 r = cg_get_xattr_bool(ctx->path, "user.oomd_omit");
205 if (r == -ENOMEM)
206 return log_oom_debug();
207 if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
208 log_debug_errno(r, "Failed to get xattr user.oomd_omit, ignoring: %m");
209 ctx->preference = r > 0 ? MANAGED_OOM_PREFERENCE_OMIT : ctx->preference;
210
211 return 0;
212 }
213
214 int oomd_sort_cgroup_contexts(Hashmap *h, oomd_compare_t compare_func, const char *prefix, OomdCGroupContext ***ret) {
215 _cleanup_free_ OomdCGroupContext **sorted = NULL;
216 OomdCGroupContext *item;
217 size_t k = 0;
218 int r;
219
220 assert(h);
221 assert(compare_func);
222 assert(ret);
223
224 sorted = new0(OomdCGroupContext*, hashmap_size(h));
225 if (!sorted)
226 return -ENOMEM;
227
228 HASHMAP_FOREACH(item, h) {
229 /* Skip over cgroups that are not valid candidates or are explicitly marked for omission */
230 if (item->path && prefix && !path_startswith(item->path, prefix))
231 continue;
232
233 r = oomd_fetch_cgroup_oom_preference(item, prefix);
234 if (r == -ENOMEM)
235 return r;
236
237 if (item->preference == MANAGED_OOM_PREFERENCE_OMIT)
238 continue;
239
240 sorted[k++] = item;
241 }
242
243 typesafe_qsort(sorted, k, compare_func);
244
245 *ret = TAKE_PTR(sorted);
246
247 assert(k <= INT_MAX);
248 return (int) k;
249 }
250
251 int oomd_cgroup_kill(Manager *m, OomdCGroupContext *ctx, bool recurse, const char *reason) {
252 _cleanup_set_free_ Set *pids_killed = NULL;
253 int r;
254
255 assert(ctx);
256 assert(!m || reason);
257
258 pids_killed = set_new(NULL);
259 if (!pids_killed)
260 return -ENOMEM;
261
262 r = increment_oomd_xattr(ctx->path, "user.oomd_ooms", 1);
263 if (r < 0)
264 log_debug_errno(r, "Failed to set user.oomd_ooms before kill: %m");
265
266 if (recurse)
267 r = cg_kill_recursive(ctx->path, SIGKILL, CGROUP_IGNORE_SELF, pids_killed, log_kill, NULL);
268 else
269 r = cg_kill(ctx->path, SIGKILL, CGROUP_IGNORE_SELF, pids_killed, log_kill, NULL);
270
271 /* The cgroup could have been cleaned up after we have sent SIGKILL to all of the processes, but before
272 * we could do one last iteration of cgroup.procs to check. Or the service unit could have exited and
273 * was removed between picking candidates and coming into this function. In either case, let's log
274 * about it let the caller decide what to do once they know how many PIDs were killed. */
275 if (IN_SET(r, -ENOENT, -ENODEV))
276 log_debug_errno(r, "Error when sending SIGKILL to processes in cgroup path %s, ignoring: %m", ctx->path);
277 else if (r < 0)
278 return r;
279
280 if (set_isempty(pids_killed))
281 log_debug("Nothing killed when attempting to kill %s", ctx->path);
282
283 r = increment_oomd_xattr(ctx->path, "user.oomd_kill", set_size(pids_killed));
284 if (r < 0)
285 log_debug_errno(r, "Failed to set user.oomd_kill on kill: %m");
286
287 /* send dbus signal */
288 if (m)
289 (void) sd_bus_emit_signal(m->bus,
290 "/org/freedesktop/oom1",
291 "org.freedesktop.oom1.Manager",
292 "Killed",
293 "ss",
294 ctx->path,
295 reason);
296
297 return !set_isempty(pids_killed);
298 }
299
300 static void oomd_kill_state_free(OomdKillState *ks) {
301 if (!ks)
302 return;
303
304 assert(ks->manager);
305
306 set_free(ks->links);
307
308 set_remove(ks->manager->kill_states, ks);
309 oomd_cgroup_context_unref(ks->ctx);
310 free(ks->reason);
311 free(ks);
312 }
313
314 static int oomd_kill_state_compare(const OomdKillState *a, const OomdKillState *b) {
315 return path_compare(a->ctx->path, b->ctx->path);
316 }
317
318 static void oomd_kill_state_hash_func(const OomdKillState *ks, struct siphash *state) {
319 path_hash_func(ks->ctx->path, state);
320 }
321
322 DEFINE_PRIVATE_HASH_OPS_WITH_KEY_DESTRUCTOR(
323 oomd_kill_state_hash_ops,
324 OomdKillState,
325 oomd_kill_state_hash_func,
326 oomd_kill_state_compare,
327 oomd_kill_state_free);
328
329 /* oomd_kill_state_remove() is called N+1 times where N is the number of prekill hooks found.
330 * The extra call is just after creating the kill state, so to have at least a call if no
331 * prekill hooks are found. Each call removes one link from the kill state, and when the set
332 * is empty, it performs the actual cgroup kill. */
333 static void oomd_kill_state_remove(OomdKillState *ks) {
334 int r;
335
336 assert(ks);
337 assert(ks->ctx);
338
339 if (!set_isempty(ks->links))
340 return;
341
342 r = oomd_cgroup_kill(ks->manager, ks->ctx, /* recurse= */ true, ks->reason);
343 if (r < 0)
344 log_debug_errno(r, "Failed to kill cgroup '%s', ignoring: %m", ks->ctx->path);
345 oomd_kill_state_free(ks);
346 }
347
348 static int prekill_callback(
349 sd_varlink *link,
350 sd_json_variant *parameters,
351 const char *error_id,
352 sd_varlink_reply_flags_t flags,
353 void *userdata) {
354
355 OomdKillState *ks = ASSERT_PTR(userdata);
356
357 assert(ks);
358 assert(ks->ctx);
359
360 if (error_id)
361 log_warning("oomd prekill hook for %s returned error: %s", ks->ctx->path, error_id);
362 else
363 log_info("oomd prekill hook finished for cgroup %s", ks->ctx->path);
364
365 assert_se(set_remove(ks->links, link) == link);
366 oomd_kill_state_remove(ks);
367 sd_varlink_unref(link);
368
369 return 0;
370 }
371
372 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(OomdKillState *, oomd_kill_state_remove, NULL);
373
374 static int send_prekill_message(
375 const char *basename,
376 sd_json_variant *cparams,
377 OomdKillState *ks,
378 sd_event *e) {
379
380 _cleanup_(sd_varlink_close_unrefp) sd_varlink *link = NULL;
381 _cleanup_free_ char *hook_path = NULL;
382 int r;
383
384 assert(basename);
385 assert(cparams);
386 assert(e);
387 assert(ks);
388 assert(ks->ctx);
389 assert(ks->manager);
390
391 log_info("Invoking oomd prekill hook %s for cgroup %s", basename, ks->ctx->path);
392
393 hook_path = path_join(VARLINK_DIR_OOMD_PREKILL_HOOK, basename);
394 if (!hook_path)
395 return log_oom_debug();
396
397 r = sd_varlink_connect_address(&link, hook_path);
398 if (r < 0) {
399 log_debug_errno(r, "Socket '%s' is not connectible, probably stale, ignoring: %m", hook_path);
400 return 0;
401 }
402
403 (void) sd_varlink_set_userdata(link, ks);
404 r = sd_varlink_set_description(link, "oomd prekill hook");
405 if (r < 0)
406 return log_debug_errno(r, "Failed to set varlink description: %m");
407 (void) sd_varlink_set_relative_timeout(link, ks->manager->prekill_timeout);
408
409 r = sd_varlink_attach_event(link, e, SD_EVENT_PRIORITY_NORMAL);
410 if (r < 0)
411 return log_debug_errno(r, "Failed to attach varlink to event loop: %m");
412
413 r = sd_varlink_bind_reply(link, prekill_callback);
414 if (r < 0)
415 return log_debug_errno(r, "Failed to bind reply callback: %m");
416
417 r = sd_varlink_invoke(link, "io.systemd.oom.Prekill.Notify", cparams);
418 if (r < 0)
419 return log_debug_errno(r, "Failed to call varlink method io.systemd.oom.Prekill.Notify: %m");
420
421 r = set_ensure_consume(&ks->links, &varlink_hash_ops, TAKE_PTR(link));
422 if (r < 0)
423 return log_oom_debug();
424
425 return 0;
426 }
427
428 /* oomd_prekill_hook() sets the prekill hooks up by sending varlink messages to all sockets found
429 * in VARLINK_DIR_OOMD_PREKILL_HOOK directory. It returns immediately if no prekill hooks are configured
430 * or PrekillHookTimeoutSec= is not set. In that case, the actual killing is done immediately by
431 * the callback set up by the cleanup handler in oomd_cgroup_kill_mark(). */
432 static int oomd_prekill_hook(Manager *m, OomdKillState *ks) {
433 _cleanup_closedir_ DIR *d = NULL;
434 int r;
435
436 assert(m);
437 assert(ks);
438 assert(ks->ctx);
439
440 if (m->prekill_timeout == 0) {
441 log_debug("Zero oomd prekill timeout configured, skipping prekill hooks.");
442 return 0;
443 }
444
445 d = opendir(VARLINK_DIR_OOMD_PREKILL_HOOK);
446 if (!d) {
447 if (errno == ENOENT) {
448 log_debug("No prekill varlink socket directory %s, ignoring.", VARLINK_DIR_OOMD_PREKILL_HOOK);
449 return 0;
450 }
451 return log_debug_errno(errno, "Failed to open prekill varlink socket directory %s: %m",
452 VARLINK_DIR_OOMD_PREKILL_HOOK);
453 }
454
455 _cleanup_(sd_json_variant_unrefp) sd_json_variant *cparams = NULL;
456 r = sd_json_buildo(&cparams, SD_JSON_BUILD_PAIR_STRING("cgroup", ks->ctx->path));
457 if (r < 0)
458 return log_oom_debug();
459
460 FOREACH_DIRENT(de, d, return -errno) {
461 if (!IN_SET(de->d_type, DT_SOCK, DT_UNKNOWN))
462 continue;
463
464 r = send_prekill_message(de->d_name, cparams, ks, m->event);
465 if (r < 0)
466 log_warning_errno(r, "Failed to send oomd prekill message to %s for cgroup %s, ignoring: %m",
467 de->d_name, ks->ctx->path);
468 }
469
470 return 0;
471 }
472
473 int oomd_cgroup_kill_mark(Manager *m, OomdCGroupContext *ctx, const char *reason) {
474 int r;
475
476 assert(ctx);
477 assert(m);
478 assert(reason);
479
480 if (m->dry_run) {
481 _cleanup_free_ char *cg_path = NULL;
482
483 r = cg_get_path(ctx->path, /* suffix= */ NULL, &cg_path);
484 if (r < 0)
485 return r;
486
487 log_info("oomd dry-run: Would have tried to kill %s and all its descendants", cg_path);
488 return 0;
489 }
490
491 _cleanup_free_ char *reason_copy = strdup(reason);
492 if (!reason_copy)
493 return log_oom_debug();
494
495 _cleanup_(oomd_kill_state_removep) OomdKillState *ks = new(OomdKillState, 1);
496 if (!ks)
497 return log_oom_debug();
498
499 *ks = (OomdKillState) {
500 .manager = m,
501 .ctx = oomd_cgroup_context_ref(ctx),
502 .reason = TAKE_PTR(reason_copy),
503 };
504
505 r = set_ensure_put(&m->kill_states, &oomd_kill_state_hash_ops, ks);
506 if (r < 0)
507 return log_oom_debug();
508 if (r == 0) {
509 /* The cgroup is already queued. Drop only this temporary object, because running the normal
510 * cleanup path would remove by cgroup path key and could interfere with the existing queued
511 * kill state. */
512 oomd_cgroup_context_unref(ks->ctx);
513 free(ks->reason);
514 ks = mfree(ks);
515 return 0;
516 }
517
518 r = oomd_prekill_hook(m, ks);
519 if (r < 0)
520 log_warning_errno(r, "oomd prekill hook failed for %s, ignoring: %m", ctx->path);
521
522 return 1;
523 }
524
525 typedef void (*dump_candidate_func)(const OomdCGroupContext *ctx, FILE *f, const char *prefix);
526
527 static int dump_kill_candidates(
528 OomdCGroupContext *sorted[],
529 size_t n,
530 const OomdCGroupContext *killed,
531 dump_candidate_func dump_func) {
532
533 _cleanup_(memstream_done) MemStream m = {};
534 FILE *f;
535
536 /* Try dumping top offendors, ignoring any errors that might happen. */
537
538 assert(sorted || n == 0);
539 assert(dump_func);
540
541 /* If nothing killed, then limit the number of contexts to be dumped, for safety. */
542 if (!killed)
543 n = MIN(n, DUMP_ON_KILL_COUNT);
544
545 f = memstream_init(&m);
546 if (!f)
547 return -ENOMEM;
548
549 fprintf(f, "Considered %zu cgroups for killing, top candidates were:\n", n);
550 FOREACH_ARRAY(i, sorted, n) {
551 const OomdCGroupContext *c = *i;
552
553 dump_func(c, f, "\t");
554
555 if (c == killed)
556 break;
557 }
558
559 return memstream_dump(LOG_INFO, &m);
560 }
561
562 int oomd_select_by_pgscan_rate(Hashmap *h, const char *prefix, OomdCGroupContext **ret_selected) {
563 _cleanup_free_ OomdCGroupContext **sorted = NULL;
564 int r, n, ret = 0;
565
566 assert(h);
567 assert(ret_selected);
568
569 n = oomd_sort_cgroup_contexts(h, compare_pgscan_rate_and_memory_usage, prefix, &sorted);
570 if (n < 0)
571 return n;
572
573 FOREACH_ARRAY(i, sorted, n) {
574 OomdCGroupContext *c = *i;
575
576 /* Skip cgroups with no reclaim and memory usage; it won't alleviate pressure.
577 * Continue since there might be "avoid" cgroups at the end. */
578 if (c->pgscan == 0 && c->current_memory_usage == 0)
579 continue;
580
581 /* First try killing recursively to ensure all child cgroups can be killed. */
582 r = cg_kill_recursive(c->path, /* sig= */ 0, CGROUP_IGNORE_SELF, /* killed_pids= */ NULL,
583 /* log_kill= */ NULL, /* userdata= */ NULL);
584 if (r < 0)
585 continue;
586
587 ret = 1;
588 *ret_selected = c;
589 break;
590 }
591
592 (void) dump_kill_candidates(sorted, n, *ret_selected, oomd_dump_memory_pressure_cgroup_context);
593 return ret;
594 }
595
596 int oomd_select_by_swap_usage(Hashmap *h, const char *prefix, uint64_t threshold_usage, OomdCGroupContext **ret_selected) {
597 _cleanup_free_ OomdCGroupContext **sorted = NULL;
598 int r, n, ret = 0;
599
600 assert(h);
601 assert(ret_selected);
602
603 n = oomd_sort_cgroup_contexts(h, compare_swap_usage, prefix, &sorted);
604 if (n < 0)
605 return n;
606
607 /* Try to kill cgroups with non-zero swap usage until we either succeed in killing or we get to a cgroup with
608 * no swap usage. Threshold killing only cgroups with more than threshold swap usage. */
609
610 FOREACH_ARRAY(i, sorted, n) {
611 OomdCGroupContext *c = *i;
612
613 /* Skip over cgroups with not enough swap usage. Don't break since there might be "avoid"
614 * cgroups at the end. */
615 if (c->swap_usage <= threshold_usage)
616 continue;
617
618 /* First try killing recursively to ensure all child cgroups can be killed. */
619 r = cg_kill_recursive(c->path, /* sig= */ 0, CGROUP_IGNORE_SELF, /* killed_pids= */ NULL,
620 /* log_kill= */ NULL, /* userdata= */ NULL);
621 if (r < 0)
622 continue;
623
624 ret = 1;
625 *ret_selected = c;
626 break;
627 }
628
629 (void) dump_kill_candidates(sorted, n, *ret_selected, oomd_dump_swap_cgroup_context);
630 return ret;
631 }
632
633 int oomd_cgroup_context_acquire(const char *path, OomdCGroupContext **ret) {
634 _cleanup_(oomd_cgroup_context_unrefp) OomdCGroupContext *ctx = NULL;
635 _cleanup_free_ char *p = NULL;
636 bool is_root;
637 int r;
638
639 assert(path);
640 assert(ret);
641
642 ctx = new0(OomdCGroupContext, 1);
643 if (!ctx)
644 return -ENOMEM;
645
646 *ctx = (OomdCGroupContext) {
647 .n_ref = 1,
648 .preference = MANAGED_OOM_PREFERENCE_NONE,
649 .path = strdup(empty_to_root(path)),
650 };
651 if (!ctx->path)
652 return -ENOMEM;
653
654 is_root = empty_or_root(path);
655
656 r = cg_get_path(path, "memory.pressure", &p);
657 if (r < 0)
658 return log_debug_errno(r, "Error getting cgroup memory pressure path from %s: %m", path);
659
660 r = read_resource_pressure(p, PRESSURE_TYPE_FULL, &ctx->memory_pressure);
661 if (r < 0)
662 return log_debug_errno(r, "Error parsing memory pressure from %s: %m", p);
663
664 if (is_root) {
665 r = procfs_memory_get_used(&ctx->current_memory_usage);
666 if (r < 0)
667 return log_debug_errno(r, "Error getting memory used from procfs: %m");
668 } else {
669 r = cg_get_attribute_as_uint64(path, "memory.current", &ctx->current_memory_usage);
670 if (r < 0)
671 return log_debug_errno(r, "Error getting memory.current from %s: %m", path);
672
673 r = cg_get_attribute_as_uint64(path, "memory.min", &ctx->memory_min);
674 if (r < 0)
675 return log_debug_errno(r, "Error getting memory.min from %s: %m", path);
676
677 r = cg_get_attribute_as_uint64(path, "memory.low", &ctx->memory_low);
678 if (r < 0)
679 return log_debug_errno(r, "Error getting memory.low from %s: %m", path);
680
681 r = cg_get_attribute_as_uint64(path, "memory.swap.current", &ctx->swap_usage);
682 if (r == -ENODATA)
683 /* The kernel can be compiled without support for memory.swap.* files,
684 * or it can be disabled with boot param 'swapaccount=0' */
685 log_once(LOG_WARNING, "No kernel support for memory.swap.current from %s (try boot param swapaccount=1), ignoring.", path);
686 else if (r < 0)
687 return log_debug_errno(r, "Error getting memory.swap.current from %s: %m", path);
688
689 r = cg_get_keyed_attribute_uint64(path, "memory.stat", "pgscan", &ctx->pgscan);
690 if (r < 0)
691 return log_debug_errno(r, "Error getting pgscan from memory.stat under %s: %m", path);
692 }
693
694 *ret = TAKE_PTR(ctx);
695 return 0;
696 }
697
698 int oomd_system_context_acquire(const char *proc_meminfo_path, OomdSystemContext *ret) {
699 _cleanup_fclose_ FILE *f = NULL;
700 unsigned field_filled = 0;
701 OomdSystemContext ctx = {};
702 uint64_t mem_available, swap_free;
703 int r;
704
705 enum {
706 MEM_TOTAL = 1U << 0,
707 MEM_AVAILABLE = 1U << 1,
708 SWAP_TOTAL = 1U << 2,
709 SWAP_FREE = 1U << 3,
710 ALL = MEM_TOTAL|MEM_AVAILABLE|SWAP_TOTAL|SWAP_FREE,
711 };
712
713 assert(proc_meminfo_path);
714 assert(ret);
715
716 f = fopen(proc_meminfo_path, "re");
717 if (!f)
718 return -errno;
719
720 for (;;) {
721 _cleanup_free_ char *line = NULL;
722 char *word;
723
724 r = read_line(f, LONG_LINE_MAX, &line);
725 if (r < 0)
726 return r;
727 if (r == 0)
728 return -EINVAL;
729
730 if ((word = startswith(line, "MemTotal:"))) {
731 field_filled |= MEM_TOTAL;
732 r = convert_meminfo_value_to_uint64_bytes(word, &ctx.mem_total);
733 } else if ((word = startswith(line, "MemAvailable:"))) {
734 field_filled |= MEM_AVAILABLE;
735 r = convert_meminfo_value_to_uint64_bytes(word, &mem_available);
736 } else if ((word = startswith(line, "SwapTotal:"))) {
737 field_filled |= SWAP_TOTAL;
738 r = convert_meminfo_value_to_uint64_bytes(word, &ctx.swap_total);
739 } else if ((word = startswith(line, "SwapFree:"))) {
740 field_filled |= SWAP_FREE;
741 r = convert_meminfo_value_to_uint64_bytes(word, &swap_free);
742 } else
743 continue;
744
745 if (r < 0)
746 return log_debug_errno(r, "Error converting '%s' from %s to uint64_t: %m", line, proc_meminfo_path);
747
748 if (field_filled == ALL)
749 break;
750 }
751
752 if (field_filled != ALL)
753 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "%s is missing expected fields", proc_meminfo_path);
754
755 if (mem_available > ctx.mem_total)
756 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
757 "MemAvailable (%" PRIu64 ") cannot be greater than MemTotal (%" PRIu64 ")",
758 mem_available,
759 ctx.mem_total);
760
761 if (swap_free > ctx.swap_total)
762 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
763 "SwapFree (%" PRIu64 ") cannot be greater than SwapTotal (%" PRIu64 ")",
764 swap_free,
765 ctx.swap_total);
766
767 ctx.mem_used = ctx.mem_total - mem_available;
768 ctx.swap_used = ctx.swap_total - swap_free;
769
770 *ret = ctx;
771 return 0;
772 }
773
774 int oomd_insert_cgroup_context(Hashmap *old_h, Hashmap *new_h, const char *path) {
775 _cleanup_(oomd_cgroup_context_unrefp) OomdCGroupContext *curr_ctx = NULL;
776 OomdCGroupContext *old_ctx;
777 int r;
778
779 assert(new_h);
780 assert(path);
781
782 path = empty_to_root(path);
783
784 r = oomd_cgroup_context_acquire(path, &curr_ctx);
785 if (r < 0)
786 return log_debug_errno(r, "Failed to get OomdCGroupContext for %s: %m", path);
787
788 assert_se(streq(path, curr_ctx->path));
789
790 old_ctx = hashmap_get(old_h, path);
791 if (old_ctx) {
792 curr_ctx->last_pgscan = old_ctx->pgscan;
793 curr_ctx->mem_pressure_limit = old_ctx->mem_pressure_limit;
794 curr_ctx->mem_pressure_limit_hit_start = old_ctx->mem_pressure_limit_hit_start;
795 curr_ctx->mem_pressure_duration_usec = old_ctx->mem_pressure_duration_usec;
796 curr_ctx->last_had_mem_reclaim = old_ctx->last_had_mem_reclaim;
797 curr_ctx->rules = strv_copy(old_ctx->rules);
798 if (old_ctx->rules && !curr_ctx->rules)
799 return -ENOMEM;
800 }
801
802 if (oomd_pgscan_rate(curr_ctx) > 0)
803 curr_ctx->last_had_mem_reclaim = now(CLOCK_MONOTONIC);
804
805 r = hashmap_put(new_h, curr_ctx->path, curr_ctx);
806 if (r < 0)
807 return r;
808
809 TAKE_PTR(curr_ctx);
810 return 0;
811 }
812
813 void oomd_update_cgroup_contexts_between_hashmaps(Hashmap *old_h, Hashmap *curr_h) {
814 OomdCGroupContext *ctx;
815
816 assert(old_h);
817 assert(curr_h);
818
819 HASHMAP_FOREACH(ctx, curr_h) {
820 OomdCGroupContext *old_ctx;
821
822 old_ctx = hashmap_get(old_h, ctx->path);
823 if (!old_ctx)
824 continue;
825
826 ctx->last_pgscan = old_ctx->pgscan;
827 ctx->mem_pressure_limit = old_ctx->mem_pressure_limit;
828 ctx->mem_pressure_limit_hit_start = old_ctx->mem_pressure_limit_hit_start;
829 ctx->mem_pressure_duration_usec = old_ctx->mem_pressure_duration_usec;
830 ctx->last_had_mem_reclaim = old_ctx->last_had_mem_reclaim;
831 /* Note: rules are intentionally not copied here. This function is only used on
832 * candidate hashmaps (populated by recursively_get_cgroup_context for descendant
833 * cgroups), which never carry rules. */
834
835 if (oomd_pgscan_rate(ctx) > 0)
836 ctx->last_had_mem_reclaim = now(CLOCK_MONOTONIC);
837 }
838 }
839
840 void oomd_dump_swap_cgroup_context(const OomdCGroupContext *ctx, FILE *f, const char *prefix) {
841 assert(ctx);
842 assert(f);
843
844 if (!empty_or_root(ctx->path))
845 fprintf(f,
846 "%sPath: %s\n"
847 "%s\tSwap Usage: %s\n",
848 strempty(prefix), ctx->path,
849 strempty(prefix), FORMAT_BYTES(ctx->swap_usage));
850 else
851 fprintf(f,
852 "%sPath: %s\n"
853 "%s\tSwap Usage: (see System Context)\n",
854 strempty(prefix), ctx->path,
855 strempty(prefix));
856 }
857
858 void oomd_dump_memory_pressure_cgroup_context(const OomdCGroupContext *ctx, FILE *f, const char *prefix) {
859 assert(ctx);
860 assert(f);
861
862 fprintf(f,
863 "%sPath: %s\n"
864 "%s\tMemory Pressure Limit: %lu.%02lu%%\n"
865 "%s\tMemory Pressure Duration: %s\n"
866 "%s\tPressure: Avg10: %lu.%02lu, Avg60: %lu.%02lu, Avg300: %lu.%02lu, Total: %s\n"
867 "%s\tCurrent Memory Usage: %s\n",
868 strempty(prefix), ctx->path,
869 strempty(prefix), LOADAVG_INT_SIDE(ctx->mem_pressure_limit), LOADAVG_DECIMAL_SIDE(ctx->mem_pressure_limit),
870 strempty(prefix), FORMAT_TIMESPAN(ctx->mem_pressure_duration_usec, USEC_PER_SEC),
871 strempty(prefix),
872 LOADAVG_INT_SIDE(ctx->memory_pressure.avg10), LOADAVG_DECIMAL_SIDE(ctx->memory_pressure.avg10),
873 LOADAVG_INT_SIDE(ctx->memory_pressure.avg60), LOADAVG_DECIMAL_SIDE(ctx->memory_pressure.avg60),
874 LOADAVG_INT_SIDE(ctx->memory_pressure.avg300), LOADAVG_DECIMAL_SIDE(ctx->memory_pressure.avg300),
875 FORMAT_TIMESPAN(ctx->memory_pressure.total, USEC_PER_SEC),
876 strempty(prefix), FORMAT_BYTES(ctx->current_memory_usage));
877
878 if (!empty_or_root(ctx->path))
879 fprintf(f,
880 "%s\tMemory Min: %s\n"
881 "%s\tMemory Low: %s\n"
882 "%s\tPgscan: %" PRIu64 "\n"
883 "%s\tLast Pgscan: %" PRIu64 "\n",
884 strempty(prefix), FORMAT_BYTES_CGROUP_PROTECTION(ctx->memory_min),
885 strempty(prefix), FORMAT_BYTES_CGROUP_PROTECTION(ctx->memory_low),
886 strempty(prefix), ctx->pgscan,
887 strempty(prefix), ctx->last_pgscan);
888 }
889
890 void oomd_dump_system_context(const OomdSystemContext *ctx, FILE *f, const char *prefix) {
891 assert(ctx);
892 assert(f);
893
894 fprintf(f,
895 "%sMemory: Used: %s, Total: %s\n"
896 "%sSwap: Used: %s, Total: %s\n",
897 strempty(prefix),
898 FORMAT_BYTES(ctx->mem_used),
899 FORMAT_BYTES(ctx->mem_total),
900 strempty(prefix),
901 FORMAT_BYTES(ctx->swap_used),
902 FORMAT_BYTES(ctx->swap_total));
903 }