1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include <sys/utsname.h>
10 #include <sys/xattr.h>
13 #include "alloc-util.h"
14 #include "cgroup-util.h"
15 #include "constants.h"
16 #include "dirent-util.h"
17 #include "extract-word.h"
20 #include "format-util.h"
23 #include "login-util.h"
25 #include "missing_magic.h"
26 #include "missing_threads.h"
28 #include "parse-util.h"
29 #include "path-util.h"
30 #include "process-util.h"
33 #include "stat-util.h"
34 #include "stdio-util.h"
35 #include "string-table.h"
36 #include "string-util.h"
38 #include "unit-name.h"
39 #include "user-util.h"
40 #include "xattr-util.h"
42 static int cg_enumerate_items(const char *controller
, const char *path
, FILE **ret
, const char *item
) {
43 _cleanup_free_
char *fs
= NULL
;
49 r
= cg_get_path(controller
, path
, item
, &fs
);
61 int cg_enumerate_processes(const char *controller
, const char *path
, FILE **ret
) {
62 return cg_enumerate_items(controller
, path
, ret
, "cgroup.procs");
65 int cg_read_pid(FILE *f
, pid_t
*ret
) {
68 /* Note that the cgroup.procs might contain duplicates! See cgroups.txt for details. */
74 if (fscanf(f
, "%lu", &ul
) != 1) {
81 return errno_or_else(EIO
);
93 int cg_read_pidref(FILE *f
, PidRef
*ret
) {
102 r
= cg_read_pid(f
, &pid
);
110 r
= pidref_set_pid(ret
, pid
);
116 /* ESRCH → gone by now? just skip over it, read the next */
121 const char *controller
,
126 _cleanup_free_
char *events
= NULL
, *content
= NULL
;
129 r
= cg_get_path(controller
, path
, "cgroup.events", &events
);
133 r
= read_full_virtual_file(events
, &content
, NULL
);
137 for (const char *p
= content
;;) {
138 _cleanup_free_
char *line
= NULL
, *key
= NULL
, *val
= NULL
;
141 r
= extract_first_word(&p
, &line
, "\n", 0);
148 r
= extract_first_word(&q
, &key
, " ", 0);
154 if (!streq(key
, event
))
161 *ret
= TAKE_PTR(val
);
166 bool cg_ns_supported(void) {
167 static thread_local
int enabled
= -1;
172 if (access("/proc/self/ns/cgroup", F_OK
) < 0) {
174 log_debug_errno(errno
, "Failed to check whether /proc/self/ns/cgroup is available, assuming not: %m");
182 bool cg_freezer_supported(void) {
183 static thread_local
int supported
= -1;
188 supported
= cg_all_unified() > 0 && access("/sys/fs/cgroup/init.scope/cgroup.freeze", F_OK
) == 0;
193 bool cg_kill_supported(void) {
194 static thread_local
int supported
= -1;
199 if (cg_all_unified() <= 0)
201 else if (access("/sys/fs/cgroup/init.scope/cgroup.kill", F_OK
) < 0) {
203 log_debug_errno(errno
, "Failed to check if cgroup.kill is available, assuming not: %m");
211 int cg_enumerate_subgroups(const char *controller
, const char *path
, DIR **ret
) {
212 _cleanup_free_
char *fs
= NULL
;
218 /* This is not recursive! */
220 r
= cg_get_path(controller
, path
, NULL
, &fs
);
232 int cg_read_subgroup(DIR *d
, char **ret
) {
236 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
239 if (de
->d_type
!= DT_DIR
)
242 if (dot_or_dot_dot(de
->d_name
))
245 b
= strdup(de
->d_name
);
257 int cg_rmdir(const char *controller
, const char *path
) {
258 _cleanup_free_
char *p
= NULL
;
261 r
= cg_get_path(controller
, path
, NULL
, &p
);
266 if (r
< 0 && errno
!= ENOENT
)
269 r
= cg_hybrid_unified();
273 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
274 r
= cg_rmdir(SYSTEMD_CGROUP_CONTROLLER_LEGACY
, path
);
276 log_warning_errno(r
, "Failed to remove compat systemd cgroup %s: %m", path
);
282 static int cg_kill_items(
287 cg_kill_log_func_t log_kill
,
291 _cleanup_set_free_ Set
*allocated_set
= NULL
;
293 int r
, ret
= 0, ret_log_kill
= 0;
297 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
298 * SIGCONT on SIGKILL. */
299 if (IN_SET(sig
, SIGCONT
, SIGKILL
))
300 flags
&= ~CGROUP_SIGCONT
;
302 /* This goes through the tasks list and kills them all. This
303 * is repeated until no further processes are added to the
304 * tasks list, to properly handle forking processes */
307 s
= allocated_set
= set_new(NULL
);
313 _cleanup_fclose_
FILE *f
= NULL
;
316 r
= cg_enumerate_items(SYSTEMD_CGROUP_CONTROLLER
, path
, &f
, item
);
320 return RET_GATHER(ret
, r
);
323 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
325 r
= cg_read_pidref(f
, &pidref
);
327 return RET_GATHER(ret
, r
);
331 if ((flags
& CGROUP_IGNORE_SELF
) && pidref_is_self(&pidref
))
334 if (set_get(s
, PID_TO_PTR(pidref
.pid
)) == PID_TO_PTR(pidref
.pid
))
338 ret_log_kill
= log_kill(&pidref
, sig
, userdata
);
340 /* If we haven't killed this process yet, kill it */
341 r
= pidref_kill(&pidref
, sig
);
342 if (r
< 0 && r
!= -ESRCH
)
345 if (flags
& CGROUP_SIGCONT
)
346 (void) pidref_kill(&pidref
, SIGCONT
);
358 r
= set_put(s
, PID_TO_PTR(pidref
.pid
));
360 return RET_GATHER(ret
, r
);
363 /* To avoid racing against processes which fork quicker than we can kill them, we repeat this
364 * until no new pids need to be killed. */
376 cg_kill_log_func_t log_kill
,
381 r
= cg_kill_items(path
, sig
, flags
, s
, log_kill
, userdata
, "cgroup.procs");
382 if (r
< 0 || sig
!= SIGKILL
)
387 /* Only in case of killing with SIGKILL and when using cgroupsv2, kill remaining threads manually as
388 a workaround for kernel bug. It was fixed in 5.2-rc5 (c03cd7738a83), backported to 4.19.66
389 (4340d175b898) and 4.14.138 (feb6b123b7dd). */
390 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
396 r
= cg_kill_items(path
, sig
, flags
, s
, log_kill
, userdata
, "cgroup.threads");
400 return r
> 0 || ret
> 0;
403 int cg_kill_kernel_sigkill(const char *path
) {
404 /* Kills the cgroup at `path` directly by writing to its cgroup.kill file. This sends SIGKILL to all
405 * processes in the cgroup and has the advantage of being completely atomic, unlike cg_kill_items(). */
407 _cleanup_free_
char *killfile
= NULL
;
412 if (!cg_kill_supported())
415 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, "cgroup.kill", &killfile
);
419 r
= write_string_file(killfile
, "1", WRITE_STRING_FILE_DISABLE_BUFFER
);
426 int cg_kill_recursive(
431 cg_kill_log_func_t log_kill
,
439 if (sig
== SIGKILL
&& cg_kill_supported() &&
440 !FLAGS_SET(flags
, CGROUP_IGNORE_SELF
) && !s
&& !log_kill
)
441 /* ignore CGROUP_SIGCONT, since this is a no-op alongside SIGKILL */
442 ret
= cg_kill_kernel_sigkill(path
);
444 _cleanup_set_free_ Set
*allocated_set
= NULL
;
445 _cleanup_closedir_
DIR *d
= NULL
;
448 s
= allocated_set
= set_new(NULL
);
453 ret
= cg_kill(path
, sig
, flags
, s
, log_kill
, userdata
);
455 r
= cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER
, path
, &d
);
464 _cleanup_free_
char *fn
= NULL
, *p
= NULL
;
466 r
= cg_read_subgroup(d
, &fn
);
474 p
= path_join(empty_to_root(path
), fn
);
478 r
= cg_kill_recursive(p
, sig
, flags
, s
, log_kill
, userdata
);
479 if (r
!= 0 && ret
>= 0)
484 if (FLAGS_SET(flags
, CGROUP_REMOVE
)) {
485 r
= cg_rmdir(SYSTEMD_CGROUP_CONTROLLER
, path
);
486 if (!IN_SET(r
, -ENOENT
, -EBUSY
))
493 static const char *controller_to_dirname(const char *controller
) {
496 /* Converts a controller name to the directory name below /sys/fs/cgroup/ we want to mount it
497 * to. Effectively, this just cuts off the name= prefixed used for named hierarchies, if it is
500 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
501 if (cg_hybrid_unified() > 0)
502 controller
= SYSTEMD_CGROUP_CONTROLLER_HYBRID
;
504 controller
= SYSTEMD_CGROUP_CONTROLLER_LEGACY
;
507 return startswith(controller
, "name=") ?: controller
;
510 static int join_path_legacy(const char *controller
, const char *path
, const char *suffix
, char **ret
) {
517 dn
= controller_to_dirname(controller
);
519 if (isempty(path
) && isempty(suffix
))
520 t
= path_join("/sys/fs/cgroup", dn
);
521 else if (isempty(path
))
522 t
= path_join("/sys/fs/cgroup", dn
, suffix
);
523 else if (isempty(suffix
))
524 t
= path_join("/sys/fs/cgroup", dn
, path
);
526 t
= path_join("/sys/fs/cgroup", dn
, path
, suffix
);
534 static int join_path_unified(const char *path
, const char *suffix
, char **ret
) {
539 if (isempty(path
) && isempty(suffix
))
540 t
= strdup("/sys/fs/cgroup");
541 else if (isempty(path
))
542 t
= path_join("/sys/fs/cgroup", suffix
);
543 else if (isempty(suffix
))
544 t
= path_join("/sys/fs/cgroup", path
);
546 t
= path_join("/sys/fs/cgroup", path
, suffix
);
554 int cg_get_path(const char *controller
, const char *path
, const char *suffix
, char **ret
) {
562 /* If no controller is specified, we return the path *below* the controllers, without any
565 if (isempty(path
) && isempty(suffix
))
570 else if (isempty(path
))
573 t
= path_join(path
, suffix
);
577 *ret
= path_simplify(t
);
581 if (!cg_controller_is_valid(controller
))
584 r
= cg_all_unified();
588 r
= join_path_unified(path
, suffix
, ret
);
590 r
= join_path_legacy(controller
, path
, suffix
, ret
);
598 static int controller_is_v1_accessible(const char *root
, const char *controller
) {
599 const char *cpath
, *dn
;
603 dn
= controller_to_dirname(controller
);
605 /* If root if specified, we check that:
606 * - possible subcgroup is created at root,
607 * - we can modify the hierarchy. */
609 cpath
= strjoina("/sys/fs/cgroup/", dn
, root
, root
? "/cgroup.procs" : NULL
);
610 return laccess(cpath
, root
? W_OK
: F_OK
);
613 int cg_get_path_and_check(const char *controller
, const char *path
, const char *suffix
, char **ret
) {
619 if (!cg_controller_is_valid(controller
))
622 r
= cg_all_unified();
626 /* In the unified hierarchy all controllers are considered accessible,
627 * except for the named hierarchies */
628 if (startswith(controller
, "name="))
631 /* Check if the specified controller is actually accessible */
632 r
= controller_is_v1_accessible(NULL
, controller
);
637 return cg_get_path(controller
, path
, suffix
, ret
);
640 int cg_set_xattr(const char *path
, const char *name
, const void *value
, size_t size
, int flags
) {
641 _cleanup_free_
char *fs
= NULL
;
646 assert(value
|| size
<= 0);
648 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, NULL
, &fs
);
652 return RET_NERRNO(setxattr(fs
, name
, value
, size
, flags
));
655 int cg_get_xattr(const char *path
, const char *name
, void *value
, size_t size
) {
656 _cleanup_free_
char *fs
= NULL
;
663 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, NULL
, &fs
);
667 n
= getxattr(fs
, name
, value
, size
);
674 int cg_get_xattr_malloc(const char *path
, const char *name
, char **ret
) {
675 _cleanup_free_
char *fs
= NULL
;
681 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, NULL
, &fs
);
685 return lgetxattr_malloc(fs
, name
, ret
);
688 int cg_get_xattr_bool(const char *path
, const char *name
) {
689 _cleanup_free_
char *fs
= NULL
;
695 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, NULL
, &fs
);
699 return getxattr_at_bool(AT_FDCWD
, fs
, name
, /* flags= */ 0);
702 int cg_remove_xattr(const char *path
, const char *name
) {
703 _cleanup_free_
char *fs
= NULL
;
709 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, NULL
, &fs
);
713 return RET_NERRNO(removexattr(fs
, name
));
716 int cg_pid_get_path(const char *controller
, pid_t pid
, char **ret_path
) {
717 _cleanup_fclose_
FILE *f
= NULL
;
718 const char *fs
, *controller_str
= NULL
; /* avoid false maybe-uninitialized warning */
725 if (!cg_controller_is_valid(controller
))
728 controller
= SYSTEMD_CGROUP_CONTROLLER
;
730 unified
= cg_unified_controller(controller
);
734 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
))
735 controller_str
= SYSTEMD_CGROUP_CONTROLLER_LEGACY
;
737 controller_str
= controller
;
740 fs
= procfs_file_alloca(pid
, "cgroup");
741 r
= fopen_unlocked(fs
, "re", &f
);
748 _cleanup_free_
char *line
= NULL
;
751 r
= read_line(f
, LONG_LINE_MAX
, &line
);
758 e
= startswith(line
, "0:");
768 l
= strchr(line
, ':');
778 assert(controller_str
);
779 r
= string_contains_word(l
, ",", controller_str
);
786 char *path
= strdup(e
+ 1);
790 /* Truncate suffix indicating the process is a zombie */
791 e
= endswith(path
, " (deleted)");
800 int cg_pidref_get_path(const char *controller
, const PidRef
*pidref
, char **ret_path
) {
801 _cleanup_free_
char *path
= NULL
;
806 if (!pidref_is_set(pidref
))
809 r
= cg_pid_get_path(controller
, pidref
->pid
, &path
);
813 /* Before we return the path, make sure the procfs entry for this pid still matches the pidref */
814 r
= pidref_verify(pidref
);
818 *ret_path
= TAKE_PTR(path
);
822 int cg_install_release_agent(const char *controller
, const char *agent
) {
823 _cleanup_free_
char *fs
= NULL
, *contents
= NULL
;
829 r
= cg_unified_controller(controller
);
832 if (r
> 0) /* doesn't apply to unified hierarchy */
835 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
839 r
= read_one_line_file(fs
, &contents
);
843 sc
= strstrip(contents
);
845 r
= write_string_file(fs
, agent
, WRITE_STRING_FILE_DISABLE_BUFFER
);
848 } else if (!path_equal(sc
, agent
))
852 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
856 contents
= mfree(contents
);
857 r
= read_one_line_file(fs
, &contents
);
861 sc
= strstrip(contents
);
862 if (streq(sc
, "0")) {
863 r
= write_string_file(fs
, "1", WRITE_STRING_FILE_DISABLE_BUFFER
);
876 int cg_uninstall_release_agent(const char *controller
) {
877 _cleanup_free_
char *fs
= NULL
;
880 r
= cg_unified_controller(controller
);
883 if (r
> 0) /* Doesn't apply to unified hierarchy */
886 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
890 r
= write_string_file(fs
, "0", WRITE_STRING_FILE_DISABLE_BUFFER
);
896 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
900 r
= write_string_file(fs
, "", WRITE_STRING_FILE_DISABLE_BUFFER
);
907 int cg_is_empty(const char *controller
, const char *path
) {
908 _cleanup_fclose_
FILE *f
= NULL
;
914 r
= cg_enumerate_processes(controller
, path
, &f
);
920 r
= cg_read_pid(f
, &pid
);
927 int cg_is_empty_recursive(const char *controller
, const char *path
) {
932 /* The root cgroup is always populated */
933 if (controller
&& empty_or_root(path
))
936 r
= cg_unified_controller(controller
);
940 _cleanup_free_
char *t
= NULL
;
942 /* On the unified hierarchy we can check empty state
943 * via the "populated" attribute of "cgroup.events". */
945 r
= cg_read_event(controller
, path
, "populated", &t
);
951 return streq(t
, "0");
953 _cleanup_closedir_
DIR *d
= NULL
;
956 r
= cg_is_empty(controller
, path
);
960 r
= cg_enumerate_subgroups(controller
, path
, &d
);
966 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
967 _cleanup_free_
char *p
= NULL
;
969 p
= path_join(path
, fn
);
974 r
= cg_is_empty_recursive(controller
, p
);
985 int cg_split_spec(const char *spec
, char **ret_controller
, char **ret_path
) {
986 _cleanup_free_
char *controller
= NULL
, *path
= NULL
;
992 if (!path_is_normalized(spec
))
996 r
= path_simplify_alloc(spec
, &path
);
1004 e
= strchr(spec
, ':');
1006 controller
= strndup(spec
, e
-spec
);
1009 if (!cg_controller_is_valid(controller
))
1012 if (!isempty(e
+ 1)) {
1017 if (!path_is_normalized(path
) ||
1018 !path_is_absolute(path
))
1021 path_simplify(path
);
1025 if (!cg_controller_is_valid(spec
))
1028 if (ret_controller
) {
1029 controller
= strdup(spec
);
1037 *ret_controller
= TAKE_PTR(controller
);
1039 *ret_path
= TAKE_PTR(path
);
1043 int cg_mangle_path(const char *path
, char **ret
) {
1044 _cleanup_free_
char *c
= NULL
, *p
= NULL
;
1050 /* First, check if it already is a filesystem path */
1051 if (path_startswith(path
, "/sys/fs/cgroup"))
1052 return path_simplify_alloc(path
, ret
);
1054 /* Otherwise, treat it as cg spec */
1055 r
= cg_split_spec(path
, &c
, &p
);
1059 return cg_get_path(c
?: SYSTEMD_CGROUP_CONTROLLER
, p
?: "/", NULL
, ret
);
1062 int cg_get_root_path(char **ret_path
) {
1068 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 1, &p
);
1072 e
= endswith(p
, "/" SPECIAL_INIT_SCOPE
);
1074 e
= endswith(p
, "/" SPECIAL_SYSTEM_SLICE
); /* legacy */
1076 e
= endswith(p
, "/system"); /* even more legacy */
1084 int cg_shift_path(const char *cgroup
, const char *root
, const char **ret_shifted
) {
1085 _cleanup_free_
char *rt
= NULL
;
1090 assert(ret_shifted
);
1093 /* If the root was specified let's use that, otherwise
1094 * let's determine it from PID 1 */
1096 r
= cg_get_root_path(&rt
);
1103 p
= path_startswith(cgroup
, root
);
1104 if (p
&& p
> cgroup
)
1105 *ret_shifted
= p
- 1;
1107 *ret_shifted
= cgroup
;
1112 int cg_pid_get_path_shifted(pid_t pid
, const char *root
, char **ret_cgroup
) {
1113 _cleanup_free_
char *raw
= NULL
;
1120 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &raw
);
1124 r
= cg_shift_path(raw
, root
, &c
);
1129 *ret_cgroup
= TAKE_PTR(raw
);
1143 int cg_path_decode_unit(const char *cgroup
, char **ret_unit
) {
1150 n
= strcspn(cgroup
, "/");
1154 c
= strndupa_safe(cgroup
, n
);
1157 if (!unit_name_is_valid(c
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
1168 static bool valid_slice_name(const char *p
, size_t n
) {
1173 if (n
< STRLEN("x.slice"))
1176 if (memcmp(p
+ n
- 6, ".slice", 6) == 0) {
1182 c
= cg_unescape(buf
);
1184 return unit_name_is_valid(c
, UNIT_NAME_PLAIN
);
1190 static const char *skip_slices(const char *p
) {
1193 /* Skips over all slice assignments */
1198 p
+= strspn(p
, "/");
1200 n
= strcspn(p
, "/");
1201 if (!valid_slice_name(p
, n
))
1208 int cg_path_get_unit(const char *path
, char **ret
) {
1209 _cleanup_free_
char *unit
= NULL
;
1216 e
= skip_slices(path
);
1218 r
= cg_path_decode_unit(e
, &unit
);
1222 /* We skipped over the slices, don't accept any now */
1223 if (endswith(unit
, ".slice"))
1226 *ret
= TAKE_PTR(unit
);
1230 int cg_path_get_unit_path(const char *path
, char **ret
) {
1231 _cleanup_free_
char *path_copy
= NULL
;
1237 path_copy
= strdup(path
);
1241 unit_name
= (char *)skip_slices(path_copy
);
1242 unit_name
[strcspn(unit_name
, "/")] = 0;
1244 if (!unit_name_is_valid(cg_unescape(unit_name
), UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
1247 *ret
= TAKE_PTR(path_copy
);
1252 int cg_pid_get_unit(pid_t pid
, char **ret_unit
) {
1253 _cleanup_free_
char *cgroup
= NULL
;
1258 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1262 return cg_path_get_unit(cgroup
, ret_unit
);
1265 int cg_pidref_get_unit(const PidRef
*pidref
, char **ret
) {
1266 _cleanup_free_
char *unit
= NULL
;
1271 if (!pidref_is_set(pidref
))
1274 r
= cg_pid_get_unit(pidref
->pid
, &unit
);
1278 r
= pidref_verify(pidref
);
1282 *ret
= TAKE_PTR(unit
);
1287 * Skip session-*.scope, but require it to be there.
1289 static const char *skip_session(const char *p
) {
1295 p
+= strspn(p
, "/");
1297 n
= strcspn(p
, "/");
1298 if (n
< STRLEN("session-x.scope"))
1301 if (memcmp(p
, "session-", 8) == 0 && memcmp(p
+ n
- 6, ".scope", 6) == 0) {
1302 char buf
[n
- 8 - 6 + 1];
1304 memcpy(buf
, p
+ 8, n
- 8 - 6);
1307 /* Note that session scopes never need unescaping,
1308 * since they cannot conflict with the kernel's own
1309 * names, hence we don't need to call cg_unescape()
1312 if (!session_id_valid(buf
))
1316 p
+= strspn(p
, "/");
1324 * Skip user@*.service, but require it to be there.
1326 static const char *skip_user_manager(const char *p
) {
1332 p
+= strspn(p
, "/");
1334 n
= strcspn(p
, "/");
1335 if (n
< STRLEN("user@x.service"))
1338 if (memcmp(p
, "user@", 5) == 0 && memcmp(p
+ n
- 8, ".service", 8) == 0) {
1339 char buf
[n
- 5 - 8 + 1];
1341 memcpy(buf
, p
+ 5, n
- 5 - 8);
1344 /* Note that user manager services never need unescaping,
1345 * since they cannot conflict with the kernel's own
1346 * names, hence we don't need to call cg_unescape()
1349 if (parse_uid(buf
, NULL
) < 0)
1353 p
+= strspn(p
, "/");
1361 static const char *skip_user_prefix(const char *path
) {
1366 /* Skip slices, if there are any */
1367 e
= skip_slices(path
);
1369 /* Skip the user manager, if it's in the path now... */
1370 t
= skip_user_manager(e
);
1374 /* Alternatively skip the user session if it is in the path... */
1375 return skip_session(e
);
1378 int cg_path_get_user_unit(const char *path
, char **ret
) {
1384 t
= skip_user_prefix(path
);
1388 /* And from here on it looks pretty much the same as for a system unit, hence let's use the same
1390 return cg_path_get_unit(t
, ret
);
1393 int cg_pid_get_user_unit(pid_t pid
, char **ret_unit
) {
1394 _cleanup_free_
char *cgroup
= NULL
;
1399 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1403 return cg_path_get_user_unit(cgroup
, ret_unit
);
1406 int cg_path_get_machine_name(const char *path
, char **ret_machine
) {
1407 _cleanup_free_
char *u
= NULL
;
1411 r
= cg_path_get_unit(path
, &u
);
1415 sl
= strjoina("/run/systemd/machines/unit:", u
);
1416 return readlink_malloc(sl
, ret_machine
);
1419 int cg_pid_get_machine_name(pid_t pid
, char **ret_machine
) {
1420 _cleanup_free_
char *cgroup
= NULL
;
1423 assert(ret_machine
);
1425 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1429 return cg_path_get_machine_name(cgroup
, ret_machine
);
1432 int cg_path_get_cgroupid(const char *path
, uint64_t *ret
) {
1433 cg_file_handle fh
= CG_FILE_HANDLE_INIT
;
1439 /* This is cgroupfs so we know the size of the handle, thus no need to loop around like
1440 * name_to_handle_at_loop() does in mountpoint-util.c */
1441 if (name_to_handle_at(AT_FDCWD
, path
, &fh
.file_handle
, &mnt_id
, 0) < 0)
1444 *ret
= CG_FILE_HANDLE_CGROUPID(fh
);
1448 int cg_path_get_session(const char *path
, char **ret_session
) {
1449 _cleanup_free_
char *unit
= NULL
;
1455 r
= cg_path_get_unit(path
, &unit
);
1459 start
= startswith(unit
, "session-");
1462 end
= endswith(start
, ".scope");
1467 if (!session_id_valid(start
))
1483 int cg_pid_get_session(pid_t pid
, char **ret_session
) {
1484 _cleanup_free_
char *cgroup
= NULL
;
1487 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1491 return cg_path_get_session(cgroup
, ret_session
);
1494 int cg_path_get_owner_uid(const char *path
, uid_t
*ret_uid
) {
1495 _cleanup_free_
char *slice
= NULL
;
1501 r
= cg_path_get_slice(path
, &slice
);
1505 start
= startswith(slice
, "user-");
1509 end
= endswith(start
, ".slice");
1514 if (parse_uid(start
, ret_uid
) < 0)
1520 int cg_pid_get_owner_uid(pid_t pid
, uid_t
*ret_uid
) {
1521 _cleanup_free_
char *cgroup
= NULL
;
1524 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1528 return cg_path_get_owner_uid(cgroup
, ret_uid
);
1531 int cg_path_get_slice(const char *p
, char **ret_slice
) {
1532 const char *e
= NULL
;
1537 /* Finds the right-most slice unit from the beginning, but
1538 * stops before we come to the first non-slice unit. */
1543 p
+= strspn(p
, "/");
1545 n
= strcspn(p
, "/");
1546 if (!valid_slice_name(p
, n
)) {
1551 s
= strdup(SPECIAL_ROOT_SLICE
);
1559 return cg_path_decode_unit(e
, ret_slice
);
1567 int cg_pid_get_slice(pid_t pid
, char **ret_slice
) {
1568 _cleanup_free_
char *cgroup
= NULL
;
1573 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1577 return cg_path_get_slice(cgroup
, ret_slice
);
1580 int cg_path_get_user_slice(const char *p
, char **ret_slice
) {
1585 t
= skip_user_prefix(p
);
1589 /* And now it looks pretty much the same as for a system slice, so let's just use the same parser
1591 return cg_path_get_slice(t
, ret_slice
);
1594 int cg_pid_get_user_slice(pid_t pid
, char **ret_slice
) {
1595 _cleanup_free_
char *cgroup
= NULL
;
1600 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1604 return cg_path_get_user_slice(cgroup
, ret_slice
);
1607 bool cg_needs_escape(const char *p
) {
1609 /* Checks if the specified path is a valid cgroup name by our rules, or if it must be escaped. Note
1610 * that we consider escaped cgroup names invalid here, as they need to be escaped a second time if
1611 * they shall be used. Also note that various names cannot be made valid by escaping even if we
1612 * return true here (because too long, or contain the forbidden character "/"). */
1614 if (!filename_is_valid(p
))
1617 if (IN_SET(p
[0], '_', '.'))
1620 if (STR_IN_SET(p
, "notify_on_release", "release_agent", "tasks"))
1623 if (startswith(p
, "cgroup."))
1626 for (CGroupController c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1629 q
= startswith(p
, cgroup_controller_to_string(c
));
1640 int cg_escape(const char *p
, char **ret
) {
1641 _cleanup_free_
char *n
= NULL
;
1643 /* This implements very minimal escaping for names to be used as file names in the cgroup tree: any
1644 * name which might conflict with a kernel name or is prefixed with '_' is prefixed with a '_'. That
1645 * way, when reading cgroup names it is sufficient to remove a single prefixing underscore if there
1648 /* The return value of this function (unlike cg_unescape()) needs free()! */
1650 if (cg_needs_escape(p
)) {
1651 n
= strjoin("_", p
);
1655 if (!filename_is_valid(n
)) /* became invalid due to the prefixing? Or contained things like a slash that cannot be fixed by prefixing? */
1667 char *cg_unescape(const char *p
) {
1670 /* The return value of this function (unlike cg_escape())
1671 * doesn't need free()! */
1679 #define CONTROLLER_VALID \
1683 bool cg_controller_is_valid(const char *p
) {
1689 if (streq(p
, SYSTEMD_CGROUP_CONTROLLER
))
1692 s
= startswith(p
, "name=");
1696 if (IN_SET(*p
, 0, '_'))
1699 for (t
= p
; *t
; t
++)
1700 if (!strchr(CONTROLLER_VALID
, *t
))
1703 if (t
- p
> NAME_MAX
)
1709 int cg_slice_to_path(const char *unit
, char **ret
) {
1710 _cleanup_free_
char *p
= NULL
, *s
= NULL
, *e
= NULL
;
1717 if (streq(unit
, SPECIAL_ROOT_SLICE
)) {
1727 if (!unit_name_is_valid(unit
, UNIT_NAME_PLAIN
))
1730 if (!endswith(unit
, ".slice"))
1733 r
= unit_name_to_prefix(unit
, &p
);
1737 dash
= strchr(p
, '-');
1739 /* Don't allow initial dashes */
1744 _cleanup_free_
char *escaped
= NULL
;
1745 char n
[dash
- p
+ sizeof(".slice")];
1747 #if HAS_FEATURE_MEMORY_SANITIZER
1748 /* msan doesn't instrument stpncpy, so it thinks
1749 * n is later used uninitialized:
1750 * https://github.com/google/sanitizers/issues/926
1755 /* Don't allow trailing or double dashes */
1756 if (IN_SET(dash
[1], 0, '-'))
1759 strcpy(stpncpy(n
, p
, dash
- p
), ".slice");
1760 if (!unit_name_is_valid(n
, UNIT_NAME_PLAIN
))
1763 r
= cg_escape(n
, &escaped
);
1767 if (!strextend(&s
, escaped
, "/"))
1770 dash
= strchr(dash
+1, '-');
1773 r
= cg_escape(unit
, &e
);
1777 if (!strextend(&s
, e
))
1784 int cg_is_threaded(const char *path
) {
1785 _cleanup_free_
char *fs
= NULL
, *contents
= NULL
;
1786 _cleanup_strv_free_
char **v
= NULL
;
1789 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, "cgroup.type", &fs
);
1793 r
= read_full_virtual_file(fs
, &contents
, NULL
);
1795 return false; /* Assume no. */
1799 v
= strv_split(contents
, NULL
);
1803 /* If the cgroup is in the threaded mode, it contains "threaded".
1804 * If one of the parents or siblings is in the threaded mode, it may contain "invalid". */
1805 return strv_contains(v
, "threaded") || strv_contains(v
, "invalid");
1808 int cg_set_attribute(const char *controller
, const char *path
, const char *attribute
, const char *value
) {
1809 _cleanup_free_
char *p
= NULL
;
1812 r
= cg_get_path(controller
, path
, attribute
, &p
);
1816 return write_string_file(p
, value
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1819 int cg_get_attribute(const char *controller
, const char *path
, const char *attribute
, char **ret
) {
1820 _cleanup_free_
char *p
= NULL
;
1823 r
= cg_get_path(controller
, path
, attribute
, &p
);
1827 return read_one_line_file(p
, ret
);
1830 int cg_get_attribute_as_uint64(const char *controller
, const char *path
, const char *attribute
, uint64_t *ret
) {
1831 _cleanup_free_
char *value
= NULL
;
1837 r
= cg_get_attribute(controller
, path
, attribute
, &value
);
1843 if (streq(value
, "max")) {
1844 *ret
= CGROUP_LIMIT_MAX
;
1848 r
= safe_atou64(value
, &v
);
1856 int cg_get_attribute_as_bool(const char *controller
, const char *path
, const char *attribute
, bool *ret
) {
1857 _cleanup_free_
char *value
= NULL
;
1862 r
= cg_get_attribute(controller
, path
, attribute
, &value
);
1868 r
= parse_boolean(value
);
1876 int cg_get_owner(const char *path
, uid_t
*ret_uid
) {
1877 _cleanup_free_
char *f
= NULL
;
1883 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, NULL
, &f
);
1887 if (stat(f
, &stats
) < 0)
1890 r
= stat_verify_directory(&stats
);
1894 *ret_uid
= stats
.st_uid
;
1898 int cg_get_keyed_attribute_full(
1899 const char *controller
,
1901 const char *attribute
,
1904 CGroupKeyMode mode
) {
1906 _cleanup_free_
char *filename
= NULL
, *contents
= NULL
;
1908 size_t n
, i
, n_done
= 0;
1912 /* Reads one or more fields of a cgroup v2 keyed attribute file. The 'keys' parameter should be an strv with
1913 * all keys to retrieve. The 'ret_values' parameter should be passed as string size with the same number of
1914 * entries as 'keys'. On success each entry will be set to the value of the matching key.
1916 * If the attribute file doesn't exist at all returns ENOENT, if any key is not found returns ENXIO. If mode
1917 * is set to GG_KEY_MODE_GRACEFUL we ignore missing keys and return those that were parsed successfully. */
1919 r
= cg_get_path(controller
, path
, attribute
, &filename
);
1923 r
= read_full_file(filename
, &contents
, NULL
);
1927 n
= strv_length(keys
);
1928 if (n
== 0) /* No keys to retrieve? That's easy, we are done then */
1931 /* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
1932 v
= newa0(char*, n
);
1934 for (p
= contents
; *p
;) {
1935 const char *w
= NULL
;
1937 for (i
= 0; i
< n
; i
++)
1939 w
= first_word(p
, keys
[i
]);
1947 l
= strcspn(w
, NEWLINE
);
1948 v
[i
] = strndup(w
, l
);
1960 p
+= strcspn(p
, NEWLINE
);
1962 p
+= strspn(p
, NEWLINE
);
1965 if (mode
& CG_KEY_MODE_GRACEFUL
)
1971 free_many_charp(v
, n
);
1975 memcpy(ret_values
, v
, sizeof(char*) * n
);
1976 if (mode
& CG_KEY_MODE_GRACEFUL
)
1982 int cg_mask_to_string(CGroupMask mask
, char **ret
) {
1983 _cleanup_free_
char *s
= NULL
;
1995 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1999 if (!FLAGS_SET(mask
, CGROUP_CONTROLLER_TO_MASK(c
)))
2002 k
= cgroup_controller_to_string(c
);
2005 if (!GREEDY_REALLOC(s
, n
+ space
+ l
+ 1))
2010 memcpy(s
+ n
+ space
, k
, l
);
2024 int cg_mask_from_string(const char *value
, CGroupMask
*ret
) {
2031 _cleanup_free_
char *n
= NULL
;
2035 r
= extract_first_word(&value
, &n
, NULL
, 0);
2041 v
= cgroup_controller_from_string(n
);
2045 m
|= CGROUP_CONTROLLER_TO_MASK(v
);
2052 int cg_mask_supported_subtree(const char *root
, CGroupMask
*ret
) {
2056 /* Determines the mask of supported cgroup controllers. Only includes controllers we can make sense of and that
2057 * are actually accessible. Only covers real controllers, i.e. not the CGROUP_CONTROLLER_BPF_xyz
2058 * pseudo-controllers. */
2060 r
= cg_all_unified();
2064 _cleanup_free_
char *controllers
= NULL
, *path
= NULL
;
2066 /* In the unified hierarchy we can read the supported and accessible controllers from
2067 * the top-level cgroup attribute */
2069 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, root
, "cgroup.controllers", &path
);
2073 r
= read_one_line_file(path
, &controllers
);
2077 r
= cg_mask_from_string(controllers
, &mask
);
2081 /* Mask controllers that are not supported in unified hierarchy. */
2082 mask
&= CGROUP_MASK_V2
;
2087 /* In the legacy hierarchy, we check which hierarchies are accessible. */
2090 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2091 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2094 if (!FLAGS_SET(CGROUP_MASK_V1
, bit
))
2097 n
= cgroup_controller_to_string(c
);
2098 if (controller_is_v1_accessible(root
, n
) >= 0)
2107 int cg_mask_supported(CGroupMask
*ret
) {
2108 _cleanup_free_
char *root
= NULL
;
2111 r
= cg_get_root_path(&root
);
2115 return cg_mask_supported_subtree(root
, ret
);
2118 int cg_kernel_controllers(Set
**ret
) {
2119 _cleanup_set_free_ Set
*controllers
= NULL
;
2120 _cleanup_fclose_
FILE *f
= NULL
;
2125 /* Determines the full list of kernel-known controllers. Might include controllers we don't actually support
2126 * and controllers that aren't currently accessible (because not mounted). This does not include "name="
2127 * pseudo-controllers. */
2129 r
= fopen_unlocked("/proc/cgroups", "re", &f
);
2137 /* Ignore the header line */
2138 (void) read_line(f
, SIZE_MAX
, NULL
);
2141 _cleanup_free_
char *controller
= NULL
;
2145 if (fscanf(f
, "%ms %*i %*i %i", &controller
, &enabled
) != 2) {
2151 return errno_or_else(EIO
);
2159 if (!cg_controller_is_valid(controller
))
2162 r
= set_ensure_consume(&controllers
, &string_hash_ops_free
, TAKE_PTR(controller
));
2167 *ret
= TAKE_PTR(controllers
);
2172 /* The hybrid mode was initially implemented in v232 and simply mounted cgroup2 on
2173 * /sys/fs/cgroup/systemd. This unfortunately broke other tools (such as docker) which expected the v1
2174 * "name=systemd" hierarchy on /sys/fs/cgroup/systemd. From v233 and on, the hybrid mode mounts v2 on
2175 * /sys/fs/cgroup/unified and maintains "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility
2178 * To keep live upgrade working, we detect and support v232 layout. When v232 layout is detected, to keep
2179 * cgroup v2 process management but disable the compat dual layout, we return true on
2180 * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and false on cg_hybrid_unified().
2182 static thread_local
bool unified_systemd_v232
;
2184 int cg_unified_cached(bool flush
) {
2185 static thread_local CGroupUnified unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
2189 /* Checks if we support the unified hierarchy. Returns an
2190 * error when the cgroup hierarchies aren't mounted yet or we
2191 * have any other trouble determining if the unified hierarchy
2195 unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
2196 else if (unified_cache
>= CGROUP_UNIFIED_NONE
)
2197 return unified_cache
;
2199 if (statfs("/sys/fs/cgroup/", &fs
) < 0)
2200 return log_debug_errno(errno
, "statfs(\"/sys/fs/cgroup/\") failed: %m");
2202 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
2203 log_debug("Found cgroup2 on /sys/fs/cgroup/, full unified hierarchy");
2204 unified_cache
= CGROUP_UNIFIED_ALL
;
2205 } else if (F_TYPE_EQUAL(fs
.f_type
, TMPFS_MAGIC
)) {
2206 if (statfs("/sys/fs/cgroup/unified/", &fs
) == 0 &&
2207 F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
2208 log_debug("Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller");
2209 unified_cache
= CGROUP_UNIFIED_SYSTEMD
;
2210 unified_systemd_v232
= false;
2212 if (statfs("/sys/fs/cgroup/systemd/", &fs
) < 0) {
2213 if (errno
== ENOENT
) {
2214 /* Some other software may have set up /sys/fs/cgroup in a configuration we do not recognize. */
2215 log_debug_errno(errno
, "Unsupported cgroupsv1 setup detected: name=systemd hierarchy not found.");
2218 return log_debug_errno(errno
, "statfs(\"/sys/fs/cgroup/systemd\" failed: %m");
2221 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
2222 log_debug("Found cgroup2 on /sys/fs/cgroup/systemd, unified hierarchy for systemd controller (v232 variant)");
2223 unified_cache
= CGROUP_UNIFIED_SYSTEMD
;
2224 unified_systemd_v232
= true;
2225 } else if (F_TYPE_EQUAL(fs
.f_type
, CGROUP_SUPER_MAGIC
)) {
2226 log_debug("Found cgroup on /sys/fs/cgroup/systemd, legacy hierarchy");
2227 unified_cache
= CGROUP_UNIFIED_NONE
;
2229 log_debug("Unexpected filesystem type %llx mounted on /sys/fs/cgroup/systemd, assuming legacy hierarchy",
2230 (unsigned long long) fs
.f_type
);
2231 unified_cache
= CGROUP_UNIFIED_NONE
;
2234 } else if (F_TYPE_EQUAL(fs
.f_type
, SYSFS_MAGIC
)) {
2235 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
2236 "No filesystem is currently mounted on /sys/fs/cgroup.");
2238 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
2239 "Unknown filesystem type %llx mounted on /sys/fs/cgroup.",
2240 (unsigned long long)fs
.f_type
);
2242 return unified_cache
;
2245 int cg_unified_controller(const char *controller
) {
2248 r
= cg_unified_cached(false);
2252 if (r
== CGROUP_UNIFIED_NONE
)
2255 if (r
>= CGROUP_UNIFIED_ALL
)
2258 return streq_ptr(controller
, SYSTEMD_CGROUP_CONTROLLER
);
2261 int cg_all_unified(void) {
2264 r
= cg_unified_cached(false);
2268 return r
>= CGROUP_UNIFIED_ALL
;
2271 int cg_hybrid_unified(void) {
2274 r
= cg_unified_cached(false);
2278 return r
== CGROUP_UNIFIED_SYSTEMD
&& !unified_systemd_v232
;
2281 int cg_is_delegated(const char *path
) {
2286 r
= cg_get_xattr_bool(path
, "trusted.delegate");
2287 if (!ERRNO_IS_NEG_XATTR_ABSENT(r
))
2290 /* If the trusted xattr isn't set (preferred), then check the untrusted one. Under the assumption
2291 * that whoever is trusted enough to own the cgroup, is also trusted enough to decide if it is
2292 * delegated or not this should be safe. */
2293 r
= cg_get_xattr_bool(path
, "user.delegate");
2294 return ERRNO_IS_NEG_XATTR_ABSENT(r
) ? false : r
;
2297 int cg_is_delegated_fd(int fd
) {
2302 r
= getxattr_at_bool(fd
, /* path= */ NULL
, "trusted.delegate", /* flags= */ 0);
2303 if (!ERRNO_IS_NEG_XATTR_ABSENT(r
))
2306 r
= getxattr_at_bool(fd
, /* path= */ NULL
, "user.delegate", /* flags= */ 0);
2307 return ERRNO_IS_NEG_XATTR_ABSENT(r
) ? false : r
;
2310 int cg_has_coredump_receive(const char *path
) {
2315 r
= cg_get_xattr_bool(path
, "user.coredump_receive");
2316 if (ERRNO_IS_NEG_XATTR_ABSENT(r
))
2322 const uint64_t cgroup_io_limit_defaults
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2323 [CGROUP_IO_RBPS_MAX
] = CGROUP_LIMIT_MAX
,
2324 [CGROUP_IO_WBPS_MAX
] = CGROUP_LIMIT_MAX
,
2325 [CGROUP_IO_RIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2326 [CGROUP_IO_WIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2329 static const char* const cgroup_io_limit_type_table
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2330 [CGROUP_IO_RBPS_MAX
] = "IOReadBandwidthMax",
2331 [CGROUP_IO_WBPS_MAX
] = "IOWriteBandwidthMax",
2332 [CGROUP_IO_RIOPS_MAX
] = "IOReadIOPSMax",
2333 [CGROUP_IO_WIOPS_MAX
] = "IOWriteIOPSMax",
2336 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type
, CGroupIOLimitType
);
2338 bool is_cgroup_fs(const struct statfs
*s
) {
2339 return is_fs_type(s
, CGROUP_SUPER_MAGIC
) ||
2340 is_fs_type(s
, CGROUP2_SUPER_MAGIC
);
2343 bool fd_is_cgroup_fs(int fd
) {
2346 if (fstatfs(fd
, &s
) < 0)
2349 return is_cgroup_fs(&s
);
2352 static const char *const cgroup_controller_table
[_CGROUP_CONTROLLER_MAX
] = {
2353 [CGROUP_CONTROLLER_CPU
] = "cpu",
2354 [CGROUP_CONTROLLER_CPUACCT
] = "cpuacct",
2355 [CGROUP_CONTROLLER_CPUSET
] = "cpuset",
2356 [CGROUP_CONTROLLER_IO
] = "io",
2357 [CGROUP_CONTROLLER_BLKIO
] = "blkio",
2358 [CGROUP_CONTROLLER_MEMORY
] = "memory",
2359 [CGROUP_CONTROLLER_DEVICES
] = "devices",
2360 [CGROUP_CONTROLLER_PIDS
] = "pids",
2361 [CGROUP_CONTROLLER_BPF_FIREWALL
] = "bpf-firewall",
2362 [CGROUP_CONTROLLER_BPF_DEVICES
] = "bpf-devices",
2363 [CGROUP_CONTROLLER_BPF_FOREIGN
] = "bpf-foreign",
2364 [CGROUP_CONTROLLER_BPF_SOCKET_BIND
] = "bpf-socket-bind",
2365 [CGROUP_CONTROLLER_BPF_RESTRICT_NETWORK_INTERFACES
] = "bpf-restrict-network-interfaces",
2368 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller
, CGroupController
);
2370 CGroupMask
get_cpu_accounting_mask(void) {
2371 static CGroupMask needed_mask
= (CGroupMask
) -1;
2373 /* On kernel ≥4.15 with unified hierarchy, cpu.stat's usage_usec is
2374 * provided externally from the CPU controller, which means we don't
2375 * need to enable the CPU controller just to get metrics. This is good,
2376 * because enabling the CPU controller comes at a minor performance
2377 * hit, especially when it's propagated deep into large hierarchies.
2378 * There's also no separate CPU accounting controller available within
2379 * a unified hierarchy.
2381 * This combination of factors results in the desired cgroup mask to
2382 * enable for CPU accounting varying as follows:
2384 * ╔═════════════════════╤═════════════════════╗
2385 * ║ Linux ≥4.15 │ Linux <4.15 ║
2386 * ╔═══════════════╬═════════════════════╪═════════════════════╣
2387 * ║ Unified ║ nothing │ CGROUP_MASK_CPU ║
2388 * ╟───────────────╫─────────────────────┼─────────────────────╢
2389 * ║ Hybrid/Legacy ║ CGROUP_MASK_CPUACCT │ CGROUP_MASK_CPUACCT ║
2390 * ╚═══════════════╩═════════════════════╧═════════════════════╝
2392 * We check kernel version here instead of manually checking whether
2393 * cpu.stat is present for every cgroup, as that check in itself would
2394 * already be fairly expensive.
2396 * Kernels where this patch has been backported will therefore have the
2397 * CPU controller enabled unnecessarily. This is more expensive than
2398 * necessary, but harmless. ☺️
2401 if (needed_mask
== (CGroupMask
) -1) {
2402 if (cg_all_unified()) {
2404 assert_se(uname(&u
) >= 0);
2406 if (strverscmp_improved(u
.release
, "4.15") < 0)
2407 needed_mask
= CGROUP_MASK_CPU
;
2411 needed_mask
= CGROUP_MASK_CPUACCT
;
2417 bool cpu_accounting_is_cheap(void) {
2418 return get_cpu_accounting_mask() == 0;
2421 static const char* const managed_oom_mode_table
[_MANAGED_OOM_MODE_MAX
] = {
2422 [MANAGED_OOM_AUTO
] = "auto",
2423 [MANAGED_OOM_KILL
] = "kill",
2426 DEFINE_STRING_TABLE_LOOKUP(managed_oom_mode
, ManagedOOMMode
);
2428 static const char* const managed_oom_preference_table
[_MANAGED_OOM_PREFERENCE_MAX
] = {
2429 [MANAGED_OOM_PREFERENCE_NONE
] = "none",
2430 [MANAGED_OOM_PREFERENCE_AVOID
] = "avoid",
2431 [MANAGED_OOM_PREFERENCE_OMIT
] = "omit",
2434 DEFINE_STRING_TABLE_LOOKUP(managed_oom_preference
, ManagedOOMPreference
);