1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
29 #include <sys/types.h>
32 #include "alloc-util.h"
33 #include "cgroup-util.h"
34 #include "dirent-util.h"
35 #include "extract-word.h"
38 #include "formats-util.h"
40 #include "login-util.h"
43 #include "parse-util.h"
44 #include "path-util.h"
45 #include "proc-cmdline.h"
46 #include "process-util.h"
48 //#include "special.h"
49 #include "stat-util.h"
50 #include "string-table.h"
51 #include "string-util.h"
52 #include "unit-name.h"
53 #include "user-util.h"
56 int cg_enumerate_processes(const char *controller, const char *path, FILE **_f) {
57 _cleanup_free_ char *fs = NULL;
63 r = cg_get_path(controller, path, "cgroup.procs", &fs);
75 int cg_read_pid(FILE *f, pid_t *_pid) {
78 /* Note that the cgroup.procs might contain duplicates! See
79 * cgroups.txt for details. */
85 if (fscanf(f, "%lu", &ul) != 1) {
90 return errno ? -errno : -EIO;
100 int cg_enumerate_subgroups(const char *controller, const char *path, DIR **_d) {
101 _cleanup_free_ char *fs = NULL;
107 /* This is not recursive! */
109 r = cg_get_path(controller, path, NULL, &fs);
121 int cg_read_subgroup(DIR *d, char **fn) {
127 FOREACH_DIRENT_ALL(de, d, return -errno) {
130 if (de->d_type != DT_DIR)
133 if (streq(de->d_name, ".") ||
134 streq(de->d_name, ".."))
137 b = strdup(de->d_name);
148 int cg_rmdir(const char *controller, const char *path) {
149 _cleanup_free_ char *p = NULL;
152 r = cg_get_path(controller, path, NULL, &p);
157 if (r < 0 && errno != ENOENT)
163 int cg_kill(const char *controller, const char *path, int sig, bool sigcont, bool ignore_self, Set *s) {
164 _cleanup_set_free_ Set *allocated_set = NULL;
171 /* This goes through the tasks list and kills them all. This
172 * is repeated until no further processes are added to the
173 * tasks list, to properly handle forking processes */
176 s = allocated_set = set_new(NULL);
184 _cleanup_fclose_ FILE *f = NULL;
188 r = cg_enumerate_processes(controller, path, &f);
190 if (ret >= 0 && r != -ENOENT)
196 while ((r = cg_read_pid(f, &pid)) > 0) {
198 if (ignore_self && pid == my_pid)
201 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
204 /* If we haven't killed this process yet, kill
206 if (kill(pid, sig) < 0) {
207 if (ret >= 0 && errno != ESRCH)
210 if (sigcont && sig != SIGKILL)
211 (void) kill(pid, SIGCONT);
219 r = set_put(s, PID_TO_PTR(pid));
235 /* To avoid racing against processes which fork
236 * quicker than we can kill them we repeat this until
237 * no new pids need to be killed. */
244 int cg_kill_recursive(const char *controller, const char *path, int sig, bool sigcont, bool ignore_self, bool rem, Set *s) {
245 _cleanup_set_free_ Set *allocated_set = NULL;
246 _cleanup_closedir_ DIR *d = NULL;
254 s = allocated_set = set_new(NULL);
259 ret = cg_kill(controller, path, sig, sigcont, ignore_self, s);
261 r = cg_enumerate_subgroups(controller, path, &d);
263 if (ret >= 0 && r != -ENOENT)
269 while ((r = cg_read_subgroup(d, &fn)) > 0) {
270 _cleanup_free_ char *p = NULL;
272 p = strjoin(path, "/", fn, NULL);
277 r = cg_kill_recursive(controller, p, sig, sigcont, ignore_self, rem, s);
278 if (r != 0 && ret >= 0)
282 if (ret >= 0 && r < 0)
286 r = cg_rmdir(controller, path);
287 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
294 int cg_migrate(const char *cfrom, const char *pfrom, const char *cto, const char *pto, bool ignore_self) {
296 _cleanup_set_free_ Set *s = NULL;
311 log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
312 cfrom, pfrom, cto, pto,
313 ignore_self ? "ignoring self" : "watching self");
316 _cleanup_fclose_ FILE *f = NULL;
320 r = cg_enumerate_processes(cfrom, pfrom, &f);
322 if (ret >= 0 && r != -ENOENT)
328 while ((r = cg_read_pid(f, &pid)) > 0) {
330 /* This might do weird stuff if we aren't a
331 * single-threaded program. However, we
332 * luckily know we are not */
333 if (ignore_self && pid == my_pid)
336 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
339 /* Ignore kernel threads. Since they can only
340 * exist in the root cgroup, we only check for
343 (isempty(pfrom) || path_equal(pfrom, "/")) &&
344 is_kernel_thread(pid) > 0)
347 r = cg_attach(cto, pto, pid);
349 if (ret >= 0 && r != -ESRCH)
356 r = set_put(s, PID_TO_PTR(pid));
376 int cg_migrate_recursive(
384 _cleanup_closedir_ DIR *d = NULL;
393 ret = cg_migrate(cfrom, pfrom, cto, pto, ignore_self);
395 r = cg_enumerate_subgroups(cfrom, pfrom, &d);
397 if (ret >= 0 && r != -ENOENT)
403 while ((r = cg_read_subgroup(d, &fn)) > 0) {
404 _cleanup_free_ char *p = NULL;
406 p = strjoin(pfrom, "/", fn, NULL);
411 r = cg_migrate_recursive(cfrom, p, cto, pto, ignore_self, rem);
412 if (r != 0 && ret >= 0)
416 if (r < 0 && ret >= 0)
420 r = cg_rmdir(cfrom, pfrom);
421 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
428 int cg_migrate_recursive_fallback(
443 r = cg_migrate_recursive(cfrom, pfrom, cto, pto, ignore_self, rem);
445 char prefix[strlen(pto) + 1];
447 /* This didn't work? Then let's try all prefixes of the destination */
449 PATH_FOREACH_PREFIX(prefix, pto) {
452 q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, ignore_self, rem);
461 static const char *controller_to_dirname(const char *controller) {
466 /* Converts a controller name to the directory name below
467 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
468 * just cuts off the name= prefixed used for named
469 * hierarchies, if it is specified. */
471 e = startswith(controller, "name=");
478 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
485 dn = controller_to_dirname(controller);
487 if (isempty(path) && isempty(suffix))
488 t = strappend("/sys/fs/cgroup/", dn);
489 else if (isempty(path))
490 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix, NULL);
491 else if (isempty(suffix))
492 t = strjoin("/sys/fs/cgroup/", dn, "/", path, NULL);
494 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix, NULL);
502 static int join_path_unified(const char *path, const char *suffix, char **fs) {
507 if (isempty(path) && isempty(suffix))
508 t = strdup("/sys/fs/cgroup");
509 else if (isempty(path))
510 t = strappend("/sys/fs/cgroup/", suffix);
511 else if (isempty(suffix))
512 t = strappend("/sys/fs/cgroup/", path);
514 t = strjoin("/sys/fs/cgroup/", path, "/", suffix, NULL);
522 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
530 /* If no controller is specified, we return the path
531 * *below* the controllers, without any prefix. */
533 if (!path && !suffix)
541 t = strjoin(path, "/", suffix, NULL);
545 *fs = path_kill_slashes(t);
549 if (!cg_controller_is_valid(controller))
552 unified = cg_unified();
557 r = join_path_unified(path, suffix, fs);
559 r = join_path_legacy(controller, path, suffix, fs);
564 path_kill_slashes(*fs);
568 static int controller_is_accessible(const char *controller) {
573 /* Checks whether a specific controller is accessible,
574 * i.e. its hierarchy mounted. In the unified hierarchy all
575 * controllers are considered accessible, except for the named
578 if (!cg_controller_is_valid(controller))
581 unified = cg_unified();
585 /* We don't support named hierarchies if we are using
586 * the unified hierarchy. */
588 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
591 if (startswith(controller, "name="))
597 dn = controller_to_dirname(controller);
598 cc = strjoina("/sys/fs/cgroup/", dn);
600 if (laccess(cc, F_OK) < 0)
607 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
613 /* Check if the specified controller is actually accessible */
614 r = controller_is_accessible(controller);
618 return cg_get_path(controller, path, suffix, fs);
621 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
626 if (typeflag != FTW_DP)
629 if (ftwbuf->level < 1)
636 int cg_trim(const char *controller, const char *path, bool delete_root) {
637 _cleanup_free_ char *fs = NULL;
642 r = cg_get_path(controller, path, NULL, &fs);
647 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
657 if (rmdir(fs) < 0 && errno != ENOENT)
664 int cg_create(const char *controller, const char *path) {
665 _cleanup_free_ char *fs = NULL;
668 r = cg_get_path_and_check(controller, path, NULL, &fs);
672 r = mkdir_parents(fs, 0755);
676 if (mkdir(fs, 0755) < 0) {
687 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
692 r = cg_create(controller, path);
696 q = cg_attach(controller, path, pid);
700 /* This does not remove the cgroup on failure */
704 int cg_attach(const char *controller, const char *path, pid_t pid) {
705 _cleanup_free_ char *fs = NULL;
706 char c[DECIMAL_STR_MAX(pid_t) + 2];
712 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
719 snprintf(c, sizeof(c), PID_FMT"\n", pid);
721 return write_string_file(fs, c, 0);
724 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
731 r = cg_attach(controller, path, pid);
733 char prefix[strlen(path) + 1];
735 /* This didn't work? Then let's try all prefixes of
738 PATH_FOREACH_PREFIX(prefix, path) {
741 q = cg_attach(controller, prefix, pid);
750 /// UNNEEDED by elogind
752 int cg_set_group_access(
753 const char *controller,
759 _cleanup_free_ char *fs = NULL;
762 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
765 if (mode != MODE_INVALID)
768 r = cg_get_path(controller, path, NULL, &fs);
772 return chmod_and_chown(fs, mode, uid, gid);
775 int cg_set_task_access(
776 const char *controller,
782 _cleanup_free_ char *fs = NULL, *procs = NULL;
787 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
790 if (mode != MODE_INVALID)
793 r = cg_get_path(controller, path, "cgroup.procs", &fs);
797 r = chmod_and_chown(fs, mode, uid, gid);
801 unified = cg_unified();
807 /* Compatibility, Always keep values for "tasks" in sync with
809 if (cg_get_path(controller, path, "tasks", &procs) >= 0)
810 (void) chmod_and_chown(procs, mode, uid, gid);
816 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
817 _cleanup_fclose_ FILE *f = NULL;
826 unified = cg_unified();
831 if (!cg_controller_is_valid(controller))
834 controller = SYSTEMD_CGROUP_CONTROLLER;
836 cs = strlen(controller);
839 fs = procfs_file_alloca(pid, "cgroup");
840 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
841 pid, fs, controller);
844 return errno == ENOENT ? -ESRCH : -errno;
846 FOREACH_LINE(line, f, return -errno) {
852 e = startswith(line, "0:");
862 const char *word, *state;
865 l = strchr(line, ':');
875 FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
876 if (k == cs && memcmp(word, controller, cs) == 0) {
886 log_debug_elogind("Found %s:%s", line, e+1);
898 int cg_install_release_agent(const char *controller, const char *agent) {
899 _cleanup_free_ char *fs = NULL, *contents = NULL;
905 unified = cg_unified();
908 if (unified) /* doesn't apply to unified hierarchy */
911 r = cg_get_path(controller, NULL, "release_agent", &fs);
915 r = read_one_line_file(fs, &contents);
919 sc = strstrip(contents);
921 r = write_string_file(fs, agent, 0);
924 } else if (!path_equal(sc, agent))
928 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
932 contents = mfree(contents);
933 r = read_one_line_file(fs, &contents);
937 sc = strstrip(contents);
938 if (streq(sc, "0")) {
939 r = write_string_file(fs, "1", 0);
952 int cg_uninstall_release_agent(const char *controller) {
953 _cleanup_free_ char *fs = NULL;
956 unified = cg_unified();
959 if (unified) /* Doesn't apply to unified hierarchy */
962 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
966 r = write_string_file(fs, "0", 0);
972 r = cg_get_path(controller, NULL, "release_agent", &fs);
976 r = write_string_file(fs, "", 0);
983 int cg_is_empty(const char *controller, const char *path) {
984 _cleanup_fclose_ FILE *f = NULL;
990 r = cg_enumerate_processes(controller, path, &f);
996 r = cg_read_pid(f, &pid);
1003 int cg_is_empty_recursive(const char *controller, const char *path) {
1008 /* The root cgroup is always populated */
1009 if (controller && (isempty(path) || path_equal(path, "/")))
1012 unified = cg_unified();
1017 _cleanup_free_ char *populated = NULL, *t = NULL;
1019 /* On the unified hierarchy we can check empty state
1020 * via the "cgroup.populated" attribute. */
1022 r = cg_get_path(controller, path, "cgroup.populated", &populated);
1026 r = read_one_line_file(populated, &t);
1032 return streq(t, "0");
1034 _cleanup_closedir_ DIR *d = NULL;
1037 r = cg_is_empty(controller, path);
1041 r = cg_enumerate_subgroups(controller, path, &d);
1047 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1048 _cleanup_free_ char *p = NULL;
1050 p = strjoin(path, "/", fn, NULL);
1055 r = cg_is_empty_recursive(controller, p);
1066 int cg_split_spec(const char *spec, char **controller, char **path) {
1067 char *t = NULL, *u = NULL;
1073 if (!path_is_safe(spec))
1081 *path = path_kill_slashes(t);
1090 e = strchr(spec, ':');
1092 if (!cg_controller_is_valid(spec))
1109 t = strndup(spec, e-spec);
1112 if (!cg_controller_is_valid(t)) {
1126 if (!path_is_safe(u) ||
1127 !path_is_absolute(u)) {
1133 path_kill_slashes(u);
1149 int cg_mangle_path(const char *path, char **result) {
1150 _cleanup_free_ char *c = NULL, *p = NULL;
1157 /* First, check if it already is a filesystem path */
1158 if (path_startswith(path, "/sys/fs/cgroup")) {
1164 *result = path_kill_slashes(t);
1168 /* Otherwise, treat it as cg spec */
1169 r = cg_split_spec(path, &c, &p);
1173 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1176 int cg_get_root_path(char **path) {
1177 /// elogind does not support systemd scopes and slices
1184 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1188 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1190 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1192 e = endswith(p, "/system"); /* even more legacy */
1200 return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1204 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1205 _cleanup_free_ char *rt = NULL;
1213 /* If the root was specified let's use that, otherwise
1214 * let's determine it from PID 1 */
1216 r = cg_get_root_path(&rt);
1221 log_debug_elogind("Determined root path: \"%s\"", root);
1224 p = path_startswith(cgroup, root);
1225 if (p && p[0] && (p > cgroup))
1233 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1234 _cleanup_free_ char *raw = NULL;
1241 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1245 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1246 raw, pid, root ? root : "NULL");
1247 r = cg_shift_path(raw, root, &c);
1263 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1268 /// UNNEEDED by elogind
1270 int cg_path_decode_unit(const char *cgroup, char **unit){
1277 n = strcspn(cgroup, "/");
1281 c = strndupa(cgroup, n);
1284 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1295 static bool valid_slice_name(const char *p, size_t n) {
1300 if (n < strlen("x.slice"))
1303 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1309 c = cg_unescape(buf);
1311 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1317 static const char *skip_slices(const char *p) {
1320 /* Skips over all slice assignments */
1325 p += strspn(p, "/");
1327 n = strcspn(p, "/");
1328 if (!valid_slice_name(p, n))
1335 int cg_path_get_unit(const char *path, char **ret) {
1343 e = skip_slices(path);
1345 r = cg_path_decode_unit(e, &unit);
1349 /* We skipped over the slices, don't accept any now */
1350 if (endswith(unit, ".slice")) {
1359 int cg_pid_get_unit(pid_t pid, char **unit) {
1360 _cleanup_free_ char *cgroup = NULL;
1365 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1369 return cg_path_get_unit(cgroup, unit);
1373 * Skip session-*.scope, but require it to be there.
1375 static const char *skip_session(const char *p) {
1381 p += strspn(p, "/");
1383 n = strcspn(p, "/");
1384 if (n < strlen("session-x.scope"))
1387 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1388 char buf[n - 8 - 6 + 1];
1390 memcpy(buf, p + 8, n - 8 - 6);
1393 /* Note that session scopes never need unescaping,
1394 * since they cannot conflict with the kernel's own
1395 * names, hence we don't need to call cg_unescape()
1398 if (!session_id_valid(buf))
1402 p += strspn(p, "/");
1410 * Skip user@*.service, but require it to be there.
1412 static const char *skip_user_manager(const char *p) {
1418 p += strspn(p, "/");
1420 n = strcspn(p, "/");
1421 if (n < strlen("user@x.service"))
1424 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1425 char buf[n - 5 - 8 + 1];
1427 memcpy(buf, p + 5, n - 5 - 8);
1430 /* Note that user manager services never need unescaping,
1431 * since they cannot conflict with the kernel's own
1432 * names, hence we don't need to call cg_unescape()
1435 if (parse_uid(buf, NULL) < 0)
1439 p += strspn(p, "/");
1447 static const char *skip_user_prefix(const char *path) {
1452 /* Skip slices, if there are any */
1453 e = skip_slices(path);
1455 /* Skip the user manager, if it's in the path now... */
1456 t = skip_user_manager(e);
1460 /* Alternatively skip the user session if it is in the path... */
1461 return skip_session(e);
1464 int cg_path_get_user_unit(const char *path, char **ret) {
1470 t = skip_user_prefix(path);
1474 /* And from here on it looks pretty much the same as for a
1475 * system unit, hence let's use the same parser from here
1477 return cg_path_get_unit(t, ret);
1480 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1481 _cleanup_free_ char *cgroup = NULL;
1486 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1490 return cg_path_get_user_unit(cgroup, unit);
1493 int cg_path_get_machine_name(const char *path, char **machine) {
1494 _cleanup_free_ char *u = NULL;
1498 r = cg_path_get_unit(path, &u);
1502 sl = strjoina("/run/systemd/machines/unit:", u);
1503 return readlink_malloc(sl, machine);
1506 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1507 _cleanup_free_ char *cgroup = NULL;
1512 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1516 return cg_path_get_machine_name(cgroup, machine);
1520 int cg_path_get_session(const char *path, char **session) {
1521 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1522 wrinkle is that SESSION might be escaped. */
1524 _cleanup_free_ char *unit = NULL;
1530 r = cg_path_get_unit(path, &unit);
1534 start = startswith(unit, "session-");
1537 end = endswith(start, ".scope");
1542 if (!session_id_valid(start))
1545 const char *e, *n, *start;
1548 log_debug_elogind("path is \"%s\"", path);
1549 assert(path[0] == '/');
1552 n = strchrnul(e, '/');
1556 start = strndupa(e, n - e);
1557 start = cg_unescape(start);
1566 log_debug_elogind("found session: \"%s\"", start);
1577 int cg_pid_get_session(pid_t pid, char **session) {
1578 _cleanup_free_ char *cgroup = NULL;
1581 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1585 return cg_path_get_session(cgroup, session);
1588 /// UNNEEDED by elogind
1590 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1591 _cleanup_free_ char *slice = NULL;
1597 r = cg_path_get_slice(path, &slice);
1601 start = startswith(slice, "user-");
1604 end = endswith(start, ".slice");
1609 if (parse_uid(start, uid) < 0)
1615 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1616 _cleanup_free_ char *cgroup = NULL;
1619 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1623 return cg_path_get_owner_uid(cgroup, uid);
1626 int cg_path_get_slice(const char *p, char **slice) {
1627 const char *e = NULL;
1632 /* Finds the right-most slice unit from the beginning, but
1633 * stops before we come to the first non-slice unit. */
1638 p += strspn(p, "/");
1640 n = strcspn(p, "/");
1641 if (!valid_slice_name(p, n)) {
1646 s = strdup("-.slice");
1654 return cg_path_decode_unit(e, slice);
1662 int cg_pid_get_slice(pid_t pid, char **slice) {
1663 _cleanup_free_ char *cgroup = NULL;
1668 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1672 return cg_path_get_slice(cgroup, slice);
1675 int cg_path_get_user_slice(const char *p, char **slice) {
1680 t = skip_user_prefix(p);
1684 /* And now it looks pretty much the same as for a system
1685 * slice, so let's just use the same parser from here on. */
1686 return cg_path_get_slice(t, slice);
1689 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1690 _cleanup_free_ char *cgroup = NULL;
1695 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1699 return cg_path_get_user_slice(cgroup, slice);
1703 char *cg_escape(const char *p) {
1704 bool need_prefix = false;
1706 /* This implements very minimal escaping for names to be used
1707 * as file names in the cgroup tree: any name which might
1708 * conflict with a kernel name or is prefixed with '_' is
1709 * prefixed with a '_'. That way, when reading cgroup names it
1710 * is sufficient to remove a single prefixing underscore if
1713 /* The return value of this function (unlike cg_unescape())
1719 streq(p, "notify_on_release") ||
1720 streq(p, "release_agent") ||
1721 streq(p, "tasks") ||
1722 startswith(p, "cgroup."))
1727 dot = strrchr(p, '.');
1732 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1735 n = cgroup_controller_to_string(c);
1740 if (memcmp(p, n, l) != 0)
1750 return strappend("_", p);
1755 char *cg_unescape(const char *p) {
1758 /* The return value of this function (unlike cg_escape())
1759 * doesn't need free()! */
1767 #define CONTROLLER_VALID \
1771 bool cg_controller_is_valid(const char *p) {
1777 s = startswith(p, "name=");
1781 if (*p == 0 || *p == '_')
1784 for (t = p; *t; t++)
1785 if (!strchr(CONTROLLER_VALID, *t))
1788 if (t - p > FILENAME_MAX)
1794 /// UNNEEDED by elogind
1796 int cg_slice_to_path(const char *unit, char **ret) {
1797 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1804 if (streq(unit, "-.slice")) {
1814 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1817 if (!endswith(unit, ".slice"))
1820 r = unit_name_to_prefix(unit, &p);
1824 dash = strchr(p, '-');
1826 /* Don't allow initial dashes */
1831 _cleanup_free_ char *escaped = NULL;
1832 char n[dash - p + sizeof(".slice")];
1834 /* Don't allow trailing or double dashes */
1835 if (dash[1] == 0 || dash[1] == '-')
1838 strcpy(stpncpy(n, p, dash - p), ".slice");
1839 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1842 escaped = cg_escape(n);
1846 if (!strextend(&s, escaped, "/", NULL))
1849 dash = strchr(dash+1, '-');
1852 e = cg_escape(unit);
1856 if (!strextend(&s, e, NULL))
1866 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1867 _cleanup_free_ char *p = NULL;
1870 r = cg_get_path(controller, path, attribute, &p);
1874 return write_string_file(p, value, 0);
1877 /// UNNEEDED by elogind
1879 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1880 _cleanup_free_ char *p = NULL;
1883 r = cg_get_path(controller, path, attribute, &p);
1887 return read_one_line_file(p, ret);
1890 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
1894 /* This one will create a cgroup in our private tree, but also
1895 * duplicate it in the trees specified in mask, and remove it
1898 /* First create the cgroup in our own hierarchy. */
1899 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1903 /* If we are in the unified hierarchy, we are done now */
1904 unified = cg_unified();
1910 /* Otherwise, do the same in the other hierarchies */
1911 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1912 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1915 n = cgroup_controller_to_string(c);
1918 (void) cg_create(n, path);
1919 else if (supported & bit)
1920 (void) cg_trim(n, path, true);
1926 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
1930 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
1934 unified = cg_unified();
1940 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1941 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1942 const char *p = NULL;
1944 if (!(supported & bit))
1948 p = path_callback(bit, userdata);
1953 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
1959 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
1964 SET_FOREACH(pidp, pids, i) {
1965 pid_t pid = PTR_TO_PID(pidp);
1968 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
1969 if (q < 0 && r >= 0)
1976 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
1980 if (!path_equal(from, to)) {
1981 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, false, true);
1986 unified = cg_unified();
1992 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1993 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1994 const char *p = NULL;
1996 if (!(supported & bit))
2000 p = to_callback(bit, userdata);
2005 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, false, false);
2011 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2015 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2019 unified = cg_unified();
2025 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2026 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2028 if (!(supported & bit))
2031 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2038 int cg_mask_supported(CGroupMask *ret) {
2039 CGroupMask mask = 0;
2042 /* Determines the mask of supported cgroup controllers. Only
2043 * includes controllers we can make sense of and that are
2044 * actually accessible. */
2046 unified = cg_unified();
2050 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2053 /* In the unified hierarchy we can read the supported
2054 * and accessible controllers from a the top-level
2055 * cgroup attribute */
2057 r = cg_get_root_path(&root);
2061 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2065 r = read_one_line_file(path, &controllers);
2071 _cleanup_free_ char *n = NULL;
2074 r = extract_first_word(&c, &n, NULL, 0);
2080 v = cgroup_controller_from_string(n);
2084 mask |= CGROUP_CONTROLLER_TO_MASK(v);
2087 /* Currently, we only support the memory and pids
2088 * controller in the unified hierarchy, mask
2089 * everything else off. */
2090 mask &= CGROUP_MASK_MEMORY | CGROUP_MASK_PIDS;
2095 /* In the legacy hierarchy, we check whether which
2096 * hierarchies are mounted. */
2098 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2101 n = cgroup_controller_to_string(c);
2102 if (controller_is_accessible(n) >= 0)
2103 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2111 /// UNNEEDED by elogind
2113 int cg_kernel_controllers(Set *controllers) {
2114 _cleanup_fclose_ FILE *f = NULL;
2118 assert(controllers);
2120 /* Determines the full list of kernel-known controllers. Might
2121 * include controllers we don't actually support, arbitrary
2122 * named hierarchies and controllers that aren't currently
2123 * accessible (because not mounted). */
2125 f = fopen("/proc/cgroups", "re");
2127 if (errno == ENOENT)
2132 /* Ignore the header line */
2133 (void) fgets(buf, sizeof(buf), f);
2140 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2145 if (ferror(f) && errno != 0)
2156 if (!cg_controller_is_valid(controller)) {
2161 r = set_consume(controllers, controller);
2170 static thread_local int unified_cache = -1;
2172 int cg_unified(void) {
2175 /* Checks if we support the unified hierarchy. Returns an
2176 * error when the cgroup hierarchies aren't mounted yet or we
2177 * have any other trouble determining if the unified hierarchy
2180 if (unified_cache >= 0)
2181 return unified_cache;
2183 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2186 /// elogind can not support the unified hierarchy as a controller,
2187 /// so always assume a classical hierarchy.
2188 /// If, ond only *if*, someone really wants to substitute systemd-login
2189 /// in an environment managed by systemd with elogin, we might have to
2190 /// add such a support.
2192 if (F_TYPE_EQUAL(fs.f_type, CGROUP_SUPER_MAGIC))
2193 unified_cache = true;
2194 else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2196 if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2198 unified_cache = false;
2202 return unified_cache;
2205 /// UNNEEDED by elogind
2207 void cg_unified_flush(void) {
2211 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2212 _cleanup_free_ char *fs = NULL;
2221 unified = cg_unified();
2224 if (!unified) /* on the legacy hiearchy there's no joining of controllers defined */
2227 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2231 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2232 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2235 if (!(supported & bit))
2238 n = cgroup_controller_to_string(c);
2240 char s[1 + strlen(n) + 1];
2242 s[0] = mask & bit ? '+' : '-';
2245 r = write_string_file(fs, s, 0);
2247 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2254 bool cg_is_unified_wanted(void) {
2255 static thread_local int wanted = -1;
2258 /* If the hierarchy is already mounted, then follow whatever
2259 * was chosen for it. */
2260 unified = cg_unified();
2264 /* Otherwise, let's see what the kernel command line has to
2265 * say. Since checking that is expensive, let's cache the
2270 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL);
2272 return (wanted = true);
2274 _cleanup_free_ char *value = NULL;
2276 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value);
2280 return (wanted = false);
2282 return (wanted = parse_boolean(value) > 0);
2286 bool cg_is_legacy_wanted(void) {
2287 return !cg_is_unified_wanted();
2290 bool cg_is_legacy_wanted(void) {
2295 /// UNNEEDED by elogind
2297 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2302 *ret = CGROUP_CPU_SHARES_INVALID;
2306 r = safe_atou64(s, &u);
2310 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2317 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2322 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2326 r = safe_atou64(s, &u);
2330 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2338 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2339 [CGROUP_CONTROLLER_CPU] = "cpu",
2340 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2341 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2342 [CGROUP_CONTROLLER_MEMORY] = "memory",
2343 [CGROUP_CONTROLLER_DEVICES] = "devices",
2344 [CGROUP_CONTROLLER_PIDS] = "pids",
2345 [CGROUP_CONTROLLER_NET_CLS] = "net_cls",
2348 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);