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>
33 #include "alloc-util.h"
34 #include "cgroup-util.h"
36 #include "dirent-util.h"
37 #include "extract-word.h"
40 #include "formats-util.h"
43 #include "login-util.h"
45 //#include "missing.h"
47 #include "parse-util.h"
48 #include "path-util.h"
49 #include "proc-cmdline.h"
50 #include "process-util.h"
52 //#include "special.h"
53 #include "stat-util.h"
54 #include "stdio-util.h"
55 #include "string-table.h"
56 #include "string-util.h"
57 #include "unit-name.h"
58 #include "user-util.h"
60 int cg_enumerate_processes(const char *controller, const char *path, FILE **_f) {
61 _cleanup_free_ char *fs = NULL;
67 r = cg_get_path(controller, path, "cgroup.procs", &fs);
79 int cg_read_pid(FILE *f, pid_t *_pid) {
82 /* Note that the cgroup.procs might contain duplicates! See
83 * cgroups.txt for details. */
89 if (fscanf(f, "%lu", &ul) != 1) {
94 return errno > 0 ? -errno : -EIO;
104 int cg_read_event(const char *controller, const char *path, const char *event,
107 _cleanup_free_ char *events = NULL, *content = NULL;
111 r = cg_get_path(controller, path, "cgroup.events", &events);
115 r = read_full_file(events, &content, NULL);
120 while ((line = strsep(&p, "\n"))) {
123 key = strsep(&line, " ");
127 if (strcmp(key, event))
137 int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
138 _cleanup_free_ char *fs = NULL;
144 /* This is not recursive! */
146 r = cg_get_path(controller, path, NULL, &fs);
158 int cg_read_subgroup(DIR *d, char **fn) {
164 FOREACH_DIRENT_ALL(de, d, return -errno) {
167 if (de->d_type != DT_DIR)
170 if (streq(de->d_name, ".") ||
171 streq(de->d_name, ".."))
174 b = strdup(de->d_name);
185 int cg_rmdir(const char *controller, const char *path) {
186 _cleanup_free_ char *p = NULL;
189 r = cg_get_path(controller, path, NULL, &p);
194 if (r < 0 && errno != ENOENT)
201 const char *controller,
206 cg_kill_log_func_t log_kill,
209 _cleanup_set_free_ Set *allocated_set = NULL;
216 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
217 * SIGCONT on SIGKILL. */
218 if (IN_SET(sig, SIGCONT, SIGKILL))
219 flags &= ~CGROUP_SIGCONT;
221 /* This goes through the tasks list and kills them all. This
222 * is repeated until no further processes are added to the
223 * tasks list, to properly handle forking processes */
226 s = allocated_set = set_new(NULL);
234 _cleanup_fclose_ FILE *f = NULL;
238 r = cg_enumerate_processes(controller, path, &f);
240 if (ret >= 0 && r != -ENOENT)
246 while ((r = cg_read_pid(f, &pid)) > 0) {
248 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
251 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
255 log_kill(pid, sig, userdata);
257 /* If we haven't killed this process yet, kill
259 if (kill(pid, sig) < 0) {
260 if (ret >= 0 && errno != ESRCH)
263 if (flags & CGROUP_SIGCONT)
264 (void) kill(pid, SIGCONT);
272 r = set_put(s, PID_TO_PTR(pid));
288 /* To avoid racing against processes which fork
289 * quicker than we can kill them we repeat this until
290 * no new pids need to be killed. */
297 int cg_kill_recursive(
298 const char *controller,
303 cg_kill_log_func_t log_kill,
306 _cleanup_set_free_ Set *allocated_set = NULL;
307 _cleanup_closedir_ DIR *d = NULL;
315 s = allocated_set = set_new(NULL);
320 ret = cg_kill(controller, path, sig, flags, s, log_kill, userdata);
322 r = cg_enumerate_subgroups(controller, path, &d);
324 if (ret >= 0 && r != -ENOENT)
330 while ((r = cg_read_subgroup(d, &fn)) > 0) {
331 _cleanup_free_ char *p = NULL;
333 p = strjoin(path, "/", fn, NULL);
338 r = cg_kill_recursive(controller, p, sig, flags, s, log_kill, userdata);
339 if (r != 0 && ret >= 0)
342 if (ret >= 0 && r < 0)
345 if (flags & CGROUP_REMOVE) {
346 r = cg_rmdir(controller, path);
347 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
362 _cleanup_set_free_ Set *s = NULL;
377 log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
378 cfrom, pfrom, cto, pto,
379 (flags & CGROUP_IGNORE_SELF)
380 ? "ignoring self" : "watching self");
382 _cleanup_fclose_ FILE *f = NULL;
386 r = cg_enumerate_processes(cfrom, pfrom, &f);
388 if (ret >= 0 && r != -ENOENT)
394 while ((r = cg_read_pid(f, &pid)) > 0) {
396 /* This might do weird stuff if we aren't a
397 * single-threaded program. However, we
398 * luckily know we are not */
399 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
402 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
405 /* Ignore kernel threads. Since they can only
406 * exist in the root cgroup, we only check for
409 (isempty(pfrom) || path_equal(pfrom, "/")) &&
410 is_kernel_thread(pid) > 0)
413 r = cg_attach(cto, pto, pid);
415 if (ret >= 0 && r != -ESRCH)
422 r = set_put(s, PID_TO_PTR(pid));
442 int cg_migrate_recursive(
449 _cleanup_closedir_ DIR *d = NULL;
458 ret = cg_migrate(cfrom, pfrom, cto, pto, flags);
460 r = cg_enumerate_subgroups(cfrom, pfrom, &d);
462 if (ret >= 0 && r != -ENOENT)
468 while ((r = cg_read_subgroup(d, &fn)) > 0) {
469 _cleanup_free_ char *p = NULL;
471 p = strjoin(pfrom, "/", fn, NULL);
476 r = cg_migrate_recursive(cfrom, p, cto, pto, flags);
477 if (r != 0 && ret >= 0)
481 if (r < 0 && ret >= 0)
484 if (flags & CGROUP_REMOVE) {
485 r = cg_rmdir(cfrom, pfrom);
486 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
493 int cg_migrate_recursive_fallback(
507 r = cg_migrate_recursive(cfrom, pfrom, cto, pto, flags);
509 char prefix[strlen(pto) + 1];
511 /* This didn't work? Then let's try all prefixes of the destination */
513 PATH_FOREACH_PREFIX(prefix, pto) {
516 q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, flags);
525 static const char *controller_to_dirname(const char *controller) {
530 /* Converts a controller name to the directory name below
531 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
532 * just cuts off the name= prefixed used for named
533 * hierarchies, if it is specified. */
535 e = startswith(controller, "name=");
542 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
549 dn = controller_to_dirname(controller);
551 if (isempty(path) && isempty(suffix))
552 t = strappend("/sys/fs/cgroup/", dn);
553 else if (isempty(path))
554 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix, NULL);
555 else if (isempty(suffix))
556 t = strjoin("/sys/fs/cgroup/", dn, "/", path, NULL);
558 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix, NULL);
566 static int join_path_unified(const char *path, const char *suffix, char **fs) {
571 if (isempty(path) && isempty(suffix))
572 t = strdup("/sys/fs/cgroup");
573 else if (isempty(path))
574 t = strappend("/sys/fs/cgroup/", suffix);
575 else if (isempty(suffix))
576 t = strappend("/sys/fs/cgroup/", path);
578 t = strjoin("/sys/fs/cgroup/", path, "/", suffix, NULL);
586 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
594 /* If no controller is specified, we return the path
595 * *below* the controllers, without any prefix. */
597 if (!path && !suffix)
605 t = strjoin(path, "/", suffix, NULL);
609 *fs = path_kill_slashes(t);
613 if (!cg_controller_is_valid(controller))
616 unified = cg_unified();
621 r = join_path_unified(path, suffix, fs);
623 r = join_path_legacy(controller, path, suffix, fs);
627 path_kill_slashes(*fs);
631 static int controller_is_accessible(const char *controller) {
636 /* Checks whether a specific controller is accessible,
637 * i.e. its hierarchy mounted. In the unified hierarchy all
638 * controllers are considered accessible, except for the named
641 if (!cg_controller_is_valid(controller))
644 unified = cg_unified();
648 /* We don't support named hierarchies if we are using
649 * the unified hierarchy. */
651 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
654 if (startswith(controller, "name="))
660 dn = controller_to_dirname(controller);
661 cc = strjoina("/sys/fs/cgroup/", dn);
663 if (laccess(cc, F_OK) < 0)
670 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
676 /* Check if the specified controller is actually accessible */
677 r = controller_is_accessible(controller);
681 return cg_get_path(controller, path, suffix, fs);
684 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
689 if (typeflag != FTW_DP)
692 if (ftwbuf->level < 1)
699 int cg_trim(const char *controller, const char *path, bool delete_root) {
700 _cleanup_free_ char *fs = NULL;
705 r = cg_get_path(controller, path, NULL, &fs);
710 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
720 if (rmdir(fs) < 0 && errno != ENOENT)
727 int cg_create(const char *controller, const char *path) {
728 _cleanup_free_ char *fs = NULL;
731 r = cg_get_path_and_check(controller, path, NULL, &fs);
735 r = mkdir_parents(fs, 0755);
739 if (mkdir(fs, 0755) < 0) {
750 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
755 r = cg_create(controller, path);
759 q = cg_attach(controller, path, pid);
763 /* This does not remove the cgroup on failure */
767 int cg_attach(const char *controller, const char *path, pid_t pid) {
768 _cleanup_free_ char *fs = NULL;
769 char c[DECIMAL_STR_MAX(pid_t) + 2];
775 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
782 xsprintf(c, PID_FMT "\n", pid);
784 return write_string_file(fs, c, 0);
787 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
794 r = cg_attach(controller, path, pid);
796 char prefix[strlen(path) + 1];
798 /* This didn't work? Then let's try all prefixes of
801 PATH_FOREACH_PREFIX(prefix, path) {
804 q = cg_attach(controller, prefix, pid);
813 #if 0 /// UNNEEDED by elogind
814 int cg_set_group_access(
815 const char *controller,
821 _cleanup_free_ char *fs = NULL;
824 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
827 if (mode != MODE_INVALID)
830 r = cg_get_path(controller, path, NULL, &fs);
834 return chmod_and_chown(fs, mode, uid, gid);
837 int cg_set_task_access(
838 const char *controller,
844 _cleanup_free_ char *fs = NULL, *procs = NULL;
849 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
852 if (mode != MODE_INVALID)
855 r = cg_get_path(controller, path, "cgroup.procs", &fs);
859 r = chmod_and_chown(fs, mode, uid, gid);
863 unified = cg_unified();
869 /* Compatibility, Always keep values for "tasks" in sync with
871 if (cg_get_path(controller, path, "tasks", &procs) >= 0)
872 (void) chmod_and_chown(procs, mode, uid, gid);
878 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
879 _cleanup_fclose_ FILE *f = NULL;
888 unified = cg_unified();
893 if (!cg_controller_is_valid(controller))
896 controller = SYSTEMD_CGROUP_CONTROLLER;
898 cs = strlen(controller);
901 fs = procfs_file_alloca(pid, "cgroup");
902 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
903 pid, fs, controller);
906 return errno == ENOENT ? -ESRCH : -errno;
908 FOREACH_LINE(line, f, return -errno) {
914 e = startswith(line, "0:");
924 const char *word, *state;
927 l = strchr(line, ':');
937 FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
938 if (k == cs && memcmp(word, controller, cs) == 0) {
948 log_debug_elogind("Found %s:%s", line, e+1);
960 int cg_install_release_agent(const char *controller, const char *agent) {
961 _cleanup_free_ char *fs = NULL, *contents = NULL;
967 unified = cg_unified();
970 if (unified) /* doesn't apply to unified hierarchy */
973 r = cg_get_path(controller, NULL, "release_agent", &fs);
977 r = read_one_line_file(fs, &contents);
981 sc = strstrip(contents);
983 r = write_string_file(fs, agent, 0);
986 } else if (!path_equal(sc, agent))
990 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
994 contents = mfree(contents);
995 r = read_one_line_file(fs, &contents);
999 sc = strstrip(contents);
1000 if (streq(sc, "0")) {
1001 r = write_string_file(fs, "1", 0);
1008 if (!streq(sc, "1"))
1014 int cg_uninstall_release_agent(const char *controller) {
1015 _cleanup_free_ char *fs = NULL;
1018 unified = cg_unified();
1021 if (unified) /* Doesn't apply to unified hierarchy */
1024 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1028 r = write_string_file(fs, "0", 0);
1034 r = cg_get_path(controller, NULL, "release_agent", &fs);
1038 r = write_string_file(fs, "", 0);
1045 int cg_is_empty(const char *controller, const char *path) {
1046 _cleanup_fclose_ FILE *f = NULL;
1052 r = cg_enumerate_processes(controller, path, &f);
1058 r = cg_read_pid(f, &pid);
1065 int cg_is_empty_recursive(const char *controller, const char *path) {
1070 /* The root cgroup is always populated */
1071 if (controller && (isempty(path) || path_equal(path, "/")))
1074 unified = cg_unified();
1079 _cleanup_free_ char *t = NULL;
1081 /* On the unified hierarchy we can check empty state
1082 * via the "populated" attribute of "cgroup.events". */
1084 r = cg_read_event(controller, path, "populated", &t);
1088 return streq(t, "0");
1090 _cleanup_closedir_ DIR *d = NULL;
1093 r = cg_is_empty(controller, path);
1097 r = cg_enumerate_subgroups(controller, path, &d);
1103 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1104 _cleanup_free_ char *p = NULL;
1106 p = strjoin(path, "/", fn, NULL);
1111 r = cg_is_empty_recursive(controller, p);
1122 int cg_split_spec(const char *spec, char **controller, char **path) {
1123 char *t = NULL, *u = NULL;
1129 if (!path_is_safe(spec))
1137 *path = path_kill_slashes(t);
1146 e = strchr(spec, ':');
1148 if (!cg_controller_is_valid(spec))
1165 t = strndup(spec, e-spec);
1168 if (!cg_controller_is_valid(t)) {
1182 if (!path_is_safe(u) ||
1183 !path_is_absolute(u)) {
1189 path_kill_slashes(u);
1205 int cg_mangle_path(const char *path, char **result) {
1206 _cleanup_free_ char *c = NULL, *p = NULL;
1213 /* First, check if it already is a filesystem path */
1214 if (path_startswith(path, "/sys/fs/cgroup")) {
1220 *result = path_kill_slashes(t);
1224 /* Otherwise, treat it as cg spec */
1225 r = cg_split_spec(path, &c, &p);
1229 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1232 int cg_get_root_path(char **path) {
1233 #if 0 /// elogind does not support systemd scopes and slices
1239 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1243 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1245 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1247 e = endswith(p, "/system"); /* even more legacy */
1255 return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1259 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1260 _cleanup_free_ char *rt = NULL;
1268 /* If the root was specified let's use that, otherwise
1269 * let's determine it from PID 1 */
1271 r = cg_get_root_path(&rt);
1276 log_debug_elogind("Determined root path: \"%s\"", root);
1279 p = path_startswith(cgroup, root);
1280 if (p && p[0] && (p > cgroup))
1288 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1289 _cleanup_free_ char *raw = NULL;
1296 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1300 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1301 raw, pid, root ? root : "NULL");
1302 r = cg_shift_path(raw, root, &c);
1318 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1323 #if 0 /// UNNEEDED by elogind
1324 int cg_path_decode_unit(const char *cgroup, char **unit) {
1331 n = strcspn(cgroup, "/");
1335 c = strndupa(cgroup, n);
1338 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1349 static bool valid_slice_name(const char *p, size_t n) {
1354 if (n < strlen("x.slice"))
1357 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1363 c = cg_unescape(buf);
1365 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1371 static const char *skip_slices(const char *p) {
1374 /* Skips over all slice assignments */
1379 p += strspn(p, "/");
1381 n = strcspn(p, "/");
1382 if (!valid_slice_name(p, n))
1389 int cg_path_get_unit(const char *path, char **ret) {
1397 e = skip_slices(path);
1399 r = cg_path_decode_unit(e, &unit);
1403 /* We skipped over the slices, don't accept any now */
1404 if (endswith(unit, ".slice")) {
1413 int cg_pid_get_unit(pid_t pid, char **unit) {
1414 _cleanup_free_ char *cgroup = NULL;
1419 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1423 return cg_path_get_unit(cgroup, unit);
1427 * Skip session-*.scope, but require it to be there.
1429 static const char *skip_session(const char *p) {
1435 p += strspn(p, "/");
1437 n = strcspn(p, "/");
1438 if (n < strlen("session-x.scope"))
1441 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1442 char buf[n - 8 - 6 + 1];
1444 memcpy(buf, p + 8, n - 8 - 6);
1447 /* Note that session scopes never need unescaping,
1448 * since they cannot conflict with the kernel's own
1449 * names, hence we don't need to call cg_unescape()
1452 if (!session_id_valid(buf))
1456 p += strspn(p, "/");
1464 * Skip user@*.service, but require it to be there.
1466 static const char *skip_user_manager(const char *p) {
1472 p += strspn(p, "/");
1474 n = strcspn(p, "/");
1475 if (n < strlen("user@x.service"))
1478 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1479 char buf[n - 5 - 8 + 1];
1481 memcpy(buf, p + 5, n - 5 - 8);
1484 /* Note that user manager services never need unescaping,
1485 * since they cannot conflict with the kernel's own
1486 * names, hence we don't need to call cg_unescape()
1489 if (parse_uid(buf, NULL) < 0)
1493 p += strspn(p, "/");
1501 static const char *skip_user_prefix(const char *path) {
1506 /* Skip slices, if there are any */
1507 e = skip_slices(path);
1509 /* Skip the user manager, if it's in the path now... */
1510 t = skip_user_manager(e);
1514 /* Alternatively skip the user session if it is in the path... */
1515 return skip_session(e);
1518 int cg_path_get_user_unit(const char *path, char **ret) {
1524 t = skip_user_prefix(path);
1528 /* And from here on it looks pretty much the same as for a
1529 * system unit, hence let's use the same parser from here
1531 return cg_path_get_unit(t, ret);
1534 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1535 _cleanup_free_ char *cgroup = NULL;
1540 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1544 return cg_path_get_user_unit(cgroup, unit);
1547 int cg_path_get_machine_name(const char *path, char **machine) {
1548 _cleanup_free_ char *u = NULL;
1552 r = cg_path_get_unit(path, &u);
1556 sl = strjoina("/run/systemd/machines/unit:", u);
1557 return readlink_malloc(sl, machine);
1560 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1561 _cleanup_free_ char *cgroup = NULL;
1566 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1570 return cg_path_get_machine_name(cgroup, machine);
1574 int cg_path_get_session(const char *path, char **session) {
1575 #if 0 /// UNNEEDED by elogind
1576 _cleanup_free_ char *unit = NULL;
1582 r = cg_path_get_unit(path, &unit);
1586 start = startswith(unit, "session-");
1589 end = endswith(start, ".scope");
1594 if (!session_id_valid(start))
1597 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1598 wrinkle is that SESSION might be escaped. */
1599 const char *e, *n, *start;
1602 log_debug_elogind("path is \"%s\"", path);
1603 assert(path[0] == '/');
1606 n = strchrnul(e, '/');
1610 start = strndupa(e, n - e);
1611 start = cg_unescape(start);
1620 log_debug_elogind("found session: \"%s\"", start);
1631 int cg_pid_get_session(pid_t pid, char **session) {
1632 _cleanup_free_ char *cgroup = NULL;
1635 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1639 return cg_path_get_session(cgroup, session);
1642 #if 0 /// UNNEEDED by elogind
1643 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1644 _cleanup_free_ char *slice = NULL;
1650 r = cg_path_get_slice(path, &slice);
1654 start = startswith(slice, "user-");
1657 end = endswith(start, ".slice");
1662 if (parse_uid(start, uid) < 0)
1668 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1669 _cleanup_free_ char *cgroup = NULL;
1672 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1676 return cg_path_get_owner_uid(cgroup, uid);
1679 int cg_path_get_slice(const char *p, char **slice) {
1680 const char *e = NULL;
1685 /* Finds the right-most slice unit from the beginning, but
1686 * stops before we come to the first non-slice unit. */
1691 p += strspn(p, "/");
1693 n = strcspn(p, "/");
1694 if (!valid_slice_name(p, n)) {
1699 s = strdup("-.slice");
1707 return cg_path_decode_unit(e, slice);
1715 int cg_pid_get_slice(pid_t pid, char **slice) {
1716 _cleanup_free_ char *cgroup = NULL;
1721 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1725 return cg_path_get_slice(cgroup, slice);
1728 int cg_path_get_user_slice(const char *p, char **slice) {
1733 t = skip_user_prefix(p);
1737 /* And now it looks pretty much the same as for a system
1738 * slice, so let's just use the same parser from here on. */
1739 return cg_path_get_slice(t, slice);
1742 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1743 _cleanup_free_ char *cgroup = NULL;
1748 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1752 return cg_path_get_user_slice(cgroup, slice);
1756 char *cg_escape(const char *p) {
1757 bool need_prefix = false;
1759 /* This implements very minimal escaping for names to be used
1760 * as file names in the cgroup tree: any name which might
1761 * conflict with a kernel name or is prefixed with '_' is
1762 * prefixed with a '_'. That way, when reading cgroup names it
1763 * is sufficient to remove a single prefixing underscore if
1766 /* The return value of this function (unlike cg_unescape())
1772 streq(p, "notify_on_release") ||
1773 streq(p, "release_agent") ||
1774 streq(p, "tasks") ||
1775 startswith(p, "cgroup."))
1780 dot = strrchr(p, '.');
1785 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1788 n = cgroup_controller_to_string(c);
1793 if (memcmp(p, n, l) != 0)
1803 return strappend("_", p);
1808 char *cg_unescape(const char *p) {
1811 /* The return value of this function (unlike cg_escape())
1812 * doesn't need free()! */
1820 #define CONTROLLER_VALID \
1824 bool cg_controller_is_valid(const char *p) {
1830 s = startswith(p, "name=");
1834 if (*p == 0 || *p == '_')
1837 for (t = p; *t; t++)
1838 if (!strchr(CONTROLLER_VALID, *t))
1841 if (t - p > FILENAME_MAX)
1847 #if 0 /// UNNEEDED by elogind
1848 int cg_slice_to_path(const char *unit, char **ret) {
1849 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1856 if (streq(unit, "-.slice")) {
1866 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1869 if (!endswith(unit, ".slice"))
1872 r = unit_name_to_prefix(unit, &p);
1876 dash = strchr(p, '-');
1878 /* Don't allow initial dashes */
1883 _cleanup_free_ char *escaped = NULL;
1884 char n[dash - p + sizeof(".slice")];
1886 /* Don't allow trailing or double dashes */
1887 if (dash[1] == 0 || dash[1] == '-')
1890 strcpy(stpncpy(n, p, dash - p), ".slice");
1891 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1894 escaped = cg_escape(n);
1898 if (!strextend(&s, escaped, "/", NULL))
1901 dash = strchr(dash+1, '-');
1904 e = cg_escape(unit);
1908 if (!strextend(&s, e, NULL))
1918 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1919 _cleanup_free_ char *p = NULL;
1922 r = cg_get_path(controller, path, attribute, &p);
1926 return write_string_file(p, value, 0);
1929 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1930 _cleanup_free_ char *p = NULL;
1933 r = cg_get_path(controller, path, attribute, &p);
1937 return read_one_line_file(p, ret);
1940 #if 0 /// UNNEEDED by elogind
1941 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
1945 /* This one will create a cgroup in our private tree, but also
1946 * duplicate it in the trees specified in mask, and remove it
1949 /* First create the cgroup in our own hierarchy. */
1950 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1954 /* If we are in the unified hierarchy, we are done now */
1955 unified = cg_unified();
1961 /* Otherwise, do the same in the other hierarchies */
1962 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1963 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1966 n = cgroup_controller_to_string(c);
1969 (void) cg_create(n, path);
1970 else if (supported & bit)
1971 (void) cg_trim(n, path, true);
1977 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
1981 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
1985 unified = cg_unified();
1991 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1992 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1993 const char *p = NULL;
1995 if (!(supported & bit))
1999 p = path_callback(bit, userdata);
2004 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
2010 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2015 SET_FOREACH(pidp, pids, i) {
2016 pid_t pid = PTR_TO_PID(pidp);
2019 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2020 if (q < 0 && r >= 0)
2027 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2031 if (!path_equal(from, to)) {
2032 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2037 unified = cg_unified();
2043 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2044 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2045 const char *p = NULL;
2047 if (!(supported & bit))
2051 p = to_callback(bit, userdata);
2056 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2062 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2066 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2070 unified = cg_unified();
2076 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2077 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2079 if (!(supported & bit))
2082 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2089 int cg_mask_supported(CGroupMask *ret) {
2090 CGroupMask mask = 0;
2093 /* Determines the mask of supported cgroup controllers. Only
2094 * includes controllers we can make sense of and that are
2095 * actually accessible. */
2097 unified = cg_unified();
2101 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2104 /* In the unified hierarchy we can read the supported
2105 * and accessible controllers from a the top-level
2106 * cgroup attribute */
2108 r = cg_get_root_path(&root);
2112 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2116 r = read_one_line_file(path, &controllers);
2122 _cleanup_free_ char *n = NULL;
2125 r = extract_first_word(&c, &n, NULL, 0);
2131 v = cgroup_controller_from_string(n);
2135 mask |= CGROUP_CONTROLLER_TO_MASK(v);
2138 /* Currently, we only support the memory, io and pids
2139 * controller in the unified hierarchy, mask
2140 * everything else off. */
2141 mask &= CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2146 /* In the legacy hierarchy, we check whether which
2147 * hierarchies are mounted. */
2149 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2152 n = cgroup_controller_to_string(c);
2153 if (controller_is_accessible(n) >= 0)
2154 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2162 #if 0 /// UNNEEDED by elogind
2163 int cg_kernel_controllers(Set *controllers) {
2164 _cleanup_fclose_ FILE *f = NULL;
2168 assert(controllers);
2170 /* Determines the full list of kernel-known controllers. Might
2171 * include controllers we don't actually support, arbitrary
2172 * named hierarchies and controllers that aren't currently
2173 * accessible (because not mounted). */
2175 f = fopen("/proc/cgroups", "re");
2177 if (errno == ENOENT)
2182 /* Ignore the header line */
2183 (void) fgets(buf, sizeof(buf), f);
2190 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2195 if (ferror(f) && errno > 0)
2206 if (!cg_controller_is_valid(controller)) {
2211 r = set_consume(controllers, controller);
2220 static thread_local int unified_cache = -1;
2222 int cg_unified(void) {
2225 /* Checks if we support the unified hierarchy. Returns an
2226 * error when the cgroup hierarchies aren't mounted yet or we
2227 * have any other trouble determining if the unified hierarchy
2230 if (unified_cache >= 0)
2231 return unified_cache;
2233 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2236 #if 0 /// UNNEEDED by elogind
2237 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC))
2238 unified_cache = true;
2239 else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2241 /* elogind can not support the unified hierarchy as a controller,
2242 * so always assume a classical hierarchy.
2243 * If, ond only *if*, someone really wants to substitute systemd-login
2244 * in an environment managed by systemd with elogin, we might have to
2245 * add such a support. */
2246 if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2248 unified_cache = false;
2252 return unified_cache;
2255 #if 0 /// UNNEEDED by elogind
2256 void cg_unified_flush(void) {
2260 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2261 _cleanup_free_ char *fs = NULL;
2270 unified = cg_unified();
2273 if (!unified) /* on the legacy hiearchy there's no joining of controllers defined */
2276 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2280 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2281 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2284 if (!(supported & bit))
2287 n = cgroup_controller_to_string(c);
2289 char s[1 + strlen(n) + 1];
2291 s[0] = mask & bit ? '+' : '-';
2294 r = write_string_file(fs, s, 0);
2296 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2303 bool cg_is_unified_wanted(void) {
2304 static thread_local int wanted = -1;
2307 /* If the hierarchy is already mounted, then follow whatever
2308 * was chosen for it. */
2309 unified = cg_unified();
2313 /* Otherwise, let's see what the kernel command line has to
2314 * say. Since checking that is expensive, let's cache the
2319 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL);
2321 return (wanted = true);
2323 _cleanup_free_ char *value = NULL;
2325 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value);
2329 return (wanted = false);
2331 return (wanted = parse_boolean(value) > 0);
2335 bool cg_is_legacy_wanted(void) {
2336 return !cg_is_unified_wanted();
2339 bool cg_is_legacy_wanted(void) {
2344 #if 0 /// UNNEEDED by elogind
2345 int cg_weight_parse(const char *s, uint64_t *ret) {
2350 *ret = CGROUP_WEIGHT_INVALID;
2354 r = safe_atou64(s, &u);
2358 if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2365 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2366 [CGROUP_IO_RBPS_MAX] = CGROUP_LIMIT_MAX,
2367 [CGROUP_IO_WBPS_MAX] = CGROUP_LIMIT_MAX,
2368 [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2369 [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2372 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2373 [CGROUP_IO_RBPS_MAX] = "IOReadBandwidthMax",
2374 [CGROUP_IO_WBPS_MAX] = "IOWriteBandwidthMax",
2375 [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2376 [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2379 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2381 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2386 *ret = CGROUP_CPU_SHARES_INVALID;
2390 r = safe_atou64(s, &u);
2394 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2401 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2406 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2410 r = safe_atou64(s, &u);
2414 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2422 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2423 [CGROUP_CONTROLLER_CPU] = "cpu",
2424 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2425 [CGROUP_CONTROLLER_IO] = "io",
2426 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2427 [CGROUP_CONTROLLER_MEMORY] = "memory",
2428 [CGROUP_CONTROLLER_DEVICES] = "devices",
2429 [CGROUP_CONTROLLER_PIDS] = "pids",
2432 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);