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 unified = cg_all_unified();
637 r = join_path_unified(path, suffix, fs);
639 r = join_path_legacy(controller, path, suffix, fs);
643 path_kill_slashes(*fs);
647 static int controller_is_accessible(const char *controller) {
652 /* Checks whether a specific controller is accessible,
653 * i.e. its hierarchy mounted. In the unified hierarchy all
654 * controllers are considered accessible, except for the named
657 if (!cg_controller_is_valid(controller))
660 unified = cg_all_unified();
664 /* We don't support named hierarchies if we are using
665 * the unified hierarchy. */
667 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
670 if (startswith(controller, "name="))
676 dn = controller_to_dirname(controller);
677 cc = strjoina("/sys/fs/cgroup/", dn);
679 if (laccess(cc, F_OK) < 0)
686 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
692 /* Check if the specified controller is actually accessible */
693 r = controller_is_accessible(controller);
697 return cg_get_path(controller, path, suffix, fs);
700 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
705 if (typeflag != FTW_DP)
708 if (ftwbuf->level < 1)
715 int cg_trim(const char *controller, const char *path, bool delete_root) {
716 _cleanup_free_ char *fs = NULL;
721 r = cg_get_path(controller, path, NULL, &fs);
726 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
736 if (rmdir(fs) < 0 && errno != ENOENT)
743 int cg_create(const char *controller, const char *path) {
744 _cleanup_free_ char *fs = NULL;
747 r = cg_get_path_and_check(controller, path, NULL, &fs);
751 r = mkdir_parents(fs, 0755);
755 if (mkdir(fs, 0755) < 0) {
766 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
771 r = cg_create(controller, path);
775 q = cg_attach(controller, path, pid);
779 /* This does not remove the cgroup on failure */
783 int cg_attach(const char *controller, const char *path, pid_t pid) {
784 _cleanup_free_ char *fs = NULL;
785 char c[DECIMAL_STR_MAX(pid_t) + 2];
791 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
798 xsprintf(c, PID_FMT "\n", pid);
800 return write_string_file(fs, c, 0);
803 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
810 r = cg_attach(controller, path, pid);
812 char prefix[strlen(path) + 1];
814 /* This didn't work? Then let's try all prefixes of
817 PATH_FOREACH_PREFIX(prefix, path) {
820 q = cg_attach(controller, prefix, pid);
829 #if 0 /// UNNEEDED by elogind
830 int cg_set_group_access(
831 const char *controller,
837 _cleanup_free_ char *fs = NULL;
840 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
843 if (mode != MODE_INVALID)
846 r = cg_get_path(controller, path, NULL, &fs);
850 return chmod_and_chown(fs, mode, uid, gid);
853 int cg_set_task_access(
854 const char *controller,
860 _cleanup_free_ char *fs = NULL, *procs = NULL;
865 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
868 if (mode != MODE_INVALID)
871 r = cg_get_path(controller, path, "cgroup.procs", &fs);
875 r = chmod_and_chown(fs, mode, uid, gid);
879 unified = cg_unified(controller);
885 /* Compatibility, Always keep values for "tasks" in sync with
887 if (cg_get_path(controller, path, "tasks", &procs) >= 0)
888 (void) chmod_and_chown(procs, mode, uid, gid);
893 int cg_set_xattr(const char *controller, const char *path, const char *name, const void *value, size_t size, int flags) {
894 _cleanup_free_ char *fs = NULL;
899 assert(value || size <= 0);
901 r = cg_get_path(controller, path, NULL, &fs);
905 if (setxattr(fs, name, value, size, flags) < 0)
911 int cg_get_xattr(const char *controller, const char *path, const char *name, void *value, size_t size) {
912 _cleanup_free_ char *fs = NULL;
919 r = cg_get_path(controller, path, NULL, &fs);
923 n = getxattr(fs, name, value, size);
931 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
932 _cleanup_fclose_ FILE *f = NULL;
942 if (!cg_controller_is_valid(controller))
945 controller = SYSTEMD_CGROUP_CONTROLLER;
947 unified = cg_unified(controller);
951 cs = strlen(controller);
953 fs = procfs_file_alloca(pid, "cgroup");
954 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
955 pid, fs, controller);
958 return errno == ENOENT ? -ESRCH : -errno;
960 FOREACH_LINE(line, f, return -errno) {
966 e = startswith(line, "0:");
976 const char *word, *state;
979 l = strchr(line, ':');
989 FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
990 if (k == cs && memcmp(word, controller, cs) == 0) {
1000 log_debug_elogind("Found %s:%s", line, e+1);
1012 int cg_install_release_agent(const char *controller, const char *agent) {
1013 _cleanup_free_ char *fs = NULL, *contents = NULL;
1019 unified = cg_unified(controller);
1022 if (unified) /* doesn't apply to unified hierarchy */
1025 r = cg_get_path(controller, NULL, "release_agent", &fs);
1029 r = read_one_line_file(fs, &contents);
1033 sc = strstrip(contents);
1035 r = write_string_file(fs, agent, 0);
1038 } else if (!path_equal(sc, agent))
1042 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1046 contents = mfree(contents);
1047 r = read_one_line_file(fs, &contents);
1051 sc = strstrip(contents);
1052 if (streq(sc, "0")) {
1053 r = write_string_file(fs, "1", 0);
1060 if (!streq(sc, "1"))
1066 int cg_uninstall_release_agent(const char *controller) {
1067 _cleanup_free_ char *fs = NULL;
1070 unified = cg_unified(controller);
1073 if (unified) /* Doesn't apply to unified hierarchy */
1076 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1080 r = write_string_file(fs, "0", 0);
1086 r = cg_get_path(controller, NULL, "release_agent", &fs);
1090 r = write_string_file(fs, "", 0);
1097 int cg_is_empty(const char *controller, const char *path) {
1098 _cleanup_fclose_ FILE *f = NULL;
1104 r = cg_enumerate_processes(controller, path, &f);
1110 r = cg_read_pid(f, &pid);
1117 int cg_is_empty_recursive(const char *controller, const char *path) {
1122 /* The root cgroup is always populated */
1123 if (controller && (isempty(path) || path_equal(path, "/")))
1126 unified = cg_unified(controller);
1131 _cleanup_free_ char *t = NULL;
1133 /* On the unified hierarchy we can check empty state
1134 * via the "populated" attribute of "cgroup.events". */
1136 r = cg_read_event(controller, path, "populated", &t);
1140 return streq(t, "0");
1142 _cleanup_closedir_ DIR *d = NULL;
1145 r = cg_is_empty(controller, path);
1149 r = cg_enumerate_subgroups(controller, path, &d);
1155 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1156 _cleanup_free_ char *p = NULL;
1158 p = strjoin(path, "/", fn);
1163 r = cg_is_empty_recursive(controller, p);
1174 int cg_split_spec(const char *spec, char **controller, char **path) {
1175 char *t = NULL, *u = NULL;
1181 if (!path_is_safe(spec))
1189 *path = path_kill_slashes(t);
1198 e = strchr(spec, ':');
1200 if (!cg_controller_is_valid(spec))
1217 t = strndup(spec, e-spec);
1220 if (!cg_controller_is_valid(t)) {
1234 if (!path_is_safe(u) ||
1235 !path_is_absolute(u)) {
1241 path_kill_slashes(u);
1257 int cg_mangle_path(const char *path, char **result) {
1258 _cleanup_free_ char *c = NULL, *p = NULL;
1265 /* First, check if it already is a filesystem path */
1266 if (path_startswith(path, "/sys/fs/cgroup")) {
1272 *result = path_kill_slashes(t);
1276 /* Otherwise, treat it as cg spec */
1277 r = cg_split_spec(path, &c, &p);
1281 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1284 int cg_get_root_path(char **path) {
1285 #if 0 /// elogind does not support systemd scopes and slices
1291 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1295 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1297 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1299 e = endswith(p, "/system"); /* even more legacy */
1307 return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1311 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1312 _cleanup_free_ char *rt = NULL;
1320 /* If the root was specified let's use that, otherwise
1321 * let's determine it from PID 1 */
1323 r = cg_get_root_path(&rt);
1328 log_debug_elogind("Determined root path: \"%s\"", root);
1331 p = path_startswith(cgroup, root);
1332 #if 0 /// With other controllers, elogind might end up in /elogind, and *p is 0
1333 if (p && p > cgroup)
1335 if (p && p[0] && (p > cgroup))
1344 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1345 _cleanup_free_ char *raw = NULL;
1352 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1356 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1357 raw, pid, root ? root : "NULL");
1358 r = cg_shift_path(raw, root, &c);
1374 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1379 #if 0 /// UNNEEDED by elogind
1380 int cg_path_decode_unit(const char *cgroup, char **unit) {
1387 n = strcspn(cgroup, "/");
1391 c = strndupa(cgroup, n);
1394 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1405 static bool valid_slice_name(const char *p, size_t n) {
1410 if (n < strlen("x.slice"))
1413 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1419 c = cg_unescape(buf);
1421 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1427 static const char *skip_slices(const char *p) {
1430 /* Skips over all slice assignments */
1435 p += strspn(p, "/");
1437 n = strcspn(p, "/");
1438 if (!valid_slice_name(p, n))
1445 int cg_path_get_unit(const char *path, char **ret) {
1453 e = skip_slices(path);
1455 r = cg_path_decode_unit(e, &unit);
1459 /* We skipped over the slices, don't accept any now */
1460 if (endswith(unit, ".slice")) {
1469 int cg_pid_get_unit(pid_t pid, char **unit) {
1470 _cleanup_free_ char *cgroup = NULL;
1475 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1479 return cg_path_get_unit(cgroup, unit);
1483 * Skip session-*.scope, but require it to be there.
1485 static const char *skip_session(const char *p) {
1491 p += strspn(p, "/");
1493 n = strcspn(p, "/");
1494 if (n < strlen("session-x.scope"))
1497 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1498 char buf[n - 8 - 6 + 1];
1500 memcpy(buf, p + 8, n - 8 - 6);
1503 /* Note that session scopes never need unescaping,
1504 * since they cannot conflict with the kernel's own
1505 * names, hence we don't need to call cg_unescape()
1508 if (!session_id_valid(buf))
1512 p += strspn(p, "/");
1520 * Skip user@*.service, but require it to be there.
1522 static const char *skip_user_manager(const char *p) {
1528 p += strspn(p, "/");
1530 n = strcspn(p, "/");
1531 if (n < strlen("user@x.service"))
1534 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1535 char buf[n - 5 - 8 + 1];
1537 memcpy(buf, p + 5, n - 5 - 8);
1540 /* Note that user manager services never need unescaping,
1541 * since they cannot conflict with the kernel's own
1542 * names, hence we don't need to call cg_unescape()
1545 if (parse_uid(buf, NULL) < 0)
1549 p += strspn(p, "/");
1557 static const char *skip_user_prefix(const char *path) {
1562 /* Skip slices, if there are any */
1563 e = skip_slices(path);
1565 /* Skip the user manager, if it's in the path now... */
1566 t = skip_user_manager(e);
1570 /* Alternatively skip the user session if it is in the path... */
1571 return skip_session(e);
1574 int cg_path_get_user_unit(const char *path, char **ret) {
1580 t = skip_user_prefix(path);
1584 /* And from here on it looks pretty much the same as for a
1585 * system unit, hence let's use the same parser from here
1587 return cg_path_get_unit(t, ret);
1590 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1591 _cleanup_free_ char *cgroup = NULL;
1596 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1600 return cg_path_get_user_unit(cgroup, unit);
1603 int cg_path_get_machine_name(const char *path, char **machine) {
1604 _cleanup_free_ char *u = NULL;
1608 r = cg_path_get_unit(path, &u);
1612 sl = strjoina("/run/systemd/machines/unit:", u);
1613 return readlink_malloc(sl, machine);
1616 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1617 _cleanup_free_ char *cgroup = NULL;
1622 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1626 return cg_path_get_machine_name(cgroup, machine);
1630 int cg_path_get_session(const char *path, char **session) {
1631 #if 0 /// UNNEEDED by elogind
1632 _cleanup_free_ char *unit = NULL;
1638 r = cg_path_get_unit(path, &unit);
1642 start = startswith(unit, "session-");
1645 end = endswith(start, ".scope");
1650 if (!session_id_valid(start))
1653 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1654 wrinkle is that SESSION might be escaped. */
1655 const char *e, *n, *start;
1658 log_debug_elogind("path is \"%s\"", path);
1659 assert(path[0] == '/');
1662 n = strchrnul(e, '/');
1666 start = strndupa(e, n - e);
1667 start = cg_unescape(start);
1676 log_debug_elogind("found session: \"%s\"", start);
1687 int cg_pid_get_session(pid_t pid, char **session) {
1688 _cleanup_free_ char *cgroup = NULL;
1691 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1695 return cg_path_get_session(cgroup, session);
1698 #if 0 /// UNNEEDED by elogind
1699 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1700 _cleanup_free_ char *slice = NULL;
1706 r = cg_path_get_slice(path, &slice);
1710 start = startswith(slice, "user-");
1713 end = endswith(start, ".slice");
1718 if (parse_uid(start, uid) < 0)
1724 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1725 _cleanup_free_ char *cgroup = NULL;
1728 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1732 return cg_path_get_owner_uid(cgroup, uid);
1735 int cg_path_get_slice(const char *p, char **slice) {
1736 const char *e = NULL;
1741 /* Finds the right-most slice unit from the beginning, but
1742 * stops before we come to the first non-slice unit. */
1747 p += strspn(p, "/");
1749 n = strcspn(p, "/");
1750 if (!valid_slice_name(p, n)) {
1755 s = strdup(SPECIAL_ROOT_SLICE);
1763 return cg_path_decode_unit(e, slice);
1771 int cg_pid_get_slice(pid_t pid, char **slice) {
1772 _cleanup_free_ char *cgroup = NULL;
1777 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1781 return cg_path_get_slice(cgroup, slice);
1784 int cg_path_get_user_slice(const char *p, char **slice) {
1789 t = skip_user_prefix(p);
1793 /* And now it looks pretty much the same as for a system
1794 * slice, so let's just use the same parser from here on. */
1795 return cg_path_get_slice(t, slice);
1798 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1799 _cleanup_free_ char *cgroup = NULL;
1804 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1808 return cg_path_get_user_slice(cgroup, slice);
1812 char *cg_escape(const char *p) {
1813 bool need_prefix = false;
1815 /* This implements very minimal escaping for names to be used
1816 * as file names in the cgroup tree: any name which might
1817 * conflict with a kernel name or is prefixed with '_' is
1818 * prefixed with a '_'. That way, when reading cgroup names it
1819 * is sufficient to remove a single prefixing underscore if
1822 /* The return value of this function (unlike cg_unescape())
1828 streq(p, "notify_on_release") ||
1829 streq(p, "release_agent") ||
1830 streq(p, "tasks") ||
1831 startswith(p, "cgroup."))
1836 dot = strrchr(p, '.');
1841 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1844 n = cgroup_controller_to_string(c);
1849 if (memcmp(p, n, l) != 0)
1859 return strappend("_", p);
1864 char *cg_unescape(const char *p) {
1867 /* The return value of this function (unlike cg_escape())
1868 * doesn't need free()! */
1876 #define CONTROLLER_VALID \
1880 bool cg_controller_is_valid(const char *p) {
1886 s = startswith(p, "name=");
1890 if (*p == 0 || *p == '_')
1893 for (t = p; *t; t++)
1894 if (!strchr(CONTROLLER_VALID, *t))
1897 if (t - p > FILENAME_MAX)
1903 #if 0 /// UNNEEDED by elogind
1904 int cg_slice_to_path(const char *unit, char **ret) {
1905 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1912 if (streq(unit, SPECIAL_ROOT_SLICE)) {
1922 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1925 if (!endswith(unit, ".slice"))
1928 r = unit_name_to_prefix(unit, &p);
1932 dash = strchr(p, '-');
1934 /* Don't allow initial dashes */
1939 _cleanup_free_ char *escaped = NULL;
1940 char n[dash - p + sizeof(".slice")];
1942 /* Don't allow trailing or double dashes */
1943 if (dash[1] == 0 || dash[1] == '-')
1946 strcpy(stpncpy(n, p, dash - p), ".slice");
1947 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1950 escaped = cg_escape(n);
1954 if (!strextend(&s, escaped, "/", NULL))
1957 dash = strchr(dash+1, '-');
1960 e = cg_escape(unit);
1964 if (!strextend(&s, e, NULL))
1974 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1975 _cleanup_free_ char *p = NULL;
1978 r = cg_get_path(controller, path, attribute, &p);
1982 return write_string_file(p, value, 0);
1985 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1986 _cleanup_free_ char *p = NULL;
1989 r = cg_get_path(controller, path, attribute, &p);
1993 return read_one_line_file(p, ret);
1996 #if 0 /// UNNEEDED by elogind
1997 int cg_get_keyed_attribute(const char *controller, const char *path, const char *attribute, const char **keys, char **values) {
1998 _cleanup_free_ char *filename = NULL, *content = NULL;
2002 for (i = 0; keys[i]; i++)
2005 r = cg_get_path(controller, path, attribute, &filename);
2009 r = read_full_file(filename, &content, NULL);
2014 while ((line = strsep(&p, "\n"))) {
2017 key = strsep(&line, " ");
2019 for (i = 0; keys[i]; i++) {
2020 if (streq(key, keys[i])) {
2021 values[i] = strdup(line);
2027 for (i = 0; keys[i]; i++) {
2029 for (i = 0; keys[i]; i++) {
2040 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
2044 /* This one will create a cgroup in our private tree, but also
2045 * duplicate it in the trees specified in mask, and remove it
2048 /* First create the cgroup in our own hierarchy. */
2049 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
2053 /* If we are in the unified hierarchy, we are done now */
2054 unified = cg_all_unified();
2060 /* Otherwise, do the same in the other hierarchies */
2061 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2062 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2065 n = cgroup_controller_to_string(c);
2068 (void) cg_create(n, path);
2069 else if (supported & bit)
2070 (void) cg_trim(n, path, true);
2076 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
2080 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
2084 unified = cg_all_unified();
2090 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2091 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2092 const char *p = NULL;
2094 if (!(supported & bit))
2098 p = path_callback(bit, userdata);
2103 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
2109 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2114 SET_FOREACH(pidp, pids, i) {
2115 pid_t pid = PTR_TO_PID(pidp);
2118 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2119 if (q < 0 && r >= 0)
2126 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2130 if (!path_equal(from, to)) {
2131 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2136 unified = cg_all_unified();
2142 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2143 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2144 const char *p = NULL;
2146 if (!(supported & bit))
2150 p = to_callback(bit, userdata);
2155 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2161 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2165 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2169 unified = cg_all_unified();
2175 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2176 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2178 if (!(supported & bit))
2181 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2188 int cg_mask_supported(CGroupMask *ret) {
2189 CGroupMask mask = 0;
2192 /* Determines the mask of supported cgroup controllers. Only
2193 * includes controllers we can make sense of and that are
2194 * actually accessible. */
2196 unified = cg_all_unified();
2200 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2203 /* In the unified hierarchy we can read the supported
2204 * and accessible controllers from a the top-level
2205 * cgroup attribute */
2207 r = cg_get_root_path(&root);
2211 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2215 r = read_one_line_file(path, &controllers);
2221 _cleanup_free_ char *n = NULL;
2224 r = extract_first_word(&c, &n, NULL, 0);
2230 v = cgroup_controller_from_string(n);
2234 mask |= CGROUP_CONTROLLER_TO_MASK(v);
2237 /* Currently, we support the cpu, memory, io and pids
2238 * controller in the unified hierarchy, mask
2239 * everything else off. */
2240 mask &= CGROUP_MASK_CPU | CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2245 /* In the legacy hierarchy, we check whether which
2246 * hierarchies are mounted. */
2248 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2251 n = cgroup_controller_to_string(c);
2252 if (controller_is_accessible(n) >= 0)
2253 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2261 #if 0 /// UNNEEDED by elogind
2262 int cg_kernel_controllers(Set *controllers) {
2263 _cleanup_fclose_ FILE *f = NULL;
2267 assert(controllers);
2269 /* Determines the full list of kernel-known controllers. Might
2270 * include controllers we don't actually support, arbitrary
2271 * named hierarchies and controllers that aren't currently
2272 * accessible (because not mounted). */
2274 f = fopen("/proc/cgroups", "re");
2276 if (errno == ENOENT)
2281 /* Ignore the header line */
2282 (void) fgets(buf, sizeof(buf), f);
2289 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2294 if (ferror(f) && errno > 0)
2305 if (!cg_controller_is_valid(controller)) {
2310 r = set_consume(controllers, controller);
2319 static thread_local CGroupUnified unified_cache = CGROUP_UNIFIED_UNKNOWN;
2321 static int cg_update_unified(void) {
2325 /* Checks if we support the unified hierarchy. Returns an
2326 * error when the cgroup hierarchies aren't mounted yet or we
2327 * have any other trouble determining if the unified hierarchy
2330 if (unified_cache >= CGROUP_UNIFIED_NONE)
2333 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2336 #if 0 /// UNNEEDED by elogind
2337 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC))
2338 unified_cache = CGROUP_UNIFIED_ALL;
2339 else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC)) {
2340 if (statfs("/sys/fs/cgroup/systemd/", &fs) < 0)
2343 unified_cache = F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC) ?
2344 CGROUP_UNIFIED_SYSTEMD : CGROUP_UNIFIED_NONE;
2348 /* elogind can not support the unified hierarchy as a controller,
2349 * so always assume a classical hierarchy.
2350 * If, and only *if*, someone really wants to substitute systemd-login
2351 * in an environment managed by systemd with elogind, we might have to
2352 * add such a support. */
2353 unified_cache = CGROUP_UNIFIED_NONE;
2359 int cg_unified(const char *controller) {
2363 r = cg_update_unified();
2367 if (streq_ptr(controller, SYSTEMD_CGROUP_CONTROLLER))
2368 return unified_cache >= CGROUP_UNIFIED_SYSTEMD;
2370 return unified_cache >= CGROUP_UNIFIED_ALL;
2373 int cg_all_unified(void) {
2375 return cg_unified(NULL);
2378 #if 0 /// UNNEEDED by elogind
2379 void cg_unified_flush(void) {
2380 unified_cache = CGROUP_UNIFIED_UNKNOWN;
2383 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2384 _cleanup_free_ char *fs = NULL;
2393 unified = cg_all_unified();
2396 if (!unified) /* on the legacy hiearchy there's no joining of controllers defined */
2399 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2403 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2404 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2407 if (!(supported & bit))
2410 n = cgroup_controller_to_string(c);
2412 char s[1 + strlen(n) + 1];
2414 s[0] = mask & bit ? '+' : '-';
2417 r = write_string_file(fs, s, 0);
2419 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2426 bool cg_is_unified_wanted(void) {
2427 static thread_local int wanted = -1;
2431 /* If the hierarchy is already mounted, then follow whatever
2432 * was chosen for it. */
2433 unified = cg_all_unified();
2437 /* Otherwise, let's see what the kernel command line has to
2438 * say. Since checking that is expensive, let's cache the
2443 r = proc_cmdline_get_bool("systemd.unified_cgroup_hierarchy", &b);
2447 return (wanted = r > 0 ? b : false);
2450 bool cg_is_legacy_wanted(void) {
2451 return !cg_is_unified_wanted();
2454 bool cg_is_unified_systemd_controller_wanted(void) {
2455 static thread_local int wanted = -1;
2459 /* If the unified hierarchy is requested in full, no need to
2460 * bother with this. */
2461 if (cg_is_unified_wanted())
2464 /* If the hierarchy is already mounted, then follow whatever
2465 * was chosen for it. */
2466 unified = cg_unified(SYSTEMD_CGROUP_CONTROLLER);
2470 /* Otherwise, let's see what the kernel command line has to
2471 * say. Since checking that is expensive, let's cache the
2476 r = proc_cmdline_get_bool("systemd.legacy_systemd_cgroup_controller", &b);
2481 bool cg_is_legacy_wanted(void) {
2483 /* The meaning of the kernel option is reversed wrt. to the return value
2484 * of this function, hence the negation. */
2485 return (wanted = r > 0 ? !b : false);
2486 return (wanted = r > 0 ? b : false);
2489 bool cg_is_legacy_systemd_controller_wanted(void) {
2490 return cg_is_legacy_wanted() && !cg_is_unified_systemd_controller_wanted();
2494 #if 0 /// UNNEEDED by elogind
2495 int cg_weight_parse(const char *s, uint64_t *ret) {
2500 *ret = CGROUP_WEIGHT_INVALID;
2504 r = safe_atou64(s, &u);
2508 if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2515 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2516 [CGROUP_IO_RBPS_MAX] = CGROUP_LIMIT_MAX,
2517 [CGROUP_IO_WBPS_MAX] = CGROUP_LIMIT_MAX,
2518 [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2519 [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2522 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2523 [CGROUP_IO_RBPS_MAX] = "IOReadBandwidthMax",
2524 [CGROUP_IO_WBPS_MAX] = "IOWriteBandwidthMax",
2525 [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2526 [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2529 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2531 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2536 *ret = CGROUP_CPU_SHARES_INVALID;
2540 r = safe_atou64(s, &u);
2544 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2551 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2556 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2560 r = safe_atou64(s, &u);
2564 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2572 bool is_cgroup_fs(const struct statfs *s) {
2573 return is_fs_type(s, CGROUP_SUPER_MAGIC) ||
2574 is_fs_type(s, CGROUP2_SUPER_MAGIC);
2577 bool fd_is_cgroup_fs(int fd) {
2580 if (fstatfs(fd, &s) < 0)
2583 return is_cgroup_fs(&s);
2586 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2587 [CGROUP_CONTROLLER_CPU] = "cpu",
2588 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2589 [CGROUP_CONTROLLER_IO] = "io",
2590 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2591 [CGROUP_CONTROLLER_MEMORY] = "memory",
2592 [CGROUP_CONTROLLER_DEVICES] = "devices",
2593 [CGROUP_CONTROLLER_PIDS] = "pids",
2596 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);