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_fs.h"
26 #include "missing_magic.h"
27 #include "missing_threads.h"
29 #include "parse-util.h"
30 #include "path-util.h"
31 #include "process-util.h"
34 #include "stat-util.h"
35 #include "stdio-util.h"
36 #include "string-table.h"
37 #include "string-util.h"
39 #include "unit-name.h"
40 #include "user-util.h"
41 #include "xattr-util.h"
43 int cg_path_open(const char *controller
, const char *path
) {
44 _cleanup_free_
char *fs
= NULL
;
47 r
= cg_get_path(controller
, path
, /* item=*/ NULL
, &fs
);
51 return RET_NERRNO(open(fs
, O_DIRECTORY
|O_CLOEXEC
));
54 int cg_cgroupid_open(int cgroupfs_fd
, uint64_t id
) {
55 _cleanup_close_
int fsfd
= -EBADF
;
57 if (cgroupfs_fd
< 0) {
58 fsfd
= open("/sys/fs/cgroup", O_CLOEXEC
|O_DIRECTORY
);
65 cg_file_handle fh
= CG_FILE_HANDLE_INIT
;
66 CG_FILE_HANDLE_CGROUPID(fh
) = id
;
68 int fd
= open_by_handle_at(cgroupfs_fd
, &fh
.file_handle
, O_DIRECTORY
|O_CLOEXEC
);
75 static int cg_enumerate_items(const char *controller
, const char *path
, FILE **ret
, const char *item
) {
76 _cleanup_free_
char *fs
= NULL
;
82 r
= cg_get_path(controller
, path
, item
, &fs
);
94 int cg_enumerate_processes(const char *controller
, const char *path
, FILE **ret
) {
95 return cg_enumerate_items(controller
, path
, ret
, "cgroup.procs");
98 int cg_read_pid(FILE *f
, pid_t
*ret
, CGroupFlags flags
) {
101 /* Note that the cgroup.procs might contain duplicates! See cgroups.txt for details. */
108 if (fscanf(f
, "%lu", &ul
) != 1) {
115 return errno_or_else(EIO
);
121 /* In some circumstances (e.g. WSL), cgroups might contain unmappable PIDs from other
122 * contexts. These show up as zeros, and depending on the caller, can either be plain
123 * skipped over, or returned as-is. */
124 if (ul
== 0 && !FLAGS_SET(flags
, CGROUP_DONT_SKIP_UNMAPPED
))
132 int cg_read_pidref(FILE *f
, PidRef
*ret
, CGroupFlags flags
) {
141 r
= cg_read_pid(f
, &pid
, flags
);
152 r
= pidref_set_pid(ret
, pid
);
158 /* ESRCH → gone by now? just skip over it, read the next */
163 const char *controller
,
168 _cleanup_free_
char *events
= NULL
, *content
= NULL
;
171 r
= cg_get_path(controller
, path
, "cgroup.events", &events
);
175 r
= read_full_virtual_file(events
, &content
, NULL
);
179 for (const char *p
= content
;;) {
180 _cleanup_free_
char *line
= NULL
, *key
= NULL
;
183 r
= extract_first_word(&p
, &line
, "\n", 0);
190 r
= extract_first_word(&q
, &key
, " ", 0);
196 if (!streq(key
, event
))
199 return strdup_to(ret
, q
);
203 bool cg_ns_supported(void) {
204 static thread_local
int enabled
= -1;
209 if (access("/proc/self/ns/cgroup", F_OK
) < 0) {
211 log_debug_errno(errno
, "Failed to check whether /proc/self/ns/cgroup is available, assuming not: %m");
219 bool cg_freezer_supported(void) {
220 static thread_local
int supported
= -1;
225 supported
= cg_all_unified() > 0 && access("/sys/fs/cgroup/init.scope/cgroup.freeze", F_OK
) == 0;
230 bool cg_kill_supported(void) {
231 static thread_local
int supported
= -1;
236 if (cg_all_unified() <= 0)
238 else if (access("/sys/fs/cgroup/init.scope/cgroup.kill", F_OK
) < 0) {
240 log_debug_errno(errno
, "Failed to check if cgroup.kill is available, assuming not: %m");
248 int cg_enumerate_subgroups(const char *controller
, const char *path
, DIR **ret
) {
249 _cleanup_free_
char *fs
= NULL
;
255 /* This is not recursive! */
257 r
= cg_get_path(controller
, path
, NULL
, &fs
);
269 int cg_read_subgroup(DIR *d
, char **ret
) {
273 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
274 if (de
->d_type
!= DT_DIR
)
277 if (dot_or_dot_dot(de
->d_name
))
280 return strdup_to_full(ret
, de
->d_name
);
287 int cg_rmdir(const char *controller
, const char *path
) {
288 _cleanup_free_
char *p
= NULL
;
291 r
= cg_get_path(controller
, path
, NULL
, &p
);
296 if (r
< 0 && errno
!= ENOENT
)
299 r
= cg_hybrid_unified();
303 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
304 r
= cg_rmdir(SYSTEMD_CGROUP_CONTROLLER_LEGACY
, path
);
306 log_warning_errno(r
, "Failed to remove compat systemd cgroup %s: %m", path
);
312 static int cg_kill_items(
317 cg_kill_log_func_t log_kill
,
321 _cleanup_set_free_ Set
*allocated_set
= NULL
;
323 int r
, ret
= 0, ret_log_kill
= 0;
327 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
328 * SIGCONT on SIGKILL. */
329 if (IN_SET(sig
, SIGCONT
, SIGKILL
))
330 flags
&= ~CGROUP_SIGCONT
;
332 /* This goes through the tasks list and kills them all. This
333 * is repeated until no further processes are added to the
334 * tasks list, to properly handle forking processes */
337 s
= allocated_set
= set_new(NULL
);
343 _cleanup_fclose_
FILE *f
= NULL
;
346 r
= cg_enumerate_items(SYSTEMD_CGROUP_CONTROLLER
, path
, &f
, item
);
350 return RET_GATHER(ret
, r
);
353 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
355 r
= cg_read_pidref(f
, &pidref
, /* flags = */ 0);
357 return RET_GATHER(ret
, r
);
361 if ((flags
& CGROUP_IGNORE_SELF
) && pidref_is_self(&pidref
))
364 if (set_get(s
, PID_TO_PTR(pidref
.pid
)) == PID_TO_PTR(pidref
.pid
))
368 ret_log_kill
= log_kill(&pidref
, sig
, userdata
);
370 /* If we haven't killed this process yet, kill it */
371 r
= pidref_kill(&pidref
, sig
);
372 if (r
< 0 && r
!= -ESRCH
)
375 if (flags
& CGROUP_SIGCONT
)
376 (void) pidref_kill(&pidref
, SIGCONT
);
388 r
= set_put(s
, PID_TO_PTR(pidref
.pid
));
390 return RET_GATHER(ret
, r
);
393 /* To avoid racing against processes which fork quicker than we can kill them, we repeat this
394 * until no new pids need to be killed. */
406 cg_kill_log_func_t log_kill
,
411 r
= cg_kill_items(path
, sig
, flags
, s
, log_kill
, userdata
, "cgroup.procs");
412 if (r
< 0 || sig
!= SIGKILL
)
417 /* Only in case of killing with SIGKILL and when using cgroupsv2, kill remaining threads manually as
418 a workaround for kernel bug. It was fixed in 5.2-rc5 (c03cd7738a83), backported to 4.19.66
419 (4340d175b898) and 4.14.138 (feb6b123b7dd). */
420 r
= cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER
);
426 r
= cg_kill_items(path
, sig
, flags
, s
, log_kill
, userdata
, "cgroup.threads");
430 return r
> 0 || ret
> 0;
433 int cg_kill_kernel_sigkill(const char *path
) {
434 /* Kills the cgroup at `path` directly by writing to its cgroup.kill file. This sends SIGKILL to all
435 * processes in the cgroup and has the advantage of being completely atomic, unlike cg_kill_items(). */
437 _cleanup_free_
char *killfile
= NULL
;
442 if (!cg_kill_supported())
445 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, "cgroup.kill", &killfile
);
449 r
= write_string_file(killfile
, "1", WRITE_STRING_FILE_DISABLE_BUFFER
);
456 int cg_kill_recursive(
461 cg_kill_log_func_t log_kill
,
469 if (sig
== SIGKILL
&& cg_kill_supported() &&
470 !FLAGS_SET(flags
, CGROUP_IGNORE_SELF
) && !s
&& !log_kill
)
471 /* ignore CGROUP_SIGCONT, since this is a no-op alongside SIGKILL */
472 ret
= cg_kill_kernel_sigkill(path
);
474 _cleanup_set_free_ Set
*allocated_set
= NULL
;
475 _cleanup_closedir_
DIR *d
= NULL
;
478 s
= allocated_set
= set_new(NULL
);
483 ret
= cg_kill(path
, sig
, flags
, s
, log_kill
, userdata
);
485 r
= cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER
, path
, &d
);
494 _cleanup_free_
char *fn
= NULL
, *p
= NULL
;
496 r
= cg_read_subgroup(d
, &fn
);
504 p
= path_join(empty_to_root(path
), fn
);
508 r
= cg_kill_recursive(p
, sig
, flags
, s
, log_kill
, userdata
);
509 if (r
!= 0 && ret
>= 0)
514 if (FLAGS_SET(flags
, CGROUP_REMOVE
)) {
515 r
= cg_rmdir(SYSTEMD_CGROUP_CONTROLLER
, path
);
516 if (!IN_SET(r
, -ENOENT
, -EBUSY
))
523 static const char *controller_to_dirname(const char *controller
) {
526 /* Converts a controller name to the directory name below /sys/fs/cgroup/ we want to mount it
527 * to. Effectively, this just cuts off the name= prefixed used for named hierarchies, if it is
530 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
531 if (cg_hybrid_unified() > 0)
532 controller
= SYSTEMD_CGROUP_CONTROLLER_HYBRID
;
534 controller
= SYSTEMD_CGROUP_CONTROLLER_LEGACY
;
537 return startswith(controller
, "name=") ?: controller
;
540 static int join_path_legacy(const char *controller
, const char *path
, const char *suffix
, char **ret
) {
547 dn
= controller_to_dirname(controller
);
549 if (isempty(path
) && isempty(suffix
))
550 t
= path_join("/sys/fs/cgroup", dn
);
551 else if (isempty(path
))
552 t
= path_join("/sys/fs/cgroup", dn
, suffix
);
553 else if (isempty(suffix
))
554 t
= path_join("/sys/fs/cgroup", dn
, path
);
556 t
= path_join("/sys/fs/cgroup", dn
, path
, suffix
);
564 static int join_path_unified(const char *path
, const char *suffix
, char **ret
) {
569 if (isempty(path
) && isempty(suffix
))
570 t
= strdup("/sys/fs/cgroup");
571 else if (isempty(path
))
572 t
= path_join("/sys/fs/cgroup", suffix
);
573 else if (isempty(suffix
))
574 t
= path_join("/sys/fs/cgroup", path
);
576 t
= path_join("/sys/fs/cgroup", path
, suffix
);
584 int cg_get_path(const char *controller
, const char *path
, const char *suffix
, char **ret
) {
592 /* If no controller is specified, we return the path *below* the controllers, without any
595 if (isempty(path
) && isempty(suffix
))
600 else if (isempty(path
))
603 t
= path_join(path
, suffix
);
607 *ret
= path_simplify(t
);
611 if (!cg_controller_is_valid(controller
))
614 r
= cg_all_unified();
618 r
= join_path_unified(path
, suffix
, ret
);
620 r
= join_path_legacy(controller
, path
, suffix
, ret
);
628 static int controller_is_v1_accessible(const char *root
, const char *controller
) {
629 const char *cpath
, *dn
;
633 dn
= controller_to_dirname(controller
);
635 /* If root if specified, we check that:
636 * - possible subcgroup is created at root,
637 * - we can modify the hierarchy. */
639 cpath
= strjoina("/sys/fs/cgroup/", dn
, root
, root
? "/cgroup.procs" : NULL
);
640 return laccess(cpath
, root
? W_OK
: F_OK
);
643 int cg_get_path_and_check(const char *controller
, const char *path
, const char *suffix
, char **ret
) {
649 if (!cg_controller_is_valid(controller
))
652 r
= cg_all_unified();
656 /* In the unified hierarchy all controllers are considered accessible,
657 * except for the named hierarchies */
658 if (startswith(controller
, "name="))
661 /* Check if the specified controller is actually accessible */
662 r
= controller_is_v1_accessible(NULL
, controller
);
667 return cg_get_path(controller
, path
, suffix
, ret
);
670 int cg_set_xattr(const char *path
, const char *name
, const void *value
, size_t size
, int flags
) {
671 _cleanup_free_
char *fs
= NULL
;
676 assert(value
|| size
<= 0);
678 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, NULL
, &fs
);
682 return RET_NERRNO(setxattr(fs
, name
, value
, size
, flags
));
685 int cg_get_xattr(const char *path
, const char *name
, void *value
, size_t size
) {
686 _cleanup_free_
char *fs
= NULL
;
693 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, NULL
, &fs
);
697 n
= getxattr(fs
, name
, value
, size
);
704 int cg_get_xattr_malloc(const char *path
, const char *name
, char **ret
) {
705 _cleanup_free_
char *fs
= NULL
;
711 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, NULL
, &fs
);
715 return lgetxattr_malloc(fs
, name
, ret
);
718 int cg_get_xattr_bool(const char *path
, const char *name
) {
719 _cleanup_free_
char *fs
= NULL
;
725 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, NULL
, &fs
);
729 return getxattr_at_bool(AT_FDCWD
, fs
, name
, /* flags= */ 0);
732 int cg_remove_xattr(const char *path
, const char *name
) {
733 _cleanup_free_
char *fs
= NULL
;
739 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, NULL
, &fs
);
743 return RET_NERRNO(removexattr(fs
, name
));
746 int cg_pid_get_path(const char *controller
, pid_t pid
, char **ret_path
) {
747 _cleanup_fclose_
FILE *f
= NULL
;
748 const char *fs
, *controller_str
= NULL
; /* avoid false maybe-uninitialized warning */
755 if (!cg_controller_is_valid(controller
))
758 controller
= SYSTEMD_CGROUP_CONTROLLER
;
760 unified
= cg_unified_controller(controller
);
764 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
))
765 controller_str
= SYSTEMD_CGROUP_CONTROLLER_LEGACY
;
767 controller_str
= controller
;
770 fs
= procfs_file_alloca(pid
, "cgroup");
771 r
= fopen_unlocked(fs
, "re", &f
);
778 _cleanup_free_
char *line
= NULL
;
781 r
= read_line(f
, LONG_LINE_MAX
, &line
);
788 e
= startswith(line
, "0:");
798 l
= strchr(line
, ':');
808 assert(controller_str
);
809 r
= string_contains_word(l
, ",", controller_str
);
816 char *path
= strdup(e
+ 1);
820 /* Truncate suffix indicating the process is a zombie */
821 e
= endswith(path
, " (deleted)");
830 int cg_pidref_get_path(const char *controller
, const PidRef
*pidref
, char **ret_path
) {
831 _cleanup_free_
char *path
= NULL
;
836 if (!pidref_is_set(pidref
))
839 r
= cg_pid_get_path(controller
, pidref
->pid
, &path
);
843 /* Before we return the path, make sure the procfs entry for this pid still matches the pidref */
844 r
= pidref_verify(pidref
);
848 *ret_path
= TAKE_PTR(path
);
852 int cg_install_release_agent(const char *controller
, const char *agent
) {
853 _cleanup_free_
char *fs
= NULL
, *contents
= NULL
;
859 r
= cg_unified_controller(controller
);
862 if (r
> 0) /* doesn't apply to unified hierarchy */
865 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
869 r
= read_one_line_file(fs
, &contents
);
873 sc
= strstrip(contents
);
875 r
= write_string_file(fs
, agent
, WRITE_STRING_FILE_DISABLE_BUFFER
);
878 } else if (!path_equal(sc
, agent
))
882 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
886 contents
= mfree(contents
);
887 r
= read_one_line_file(fs
, &contents
);
891 sc
= strstrip(contents
);
892 if (streq(sc
, "0")) {
893 r
= write_string_file(fs
, "1", WRITE_STRING_FILE_DISABLE_BUFFER
);
906 int cg_uninstall_release_agent(const char *controller
) {
907 _cleanup_free_
char *fs
= NULL
;
910 r
= cg_unified_controller(controller
);
913 if (r
> 0) /* Doesn't apply to unified hierarchy */
916 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
920 r
= write_string_file(fs
, "0", WRITE_STRING_FILE_DISABLE_BUFFER
);
926 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
930 r
= write_string_file(fs
, "", WRITE_STRING_FILE_DISABLE_BUFFER
);
937 int cg_is_empty(const char *controller
, const char *path
) {
938 _cleanup_fclose_
FILE *f
= NULL
;
944 r
= cg_enumerate_processes(controller
, path
, &f
);
950 r
= cg_read_pid(f
, &pid
, CGROUP_DONT_SKIP_UNMAPPED
);
957 int cg_is_empty_recursive(const char *controller
, const char *path
) {
962 /* The root cgroup is always populated */
963 if (controller
&& empty_or_root(path
))
966 r
= cg_unified_controller(controller
);
970 _cleanup_free_
char *t
= NULL
;
972 /* On the unified hierarchy we can check empty state
973 * via the "populated" attribute of "cgroup.events". */
975 r
= cg_read_event(controller
, path
, "populated", &t
);
981 return streq(t
, "0");
983 _cleanup_closedir_
DIR *d
= NULL
;
986 r
= cg_is_empty(controller
, path
);
990 r
= cg_enumerate_subgroups(controller
, path
, &d
);
996 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
997 _cleanup_free_
char *p
= NULL
;
999 p
= path_join(path
, fn
);
1004 r
= cg_is_empty_recursive(controller
, p
);
1015 int cg_split_spec(const char *spec
, char **ret_controller
, char **ret_path
) {
1016 _cleanup_free_
char *controller
= NULL
, *path
= NULL
;
1022 if (!path_is_normalized(spec
))
1026 r
= path_simplify_alloc(spec
, &path
);
1034 e
= strchr(spec
, ':');
1036 controller
= strndup(spec
, e
-spec
);
1039 if (!cg_controller_is_valid(controller
))
1042 if (!isempty(e
+ 1)) {
1047 if (!path_is_normalized(path
) ||
1048 !path_is_absolute(path
))
1051 path_simplify(path
);
1055 if (!cg_controller_is_valid(spec
))
1058 if (ret_controller
) {
1059 controller
= strdup(spec
);
1067 *ret_controller
= TAKE_PTR(controller
);
1069 *ret_path
= TAKE_PTR(path
);
1073 int cg_mangle_path(const char *path
, char **ret
) {
1074 _cleanup_free_
char *c
= NULL
, *p
= NULL
;
1080 /* First, check if it already is a filesystem path */
1081 if (path_startswith(path
, "/sys/fs/cgroup"))
1082 return path_simplify_alloc(path
, ret
);
1084 /* Otherwise, treat it as cg spec */
1085 r
= cg_split_spec(path
, &c
, &p
);
1089 return cg_get_path(c
?: SYSTEMD_CGROUP_CONTROLLER
, p
?: "/", NULL
, ret
);
1092 int cg_get_root_path(char **ret_path
) {
1098 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 1, &p
);
1102 e
= endswith(p
, "/" SPECIAL_INIT_SCOPE
);
1104 e
= endswith(p
, "/" SPECIAL_SYSTEM_SLICE
); /* legacy */
1106 e
= endswith(p
, "/system"); /* even more legacy */
1114 int cg_shift_path(const char *cgroup
, const char *root
, const char **ret_shifted
) {
1115 _cleanup_free_
char *rt
= NULL
;
1120 assert(ret_shifted
);
1123 /* If the root was specified let's use that, otherwise
1124 * let's determine it from PID 1 */
1126 r
= cg_get_root_path(&rt
);
1133 p
= path_startswith(cgroup
, root
);
1134 if (p
&& p
> cgroup
)
1135 *ret_shifted
= p
- 1;
1137 *ret_shifted
= cgroup
;
1142 int cg_pid_get_path_shifted(pid_t pid
, const char *root
, char **ret_cgroup
) {
1143 _cleanup_free_
char *raw
= NULL
;
1150 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &raw
);
1154 r
= cg_shift_path(raw
, root
, &c
);
1159 *ret_cgroup
= TAKE_PTR(raw
);
1163 return strdup_to(ret_cgroup
, c
);
1166 int cg_path_decode_unit(const char *cgroup
, char **ret_unit
) {
1170 size_t n
= strcspn(cgroup
, "/");
1174 char *c
= strndupa_safe(cgroup
, n
);
1177 if (!unit_name_is_valid(c
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
1180 return strdup_to(ret_unit
, c
);
1183 static bool valid_slice_name(const char *p
, size_t n
) {
1188 if (n
< STRLEN("x.slice"))
1191 if (memcmp(p
+ n
- 6, ".slice", 6) == 0) {
1197 c
= cg_unescape(buf
);
1199 return unit_name_is_valid(c
, UNIT_NAME_PLAIN
);
1205 static const char *skip_slices(const char *p
) {
1208 /* Skips over all slice assignments */
1213 p
+= strspn(p
, "/");
1215 n
= strcspn(p
, "/");
1216 if (!valid_slice_name(p
, n
))
1223 int cg_path_get_unit(const char *path
, char **ret
) {
1224 _cleanup_free_
char *unit
= NULL
;
1231 e
= skip_slices(path
);
1233 r
= cg_path_decode_unit(e
, &unit
);
1237 /* We skipped over the slices, don't accept any now */
1238 if (endswith(unit
, ".slice"))
1241 *ret
= TAKE_PTR(unit
);
1245 int cg_path_get_unit_path(const char *path
, char **ret
) {
1246 _cleanup_free_
char *path_copy
= NULL
;
1252 path_copy
= strdup(path
);
1256 unit_name
= (char *)skip_slices(path_copy
);
1257 unit_name
[strcspn(unit_name
, "/")] = 0;
1259 if (!unit_name_is_valid(cg_unescape(unit_name
), UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
1262 *ret
= TAKE_PTR(path_copy
);
1267 int cg_pid_get_unit(pid_t pid
, char **ret_unit
) {
1268 _cleanup_free_
char *cgroup
= NULL
;
1273 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1277 return cg_path_get_unit(cgroup
, ret_unit
);
1280 int cg_pidref_get_unit(const PidRef
*pidref
, char **ret
) {
1281 _cleanup_free_
char *unit
= NULL
;
1286 if (!pidref_is_set(pidref
))
1289 r
= cg_pid_get_unit(pidref
->pid
, &unit
);
1293 r
= pidref_verify(pidref
);
1297 *ret
= TAKE_PTR(unit
);
1302 * Skip session-*.scope, but require it to be there.
1304 static const char *skip_session(const char *p
) {
1310 p
+= strspn(p
, "/");
1312 n
= strcspn(p
, "/");
1313 if (n
< STRLEN("session-x.scope"))
1316 if (memcmp(p
, "session-", 8) == 0 && memcmp(p
+ n
- 6, ".scope", 6) == 0) {
1317 char buf
[n
- 8 - 6 + 1];
1319 memcpy(buf
, p
+ 8, n
- 8 - 6);
1322 /* Note that session scopes never need unescaping,
1323 * since they cannot conflict with the kernel's own
1324 * names, hence we don't need to call cg_unescape()
1327 if (!session_id_valid(buf
))
1331 p
+= strspn(p
, "/");
1339 * Skip user@*.service, but require it to be there.
1341 static const char *skip_user_manager(const char *p
) {
1347 p
+= strspn(p
, "/");
1349 n
= strcspn(p
, "/");
1350 if (n
< STRLEN("user@x.service"))
1353 if (memcmp(p
, "user@", 5) == 0 && memcmp(p
+ n
- 8, ".service", 8) == 0) {
1354 char buf
[n
- 5 - 8 + 1];
1356 memcpy(buf
, p
+ 5, n
- 5 - 8);
1359 /* Note that user manager services never need unescaping,
1360 * since they cannot conflict with the kernel's own
1361 * names, hence we don't need to call cg_unescape()
1364 if (parse_uid(buf
, NULL
) < 0)
1368 p
+= strspn(p
, "/");
1376 static const char *skip_user_prefix(const char *path
) {
1381 /* Skip slices, if there are any */
1382 e
= skip_slices(path
);
1384 /* Skip the user manager, if it's in the path now... */
1385 t
= skip_user_manager(e
);
1389 /* Alternatively skip the user session if it is in the path... */
1390 return skip_session(e
);
1393 int cg_path_get_user_unit(const char *path
, char **ret
) {
1399 t
= skip_user_prefix(path
);
1403 /* And from here on it looks pretty much the same as for a system unit, hence let's use the same
1405 return cg_path_get_unit(t
, ret
);
1408 int cg_pid_get_user_unit(pid_t pid
, char **ret_unit
) {
1409 _cleanup_free_
char *cgroup
= NULL
;
1414 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1418 return cg_path_get_user_unit(cgroup
, ret_unit
);
1421 int cg_path_get_machine_name(const char *path
, char **ret_machine
) {
1422 _cleanup_free_
char *u
= NULL
;
1426 r
= cg_path_get_unit(path
, &u
);
1430 sl
= strjoina("/run/systemd/machines/unit:", u
);
1431 return readlink_malloc(sl
, ret_machine
);
1434 int cg_pid_get_machine_name(pid_t pid
, char **ret_machine
) {
1435 _cleanup_free_
char *cgroup
= NULL
;
1438 assert(ret_machine
);
1440 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1444 return cg_path_get_machine_name(cgroup
, ret_machine
);
1447 int cg_path_get_cgroupid(const char *path
, uint64_t *ret
) {
1448 cg_file_handle fh
= CG_FILE_HANDLE_INIT
;
1454 /* This is cgroupfs so we know the size of the handle, thus no need to loop around like
1455 * name_to_handle_at_loop() does in mountpoint-util.c */
1456 if (name_to_handle_at(AT_FDCWD
, path
, &fh
.file_handle
, &mnt_id
, 0) < 0)
1459 *ret
= CG_FILE_HANDLE_CGROUPID(fh
);
1463 int cg_fd_get_cgroupid(int fd
, uint64_t *ret
) {
1464 cg_file_handle fh
= CG_FILE_HANDLE_INIT
;
1470 if (name_to_handle_at(fd
, "", &fh
.file_handle
, &mnt_id
, AT_EMPTY_PATH
) < 0)
1473 *ret
= CG_FILE_HANDLE_CGROUPID(fh
);
1477 int cg_path_get_session(const char *path
, char **ret_session
) {
1478 _cleanup_free_
char *unit
= NULL
;
1484 r
= cg_path_get_unit(path
, &unit
);
1488 start
= startswith(unit
, "session-");
1491 end
= endswith(start
, ".scope");
1496 if (!session_id_valid(start
))
1502 return strdup_to(ret_session
, start
);
1505 int cg_pid_get_session(pid_t pid
, char **ret_session
) {
1506 _cleanup_free_
char *cgroup
= NULL
;
1509 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1513 return cg_path_get_session(cgroup
, ret_session
);
1516 int cg_path_get_owner_uid(const char *path
, uid_t
*ret_uid
) {
1517 _cleanup_free_
char *slice
= NULL
;
1523 r
= cg_path_get_slice(path
, &slice
);
1527 start
= startswith(slice
, "user-");
1531 end
= endswith(start
, ".slice");
1536 if (parse_uid(start
, ret_uid
) < 0)
1542 int cg_pid_get_owner_uid(pid_t pid
, uid_t
*ret_uid
) {
1543 _cleanup_free_
char *cgroup
= NULL
;
1546 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1550 return cg_path_get_owner_uid(cgroup
, ret_uid
);
1553 int cg_path_get_slice(const char *p
, char **ret_slice
) {
1554 const char *e
= NULL
;
1559 /* Finds the right-most slice unit from the beginning, but stops before we come to
1560 * the first non-slice unit. */
1566 n
= path_find_first_component(&p
, /* accept_dot_dot = */ false, &s
);
1569 if (!valid_slice_name(s
, n
))
1576 return cg_path_decode_unit(e
, ret_slice
);
1578 return strdup_to(ret_slice
, SPECIAL_ROOT_SLICE
);
1581 int cg_pid_get_slice(pid_t pid
, char **ret_slice
) {
1582 _cleanup_free_
char *cgroup
= NULL
;
1587 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1591 return cg_path_get_slice(cgroup
, ret_slice
);
1594 int cg_path_get_user_slice(const char *p
, char **ret_slice
) {
1599 t
= skip_user_prefix(p
);
1603 /* And now it looks pretty much the same as for a system slice, so let's just use the same parser
1605 return cg_path_get_slice(t
, ret_slice
);
1608 int cg_pid_get_user_slice(pid_t pid
, char **ret_slice
) {
1609 _cleanup_free_
char *cgroup
= NULL
;
1614 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1618 return cg_path_get_user_slice(cgroup
, ret_slice
);
1621 bool cg_needs_escape(const char *p
) {
1623 /* Checks if the specified path is a valid cgroup name by our rules, or if it must be escaped. Note
1624 * that we consider escaped cgroup names invalid here, as they need to be escaped a second time if
1625 * they shall be used. Also note that various names cannot be made valid by escaping even if we
1626 * return true here (because too long, or contain the forbidden character "/"). */
1628 if (!filename_is_valid(p
))
1631 if (IN_SET(p
[0], '_', '.'))
1634 if (STR_IN_SET(p
, "notify_on_release", "release_agent", "tasks"))
1637 if (startswith(p
, "cgroup."))
1640 for (CGroupController c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1643 q
= startswith(p
, cgroup_controller_to_string(c
));
1654 int cg_escape(const char *p
, char **ret
) {
1655 _cleanup_free_
char *n
= NULL
;
1657 /* This implements very minimal escaping for names to be used as file names in the cgroup tree: any
1658 * name which might conflict with a kernel name or is prefixed with '_' is prefixed with a '_'. That
1659 * way, when reading cgroup names it is sufficient to remove a single prefixing underscore if there
1662 /* The return value of this function (unlike cg_unescape()) needs free()! */
1664 if (cg_needs_escape(p
)) {
1665 n
= strjoin("_", p
);
1669 if (!filename_is_valid(n
)) /* became invalid due to the prefixing? Or contained things like a slash that cannot be fixed by prefixing? */
1681 char *cg_unescape(const char *p
) {
1684 /* The return value of this function (unlike cg_escape())
1685 * doesn't need free()! */
1693 #define CONTROLLER_VALID \
1697 bool cg_controller_is_valid(const char *p
) {
1703 if (streq(p
, SYSTEMD_CGROUP_CONTROLLER
))
1706 s
= startswith(p
, "name=");
1710 if (IN_SET(*p
, 0, '_'))
1713 for (t
= p
; *t
; t
++)
1714 if (!strchr(CONTROLLER_VALID
, *t
))
1717 if (t
- p
> NAME_MAX
)
1723 int cg_slice_to_path(const char *unit
, char **ret
) {
1724 _cleanup_free_
char *p
= NULL
, *s
= NULL
, *e
= NULL
;
1731 if (streq(unit
, SPECIAL_ROOT_SLICE
))
1732 return strdup_to(ret
, "");
1734 if (!unit_name_is_valid(unit
, UNIT_NAME_PLAIN
))
1737 if (!endswith(unit
, ".slice"))
1740 r
= unit_name_to_prefix(unit
, &p
);
1744 dash
= strchr(p
, '-');
1746 /* Don't allow initial dashes */
1751 _cleanup_free_
char *escaped
= NULL
;
1752 char n
[dash
- p
+ sizeof(".slice")];
1754 #if HAS_FEATURE_MEMORY_SANITIZER
1755 /* msan doesn't instrument stpncpy, so it thinks
1756 * n is later used uninitialized:
1757 * https://github.com/google/sanitizers/issues/926
1762 /* Don't allow trailing or double dashes */
1763 if (IN_SET(dash
[1], 0, '-'))
1766 strcpy(stpncpy(n
, p
, dash
- p
), ".slice");
1767 if (!unit_name_is_valid(n
, UNIT_NAME_PLAIN
))
1770 r
= cg_escape(n
, &escaped
);
1774 if (!strextend(&s
, escaped
, "/"))
1777 dash
= strchr(dash
+1, '-');
1780 r
= cg_escape(unit
, &e
);
1784 if (!strextend(&s
, e
))
1791 int cg_is_threaded(const char *path
) {
1792 _cleanup_free_
char *fs
= NULL
, *contents
= NULL
;
1793 _cleanup_strv_free_
char **v
= NULL
;
1796 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, "cgroup.type", &fs
);
1800 r
= read_full_virtual_file(fs
, &contents
, NULL
);
1802 return false; /* Assume no. */
1806 v
= strv_split(contents
, NULL
);
1810 /* If the cgroup is in the threaded mode, it contains "threaded".
1811 * If one of the parents or siblings is in the threaded mode, it may contain "invalid". */
1812 return strv_contains(v
, "threaded") || strv_contains(v
, "invalid");
1815 int cg_set_attribute(const char *controller
, const char *path
, const char *attribute
, const char *value
) {
1816 _cleanup_free_
char *p
= NULL
;
1819 r
= cg_get_path(controller
, path
, attribute
, &p
);
1823 return write_string_file(p
, value
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1826 int cg_get_attribute(const char *controller
, const char *path
, const char *attribute
, char **ret
) {
1827 _cleanup_free_
char *p
= NULL
;
1830 r
= cg_get_path(controller
, path
, attribute
, &p
);
1834 return read_one_line_file(p
, ret
);
1837 int cg_get_attribute_as_uint64(const char *controller
, const char *path
, const char *attribute
, uint64_t *ret
) {
1838 _cleanup_free_
char *value
= NULL
;
1844 r
= cg_get_attribute(controller
, path
, attribute
, &value
);
1850 if (streq(value
, "max")) {
1851 *ret
= CGROUP_LIMIT_MAX
;
1855 r
= safe_atou64(value
, &v
);
1863 int cg_get_attribute_as_bool(const char *controller
, const char *path
, const char *attribute
, bool *ret
) {
1864 _cleanup_free_
char *value
= NULL
;
1869 r
= cg_get_attribute(controller
, path
, attribute
, &value
);
1875 r
= parse_boolean(value
);
1883 int cg_get_owner(const char *path
, uid_t
*ret_uid
) {
1884 _cleanup_free_
char *f
= NULL
;
1890 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, path
, NULL
, &f
);
1894 if (stat(f
, &stats
) < 0)
1897 r
= stat_verify_directory(&stats
);
1901 *ret_uid
= stats
.st_uid
;
1905 int cg_get_keyed_attribute_full(
1906 const char *controller
,
1908 const char *attribute
,
1911 CGroupKeyMode mode
) {
1913 _cleanup_free_
char *filename
= NULL
, *contents
= NULL
;
1915 size_t n
, i
, n_done
= 0;
1919 /* Reads one or more fields of a cgroup v2 keyed attribute file. The 'keys' parameter should be an strv with
1920 * all keys to retrieve. The 'ret_values' parameter should be passed as string size with the same number of
1921 * entries as 'keys'. On success each entry will be set to the value of the matching key.
1923 * If the attribute file doesn't exist at all returns ENOENT, if any key is not found returns ENXIO. If mode
1924 * is set to GG_KEY_MODE_GRACEFUL we ignore missing keys and return those that were parsed successfully. */
1926 r
= cg_get_path(controller
, path
, attribute
, &filename
);
1930 r
= read_full_file(filename
, &contents
, NULL
);
1934 n
= strv_length(keys
);
1935 if (n
== 0) /* No keys to retrieve? That's easy, we are done then */
1938 /* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
1939 v
= newa0(char*, n
);
1941 for (p
= contents
; *p
;) {
1942 const char *w
= NULL
;
1944 for (i
= 0; i
< n
; i
++)
1946 w
= first_word(p
, keys
[i
]);
1954 l
= strcspn(w
, NEWLINE
);
1955 v
[i
] = strndup(w
, l
);
1967 p
+= strcspn(p
, NEWLINE
);
1969 p
+= strspn(p
, NEWLINE
);
1972 if (mode
& CG_KEY_MODE_GRACEFUL
)
1978 free_many_charp(v
, n
);
1982 memcpy(ret_values
, v
, sizeof(char*) * n
);
1983 if (mode
& CG_KEY_MODE_GRACEFUL
)
1989 int cg_mask_to_string(CGroupMask mask
, char **ret
) {
1990 _cleanup_free_
char *s
= NULL
;
2002 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2006 if (!FLAGS_SET(mask
, CGROUP_CONTROLLER_TO_MASK(c
)))
2009 k
= cgroup_controller_to_string(c
);
2012 if (!GREEDY_REALLOC(s
, n
+ space
+ l
+ 1))
2017 memcpy(s
+ n
+ space
, k
, l
);
2031 int cg_mask_from_string(const char *value
, CGroupMask
*ret
) {
2038 _cleanup_free_
char *n
= NULL
;
2042 r
= extract_first_word(&value
, &n
, NULL
, 0);
2048 v
= cgroup_controller_from_string(n
);
2052 m
|= CGROUP_CONTROLLER_TO_MASK(v
);
2059 int cg_mask_supported_subtree(const char *root
, CGroupMask
*ret
) {
2063 /* Determines the mask of supported cgroup controllers. Only includes controllers we can make sense of and that
2064 * are actually accessible. Only covers real controllers, i.e. not the CGROUP_CONTROLLER_BPF_xyz
2065 * pseudo-controllers. */
2067 r
= cg_all_unified();
2071 _cleanup_free_
char *controllers
= NULL
, *path
= NULL
;
2073 /* In the unified hierarchy we can read the supported and accessible controllers from
2074 * the top-level cgroup attribute */
2076 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, root
, "cgroup.controllers", &path
);
2080 r
= read_one_line_file(path
, &controllers
);
2084 r
= cg_mask_from_string(controllers
, &mask
);
2088 /* Mask controllers that are not supported in unified hierarchy. */
2089 mask
&= CGROUP_MASK_V2
;
2094 /* In the legacy hierarchy, we check which hierarchies are accessible. */
2097 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
2098 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
2101 if (!FLAGS_SET(CGROUP_MASK_V1
, bit
))
2104 n
= cgroup_controller_to_string(c
);
2105 if (controller_is_v1_accessible(root
, n
) >= 0)
2114 int cg_mask_supported(CGroupMask
*ret
) {
2115 _cleanup_free_
char *root
= NULL
;
2118 r
= cg_get_root_path(&root
);
2122 return cg_mask_supported_subtree(root
, ret
);
2125 int cg_kernel_controllers(Set
**ret
) {
2126 _cleanup_set_free_ Set
*controllers
= NULL
;
2127 _cleanup_fclose_
FILE *f
= NULL
;
2132 /* Determines the full list of kernel-known controllers. Might include controllers we don't actually support
2133 * and controllers that aren't currently accessible (because not mounted). This does not include "name="
2134 * pseudo-controllers. */
2136 r
= fopen_unlocked("/proc/cgroups", "re", &f
);
2144 /* Ignore the header line */
2145 (void) read_line(f
, SIZE_MAX
, NULL
);
2148 _cleanup_free_
char *controller
= NULL
;
2151 if (fscanf(f
, "%ms %*i %*i %i", &controller
, &enabled
) != 2) {
2165 if (!cg_controller_is_valid(controller
))
2168 r
= set_ensure_consume(&controllers
, &string_hash_ops_free
, TAKE_PTR(controller
));
2173 *ret
= TAKE_PTR(controllers
);
2178 /* The hybrid mode was initially implemented in v232 and simply mounted cgroup2 on
2179 * /sys/fs/cgroup/systemd. This unfortunately broke other tools (such as docker) which expected the v1
2180 * "name=systemd" hierarchy on /sys/fs/cgroup/systemd. From v233 and on, the hybrid mode mounts v2 on
2181 * /sys/fs/cgroup/unified and maintains "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility
2184 * To keep live upgrade working, we detect and support v232 layout. When v232 layout is detected, to keep
2185 * cgroup v2 process management but disable the compat dual layout, we return true on
2186 * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and false on cg_hybrid_unified().
2188 static thread_local
bool unified_systemd_v232
;
2190 int cg_unified_cached(bool flush
) {
2191 static thread_local CGroupUnified unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
2195 /* Checks if we support the unified hierarchy. Returns an
2196 * error when the cgroup hierarchies aren't mounted yet or we
2197 * have any other trouble determining if the unified hierarchy
2201 unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
2202 else if (unified_cache
>= CGROUP_UNIFIED_NONE
)
2203 return unified_cache
;
2205 if (statfs("/sys/fs/cgroup/", &fs
) < 0)
2206 return log_debug_errno(errno
, "statfs(\"/sys/fs/cgroup/\") failed: %m");
2208 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
2209 log_debug("Found cgroup2 on /sys/fs/cgroup/, full unified hierarchy");
2210 unified_cache
= CGROUP_UNIFIED_ALL
;
2211 } else if (F_TYPE_EQUAL(fs
.f_type
, TMPFS_MAGIC
)) {
2212 if (statfs("/sys/fs/cgroup/unified/", &fs
) == 0 &&
2213 F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
2214 log_debug("Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller");
2215 unified_cache
= CGROUP_UNIFIED_SYSTEMD
;
2216 unified_systemd_v232
= false;
2218 if (statfs("/sys/fs/cgroup/systemd/", &fs
) < 0) {
2219 if (errno
== ENOENT
) {
2220 /* Some other software may have set up /sys/fs/cgroup in a configuration we do not recognize. */
2221 log_debug_errno(errno
, "Unsupported cgroupsv1 setup detected: name=systemd hierarchy not found.");
2224 return log_debug_errno(errno
, "statfs(\"/sys/fs/cgroup/systemd\" failed: %m");
2227 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
2228 log_debug("Found cgroup2 on /sys/fs/cgroup/systemd, unified hierarchy for systemd controller (v232 variant)");
2229 unified_cache
= CGROUP_UNIFIED_SYSTEMD
;
2230 unified_systemd_v232
= true;
2231 } else if (F_TYPE_EQUAL(fs
.f_type
, CGROUP_SUPER_MAGIC
)) {
2232 log_debug("Found cgroup on /sys/fs/cgroup/systemd, legacy hierarchy");
2233 unified_cache
= CGROUP_UNIFIED_NONE
;
2235 log_debug("Unexpected filesystem type %llx mounted on /sys/fs/cgroup/systemd, assuming legacy hierarchy",
2236 (unsigned long long) fs
.f_type
);
2237 unified_cache
= CGROUP_UNIFIED_NONE
;
2240 } else if (F_TYPE_EQUAL(fs
.f_type
, SYSFS_MAGIC
)) {
2241 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
2242 "No filesystem is currently mounted on /sys/fs/cgroup.");
2244 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
2245 "Unknown filesystem type %llx mounted on /sys/fs/cgroup.",
2246 (unsigned long long)fs
.f_type
);
2248 return unified_cache
;
2251 int cg_unified_controller(const char *controller
) {
2254 r
= cg_unified_cached(false);
2258 if (r
== CGROUP_UNIFIED_NONE
)
2261 if (r
>= CGROUP_UNIFIED_ALL
)
2264 return streq_ptr(controller
, SYSTEMD_CGROUP_CONTROLLER
);
2267 int cg_all_unified(void) {
2270 r
= cg_unified_cached(false);
2274 return r
>= CGROUP_UNIFIED_ALL
;
2277 int cg_hybrid_unified(void) {
2280 r
= cg_unified_cached(false);
2284 return r
== CGROUP_UNIFIED_SYSTEMD
&& !unified_systemd_v232
;
2287 int cg_is_delegated(const char *path
) {
2292 r
= cg_get_xattr_bool(path
, "trusted.delegate");
2293 if (!ERRNO_IS_NEG_XATTR_ABSENT(r
))
2296 /* If the trusted xattr isn't set (preferred), then check the untrusted one. Under the assumption
2297 * that whoever is trusted enough to own the cgroup, is also trusted enough to decide if it is
2298 * delegated or not this should be safe. */
2299 r
= cg_get_xattr_bool(path
, "user.delegate");
2300 return ERRNO_IS_NEG_XATTR_ABSENT(r
) ? false : r
;
2303 int cg_is_delegated_fd(int fd
) {
2308 r
= getxattr_at_bool(fd
, /* path= */ NULL
, "trusted.delegate", /* flags= */ 0);
2309 if (!ERRNO_IS_NEG_XATTR_ABSENT(r
))
2312 r
= getxattr_at_bool(fd
, /* path= */ NULL
, "user.delegate", /* flags= */ 0);
2313 return ERRNO_IS_NEG_XATTR_ABSENT(r
) ? false : r
;
2316 int cg_has_coredump_receive(const char *path
) {
2321 r
= cg_get_xattr_bool(path
, "user.coredump_receive");
2322 if (ERRNO_IS_NEG_XATTR_ABSENT(r
))
2328 const uint64_t cgroup_io_limit_defaults
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2329 [CGROUP_IO_RBPS_MAX
] = CGROUP_LIMIT_MAX
,
2330 [CGROUP_IO_WBPS_MAX
] = CGROUP_LIMIT_MAX
,
2331 [CGROUP_IO_RIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2332 [CGROUP_IO_WIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2335 static const char* const cgroup_io_limit_type_table
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2336 [CGROUP_IO_RBPS_MAX
] = "IOReadBandwidthMax",
2337 [CGROUP_IO_WBPS_MAX
] = "IOWriteBandwidthMax",
2338 [CGROUP_IO_RIOPS_MAX
] = "IOReadIOPSMax",
2339 [CGROUP_IO_WIOPS_MAX
] = "IOWriteIOPSMax",
2342 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type
, CGroupIOLimitType
);
2344 bool is_cgroup_fs(const struct statfs
*s
) {
2345 return is_fs_type(s
, CGROUP_SUPER_MAGIC
) ||
2346 is_fs_type(s
, CGROUP2_SUPER_MAGIC
);
2349 bool fd_is_cgroup_fs(int fd
) {
2352 if (fstatfs(fd
, &s
) < 0)
2355 return is_cgroup_fs(&s
);
2358 static const char *const cgroup_controller_table
[_CGROUP_CONTROLLER_MAX
] = {
2359 [CGROUP_CONTROLLER_CPU
] = "cpu",
2360 [CGROUP_CONTROLLER_CPUACCT
] = "cpuacct",
2361 [CGROUP_CONTROLLER_CPUSET
] = "cpuset",
2362 [CGROUP_CONTROLLER_IO
] = "io",
2363 [CGROUP_CONTROLLER_BLKIO
] = "blkio",
2364 [CGROUP_CONTROLLER_MEMORY
] = "memory",
2365 [CGROUP_CONTROLLER_DEVICES
] = "devices",
2366 [CGROUP_CONTROLLER_PIDS
] = "pids",
2367 [CGROUP_CONTROLLER_BPF_FIREWALL
] = "bpf-firewall",
2368 [CGROUP_CONTROLLER_BPF_DEVICES
] = "bpf-devices",
2369 [CGROUP_CONTROLLER_BPF_FOREIGN
] = "bpf-foreign",
2370 [CGROUP_CONTROLLER_BPF_SOCKET_BIND
] = "bpf-socket-bind",
2371 [CGROUP_CONTROLLER_BPF_RESTRICT_NETWORK_INTERFACES
] = "bpf-restrict-network-interfaces",
2374 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller
, CGroupController
);
2376 CGroupMask
get_cpu_accounting_mask(void) {
2377 static CGroupMask needed_mask
= (CGroupMask
) -1;
2379 /* On kernel ≥4.15 with unified hierarchy, cpu.stat's usage_usec is
2380 * provided externally from the CPU controller, which means we don't
2381 * need to enable the CPU controller just to get metrics. This is good,
2382 * because enabling the CPU controller comes at a minor performance
2383 * hit, especially when it's propagated deep into large hierarchies.
2384 * There's also no separate CPU accounting controller available within
2385 * a unified hierarchy.
2387 * This combination of factors results in the desired cgroup mask to
2388 * enable for CPU accounting varying as follows:
2390 * ╔═════════════════════╤═════════════════════╗
2391 * ║ Linux ≥4.15 │ Linux <4.15 ║
2392 * ╔═══════════════╬═════════════════════╪═════════════════════╣
2393 * ║ Unified ║ nothing │ CGROUP_MASK_CPU ║
2394 * ╟───────────────╫─────────────────────┼─────────────────────╢
2395 * ║ Hybrid/Legacy ║ CGROUP_MASK_CPUACCT │ CGROUP_MASK_CPUACCT ║
2396 * ╚═══════════════╩═════════════════════╧═════════════════════╝
2398 * We check kernel version here instead of manually checking whether
2399 * cpu.stat is present for every cgroup, as that check in itself would
2400 * already be fairly expensive.
2402 * Kernels where this patch has been backported will therefore have the
2403 * CPU controller enabled unnecessarily. This is more expensive than
2404 * necessary, but harmless. ☺️
2407 if (needed_mask
== (CGroupMask
) -1) {
2408 if (cg_all_unified()) {
2410 assert_se(uname(&u
) >= 0);
2412 if (strverscmp_improved(u
.release
, "4.15") < 0)
2413 needed_mask
= CGROUP_MASK_CPU
;
2417 needed_mask
= CGROUP_MASK_CPUACCT
;
2423 bool cpu_accounting_is_cheap(void) {
2424 return get_cpu_accounting_mask() == 0;
2427 static const char* const managed_oom_mode_table
[_MANAGED_OOM_MODE_MAX
] = {
2428 [MANAGED_OOM_AUTO
] = "auto",
2429 [MANAGED_OOM_KILL
] = "kill",
2432 DEFINE_STRING_TABLE_LOOKUP(managed_oom_mode
, ManagedOOMMode
);
2434 static const char* const managed_oom_preference_table
[_MANAGED_OOM_PREFERENCE_MAX
] = {
2435 [MANAGED_OOM_PREFERENCE_NONE
] = "none",
2436 [MANAGED_OOM_PREFERENCE_AVOID
] = "avoid",
2437 [MANAGED_OOM_PREFERENCE_OMIT
] = "omit",
2440 DEFINE_STRING_TABLE_LOOKUP(managed_oom_preference
, ManagedOOMPreference
);