1 /* SPDX-License-Identifier: LGPL-2.1+ */
10 #include <sys/utsname.h>
11 #include <sys/xattr.h>
14 #include "alloc-util.h"
15 #include "cgroup-util.h"
17 #include "dirent-util.h"
18 #include "extract-word.h"
21 #include "format-util.h"
24 #include "login-util.h"
26 #include "missing_magic.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 **_f
, 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 **_f
) {
62 return cg_enumerate_items(controller
, path
, _f
, "cgroup.procs");
65 int cg_read_pid(FILE *f
, pid_t
*_pid
) {
68 /* Note that the cgroup.procs might contain duplicates! See
69 * cgroups.txt for details. */
75 if (fscanf(f
, "%lu", &ul
) != 1) {
80 return errno_or_else(EIO
);
91 const char *controller
,
96 _cleanup_free_
char *events
= NULL
, *content
= NULL
;
99 r
= cg_get_path(controller
, path
, "cgroup.events", &events
);
103 r
= read_full_file(events
, &content
, NULL
);
107 for (const char *p
= content
;;) {
108 _cleanup_free_
char *line
= NULL
, *key
= NULL
, *val
= NULL
;
111 r
= extract_first_word(&p
, &line
, "\n", 0);
118 r
= extract_first_word(&q
, &key
, " ", 0);
124 if (!streq(key
, event
))
131 *ret
= TAKE_PTR(val
);
136 bool cg_ns_supported(void) {
137 static thread_local
int enabled
= -1;
142 if (access("/proc/self/ns/cgroup", F_OK
) < 0) {
144 log_debug_errno(errno
, "Failed to check whether /proc/self/ns/cgroup is available, assuming not: %m");
152 bool cg_freezer_supported(void) {
153 static thread_local
int supported
= -1;
158 supported
= cg_all_unified() > 0 && access("/sys/fs/cgroup/init.scope/cgroup.freeze", F_OK
) == 0;
163 int cg_enumerate_subgroups(const char *controller
, const char *path
, DIR **_d
) {
164 _cleanup_free_
char *fs
= NULL
;
170 /* This is not recursive! */
172 r
= cg_get_path(controller
, path
, NULL
, &fs
);
184 int cg_read_subgroup(DIR *d
, char **fn
) {
190 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
193 if (de
->d_type
!= DT_DIR
)
196 if (dot_or_dot_dot(de
->d_name
))
199 b
= strdup(de
->d_name
);
210 int cg_rmdir(const char *controller
, const char *path
) {
211 _cleanup_free_
char *p
= NULL
;
214 r
= cg_get_path(controller
, path
, NULL
, &p
);
219 if (r
< 0 && errno
!= ENOENT
)
222 r
= cg_hybrid_unified();
226 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
227 r
= cg_rmdir(SYSTEMD_CGROUP_CONTROLLER_LEGACY
, path
);
229 log_warning_errno(r
, "Failed to remove compat systemd cgroup %s: %m", path
);
235 static int cg_kill_items(
236 const char *controller
,
241 cg_kill_log_func_t log_kill
,
245 _cleanup_set_free_ Set
*allocated_set
= NULL
;
247 int r
, ret
= 0, ret_log_kill
= 0;
252 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
253 * SIGCONT on SIGKILL. */
254 if (IN_SET(sig
, SIGCONT
, SIGKILL
))
255 flags
&= ~CGROUP_SIGCONT
;
257 /* This goes through the tasks list and kills them all. This
258 * is repeated until no further processes are added to the
259 * tasks list, to properly handle forking processes */
262 s
= allocated_set
= set_new(NULL
);
267 my_pid
= getpid_cached();
270 _cleanup_fclose_
FILE *f
= NULL
;
274 r
= cg_enumerate_items(controller
, path
, &f
, item
);
276 if (ret
>= 0 && r
!= -ENOENT
)
282 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
284 if ((flags
& CGROUP_IGNORE_SELF
) && pid
== my_pid
)
287 if (set_get(s
, PID_TO_PTR(pid
)) == PID_TO_PTR(pid
))
291 ret_log_kill
= log_kill(pid
, sig
, userdata
);
293 /* If we haven't killed this process yet, kill
295 if (kill(pid
, sig
) < 0) {
296 if (ret
>= 0 && errno
!= ESRCH
)
299 if (flags
& CGROUP_SIGCONT
)
300 (void) kill(pid
, SIGCONT
);
312 r
= set_put(s
, PID_TO_PTR(pid
));
328 /* To avoid racing against processes which fork
329 * quicker than we can kill them we repeat this until
330 * no new pids need to be killed. */
338 const char *controller
,
343 cg_kill_log_func_t log_kill
,
347 r
= cg_kill_items(controller
, path
, sig
, flags
, s
, log_kill
, userdata
, "cgroup.procs");
348 if (r
< 0 || sig
!= SIGKILL
)
351 /* Only in case of killing with SIGKILL and when using cgroupsv2, kill remaining threads manually as
352 a workaround for kernel bug. It was fixed in 5.2-rc5 (c03cd7738a83), backported to 4.19.66
353 (4340d175b898) and 4.14.138 (feb6b123b7dd). */
354 r
= cg_unified_controller(controller
);
358 return cg_kill_items(controller
, path
, sig
, flags
, s
, log_kill
, userdata
, "cgroup.threads");
361 int cg_kill_recursive(
362 const char *controller
,
367 cg_kill_log_func_t log_kill
,
370 _cleanup_set_free_ Set
*allocated_set
= NULL
;
371 _cleanup_closedir_
DIR *d
= NULL
;
379 s
= allocated_set
= set_new(NULL
);
384 ret
= cg_kill(controller
, path
, sig
, flags
, s
, log_kill
, userdata
);
386 r
= cg_enumerate_subgroups(controller
, path
, &d
);
388 if (ret
>= 0 && r
!= -ENOENT
)
394 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
395 _cleanup_free_
char *p
= NULL
;
397 p
= path_join(empty_to_root(path
), fn
);
402 r
= cg_kill_recursive(controller
, p
, sig
, flags
, s
, log_kill
, userdata
);
403 if (r
!= 0 && ret
>= 0)
406 if (ret
>= 0 && r
< 0)
409 if (flags
& CGROUP_REMOVE
) {
410 r
= cg_rmdir(controller
, path
);
411 if (r
< 0 && ret
>= 0 && !IN_SET(r
, -ENOENT
, -EBUSY
))
418 static const char *controller_to_dirname(const char *controller
) {
423 /* Converts a controller name to the directory name below
424 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
425 * just cuts off the name= prefixed used for named
426 * hierarchies, if it is specified. */
428 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
429 if (cg_hybrid_unified() > 0)
430 controller
= SYSTEMD_CGROUP_CONTROLLER_HYBRID
;
432 controller
= SYSTEMD_CGROUP_CONTROLLER_LEGACY
;
435 e
= startswith(controller
, "name=");
442 static int join_path_legacy(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
449 dn
= controller_to_dirname(controller
);
451 if (isempty(path
) && isempty(suffix
))
452 t
= path_join("/sys/fs/cgroup", dn
);
453 else if (isempty(path
))
454 t
= path_join("/sys/fs/cgroup", dn
, suffix
);
455 else if (isempty(suffix
))
456 t
= path_join("/sys/fs/cgroup", dn
, path
);
458 t
= path_join("/sys/fs/cgroup", dn
, path
, suffix
);
466 static int join_path_unified(const char *path
, const char *suffix
, char **fs
) {
471 if (isempty(path
) && isempty(suffix
))
472 t
= strdup("/sys/fs/cgroup");
473 else if (isempty(path
))
474 t
= path_join("/sys/fs/cgroup", suffix
);
475 else if (isempty(suffix
))
476 t
= path_join("/sys/fs/cgroup", path
);
478 t
= path_join("/sys/fs/cgroup", path
, suffix
);
486 int cg_get_path(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
494 /* If no controller is specified, we return the path
495 * *below* the controllers, without any prefix. */
497 if (!path
&& !suffix
)
505 t
= path_join(path
, suffix
);
509 *fs
= path_simplify(t
, false);
513 if (!cg_controller_is_valid(controller
))
516 r
= cg_all_unified();
520 r
= join_path_unified(path
, suffix
, fs
);
522 r
= join_path_legacy(controller
, path
, suffix
, fs
);
526 path_simplify(*fs
, false);
530 static int controller_is_accessible(const char *controller
) {
535 /* Checks whether a specific controller is accessible,
536 * i.e. its hierarchy mounted. In the unified hierarchy all
537 * controllers are considered accessible, except for the named
540 if (!cg_controller_is_valid(controller
))
543 r
= cg_all_unified();
547 /* We don't support named hierarchies if we are using
548 * the unified hierarchy. */
550 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
))
553 if (startswith(controller
, "name="))
559 dn
= controller_to_dirname(controller
);
560 cc
= strjoina("/sys/fs/cgroup/", dn
);
562 if (laccess(cc
, F_OK
) < 0)
569 int cg_get_path_and_check(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
575 /* Check if the specified controller is actually accessible */
576 r
= controller_is_accessible(controller
);
580 return cg_get_path(controller
, path
, suffix
, fs
);
583 int cg_set_xattr(const char *controller
, const char *path
, const char *name
, const void *value
, size_t size
, int flags
) {
584 _cleanup_free_
char *fs
= NULL
;
589 assert(value
|| size
<= 0);
591 r
= cg_get_path(controller
, path
, NULL
, &fs
);
595 if (setxattr(fs
, name
, value
, size
, flags
) < 0)
601 int cg_get_xattr(const char *controller
, const char *path
, const char *name
, void *value
, size_t size
) {
602 _cleanup_free_
char *fs
= NULL
;
609 r
= cg_get_path(controller
, path
, NULL
, &fs
);
613 n
= getxattr(fs
, name
, value
, size
);
620 int cg_get_xattr_malloc(const char *controller
, const char *path
, const char *name
, char **ret
) {
621 _cleanup_free_
char *fs
= NULL
;
627 r
= cg_get_path(controller
, path
, NULL
, &fs
);
631 r
= getxattr_malloc(fs
, name
, ret
, false);
638 int cg_remove_xattr(const char *controller
, const char *path
, const char *name
) {
639 _cleanup_free_
char *fs
= NULL
;
645 r
= cg_get_path(controller
, path
, NULL
, &fs
);
649 if (removexattr(fs
, name
) < 0)
655 int cg_pid_get_path(const char *controller
, pid_t pid
, char **ret_path
) {
656 _cleanup_fclose_
FILE *f
= NULL
;
657 const char *fs
, *controller_str
;
664 if (!cg_controller_is_valid(controller
))
667 controller
= SYSTEMD_CGROUP_CONTROLLER
;
669 unified
= cg_unified_controller(controller
);
673 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
))
674 controller_str
= SYSTEMD_CGROUP_CONTROLLER_LEGACY
;
676 controller_str
= controller
;
679 fs
= procfs_file_alloca(pid
, "cgroup");
680 r
= fopen_unlocked(fs
, "re", &f
);
687 _cleanup_free_
char *line
= NULL
;
690 r
= read_line(f
, LONG_LINE_MAX
, &line
);
697 e
= startswith(line
, "0:");
707 l
= strchr(line
, ':');
717 r
= string_contains_word(l
, ",", controller_str
);
724 char *path
= strdup(e
+ 1);
728 /* Truncate suffix indicating the process is a zombie */
729 e
= endswith(path
, " (deleted)");
738 int cg_install_release_agent(const char *controller
, const char *agent
) {
739 _cleanup_free_
char *fs
= NULL
, *contents
= NULL
;
745 r
= cg_unified_controller(controller
);
748 if (r
> 0) /* doesn't apply to unified hierarchy */
751 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
755 r
= read_one_line_file(fs
, &contents
);
759 sc
= strstrip(contents
);
761 r
= write_string_file(fs
, agent
, WRITE_STRING_FILE_DISABLE_BUFFER
);
764 } else if (!path_equal(sc
, agent
))
768 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
772 contents
= mfree(contents
);
773 r
= read_one_line_file(fs
, &contents
);
777 sc
= strstrip(contents
);
778 if (streq(sc
, "0")) {
779 r
= write_string_file(fs
, "1", WRITE_STRING_FILE_DISABLE_BUFFER
);
792 int cg_uninstall_release_agent(const char *controller
) {
793 _cleanup_free_
char *fs
= NULL
;
796 r
= cg_unified_controller(controller
);
799 if (r
> 0) /* Doesn't apply to unified hierarchy */
802 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
806 r
= write_string_file(fs
, "0", WRITE_STRING_FILE_DISABLE_BUFFER
);
812 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
816 r
= write_string_file(fs
, "", WRITE_STRING_FILE_DISABLE_BUFFER
);
823 int cg_is_empty(const char *controller
, const char *path
) {
824 _cleanup_fclose_
FILE *f
= NULL
;
830 r
= cg_enumerate_processes(controller
, path
, &f
);
836 r
= cg_read_pid(f
, &pid
);
843 int cg_is_empty_recursive(const char *controller
, const char *path
) {
848 /* The root cgroup is always populated */
849 if (controller
&& empty_or_root(path
))
852 r
= cg_unified_controller(controller
);
856 _cleanup_free_
char *t
= NULL
;
858 /* On the unified hierarchy we can check empty state
859 * via the "populated" attribute of "cgroup.events". */
861 r
= cg_read_event(controller
, path
, "populated", &t
);
867 return streq(t
, "0");
869 _cleanup_closedir_
DIR *d
= NULL
;
872 r
= cg_is_empty(controller
, path
);
876 r
= cg_enumerate_subgroups(controller
, path
, &d
);
882 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
883 _cleanup_free_
char *p
= NULL
;
885 p
= path_join(path
, fn
);
890 r
= cg_is_empty_recursive(controller
, p
);
901 int cg_split_spec(const char *spec
, char **ret_controller
, char **ret_path
) {
902 _cleanup_free_
char *controller
= NULL
, *path
= NULL
;
907 if (!path_is_normalized(spec
))
915 path_simplify(path
, false);
921 e
= strchr(spec
, ':');
923 controller
= strndup(spec
, e
-spec
);
926 if (!cg_controller_is_valid(controller
))
929 if (!isempty(e
+ 1)) {
934 if (!path_is_normalized(path
) ||
935 !path_is_absolute(path
))
938 path_simplify(path
, false);
942 if (!cg_controller_is_valid(spec
))
945 if (ret_controller
) {
946 controller
= strdup(spec
);
954 *ret_controller
= TAKE_PTR(controller
);
956 *ret_path
= TAKE_PTR(path
);
960 int cg_mangle_path(const char *path
, char **result
) {
961 _cleanup_free_
char *c
= NULL
, *p
= NULL
;
968 /* First, check if it already is a filesystem path */
969 if (path_startswith(path
, "/sys/fs/cgroup")) {
975 *result
= path_simplify(t
, false);
979 /* Otherwise, treat it as cg spec */
980 r
= cg_split_spec(path
, &c
, &p
);
984 return cg_get_path(c
?: SYSTEMD_CGROUP_CONTROLLER
, p
?: "/", NULL
, result
);
987 int cg_get_root_path(char **path
) {
993 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 1, &p
);
997 e
= endswith(p
, "/" SPECIAL_INIT_SCOPE
);
999 e
= endswith(p
, "/" SPECIAL_SYSTEM_SLICE
); /* legacy */
1001 e
= endswith(p
, "/system"); /* even more legacy */
1009 int cg_shift_path(const char *cgroup
, const char *root
, const char **shifted
) {
1010 _cleanup_free_
char *rt
= NULL
;
1018 /* If the root was specified let's use that, otherwise
1019 * let's determine it from PID 1 */
1021 r
= cg_get_root_path(&rt
);
1028 p
= path_startswith(cgroup
, root
);
1029 if (p
&& p
> cgroup
)
1037 int cg_pid_get_path_shifted(pid_t pid
, const char *root
, char **cgroup
) {
1038 _cleanup_free_
char *raw
= NULL
;
1045 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &raw
);
1049 r
= cg_shift_path(raw
, root
, &c
);
1054 *cgroup
= TAKE_PTR(raw
);
1068 int cg_path_decode_unit(const char *cgroup
, char **unit
) {
1075 n
= strcspn(cgroup
, "/");
1079 c
= strndupa(cgroup
, n
);
1082 if (!unit_name_is_valid(c
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
1093 static bool valid_slice_name(const char *p
, size_t n
) {
1098 if (n
< STRLEN("x.slice"))
1101 if (memcmp(p
+ n
- 6, ".slice", 6) == 0) {
1107 c
= cg_unescape(buf
);
1109 return unit_name_is_valid(c
, UNIT_NAME_PLAIN
);
1115 static const char *skip_slices(const char *p
) {
1118 /* Skips over all slice assignments */
1123 p
+= strspn(p
, "/");
1125 n
= strcspn(p
, "/");
1126 if (!valid_slice_name(p
, n
))
1133 int cg_path_get_unit(const char *path
, char **ret
) {
1141 e
= skip_slices(path
);
1143 r
= cg_path_decode_unit(e
, &unit
);
1147 /* We skipped over the slices, don't accept any now */
1148 if (endswith(unit
, ".slice")) {
1157 int cg_pid_get_unit(pid_t pid
, char **unit
) {
1158 _cleanup_free_
char *cgroup
= NULL
;
1163 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1167 return cg_path_get_unit(cgroup
, unit
);
1171 * Skip session-*.scope, but require it to be there.
1173 static const char *skip_session(const char *p
) {
1179 p
+= strspn(p
, "/");
1181 n
= strcspn(p
, "/");
1182 if (n
< STRLEN("session-x.scope"))
1185 if (memcmp(p
, "session-", 8) == 0 && memcmp(p
+ n
- 6, ".scope", 6) == 0) {
1186 char buf
[n
- 8 - 6 + 1];
1188 memcpy(buf
, p
+ 8, n
- 8 - 6);
1191 /* Note that session scopes never need unescaping,
1192 * since they cannot conflict with the kernel's own
1193 * names, hence we don't need to call cg_unescape()
1196 if (!session_id_valid(buf
))
1200 p
+= strspn(p
, "/");
1208 * Skip user@*.service, but require it to be there.
1210 static const char *skip_user_manager(const char *p
) {
1216 p
+= strspn(p
, "/");
1218 n
= strcspn(p
, "/");
1219 if (n
< STRLEN("user@x.service"))
1222 if (memcmp(p
, "user@", 5) == 0 && memcmp(p
+ n
- 8, ".service", 8) == 0) {
1223 char buf
[n
- 5 - 8 + 1];
1225 memcpy(buf
, p
+ 5, n
- 5 - 8);
1228 /* Note that user manager services never need unescaping,
1229 * since they cannot conflict with the kernel's own
1230 * names, hence we don't need to call cg_unescape()
1233 if (parse_uid(buf
, NULL
) < 0)
1237 p
+= strspn(p
, "/");
1245 static const char *skip_user_prefix(const char *path
) {
1250 /* Skip slices, if there are any */
1251 e
= skip_slices(path
);
1253 /* Skip the user manager, if it's in the path now... */
1254 t
= skip_user_manager(e
);
1258 /* Alternatively skip the user session if it is in the path... */
1259 return skip_session(e
);
1262 int cg_path_get_user_unit(const char *path
, char **ret
) {
1268 t
= skip_user_prefix(path
);
1272 /* And from here on it looks pretty much the same as for a system unit, hence let's use the same
1274 return cg_path_get_unit(t
, ret
);
1277 int cg_pid_get_user_unit(pid_t pid
, char **unit
) {
1278 _cleanup_free_
char *cgroup
= NULL
;
1283 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1287 return cg_path_get_user_unit(cgroup
, unit
);
1290 int cg_path_get_machine_name(const char *path
, char **machine
) {
1291 _cleanup_free_
char *u
= NULL
;
1295 r
= cg_path_get_unit(path
, &u
);
1299 sl
= strjoina("/run/systemd/machines/unit:", u
);
1300 return readlink_malloc(sl
, machine
);
1303 int cg_pid_get_machine_name(pid_t pid
, char **machine
) {
1304 _cleanup_free_
char *cgroup
= NULL
;
1309 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1313 return cg_path_get_machine_name(cgroup
, machine
);
1316 int cg_path_get_session(const char *path
, char **session
) {
1317 _cleanup_free_
char *unit
= NULL
;
1323 r
= cg_path_get_unit(path
, &unit
);
1327 start
= startswith(unit
, "session-");
1330 end
= endswith(start
, ".scope");
1335 if (!session_id_valid(start
))
1351 int cg_pid_get_session(pid_t pid
, char **session
) {
1352 _cleanup_free_
char *cgroup
= NULL
;
1355 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1359 return cg_path_get_session(cgroup
, session
);
1362 int cg_path_get_owner_uid(const char *path
, uid_t
*uid
) {
1363 _cleanup_free_
char *slice
= NULL
;
1369 r
= cg_path_get_slice(path
, &slice
);
1373 start
= startswith(slice
, "user-");
1376 end
= endswith(start
, ".slice");
1381 if (parse_uid(start
, uid
) < 0)
1387 int cg_pid_get_owner_uid(pid_t pid
, uid_t
*uid
) {
1388 _cleanup_free_
char *cgroup
= NULL
;
1391 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1395 return cg_path_get_owner_uid(cgroup
, uid
);
1398 int cg_path_get_slice(const char *p
, char **slice
) {
1399 const char *e
= NULL
;
1404 /* Finds the right-most slice unit from the beginning, but
1405 * stops before we come to the first non-slice unit. */
1410 p
+= strspn(p
, "/");
1412 n
= strcspn(p
, "/");
1413 if (!valid_slice_name(p
, n
)) {
1418 s
= strdup(SPECIAL_ROOT_SLICE
);
1426 return cg_path_decode_unit(e
, slice
);
1434 int cg_pid_get_slice(pid_t pid
, char **slice
) {
1435 _cleanup_free_
char *cgroup
= NULL
;
1440 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1444 return cg_path_get_slice(cgroup
, slice
);
1447 int cg_path_get_user_slice(const char *p
, char **slice
) {
1452 t
= skip_user_prefix(p
);
1456 /* And now it looks pretty much the same as for a system
1457 * slice, so let's just use the same parser from here on. */
1458 return cg_path_get_slice(t
, slice
);
1461 int cg_pid_get_user_slice(pid_t pid
, char **slice
) {
1462 _cleanup_free_
char *cgroup
= NULL
;
1467 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1471 return cg_path_get_user_slice(cgroup
, slice
);
1474 char *cg_escape(const char *p
) {
1475 bool need_prefix
= false;
1477 /* This implements very minimal escaping for names to be used
1478 * as file names in the cgroup tree: any name which might
1479 * conflict with a kernel name or is prefixed with '_' is
1480 * prefixed with a '_'. That way, when reading cgroup names it
1481 * is sufficient to remove a single prefixing underscore if
1484 /* The return value of this function (unlike cg_unescape())
1487 if (IN_SET(p
[0], 0, '_', '.') ||
1488 STR_IN_SET(p
, "notify_on_release", "release_agent", "tasks") ||
1489 startswith(p
, "cgroup."))
1494 dot
= strrchr(p
, '.');
1499 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1502 n
= cgroup_controller_to_string(c
);
1507 if (memcmp(p
, n
, l
) != 0)
1517 return strjoin("_", p
);
1522 char *cg_unescape(const char *p
) {
1525 /* The return value of this function (unlike cg_escape())
1526 * doesn't need free()! */
1534 #define CONTROLLER_VALID \
1538 bool cg_controller_is_valid(const char *p
) {
1544 if (streq(p
, SYSTEMD_CGROUP_CONTROLLER
))
1547 s
= startswith(p
, "name=");
1551 if (IN_SET(*p
, 0, '_'))
1554 for (t
= p
; *t
; t
++)
1555 if (!strchr(CONTROLLER_VALID
, *t
))
1558 if (t
- p
> FILENAME_MAX
)
1564 int cg_slice_to_path(const char *unit
, char **ret
) {
1565 _cleanup_free_
char *p
= NULL
, *s
= NULL
, *e
= NULL
;
1572 if (streq(unit
, SPECIAL_ROOT_SLICE
)) {
1582 if (!unit_name_is_valid(unit
, UNIT_NAME_PLAIN
))
1585 if (!endswith(unit
, ".slice"))
1588 r
= unit_name_to_prefix(unit
, &p
);
1592 dash
= strchr(p
, '-');
1594 /* Don't allow initial dashes */
1599 _cleanup_free_
char *escaped
= NULL
;
1600 char n
[dash
- p
+ sizeof(".slice")];
1602 #if HAS_FEATURE_MEMORY_SANITIZER
1603 /* msan doesn't instrument stpncpy, so it thinks
1604 * n is later used uninitialized:
1605 * https://github.com/google/sanitizers/issues/926
1610 /* Don't allow trailing or double dashes */
1611 if (IN_SET(dash
[1], 0, '-'))
1614 strcpy(stpncpy(n
, p
, dash
- p
), ".slice");
1615 if (!unit_name_is_valid(n
, UNIT_NAME_PLAIN
))
1618 escaped
= cg_escape(n
);
1622 if (!strextend(&s
, escaped
, "/", NULL
))
1625 dash
= strchr(dash
+1, '-');
1628 e
= cg_escape(unit
);
1632 if (!strextend(&s
, e
, NULL
))
1640 int cg_set_attribute(const char *controller
, const char *path
, const char *attribute
, const char *value
) {
1641 _cleanup_free_
char *p
= NULL
;
1644 r
= cg_get_path(controller
, path
, attribute
, &p
);
1648 return write_string_file(p
, value
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1651 int cg_get_attribute(const char *controller
, const char *path
, const char *attribute
, char **ret
) {
1652 _cleanup_free_
char *p
= NULL
;
1655 r
= cg_get_path(controller
, path
, attribute
, &p
);
1659 return read_one_line_file(p
, ret
);
1662 int cg_get_attribute_as_uint64(const char *controller
, const char *path
, const char *attribute
, uint64_t *ret
) {
1663 _cleanup_free_
char *value
= NULL
;
1669 r
= cg_get_attribute(controller
, path
, attribute
, &value
);
1675 if (streq(value
, "max")) {
1676 *ret
= CGROUP_LIMIT_MAX
;
1680 r
= safe_atou64(value
, &v
);
1688 int cg_get_keyed_attribute_full(
1689 const char *controller
,
1691 const char *attribute
,
1694 CGroupKeyMode mode
) {
1696 _cleanup_free_
char *filename
= NULL
, *contents
= NULL
;
1698 size_t n
, i
, n_done
= 0;
1702 /* Reads one or more fields of a cgroup v2 keyed attribute file. The 'keys' parameter should be an strv with
1703 * all keys to retrieve. The 'ret_values' parameter should be passed as string size with the same number of
1704 * entries as 'keys'. On success each entry will be set to the value of the matching key.
1706 * If the attribute file doesn't exist at all returns ENOENT, if any key is not found returns ENXIO. If mode
1707 * is set to GG_KEY_MODE_GRACEFUL we ignore missing keys and return those that were parsed successfully. */
1709 r
= cg_get_path(controller
, path
, attribute
, &filename
);
1713 r
= read_full_file(filename
, &contents
, NULL
);
1717 n
= strv_length(keys
);
1718 if (n
== 0) /* No keys to retrieve? That's easy, we are done then */
1721 /* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
1722 v
= newa0(char*, n
);
1724 for (p
= contents
; *p
;) {
1725 const char *w
= NULL
;
1727 for (i
= 0; i
< n
; i
++)
1729 w
= first_word(p
, keys
[i
]);
1737 l
= strcspn(w
, NEWLINE
);
1738 v
[i
] = strndup(w
, l
);
1750 p
+= strcspn(p
, NEWLINE
);
1752 p
+= strspn(p
, NEWLINE
);
1755 if (mode
& CG_KEY_MODE_GRACEFUL
)
1761 for (i
= 0; i
< n
; i
++)
1767 memcpy(ret_values
, v
, sizeof(char*) * n
);
1768 if (mode
& CG_KEY_MODE_GRACEFUL
)
1774 int cg_mask_to_string(CGroupMask mask
, char **ret
) {
1775 _cleanup_free_
char *s
= NULL
;
1776 size_t n
= 0, allocated
= 0;
1787 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1791 if (!FLAGS_SET(mask
, CGROUP_CONTROLLER_TO_MASK(c
)))
1794 k
= cgroup_controller_to_string(c
);
1797 if (!GREEDY_REALLOC(s
, allocated
, n
+ space
+ l
+ 1))
1802 memcpy(s
+ n
+ space
, k
, l
);
1816 int cg_mask_from_string(const char *value
, CGroupMask
*ret
) {
1823 _cleanup_free_
char *n
= NULL
;
1827 r
= extract_first_word(&value
, &n
, NULL
, 0);
1833 v
= cgroup_controller_from_string(n
);
1837 m
|= CGROUP_CONTROLLER_TO_MASK(v
);
1844 int cg_mask_supported(CGroupMask
*ret
) {
1848 /* Determines the mask of supported cgroup controllers. Only includes controllers we can make sense of and that
1849 * are actually accessible. Only covers real controllers, i.e. not the CGROUP_CONTROLLER_BPF_xyz
1850 * pseudo-controllers. */
1852 r
= cg_all_unified();
1856 _cleanup_free_
char *root
= NULL
, *controllers
= NULL
, *path
= NULL
;
1858 /* In the unified hierarchy we can read the supported
1859 * and accessible controllers from a the top-level
1860 * cgroup attribute */
1862 r
= cg_get_root_path(&root
);
1866 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, root
, "cgroup.controllers", &path
);
1870 r
= read_one_line_file(path
, &controllers
);
1874 r
= cg_mask_from_string(controllers
, &mask
);
1878 /* Mask controllers that are not supported in unified hierarchy. */
1879 mask
&= CGROUP_MASK_V2
;
1884 /* In the legacy hierarchy, we check which hierarchies are mounted. */
1887 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1888 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1891 if (!FLAGS_SET(CGROUP_MASK_V1
, bit
))
1894 n
= cgroup_controller_to_string(c
);
1895 if (controller_is_accessible(n
) >= 0)
1904 int cg_kernel_controllers(Set
**ret
) {
1905 _cleanup_set_free_free_ Set
*controllers
= NULL
;
1906 _cleanup_fclose_
FILE *f
= NULL
;
1911 /* Determines the full list of kernel-known controllers. Might include controllers we don't actually support
1912 * and controllers that aren't currently accessible (because not mounted). This does not include "name="
1913 * pseudo-controllers. */
1915 controllers
= set_new(&string_hash_ops
);
1919 r
= fopen_unlocked("/proc/cgroups", "re", &f
);
1927 /* Ignore the header line */
1928 (void) read_line(f
, (size_t) -1, NULL
);
1935 if (fscanf(f
, "%ms %*i %*i %i", &controller
, &enabled
) != 2) {
1941 return errno_or_else(EIO
);
1951 if (!cg_controller_is_valid(controller
)) {
1956 r
= set_consume(controllers
, controller
);
1961 *ret
= TAKE_PTR(controllers
);
1966 /* The hybrid mode was initially implemented in v232 and simply mounted cgroup2 on
1967 * /sys/fs/cgroup/systemd. This unfortunately broke other tools (such as docker) which expected the v1
1968 * "name=systemd" hierarchy on /sys/fs/cgroup/systemd. From v233 and on, the hybrid mode mounts v2 on
1969 * /sys/fs/cgroup/unified and maintains "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility
1972 * To keep live upgrade working, we detect and support v232 layout. When v232 layout is detected, to keep
1973 * cgroup v2 process management but disable the compat dual layout, we return true on
1974 * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and false on cg_hybrid_unified().
1976 static thread_local
bool unified_systemd_v232
;
1978 int cg_unified_cached(bool flush
) {
1979 static thread_local CGroupUnified unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
1983 /* Checks if we support the unified hierarchy. Returns an
1984 * error when the cgroup hierarchies aren't mounted yet or we
1985 * have any other trouble determining if the unified hierarchy
1989 unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
1990 else if (unified_cache
>= CGROUP_UNIFIED_NONE
)
1991 return unified_cache
;
1993 if (statfs("/sys/fs/cgroup/", &fs
) < 0)
1994 return log_debug_errno(errno
, "statfs(\"/sys/fs/cgroup/\") failed: %m");
1996 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
1997 log_debug("Found cgroup2 on /sys/fs/cgroup/, full unified hierarchy");
1998 unified_cache
= CGROUP_UNIFIED_ALL
;
1999 } else if (F_TYPE_EQUAL(fs
.f_type
, TMPFS_MAGIC
)) {
2000 if (statfs("/sys/fs/cgroup/unified/", &fs
) == 0 &&
2001 F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
2002 log_debug("Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller");
2003 unified_cache
= CGROUP_UNIFIED_SYSTEMD
;
2004 unified_systemd_v232
= false;
2006 if (statfs("/sys/fs/cgroup/systemd/", &fs
) < 0)
2007 return log_debug_errno(errno
, "statfs(\"/sys/fs/cgroup/systemd\" failed: %m");
2009 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
2010 log_debug("Found cgroup2 on /sys/fs/cgroup/systemd, unified hierarchy for systemd controller (v232 variant)");
2011 unified_cache
= CGROUP_UNIFIED_SYSTEMD
;
2012 unified_systemd_v232
= true;
2013 } else if (F_TYPE_EQUAL(fs
.f_type
, CGROUP_SUPER_MAGIC
)) {
2014 log_debug("Found cgroup on /sys/fs/cgroup/systemd, legacy hierarchy");
2015 unified_cache
= CGROUP_UNIFIED_NONE
;
2017 log_debug("Unexpected filesystem type %llx mounted on /sys/fs/cgroup/systemd, assuming legacy hierarchy",
2018 (unsigned long long) fs
.f_type
);
2019 unified_cache
= CGROUP_UNIFIED_NONE
;
2022 } else if (F_TYPE_EQUAL(fs
.f_type
, SYSFS_MAGIC
)) {
2023 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
2024 "No filesystem is currently mounted on /sys/fs/cgroup.");
2026 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
2027 "Unknown filesystem type %llx mounted on /sys/fs/cgroup.",
2028 (unsigned long long)fs
.f_type
);
2030 return unified_cache
;
2033 int cg_unified_controller(const char *controller
) {
2036 r
= cg_unified_cached(false);
2040 if (r
== CGROUP_UNIFIED_NONE
)
2043 if (r
>= CGROUP_UNIFIED_ALL
)
2046 return streq_ptr(controller
, SYSTEMD_CGROUP_CONTROLLER
);
2049 int cg_all_unified(void) {
2052 r
= cg_unified_cached(false);
2056 return r
>= CGROUP_UNIFIED_ALL
;
2059 int cg_hybrid_unified(void) {
2062 r
= cg_unified_cached(false);
2066 return r
== CGROUP_UNIFIED_SYSTEMD
&& !unified_systemd_v232
;
2069 const uint64_t cgroup_io_limit_defaults
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2070 [CGROUP_IO_RBPS_MAX
] = CGROUP_LIMIT_MAX
,
2071 [CGROUP_IO_WBPS_MAX
] = CGROUP_LIMIT_MAX
,
2072 [CGROUP_IO_RIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2073 [CGROUP_IO_WIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2076 static const char* const cgroup_io_limit_type_table
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2077 [CGROUP_IO_RBPS_MAX
] = "IOReadBandwidthMax",
2078 [CGROUP_IO_WBPS_MAX
] = "IOWriteBandwidthMax",
2079 [CGROUP_IO_RIOPS_MAX
] = "IOReadIOPSMax",
2080 [CGROUP_IO_WIOPS_MAX
] = "IOWriteIOPSMax",
2083 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type
, CGroupIOLimitType
);
2085 bool is_cgroup_fs(const struct statfs
*s
) {
2086 return is_fs_type(s
, CGROUP_SUPER_MAGIC
) ||
2087 is_fs_type(s
, CGROUP2_SUPER_MAGIC
);
2090 bool fd_is_cgroup_fs(int fd
) {
2093 if (fstatfs(fd
, &s
) < 0)
2096 return is_cgroup_fs(&s
);
2099 static const char *const cgroup_controller_table
[_CGROUP_CONTROLLER_MAX
] = {
2100 [CGROUP_CONTROLLER_CPU
] = "cpu",
2101 [CGROUP_CONTROLLER_CPUACCT
] = "cpuacct",
2102 [CGROUP_CONTROLLER_CPUSET
] = "cpuset",
2103 [CGROUP_CONTROLLER_IO
] = "io",
2104 [CGROUP_CONTROLLER_BLKIO
] = "blkio",
2105 [CGROUP_CONTROLLER_MEMORY
] = "memory",
2106 [CGROUP_CONTROLLER_DEVICES
] = "devices",
2107 [CGROUP_CONTROLLER_PIDS
] = "pids",
2108 [CGROUP_CONTROLLER_BPF_FIREWALL
] = "bpf-firewall",
2109 [CGROUP_CONTROLLER_BPF_DEVICES
] = "bpf-devices",
2112 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller
, CGroupController
);
2114 CGroupMask
get_cpu_accounting_mask(void) {
2115 static CGroupMask needed_mask
= (CGroupMask
) -1;
2117 /* On kernel ≥4.15 with unified hierarchy, cpu.stat's usage_usec is
2118 * provided externally from the CPU controller, which means we don't
2119 * need to enable the CPU controller just to get metrics. This is good,
2120 * because enabling the CPU controller comes at a minor performance
2121 * hit, especially when it's propagated deep into large hierarchies.
2122 * There's also no separate CPU accounting controller available within
2123 * a unified hierarchy.
2125 * This combination of factors results in the desired cgroup mask to
2126 * enable for CPU accounting varying as follows:
2128 * ╔═════════════════════╤═════════════════════╗
2129 * ║ Linux ≥4.15 │ Linux <4.15 ║
2130 * ╔═══════════════╬═════════════════════╪═════════════════════╣
2131 * ║ Unified ║ nothing │ CGROUP_MASK_CPU ║
2132 * ╟───────────────╫─────────────────────┼─────────────────────╢
2133 * ║ Hybrid/Legacy ║ CGROUP_MASK_CPUACCT │ CGROUP_MASK_CPUACCT ║
2134 * ╚═══════════════╩═════════════════════╧═════════════════════╝
2136 * We check kernel version here instead of manually checking whether
2137 * cpu.stat is present for every cgroup, as that check in itself would
2138 * already be fairly expensive.
2140 * Kernels where this patch has been backported will therefore have the
2141 * CPU controller enabled unnecessarily. This is more expensive than
2142 * necessary, but harmless. ☺️
2145 if (needed_mask
== (CGroupMask
) -1) {
2146 if (cg_all_unified()) {
2148 assert_se(uname(&u
) >= 0);
2150 if (str_verscmp(u
.release
, "4.15") < 0)
2151 needed_mask
= CGROUP_MASK_CPU
;
2155 needed_mask
= CGROUP_MASK_CPUACCT
;
2161 bool cpu_accounting_is_cheap(void) {
2162 return get_cpu_accounting_mask() == 0;
2165 static const char* const managed_oom_mode_table
[_MANAGED_OOM_MODE_MAX
] = {
2166 [MANAGED_OOM_AUTO
] = "auto",
2167 [MANAGED_OOM_KILL
] = "kill",
2170 DEFINE_STRING_TABLE_LOOKUP(managed_oom_mode
, ManagedOOMMode
);