1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010 Lennart Poettering
14 #include <stdio_ext.h>
18 //#include <sys/statfs.h>
19 #include <sys/types.h>
20 #include <sys/xattr.h>
23 #include "alloc-util.h"
24 #include "cgroup-util.h"
26 #include "dirent-util.h"
27 #include "extract-word.h"
30 #include "format-util.h"
33 #include "login-util.h"
35 //#include "missing.h"
37 #include "parse-util.h"
38 #include "path-util.h"
39 #include "proc-cmdline.h"
40 #include "process-util.h"
42 //#include "special.h"
43 #include "stat-util.h"
44 #include "stdio-util.h"
45 #include "string-table.h"
46 #include "string-util.h"
48 #include "unit-name.h"
49 #include "user-util.h"
51 int cg_enumerate_processes(const char *controller, const char *path, FILE **_f) {
52 _cleanup_free_ char *fs = NULL;
58 r = cg_get_path(controller, path, "cgroup.procs", &fs);
70 int cg_read_pid(FILE *f, pid_t *_pid) {
73 /* Note that the cgroup.procs might contain duplicates! See
74 * cgroups.txt for details. */
80 if (fscanf(f, "%lu", &ul) != 1) {
85 return errno > 0 ? -errno : -EIO;
96 const char *controller,
101 _cleanup_free_ char *events = NULL, *content = NULL;
105 r = cg_get_path(controller, path, "cgroup.events", &events);
109 r = read_full_file(events, &content, NULL);
114 while ((line = strsep(&p, "\n"))) {
117 key = strsep(&line, " ");
121 if (strcmp(key, event))
131 #if 0 /// UNNEEDED by elogind
132 bool cg_ns_supported(void) {
133 static thread_local int enabled = -1;
138 if (access("/proc/self/ns/cgroup", F_OK) == 0)
147 int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
148 _cleanup_free_ char *fs = NULL;
154 /* This is not recursive! */
156 r = cg_get_path(controller, path, NULL, &fs);
168 int cg_read_subgroup(DIR *d, char **fn) {
174 FOREACH_DIRENT_ALL(de, d, return -errno) {
177 if (de->d_type != DT_DIR)
180 if (dot_or_dot_dot(de->d_name))
183 b = strdup(de->d_name);
194 int cg_rmdir(const char *controller, const char *path) {
195 _cleanup_free_ char *p = NULL;
198 r = cg_get_path(controller, path, NULL, &p);
203 if (r < 0 && errno != ENOENT)
206 r = cg_hybrid_unified();
212 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
213 r = cg_rmdir(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path);
215 log_warning_errno(r, "Failed to remove compat systemd cgroup %s: %m", path);
222 const char *controller,
227 cg_kill_log_func_t log_kill,
230 _cleanup_set_free_ Set *allocated_set = NULL;
237 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
238 * SIGCONT on SIGKILL. */
239 if (IN_SET(sig, SIGCONT, SIGKILL))
240 flags &= ~CGROUP_SIGCONT;
242 /* This goes through the tasks list and kills them all. This
243 * is repeated until no further processes are added to the
244 * tasks list, to properly handle forking processes */
247 s = allocated_set = set_new(NULL);
252 my_pid = getpid_cached();
255 _cleanup_fclose_ FILE *f = NULL;
259 r = cg_enumerate_processes(controller, path, &f);
261 if (ret >= 0 && r != -ENOENT)
267 while ((r = cg_read_pid(f, &pid)) > 0) {
269 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
272 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
276 log_kill(pid, sig, userdata);
278 /* If we haven't killed this process yet, kill
280 if (kill(pid, sig) < 0) {
281 if (ret >= 0 && errno != ESRCH)
284 if (flags & CGROUP_SIGCONT)
285 (void) kill(pid, SIGCONT);
293 r = set_put(s, PID_TO_PTR(pid));
309 /* To avoid racing against processes which fork
310 * quicker than we can kill them we repeat this until
311 * no new pids need to be killed. */
318 int cg_kill_recursive(
319 const char *controller,
324 cg_kill_log_func_t log_kill,
327 _cleanup_set_free_ Set *allocated_set = NULL;
328 _cleanup_closedir_ DIR *d = NULL;
336 s = allocated_set = set_new(NULL);
341 ret = cg_kill(controller, path, sig, flags, s, log_kill, userdata);
343 r = cg_enumerate_subgroups(controller, path, &d);
345 if (ret >= 0 && r != -ENOENT)
351 while ((r = cg_read_subgroup(d, &fn)) > 0) {
352 _cleanup_free_ char *p = NULL;
354 p = strjoin(path, "/", fn);
359 r = cg_kill_recursive(controller, p, sig, flags, s, log_kill, userdata);
360 if (r != 0 && ret >= 0)
363 if (ret >= 0 && r < 0)
366 if (flags & CGROUP_REMOVE) {
367 r = cg_rmdir(controller, path);
368 if (r < 0 && ret >= 0 && !IN_SET(r, -ENOENT, -EBUSY))
383 _cleanup_set_free_ Set *s = NULL;
396 my_pid = getpid_cached();
398 log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
399 cfrom, pfrom, cto, pto,
400 (flags & CGROUP_IGNORE_SELF)
401 ? "ignoring self" : "watching self");
403 _cleanup_fclose_ FILE *f = NULL;
407 r = cg_enumerate_processes(cfrom, pfrom, &f);
409 if (ret >= 0 && r != -ENOENT)
415 while ((r = cg_read_pid(f, &pid)) > 0) {
417 /* This might do weird stuff if we aren't a
418 * single-threaded program. However, we
419 * luckily know we are not */
420 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
423 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
426 /* Ignore kernel threads. Since they can only
427 * exist in the root cgroup, we only check for
430 empty_or_root(pfrom) &&
431 is_kernel_thread(pid) > 0)
434 r = cg_attach(cto, pto, pid);
436 if (ret >= 0 && r != -ESRCH)
443 r = set_put(s, PID_TO_PTR(pid));
463 int cg_migrate_recursive(
470 _cleanup_closedir_ DIR *d = NULL;
479 ret = cg_migrate(cfrom, pfrom, cto, pto, flags);
481 r = cg_enumerate_subgroups(cfrom, pfrom, &d);
483 if (ret >= 0 && r != -ENOENT)
489 while ((r = cg_read_subgroup(d, &fn)) > 0) {
490 _cleanup_free_ char *p = NULL;
492 p = strjoin(pfrom, "/", fn);
497 r = cg_migrate_recursive(cfrom, p, cto, pto, flags);
498 if (r != 0 && ret >= 0)
502 if (r < 0 && ret >= 0)
505 if (flags & CGROUP_REMOVE) {
506 r = cg_rmdir(cfrom, pfrom);
507 if (r < 0 && ret >= 0 && !IN_SET(r, -ENOENT, -EBUSY))
514 int cg_migrate_recursive_fallback(
528 r = cg_migrate_recursive(cfrom, pfrom, cto, pto, flags);
530 char prefix[strlen(pto) + 1];
532 /* This didn't work? Then let's try all prefixes of the destination */
534 PATH_FOREACH_PREFIX(prefix, pto) {
537 q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, flags);
546 static const char *controller_to_dirname(const char *controller) {
551 /* Converts a controller name to the directory name below
552 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
553 * just cuts off the name= prefixed used for named
554 * hierarchies, if it is specified. */
556 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
557 if (cg_hybrid_unified() > 0)
558 controller = SYSTEMD_CGROUP_CONTROLLER_HYBRID;
560 controller = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
563 e = startswith(controller, "name=");
570 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
577 dn = controller_to_dirname(controller);
579 if (isempty(path) && isempty(suffix))
580 t = strappend("/sys/fs/cgroup/", dn);
581 else if (isempty(path))
582 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix);
583 else if (isempty(suffix))
584 t = strjoin("/sys/fs/cgroup/", dn, "/", path);
586 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix);
594 static int join_path_unified(const char *path, const char *suffix, char **fs) {
599 if (isempty(path) && isempty(suffix))
600 t = strdup("/sys/fs/cgroup");
601 else if (isempty(path))
602 t = strappend("/sys/fs/cgroup/", suffix);
603 else if (isempty(suffix))
604 t = strappend("/sys/fs/cgroup/", path);
606 t = strjoin("/sys/fs/cgroup/", path, "/", suffix);
614 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
622 /* If no controller is specified, we return the path
623 * *below* the controllers, without any prefix. */
625 if (!path && !suffix)
633 t = strjoin(path, "/", suffix);
637 *fs = path_simplify(t, false);
641 if (!cg_controller_is_valid(controller))
644 r = cg_all_unified();
648 r = join_path_unified(path, suffix, fs);
650 r = join_path_legacy(controller, path, suffix, fs);
654 path_simplify(*fs, false);
658 static int controller_is_accessible(const char *controller) {
663 /* Checks whether a specific controller is accessible,
664 * i.e. its hierarchy mounted. In the unified hierarchy all
665 * controllers are considered accessible, except for the named
668 if (!cg_controller_is_valid(controller))
671 r = cg_all_unified();
675 /* We don't support named hierarchies if we are using
676 * the unified hierarchy. */
678 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
681 if (startswith(controller, "name="))
687 dn = controller_to_dirname(controller);
688 cc = strjoina("/sys/fs/cgroup/", dn);
690 if (laccess(cc, F_OK) < 0)
697 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
703 /* Check if the specified controller is actually accessible */
704 r = controller_is_accessible(controller);
708 return cg_get_path(controller, path, suffix, fs);
711 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
716 if (typeflag != FTW_DP)
719 if (ftwbuf->level < 1)
726 int cg_trim(const char *controller, const char *path, bool delete_root) {
727 _cleanup_free_ char *fs = NULL;
732 r = cg_get_path(controller, path, NULL, &fs);
737 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
747 if (rmdir(fs) < 0 && errno != ENOENT)
751 q = cg_hybrid_unified();
754 if (q > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
755 q = cg_trim(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, delete_root);
757 log_warning_errno(q, "Failed to trim compat systemd cgroup %s: %m", path);
763 /* Create a cgroup in the hierarchy of controller.
764 * Returns 0 if the group already existed, 1 on success, negative otherwise.
766 int cg_create(const char *controller, const char *path) {
767 _cleanup_free_ char *fs = NULL;
770 r = cg_get_path_and_check(controller, path, NULL, &fs);
774 r = mkdir_parents(fs, 0755);
778 r = mkdir_errno_wrapper(fs, 0755);
784 r = cg_hybrid_unified();
788 if (r > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
789 r = cg_create(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path);
791 log_warning_errno(r, "Failed to create compat systemd cgroup %s: %m", path);
797 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
802 r = cg_create(controller, path);
806 q = cg_attach(controller, path, pid);
810 /* This does not remove the cgroup on failure */
814 int cg_attach(const char *controller, const char *path, pid_t pid) {
815 _cleanup_free_ char *fs = NULL;
816 char c[DECIMAL_STR_MAX(pid_t) + 2];
822 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
827 pid = getpid_cached();
829 xsprintf(c, PID_FMT "\n", pid);
831 r = write_string_file(fs, c, 0);
835 r = cg_hybrid_unified();
839 if (r > 0 && streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
840 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, pid);
842 log_warning_errno(r, "Failed to attach "PID_FMT" to compat systemd cgroup %s: %m", pid, path);
848 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
855 r = cg_attach(controller, path, pid);
857 char prefix[strlen(path) + 1];
859 /* This didn't work? Then let's try all prefixes of
862 PATH_FOREACH_PREFIX(prefix, path) {
865 q = cg_attach(controller, prefix, pid);
874 #if 0 /// UNNEEDED by elogind
876 const char *controller,
886 /* cgroupsv1, aka legacy/non-unified */
887 static const struct Attribute legacy_attributes[] = {
888 { "cgroup.procs", true },
890 { "cgroup.clone_children", false },
894 /* cgroupsv2, aka unified */
895 static const struct Attribute unified_attributes[] = {
896 { "cgroup.procs", true },
897 { "cgroup.subtree_control", true },
898 { "cgroup.threads", false },
902 static const struct Attribute* const attributes[] = {
903 [false] = legacy_attributes,
904 [true] = unified_attributes,
907 _cleanup_free_ char *fs = NULL;
908 const struct Attribute *i;
913 if (uid == UID_INVALID && gid == GID_INVALID)
916 unified = cg_unified_controller(controller);
920 /* Configure access to the cgroup itself */
921 r = cg_get_path(controller, path, NULL, &fs);
925 r = chmod_and_chown(fs, 0755, uid, gid);
929 /* Configure access to the cgroup's attributes */
930 for (i = attributes[unified]; i->name; i++) {
933 r = cg_get_path(controller, path, i->name, &fs);
937 r = chmod_and_chown(fs, 0644, uid, gid);
942 log_debug_errno(r, "Failed to set access on cgroup %s, ignoring: %m", fs);
946 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER)) {
947 r = cg_hybrid_unified();
951 /* Always propagate access mode from unified to legacy controller */
952 r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER_LEGACY, path, uid, gid);
954 log_debug_errno(r, "Failed to set access on compatibility elogind cgroup %s, ignoring: %m", path);
961 int cg_set_xattr(const char *controller, const char *path, const char *name, const void *value, size_t size, int flags) {
962 _cleanup_free_ char *fs = NULL;
967 assert(value || size <= 0);
969 r = cg_get_path(controller, path, NULL, &fs);
973 if (setxattr(fs, name, value, size, flags) < 0)
979 int cg_get_xattr(const char *controller, const char *path, const char *name, void *value, size_t size) {
980 _cleanup_free_ char *fs = NULL;
987 r = cg_get_path(controller, path, NULL, &fs);
991 n = getxattr(fs, name, value, size);
999 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
1000 _cleanup_fclose_ FILE *f = NULL;
1001 char line[LINE_MAX];
1002 #if 0 /// At elogind we do not want that (false alarm) "maybe uninitialized" warning
1003 const char *fs, *controller_str;
1005 const char *fs, *controller_str = NULL;
1014 if (!cg_controller_is_valid(controller))
1017 controller = SYSTEMD_CGROUP_CONTROLLER;
1019 unified = cg_unified_controller(controller);
1023 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
1024 controller_str = SYSTEMD_CGROUP_CONTROLLER_LEGACY;
1026 controller_str = controller;
1028 cs = strlen(controller_str);
1031 fs = procfs_file_alloca(pid, "cgroup");
1032 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
1033 pid, fs, controller);
1034 f = fopen(fs, "re");
1036 return errno == ENOENT ? -ESRCH : -errno;
1038 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
1040 FOREACH_LINE(line, f, return -errno) {
1046 e = startswith(line, "0:");
1056 const char *word, *state;
1059 l = strchr(line, ':');
1069 FOREACH_WORD_SEPARATOR(word, k, l, ",", state)
1070 if (k == cs && memcmp(word, controller_str, cs) == 0) {
1078 log_debug_elogind("Found %s:%s", line, e+1);
1083 /* Truncate suffix indicating the process is a zombie */
1084 e = endswith(p, " (deleted)");
1095 #if 0 /// UNNEEDED by elogind
1096 int cg_install_release_agent(const char *controller, const char *agent) {
1097 _cleanup_free_ char *fs = NULL, *contents = NULL;
1103 r = cg_unified_controller(controller);
1106 if (r > 0) /* doesn't apply to unified hierarchy */
1109 r = cg_get_path(controller, NULL, "release_agent", &fs);
1113 r = read_one_line_file(fs, &contents);
1117 sc = strstrip(contents);
1119 r = write_string_file(fs, agent, 0);
1122 } else if (!path_equal(sc, agent))
1126 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1130 contents = mfree(contents);
1131 r = read_one_line_file(fs, &contents);
1135 sc = strstrip(contents);
1136 if (streq(sc, "0")) {
1137 r = write_string_file(fs, "1", 0);
1144 if (!streq(sc, "1"))
1150 int cg_uninstall_release_agent(const char *controller) {
1151 _cleanup_free_ char *fs = NULL;
1154 r = cg_unified_controller(controller);
1157 if (r > 0) /* Doesn't apply to unified hierarchy */
1160 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1164 r = write_string_file(fs, "0", 0);
1170 r = cg_get_path(controller, NULL, "release_agent", &fs);
1174 r = write_string_file(fs, "", 0);
1182 int cg_is_empty(const char *controller, const char *path) {
1183 _cleanup_fclose_ FILE *f = NULL;
1189 r = cg_enumerate_processes(controller, path, &f);
1195 r = cg_read_pid(f, &pid);
1202 int cg_is_empty_recursive(const char *controller, const char *path) {
1207 /* The root cgroup is always populated */
1208 if (controller && empty_or_root(path))
1211 r = cg_unified_controller(controller);
1215 _cleanup_free_ char *t = NULL;
1217 /* On the unified hierarchy we can check empty state
1218 * via the "populated" attribute of "cgroup.events". */
1220 r = cg_read_event(controller, path, "populated", &t);
1224 return streq(t, "0");
1226 _cleanup_closedir_ DIR *d = NULL;
1229 r = cg_is_empty(controller, path);
1233 r = cg_enumerate_subgroups(controller, path, &d);
1239 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1240 _cleanup_free_ char *p = NULL;
1242 p = strjoin(path, "/", fn);
1247 r = cg_is_empty_recursive(controller, p);
1258 int cg_split_spec(const char *spec, char **controller, char **path) {
1259 char *t = NULL, *u = NULL;
1265 if (!path_is_normalized(spec))
1273 *path = path_simplify(t, false);
1282 e = strchr(spec, ':');
1284 if (!cg_controller_is_valid(spec))
1301 t = strndup(spec, e-spec);
1304 if (!cg_controller_is_valid(t)) {
1318 if (!path_is_normalized(u) ||
1319 !path_is_absolute(u)) {
1325 path_simplify(u, false);
1341 int cg_mangle_path(const char *path, char **result) {
1342 _cleanup_free_ char *c = NULL, *p = NULL;
1349 /* First, check if it already is a filesystem path */
1350 if (path_startswith(path, "/sys/fs/cgroup")) {
1356 *result = path_simplify(t, false);
1360 /* Otherwise, treat it as cg spec */
1361 r = cg_split_spec(path, &c, &p);
1365 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1368 int cg_get_root_path(char **path) {
1374 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1378 #if 0 /// elogind does not support systemd scopes and slices
1379 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1381 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1383 e = endswith(p, "/system"); /* even more legacy */
1385 e = endswith(p, "/elogind");
1394 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1395 _cleanup_free_ char *rt = NULL;
1403 /* If the root was specified let's use that, otherwise
1404 * let's determine it from PID 1 */
1406 r = cg_get_root_path(&rt);
1411 log_debug_elogind("Determined root path: \"%s\"", root);
1414 p = path_startswith(cgroup, root);
1415 #if 0 /// With other controllers, elogind might end up in /elogind, and *p is 0
1416 if (p && p > cgroup)
1418 if (p && p[0] && (p > cgroup))
1427 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1428 _cleanup_free_ char *raw = NULL;
1435 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1439 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1440 raw, pid, root ? root : "NULL");
1441 r = cg_shift_path(raw, root, &c);
1446 *cgroup = TAKE_PTR(raw);
1456 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1461 int cg_path_decode_unit(const char *cgroup, char **unit) {
1468 #if 0 /// elogind has a different naming: <controller>:/<session id>. So prefix is always len < 3
1469 n = strcspn(cgroup, "/");
1473 n = strspn(cgroup, "/") + 1;
1476 c = strndupa(cgroup, n);
1479 #if 0 /// elogind session ids are never valid unit names.
1480 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1492 static bool valid_slice_name(const char *p, size_t n) {
1497 if (n < STRLEN("x.slice"))
1500 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1506 c = cg_unescape(buf);
1508 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1514 static const char *skip_slices(const char *p) {
1517 /* Skips over all slice assignments */
1522 p += strspn(p, "/");
1524 n = strcspn(p, "/");
1525 if (!valid_slice_name(p, n))
1532 int cg_path_get_unit(const char *path, char **ret) {
1540 e = skip_slices(path);
1542 r = cg_path_decode_unit(e, &unit);
1546 /* We skipped over the slices, don't accept any now */
1547 if (endswith(unit, ".slice")) {
1556 int cg_pid_get_unit(pid_t pid, char **unit) {
1557 _cleanup_free_ char *cgroup = NULL;
1562 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1566 return cg_path_get_unit(cgroup, unit);
1569 #if 0 /// UNNEEDED by elogind
1571 * Skip session-*.scope, but require it to be there.
1573 static const char *skip_session(const char *p) {
1579 p += strspn(p, "/");
1581 n = strcspn(p, "/");
1582 if (n < STRLEN("session-x.scope"))
1585 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1586 char buf[n - 8 - 6 + 1];
1588 memcpy(buf, p + 8, n - 8 - 6);
1591 /* Note that session scopes never need unescaping,
1592 * since they cannot conflict with the kernel's own
1593 * names, hence we don't need to call cg_unescape()
1596 if (!session_id_valid(buf))
1600 p += strspn(p, "/");
1608 * Skip user@*.service, but require it to be there.
1610 static const char *skip_user_manager(const char *p) {
1616 p += strspn(p, "/");
1618 n = strcspn(p, "/");
1619 if (n < STRLEN("user@x.service"))
1622 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1623 char buf[n - 5 - 8 + 1];
1625 memcpy(buf, p + 5, n - 5 - 8);
1628 /* Note that user manager services never need unescaping,
1629 * since they cannot conflict with the kernel's own
1630 * names, hence we don't need to call cg_unescape()
1633 if (parse_uid(buf, NULL) < 0)
1637 p += strspn(p, "/");
1645 static const char *skip_user_prefix(const char *path) {
1650 /* Skip slices, if there are any */
1651 e = skip_slices(path);
1653 /* Skip the user manager, if it's in the path now... */
1654 t = skip_user_manager(e);
1658 /* Alternatively skip the user session if it is in the path... */
1659 return skip_session(e);
1662 int cg_path_get_user_unit(const char *path, char **ret) {
1668 t = skip_user_prefix(path);
1672 /* And from here on it looks pretty much the same as for a
1673 * system unit, hence let's use the same parser from here
1675 return cg_path_get_unit(t, ret);
1678 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1679 _cleanup_free_ char *cgroup = NULL;
1684 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1688 return cg_path_get_user_unit(cgroup, unit);
1691 int cg_path_get_machine_name(const char *path, char **machine) {
1692 _cleanup_free_ char *u = NULL;
1696 r = cg_path_get_unit(path, &u);
1700 sl = strjoina("/run/systemd/machines/unit:", u);
1701 return readlink_malloc(sl, machine);
1704 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1705 _cleanup_free_ char *cgroup = NULL;
1710 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1714 return cg_path_get_machine_name(cgroup, machine);
1718 int cg_path_get_session(const char *path, char **session) {
1719 #if 0 /// UNNEEDED by elogind
1720 _cleanup_free_ char *unit = NULL;
1726 r = cg_path_get_unit(path, &unit);
1730 start = startswith(unit, "session-");
1733 end = endswith(start, ".scope");
1738 if (!session_id_valid(start))
1741 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1742 wrinkle is that SESSION might be escaped. */
1743 const char *e, *n, *start;
1746 log_debug_elogind("path is \"%s\"", path);
1747 assert(path[0] == '/');
1750 n = strchrnul(e, '/');
1754 start = strndupa(e, n - e);
1755 start = cg_unescape(start);
1764 log_debug_elogind("found session: \"%s\"", start);
1775 int cg_pid_get_session(pid_t pid, char **session) {
1776 _cleanup_free_ char *cgroup = NULL;
1779 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1783 return cg_path_get_session(cgroup, session);
1786 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1787 #if 0 /// elogind needs one more value
1788 _cleanup_free_ char *slice = NULL;
1791 _cleanup_free_ char *slice = NULL, *p = NULL, *s = NULL;
1797 r = cg_path_get_slice(path, &slice);
1801 #if 0 /// elogind does not support systemd slices
1802 start = startswith(slice, "user-");
1805 end = endswith(start, ".slice");
1810 if (parse_uid(start, uid) < 0)
1813 p = strappend("/run/systemd/sessions/", slice);
1815 r = parse_env_file(p, NEWLINE, "UID", &s, NULL);
1823 if (parse_uid(s, uid) < 0)
1830 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1831 _cleanup_free_ char *cgroup = NULL;
1834 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1838 return cg_path_get_owner_uid(cgroup, uid);
1841 int cg_path_get_slice(const char *p, char **slice) {
1842 const char *e = NULL;
1847 #if 0 /// elogind does not support systemd slices
1848 /* Finds the right-most slice unit from the beginning, but
1849 * stops before we come to the first non-slice unit. */
1854 p += strspn(p, "/");
1856 n = strcspn(p, "/");
1857 if (!valid_slice_name(p, n)) {
1862 s = strdup(SPECIAL_ROOT_SLICE);
1870 return cg_path_decode_unit(e, slice);
1877 /* In elogind, what is reported here, is the location of
1878 * the session. This is derived from /proc/<self|PID>/cgroup.
1879 * In there we look at the controller, which will look something
1880 * like "1:name=openrc:/3".
1881 * The last part gets extracted (and is now p), which is "/3" in
1882 * this case. The three is the session id, and that can be mapped.
1884 e = startswith(p, "/");
1895 int cg_pid_get_slice(pid_t pid, char **slice) {
1896 _cleanup_free_ char *cgroup = NULL;
1901 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1902 log_debug_elogind("Found cgroup %s for pid %u (result %d)",
1907 return cg_path_get_slice(cgroup, slice);
1910 int cg_path_get_user_slice(const char *p, char **slice) {
1911 #if 0 /// UNNEEDED by elogind
1917 #if 0 /// nothing to skip in elogind
1918 t = skip_user_prefix(p);
1923 #if 0 /// UNNEEDED by elogind
1924 /* And now it looks pretty much the same as for a system
1925 * slice, so let's just use the same parser from here on. */
1926 return cg_path_get_slice(t, slice);
1928 /* In elogind there is nothing to skip, we can use the path
1929 * directly. Generally speaking this is always a session id
1930 * to user mapping. */
1931 return cg_path_get_slice(p, slice);
1935 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1936 _cleanup_free_ char *cgroup = NULL;
1941 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1945 return cg_path_get_user_slice(cgroup, slice);
1948 char *cg_escape(const char *p) {
1949 bool need_prefix = false;
1951 /* This implements very minimal escaping for names to be used
1952 * as file names in the cgroup tree: any name which might
1953 * conflict with a kernel name or is prefixed with '_' is
1954 * prefixed with a '_'. That way, when reading cgroup names it
1955 * is sufficient to remove a single prefixing underscore if
1958 /* The return value of this function (unlike cg_unescape())
1961 if (IN_SET(p[0], 0, '_', '.') ||
1962 streq(p, "notify_on_release") ||
1963 streq(p, "release_agent") ||
1964 streq(p, "tasks") ||
1965 startswith(p, "cgroup."))
1970 dot = strrchr(p, '.');
1975 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1978 n = cgroup_controller_to_string(c);
1983 if (memcmp(p, n, l) != 0)
1993 return strappend("_", p);
1998 char *cg_unescape(const char *p) {
2001 /* The return value of this function (unlike cg_escape())
2002 * doesn't need free()! */
2010 #define CONTROLLER_VALID \
2014 bool cg_controller_is_valid(const char *p) {
2020 if (streq(p, SYSTEMD_CGROUP_CONTROLLER))
2023 s = startswith(p, "name=");
2027 if (IN_SET(*p, 0, '_'))
2030 for (t = p; *t; t++)
2031 if (!strchr(CONTROLLER_VALID, *t))
2034 if (t - p > FILENAME_MAX)
2040 #if 0 /// UNNEEDED by elogind
2041 int cg_slice_to_path(const char *unit, char **ret) {
2042 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
2049 if (streq(unit, SPECIAL_ROOT_SLICE)) {
2059 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
2062 if (!endswith(unit, ".slice"))
2065 r = unit_name_to_prefix(unit, &p);
2069 dash = strchr(p, '-');
2071 /* Don't allow initial dashes */
2076 _cleanup_free_ char *escaped = NULL;
2077 char n[dash - p + sizeof(".slice")];
2079 #if HAS_FEATURE_MEMORY_SANITIZER
2080 /* msan doesn't instrument stpncpy, so it thinks
2081 * n is later used unitialized:
2082 * https://github.com/google/sanitizers/issues/926
2087 /* Don't allow trailing or double dashes */
2088 if (IN_SET(dash[1], 0, '-'))
2091 strcpy(stpncpy(n, p, dash - p), ".slice");
2092 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
2095 escaped = cg_escape(n);
2099 if (!strextend(&s, escaped, "/", NULL))
2102 dash = strchr(dash+1, '-');
2105 e = cg_escape(unit);
2109 if (!strextend(&s, e, NULL))
2118 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
2119 _cleanup_free_ char *p = NULL;
2122 r = cg_get_path(controller, path, attribute, &p);
2126 return write_string_file(p, value, 0);
2129 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
2130 _cleanup_free_ char *p = NULL;
2133 r = cg_get_path(controller, path, attribute, &p);
2137 return read_one_line_file(p, ret);
2140 #if 0 /// UNNEEDED by elogind
2141 int cg_get_keyed_attribute(
2142 const char *controller,
2144 const char *attribute,
2146 char **ret_values) {
2148 _cleanup_free_ char *filename = NULL, *contents = NULL;
2150 size_t n, i, n_done = 0;
2154 /* Reads one or more fields of a cgroupsv2 keyed attribute file. The 'keys' parameter should be an strv with
2155 * all keys to retrieve. The 'ret_values' parameter should be passed as string size with the same number of
2156 * entries as 'keys'. On success each entry will be set to the value of the matching key.
2158 * If the attribute file doesn't exist at all returns ENOENT, if any key is not found returns ENXIO. */
2160 r = cg_get_path(controller, path, attribute, &filename);
2164 r = read_full_file(filename, &contents, NULL);
2168 n = strv_length(keys);
2169 if (n == 0) /* No keys to retrieve? That's easy, we are done then */
2172 /* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
2173 v = newa0(char*, n);
2175 for (p = contents; *p;) {
2176 const char *w = NULL;
2178 for (i = 0; i < n; i++)
2180 w = first_word(p, keys[i]);
2188 l = strcspn(w, NEWLINE);
2189 v[i] = strndup(w, l);
2201 p += strcspn(p, NEWLINE);
2203 p += strspn(p, NEWLINE);
2209 for (i = 0; i < n; i++)
2215 memcpy(ret_values, v, sizeof(char*) * n);
2220 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
2225 /* This one will create a cgroup in our private tree, but also
2226 * duplicate it in the trees specified in mask, and remove it
2229 * Returns 0 if the group already existed in the systemd hierarchy,
2230 * 1 on success, negative otherwise.
2233 /* First create the cgroup in our own hierarchy. */
2234 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
2239 /* If we are in the unified hierarchy, we are done now */
2240 r = cg_all_unified();
2246 /* Otherwise, do the same in the other hierarchies */
2247 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2248 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2251 n = cgroup_controller_to_string(c);
2254 (void) cg_create(n, path);
2255 else if (supported & bit)
2256 (void) cg_trim(n, path, true);
2262 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
2266 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
2270 r = cg_all_unified();
2276 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2277 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2278 const char *p = NULL;
2280 if (!(supported & bit))
2284 p = path_callback(bit, userdata);
2289 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
2295 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2300 SET_FOREACH(pidp, pids, i) {
2301 pid_t pid = PTR_TO_PID(pidp);
2304 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2305 if (q < 0 && r >= 0)
2312 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2316 if (!path_equal(from, to)) {
2317 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2322 q = cg_all_unified();
2328 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2329 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2330 const char *p = NULL;
2332 if (!(supported & bit))
2336 p = to_callback(bit, userdata);
2341 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2347 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2351 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2355 q = cg_all_unified();
2361 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2362 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2364 if (!(supported & bit))
2367 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2374 int cg_mask_to_string(CGroupMask mask, char **ret) {
2375 _cleanup_free_ char *s = NULL;
2376 size_t n = 0, allocated = 0;
2387 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2391 if (!(mask & CGROUP_CONTROLLER_TO_MASK(c)))
2394 k = cgroup_controller_to_string(c);
2397 if (!GREEDY_REALLOC(s, allocated, n + space + l + 1))
2402 memcpy(s + n + space, k, l);
2416 int cg_mask_from_string(const char *value, CGroupMask *mask) {
2421 _cleanup_free_ char *n = NULL;
2425 r = extract_first_word(&value, &n, NULL, 0);
2431 v = cgroup_controller_from_string(n);
2435 *mask |= CGROUP_CONTROLLER_TO_MASK(v);
2440 int cg_mask_supported(CGroupMask *ret) {
2441 CGroupMask mask = 0;
2444 /* Determines the mask of supported cgroup controllers. Only
2445 * includes controllers we can make sense of and that are
2446 * actually accessible. */
2448 r = cg_all_unified();
2452 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2454 /* In the unified hierarchy we can read the supported
2455 * and accessible controllers from a the top-level
2456 * cgroup attribute */
2458 r = cg_get_root_path(&root);
2462 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2466 r = read_one_line_file(path, &controllers);
2470 r = cg_mask_from_string(controllers, &mask);
2474 /* Currently, we support the cpu, memory, io and pids
2475 * controller in the unified hierarchy, mask
2476 * everything else off. */
2477 mask &= CGROUP_MASK_CPU | CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2482 /* In the legacy hierarchy, we check whether which
2483 * hierarchies are mounted. */
2485 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2488 n = cgroup_controller_to_string(c);
2489 if (controller_is_accessible(n) >= 0)
2490 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2498 #if 0 /// UNNEEDED by elogind
2499 int cg_kernel_controllers(Set **ret) {
2500 _cleanup_set_free_free_ Set *controllers = NULL;
2501 _cleanup_fclose_ FILE *f = NULL;
2506 /* Determines the full list of kernel-known controllers. Might
2507 * include controllers we don't actually support, arbitrary
2508 * named hierarchies and controllers that aren't currently
2509 * accessible (because not mounted). */
2511 controllers = set_new(&string_hash_ops);
2515 f = fopen("/proc/cgroups", "re");
2517 if (errno == ENOENT) {
2525 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
2527 /* Ignore the header line */
2528 (void) read_line(f, (size_t) -1, NULL);
2535 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2540 if (ferror(f) && errno > 0)
2551 if (!cg_controller_is_valid(controller)) {
2556 r = set_consume(controllers, controller);
2561 *ret = TAKE_PTR(controllers);
2567 static thread_local CGroupUnified unified_cache = CGROUP_UNIFIED_UNKNOWN;
2569 /* The hybrid mode was initially implemented in v232 and simply mounted cgroup v2 on /sys/fs/cgroup/systemd. This
2570 * unfortunately broke other tools (such as docker) which expected the v1 "name=systemd" hierarchy on
2571 * /sys/fs/cgroup/systemd. From v233 and on, the hybrid mode mountnbs v2 on /sys/fs/cgroup/unified and maintains
2572 * "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility with other tools.
2574 * To keep live upgrade working, we detect and support v232 layout. When v232 layout is detected, to keep cgroup v2
2575 * process management but disable the compat dual layout, we return %true on
2576 * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and %false on cg_hybrid_unified().
2578 static thread_local bool unified_systemd_v232;
2580 static int cg_unified_update(void) {
2584 /* Checks if we support the unified hierarchy. Returns an
2585 * error when the cgroup hierarchies aren't mounted yet or we
2586 * have any other trouble determining if the unified hierarchy
2589 if (unified_cache >= CGROUP_UNIFIED_NONE)
2592 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2593 return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/\") failed: %m");
2595 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2596 log_debug("Found cgroup2 on /sys/fs/cgroup/, full unified hierarchy");
2597 unified_cache = CGROUP_UNIFIED_ALL;
2598 #if 0 /// The handling of cgroups is a bit different with elogind
2599 } else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2600 log_debug("Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller");
2602 } else if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC)
2603 || F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2605 if (statfs("/sys/fs/cgroup/unified/", &fs) == 0 &&
2606 F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2607 unified_cache = CGROUP_UNIFIED_SYSTEMD;
2608 unified_systemd_v232 = false;
2610 #if 0 /// There is no sub-grouping within elogind
2611 if (statfs("/sys/fs/cgroup/systemd/", &fs) < 0)
2612 return log_debug_errno(errno, "statfs(\"/sys/fs/cgroup/systemd\" failed: %m");
2614 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC)) {
2615 log_debug("Found cgroup2 on /sys/fs/cgroup/systemd, unified hierarchy for systemd controller (v232 variant)");
2616 unified_cache = CGROUP_UNIFIED_SYSTEMD;
2617 unified_systemd_v232 = true;
2618 } else if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC)) {
2619 log_debug("Found cgroup on /sys/fs/cgroup/systemd, legacy hierarchy");
2620 unified_cache = CGROUP_UNIFIED_NONE;
2622 log_debug("Unexpected filesystem type %llx mounted on /sys/fs/cgroup/systemd, assuming legacy hierarchy",
2623 (unsigned long long) fs.f_type);
2624 unified_cache = CGROUP_UNIFIED_NONE;
2627 unified_cache = CGROUP_UNIFIED_NONE;
2631 log_debug("Unknown filesystem type %llx mounted on /sys/fs/cgroup.",
2632 (unsigned long long) fs.f_type);
2639 int cg_unified_controller(const char *controller) {
2642 r = cg_unified_update();
2646 if (unified_cache == CGROUP_UNIFIED_NONE)
2649 if (unified_cache >= CGROUP_UNIFIED_ALL)
2652 #if 0 /// only if elogind is the controller we can use cgroups2 in hybrid mode
2653 return streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER);
2655 return streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER_HYBRID);
2659 int cg_all_unified(void) {
2662 r = cg_unified_update();
2666 return unified_cache >= CGROUP_UNIFIED_ALL;
2669 int cg_hybrid_unified(void) {
2672 r = cg_unified_update();
2676 return unified_cache == CGROUP_UNIFIED_SYSTEMD && !unified_systemd_v232;
2679 int cg_unified_flush(void) {
2680 unified_cache = CGROUP_UNIFIED_UNKNOWN;
2682 return cg_unified_update();
2685 #if 0 /// UNNEEDED by elogind
2686 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2687 _cleanup_fclose_ FILE *f = NULL;
2688 _cleanup_free_ char *fs = NULL;
2697 r = cg_all_unified();
2700 if (r == 0) /* on the legacy hiearchy there's no joining of controllers defined */
2703 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2707 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2708 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2711 if (!(supported & bit))
2714 n = cgroup_controller_to_string(c);
2716 char s[1 + strlen(n) + 1];
2718 s[0] = mask & bit ? '+' : '-';
2722 f = fopen(fs, "we");
2724 log_debug_errno(errno, "Failed to open cgroup.subtree_control file of %s: %m", p);
2729 r = write_string_stream(f, s, 0);
2731 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2741 bool cg_is_unified_wanted(void) {
2742 static thread_local int wanted = -1;
2743 #if 0 /// UNNEEDED by elogind
2747 const bool is_default = DEFAULT_HIERARCHY == CGROUP_UNIFIED_ALL;
2749 /* If we have a cached value, return that. */
2753 /* If the hierarchy is already mounted, then follow whatever
2754 * was chosen for it. */
2755 if (cg_unified_flush() >= 0)
2756 return (wanted = unified_cache >= CGROUP_UNIFIED_ALL);
2758 #if 0 /// elogind is not init and has no business with kernel command line
2759 /* Otherwise, let's see what the kernel command line has to say.
2760 * Since checking is expensive, cache a non-error result. */
2761 r = proc_cmdline_get_bool("systemd.unified_cgroup_hierarchy", &b);
2763 return (wanted = r > 0 ? b : is_default);
2769 bool cg_is_legacy_wanted(void) {
2770 static thread_local int wanted = -1;
2772 /* If we have a cached value, return that. */
2776 /* Check if we have cgroups2 already mounted. */
2777 if (cg_unified_flush() >= 0 &&
2778 unified_cache == CGROUP_UNIFIED_ALL)
2779 return (wanted = false);
2781 /* Otherwise, assume that at least partial legacy is wanted,
2782 * since cgroups2 should already be mounted at this point. */
2783 return (wanted = true);
2786 bool cg_is_hybrid_wanted(void) {
2787 static thread_local int wanted = -1;
2788 #if 0 /// UNNEEDED by elogind
2792 const bool is_default = DEFAULT_HIERARCHY >= CGROUP_UNIFIED_SYSTEMD;
2793 /* We default to true if the default is "hybrid", obviously,
2794 * but also when the default is "unified", because if we get
2795 * called, it means that unified hierarchy was not mounted. */
2797 /* If we have a cached value, return that. */
2801 /* If the hierarchy is already mounted, then follow whatever
2802 * was chosen for it. */
2803 if (cg_unified_flush() >= 0 &&
2804 unified_cache == CGROUP_UNIFIED_ALL)
2805 return (wanted = false);
2807 #if 0 /// elogind is not init and has no business with kernel command line
2808 /* Otherwise, let's see what the kernel command line has to say.
2809 * Since checking is expensive, cache a non-error result. */
2810 r = proc_cmdline_get_bool("systemd.legacy_systemd_cgroup_controller", &b);
2812 /* The meaning of the kernel option is reversed wrt. to the return value
2813 * of this function, hence the negation. */
2814 return (wanted = r > 0 ? !b : is_default);
2820 #if 0 /// UNNEEDED by elogind
2821 int cg_weight_parse(const char *s, uint64_t *ret) {
2826 *ret = CGROUP_WEIGHT_INVALID;
2830 r = safe_atou64(s, &u);
2834 if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2841 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2842 [CGROUP_IO_RBPS_MAX] = CGROUP_LIMIT_MAX,
2843 [CGROUP_IO_WBPS_MAX] = CGROUP_LIMIT_MAX,
2844 [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2845 [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2848 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2849 [CGROUP_IO_RBPS_MAX] = "IOReadBandwidthMax",
2850 [CGROUP_IO_WBPS_MAX] = "IOWriteBandwidthMax",
2851 [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2852 [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2855 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2857 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2862 *ret = CGROUP_CPU_SHARES_INVALID;
2866 r = safe_atou64(s, &u);
2870 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2877 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2882 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2886 r = safe_atou64(s, &u);
2890 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2898 bool is_cgroup_fs(const struct statfs *s) {
2899 return is_fs_type(s, CGROUP_SUPER_MAGIC) ||
2900 is_fs_type(s, CGROUP2_SUPER_MAGIC);
2903 bool fd_is_cgroup_fs(int fd) {
2906 if (fstatfs(fd, &s) < 0)
2909 return is_cgroup_fs(&s);
2912 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2913 [CGROUP_CONTROLLER_CPU] = "cpu",
2914 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2915 [CGROUP_CONTROLLER_IO] = "io",
2916 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2917 [CGROUP_CONTROLLER_MEMORY] = "memory",
2918 [CGROUP_CONTROLLER_DEVICES] = "devices",
2919 [CGROUP_CONTROLLER_PIDS] = "pids",
2922 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);