1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2010 Lennart Poettering
12 #include <stdio_ext.h>
16 //#include <sys/statfs.h>
17 #include <sys/types.h>
18 #include <sys/xattr.h>
21 #include "alloc-util.h"
22 #include "cgroup-util.h"
24 #include "dirent-util.h"
25 #include "extract-word.h"
28 #include "format-util.h"
31 #include "login-util.h"
33 //#include "missing.h"
35 #include "parse-util.h"
36 #include "path-util.h"
37 #include "proc-cmdline.h"
38 #include "process-util.h"
40 //#include "special.h"
41 #include "stat-util.h"
42 #include "stdio-util.h"
43 #include "string-table.h"
44 #include "string-util.h"
46 #include "unit-name.h"
47 #include "user-util.h"
49 int cg_enumerate_processes(const char *controller, const char *path, FILE **_f) {
50 _cleanup_free_ char *fs = NULL;
56 r = cg_get_path(controller, path, "cgroup.procs", &fs);
68 int cg_read_pid(FILE *f, pid_t *_pid) {
71 /* Note that the cgroup.procs might contain duplicates! See
72 * cgroups.txt for details. */
78 if (fscanf(f, "%lu", &ul) != 1) {
83 return errno > 0 ? -errno : -EIO;
94 const char *controller,
99 _cleanup_free_ char *events = NULL, *content = NULL;
103 r = cg_get_path(controller, path, "cgroup.events", &events);
107 r = read_full_file(events, &content, NULL);
112 while ((line = strsep(&p, "\n"))) {
115 key = strsep(&line, " ");
119 if (strcmp(key, event))
129 #if 0 /// UNNEEDED by elogind
130 bool cg_ns_supported(void) {
131 static thread_local int enabled = -1;
136 if (access("/proc/self/ns/cgroup", F_OK) == 0)
145 int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
146 _cleanup_free_ char *fs = NULL;
152 /* This is not recursive! */
154 r = cg_get_path(controller, path, NULL, &fs);
166 int cg_read_subgroup(DIR *d, char **fn) {
172 FOREACH_DIRENT_ALL(de, d, return -errno) {
175 if (de->d_type != DT_DIR)
178 if (dot_or_dot_dot(de->d_name))
181 b = strdup(de->d_name);
192 int cg_rmdir(const char *controller, const char *path) {
193 _cleanup_free_ char *p = NULL;
196 r = cg_get_path(controller, path, NULL, &p);
201 if (r < 0 && errno != ENOENT)
204 r = cg_hybrid_unified();
210 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
211 r = cg_rmdir(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path);
213 log_warning_errno(r, "Failed to remove compat systemd cgroup %s: %m", path);
220 const char *controller,
225 cg_kill_log_func_t log_kill,
228 _cleanup_set_free_ Set *allocated_set = NULL;
235 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
236 * SIGCONT on SIGKILL. */
237 if (IN_SET(sig, SIGCONT, SIGKILL))
238 flags &= ~CGROUP_SIGCONT;
240 /* This goes through the tasks list and kills them all. This
241 * is repeated until no further processes are added to the
242 * tasks list, to properly handle forking processes */
245 s = allocated_set = set_new(NULL);
250 my_pid = getpid_cached();
253 _cleanup_fclose_ FILE *f = NULL;
257 r = cg_enumerate_processes(controller, path, &f);
259 if (ret >= 0 && r != -ENOENT)
265 while ((r = cg_read_pid(f, &pid)) > 0) {
267 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
270 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
274 log_kill(pid, sig, userdata);
276 /* If we haven't killed this process yet, kill
278 if (kill(pid, sig) < 0) {
279 if (ret >= 0 && errno != ESRCH)
282 if (flags & CGROUP_SIGCONT)
283 (void) kill(pid, SIGCONT);
291 r = set_put(s, PID_TO_PTR(pid));
307 /* To avoid racing against processes which fork
308 * quicker than we can kill them we repeat this until
309 * no new pids need to be killed. */
316 int cg_kill_recursive(
317 const char *controller,
322 cg_kill_log_func_t log_kill,
325 _cleanup_set_free_ Set *allocated_set = NULL;
326 _cleanup_closedir_ DIR *d = NULL;
334 s = allocated_set = set_new(NULL);
339 ret = cg_kill(controller, path, sig, flags, s, log_kill, userdata);
341 r = cg_enumerate_subgroups(controller, path, &d);
343 if (ret >= 0 && r != -ENOENT)
349 while ((r = cg_read_subgroup(d, &fn)) > 0) {
350 _cleanup_free_ char *p = NULL;
352 p = strjoin(path, "/", fn);
357 r = cg_kill_recursive(controller, p, sig, flags, s, log_kill, userdata);
358 if (r != 0 && ret >= 0)
361 if (ret >= 0 && r < 0)
364 if (flags & CGROUP_REMOVE) {
365 r = cg_rmdir(controller, path);
366 if (r < 0 && ret >= 0 && !IN_SET(r, -ENOENT, -EBUSY))
381 _cleanup_set_free_ Set *s = NULL;
394 my_pid = getpid_cached();
396 log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
397 cfrom, pfrom, cto, pto,
398 (flags & CGROUP_IGNORE_SELF)
399 ? "ignoring self" : "watching self");
401 _cleanup_fclose_ FILE *f = NULL;
405 r = cg_enumerate_processes(cfrom, pfrom, &f);
407 if (ret >= 0 && r != -ENOENT)
413 while ((r = cg_read_pid(f, &pid)) > 0) {
415 /* This might do weird stuff if we aren't a
416 * single-threaded program. However, we
417 * luckily know we are not */
418 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
421 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
424 /* Ignore kernel threads. Since they can only
425 * exist in the root cgroup, we only check for
428 empty_or_root(pfrom) &&
429 is_kernel_thread(pid) > 0)
432 r = cg_attach(cto, pto, pid);
434 if (ret >= 0 && r != -ESRCH)
441 r = set_put(s, PID_TO_PTR(pid));
461 int cg_migrate_recursive(
468 _cleanup_closedir_ DIR *d = NULL;
477 ret = cg_migrate(cfrom, pfrom, cto, pto, flags);
479 r = cg_enumerate_subgroups(cfrom, pfrom, &d);
481 if (ret >= 0 && r != -ENOENT)
487 while ((r = cg_read_subgroup(d, &fn)) > 0) {
488 _cleanup_free_ char *p = NULL;
490 p = strjoin(pfrom, "/", fn);
495 r = cg_migrate_recursive(cfrom, p, cto, pto, flags);
496 if (r != 0 && ret >= 0)
500 if (r < 0 && ret >= 0)
503 if (flags & CGROUP_REMOVE) {
504 r = cg_rmdir(cfrom, pfrom);
505 if (r < 0 && ret >= 0 && !IN_SET(r, -ENOENT, -EBUSY))
512 int cg_migrate_recursive_fallback(
526 r = cg_migrate_recursive(cfrom, pfrom, cto, pto, flags);
528 char prefix[strlen(pto) + 1];
530 /* This didn't work? Then let's try all prefixes of the destination */
532 PATH_FOREACH_PREFIX(prefix, pto) {
535 q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, flags);
544 static const char *controller_to_dirname(const char *controller) {
549 /* Converts a controller name to the directory name below
550 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
551 * just cuts off the name= prefixed used for named
552 * hierarchies, if it is specified. */
554 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
555 if (cg_hybrid_unified() > 0)
556 controller = SYSTEMD_CGROUP_CONTROLLER_HYBRID;
558 controller = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
561 e = startswith(controller, "name=");
568 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
575 dn = controller_to_dirname(controller);
577 if (isempty(path) && isempty(suffix))
578 t = strappend("/sys/fs/cgroup/", dn);
579 else if (isempty(path))
580 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix);
581 else if (isempty(suffix))
582 t = strjoin("/sys/fs/cgroup/", dn, "/", path);
584 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix);
592 static int join_path_unified(const char *path, const char *suffix, char **fs) {
597 if (isempty(path) && isempty(suffix))
598 t = strdup("/sys/fs/cgroup");
599 else if (isempty(path))
600 t = strappend("/sys/fs/cgroup/", suffix);
601 else if (isempty(suffix))
602 t = strappend("/sys/fs/cgroup/", path);
604 t = strjoin("/sys/fs/cgroup/", path, "/", suffix);
612 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
620 /* If no controller is specified, we return the path
621 * *below* the controllers, without any prefix. */
623 if (!path && !suffix)
631 t = strjoin(path, "/", suffix);
635 *fs = path_simplify(t, false);
639 if (!cg_controller_is_valid(controller))
642 r = cg_all_unified();
646 r = join_path_unified(path, suffix, fs);
648 r = join_path_legacy(controller, path, suffix, fs);
652 path_simplify(*fs, false);
656 static int controller_is_accessible(const char *controller) {
661 /* Checks whether a specific controller is accessible,
662 * i.e. its hierarchy mounted. In the unified hierarchy all
663 * controllers are considered accessible, except for the named
666 if (!cg_controller_is_valid(controller))
669 r = cg_all_unified();
673 /* We don't support named hierarchies if we are using
674 * the unified hierarchy. */
676 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
679 if (startswith(controller, "name="))
685 dn = controller_to_dirname(controller);
686 cc = strjoina("/sys/fs/cgroup/", dn);
688 if (laccess(cc, F_OK) < 0)
695 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
701 /* Check if the specified controller is actually accessible */
702 r = controller_is_accessible(controller);
706 return cg_get_path(controller, path, suffix, fs);
709 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
714 if (typeflag != FTW_DP)
717 if (ftwbuf->level < 1)
724 int cg_trim(const char *controller, const char *path, bool delete_root) {
725 _cleanup_free_ char *fs = NULL;
730 r = cg_get_path(controller, path, NULL, &fs);
735 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
745 if (rmdir(fs) < 0 && errno != ENOENT)
749 q = cg_hybrid_unified();
752 if (q > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
753 q = cg_trim(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, delete_root);
755 log_warning_errno(q, "Failed to trim compat systemd cgroup %s: %m", path);
761 /* Create a cgroup in the hierarchy of controller.
762 * Returns 0 if the group already existed, 1 on success, negative otherwise.
764 int cg_create(const char *controller, const char *path) {
765 _cleanup_free_ char *fs = NULL;
768 r = cg_get_path_and_check(controller, path, NULL, &fs);
772 r = mkdir_parents(fs, 0755);
776 r = mkdir_errno_wrapper(fs, 0755);
782 r = cg_hybrid_unified();
786 if (r > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
787 r = cg_create(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path);
789 log_warning_errno(r, "Failed to create compat systemd cgroup %s: %m", path);
795 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
800 r = cg_create(controller, path);
804 q = cg_attach(controller, path, pid);
808 /* This does not remove the cgroup on failure */
812 int cg_attach(const char *controller, const char *path, pid_t pid) {
813 _cleanup_free_ char *fs = NULL;
814 char c[DECIMAL_STR_MAX(pid_t) + 2];
820 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
825 pid = getpid_cached();
827 xsprintf(c, PID_FMT "\n", pid);
829 r = write_string_file(fs, c, 0);
833 r = cg_hybrid_unified();
837 if (r > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
838 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, pid);
840 log_warning_errno(r, "Failed to attach "PID_FMT" to compat systemd cgroup %s: %m", pid, path);
846 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
853 r = cg_attach(controller, path, pid);
855 char prefix[strlen(path) + 1];
857 /* This didn't work? Then let's try all prefixes of
860 PATH_FOREACH_PREFIX(prefix, path) {
863 q = cg_attach(controller, prefix, pid);
872 #if 0 /// UNNEEDED by elogind
874 const char *controller,
884 /* cgroupsv1, aka legacy/non-unified */
885 static const struct Attribute legacy_attributes[] = {
886 { "cgroup.procs", true },
888 { "cgroup.clone_children", false },
892 /* cgroupsv2, aka unified */
893 static const struct Attribute unified_attributes[] = {
894 { "cgroup.procs", true },
895 { "cgroup.subtree_control", true },
896 { "cgroup.threads", false },
900 static const struct Attribute* const attributes[] = {
901 [false] = legacy_attributes,
902 [true] = unified_attributes,
905 _cleanup_free_ char *fs = NULL;
906 const struct Attribute *i;
911 if (uid == UID_INVALID && gid == GID_INVALID)
914 unified = cg_unified_controller(controller);
918 /* Configure access to the cgroup itself */
919 r = cg_get_path(controller, path, NULL, &fs);
923 r = chmod_and_chown(fs, 0755, uid, gid);
927 /* Configure access to the cgroup's attributes */
928 for (i = attributes[unified]; i->name; i++) {
931 r = cg_get_path(controller, path, i->name, &fs);
935 r = chmod_and_chown(fs, 0644, uid, gid);
940 log_debug_errno(r, "Failed to set access on cgroup %s, ignoring: %m", fs);
944 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
945 r = cg_hybrid_unified();
949 /* Always propagate access mode from unified to legacy controller */
950 r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, uid, gid);
952 log_debug_errno(r, "Failed to set access on compatibility elogind cgroup %s, ignoring: %m", path);
959 int cg_set_xattr(const char *controller, const char *path, const char *name, const void *value, size_t size, int flags) {
960 _cleanup_free_ char *fs = NULL;
965 assert(value || size <= 0);
967 r = cg_get_path(controller, path, NULL, &fs);
971 if (setxattr(fs, name, value, size, flags) < 0)
977 int cg_get_xattr(const char *controller, const char *path, const char *name, void *value, size_t size) {
978 _cleanup_free_ char *fs = NULL;
985 r = cg_get_path(controller, path, NULL, &fs);
989 n = getxattr(fs, name, value, size);
997 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
998 _cleanup_fclose_ FILE *f = NULL;
1000 #if 0 /// At elogind we do not want that (false alarm) "maybe uninitialized" warning
1001 const char *fs, *controller_str;
1003 const char *fs, *controller_str = NULL;
1012 if (!cg_controller_is_valid(controller))
1015 controller = SYSTEMD_CGROUP_CONTROLLER;
1017 unified = cg_unified_controller(controller);
1021 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
1022 controller_str = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
1024 controller_str = controller;
1026 cs = strlen(controller_str);
1029 fs = procfs_file_alloca(pid, "cgroup");
1030 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
1031 pid, fs, controller);
1032 f = fopen(fs, "re");
1034 return errno == ENOENT ? -ESRCH : -errno;
1036 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
1038 FOREACH_LINE(line, f, return -errno) {
1044 e = startswith(line, "0:");
1054 const char *word, *state;
1057 l = strchr(line, ':');
1067 FOREACH_WORD_SEPARATOR(word, k, l, ",", state)
1068 if (k == cs && memcmp(word, controller_str, cs) == 0) {
1076 log_debug_elogind("Found %s:%s", line, e+1);
1081 /* Truncate suffix indicating the process is a zombie */
1082 e = endswith(p, " (deleted)");
1093 #if 0 /// UNNEEDED by elogind
1094 int cg_install_release_agent(const char *controller, const char *agent) {
1095 _cleanup_free_ char *fs = NULL, *contents = NULL;
1101 r = cg_unified_controller(controller);
1104 if (r > 0) /* doesn't apply to unified hierarchy */
1107 r = cg_get_path(controller, NULL, "release_agent", &fs);
1111 r = read_one_line_file(fs, &contents);
1115 sc = strstrip(contents);
1117 r = write_string_file(fs, agent, 0);
1120 } else if (!path_equal(sc, agent))
1124 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1128 contents = mfree(contents);
1129 r = read_one_line_file(fs, &contents);
1133 sc = strstrip(contents);
1134 if (streq(sc, "0")) {
1135 r = write_string_file(fs, "1", 0);
1142 if (!streq(sc, "1"))
1148 int cg_uninstall_release_agent(const char *controller) {
1149 _cleanup_free_ char *fs = NULL;
1152 r = cg_unified_controller(controller);
1155 if (r > 0) /* Doesn't apply to unified hierarchy */
1158 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1162 r = write_string_file(fs, "0", 0);
1168 r = cg_get_path(controller, NULL, "release_agent", &fs);
1172 r = write_string_file(fs, "", 0);
1180 int cg_is_empty(const char *controller, const char *path) {
1181 _cleanup_fclose_ FILE *f = NULL;
1187 r = cg_enumerate_processes(controller, path, &f);
1193 r = cg_read_pid(f, &pid);
1200 int cg_is_empty_recursive(const char *controller, const char *path) {
1205 /* The root cgroup is always populated */
1206 if (controller && empty_or_root(path))
1209 r = cg_unified_controller(controller);
1213 _cleanup_free_ char *t = NULL;
1215 /* On the unified hierarchy we can check empty state
1216 * via the "populated" attribute of "cgroup.events". */
1218 r = cg_read_event(controller, path, "populated", &t);
1222 return streq(t, "0");
1224 _cleanup_closedir_ DIR *d = NULL;
1227 r = cg_is_empty(controller, path);
1231 r = cg_enumerate_subgroups(controller, path, &d);
1237 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1238 _cleanup_free_ char *p = NULL;
1240 p = strjoin(path, "/", fn);
1245 r = cg_is_empty_recursive(controller, p);
1256 int cg_split_spec(const char *spec, char **controller, char **path) {
1257 char *t = NULL, *u = NULL;
1263 if (!path_is_normalized(spec))
1271 *path = path_simplify(t, false);
1280 e = strchr(spec, ':');
1282 if (!cg_controller_is_valid(spec))
1299 t = strndup(spec, e-spec);
1302 if (!cg_controller_is_valid(t)) {
1316 if (!path_is_normalized(u) ||
1317 !path_is_absolute(u)) {
1323 path_simplify(u, false);
1339 int cg_mangle_path(const char *path, char **result) {
1340 _cleanup_free_ char *c = NULL, *p = NULL;
1347 /* First, check if it already is a filesystem path */
1348 if (path_startswith(path, "/sys/fs/cgroup")) {
1354 *result = path_simplify(t, false);
1358 /* Otherwise, treat it as cg spec */
1359 r = cg_split_spec(path, &c, &p);
1363 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1366 int cg_get_root_path(char **path) {
1372 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1376 #if 0 /// elogind does not support systemd scopes and slices
1377 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1379 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1381 e = endswith(p, "/system"); /* even more legacy */
1383 e = endswith(p, "/elogind");
1392 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1393 _cleanup_free_ char *rt = NULL;
1401 /* If the root was specified let's use that, otherwise
1402 * let's determine it from PID 1 */
1404 r = cg_get_root_path(&rt);
1409 log_debug_elogind("Determined root path: \"%s\"", root);
1412 p = path_startswith(cgroup, root);
1413 #if 0 /// With other controllers, elogind might end up in /elogind, and *p is 0
1414 if (p && p > cgroup)
1416 if (p && p[0] && (p > cgroup))
1425 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1426 _cleanup_free_ char *raw = NULL;
1433 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1437 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1438 raw, pid, root ? root : "NULL");
1439 r = cg_shift_path(raw, root, &c);
1444 *cgroup = TAKE_PTR(raw);
1454 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1459 int cg_path_decode_unit(const char *cgroup, char **unit) {
1466 #if 0 /// elogind has a different naming: <controller>:/<session id>. So prefix is always len < 3
1467 n = strcspn(cgroup, "/");
1471 n = strspn(cgroup, "/") + 1;
1474 c = strndupa(cgroup, n);
1477 #if 0 /// elogind session ids are never valid unit names.
1478 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1490 static bool valid_slice_name(const char *p, size_t n) {
1495 if (n < STRLEN("x.slice"))
1498 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1504 c = cg_unescape(buf);
1506 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1512 static const char *skip_slices(const char *p) {
1515 /* Skips over all slice assignments */
1520 p += strspn(p, "/");
1522 n = strcspn(p, "/");
1523 if (!valid_slice_name(p, n))
1530 int cg_path_get_unit(const char *path, char **ret) {
1538 e = skip_slices(path);
1540 r = cg_path_decode_unit(e, &unit);
1544 /* We skipped over the slices, don't accept any now */
1545 if (endswith(unit, ".slice")) {
1554 int cg_pid_get_unit(pid_t pid, char **unit) {
1555 _cleanup_free_ char *cgroup = NULL;
1560 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1564 return cg_path_get_unit(cgroup, unit);
1567 #if 0 /// UNNEEDED by elogind
1569 * Skip session-*.scope, but require it to be there.
1571 static const char *skip_session(const char *p) {
1577 p += strspn(p, "/");
1579 n = strcspn(p, "/");
1580 if (n < STRLEN("session-x.scope"))
1583 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1584 char buf[n - 8 - 6 + 1];
1586 memcpy(buf, p + 8, n - 8 - 6);
1589 /* Note that session scopes never need unescaping,
1590 * since they cannot conflict with the kernel's own
1591 * names, hence we don't need to call cg_unescape()
1594 if (!session_id_valid(buf))
1598 p += strspn(p, "/");
1606 * Skip user@*.service, but require it to be there.
1608 static const char *skip_user_manager(const char *p) {
1614 p += strspn(p, "/");
1616 n = strcspn(p, "/");
1617 if (n < STRLEN("user@x.service"))
1620 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1621 char buf[n - 5 - 8 + 1];
1623 memcpy(buf, p + 5, n - 5 - 8);
1626 /* Note that user manager services never need unescaping,
1627 * since they cannot conflict with the kernel's own
1628 * names, hence we don't need to call cg_unescape()
1631 if (parse_uid(buf, NULL) < 0)
1635 p += strspn(p, "/");
1643 static const char *skip_user_prefix(const char *path) {
1648 /* Skip slices, if there are any */
1649 e = skip_slices(path);
1651 /* Skip the user manager, if it's in the path now... */
1652 t = skip_user_manager(e);
1656 /* Alternatively skip the user session if it is in the path... */
1657 return skip_session(e);
1660 int cg_path_get_user_unit(const char *path, char **ret) {
1666 t = skip_user_prefix(path);
1670 /* And from here on it looks pretty much the same as for a
1671 * system unit, hence let's use the same parser from here
1673 return cg_path_get_unit(t, ret);
1676 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1677 _cleanup_free_ char *cgroup = NULL;
1682 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1686 return cg_path_get_user_unit(cgroup, unit);
1689 int cg_path_get_machine_name(const char *path, char **machine) {
1690 _cleanup_free_ char *u = NULL;
1694 r = cg_path_get_unit(path, &u);
1698 sl = strjoina("/run/systemd/machines/unit:", u);
1699 return readlink_malloc(sl, machine);
1702 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1703 _cleanup_free_ char *cgroup = NULL;
1708 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1712 return cg_path_get_machine_name(cgroup, machine);
1716 int cg_path_get_session(const char *path, char **session) {
1717 #if 0 /// UNNEEDED by elogind
1718 _cleanup_free_ char *unit = NULL;
1724 r = cg_path_get_unit(path, &unit);
1728 start = startswith(unit, "session-");
1731 end = endswith(start, ".scope");
1736 if (!session_id_valid(start))
1739 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1740 wrinkle is that SESSION might be escaped. */
1741 const char *e, *n, *start;
1744 log_debug_elogind("path is \"%s\"", path);
1745 assert(path[0] == '/');
1748 n = strchrnul(e, '/');
1752 start = strndupa(e, n - e);
1753 start = cg_unescape(start);
1762 log_debug_elogind("found session: \"%s\"", start);
1773 int cg_pid_get_session(pid_t pid, char **session) {
1774 _cleanup_free_ char *cgroup = NULL;
1777 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1781 return cg_path_get_session(cgroup, session);
1784 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1785 #if 0 /// elogind needs one more value
1786 _cleanup_free_ char *slice = NULL;
1789 _cleanup_free_ char *slice = NULL, *p = NULL, *s = NULL;
1795 r = cg_path_get_slice(path, &slice);
1799 #if 0 /// elogind does not support systemd slices
1800 start = startswith(slice, "user-");
1803 end = endswith(start, ".slice");
1808 if (parse_uid(start, uid) < 0)
1811 p = strappend("/run/systemd/sessions/", slice);
1813 r = parse_env_file(p, NEWLINE, "UID", &s, NULL);
1821 if (parse_uid(s, uid) < 0)
1828 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1829 _cleanup_free_ char *cgroup = NULL;
1832 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1836 return cg_path_get_owner_uid(cgroup, uid);
1839 int cg_path_get_slice(const char *p, char **slice) {
1840 const char *e = NULL;
1845 #if 0 /// elogind does not support systemd slices
1846 /* Finds the right-most slice unit from the beginning, but
1847 * stops before we come to the first non-slice unit. */
1852 p += strspn(p, "/");
1854 n = strcspn(p, "/");
1855 if (!valid_slice_name(p, n)) {
1860 s = strdup(SPECIAL_ROOT_SLICE);
1868 return cg_path_decode_unit(e, slice);
1875 /* In elogind, what is reported here, is the location of
1876 * the session. This is derived from /proc/<self|PID>/cgroup.
1877 * In there we look at the controller, which will look something
1878 * like "1:name=openrc:/3".
1879 * The last part gets extracted (and is now p), which is "/3" in
1880 * this case. The three is the session id, and that can be mapped.
1882 e = startswith(p, "/");
1893 int cg_pid_get_slice(pid_t pid, char **slice) {
1894 _cleanup_free_ char *cgroup = NULL;
1899 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1900 log_debug_elogind("Found cgroup %s for pid %u (result %d)",
1905 return cg_path_get_slice(cgroup, slice);
1908 int cg_path_get_user_slice(const char *p, char **slice) {
1909 #if 0 /// UNNEEDED by elogind
1915 #if 0 /// nothing to skip in elogind
1916 t = skip_user_prefix(p);
1921 #if 0 /// UNNEEDED by elogind
1922 /* And now it looks pretty much the same as for a system
1923 * slice, so let's just use the same parser from here on. */
1924 return cg_path_get_slice(t, slice);
1926 /* In elogind there is nothing to skip, we can use the path
1927 * directly. Generally speaking this is always a session id
1928 * to user mapping. */
1929 return cg_path_get_slice(p, slice);
1933 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1934 _cleanup_free_ char *cgroup = NULL;
1939 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1943 return cg_path_get_user_slice(cgroup, slice);
1946 char *cg_escape(const char *p) {
1947 bool need_prefix = false;
1949 /* This implements very minimal escaping for names to be used
1950 * as file names in the cgroup tree: any name which might
1951 * conflict with a kernel name or is prefixed with '_' is
1952 * prefixed with a '_'. That way, when reading cgroup names it
1953 * is sufficient to remove a single prefixing underscore if
1956 /* The return value of this function (unlike cg_unescape())
1959 if (IN_SET(p[0], 0, '_', '.') ||
1960 streq(p, "notify_on_release") ||
1961 streq(p, "release_agent") ||
1962 streq(p, "tasks") ||
1963 startswith(p, "cgroup."))
1968 dot = strrchr(p, '.');
1973 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1976 n = cgroup_controller_to_string(c);
1981 if (memcmp(p, n, l) != 0)
1991 return strappend("_", p);
1996 char *cg_unescape(const char *p) {
1999 /* The return value of this function (unlike cg_escape())
2000 * doesn't need free()! */
2008 #define CONTROLLER_VALID \
2012 bool cg_controller_is_valid(const char *p) {
2018 if (streq(p, SYSTEMD_CGROUP_CONTROLLER))
2021 s = startswith(p, "name=");
2025 if (IN_SET(*p, 0, '_'))
2028 for (t = p; *t; t++)
2029 if (!strchr(CONTROLLER_VALID, *t))
2032 if (t - p > FILENAME_MAX)
2038 #if 0 /// UNNEEDED by elogind
2039 int cg_slice_to_path(const char *unit, char **ret) {
2040 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
2047 if (streq(unit, SPECIAL_ROOT_SLICE)) {
2057 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
2060 if (!endswith(unit, ".slice"))
2063 r = unit_name_to_prefix(unit, &p);
2067 dash = strchr(p, '-');
2069 /* Don't allow initial dashes */
2074 _cleanup_free_ char *escaped = NULL;
2075 char n[dash - p + sizeof(".slice")];
2077 #if HAS_FEATURE_MEMORY_SANITIZER
2078 /* msan doesn't instrument stpncpy, so it thinks
2079 * n is later used unitialized:
2080 * https://github.com/google/sanitizers/issues/926
2085 /* Don't allow trailing or double dashes */
2086 if (IN_SET(dash[1], 0, '-'))
2089 strcpy(stpncpy(n, p, dash - p), ".slice");
2090 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
2093 escaped = cg_escape(n);
2097 if (!strextend(&s, escaped, "/", NULL))
2100 dash = strchr(dash+1, '-');
2103 e = cg_escape(unit);
2107 if (!strextend(&s, e, NULL))
2116 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
2117 _cleanup_free_ char *p = NULL;
2120 r = cg_get_path(controller, path, attribute, &p);
2124 return write_string_file(p, value, 0);
2127 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
2128 _cleanup_free_ char *p = NULL;
2131 r = cg_get_path(controller, path, attribute, &p);
2135 return read_one_line_file(p, ret);
2138 #if 0 /// UNNEEDED by elogind
2139 int cg_get_keyed_attribute(
2140 const char *controller,
2142 const char *attribute,
2144 char **ret_values) {
2146 _cleanup_free_ char *filename = NULL, *contents = NULL;
2148 size_t n, i, n_done = 0;
2152 /* Reads one or more fields of a cgroupsv2 keyed attribute file. The 'keys' parameter should be an strv with
2153 * all keys to retrieve. The 'ret_values' parameter should be passed as string size with the same number of
2154 * entries as 'keys'. On success each entry will be set to the value of the matching key.
2156 * If the attribute file doesn't exist at all returns ENOENT, if any key is not found returns ENXIO. */
2158 r = cg_get_path(controller, path, attribute, &filename);
2162 r = read_full_file(filename, &contents, NULL);
2166 n = strv_length(keys);
2167 if (n == 0) /* No keys to retrieve? That's easy, we are done then */
2170 /* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
2171 v = newa0(char*, n);
2173 for (p = contents; *p;) {
2174 const char *w = NULL;
2176 for (i = 0; i < n; i++)
2178 w = first_word(p, keys[i]);
2186 l = strcspn(w, NEWLINE);
2187 v[i] = strndup(w, l);
2199 p += strcspn(p, NEWLINE);
2201 p += strspn(p, NEWLINE);
2207 for (i = 0; i < n; i++)
2213 memcpy(ret_values, v, sizeof(char*) * n);
2218 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
2223 /* This one will create a cgroup in our private tree, but also
2224 * duplicate it in the trees specified in mask, and remove it
2227 * Returns 0 if the group already existed in the systemd hierarchy,
2228 * 1 on success, negative otherwise.
2231 /* First create the cgroup in our own hierarchy. */
2232 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
2237 /* If we are in the unified hierarchy, we are done now */
2238 r = cg_all_unified();
2244 /* Otherwise, do the same in the other hierarchies */
2245 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2246 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2249 n = cgroup_controller_to_string(c);
2252 (void) cg_create(n, path);
2253 else if (supported & bit)
2254 (void) cg_trim(n, path, true);
2260 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
2264 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
2268 r = cg_all_unified();
2274 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2275 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2276 const char *p = NULL;
2278 if (!(supported & bit))
2282 p = path_callback(bit, userdata);
2287 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
2293 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2298 SET_FOREACH(pidp, pids, i) {
2299 pid_t pid = PTR_TO_PID(pidp);
2302 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2303 if (q < 0 && r >= 0)
2310 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2314 if (!path_equal(from, to)) {
2315 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2320 q = cg_all_unified();
2326 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2327 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2328 const char *p = NULL;
2330 if (!(supported & bit))
2334 p = to_callback(bit, userdata);
2339 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2345 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2349 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2353 q = cg_all_unified();
2359 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2360 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2362 if (!(supported & bit))
2365 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2372 int cg_mask_to_string(CGroupMask mask, char **ret) {
2373 _cleanup_free_ char *s = NULL;
2374 size_t n = 0, allocated = 0;
2385 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2389 if (!(mask & CGROUP_CONTROLLER_TO_MASK(c)))
2392 k = cgroup_controller_to_string(c);
2395 if (!GREEDY_REALLOC(s, allocated, n + space + l + 1))
2400 memcpy(s + n + space, k, l);
2414 int cg_mask_from_string(const char *value, CGroupMask *mask) {
2419 _cleanup_free_ char *n = NULL;
2423 r = extract_first_word(&value, &n, NULL, 0);
2429 v = cgroup_controller_from_string(n);
2433 *mask |= CGROUP_CONTROLLER_TO_MASK(v);
2438 int cg_mask_supported(CGroupMask *ret) {
2439 CGroupMask mask = 0;
2442 /* Determines the mask of supported cgroup controllers. Only
2443 * includes controllers we can make sense of and that are
2444 * actually accessible. */
2446 r = cg_all_unified();
2450 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2452 /* In the unified hierarchy we can read the supported
2453 * and accessible controllers from a the top-level
2454 * cgroup attribute */
2456 r = cg_get_root_path(&root);
2460 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2464 r = read_one_line_file(path, &controllers);
2468 r = cg_mask_from_string(controllers, &mask);
2472 /* Currently, we support the cpu, memory, io and pids
2473 * controller in the unified hierarchy, mask
2474 * everything else off. */
2475 mask &= CGROUP_MASK_CPU | CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2480 /* In the legacy hierarchy, we check whether which
2481 * hierarchies are mounted. */
2483 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2486 n = cgroup_controller_to_string(c);
2487 if (controller_is_accessible(n) >= 0)
2488 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2496 #if 0 /// UNNEEDED by elogind
2497 int cg_kernel_controllers(Set **ret) {
2498 _cleanup_set_free_free_ Set *controllers = NULL;
2499 _cleanup_fclose_ FILE *f = NULL;
2504 /* Determines the full list of kernel-known controllers. Might
2505 * include controllers we don't actually support, arbitrary
2506 * named hierarchies and controllers that aren't currently
2507 * accessible (because not mounted). */
2509 controllers = set_new(&string_hash_ops);
2513 f = fopen("/proc/cgroups", "re");
2515 if (errno == ENOENT) {
2523 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
2525 /* Ignore the header line */
2526 (void) read_line(f, (size_t) -1, NULL);
2533 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2538 if (ferror(f) && errno > 0)
2549 if (!cg_controller_is_valid(controller)) {
2554 r = set_consume(controllers, controller);
2559 *ret = TAKE_PTR(controllers);
2565 static thread_local CGroupUnified unified_cache = CGROUP_UNIFIED_UNKNOWN;
2567 /* The hybrid mode was initially implemented in v232 and simply mounted cgroup v2 on /sys/fs/cgroup/systemd. This
2568 * unfortunately broke other tools (such as docker) which expected the v1 "name=systemd" hierarchy on
2569 * /sys/fs/cgroup/systemd. From v233 and on, the hybrid mode mountnbs v2 on /sys/fs/cgroup/unified and maintains
2570 * "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility with other tools.
2572 * To keep live upgrade working, we detect and support v232 layout. When v232 layout is detected, to keep cgroup v2
2573 * process management but disable the compat dual layout, we return %true on
2574 * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and %false on cg_hybrid_unified().
2576 static thread_local bool unified_systemd_v232;
2578 static int cg_unified_update(void) {
2582 /* Checks if we support the unified hierarchy. Returns an
2583 * error when the cgroup hierarchies aren't mounted yet or we
2584 * have any other trouble determining if the unified hierarchy
2587 if (unified_cache >= CGROUP_UNIFIED_NONE)
2590 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2591 return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/\") failed: %m");
2593 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2594 log_debug("Found cgroup2 on /sys/fs/cgroup/, full unified hierarchy");
2595 unified_cache = CGROUP_UNIFIED_ALL;
2596 #if 0 /// The handling of cgroups is a bit different with elogind
2597 } else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2598 log_debug("Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller");
2600 } else if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC)
2601 || F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2603 if (statfs("/sys/fs/cgroup/unified/", &fs) == 0 &&
2604 F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2605 unified_cache = CGROUP_UNIFIED_SYSTEMD;
2606 unified_systemd_v232 = false;
2608 #if 0 /// There is no sub-grouping within elogind
2609 if (statfs("/sys/fs/cgroup/systemd/", &fs) < 0)
2610 return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/systemd\" failed: %m");
2612 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2613 log_debug("Found cgroup2 on /sys/fs/cgroup/systemd, unified hierarchy for systemd controller (v232 variant)");
2614 unified_cache = CGROUP_UNIFIED_SYSTEMD;
2615 unified_systemd_v232 = true;
2616 } else if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC)) {
2617 log_debug("Found cgroup on /sys/fs/cgroup/systemd, legacy hierarchy");
2618 unified_cache = CGROUP_UNIFIED_NONE;
2620 log_debug("Unexpected filesystem type %llx mounted on /sys/fs/cgroup/systemd, assuming legacy hierarchy",
2621 (unsigned long long) fs.f_type);
2622 unified_cache = CGROUP_UNIFIED_NONE;
2625 unified_cache = CGROUP_UNIFIED_NONE;
2629 log_debug("Unknown filesystem type %llx mounted on /sys/fs/cgroup.",
2630 (unsigned long long) fs.f_type);
2637 int cg_unified_controller(const char *controller) {
2640 r = cg_unified_update();
2644 if (unified_cache == CGROUP_UNIFIED_NONE)
2647 if (unified_cache >= CGROUP_UNIFIED_ALL)
2650 #if 0 /// only if elogind is the controller we can use cgroups2 in hybrid mode
2651 return streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER);
2653 return streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER_HYBRID);
2657 int cg_all_unified(void) {
2660 r = cg_unified_update();
2664 return unified_cache >= CGROUP_UNIFIED_ALL;
2667 int cg_hybrid_unified(void) {
2670 r = cg_unified_update();
2674 return unified_cache == CGROUP_UNIFIED_SYSTEMD && !unified_systemd_v232;
2677 int cg_unified_flush(void) {
2678 unified_cache = CGROUP_UNIFIED_UNKNOWN;
2680 return cg_unified_update();
2683 #if 0 /// UNNEEDED by elogind
2684 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2685 _cleanup_fclose_ FILE *f = NULL;
2686 _cleanup_free_ char *fs = NULL;
2695 r = cg_all_unified();
2698 if (r == 0) /* on the legacy hiearchy there's no joining of controllers defined */
2701 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2705 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2706 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2709 if (!(supported & bit))
2712 n = cgroup_controller_to_string(c);
2714 char s[1 + strlen(n) + 1];
2716 s[0] = mask & bit ? '+' : '-';
2720 f = fopen(fs, "we");
2722 log_debug_errno(errno, "Failed to open cgroup.subtree_control file of %s: %m", p);
2727 r = write_string_stream(f, s, 0);
2729 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2739 bool cg_is_unified_wanted(void) {
2740 static thread_local int wanted = -1;
2741 #if 0 /// UNNEEDED by elogind
2745 const bool is_default = DEFAULT_HIERARCHY == CGROUP_UNIFIED_ALL;
2747 /* If we have a cached value, return that. */
2751 /* If the hierarchy is already mounted, then follow whatever
2752 * was chosen for it. */
2753 if (cg_unified_flush() >= 0)
2754 return (wanted = unified_cache >= CGROUP_UNIFIED_ALL);
2756 #if 0 /// elogind is not init and has no business with kernel command line
2757 /* Otherwise, let's see what the kernel command line has to say.
2758 * Since checking is expensive, cache a non-error result. */
2759 r = proc_cmdline_get_bool("systemd.unified_cgroup_hierarchy", &b);
2761 return (wanted = r > 0 ? b : is_default);
2767 bool cg_is_legacy_wanted(void) {
2768 static thread_local int wanted = -1;
2770 /* If we have a cached value, return that. */
2774 /* Check if we have cgroups2 already mounted. */
2775 if (cg_unified_flush() >= 0 &&
2776 unified_cache == CGROUP_UNIFIED_ALL)
2777 return (wanted = false);
2779 /* Otherwise, assume that at least partial legacy is wanted,
2780 * since cgroups2 should already be mounted at this point. */
2781 return (wanted = true);
2784 bool cg_is_hybrid_wanted(void) {
2785 static thread_local int wanted = -1;
2786 #if 0 /// UNNEEDED by elogind
2790 const bool is_default = DEFAULT_HIERARCHY >= CGROUP_UNIFIED_SYSTEMD;
2791 /* We default to true if the default is "hybrid", obviously,
2792 * but also when the default is "unified", because if we get
2793 * called, it means that unified hierarchy was not mounted. */
2795 /* If we have a cached value, return that. */
2799 /* If the hierarchy is already mounted, then follow whatever
2800 * was chosen for it. */
2801 if (cg_unified_flush() >= 0 &&
2802 unified_cache == CGROUP_UNIFIED_ALL)
2803 return (wanted = false);
2805 #if 0 /// elogind is not init and has no business with kernel command line
2806 /* Otherwise, let's see what the kernel command line has to say.
2807 * Since checking is expensive, cache a non-error result. */
2808 r = proc_cmdline_get_bool("systemd.legacy_systemd_cgroup_controller", &b);
2810 /* The meaning of the kernel option is reversed wrt. to the return value
2811 * of this function, hence the negation. */
2812 return (wanted = r > 0 ? !b : is_default);
2818 #if 0 /// UNNEEDED by elogind
2819 int cg_weight_parse(const char *s, uint64_t *ret) {
2824 *ret = CGROUP_WEIGHT_INVALID;
2828 r = safe_atou64(s, &u);
2832 if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2839 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2840 [CGROUP_IO_RBPS_MAX] = CGROUP_LIMIT_MAX,
2841 [CGROUP_IO_WBPS_MAX] = CGROUP_LIMIT_MAX,
2842 [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2843 [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2846 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2847 [CGROUP_IO_RBPS_MAX] = "IOReadBandwidthMax",
2848 [CGROUP_IO_WBPS_MAX] = "IOWriteBandwidthMax",
2849 [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2850 [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2853 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2855 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2860 *ret = CGROUP_CPU_SHARES_INVALID;
2864 r = safe_atou64(s, &u);
2868 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2875 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2880 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2884 r = safe_atou64(s, &u);
2888 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2896 bool is_cgroup_fs(const struct statfs *s) {
2897 return is_fs_type(s, CGROUP_SUPER_MAGIC) ||
2898 is_fs_type(s, CGROUP2_SUPER_MAGIC);
2901 bool fd_is_cgroup_fs(int fd) {
2904 if (fstatfs(fd, &s) < 0)
2907 return is_cgroup_fs(&s);
2910 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2911 [CGROUP_CONTROLLER_CPU] = "cpu",
2912 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2913 [CGROUP_CONTROLLER_IO] = "io",
2914 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2915 [CGROUP_CONTROLLER_MEMORY] = "memory",
2916 [CGROUP_CONTROLLER_DEVICES] = "devices",
2917 [CGROUP_CONTROLLER_PIDS] = "pids",
2920 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);