2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
29 //#include <sys/statfs.h>
30 #include <sys/types.h>
31 #include <sys/xattr.h>
34 #include "alloc-util.h"
35 #include "cgroup-util.h"
37 #include "dirent-util.h"
38 #include "extract-word.h"
41 #include "format-util.h"
44 #include "login-util.h"
46 //#include "missing.h"
48 #include "parse-util.h"
49 #include "path-util.h"
50 #include "proc-cmdline.h"
51 #include "process-util.h"
53 //#include "special.h"
54 #include "stat-util.h"
55 #include "stdio-util.h"
56 #include "string-table.h"
57 #include "string-util.h"
58 #include "unit-name.h"
59 #include "user-util.h"
61 int cg_enumerate_processes(const char *controller, const char *path, FILE **_f) {
62 _cleanup_free_ char *fs = NULL;
68 r = cg_get_path(controller, path, "cgroup.procs", &fs);
80 int cg_read_pid(FILE *f, pid_t *_pid) {
83 /* Note that the cgroup.procs might contain duplicates! See
84 * cgroups.txt for details. */
90 if (fscanf(f, "%lu", &ul) != 1) {
95 return errno > 0 ? -errno : -EIO;
105 int cg_read_event(const char *controller, const char *path, const char *event,
108 _cleanup_free_ char *events = NULL, *content = NULL;
112 r = cg_get_path(controller, path, "cgroup.events", &events);
116 r = read_full_file(events, &content, NULL);
121 while ((line = strsep(&p, "\n"))) {
124 key = strsep(&line, " ");
128 if (strcmp(key, event))
138 #if 0 /// UNNEEDED by elogind
139 bool cg_ns_supported(void) {
140 static thread_local int enabled = -1;
145 if (access("/proc/self/ns/cgroup", F_OK) == 0)
154 int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
155 _cleanup_free_ char *fs = NULL;
161 /* This is not recursive! */
163 r = cg_get_path(controller, path, NULL, &fs);
175 int cg_read_subgroup(DIR *d, char **fn) {
181 FOREACH_DIRENT_ALL(de, d, return -errno) {
184 if (de->d_type != DT_DIR)
187 if (dot_or_dot_dot(de->d_name))
190 b = strdup(de->d_name);
201 int cg_rmdir(const char *controller, const char *path) {
202 _cleanup_free_ char *p = NULL;
205 r = cg_get_path(controller, path, NULL, &p);
210 if (r < 0 && errno != ENOENT)
217 const char *controller,
222 cg_kill_log_func_t log_kill,
225 _cleanup_set_free_ Set *allocated_set = NULL;
232 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
233 * SIGCONT on SIGKILL. */
234 if (IN_SET(sig, SIGCONT, SIGKILL))
235 flags &= ~CGROUP_SIGCONT;
237 /* This goes through the tasks list and kills them all. This
238 * is repeated until no further processes are added to the
239 * tasks list, to properly handle forking processes */
242 s = allocated_set = set_new(NULL);
250 _cleanup_fclose_ FILE *f = NULL;
254 r = cg_enumerate_processes(controller, path, &f);
256 if (ret >= 0 && r != -ENOENT)
262 while ((r = cg_read_pid(f, &pid)) > 0) {
264 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
267 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
271 log_kill(pid, sig, userdata);
273 /* If we haven't killed this process yet, kill
275 if (kill(pid, sig) < 0) {
276 if (ret >= 0 && errno != ESRCH)
279 if (flags & CGROUP_SIGCONT)
280 (void) kill(pid, SIGCONT);
288 r = set_put(s, PID_TO_PTR(pid));
304 /* To avoid racing against processes which fork
305 * quicker than we can kill them we repeat this until
306 * no new pids need to be killed. */
313 int cg_kill_recursive(
314 const char *controller,
319 cg_kill_log_func_t log_kill,
322 _cleanup_set_free_ Set *allocated_set = NULL;
323 _cleanup_closedir_ DIR *d = NULL;
331 s = allocated_set = set_new(NULL);
336 ret = cg_kill(controller, path, sig, flags, s, log_kill, userdata);
338 r = cg_enumerate_subgroups(controller, path, &d);
340 if (ret >= 0 && r != -ENOENT)
346 while ((r = cg_read_subgroup(d, &fn)) > 0) {
347 _cleanup_free_ char *p = NULL;
349 p = strjoin(path, "/", fn);
354 r = cg_kill_recursive(controller, p, sig, flags, s, log_kill, userdata);
355 if (r != 0 && ret >= 0)
358 if (ret >= 0 && r < 0)
361 if (flags & CGROUP_REMOVE) {
362 r = cg_rmdir(controller, path);
363 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
378 _cleanup_set_free_ Set *s = NULL;
393 log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
394 cfrom, pfrom, cto, pto,
395 (flags & CGROUP_IGNORE_SELF)
396 ? "ignoring self" : "watching self");
398 _cleanup_fclose_ FILE *f = NULL;
402 r = cg_enumerate_processes(cfrom, pfrom, &f);
404 if (ret >= 0 && r != -ENOENT)
410 while ((r = cg_read_pid(f, &pid)) > 0) {
412 /* This might do weird stuff if we aren't a
413 * single-threaded program. However, we
414 * luckily know we are not */
415 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
418 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
421 /* Ignore kernel threads. Since they can only
422 * exist in the root cgroup, we only check for
425 (isempty(pfrom) || path_equal(pfrom, "/")) &&
426 is_kernel_thread(pid) > 0)
429 r = cg_attach(cto, pto, pid);
431 if (ret >= 0 && r != -ESRCH)
438 r = set_put(s, PID_TO_PTR(pid));
458 int cg_migrate_recursive(
465 _cleanup_closedir_ DIR *d = NULL;
474 ret = cg_migrate(cfrom, pfrom, cto, pto, flags);
476 r = cg_enumerate_subgroups(cfrom, pfrom, &d);
478 if (ret >= 0 && r != -ENOENT)
484 while ((r = cg_read_subgroup(d, &fn)) > 0) {
485 _cleanup_free_ char *p = NULL;
487 p = strjoin(pfrom, "/", fn);
492 r = cg_migrate_recursive(cfrom, p, cto, pto, flags);
493 if (r != 0 && ret >= 0)
497 if (r < 0 && ret >= 0)
500 if (flags & CGROUP_REMOVE) {
501 r = cg_rmdir(cfrom, pfrom);
502 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
509 int cg_migrate_recursive_fallback(
523 r = cg_migrate_recursive(cfrom, pfrom, cto, pto, flags);
525 char prefix[strlen(pto) + 1];
527 /* This didn't work? Then let's try all prefixes of the destination */
529 PATH_FOREACH_PREFIX(prefix, pto) {
532 q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, flags);
541 static const char *controller_to_dirname(const char *controller) {
546 /* Converts a controller name to the directory name below
547 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
548 * just cuts off the name= prefixed used for named
549 * hierarchies, if it is specified. */
551 e = startswith(controller, "name=");
558 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
565 dn = controller_to_dirname(controller);
567 if (isempty(path) && isempty(suffix))
568 t = strappend("/sys/fs/cgroup/", dn);
569 else if (isempty(path))
570 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix);
571 else if (isempty(suffix))
572 t = strjoin("/sys/fs/cgroup/", dn, "/", path);
574 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix);
582 static int join_path_unified(const char *path, const char *suffix, char **fs) {
587 if (isempty(path) && isempty(suffix))
588 t = strdup("/sys/fs/cgroup");
589 else if (isempty(path))
590 t = strappend("/sys/fs/cgroup/", suffix);
591 else if (isempty(suffix))
592 t = strappend("/sys/fs/cgroup/", path);
594 t = strjoin("/sys/fs/cgroup/", path, "/", suffix);
602 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
610 /* If no controller is specified, we return the path
611 * *below* the controllers, without any prefix. */
613 if (!path && !suffix)
621 t = strjoin(path, "/", suffix);
625 *fs = path_kill_slashes(t);
629 if (!cg_controller_is_valid(controller))
632 if (cg_all_unified())
633 r = join_path_unified(path, suffix, fs);
635 r = join_path_legacy(controller, path, suffix, fs);
639 path_kill_slashes(*fs);
643 static int controller_is_accessible(const char *controller) {
647 /* Checks whether a specific controller is accessible,
648 * i.e. its hierarchy mounted. In the unified hierarchy all
649 * controllers are considered accessible, except for the named
652 if (!cg_controller_is_valid(controller))
655 if (cg_all_unified()) {
656 /* We don't support named hierarchies if we are using
657 * the unified hierarchy. */
659 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
662 if (startswith(controller, "name="))
668 dn = controller_to_dirname(controller);
669 cc = strjoina("/sys/fs/cgroup/", dn);
671 if (laccess(cc, F_OK) < 0)
678 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
684 /* Check if the specified controller is actually accessible */
685 r = controller_is_accessible(controller);
689 return cg_get_path(controller, path, suffix, fs);
692 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
697 if (typeflag != FTW_DP)
700 if (ftwbuf->level < 1)
707 int cg_trim(const char *controller, const char *path, bool delete_root) {
708 _cleanup_free_ char *fs = NULL;
713 r = cg_get_path(controller, path, NULL, &fs);
718 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
728 if (rmdir(fs) < 0 && errno != ENOENT)
735 int cg_create(const char *controller, const char *path) {
736 _cleanup_free_ char *fs = NULL;
739 r = cg_get_path_and_check(controller, path, NULL, &fs);
743 r = mkdir_parents(fs, 0755);
747 if (mkdir(fs, 0755) < 0) {
758 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
763 r = cg_create(controller, path);
767 q = cg_attach(controller, path, pid);
771 /* This does not remove the cgroup on failure */
775 int cg_attach(const char *controller, const char *path, pid_t pid) {
776 _cleanup_free_ char *fs = NULL;
777 char c[DECIMAL_STR_MAX(pid_t) + 2];
783 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
790 xsprintf(c, PID_FMT "\n", pid);
792 return write_string_file(fs, c, 0);
795 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
802 r = cg_attach(controller, path, pid);
804 char prefix[strlen(path) + 1];
806 /* This didn't work? Then let's try all prefixes of
809 PATH_FOREACH_PREFIX(prefix, path) {
812 q = cg_attach(controller, prefix, pid);
821 #if 0 /// UNNEEDED by elogind
822 int cg_set_group_access(
823 const char *controller,
829 _cleanup_free_ char *fs = NULL;
832 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
835 if (mode != MODE_INVALID)
838 r = cg_get_path(controller, path, NULL, &fs);
842 return chmod_and_chown(fs, mode, uid, gid);
845 int cg_set_task_access(
846 const char *controller,
852 _cleanup_free_ char *fs = NULL, *procs = NULL;
857 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
860 if (mode != MODE_INVALID)
863 r = cg_get_path(controller, path, "cgroup.procs", &fs);
867 r = chmod_and_chown(fs, mode, uid, gid);
871 if (cg_unified(controller))
874 /* Compatibility, Always keep values for "tasks" in sync with
876 if (cg_get_path(controller, path, "tasks", &procs) >= 0)
877 (void) chmod_and_chown(procs, mode, uid, gid);
882 int cg_set_xattr(const char *controller, const char *path, const char *name, const void *value, size_t size, int flags) {
883 _cleanup_free_ char *fs = NULL;
888 assert(value || size <= 0);
890 r = cg_get_path(controller, path, NULL, &fs);
894 if (setxattr(fs, name, value, size, flags) < 0)
900 int cg_get_xattr(const char *controller, const char *path, const char *name, void *value, size_t size) {
901 _cleanup_free_ char *fs = NULL;
908 r = cg_get_path(controller, path, NULL, &fs);
912 n = getxattr(fs, name, value, size);
920 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
921 _cleanup_fclose_ FILE *f = NULL;
931 if (!cg_controller_is_valid(controller))
934 controller = SYSTEMD_CGROUP_CONTROLLER;
936 unified = cg_unified(controller);
938 cs = strlen(controller);
940 fs = procfs_file_alloca(pid, "cgroup");
941 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
942 pid, fs, controller);
945 return errno == ENOENT ? -ESRCH : -errno;
947 FOREACH_LINE(line, f, return -errno) {
953 e = startswith(line, "0:");
963 const char *word, *state;
966 l = strchr(line, ':');
976 FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
977 if (k == cs && memcmp(word, controller, cs) == 0) {
987 log_debug_elogind("Found %s:%s", line, e+1);
999 int cg_install_release_agent(const char *controller, const char *agent) {
1000 _cleanup_free_ char *fs = NULL, *contents = NULL;
1006 if (cg_unified(controller)) /* doesn't apply to unified hierarchy */
1009 r = cg_get_path(controller, NULL, "release_agent", &fs);
1013 r = read_one_line_file(fs, &contents);
1017 sc = strstrip(contents);
1019 r = write_string_file(fs, agent, 0);
1022 } else if (!path_equal(sc, agent))
1026 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1030 contents = mfree(contents);
1031 r = read_one_line_file(fs, &contents);
1035 sc = strstrip(contents);
1036 if (streq(sc, "0")) {
1037 r = write_string_file(fs, "1", 0);
1044 if (!streq(sc, "1"))
1050 int cg_uninstall_release_agent(const char *controller) {
1051 _cleanup_free_ char *fs = NULL;
1054 if (cg_unified(controller)) /* Doesn't apply to unified hierarchy */
1057 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1061 r = write_string_file(fs, "0", 0);
1067 r = cg_get_path(controller, NULL, "release_agent", &fs);
1071 r = write_string_file(fs, "", 0);
1078 int cg_is_empty(const char *controller, const char *path) {
1079 _cleanup_fclose_ FILE *f = NULL;
1085 r = cg_enumerate_processes(controller, path, &f);
1091 r = cg_read_pid(f, &pid);
1098 int cg_is_empty_recursive(const char *controller, const char *path) {
1103 /* The root cgroup is always populated */
1104 if (controller && (isempty(path) || path_equal(path, "/")))
1107 if (cg_unified(controller)) {
1108 _cleanup_free_ char *t = NULL;
1110 /* On the unified hierarchy we can check empty state
1111 * via the "populated" attribute of "cgroup.events". */
1113 r = cg_read_event(controller, path, "populated", &t);
1117 return streq(t, "0");
1119 _cleanup_closedir_ DIR *d = NULL;
1122 r = cg_is_empty(controller, path);
1126 r = cg_enumerate_subgroups(controller, path, &d);
1132 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1133 _cleanup_free_ char *p = NULL;
1135 p = strjoin(path, "/", fn);
1140 r = cg_is_empty_recursive(controller, p);
1151 int cg_split_spec(const char *spec, char **controller, char **path) {
1152 char *t = NULL, *u = NULL;
1158 if (!path_is_safe(spec))
1166 *path = path_kill_slashes(t);
1175 e = strchr(spec, ':');
1177 if (!cg_controller_is_valid(spec))
1194 t = strndup(spec, e-spec);
1197 if (!cg_controller_is_valid(t)) {
1211 if (!path_is_safe(u) ||
1212 !path_is_absolute(u)) {
1218 path_kill_slashes(u);
1234 int cg_mangle_path(const char *path, char **result) {
1235 _cleanup_free_ char *c = NULL, *p = NULL;
1242 /* First, check if it already is a filesystem path */
1243 if (path_startswith(path, "/sys/fs/cgroup")) {
1249 *result = path_kill_slashes(t);
1253 /* Otherwise, treat it as cg spec */
1254 r = cg_split_spec(path, &c, &p);
1258 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1261 int cg_get_root_path(char **path) {
1262 #if 0 /// elogind does not support systemd scopes and slices
1268 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1272 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1274 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1276 e = endswith(p, "/system"); /* even more legacy */
1284 return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1288 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1289 _cleanup_free_ char *rt = NULL;
1297 /* If the root was specified let's use that, otherwise
1298 * let's determine it from PID 1 */
1300 r = cg_get_root_path(&rt);
1305 log_debug_elogind("Determined root path: \"%s\"", root);
1308 p = path_startswith(cgroup, root);
1309 #if 0 /// With other controllers, elogind might end up in /elogind, and *p is 0
1310 if (p && p > cgroup)
1312 if (p && p[0] && (p > cgroup))
1321 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1322 _cleanup_free_ char *raw = NULL;
1329 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1333 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1334 raw, pid, root ? root : "NULL");
1335 r = cg_shift_path(raw, root, &c);
1351 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1356 #if 0 /// UNNEEDED by elogind
1357 int cg_path_decode_unit(const char *cgroup, char **unit) {
1364 n = strcspn(cgroup, "/");
1368 c = strndupa(cgroup, n);
1371 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1382 static bool valid_slice_name(const char *p, size_t n) {
1387 if (n < strlen("x.slice"))
1390 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1396 c = cg_unescape(buf);
1398 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1404 static const char *skip_slices(const char *p) {
1407 /* Skips over all slice assignments */
1412 p += strspn(p, "/");
1414 n = strcspn(p, "/");
1415 if (!valid_slice_name(p, n))
1422 int cg_path_get_unit(const char *path, char **ret) {
1430 e = skip_slices(path);
1432 r = cg_path_decode_unit(e, &unit);
1436 /* We skipped over the slices, don't accept any now */
1437 if (endswith(unit, ".slice")) {
1446 int cg_pid_get_unit(pid_t pid, char **unit) {
1447 _cleanup_free_ char *cgroup = NULL;
1452 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1456 return cg_path_get_unit(cgroup, unit);
1460 * Skip session-*.scope, but require it to be there.
1462 static const char *skip_session(const char *p) {
1468 p += strspn(p, "/");
1470 n = strcspn(p, "/");
1471 if (n < strlen("session-x.scope"))
1474 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1475 char buf[n - 8 - 6 + 1];
1477 memcpy(buf, p + 8, n - 8 - 6);
1480 /* Note that session scopes never need unescaping,
1481 * since they cannot conflict with the kernel's own
1482 * names, hence we don't need to call cg_unescape()
1485 if (!session_id_valid(buf))
1489 p += strspn(p, "/");
1497 * Skip user@*.service, but require it to be there.
1499 static const char *skip_user_manager(const char *p) {
1505 p += strspn(p, "/");
1507 n = strcspn(p, "/");
1508 if (n < strlen("user@x.service"))
1511 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1512 char buf[n - 5 - 8 + 1];
1514 memcpy(buf, p + 5, n - 5 - 8);
1517 /* Note that user manager services never need unescaping,
1518 * since they cannot conflict with the kernel's own
1519 * names, hence we don't need to call cg_unescape()
1522 if (parse_uid(buf, NULL) < 0)
1526 p += strspn(p, "/");
1534 static const char *skip_user_prefix(const char *path) {
1539 /* Skip slices, if there are any */
1540 e = skip_slices(path);
1542 /* Skip the user manager, if it's in the path now... */
1543 t = skip_user_manager(e);
1547 /* Alternatively skip the user session if it is in the path... */
1548 return skip_session(e);
1551 int cg_path_get_user_unit(const char *path, char **ret) {
1557 t = skip_user_prefix(path);
1561 /* And from here on it looks pretty much the same as for a
1562 * system unit, hence let's use the same parser from here
1564 return cg_path_get_unit(t, ret);
1567 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1568 _cleanup_free_ char *cgroup = NULL;
1573 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1577 return cg_path_get_user_unit(cgroup, unit);
1580 int cg_path_get_machine_name(const char *path, char **machine) {
1581 _cleanup_free_ char *u = NULL;
1585 r = cg_path_get_unit(path, &u);
1589 sl = strjoina("/run/systemd/machines/unit:", u);
1590 return readlink_malloc(sl, machine);
1593 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1594 _cleanup_free_ char *cgroup = NULL;
1599 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1603 return cg_path_get_machine_name(cgroup, machine);
1607 int cg_path_get_session(const char *path, char **session) {
1608 #if 0 /// UNNEEDED by elogind
1609 _cleanup_free_ char *unit = NULL;
1615 r = cg_path_get_unit(path, &unit);
1619 start = startswith(unit, "session-");
1622 end = endswith(start, ".scope");
1627 if (!session_id_valid(start))
1630 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1631 wrinkle is that SESSION might be escaped. */
1632 const char *e, *n, *start;
1635 log_debug_elogind("path is \"%s\"", path);
1636 assert(path[0] == '/');
1639 n = strchrnul(e, '/');
1643 start = strndupa(e, n - e);
1644 start = cg_unescape(start);
1653 log_debug_elogind("found session: \"%s\"", start);
1664 int cg_pid_get_session(pid_t pid, char **session) {
1665 _cleanup_free_ char *cgroup = NULL;
1668 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1672 return cg_path_get_session(cgroup, session);
1675 #if 0 /// UNNEEDED by elogind
1676 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1677 _cleanup_free_ char *slice = NULL;
1683 r = cg_path_get_slice(path, &slice);
1687 start = startswith(slice, "user-");
1690 end = endswith(start, ".slice");
1695 if (parse_uid(start, uid) < 0)
1701 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1702 _cleanup_free_ char *cgroup = NULL;
1705 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1709 return cg_path_get_owner_uid(cgroup, uid);
1712 int cg_path_get_slice(const char *p, char **slice) {
1713 const char *e = NULL;
1718 /* Finds the right-most slice unit from the beginning, but
1719 * stops before we come to the first non-slice unit. */
1724 p += strspn(p, "/");
1726 n = strcspn(p, "/");
1727 if (!valid_slice_name(p, n)) {
1732 s = strdup(SPECIAL_ROOT_SLICE);
1740 return cg_path_decode_unit(e, slice);
1748 int cg_pid_get_slice(pid_t pid, char **slice) {
1749 _cleanup_free_ char *cgroup = NULL;
1754 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1758 return cg_path_get_slice(cgroup, slice);
1761 int cg_path_get_user_slice(const char *p, char **slice) {
1766 t = skip_user_prefix(p);
1770 /* And now it looks pretty much the same as for a system
1771 * slice, so let's just use the same parser from here on. */
1772 return cg_path_get_slice(t, slice);
1775 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1776 _cleanup_free_ char *cgroup = NULL;
1781 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1785 return cg_path_get_user_slice(cgroup, slice);
1789 char *cg_escape(const char *p) {
1790 bool need_prefix = false;
1792 /* This implements very minimal escaping for names to be used
1793 * as file names in the cgroup tree: any name which might
1794 * conflict with a kernel name or is prefixed with '_' is
1795 * prefixed with a '_'. That way, when reading cgroup names it
1796 * is sufficient to remove a single prefixing underscore if
1799 /* The return value of this function (unlike cg_unescape())
1805 streq(p, "notify_on_release") ||
1806 streq(p, "release_agent") ||
1807 streq(p, "tasks") ||
1808 startswith(p, "cgroup."))
1813 dot = strrchr(p, '.');
1818 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1821 n = cgroup_controller_to_string(c);
1826 if (memcmp(p, n, l) != 0)
1836 return strappend("_", p);
1841 char *cg_unescape(const char *p) {
1844 /* The return value of this function (unlike cg_escape())
1845 * doesn't need free()! */
1853 #define CONTROLLER_VALID \
1857 bool cg_controller_is_valid(const char *p) {
1863 s = startswith(p, "name=");
1867 if (*p == 0 || *p == '_')
1870 for (t = p; *t; t++)
1871 if (!strchr(CONTROLLER_VALID, *t))
1874 if (t - p > FILENAME_MAX)
1880 #if 0 /// UNNEEDED by elogind
1881 int cg_slice_to_path(const char *unit, char **ret) {
1882 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1889 if (streq(unit, SPECIAL_ROOT_SLICE)) {
1899 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1902 if (!endswith(unit, ".slice"))
1905 r = unit_name_to_prefix(unit, &p);
1909 dash = strchr(p, '-');
1911 /* Don't allow initial dashes */
1916 _cleanup_free_ char *escaped = NULL;
1917 char n[dash - p + sizeof(".slice")];
1919 /* Don't allow trailing or double dashes */
1920 if (dash[1] == 0 || dash[1] == '-')
1923 strcpy(stpncpy(n, p, dash - p), ".slice");
1924 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1927 escaped = cg_escape(n);
1931 if (!strextend(&s, escaped, "/", NULL))
1934 dash = strchr(dash+1, '-');
1937 e = cg_escape(unit);
1941 if (!strextend(&s, e, NULL))
1951 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1952 _cleanup_free_ char *p = NULL;
1955 r = cg_get_path(controller, path, attribute, &p);
1959 return write_string_file(p, value, 0);
1962 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1963 _cleanup_free_ char *p = NULL;
1966 r = cg_get_path(controller, path, attribute, &p);
1970 return read_one_line_file(p, ret);
1973 #if 0 /// UNNEEDED by elogind
1974 int cg_get_keyed_attribute(const char *controller, const char *path, const char *attribute, const char **keys, char **values) {
1975 _cleanup_free_ char *filename = NULL, *content = NULL;
1979 for (i = 0; keys[i]; i++)
1982 r = cg_get_path(controller, path, attribute, &filename);
1986 r = read_full_file(filename, &content, NULL);
1991 while ((line = strsep(&p, "\n"))) {
1994 key = strsep(&line, " ");
1996 for (i = 0; keys[i]; i++) {
1997 if (streq(key, keys[i])) {
1998 values[i] = strdup(line);
2004 for (i = 0; keys[i]; i++) {
2006 for (i = 0; keys[i]; i++) {
2017 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
2021 /* This one will create a cgroup in our private tree, but also
2022 * duplicate it in the trees specified in mask, and remove it
2025 /* First create the cgroup in our own hierarchy. */
2026 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
2030 /* If we are in the unified hierarchy, we are done now */
2031 if (cg_all_unified())
2034 /* Otherwise, do the same in the other hierarchies */
2035 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2036 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2039 n = cgroup_controller_to_string(c);
2042 (void) cg_create(n, path);
2043 else if (supported & bit)
2044 (void) cg_trim(n, path, true);
2050 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
2054 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
2058 if (cg_all_unified())
2061 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2062 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2063 const char *p = NULL;
2065 if (!(supported & bit))
2069 p = path_callback(bit, userdata);
2074 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
2080 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2085 SET_FOREACH(pidp, pids, i) {
2086 pid_t pid = PTR_TO_PID(pidp);
2089 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2090 if (q < 0 && r >= 0)
2097 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2101 if (!path_equal(from, to)) {
2102 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2107 if (cg_all_unified())
2110 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2111 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2112 const char *p = NULL;
2114 if (!(supported & bit))
2118 p = to_callback(bit, userdata);
2123 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2129 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2133 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2137 if (cg_all_unified())
2140 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2141 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2143 if (!(supported & bit))
2146 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2153 int cg_mask_supported(CGroupMask *ret) {
2154 CGroupMask mask = 0;
2157 /* Determines the mask of supported cgroup controllers. Only
2158 * includes controllers we can make sense of and that are
2159 * actually accessible. */
2161 if (cg_all_unified()) {
2162 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2165 /* In the unified hierarchy we can read the supported
2166 * and accessible controllers from a the top-level
2167 * cgroup attribute */
2169 r = cg_get_root_path(&root);
2173 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2177 r = read_one_line_file(path, &controllers);
2183 _cleanup_free_ char *n = NULL;
2186 r = extract_first_word(&c, &n, NULL, 0);
2192 v = cgroup_controller_from_string(n);
2196 mask |= CGROUP_CONTROLLER_TO_MASK(v);
2199 /* Currently, we support the cpu, memory, io and pids
2200 * controller in the unified hierarchy, mask
2201 * everything else off. */
2202 mask &= CGROUP_MASK_CPU | CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2207 /* In the legacy hierarchy, we check whether which
2208 * hierarchies are mounted. */
2210 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2213 n = cgroup_controller_to_string(c);
2214 if (controller_is_accessible(n) >= 0)
2215 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2223 #if 0 /// UNNEEDED by elogind
2224 int cg_kernel_controllers(Set *controllers) {
2225 _cleanup_fclose_ FILE *f = NULL;
2229 assert(controllers);
2231 /* Determines the full list of kernel-known controllers. Might
2232 * include controllers we don't actually support, arbitrary
2233 * named hierarchies and controllers that aren't currently
2234 * accessible (because not mounted). */
2236 f = fopen("/proc/cgroups", "re");
2238 if (errno == ENOENT)
2243 /* Ignore the header line */
2244 (void) fgets(buf, sizeof(buf), f);
2251 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2256 if (ferror(f) && errno > 0)
2267 if (!cg_controller_is_valid(controller)) {
2272 r = set_consume(controllers, controller);
2281 static thread_local CGroupUnified unified_cache = CGROUP_UNIFIED_UNKNOWN;
2283 static int cg_update_unified(void) {
2287 /* Checks if we support the unified hierarchy. Returns an
2288 * error when the cgroup hierarchies aren't mounted yet or we
2289 * have any other trouble determining if the unified hierarchy
2292 if (unified_cache >= CGROUP_UNIFIED_NONE)
2295 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2298 #if 0 /// UNNEEDED by elogind
2299 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC))
2300 unified_cache = CGROUP_UNIFIED_ALL;
2301 else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2302 if (statfs("/sys/fs/cgroup/systemd/", &fs) < 0)
2305 unified_cache = F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC) ?
2306 CGROUP_UNIFIED_SYSTEMD : CGROUP_UNIFIED_NONE;
2310 /* elogind can not support the unified hierarchy as a controller,
2311 * so always assume a classical hierarchy.
2312 * If, and only *if*, someone really wants to substitute systemd-login
2313 * in an environment managed by systemd with elogind, we might have to
2314 * add such a support. */
2315 unified_cache = CGROUP_UNIFIED_NONE;
2321 bool cg_unified(const char *controller) {
2323 assert(cg_update_unified() >= 0);
2325 if (streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER))
2326 return unified_cache >= CGROUP_UNIFIED_SYSTEMD;
2328 return unified_cache >= CGROUP_UNIFIED_ALL;
2331 bool cg_all_unified(void) {
2333 return cg_unified(NULL);
2336 #if 0 /// UNNEEDED by elogind
2337 int cg_unified_flush(void) {
2338 unified_cache = CGROUP_UNIFIED_UNKNOWN;
2340 return cg_update_unified();
2343 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2344 _cleanup_free_ char *fs = NULL;
2353 if (!cg_all_unified()) /* on the legacy hiearchy there's no joining of controllers defined */
2356 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2360 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2361 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2364 if (!(supported & bit))
2367 n = cgroup_controller_to_string(c);
2369 char s[1 + strlen(n) + 1];
2371 s[0] = mask & bit ? '+' : '-';
2374 r = write_string_file(fs, s, 0);
2376 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2383 bool cg_is_unified_wanted(void) {
2384 static thread_local int wanted = -1;
2388 /* If the hierarchy is already mounted, then follow whatever
2389 * was chosen for it. */
2390 if (cg_unified_flush() >= 0)
2391 return cg_all_unified();
2393 /* Otherwise, let's see what the kernel command line has to
2394 * say. Since checking that is expensive, let's cache the
2399 r = proc_cmdline_get_bool("systemd.unified_cgroup_hierarchy", &b);
2403 return (wanted = r > 0 ? b : false);
2406 bool cg_is_legacy_wanted(void) {
2407 return !cg_is_unified_wanted();
2410 bool cg_is_unified_systemd_controller_wanted(void) {
2411 static thread_local int wanted = -1;
2415 /* If the unified hierarchy is requested in full, no need to
2416 * bother with this. */
2417 if (cg_is_unified_wanted())
2420 /* If the hierarchy is already mounted, then follow whatever
2421 * was chosen for it. */
2422 if (cg_unified_flush() >= 0)
2423 return cg_unified(SYSTEMD_CGROUP_CONTROLLER);
2425 /* Otherwise, let's see what the kernel command line has to
2426 * say. Since checking that is expensive, let's cache the
2431 r = proc_cmdline_get_bool("systemd.legacy_systemd_cgroup_controller", &b);
2436 bool cg_is_legacy_wanted(void) {
2438 /* The meaning of the kernel option is reversed wrt. to the return value
2439 * of this function, hence the negation. */
2440 return (wanted = r > 0 ? !b : false);
2441 return (wanted = r > 0 ? b : false);
2444 bool cg_is_legacy_systemd_controller_wanted(void) {
2445 return cg_is_legacy_wanted() && !cg_is_unified_systemd_controller_wanted();
2449 #if 0 /// UNNEEDED by elogind
2450 int cg_weight_parse(const char *s, uint64_t *ret) {
2455 *ret = CGROUP_WEIGHT_INVALID;
2459 r = safe_atou64(s, &u);
2463 if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2470 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2471 [CGROUP_IO_RBPS_MAX] = CGROUP_LIMIT_MAX,
2472 [CGROUP_IO_WBPS_MAX] = CGROUP_LIMIT_MAX,
2473 [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2474 [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2477 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2478 [CGROUP_IO_RBPS_MAX] = "IOReadBandwidthMax",
2479 [CGROUP_IO_WBPS_MAX] = "IOWriteBandwidthMax",
2480 [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2481 [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2484 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2486 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2491 *ret = CGROUP_CPU_SHARES_INVALID;
2495 r = safe_atou64(s, &u);
2499 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2506 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2511 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2515 r = safe_atou64(s, &u);
2519 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2527 bool is_cgroup_fs(const struct statfs *s) {
2528 return is_fs_type(s, CGROUP_SUPER_MAGIC) ||
2529 is_fs_type(s, CGROUP2_SUPER_MAGIC);
2532 bool fd_is_cgroup_fs(int fd) {
2535 if (fstatfs(fd, &s) < 0)
2538 return is_cgroup_fs(&s);
2541 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2542 [CGROUP_CONTROLLER_CPU] = "cpu",
2543 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2544 [CGROUP_CONTROLLER_IO] = "io",
2545 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2546 [CGROUP_CONTROLLER_MEMORY] = "memory",
2547 [CGROUP_CONTROLLER_DEVICES] = "devices",
2548 [CGROUP_CONTROLLER_PIDS] = "pids",
2551 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);