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 /* This goes through the tasks list and kills them all. This
217 * is repeated until no further processes are added to the
218 * tasks list, to properly handle forking processes */
221 s = allocated_set = set_new(NULL);
229 _cleanup_fclose_ FILE *f = NULL;
233 r = cg_enumerate_processes(controller, path, &f);
235 if (ret >= 0 && r != -ENOENT)
241 while ((r = cg_read_pid(f, &pid)) > 0) {
243 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
246 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
250 log_kill(pid, sig, userdata);
252 /* If we haven't killed this process yet, kill
254 if (kill(pid, sig) < 0) {
255 if (ret >= 0 && errno != ESRCH)
258 if (flags & CGROUP_SIGCONT)
259 (void) kill(pid, SIGCONT);
267 r = set_put(s, PID_TO_PTR(pid));
283 /* To avoid racing against processes which fork
284 * quicker than we can kill them we repeat this until
285 * no new pids need to be killed. */
292 int cg_kill_recursive(
293 const char *controller,
298 cg_kill_log_func_t log_kill,
301 _cleanup_set_free_ Set *allocated_set = NULL;
302 _cleanup_closedir_ DIR *d = NULL;
310 s = allocated_set = set_new(NULL);
315 ret = cg_kill(controller, path, sig, flags, s, log_kill, userdata);
317 r = cg_enumerate_subgroups(controller, path, &d);
319 if (ret >= 0 && r != -ENOENT)
325 while ((r = cg_read_subgroup(d, &fn)) > 0) {
326 _cleanup_free_ char *p = NULL;
328 p = strjoin(path, "/", fn, NULL);
333 r = cg_kill_recursive(controller, p, sig, flags, s, log_kill, userdata);
334 if (r != 0 && ret >= 0)
337 if (ret >= 0 && r < 0)
340 if (flags & CGROUP_REMOVE) {
341 r = cg_rmdir(controller, path);
342 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
357 _cleanup_set_free_ Set *s = NULL;
372 log_debug_elogind("Migrating \"%s\"/\"%s\" to \"%s\"/\"%s\" (%s)",
373 cfrom, pfrom, cto, pto,
374 ignore_self ? "ignoring self" : "watching self");
376 _cleanup_fclose_ FILE *f = NULL;
380 r = cg_enumerate_processes(cfrom, pfrom, &f);
382 if (ret >= 0 && r != -ENOENT)
388 while ((r = cg_read_pid(f, &pid)) > 0) {
390 /* This might do weird stuff if we aren't a
391 * single-threaded program. However, we
392 * luckily know we are not */
393 if ((flags & CGROUP_IGNORE_SELF) && pid == my_pid)
396 if (set_get(s, PID_TO_PTR(pid)) == PID_TO_PTR(pid))
399 /* Ignore kernel threads. Since they can only
400 * exist in the root cgroup, we only check for
403 (isempty(pfrom) || path_equal(pfrom, "/")) &&
404 is_kernel_thread(pid) > 0)
407 r = cg_attach(cto, pto, pid);
409 if (ret >= 0 && r != -ESRCH)
416 r = set_put(s, PID_TO_PTR(pid));
436 int cg_migrate_recursive(
443 _cleanup_closedir_ DIR *d = NULL;
452 ret = cg_migrate(cfrom, pfrom, cto, pto, flags);
454 r = cg_enumerate_subgroups(cfrom, pfrom, &d);
456 if (ret >= 0 && r != -ENOENT)
462 while ((r = cg_read_subgroup(d, &fn)) > 0) {
463 _cleanup_free_ char *p = NULL;
465 p = strjoin(pfrom, "/", fn, NULL);
470 r = cg_migrate_recursive(cfrom, p, cto, pto, flags);
471 if (r != 0 && ret >= 0)
475 if (r < 0 && ret >= 0)
478 if (flags & CGROUP_REMOVE) {
479 r = cg_rmdir(cfrom, pfrom);
480 if (r < 0 && ret >= 0 && r != -ENOENT && r != -EBUSY)
487 int cg_migrate_recursive_fallback(
501 r = cg_migrate_recursive(cfrom, pfrom, cto, pto, flags);
503 char prefix[strlen(pto) + 1];
505 /* This didn't work? Then let's try all prefixes of the destination */
507 PATH_FOREACH_PREFIX(prefix, pto) {
510 q = cg_migrate_recursive(cfrom, pfrom, cto, prefix, flags);
519 static const char *controller_to_dirname(const char *controller) {
524 /* Converts a controller name to the directory name below
525 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
526 * just cuts off the name= prefixed used for named
527 * hierarchies, if it is specified. */
529 e = startswith(controller, "name=");
536 static int join_path_legacy(const char *controller, const char *path, const char *suffix, char **fs) {
543 dn = controller_to_dirname(controller);
545 if (isempty(path) && isempty(suffix))
546 t = strappend("/sys/fs/cgroup/", dn);
547 else if (isempty(path))
548 t = strjoin("/sys/fs/cgroup/", dn, "/", suffix, NULL);
549 else if (isempty(suffix))
550 t = strjoin("/sys/fs/cgroup/", dn, "/", path, NULL);
552 t = strjoin("/sys/fs/cgroup/", dn, "/", path, "/", suffix, NULL);
560 static int join_path_unified(const char *path, const char *suffix, char **fs) {
565 if (isempty(path) && isempty(suffix))
566 t = strdup("/sys/fs/cgroup");
567 else if (isempty(path))
568 t = strappend("/sys/fs/cgroup/", suffix);
569 else if (isempty(suffix))
570 t = strappend("/sys/fs/cgroup/", path);
572 t = strjoin("/sys/fs/cgroup/", path, "/", suffix, NULL);
580 int cg_get_path(const char *controller, const char *path, const char *suffix, char **fs) {
588 /* If no controller is specified, we return the path
589 * *below* the controllers, without any prefix. */
591 if (!path && !suffix)
599 t = strjoin(path, "/", suffix, NULL);
603 *fs = path_kill_slashes(t);
607 if (!cg_controller_is_valid(controller))
610 unified = cg_unified();
615 r = join_path_unified(path, suffix, fs);
617 r = join_path_legacy(controller, path, suffix, fs);
621 path_kill_slashes(*fs);
625 static int controller_is_accessible(const char *controller) {
630 /* Checks whether a specific controller is accessible,
631 * i.e. its hierarchy mounted. In the unified hierarchy all
632 * controllers are considered accessible, except for the named
635 if (!cg_controller_is_valid(controller))
638 unified = cg_unified();
642 /* We don't support named hierarchies if we are using
643 * the unified hierarchy. */
645 if (streq(controller, SYSTEMD_CGROUP_CONTROLLER))
648 if (startswith(controller, "name="))
654 dn = controller_to_dirname(controller);
655 cc = strjoina("/sys/fs/cgroup/", dn);
657 if (laccess(cc, F_OK) < 0)
664 int cg_get_path_and_check(const char *controller, const char *path, const char *suffix, char **fs) {
670 /* Check if the specified controller is actually accessible */
671 r = controller_is_accessible(controller);
675 return cg_get_path(controller, path, suffix, fs);
678 static int trim_cb(const char *path, const struct stat *sb, int typeflag, struct FTW *ftwbuf) {
683 if (typeflag != FTW_DP)
686 if (ftwbuf->level < 1)
693 int cg_trim(const char *controller, const char *path, bool delete_root) {
694 _cleanup_free_ char *fs = NULL;
699 r = cg_get_path(controller, path, NULL, &fs);
704 if (nftw(fs, trim_cb, 64, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) != 0) {
714 if (rmdir(fs) < 0 && errno != ENOENT)
721 int cg_create(const char *controller, const char *path) {
722 _cleanup_free_ char *fs = NULL;
725 r = cg_get_path_and_check(controller, path, NULL, &fs);
729 r = mkdir_parents(fs, 0755);
733 if (mkdir(fs, 0755) < 0) {
744 int cg_create_and_attach(const char *controller, const char *path, pid_t pid) {
749 r = cg_create(controller, path);
753 q = cg_attach(controller, path, pid);
757 /* This does not remove the cgroup on failure */
761 int cg_attach(const char *controller, const char *path, pid_t pid) {
762 _cleanup_free_ char *fs = NULL;
763 char c[DECIMAL_STR_MAX(pid_t) + 2];
769 r = cg_get_path_and_check(controller, path, "cgroup.procs", &fs);
776 xsprintf(c, PID_FMT "\n", pid);
778 return write_string_file(fs, c, 0);
781 int cg_attach_fallback(const char *controller, const char *path, pid_t pid) {
788 r = cg_attach(controller, path, pid);
790 char prefix[strlen(path) + 1];
792 /* This didn't work? Then let's try all prefixes of
795 PATH_FOREACH_PREFIX(prefix, path) {
798 q = cg_attach(controller, prefix, pid);
807 #if 0 /// UNNEEDED by elogind
808 int cg_set_group_access(
809 const char *controller,
815 _cleanup_free_ char *fs = NULL;
818 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
821 if (mode != MODE_INVALID)
824 r = cg_get_path(controller, path, NULL, &fs);
828 return chmod_and_chown(fs, mode, uid, gid);
831 int cg_set_task_access(
832 const char *controller,
838 _cleanup_free_ char *fs = NULL, *procs = NULL;
843 if (mode == MODE_INVALID && uid == UID_INVALID && gid == GID_INVALID)
846 if (mode != MODE_INVALID)
849 r = cg_get_path(controller, path, "cgroup.procs", &fs);
853 r = chmod_and_chown(fs, mode, uid, gid);
857 unified = cg_unified();
863 /* Compatibility, Always keep values for "tasks" in sync with
865 if (cg_get_path(controller, path, "tasks", &procs) >= 0)
866 (void) chmod_and_chown(procs, mode, uid, gid);
872 int cg_pid_get_path(const char *controller, pid_t pid, char **path) {
873 _cleanup_fclose_ FILE *f = NULL;
882 unified = cg_unified();
887 if (!cg_controller_is_valid(controller))
890 controller = SYSTEMD_CGROUP_CONTROLLER;
892 cs = strlen(controller);
895 fs = procfs_file_alloca(pid, "cgroup");
896 log_debug_elogind("Searching for PID %u in \"%s\" (controller \"%s\")",
897 pid, fs, controller);
900 return errno == ENOENT ? -ESRCH : -errno;
902 FOREACH_LINE(line, f, return -errno) {
908 e = startswith(line, "0:");
918 const char *word, *state;
921 l = strchr(line, ':');
931 FOREACH_WORD_SEPARATOR(word, k, l, ",", state) {
932 if (k == cs && memcmp(word, controller, cs) == 0) {
942 log_debug_elogind("Found %s:%s", line, e+1);
954 int cg_install_release_agent(const char *controller, const char *agent) {
955 _cleanup_free_ char *fs = NULL, *contents = NULL;
961 unified = cg_unified();
964 if (unified) /* doesn't apply to unified hierarchy */
967 r = cg_get_path(controller, NULL, "release_agent", &fs);
971 r = read_one_line_file(fs, &contents);
975 sc = strstrip(contents);
977 r = write_string_file(fs, agent, 0);
980 } else if (!path_equal(sc, agent))
984 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
988 contents = mfree(contents);
989 r = read_one_line_file(fs, &contents);
993 sc = strstrip(contents);
994 if (streq(sc, "0")) {
995 r = write_string_file(fs, "1", 0);
1002 if (!streq(sc, "1"))
1008 int cg_uninstall_release_agent(const char *controller) {
1009 _cleanup_free_ char *fs = NULL;
1012 unified = cg_unified();
1015 if (unified) /* Doesn't apply to unified hierarchy */
1018 r = cg_get_path(controller, NULL, "notify_on_release", &fs);
1022 r = write_string_file(fs, "0", 0);
1028 r = cg_get_path(controller, NULL, "release_agent", &fs);
1032 r = write_string_file(fs, "", 0);
1039 int cg_is_empty(const char *controller, const char *path) {
1040 _cleanup_fclose_ FILE *f = NULL;
1046 r = cg_enumerate_processes(controller, path, &f);
1052 r = cg_read_pid(f, &pid);
1059 int cg_is_empty_recursive(const char *controller, const char *path) {
1064 /* The root cgroup is always populated */
1065 if (controller && (isempty(path) || path_equal(path, "/")))
1068 unified = cg_unified();
1073 _cleanup_free_ char *t = NULL;
1075 /* On the unified hierarchy we can check empty state
1076 * via the "populated" attribute of "cgroup.events". */
1078 r = cg_read_event(controller, path, "populated", &t);
1082 return streq(t, "0");
1084 _cleanup_closedir_ DIR *d = NULL;
1087 r = cg_is_empty(controller, path);
1091 r = cg_enumerate_subgroups(controller, path, &d);
1097 while ((r = cg_read_subgroup(d, &fn)) > 0) {
1098 _cleanup_free_ char *p = NULL;
1100 p = strjoin(path, "/", fn, NULL);
1105 r = cg_is_empty_recursive(controller, p);
1116 int cg_split_spec(const char *spec, char **controller, char **path) {
1117 char *t = NULL, *u = NULL;
1123 if (!path_is_safe(spec))
1131 *path = path_kill_slashes(t);
1140 e = strchr(spec, ':');
1142 if (!cg_controller_is_valid(spec))
1159 t = strndup(spec, e-spec);
1162 if (!cg_controller_is_valid(t)) {
1176 if (!path_is_safe(u) ||
1177 !path_is_absolute(u)) {
1183 path_kill_slashes(u);
1199 int cg_mangle_path(const char *path, char **result) {
1200 _cleanup_free_ char *c = NULL, *p = NULL;
1207 /* First, check if it already is a filesystem path */
1208 if (path_startswith(path, "/sys/fs/cgroup")) {
1214 *result = path_kill_slashes(t);
1218 /* Otherwise, treat it as cg spec */
1219 r = cg_split_spec(path, &c, &p);
1223 return cg_get_path(c ?: SYSTEMD_CGROUP_CONTROLLER, p ?: "/", NULL, result);
1226 int cg_get_root_path(char **path) {
1227 #if 0 /// elogind does not support systemd scopes and slices
1233 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, &p);
1237 e = endswith(p, "/" SPECIAL_INIT_SCOPE);
1239 e = endswith(p, "/" SPECIAL_SYSTEM_SLICE); /* legacy */
1241 e = endswith(p, "/system"); /* even more legacy */
1249 return cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, 1, path);
1253 int cg_shift_path(const char *cgroup, const char *root, const char **shifted) {
1254 _cleanup_free_ char *rt = NULL;
1262 /* If the root was specified let's use that, otherwise
1263 * let's determine it from PID 1 */
1265 r = cg_get_root_path(&rt);
1270 log_debug_elogind("Determined root path: \"%s\"", root);
1273 p = path_startswith(cgroup, root);
1274 if (p && p[0] && (p > cgroup))
1282 int cg_pid_get_path_shifted(pid_t pid, const char *root, char **cgroup) {
1283 _cleanup_free_ char *raw = NULL;
1290 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, pid, &raw);
1294 log_debug_elogind("Shifting path: \"%s\" (PID %u, root: \"%s\")",
1295 raw, pid, root ? root : "NULL");
1296 r = cg_shift_path(raw, root, &c);
1312 log_debug_elogind("Resulting cgroup:\"%s\"", *cgroup);
1317 #if 0 /// UNNEEDED by elogind
1318 int cg_path_decode_unit(const char *cgroup, char **unit) {
1325 n = strcspn(cgroup, "/");
1329 c = strndupa(cgroup, n);
1332 if (!unit_name_is_valid(c, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
1343 static bool valid_slice_name(const char *p, size_t n) {
1348 if (n < strlen("x.slice"))
1351 if (memcmp(p + n - 6, ".slice", 6) == 0) {
1357 c = cg_unescape(buf);
1359 return unit_name_is_valid(c, UNIT_NAME_PLAIN);
1365 static const char *skip_slices(const char *p) {
1368 /* Skips over all slice assignments */
1373 p += strspn(p, "/");
1375 n = strcspn(p, "/");
1376 if (!valid_slice_name(p, n))
1383 int cg_path_get_unit(const char *path, char **ret) {
1391 e = skip_slices(path);
1393 r = cg_path_decode_unit(e, &unit);
1397 /* We skipped over the slices, don't accept any now */
1398 if (endswith(unit, ".slice")) {
1407 int cg_pid_get_unit(pid_t pid, char **unit) {
1408 _cleanup_free_ char *cgroup = NULL;
1413 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1417 return cg_path_get_unit(cgroup, unit);
1421 * Skip session-*.scope, but require it to be there.
1423 static const char *skip_session(const char *p) {
1429 p += strspn(p, "/");
1431 n = strcspn(p, "/");
1432 if (n < strlen("session-x.scope"))
1435 if (memcmp(p, "session-", 8) == 0 && memcmp(p + n - 6, ".scope", 6) == 0) {
1436 char buf[n - 8 - 6 + 1];
1438 memcpy(buf, p + 8, n - 8 - 6);
1441 /* Note that session scopes never need unescaping,
1442 * since they cannot conflict with the kernel's own
1443 * names, hence we don't need to call cg_unescape()
1446 if (!session_id_valid(buf))
1450 p += strspn(p, "/");
1458 * Skip user@*.service, but require it to be there.
1460 static const char *skip_user_manager(const char *p) {
1466 p += strspn(p, "/");
1468 n = strcspn(p, "/");
1469 if (n < strlen("user@x.service"))
1472 if (memcmp(p, "user@", 5) == 0 && memcmp(p + n - 8, ".service", 8) == 0) {
1473 char buf[n - 5 - 8 + 1];
1475 memcpy(buf, p + 5, n - 5 - 8);
1478 /* Note that user manager services never need unescaping,
1479 * since they cannot conflict with the kernel's own
1480 * names, hence we don't need to call cg_unescape()
1483 if (parse_uid(buf, NULL) < 0)
1487 p += strspn(p, "/");
1495 static const char *skip_user_prefix(const char *path) {
1500 /* Skip slices, if there are any */
1501 e = skip_slices(path);
1503 /* Skip the user manager, if it's in the path now... */
1504 t = skip_user_manager(e);
1508 /* Alternatively skip the user session if it is in the path... */
1509 return skip_session(e);
1512 int cg_path_get_user_unit(const char *path, char **ret) {
1518 t = skip_user_prefix(path);
1522 /* And from here on it looks pretty much the same as for a
1523 * system unit, hence let's use the same parser from here
1525 return cg_path_get_unit(t, ret);
1528 int cg_pid_get_user_unit(pid_t pid, char **unit) {
1529 _cleanup_free_ char *cgroup = NULL;
1534 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1538 return cg_path_get_user_unit(cgroup, unit);
1541 int cg_path_get_machine_name(const char *path, char **machine) {
1542 _cleanup_free_ char *u = NULL;
1546 r = cg_path_get_unit(path, &u);
1550 sl = strjoina("/run/systemd/machines/unit:", u);
1551 return readlink_malloc(sl, machine);
1554 int cg_pid_get_machine_name(pid_t pid, char **machine) {
1555 _cleanup_free_ char *cgroup = NULL;
1560 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1564 return cg_path_get_machine_name(cgroup, machine);
1568 int cg_path_get_session(const char *path, char **session) {
1569 #if 0 /// UNNEEDED by elogind
1570 _cleanup_free_ char *unit = NULL;
1576 r = cg_path_get_unit(path, &unit);
1580 start = startswith(unit, "session-");
1583 end = endswith(start, ".scope");
1588 if (!session_id_valid(start))
1591 /* Elogind uses a flat hierarchy, just "/SESSION". The only
1592 wrinkle is that SESSION might be escaped. */
1593 const char *e, *n, *start;
1596 log_debug_elogind("path is \"%s\"", path);
1597 assert(path[0] == '/');
1600 n = strchrnul(e, '/');
1604 start = strndupa(e, n - e);
1605 start = cg_unescape(start);
1614 log_debug_elogind("found session: \"%s\"", start);
1625 int cg_pid_get_session(pid_t pid, char **session) {
1626 _cleanup_free_ char *cgroup = NULL;
1629 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1633 return cg_path_get_session(cgroup, session);
1636 #if 0 /// UNNEEDED by elogind
1637 int cg_path_get_owner_uid(const char *path, uid_t *uid) {
1638 _cleanup_free_ char *slice = NULL;
1644 r = cg_path_get_slice(path, &slice);
1648 start = startswith(slice, "user-");
1651 end = endswith(start, ".slice");
1656 if (parse_uid(start, uid) < 0)
1662 int cg_pid_get_owner_uid(pid_t pid, uid_t *uid) {
1663 _cleanup_free_ char *cgroup = NULL;
1666 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1670 return cg_path_get_owner_uid(cgroup, uid);
1673 int cg_path_get_slice(const char *p, char **slice) {
1674 const char *e = NULL;
1679 /* Finds the right-most slice unit from the beginning, but
1680 * stops before we come to the first non-slice unit. */
1685 p += strspn(p, "/");
1687 n = strcspn(p, "/");
1688 if (!valid_slice_name(p, n)) {
1693 s = strdup("-.slice");
1701 return cg_path_decode_unit(e, slice);
1709 int cg_pid_get_slice(pid_t pid, char **slice) {
1710 _cleanup_free_ char *cgroup = NULL;
1715 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1719 return cg_path_get_slice(cgroup, slice);
1722 int cg_path_get_user_slice(const char *p, char **slice) {
1727 t = skip_user_prefix(p);
1731 /* And now it looks pretty much the same as for a system
1732 * slice, so let's just use the same parser from here on. */
1733 return cg_path_get_slice(t, slice);
1736 int cg_pid_get_user_slice(pid_t pid, char **slice) {
1737 _cleanup_free_ char *cgroup = NULL;
1742 r = cg_pid_get_path_shifted(pid, NULL, &cgroup);
1746 return cg_path_get_user_slice(cgroup, slice);
1750 char *cg_escape(const char *p) {
1751 bool need_prefix = false;
1753 /* This implements very minimal escaping for names to be used
1754 * as file names in the cgroup tree: any name which might
1755 * conflict with a kernel name or is prefixed with '_' is
1756 * prefixed with a '_'. That way, when reading cgroup names it
1757 * is sufficient to remove a single prefixing underscore if
1760 /* The return value of this function (unlike cg_unescape())
1766 streq(p, "notify_on_release") ||
1767 streq(p, "release_agent") ||
1768 streq(p, "tasks") ||
1769 startswith(p, "cgroup."))
1774 dot = strrchr(p, '.');
1779 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1782 n = cgroup_controller_to_string(c);
1787 if (memcmp(p, n, l) != 0)
1797 return strappend("_", p);
1802 char *cg_unescape(const char *p) {
1805 /* The return value of this function (unlike cg_escape())
1806 * doesn't need free()! */
1814 #define CONTROLLER_VALID \
1818 bool cg_controller_is_valid(const char *p) {
1824 s = startswith(p, "name=");
1828 if (*p == 0 || *p == '_')
1831 for (t = p; *t; t++)
1832 if (!strchr(CONTROLLER_VALID, *t))
1835 if (t - p > FILENAME_MAX)
1841 #if 0 /// UNNEEDED by elogind
1842 int cg_slice_to_path(const char *unit, char **ret) {
1843 _cleanup_free_ char *p = NULL, *s = NULL, *e = NULL;
1850 if (streq(unit, "-.slice")) {
1860 if (!unit_name_is_valid(unit, UNIT_NAME_PLAIN))
1863 if (!endswith(unit, ".slice"))
1866 r = unit_name_to_prefix(unit, &p);
1870 dash = strchr(p, '-');
1872 /* Don't allow initial dashes */
1877 _cleanup_free_ char *escaped = NULL;
1878 char n[dash - p + sizeof(".slice")];
1880 /* Don't allow trailing or double dashes */
1881 if (dash[1] == 0 || dash[1] == '-')
1884 strcpy(stpncpy(n, p, dash - p), ".slice");
1885 if (!unit_name_is_valid(n, UNIT_NAME_PLAIN))
1888 escaped = cg_escape(n);
1892 if (!strextend(&s, escaped, "/", NULL))
1895 dash = strchr(dash+1, '-');
1898 e = cg_escape(unit);
1902 if (!strextend(&s, e, NULL))
1912 int cg_set_attribute(const char *controller, const char *path, const char *attribute, const char *value) {
1913 _cleanup_free_ char *p = NULL;
1916 r = cg_get_path(controller, path, attribute, &p);
1920 return write_string_file(p, value, 0);
1923 #if 0 /// UNNEEDED by elogind
1924 int cg_get_attribute(const char *controller, const char *path, const char *attribute, char **ret) {
1925 _cleanup_free_ char *p = NULL;
1928 r = cg_get_path(controller, path, attribute, &p);
1932 return read_one_line_file(p, ret);
1935 int cg_create_everywhere(CGroupMask supported, CGroupMask mask, const char *path) {
1939 /* This one will create a cgroup in our private tree, but also
1940 * duplicate it in the trees specified in mask, and remove it
1943 /* First create the cgroup in our own hierarchy. */
1944 r = cg_create(SYSTEMD_CGROUP_CONTROLLER, path);
1948 /* If we are in the unified hierarchy, we are done now */
1949 unified = cg_unified();
1955 /* Otherwise, do the same in the other hierarchies */
1956 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1957 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1960 n = cgroup_controller_to_string(c);
1963 (void) cg_create(n, path);
1964 else if (supported & bit)
1965 (void) cg_trim(n, path, true);
1971 int cg_attach_everywhere(CGroupMask supported, const char *path, pid_t pid, cg_migrate_callback_t path_callback, void *userdata) {
1975 r = cg_attach(SYSTEMD_CGROUP_CONTROLLER, path, pid);
1979 unified = cg_unified();
1985 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
1986 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
1987 const char *p = NULL;
1989 if (!(supported & bit))
1993 p = path_callback(bit, userdata);
1998 (void) cg_attach_fallback(cgroup_controller_to_string(c), p, pid);
2004 int cg_attach_many_everywhere(CGroupMask supported, const char *path, Set* pids, cg_migrate_callback_t path_callback, void *userdata) {
2009 SET_FOREACH(pidp, pids, i) {
2010 pid_t pid = PTR_TO_PID(pidp);
2013 q = cg_attach_everywhere(supported, path, pid, path_callback, userdata);
2014 if (q < 0 && r >= 0)
2021 int cg_migrate_everywhere(CGroupMask supported, const char *from, const char *to, cg_migrate_callback_t to_callback, void *userdata) {
2025 if (!path_equal(from, to)) {
2026 r = cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER, from, SYSTEMD_CGROUP_CONTROLLER, to, CGROUP_REMOVE);
2031 unified = cg_unified();
2037 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2038 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2039 const char *p = NULL;
2041 if (!(supported & bit))
2045 p = to_callback(bit, userdata);
2050 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER, to, cgroup_controller_to_string(c), p, 0);
2056 int cg_trim_everywhere(CGroupMask supported, const char *path, bool delete_root) {
2060 r = cg_trim(SYSTEMD_CGROUP_CONTROLLER, path, delete_root);
2064 unified = cg_unified();
2070 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2071 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2073 if (!(supported & bit))
2076 (void) cg_trim(cgroup_controller_to_string(c), path, delete_root);
2083 int cg_mask_supported(CGroupMask *ret) {
2084 CGroupMask mask = 0;
2087 /* Determines the mask of supported cgroup controllers. Only
2088 * includes controllers we can make sense of and that are
2089 * actually accessible. */
2091 unified = cg_unified();
2095 _cleanup_free_ char *root = NULL, *controllers = NULL, *path = NULL;
2098 /* In the unified hierarchy we can read the supported
2099 * and accessible controllers from a the top-level
2100 * cgroup attribute */
2102 r = cg_get_root_path(&root);
2106 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, root, "cgroup.controllers", &path);
2110 r = read_one_line_file(path, &controllers);
2116 _cleanup_free_ char *n = NULL;
2119 r = extract_first_word(&c, &n, NULL, 0);
2125 v = cgroup_controller_from_string(n);
2129 mask |= CGROUP_CONTROLLER_TO_MASK(v);
2132 /* Currently, we only support the memory, io and pids
2133 * controller in the unified hierarchy, mask
2134 * everything else off. */
2135 mask &= CGROUP_MASK_MEMORY | CGROUP_MASK_IO | CGROUP_MASK_PIDS;
2140 /* In the legacy hierarchy, we check whether which
2141 * hierarchies are mounted. */
2143 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2146 n = cgroup_controller_to_string(c);
2147 if (controller_is_accessible(n) >= 0)
2148 mask |= CGROUP_CONTROLLER_TO_MASK(c);
2156 #if 0 /// UNNEEDED by elogind
2157 int cg_kernel_controllers(Set *controllers) {
2158 _cleanup_fclose_ FILE *f = NULL;
2162 assert(controllers);
2164 /* Determines the full list of kernel-known controllers. Might
2165 * include controllers we don't actually support, arbitrary
2166 * named hierarchies and controllers that aren't currently
2167 * accessible (because not mounted). */
2169 f = fopen("/proc/cgroups", "re");
2171 if (errno == ENOENT)
2176 /* Ignore the header line */
2177 (void) fgets(buf, sizeof(buf), f);
2184 if (fscanf(f, "%ms %*i %*i %i", &controller, &enabled) != 2) {
2189 if (ferror(f) && errno > 0)
2200 if (!cg_controller_is_valid(controller)) {
2205 r = set_consume(controllers, controller);
2214 static thread_local int unified_cache = -1;
2216 int cg_unified(void) {
2219 /* Checks if we support the unified hierarchy. Returns an
2220 * error when the cgroup hierarchies aren't mounted yet or we
2221 * have any other trouble determining if the unified hierarchy
2224 if (unified_cache >= 0)
2225 return unified_cache;
2227 if (statfs("/sys/fs/cgroup/", &fs) < 0)
2230 #if 0 /// UNNEEDED by elogind
2231 if (F_TYPE_EQUAL(fs.f_type, CGROUP2_SUPER_MAGIC))
2232 unified_cache = true;
2233 else if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2235 /* elogind can not support the unified hierarchy as a controller,
2236 * so always assume a classical hierarchy.
2237 * If, ond only *if*, someone really wants to substitute systemd-login
2238 * in an environment managed by systemd with elogin, we might have to
2239 * add such a support. */
2240 if (F_TYPE_EQUAL(fs.f_type, TMPFS_MAGIC))
2242 unified_cache = false;
2246 return unified_cache;
2249 #if 0 /// UNNEEDED by elogind
2250 void cg_unified_flush(void) {
2254 int cg_enable_everywhere(CGroupMask supported, CGroupMask mask, const char *p) {
2255 _cleanup_free_ char *fs = NULL;
2264 unified = cg_unified();
2267 if (!unified) /* on the legacy hiearchy there's no joining of controllers defined */
2270 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, p, "cgroup.subtree_control", &fs);
2274 for (c = 0; c < _CGROUP_CONTROLLER_MAX; c++) {
2275 CGroupMask bit = CGROUP_CONTROLLER_TO_MASK(c);
2278 if (!(supported & bit))
2281 n = cgroup_controller_to_string(c);
2283 char s[1 + strlen(n) + 1];
2285 s[0] = mask & bit ? '+' : '-';
2288 r = write_string_file(fs, s, 0);
2290 log_debug_errno(r, "Failed to enable controller %s for %s (%s): %m", n, p, fs);
2297 bool cg_is_unified_wanted(void) {
2298 static thread_local int wanted = -1;
2301 /* If the hierarchy is already mounted, then follow whatever
2302 * was chosen for it. */
2303 unified = cg_unified();
2307 /* Otherwise, let's see what the kernel command line has to
2308 * say. Since checking that is expensive, let's cache the
2313 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy", NULL);
2315 return (wanted = true);
2317 _cleanup_free_ char *value = NULL;
2319 r = get_proc_cmdline_key("systemd.unified_cgroup_hierarchy=", &value);
2323 return (wanted = false);
2325 return (wanted = parse_boolean(value) > 0);
2329 bool cg_is_legacy_wanted(void) {
2330 return !cg_is_unified_wanted();
2333 bool cg_is_legacy_wanted(void) {
2338 #if 0 /// UNNEEDED by elogind
2339 int cg_weight_parse(const char *s, uint64_t *ret) {
2344 *ret = CGROUP_WEIGHT_INVALID;
2348 r = safe_atou64(s, &u);
2352 if (u < CGROUP_WEIGHT_MIN || u > CGROUP_WEIGHT_MAX)
2359 const uint64_t cgroup_io_limit_defaults[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2360 [CGROUP_IO_RBPS_MAX] = CGROUP_LIMIT_MAX,
2361 [CGROUP_IO_WBPS_MAX] = CGROUP_LIMIT_MAX,
2362 [CGROUP_IO_RIOPS_MAX] = CGROUP_LIMIT_MAX,
2363 [CGROUP_IO_WIOPS_MAX] = CGROUP_LIMIT_MAX,
2366 static const char* const cgroup_io_limit_type_table[_CGROUP_IO_LIMIT_TYPE_MAX] = {
2367 [CGROUP_IO_RBPS_MAX] = "IOReadBandwidthMax",
2368 [CGROUP_IO_WBPS_MAX] = "IOWriteBandwidthMax",
2369 [CGROUP_IO_RIOPS_MAX] = "IOReadIOPSMax",
2370 [CGROUP_IO_WIOPS_MAX] = "IOWriteIOPSMax",
2373 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type, CGroupIOLimitType);
2375 int cg_cpu_shares_parse(const char *s, uint64_t *ret) {
2380 *ret = CGROUP_CPU_SHARES_INVALID;
2384 r = safe_atou64(s, &u);
2388 if (u < CGROUP_CPU_SHARES_MIN || u > CGROUP_CPU_SHARES_MAX)
2395 int cg_blkio_weight_parse(const char *s, uint64_t *ret) {
2400 *ret = CGROUP_BLKIO_WEIGHT_INVALID;
2404 r = safe_atou64(s, &u);
2408 if (u < CGROUP_BLKIO_WEIGHT_MIN || u > CGROUP_BLKIO_WEIGHT_MAX)
2416 static const char *cgroup_controller_table[_CGROUP_CONTROLLER_MAX] = {
2417 [CGROUP_CONTROLLER_CPU] = "cpu",
2418 [CGROUP_CONTROLLER_CPUACCT] = "cpuacct",
2419 [CGROUP_CONTROLLER_IO] = "io",
2420 [CGROUP_CONTROLLER_BLKIO] = "blkio",
2421 [CGROUP_CONTROLLER_MEMORY] = "memory",
2422 [CGROUP_CONTROLLER_DEVICES] = "devices",
2423 [CGROUP_CONTROLLER_PIDS] = "pids",
2426 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller, CGroupController);