1 /* SPDX-License-Identifier: LGPL-2.1+ */
13 #include <sys/statfs.h>
14 #include <sys/types.h>
15 #include <sys/utsname.h>
16 #include <sys/xattr.h>
19 #include "alloc-util.h"
20 #include "cgroup-util.h"
22 #include "dirent-util.h"
23 #include "extract-word.h"
26 #include "format-util.h"
29 #include "login-util.h"
33 #include "parse-util.h"
34 #include "path-util.h"
35 #include "proc-cmdline.h"
36 #include "process-util.h"
39 #include "stat-util.h"
40 #include "stdio-util.h"
41 #include "string-table.h"
42 #include "string-util.h"
44 #include "unit-name.h"
45 #include "user-util.h"
47 int cg_enumerate_processes(const char *controller
, const char *path
, FILE **_f
) {
48 _cleanup_free_
char *fs
= NULL
;
54 r
= cg_get_path(controller
, path
, "cgroup.procs", &fs
);
66 int cg_read_pid(FILE *f
, pid_t
*_pid
) {
69 /* Note that the cgroup.procs might contain duplicates! See
70 * cgroups.txt for details. */
76 if (fscanf(f
, "%lu", &ul
) != 1) {
81 return errno
> 0 ? -errno
: -EIO
;
92 const char *controller
,
97 _cleanup_free_
char *events
= NULL
, *content
= NULL
;
101 r
= cg_get_path(controller
, path
, "cgroup.events", &events
);
105 r
= read_full_file(events
, &content
, NULL
);
110 while ((line
= strsep(&p
, "\n"))) {
113 key
= strsep(&line
, " ");
117 if (strcmp(key
, event
))
127 bool cg_ns_supported(void) {
128 static thread_local
int enabled
= -1;
133 if (access("/proc/self/ns/cgroup", F_OK
) < 0) {
135 log_debug_errno(errno
, "Failed to check whether /proc/self/ns/cgroup is available, assuming not: %m");
143 int cg_enumerate_subgroups(const char *controller
, const char *path
, DIR **_d
) {
144 _cleanup_free_
char *fs
= NULL
;
150 /* This is not recursive! */
152 r
= cg_get_path(controller
, path
, NULL
, &fs
);
164 int cg_read_subgroup(DIR *d
, char **fn
) {
170 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
173 if (de
->d_type
!= DT_DIR
)
176 if (dot_or_dot_dot(de
->d_name
))
179 b
= strdup(de
->d_name
);
190 int cg_rmdir(const char *controller
, const char *path
) {
191 _cleanup_free_
char *p
= NULL
;
194 r
= cg_get_path(controller
, path
, NULL
, &p
);
199 if (r
< 0 && errno
!= ENOENT
)
202 r
= cg_hybrid_unified();
206 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
207 r
= cg_rmdir(SYSTEMD_CGROUP_CONTROLLER_LEGACY
, path
);
209 log_warning_errno(r
, "Failed to remove compat systemd cgroup %s: %m", path
);
216 const char *controller
,
221 cg_kill_log_func_t log_kill
,
224 _cleanup_set_free_ Set
*allocated_set
= NULL
;
231 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
232 * SIGCONT on SIGKILL. */
233 if (IN_SET(sig
, SIGCONT
, SIGKILL
))
234 flags
&= ~CGROUP_SIGCONT
;
236 /* This goes through the tasks list and kills them all. This
237 * is repeated until no further processes are added to the
238 * tasks list, to properly handle forking processes */
241 s
= allocated_set
= set_new(NULL
);
246 my_pid
= getpid_cached();
249 _cleanup_fclose_
FILE *f
= NULL
;
253 r
= cg_enumerate_processes(controller
, path
, &f
);
255 if (ret
>= 0 && r
!= -ENOENT
)
261 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
263 if ((flags
& CGROUP_IGNORE_SELF
) && pid
== my_pid
)
266 if (set_get(s
, PID_TO_PTR(pid
)) == PID_TO_PTR(pid
))
270 log_kill(pid
, sig
, userdata
);
272 /* If we haven't killed this process yet, kill
274 if (kill(pid
, sig
) < 0) {
275 if (ret
>= 0 && errno
!= ESRCH
)
278 if (flags
& CGROUP_SIGCONT
)
279 (void) kill(pid
, SIGCONT
);
287 r
= set_put(s
, PID_TO_PTR(pid
));
303 /* To avoid racing against processes which fork
304 * quicker than we can kill them we repeat this until
305 * no new pids need to be killed. */
312 int cg_kill_recursive(
313 const char *controller
,
318 cg_kill_log_func_t log_kill
,
321 _cleanup_set_free_ Set
*allocated_set
= NULL
;
322 _cleanup_closedir_
DIR *d
= NULL
;
330 s
= allocated_set
= set_new(NULL
);
335 ret
= cg_kill(controller
, path
, sig
, flags
, s
, log_kill
, userdata
);
337 r
= cg_enumerate_subgroups(controller
, path
, &d
);
339 if (ret
>= 0 && r
!= -ENOENT
)
345 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
346 _cleanup_free_
char *p
= NULL
;
348 p
= strjoin(path
, "/", fn
);
353 r
= cg_kill_recursive(controller
, p
, sig
, flags
, s
, log_kill
, userdata
);
354 if (r
!= 0 && ret
>= 0)
357 if (ret
>= 0 && r
< 0)
360 if (flags
& CGROUP_REMOVE
) {
361 r
= cg_rmdir(controller
, path
);
362 if (r
< 0 && ret
>= 0 && !IN_SET(r
, -ENOENT
, -EBUSY
))
377 _cleanup_set_free_ Set
*s
= NULL
;
390 my_pid
= getpid_cached();
393 _cleanup_fclose_
FILE *f
= NULL
;
397 r
= cg_enumerate_processes(cfrom
, pfrom
, &f
);
399 if (ret
>= 0 && r
!= -ENOENT
)
405 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
407 /* This might do weird stuff if we aren't a
408 * single-threaded program. However, we
409 * luckily know we are not */
410 if ((flags
& CGROUP_IGNORE_SELF
) && pid
== my_pid
)
413 if (set_get(s
, PID_TO_PTR(pid
)) == PID_TO_PTR(pid
))
416 /* Ignore kernel threads. Since they can only
417 * exist in the root cgroup, we only check for
420 empty_or_root(pfrom
) &&
421 is_kernel_thread(pid
) > 0)
424 r
= cg_attach(cto
, pto
, pid
);
426 if (ret
>= 0 && r
!= -ESRCH
)
433 r
= set_put(s
, PID_TO_PTR(pid
));
453 int cg_migrate_recursive(
460 _cleanup_closedir_
DIR *d
= NULL
;
469 ret
= cg_migrate(cfrom
, pfrom
, cto
, pto
, flags
);
471 r
= cg_enumerate_subgroups(cfrom
, pfrom
, &d
);
473 if (ret
>= 0 && r
!= -ENOENT
)
479 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
480 _cleanup_free_
char *p
= NULL
;
482 p
= strjoin(pfrom
, "/", fn
);
487 r
= cg_migrate_recursive(cfrom
, p
, cto
, pto
, flags
);
488 if (r
!= 0 && ret
>= 0)
492 if (r
< 0 && ret
>= 0)
495 if (flags
& CGROUP_REMOVE
) {
496 r
= cg_rmdir(cfrom
, pfrom
);
497 if (r
< 0 && ret
>= 0 && !IN_SET(r
, -ENOENT
, -EBUSY
))
504 int cg_migrate_recursive_fallback(
518 r
= cg_migrate_recursive(cfrom
, pfrom
, cto
, pto
, flags
);
520 char prefix
[strlen(pto
) + 1];
522 /* This didn't work? Then let's try all prefixes of the destination */
524 PATH_FOREACH_PREFIX(prefix
, pto
) {
527 q
= cg_migrate_recursive(cfrom
, pfrom
, cto
, prefix
, flags
);
536 static const char *controller_to_dirname(const char *controller
) {
541 /* Converts a controller name to the directory name below
542 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
543 * just cuts off the name= prefixed used for named
544 * hierarchies, if it is specified. */
546 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
547 if (cg_hybrid_unified() > 0)
548 controller
= SYSTEMD_CGROUP_CONTROLLER_HYBRID
;
550 controller
= SYSTEMD_CGROUP_CONTROLLER_LEGACY
;
553 e
= startswith(controller
, "name=");
560 static int join_path_legacy(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
567 dn
= controller_to_dirname(controller
);
569 if (isempty(path
) && isempty(suffix
))
570 t
= strappend("/sys/fs/cgroup/", dn
);
571 else if (isempty(path
))
572 t
= strjoin("/sys/fs/cgroup/", dn
, "/", suffix
);
573 else if (isempty(suffix
))
574 t
= strjoin("/sys/fs/cgroup/", dn
, "/", path
);
576 t
= strjoin("/sys/fs/cgroup/", dn
, "/", path
, "/", suffix
);
584 static int join_path_unified(const char *path
, const char *suffix
, char **fs
) {
589 if (isempty(path
) && isempty(suffix
))
590 t
= strdup("/sys/fs/cgroup");
591 else if (isempty(path
))
592 t
= strappend("/sys/fs/cgroup/", suffix
);
593 else if (isempty(suffix
))
594 t
= strappend("/sys/fs/cgroup/", path
);
596 t
= strjoin("/sys/fs/cgroup/", path
, "/", suffix
);
604 int cg_get_path(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
612 /* If no controller is specified, we return the path
613 * *below* the controllers, without any prefix. */
615 if (!path
&& !suffix
)
623 t
= strjoin(path
, "/", suffix
);
627 *fs
= path_simplify(t
, false);
631 if (!cg_controller_is_valid(controller
))
634 r
= cg_all_unified();
638 r
= join_path_unified(path
, suffix
, fs
);
640 r
= join_path_legacy(controller
, path
, suffix
, fs
);
644 path_simplify(*fs
, false);
648 static int controller_is_accessible(const char *controller
) {
653 /* Checks whether a specific controller is accessible,
654 * i.e. its hierarchy mounted. In the unified hierarchy all
655 * controllers are considered accessible, except for the named
658 if (!cg_controller_is_valid(controller
))
661 r
= cg_all_unified();
665 /* We don't support named hierarchies if we are using
666 * the unified hierarchy. */
668 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
))
671 if (startswith(controller
, "name="))
677 dn
= controller_to_dirname(controller
);
678 cc
= strjoina("/sys/fs/cgroup/", dn
);
680 if (laccess(cc
, F_OK
) < 0)
687 int cg_get_path_and_check(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
693 /* Check if the specified controller is actually accessible */
694 r
= controller_is_accessible(controller
);
698 return cg_get_path(controller
, path
, suffix
, fs
);
701 static int trim_cb(const char *path
, const struct stat
*sb
, int typeflag
, struct FTW
*ftwbuf
) {
706 if (typeflag
!= FTW_DP
)
709 if (ftwbuf
->level
< 1)
716 int cg_trim(const char *controller
, const char *path
, bool delete_root
) {
717 _cleanup_free_
char *fs
= NULL
;
722 r
= cg_get_path(controller
, path
, NULL
, &fs
);
727 if (nftw(fs
, trim_cb
, 64, FTW_DEPTH
|FTW_MOUNT
|FTW_PHYS
) != 0) {
737 if (rmdir(fs
) < 0 && errno
!= ENOENT
)
741 q
= cg_hybrid_unified();
744 if (q
> 0 && streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
745 q
= cg_trim(SYSTEMD_CGROUP_CONTROLLER_LEGACY
, path
, delete_root
);
747 log_warning_errno(q
, "Failed to trim compat systemd cgroup %s: %m", path
);
753 /* Create a cgroup in the hierarchy of controller.
754 * Returns 0 if the group already existed, 1 on success, negative otherwise.
756 int cg_create(const char *controller
, const char *path
) {
757 _cleanup_free_
char *fs
= NULL
;
760 r
= cg_get_path_and_check(controller
, path
, NULL
, &fs
);
764 r
= mkdir_parents(fs
, 0755);
768 r
= mkdir_errno_wrapper(fs
, 0755);
774 r
= cg_hybrid_unified();
778 if (r
> 0 && streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
779 r
= cg_create(SYSTEMD_CGROUP_CONTROLLER_LEGACY
, path
);
781 log_warning_errno(r
, "Failed to create compat systemd cgroup %s: %m", path
);
787 int cg_create_and_attach(const char *controller
, const char *path
, pid_t pid
) {
792 r
= cg_create(controller
, path
);
796 q
= cg_attach(controller
, path
, pid
);
800 /* This does not remove the cgroup on failure */
804 int cg_attach(const char *controller
, const char *path
, pid_t pid
) {
805 _cleanup_free_
char *fs
= NULL
;
806 char c
[DECIMAL_STR_MAX(pid_t
) + 2];
812 r
= cg_get_path_and_check(controller
, path
, "cgroup.procs", &fs
);
817 pid
= getpid_cached();
819 xsprintf(c
, PID_FMT
"\n", pid
);
821 r
= write_string_file(fs
, c
, WRITE_STRING_FILE_DISABLE_BUFFER
);
825 r
= cg_hybrid_unified();
829 if (r
> 0 && streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
830 r
= cg_attach(SYSTEMD_CGROUP_CONTROLLER_LEGACY
, path
, pid
);
832 log_warning_errno(r
, "Failed to attach "PID_FMT
" to compat systemd cgroup %s: %m", pid
, path
);
838 int cg_attach_fallback(const char *controller
, const char *path
, pid_t pid
) {
845 r
= cg_attach(controller
, path
, pid
);
847 char prefix
[strlen(path
) + 1];
849 /* This didn't work? Then let's try all prefixes of
852 PATH_FOREACH_PREFIX(prefix
, path
) {
855 q
= cg_attach(controller
, prefix
, pid
);
865 const char *controller
,
875 /* cgroupsv1, aka legacy/non-unified */
876 static const struct Attribute legacy_attributes
[] = {
877 { "cgroup.procs", true },
879 { "cgroup.clone_children", false },
883 /* cgroupsv2, aka unified */
884 static const struct Attribute unified_attributes
[] = {
885 { "cgroup.procs", true },
886 { "cgroup.subtree_control", true },
887 { "cgroup.threads", false },
891 static const struct Attribute
* const attributes
[] = {
892 [false] = legacy_attributes
,
893 [true] = unified_attributes
,
896 _cleanup_free_
char *fs
= NULL
;
897 const struct Attribute
*i
;
902 if (uid
== UID_INVALID
&& gid
== GID_INVALID
)
905 unified
= cg_unified_controller(controller
);
909 /* Configure access to the cgroup itself */
910 r
= cg_get_path(controller
, path
, NULL
, &fs
);
914 r
= chmod_and_chown(fs
, 0755, uid
, gid
);
918 /* Configure access to the cgroup's attributes */
919 for (i
= attributes
[unified
]; i
->name
; i
++) {
922 r
= cg_get_path(controller
, path
, i
->name
, &fs
);
926 r
= chmod_and_chown(fs
, 0644, uid
, gid
);
931 log_debug_errno(r
, "Failed to set access on cgroup %s, ignoring: %m", fs
);
935 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
936 r
= cg_hybrid_unified();
940 /* Always propagate access mode from unified to legacy controller */
941 r
= cg_set_access(SYSTEMD_CGROUP_CONTROLLER_LEGACY
, path
, uid
, gid
);
943 log_debug_errno(r
, "Failed to set access on compatibility systemd cgroup %s, ignoring: %m", path
);
950 int cg_set_xattr(const char *controller
, const char *path
, const char *name
, const void *value
, size_t size
, int flags
) {
951 _cleanup_free_
char *fs
= NULL
;
956 assert(value
|| size
<= 0);
958 r
= cg_get_path(controller
, path
, NULL
, &fs
);
962 if (setxattr(fs
, name
, value
, size
, flags
) < 0)
968 int cg_get_xattr(const char *controller
, const char *path
, const char *name
, void *value
, size_t size
) {
969 _cleanup_free_
char *fs
= NULL
;
976 r
= cg_get_path(controller
, path
, NULL
, &fs
);
980 n
= getxattr(fs
, name
, value
, size
);
987 int cg_pid_get_path(const char *controller
, pid_t pid
, char **path
) {
988 _cleanup_fclose_
FILE *f
= NULL
;
989 const char *fs
, *controller_str
;
997 if (!cg_controller_is_valid(controller
))
1000 controller
= SYSTEMD_CGROUP_CONTROLLER
;
1002 unified
= cg_unified_controller(controller
);
1006 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
))
1007 controller_str
= SYSTEMD_CGROUP_CONTROLLER_LEGACY
;
1009 controller_str
= controller
;
1011 cs
= strlen(controller_str
);
1014 fs
= procfs_file_alloca(pid
, "cgroup");
1015 f
= fopen(fs
, "re");
1017 return errno
== ENOENT
? -ESRCH
: -errno
;
1019 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
1022 _cleanup_free_
char *line
= NULL
;
1025 r
= read_line(f
, LONG_LINE_MAX
, &line
);
1032 e
= startswith(line
, "0:");
1042 const char *word
, *state
;
1045 l
= strchr(line
, ':');
1055 FOREACH_WORD_SEPARATOR(word
, k
, l
, ",", state
)
1056 if (k
== cs
&& memcmp(word
, controller_str
, cs
) == 0) {
1068 /* Truncate suffix indicating the process is a zombie */
1069 e
= endswith(p
, " (deleted)");
1080 int cg_install_release_agent(const char *controller
, const char *agent
) {
1081 _cleanup_free_
char *fs
= NULL
, *contents
= NULL
;
1087 r
= cg_unified_controller(controller
);
1090 if (r
> 0) /* doesn't apply to unified hierarchy */
1093 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
1097 r
= read_one_line_file(fs
, &contents
);
1101 sc
= strstrip(contents
);
1103 r
= write_string_file(fs
, agent
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1106 } else if (!path_equal(sc
, agent
))
1110 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
1114 contents
= mfree(contents
);
1115 r
= read_one_line_file(fs
, &contents
);
1119 sc
= strstrip(contents
);
1120 if (streq(sc
, "0")) {
1121 r
= write_string_file(fs
, "1", WRITE_STRING_FILE_DISABLE_BUFFER
);
1128 if (!streq(sc
, "1"))
1134 int cg_uninstall_release_agent(const char *controller
) {
1135 _cleanup_free_
char *fs
= NULL
;
1138 r
= cg_unified_controller(controller
);
1141 if (r
> 0) /* Doesn't apply to unified hierarchy */
1144 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
1148 r
= write_string_file(fs
, "0", WRITE_STRING_FILE_DISABLE_BUFFER
);
1154 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
1158 r
= write_string_file(fs
, "", WRITE_STRING_FILE_DISABLE_BUFFER
);
1165 int cg_is_empty(const char *controller
, const char *path
) {
1166 _cleanup_fclose_
FILE *f
= NULL
;
1172 r
= cg_enumerate_processes(controller
, path
, &f
);
1178 r
= cg_read_pid(f
, &pid
);
1185 int cg_is_empty_recursive(const char *controller
, const char *path
) {
1190 /* The root cgroup is always populated */
1191 if (controller
&& empty_or_root(path
))
1194 r
= cg_unified_controller(controller
);
1198 _cleanup_free_
char *t
= NULL
;
1200 /* On the unified hierarchy we can check empty state
1201 * via the "populated" attribute of "cgroup.events". */
1203 r
= cg_read_event(controller
, path
, "populated", &t
);
1209 return streq(t
, "0");
1211 _cleanup_closedir_
DIR *d
= NULL
;
1214 r
= cg_is_empty(controller
, path
);
1218 r
= cg_enumerate_subgroups(controller
, path
, &d
);
1224 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
1225 _cleanup_free_
char *p
= NULL
;
1227 p
= strjoin(path
, "/", fn
);
1232 r
= cg_is_empty_recursive(controller
, p
);
1243 int cg_split_spec(const char *spec
, char **controller
, char **path
) {
1244 char *t
= NULL
, *u
= NULL
;
1250 if (!path_is_normalized(spec
))
1258 *path
= path_simplify(t
, false);
1267 e
= strchr(spec
, ':');
1269 if (!cg_controller_is_valid(spec
))
1286 t
= strndup(spec
, e
-spec
);
1289 if (!cg_controller_is_valid(t
)) {
1303 if (!path_is_normalized(u
) ||
1304 !path_is_absolute(u
)) {
1310 path_simplify(u
, false);
1326 int cg_mangle_path(const char *path
, char **result
) {
1327 _cleanup_free_
char *c
= NULL
, *p
= NULL
;
1334 /* First, check if it already is a filesystem path */
1335 if (path_startswith(path
, "/sys/fs/cgroup")) {
1341 *result
= path_simplify(t
, false);
1345 /* Otherwise, treat it as cg spec */
1346 r
= cg_split_spec(path
, &c
, &p
);
1350 return cg_get_path(c
?: SYSTEMD_CGROUP_CONTROLLER
, p
?: "/", NULL
, result
);
1353 int cg_get_root_path(char **path
) {
1359 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 1, &p
);
1363 e
= endswith(p
, "/" SPECIAL_INIT_SCOPE
);
1365 e
= endswith(p
, "/" SPECIAL_SYSTEM_SLICE
); /* legacy */
1367 e
= endswith(p
, "/system"); /* even more legacy */
1375 int cg_shift_path(const char *cgroup
, const char *root
, const char **shifted
) {
1376 _cleanup_free_
char *rt
= NULL
;
1384 /* If the root was specified let's use that, otherwise
1385 * let's determine it from PID 1 */
1387 r
= cg_get_root_path(&rt
);
1394 p
= path_startswith(cgroup
, root
);
1395 if (p
&& p
> cgroup
)
1403 int cg_pid_get_path_shifted(pid_t pid
, const char *root
, char **cgroup
) {
1404 _cleanup_free_
char *raw
= NULL
;
1411 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &raw
);
1415 r
= cg_shift_path(raw
, root
, &c
);
1420 *cgroup
= TAKE_PTR(raw
);
1434 int cg_path_decode_unit(const char *cgroup
, char **unit
) {
1441 n
= strcspn(cgroup
, "/");
1445 c
= strndupa(cgroup
, n
);
1448 if (!unit_name_is_valid(c
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
1459 static bool valid_slice_name(const char *p
, size_t n
) {
1464 if (n
< STRLEN("x.slice"))
1467 if (memcmp(p
+ n
- 6, ".slice", 6) == 0) {
1473 c
= cg_unescape(buf
);
1475 return unit_name_is_valid(c
, UNIT_NAME_PLAIN
);
1481 static const char *skip_slices(const char *p
) {
1484 /* Skips over all slice assignments */
1489 p
+= strspn(p
, "/");
1491 n
= strcspn(p
, "/");
1492 if (!valid_slice_name(p
, n
))
1499 int cg_path_get_unit(const char *path
, char **ret
) {
1507 e
= skip_slices(path
);
1509 r
= cg_path_decode_unit(e
, &unit
);
1513 /* We skipped over the slices, don't accept any now */
1514 if (endswith(unit
, ".slice")) {
1523 int cg_pid_get_unit(pid_t pid
, char **unit
) {
1524 _cleanup_free_
char *cgroup
= NULL
;
1529 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1533 return cg_path_get_unit(cgroup
, unit
);
1537 * Skip session-*.scope, but require it to be there.
1539 static const char *skip_session(const char *p
) {
1545 p
+= strspn(p
, "/");
1547 n
= strcspn(p
, "/");
1548 if (n
< STRLEN("session-x.scope"))
1551 if (memcmp(p
, "session-", 8) == 0 && memcmp(p
+ n
- 6, ".scope", 6) == 0) {
1552 char buf
[n
- 8 - 6 + 1];
1554 memcpy(buf
, p
+ 8, n
- 8 - 6);
1557 /* Note that session scopes never need unescaping,
1558 * since they cannot conflict with the kernel's own
1559 * names, hence we don't need to call cg_unescape()
1562 if (!session_id_valid(buf
))
1566 p
+= strspn(p
, "/");
1574 * Skip user@*.service, but require it to be there.
1576 static const char *skip_user_manager(const char *p
) {
1582 p
+= strspn(p
, "/");
1584 n
= strcspn(p
, "/");
1585 if (n
< STRLEN("user@x.service"))
1588 if (memcmp(p
, "user@", 5) == 0 && memcmp(p
+ n
- 8, ".service", 8) == 0) {
1589 char buf
[n
- 5 - 8 + 1];
1591 memcpy(buf
, p
+ 5, n
- 5 - 8);
1594 /* Note that user manager services never need unescaping,
1595 * since they cannot conflict with the kernel's own
1596 * names, hence we don't need to call cg_unescape()
1599 if (parse_uid(buf
, NULL
) < 0)
1603 p
+= strspn(p
, "/");
1611 static const char *skip_user_prefix(const char *path
) {
1616 /* Skip slices, if there are any */
1617 e
= skip_slices(path
);
1619 /* Skip the user manager, if it's in the path now... */
1620 t
= skip_user_manager(e
);
1624 /* Alternatively skip the user session if it is in the path... */
1625 return skip_session(e
);
1628 int cg_path_get_user_unit(const char *path
, char **ret
) {
1634 t
= skip_user_prefix(path
);
1638 /* And from here on it looks pretty much the same as for a
1639 * system unit, hence let's use the same parser from here
1641 return cg_path_get_unit(t
, ret
);
1644 int cg_pid_get_user_unit(pid_t pid
, char **unit
) {
1645 _cleanup_free_
char *cgroup
= NULL
;
1650 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1654 return cg_path_get_user_unit(cgroup
, unit
);
1657 int cg_path_get_machine_name(const char *path
, char **machine
) {
1658 _cleanup_free_
char *u
= NULL
;
1662 r
= cg_path_get_unit(path
, &u
);
1666 sl
= strjoina("/run/systemd/machines/unit:", u
);
1667 return readlink_malloc(sl
, machine
);
1670 int cg_pid_get_machine_name(pid_t pid
, char **machine
) {
1671 _cleanup_free_
char *cgroup
= NULL
;
1676 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1680 return cg_path_get_machine_name(cgroup
, machine
);
1683 int cg_path_get_session(const char *path
, char **session
) {
1684 _cleanup_free_
char *unit
= NULL
;
1690 r
= cg_path_get_unit(path
, &unit
);
1694 start
= startswith(unit
, "session-");
1697 end
= endswith(start
, ".scope");
1702 if (!session_id_valid(start
))
1718 int cg_pid_get_session(pid_t pid
, char **session
) {
1719 _cleanup_free_
char *cgroup
= NULL
;
1722 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1726 return cg_path_get_session(cgroup
, session
);
1729 int cg_path_get_owner_uid(const char *path
, uid_t
*uid
) {
1730 _cleanup_free_
char *slice
= NULL
;
1736 r
= cg_path_get_slice(path
, &slice
);
1740 start
= startswith(slice
, "user-");
1743 end
= endswith(start
, ".slice");
1748 if (parse_uid(start
, uid
) < 0)
1754 int cg_pid_get_owner_uid(pid_t pid
, uid_t
*uid
) {
1755 _cleanup_free_
char *cgroup
= NULL
;
1758 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1762 return cg_path_get_owner_uid(cgroup
, uid
);
1765 int cg_path_get_slice(const char *p
, char **slice
) {
1766 const char *e
= NULL
;
1771 /* Finds the right-most slice unit from the beginning, but
1772 * stops before we come to the first non-slice unit. */
1777 p
+= strspn(p
, "/");
1779 n
= strcspn(p
, "/");
1780 if (!valid_slice_name(p
, n
)) {
1785 s
= strdup(SPECIAL_ROOT_SLICE
);
1793 return cg_path_decode_unit(e
, slice
);
1801 int cg_pid_get_slice(pid_t pid
, char **slice
) {
1802 _cleanup_free_
char *cgroup
= NULL
;
1807 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1811 return cg_path_get_slice(cgroup
, slice
);
1814 int cg_path_get_user_slice(const char *p
, char **slice
) {
1819 t
= skip_user_prefix(p
);
1823 /* And now it looks pretty much the same as for a system
1824 * slice, so let's just use the same parser from here on. */
1825 return cg_path_get_slice(t
, slice
);
1828 int cg_pid_get_user_slice(pid_t pid
, char **slice
) {
1829 _cleanup_free_
char *cgroup
= NULL
;
1834 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1838 return cg_path_get_user_slice(cgroup
, slice
);
1841 char *cg_escape(const char *p
) {
1842 bool need_prefix
= false;
1844 /* This implements very minimal escaping for names to be used
1845 * as file names in the cgroup tree: any name which might
1846 * conflict with a kernel name or is prefixed with '_' is
1847 * prefixed with a '_'. That way, when reading cgroup names it
1848 * is sufficient to remove a single prefixing underscore if
1851 /* The return value of this function (unlike cg_unescape())
1854 if (IN_SET(p
[0], 0, '_', '.') ||
1855 STR_IN_SET(p
, "notify_on_release", "release_agent", "tasks") ||
1856 startswith(p
, "cgroup."))
1861 dot
= strrchr(p
, '.');
1866 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1869 n
= cgroup_controller_to_string(c
);
1874 if (memcmp(p
, n
, l
) != 0)
1884 return strappend("_", p
);
1889 char *cg_unescape(const char *p
) {
1892 /* The return value of this function (unlike cg_escape())
1893 * doesn't need free()! */
1901 #define CONTROLLER_VALID \
1905 bool cg_controller_is_valid(const char *p
) {
1911 if (streq(p
, SYSTEMD_CGROUP_CONTROLLER
))
1914 s
= startswith(p
, "name=");
1918 if (IN_SET(*p
, 0, '_'))
1921 for (t
= p
; *t
; t
++)
1922 if (!strchr(CONTROLLER_VALID
, *t
))
1925 if (t
- p
> FILENAME_MAX
)
1931 int cg_slice_to_path(const char *unit
, char **ret
) {
1932 _cleanup_free_
char *p
= NULL
, *s
= NULL
, *e
= NULL
;
1939 if (streq(unit
, SPECIAL_ROOT_SLICE
)) {
1949 if (!unit_name_is_valid(unit
, UNIT_NAME_PLAIN
))
1952 if (!endswith(unit
, ".slice"))
1955 r
= unit_name_to_prefix(unit
, &p
);
1959 dash
= strchr(p
, '-');
1961 /* Don't allow initial dashes */
1966 _cleanup_free_
char *escaped
= NULL
;
1967 char n
[dash
- p
+ sizeof(".slice")];
1969 #if HAS_FEATURE_MEMORY_SANITIZER
1970 /* msan doesn't instrument stpncpy, so it thinks
1971 * n is later used unitialized:
1972 * https://github.com/google/sanitizers/issues/926
1977 /* Don't allow trailing or double dashes */
1978 if (IN_SET(dash
[1], 0, '-'))
1981 strcpy(stpncpy(n
, p
, dash
- p
), ".slice");
1982 if (!unit_name_is_valid(n
, UNIT_NAME_PLAIN
))
1985 escaped
= cg_escape(n
);
1989 if (!strextend(&s
, escaped
, "/", NULL
))
1992 dash
= strchr(dash
+1, '-');
1995 e
= cg_escape(unit
);
1999 if (!strextend(&s
, e
, NULL
))
2007 int cg_set_attribute(const char *controller
, const char *path
, const char *attribute
, const char *value
) {
2008 _cleanup_free_
char *p
= NULL
;
2011 r
= cg_get_path(controller
, path
, attribute
, &p
);
2015 return write_string_file(p
, value
, WRITE_STRING_FILE_DISABLE_BUFFER
);
2018 int cg_get_attribute(const char *controller
, const char *path
, const char *attribute
, char **ret
) {
2019 _cleanup_free_
char *p
= NULL
;
2022 r
= cg_get_path(controller
, path
, attribute
, &p
);
2026 return read_one_line_file(p
, ret
);
2029 int cg_get_keyed_attribute(
2030 const char *controller
,
2032 const char *attribute
,
2034 char **ret_values
) {
2036 _cleanup_free_
char *filename
= NULL
, *contents
= NULL
;
2038 size_t n
, i
, n_done
= 0;
2042 /* Reads one or more fields of a cgroupsv2 keyed attribute file. The 'keys' parameter should be an strv with
2043 * all keys to retrieve. The 'ret_values' parameter should be passed as string size with the same number of
2044 * entries as 'keys'. On success each entry will be set to the value of the matching key.
2046 * If the attribute file doesn't exist at all returns ENOENT, if any key is not found returns ENXIO. */
2048 r
= cg_get_path(controller
, path
, attribute
, &filename
);
2052 r
= read_full_file(filename
, &contents
, NULL
);
2056 n
= strv_length(keys
);
2057 if (n
== 0) /* No keys to retrieve? That's easy, we are done then */
2060 /* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
2061 v
= newa0(char*, n
);
2063 for (p
= contents
; *p
;) {
2064 const char *w
= NULL
;
2066 for (i
= 0; i
< n
; i
++)
2068 w
= first_word(p
, keys
[i
]);
2076 l
= strcspn(w
, NEWLINE
);
2077 v
[i
] = strndup(w
, l
);
2089 p
+= strcspn(p
, NEWLINE
);
2091 p
+= strspn(p
, NEWLINE
);
2097 for (i
= 0; i
< n
; i
++)
2103 memcpy(ret_values
, v
, sizeof(char*) * n
);
2108 int cg_create_everywhere(CGroupMask supported
, CGroupMask mask
, const char *path
) {
2114 /* This one will create a cgroup in our private tree, but also
2115 * duplicate it in the trees specified in mask, and remove it
2118 * Returns 0 if the group already existed in the systemd hierarchy,
2119 * 1 on success, negative otherwise.
2122 /* First create the cgroup in our own hierarchy. */
2123 r
= cg_create(SYSTEMD_CGROUP_CONTROLLER
, path
);
2128 /* If we are in the unified hierarchy, we are done now */
2129 r
= cg_all_unified();
2135 supported
&= CGROUP_MASK_V1
;
2136 mask
= CGROUP_MASK_EXTEND_JOINED(mask
);
2139 /* Otherwise, do the same in the other hierarchies */
2140 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2141 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2144 if (!FLAGS_SET(supported
, bit
))
2147 if (FLAGS_SET(done
, bit
))
2150 n
= cgroup_controller_to_string(c
);
2151 if (FLAGS_SET(mask
, bit
))
2152 (void) cg_create(n
, path
);
2154 (void) cg_trim(n
, path
, true);
2156 done
|= CGROUP_MASK_EXTEND_JOINED(bit
);
2162 int cg_attach_everywhere(CGroupMask supported
, const char *path
, pid_t pid
, cg_migrate_callback_t path_callback
, void *userdata
) {
2167 r
= cg_attach(SYSTEMD_CGROUP_CONTROLLER
, path
, pid
);
2171 r
= cg_all_unified();
2177 supported
&= CGROUP_MASK_V1
;
2180 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2181 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2182 const char *p
= NULL
;
2184 if (!FLAGS_SET(supported
, bit
))
2187 if (FLAGS_SET(done
, bit
))
2191 p
= path_callback(bit
, userdata
);
2195 (void) cg_attach_fallback(cgroup_controller_to_string(c
), p
, pid
);
2196 done
|= CGROUP_MASK_EXTEND_JOINED(bit
);
2202 int cg_attach_many_everywhere(CGroupMask supported
, const char *path
, Set
* pids
, cg_migrate_callback_t path_callback
, void *userdata
) {
2207 SET_FOREACH(pidp
, pids
, i
) {
2208 pid_t pid
= PTR_TO_PID(pidp
);
2211 q
= cg_attach_everywhere(supported
, path
, pid
, path_callback
, userdata
);
2212 if (q
< 0 && r
>= 0)
2219 int cg_migrate_everywhere(CGroupMask supported
, const char *from
, const char *to
, cg_migrate_callback_t to_callback
, void *userdata
) {
2224 if (!path_equal(from
, to
)) {
2225 r
= cg_migrate_recursive(SYSTEMD_CGROUP_CONTROLLER
, from
, SYSTEMD_CGROUP_CONTROLLER
, to
, CGROUP_REMOVE
);
2230 q
= cg_all_unified();
2236 supported
&= CGROUP_MASK_V1
;
2239 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2240 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2241 const char *p
= NULL
;
2243 if (!FLAGS_SET(supported
, bit
))
2246 if (FLAGS_SET(done
, bit
))
2250 p
= to_callback(bit
, userdata
);
2254 (void) cg_migrate_recursive_fallback(SYSTEMD_CGROUP_CONTROLLER
, to
, cgroup_controller_to_string(c
), p
, 0);
2255 done
|= CGROUP_MASK_EXTEND_JOINED(bit
);
2261 int cg_trim_everywhere(CGroupMask supported
, const char *path
, bool delete_root
) {
2266 r
= cg_trim(SYSTEMD_CGROUP_CONTROLLER
, path
, delete_root
);
2270 q
= cg_all_unified();
2276 supported
&= CGROUP_MASK_V1
;
2279 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2280 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2282 if (!FLAGS_SET(supported
, bit
))
2285 if (FLAGS_SET(done
, bit
))
2288 (void) cg_trim(cgroup_controller_to_string(c
), path
, delete_root
);
2289 done
|= CGROUP_MASK_EXTEND_JOINED(bit
);
2295 int cg_mask_to_string(CGroupMask mask
, char **ret
) {
2296 _cleanup_free_
char *s
= NULL
;
2297 size_t n
= 0, allocated
= 0;
2308 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2312 if (!FLAGS_SET(mask
, CGROUP_CONTROLLER_TO_MASK(c
)))
2315 k
= cgroup_controller_to_string(c
);
2318 if (!GREEDY_REALLOC(s
, allocated
, n
+ space
+ l
+ 1))
2323 memcpy(s
+ n
+ space
, k
, l
);
2337 int cg_mask_from_string(const char *value
, CGroupMask
*ret
) {
2344 _cleanup_free_
char *n
= NULL
;
2348 r
= extract_first_word(&value
, &n
, NULL
, 0);
2354 v
= cgroup_controller_from_string(n
);
2358 m
|= CGROUP_CONTROLLER_TO_MASK(v
);
2365 int cg_mask_supported(CGroupMask
*ret
) {
2369 /* Determines the mask of supported cgroup controllers. Only includes controllers we can make sense of and that
2370 * are actually accessible. Only covers real controllers, i.e. not the CGROUP_CONTROLLER_BPF_xyz
2371 * pseudo-controllers. */
2373 r
= cg_all_unified();
2377 _cleanup_free_
char *root
= NULL
, *controllers
= NULL
, *path
= NULL
;
2379 /* In the unified hierarchy we can read the supported
2380 * and accessible controllers from a the top-level
2381 * cgroup attribute */
2383 r
= cg_get_root_path(&root
);
2387 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, root
, "cgroup.controllers", &path
);
2391 r
= read_one_line_file(path
, &controllers
);
2395 r
= cg_mask_from_string(controllers
, &mask
);
2399 /* Currently, we support the cpu, memory, io and pids controller in the unified hierarchy, mask
2400 * everything else off. */
2401 mask
&= CGROUP_MASK_V2
;
2406 /* In the legacy hierarchy, we check which hierarchies are mounted. */
2409 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2410 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2413 if (!FLAGS_SET(CGROUP_MASK_V1
, bit
))
2416 n
= cgroup_controller_to_string(c
);
2417 if (controller_is_accessible(n
) >= 0)
2426 int cg_kernel_controllers(Set
**ret
) {
2427 _cleanup_set_free_free_ Set
*controllers
= NULL
;
2428 _cleanup_fclose_
FILE *f
= NULL
;
2433 /* Determines the full list of kernel-known controllers. Might include controllers we don't actually support
2434 * and controllers that aren't currently accessible (because not mounted). This does not include "name="
2435 * pseudo-controllers. */
2437 controllers
= set_new(&string_hash_ops
);
2441 f
= fopen("/proc/cgroups", "re");
2443 if (errno
== ENOENT
) {
2451 (void) __fsetlocking(f
, FSETLOCKING_BYCALLER
);
2453 /* Ignore the header line */
2454 (void) read_line(f
, (size_t) -1, NULL
);
2461 if (fscanf(f
, "%ms %*i %*i %i", &controller
, &enabled
) != 2) {
2466 if (ferror(f
) && errno
> 0)
2477 if (!cg_controller_is_valid(controller
)) {
2482 r
= set_consume(controllers
, controller
);
2487 *ret
= TAKE_PTR(controllers
);
2492 static thread_local CGroupUnified unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
2494 /* The hybrid mode was initially implemented in v232 and simply mounted cgroup v2 on /sys/fs/cgroup/systemd. This
2495 * unfortunately broke other tools (such as docker) which expected the v1 "name=systemd" hierarchy on
2496 * /sys/fs/cgroup/systemd. From v233 and on, the hybrid mode mountnbs v2 on /sys/fs/cgroup/unified and maintains
2497 * "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility with other tools.
2499 * To keep live upgrade working, we detect and support v232 layout. When v232 layout is detected, to keep cgroup v2
2500 * process management but disable the compat dual layout, we return %true on
2501 * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and %false on cg_hybrid_unified().
2503 static thread_local
bool unified_systemd_v232
;
2505 static int cg_unified_update(void) {
2509 /* Checks if we support the unified hierarchy. Returns an
2510 * error when the cgroup hierarchies aren't mounted yet or we
2511 * have any other trouble determining if the unified hierarchy
2514 if (unified_cache
>= CGROUP_UNIFIED_NONE
)
2517 if (statfs("/sys/fs/cgroup/", &fs
) < 0)
2518 return log_debug_errno(errno
, "statfs(\"/sys/fs/cgroup/\") failed: %m");
2520 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
2521 log_debug("Found cgroup2 on /sys/fs/cgroup/, full unified hierarchy");
2522 unified_cache
= CGROUP_UNIFIED_ALL
;
2523 } else if (F_TYPE_EQUAL(fs
.f_type
, TMPFS_MAGIC
)) {
2524 if (statfs("/sys/fs/cgroup/unified/", &fs
) == 0 &&
2525 F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
2526 log_debug("Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller");
2527 unified_cache
= CGROUP_UNIFIED_SYSTEMD
;
2528 unified_systemd_v232
= false;
2530 if (statfs("/sys/fs/cgroup/systemd/", &fs
) < 0)
2531 return log_debug_errno(errno
, "statfs(\"/sys/fs/cgroup/systemd\" failed: %m");
2533 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
2534 log_debug("Found cgroup2 on /sys/fs/cgroup/systemd, unified hierarchy for systemd controller (v232 variant)");
2535 unified_cache
= CGROUP_UNIFIED_SYSTEMD
;
2536 unified_systemd_v232
= true;
2537 } else if (F_TYPE_EQUAL(fs
.f_type
, CGROUP_SUPER_MAGIC
)) {
2538 log_debug("Found cgroup on /sys/fs/cgroup/systemd, legacy hierarchy");
2539 unified_cache
= CGROUP_UNIFIED_NONE
;
2541 log_debug("Unexpected filesystem type %llx mounted on /sys/fs/cgroup/systemd, assuming legacy hierarchy",
2542 (unsigned long long) fs
.f_type
);
2543 unified_cache
= CGROUP_UNIFIED_NONE
;
2547 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
2548 "Unknown filesystem type %llx mounted on /sys/fs/cgroup.",
2549 (unsigned long long)fs
.f_type
);
2554 int cg_unified_controller(const char *controller
) {
2557 r
= cg_unified_update();
2561 if (unified_cache
== CGROUP_UNIFIED_NONE
)
2564 if (unified_cache
>= CGROUP_UNIFIED_ALL
)
2567 return streq_ptr(controller
, SYSTEMD_CGROUP_CONTROLLER
);
2570 int cg_all_unified(void) {
2573 r
= cg_unified_update();
2577 return unified_cache
>= CGROUP_UNIFIED_ALL
;
2580 int cg_hybrid_unified(void) {
2583 r
= cg_unified_update();
2587 return unified_cache
== CGROUP_UNIFIED_SYSTEMD
&& !unified_systemd_v232
;
2590 int cg_unified_flush(void) {
2591 unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
2593 return cg_unified_update();
2596 int cg_enable_everywhere(
2597 CGroupMask supported
,
2600 CGroupMask
*ret_result_mask
) {
2602 _cleanup_fclose_
FILE *f
= NULL
;
2603 _cleanup_free_
char *fs
= NULL
;
2610 if (supported
== 0) {
2611 if (ret_result_mask
)
2612 *ret_result_mask
= 0;
2616 r
= cg_all_unified();
2620 /* On the legacy hiearchy there's no concept of "enabling" controllers in cgroups defined. Let's claim
2621 * complete success right away. (If you wonder why we return the full mask here, rather than zero: the
2622 * caller tends to use the returned mask later on to compare if all controllers where properly joined,
2623 * and if not requeues realization. This use is the primary purpose of the return value, hence let's
2624 * minimize surprises here and reduce triggers for re-realization by always saying we fully
2626 if (ret_result_mask
)
2627 *ret_result_mask
= mask
& supported
& CGROUP_MASK_V2
; /* If you wonder why we mask this with
2628 * CGROUP_MASK_V2: The 'supported' mask
2629 * might contain pure-V1 or BPF
2630 * controllers, and we never want to
2631 * claim that we could enable those with
2632 * cgroup.subtree_control */
2636 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, p
, "cgroup.subtree_control", &fs
);
2640 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2641 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2644 if (!FLAGS_SET(CGROUP_MASK_V2
, bit
))
2647 if (!FLAGS_SET(supported
, bit
))
2650 n
= cgroup_controller_to_string(c
);
2652 char s
[1 + strlen(n
) + 1];
2654 s
[0] = FLAGS_SET(mask
, bit
) ? '+' : '-';
2658 f
= fopen(fs
, "we");
2660 return log_debug_errno(errno
, "Failed to open cgroup.subtree_control file of %s: %m", p
);
2663 r
= write_string_stream(f
, s
, WRITE_STRING_FILE_DISABLE_BUFFER
);
2665 log_debug_errno(r
, "Failed to %s controller %s for %s (%s): %m",
2666 FLAGS_SET(mask
, bit
) ? "enable" : "disable", n
, p
, fs
);
2669 /* If we can't turn off a controller, leave it on in the reported resulting mask. This
2670 * happens for example when we attempt to turn off a controller up in the tree that is
2671 * used down in the tree. */
2672 if (!FLAGS_SET(mask
, bit
) && r
== -EBUSY
) /* You might wonder why we check for EBUSY
2673 * only here, and not follow the same logic
2674 * for other errors such as EINVAL or
2675 * EOPNOTSUPP or anything else. That's
2676 * because EBUSY indicates that the
2677 * controllers is currently enabled and
2678 * cannot be disabled because something down
2679 * the hierarchy is still using it. Any other
2680 * error most likely means something like "I
2681 * never heard of this controller" or
2682 * similar. In the former case it's hence
2683 * safe to assume the controller is still on
2684 * after the failed operation, while in the
2685 * latter case it's safer to assume the
2686 * controller is unknown and hence certainly
2690 /* Otherwise, if we managed to turn on a controller, set the bit reflecting that. */
2691 if (FLAGS_SET(mask
, bit
))
2697 /* Let's return the precise set of controllers now enabled for the cgroup. */
2698 if (ret_result_mask
)
2699 *ret_result_mask
= ret
;
2704 bool cg_is_unified_wanted(void) {
2705 static thread_local
int wanted
= -1;
2708 const bool is_default
= DEFAULT_HIERARCHY
== CGROUP_UNIFIED_ALL
;
2709 _cleanup_free_
char *c
= NULL
;
2711 /* If we have a cached value, return that. */
2715 /* If the hierarchy is already mounted, then follow whatever
2716 * was chosen for it. */
2717 if (cg_unified_flush() >= 0)
2718 return (wanted
= unified_cache
>= CGROUP_UNIFIED_ALL
);
2720 /* If we were explicitly passed systemd.unified_cgroup_hierarchy,
2722 r
= proc_cmdline_get_bool("systemd.unified_cgroup_hierarchy", &b
);
2724 return (wanted
= b
);
2726 /* If we passed cgroup_no_v1=all with no other instructions, it seems
2727 * highly unlikely that we want to use hybrid or legacy hierarchy. */
2728 r
= proc_cmdline_get_key("cgroup_no_v1", 0, &c
);
2729 if (r
> 0 && streq_ptr(c
, "all"))
2730 return (wanted
= true);
2732 return (wanted
= is_default
);
2735 bool cg_is_legacy_wanted(void) {
2736 static thread_local
int wanted
= -1;
2738 /* If we have a cached value, return that. */
2742 /* Check if we have cgroups2 already mounted. */
2743 if (cg_unified_flush() >= 0 &&
2744 unified_cache
== CGROUP_UNIFIED_ALL
)
2745 return (wanted
= false);
2747 /* Otherwise, assume that at least partial legacy is wanted,
2748 * since cgroups2 should already be mounted at this point. */
2749 return (wanted
= true);
2752 bool cg_is_hybrid_wanted(void) {
2753 static thread_local
int wanted
= -1;
2756 const bool is_default
= DEFAULT_HIERARCHY
>= CGROUP_UNIFIED_SYSTEMD
;
2757 /* We default to true if the default is "hybrid", obviously,
2758 * but also when the default is "unified", because if we get
2759 * called, it means that unified hierarchy was not mounted. */
2761 /* If we have a cached value, return that. */
2765 /* If the hierarchy is already mounted, then follow whatever
2766 * was chosen for it. */
2767 if (cg_unified_flush() >= 0 &&
2768 unified_cache
== CGROUP_UNIFIED_ALL
)
2769 return (wanted
= false);
2771 /* Otherwise, let's see what the kernel command line has to say.
2772 * Since checking is expensive, cache a non-error result. */
2773 r
= proc_cmdline_get_bool("systemd.legacy_systemd_cgroup_controller", &b
);
2775 /* The meaning of the kernel option is reversed wrt. to the return value
2776 * of this function, hence the negation. */
2777 return (wanted
= r
> 0 ? !b
: is_default
);
2780 int cg_weight_parse(const char *s
, uint64_t *ret
) {
2785 *ret
= CGROUP_WEIGHT_INVALID
;
2789 r
= safe_atou64(s
, &u
);
2793 if (u
< CGROUP_WEIGHT_MIN
|| u
> CGROUP_WEIGHT_MAX
)
2800 const uint64_t cgroup_io_limit_defaults
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2801 [CGROUP_IO_RBPS_MAX
] = CGROUP_LIMIT_MAX
,
2802 [CGROUP_IO_WBPS_MAX
] = CGROUP_LIMIT_MAX
,
2803 [CGROUP_IO_RIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2804 [CGROUP_IO_WIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2807 static const char* const cgroup_io_limit_type_table
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2808 [CGROUP_IO_RBPS_MAX
] = "IOReadBandwidthMax",
2809 [CGROUP_IO_WBPS_MAX
] = "IOWriteBandwidthMax",
2810 [CGROUP_IO_RIOPS_MAX
] = "IOReadIOPSMax",
2811 [CGROUP_IO_WIOPS_MAX
] = "IOWriteIOPSMax",
2814 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type
, CGroupIOLimitType
);
2816 int cg_cpu_shares_parse(const char *s
, uint64_t *ret
) {
2821 *ret
= CGROUP_CPU_SHARES_INVALID
;
2825 r
= safe_atou64(s
, &u
);
2829 if (u
< CGROUP_CPU_SHARES_MIN
|| u
> CGROUP_CPU_SHARES_MAX
)
2836 int cg_blkio_weight_parse(const char *s
, uint64_t *ret
) {
2841 *ret
= CGROUP_BLKIO_WEIGHT_INVALID
;
2845 r
= safe_atou64(s
, &u
);
2849 if (u
< CGROUP_BLKIO_WEIGHT_MIN
|| u
> CGROUP_BLKIO_WEIGHT_MAX
)
2856 bool is_cgroup_fs(const struct statfs
*s
) {
2857 return is_fs_type(s
, CGROUP_SUPER_MAGIC
) ||
2858 is_fs_type(s
, CGROUP2_SUPER_MAGIC
);
2861 bool fd_is_cgroup_fs(int fd
) {
2864 if (fstatfs(fd
, &s
) < 0)
2867 return is_cgroup_fs(&s
);
2870 static const char *cgroup_controller_table
[_CGROUP_CONTROLLER_MAX
] = {
2871 [CGROUP_CONTROLLER_CPU
] = "cpu",
2872 [CGROUP_CONTROLLER_CPUACCT
] = "cpuacct",
2873 [CGROUP_CONTROLLER_IO
] = "io",
2874 [CGROUP_CONTROLLER_BLKIO
] = "blkio",
2875 [CGROUP_CONTROLLER_MEMORY
] = "memory",
2876 [CGROUP_CONTROLLER_DEVICES
] = "devices",
2877 [CGROUP_CONTROLLER_PIDS
] = "pids",
2878 [CGROUP_CONTROLLER_BPF_FIREWALL
] = "bpf-firewall",
2879 [CGROUP_CONTROLLER_BPF_DEVICES
] = "bpf-devices",
2882 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller
, CGroupController
);
2884 CGroupMask
get_cpu_accounting_mask(void) {
2885 static CGroupMask needed_mask
= (CGroupMask
) -1;
2887 /* On kernel ≥4.15 with unified hierarchy, cpu.stat's usage_usec is
2888 * provided externally from the CPU controller, which means we don't
2889 * need to enable the CPU controller just to get metrics. This is good,
2890 * because enabling the CPU controller comes at a minor performance
2891 * hit, especially when it's propagated deep into large hierarchies.
2892 * There's also no separate CPU accounting controller available within
2893 * a unified hierarchy.
2895 * This combination of factors results in the desired cgroup mask to
2896 * enable for CPU accounting varying as follows:
2898 * ╔═════════════════════╤═════════════════════╗
2899 * ║ Linux ≥4.15 │ Linux <4.15 ║
2900 * ╔═══════════════╬═════════════════════╪═════════════════════╣
2901 * ║ Unified ║ nothing │ CGROUP_MASK_CPU ║
2902 * ╟───────────────╫─────────────────────┼─────────────────────╢
2903 * ║ Hybrid/Legacy ║ CGROUP_MASK_CPUACCT │ CGROUP_MASK_CPUACCT ║
2904 * ╚═══════════════╩═════════════════════╧═════════════════════╝
2906 * We check kernel version here instead of manually checking whether
2907 * cpu.stat is present for every cgroup, as that check in itself would
2908 * already be fairly expensive.
2910 * Kernels where this patch has been backported will therefore have the
2911 * CPU controller enabled unnecessarily. This is more expensive than
2912 * necessary, but harmless. ☺️
2915 if (needed_mask
== (CGroupMask
) -1) {
2916 if (cg_all_unified()) {
2918 assert_se(uname(&u
) >= 0);
2920 if (str_verscmp(u
.release
, "4.15") < 0)
2921 needed_mask
= CGROUP_MASK_CPU
;
2925 needed_mask
= CGROUP_MASK_CPUACCT
;
2931 bool cpu_accounting_is_cheap(void) {
2932 return get_cpu_accounting_mask() == 0;