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"
41 static int cg_enumerate_items(const char *controller
, const char *path
, FILE **_f
, const char *item
) {
42 _cleanup_free_
char *fs
= NULL
;
48 r
= cg_get_path(controller
, path
, item
, &fs
);
60 int cg_enumerate_processes(const char *controller
, const char *path
, FILE **_f
) {
61 return cg_enumerate_items(controller
, path
, _f
, "cgroup.procs");
64 int cg_read_pid(FILE *f
, pid_t
*_pid
) {
67 /* Note that the cgroup.procs might contain duplicates! See
68 * cgroups.txt for details. */
74 if (fscanf(f
, "%lu", &ul
) != 1) {
79 return errno_or_else(EIO
);
90 const char *controller
,
95 _cleanup_free_
char *events
= NULL
, *content
= NULL
;
98 r
= cg_get_path(controller
, path
, "cgroup.events", &events
);
102 r
= read_full_file(events
, &content
, NULL
);
106 for (const char *p
= content
;;) {
107 _cleanup_free_
char *line
= NULL
, *key
= NULL
, *val
= NULL
;
110 r
= extract_first_word(&p
, &line
, "\n", 0);
117 r
= extract_first_word(&q
, &key
, " ", 0);
123 if (!streq(key
, event
))
130 *ret
= TAKE_PTR(val
);
135 bool cg_ns_supported(void) {
136 static thread_local
int enabled
= -1;
141 if (access("/proc/self/ns/cgroup", F_OK
) < 0) {
143 log_debug_errno(errno
, "Failed to check whether /proc/self/ns/cgroup is available, assuming not: %m");
151 int cg_enumerate_subgroups(const char *controller
, const char *path
, DIR **_d
) {
152 _cleanup_free_
char *fs
= NULL
;
158 /* This is not recursive! */
160 r
= cg_get_path(controller
, path
, NULL
, &fs
);
172 int cg_read_subgroup(DIR *d
, char **fn
) {
178 FOREACH_DIRENT_ALL(de
, d
, return -errno
) {
181 if (de
->d_type
!= DT_DIR
)
184 if (dot_or_dot_dot(de
->d_name
))
187 b
= strdup(de
->d_name
);
198 int cg_rmdir(const char *controller
, const char *path
) {
199 _cleanup_free_
char *p
= NULL
;
202 r
= cg_get_path(controller
, path
, NULL
, &p
);
207 if (r
< 0 && errno
!= ENOENT
)
210 r
= cg_hybrid_unified();
214 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
215 r
= cg_rmdir(SYSTEMD_CGROUP_CONTROLLER_LEGACY
, path
);
217 log_warning_errno(r
, "Failed to remove compat systemd cgroup %s: %m", path
);
223 static int cg_kill_items(
224 const char *controller
,
229 cg_kill_log_func_t log_kill
,
233 _cleanup_set_free_ Set
*allocated_set
= NULL
;
235 int r
, ret
= 0, ret_log_kill
= 0;
240 /* Don't send SIGCONT twice. Also, SIGKILL always works even when process is suspended, hence don't send
241 * SIGCONT on SIGKILL. */
242 if (IN_SET(sig
, SIGCONT
, SIGKILL
))
243 flags
&= ~CGROUP_SIGCONT
;
245 /* This goes through the tasks list and kills them all. This
246 * is repeated until no further processes are added to the
247 * tasks list, to properly handle forking processes */
250 s
= allocated_set
= set_new(NULL
);
255 my_pid
= getpid_cached();
258 _cleanup_fclose_
FILE *f
= NULL
;
262 r
= cg_enumerate_items(controller
, path
, &f
, item
);
264 if (ret
>= 0 && r
!= -ENOENT
)
270 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
272 if ((flags
& CGROUP_IGNORE_SELF
) && pid
== my_pid
)
275 if (set_get(s
, PID_TO_PTR(pid
)) == PID_TO_PTR(pid
))
279 ret_log_kill
= log_kill(pid
, sig
, userdata
);
281 /* If we haven't killed this process yet, kill
283 if (kill(pid
, sig
) < 0) {
284 if (ret
>= 0 && errno
!= ESRCH
)
287 if (flags
& CGROUP_SIGCONT
)
288 (void) kill(pid
, SIGCONT
);
300 r
= set_put(s
, PID_TO_PTR(pid
));
316 /* To avoid racing against processes which fork
317 * quicker than we can kill them we repeat this until
318 * no new pids need to be killed. */
326 const char *controller
,
331 cg_kill_log_func_t log_kill
,
335 r
= cg_kill_items(controller
, path
, sig
, flags
, s
, log_kill
, userdata
, "cgroup.procs");
336 if (r
< 0 || sig
!= SIGKILL
)
339 /* Only in case of killing with SIGKILL and when using cgroupsv2, kill remaining threads manually as
340 a workaround for kernel bug. It was fixed in 5.2-rc5 (c03cd7738a83), backported to 4.19.66
341 (4340d175b898) and 4.14.138 (feb6b123b7dd). */
342 r
= cg_unified_controller(controller
);
346 return cg_kill_items(controller
, path
, sig
, flags
, s
, log_kill
, userdata
, "cgroup.threads");
349 int cg_kill_recursive(
350 const char *controller
,
355 cg_kill_log_func_t log_kill
,
358 _cleanup_set_free_ Set
*allocated_set
= NULL
;
359 _cleanup_closedir_
DIR *d
= NULL
;
367 s
= allocated_set
= set_new(NULL
);
372 ret
= cg_kill(controller
, path
, sig
, flags
, s
, log_kill
, userdata
);
374 r
= cg_enumerate_subgroups(controller
, path
, &d
);
376 if (ret
>= 0 && r
!= -ENOENT
)
382 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
383 _cleanup_free_
char *p
= NULL
;
385 p
= path_join(empty_to_root(path
), fn
);
390 r
= cg_kill_recursive(controller
, p
, sig
, flags
, s
, log_kill
, userdata
);
391 if (r
!= 0 && ret
>= 0)
394 if (ret
>= 0 && r
< 0)
397 if (flags
& CGROUP_REMOVE
) {
398 r
= cg_rmdir(controller
, path
);
399 if (r
< 0 && ret
>= 0 && !IN_SET(r
, -ENOENT
, -EBUSY
))
406 static const char *controller_to_dirname(const char *controller
) {
411 /* Converts a controller name to the directory name below
412 * /sys/fs/cgroup/ we want to mount it to. Effectively, this
413 * just cuts off the name= prefixed used for named
414 * hierarchies, if it is specified. */
416 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
)) {
417 if (cg_hybrid_unified() > 0)
418 controller
= SYSTEMD_CGROUP_CONTROLLER_HYBRID
;
420 controller
= SYSTEMD_CGROUP_CONTROLLER_LEGACY
;
423 e
= startswith(controller
, "name=");
430 static int join_path_legacy(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
437 dn
= controller_to_dirname(controller
);
439 if (isempty(path
) && isempty(suffix
))
440 t
= path_join("/sys/fs/cgroup", dn
);
441 else if (isempty(path
))
442 t
= path_join("/sys/fs/cgroup", dn
, suffix
);
443 else if (isempty(suffix
))
444 t
= path_join("/sys/fs/cgroup", dn
, path
);
446 t
= path_join("/sys/fs/cgroup", dn
, path
, suffix
);
454 static int join_path_unified(const char *path
, const char *suffix
, char **fs
) {
459 if (isempty(path
) && isempty(suffix
))
460 t
= strdup("/sys/fs/cgroup");
461 else if (isempty(path
))
462 t
= path_join("/sys/fs/cgroup", suffix
);
463 else if (isempty(suffix
))
464 t
= path_join("/sys/fs/cgroup", path
);
466 t
= path_join("/sys/fs/cgroup", path
, suffix
);
474 int cg_get_path(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
482 /* If no controller is specified, we return the path
483 * *below* the controllers, without any prefix. */
485 if (!path
&& !suffix
)
493 t
= path_join(path
, suffix
);
497 *fs
= path_simplify(t
, false);
501 if (!cg_controller_is_valid(controller
))
504 r
= cg_all_unified();
508 r
= join_path_unified(path
, suffix
, fs
);
510 r
= join_path_legacy(controller
, path
, suffix
, fs
);
514 path_simplify(*fs
, false);
518 static int controller_is_accessible(const char *controller
) {
523 /* Checks whether a specific controller is accessible,
524 * i.e. its hierarchy mounted. In the unified hierarchy all
525 * controllers are considered accessible, except for the named
528 if (!cg_controller_is_valid(controller
))
531 r
= cg_all_unified();
535 /* We don't support named hierarchies if we are using
536 * the unified hierarchy. */
538 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
))
541 if (startswith(controller
, "name="))
547 dn
= controller_to_dirname(controller
);
548 cc
= strjoina("/sys/fs/cgroup/", dn
);
550 if (laccess(cc
, F_OK
) < 0)
557 int cg_get_path_and_check(const char *controller
, const char *path
, const char *suffix
, char **fs
) {
563 /* Check if the specified controller is actually accessible */
564 r
= controller_is_accessible(controller
);
568 return cg_get_path(controller
, path
, suffix
, fs
);
571 int cg_set_xattr(const char *controller
, const char *path
, const char *name
, const void *value
, size_t size
, int flags
) {
572 _cleanup_free_
char *fs
= NULL
;
577 assert(value
|| size
<= 0);
579 r
= cg_get_path(controller
, path
, NULL
, &fs
);
583 if (setxattr(fs
, name
, value
, size
, flags
) < 0)
589 int cg_get_xattr(const char *controller
, const char *path
, const char *name
, void *value
, size_t size
) {
590 _cleanup_free_
char *fs
= NULL
;
597 r
= cg_get_path(controller
, path
, NULL
, &fs
);
601 n
= getxattr(fs
, name
, value
, size
);
608 int cg_pid_get_path(const char *controller
, pid_t pid
, char **path
) {
609 _cleanup_fclose_
FILE *f
= NULL
;
610 const char *fs
, *controller_str
;
618 if (!cg_controller_is_valid(controller
))
621 controller
= SYSTEMD_CGROUP_CONTROLLER
;
623 unified
= cg_unified_controller(controller
);
627 if (streq(controller
, SYSTEMD_CGROUP_CONTROLLER
))
628 controller_str
= SYSTEMD_CGROUP_CONTROLLER_LEGACY
;
630 controller_str
= controller
;
632 cs
= strlen(controller_str
);
635 fs
= procfs_file_alloca(pid
, "cgroup");
636 r
= fopen_unlocked(fs
, "re", &f
);
643 _cleanup_free_
char *line
= NULL
;
646 r
= read_line(f
, LONG_LINE_MAX
, &line
);
653 e
= startswith(line
, "0:");
663 const char *word
, *state
;
666 l
= strchr(line
, ':');
676 FOREACH_WORD_SEPARATOR(word
, k
, l
, ",", state
)
677 if (k
== cs
&& memcmp(word
, controller_str
, cs
) == 0) {
689 /* Truncate suffix indicating the process is a zombie */
690 e
= endswith(p
, " (deleted)");
701 int cg_install_release_agent(const char *controller
, const char *agent
) {
702 _cleanup_free_
char *fs
= NULL
, *contents
= NULL
;
708 r
= cg_unified_controller(controller
);
711 if (r
> 0) /* doesn't apply to unified hierarchy */
714 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
718 r
= read_one_line_file(fs
, &contents
);
722 sc
= strstrip(contents
);
724 r
= write_string_file(fs
, agent
, WRITE_STRING_FILE_DISABLE_BUFFER
);
727 } else if (!path_equal(sc
, agent
))
731 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
735 contents
= mfree(contents
);
736 r
= read_one_line_file(fs
, &contents
);
740 sc
= strstrip(contents
);
741 if (streq(sc
, "0")) {
742 r
= write_string_file(fs
, "1", WRITE_STRING_FILE_DISABLE_BUFFER
);
755 int cg_uninstall_release_agent(const char *controller
) {
756 _cleanup_free_
char *fs
= NULL
;
759 r
= cg_unified_controller(controller
);
762 if (r
> 0) /* Doesn't apply to unified hierarchy */
765 r
= cg_get_path(controller
, NULL
, "notify_on_release", &fs
);
769 r
= write_string_file(fs
, "0", WRITE_STRING_FILE_DISABLE_BUFFER
);
775 r
= cg_get_path(controller
, NULL
, "release_agent", &fs
);
779 r
= write_string_file(fs
, "", WRITE_STRING_FILE_DISABLE_BUFFER
);
786 int cg_is_empty(const char *controller
, const char *path
) {
787 _cleanup_fclose_
FILE *f
= NULL
;
793 r
= cg_enumerate_processes(controller
, path
, &f
);
799 r
= cg_read_pid(f
, &pid
);
806 int cg_is_empty_recursive(const char *controller
, const char *path
) {
811 /* The root cgroup is always populated */
812 if (controller
&& empty_or_root(path
))
815 r
= cg_unified_controller(controller
);
819 _cleanup_free_
char *t
= NULL
;
821 /* On the unified hierarchy we can check empty state
822 * via the "populated" attribute of "cgroup.events". */
824 r
= cg_read_event(controller
, path
, "populated", &t
);
830 return streq(t
, "0");
832 _cleanup_closedir_
DIR *d
= NULL
;
835 r
= cg_is_empty(controller
, path
);
839 r
= cg_enumerate_subgroups(controller
, path
, &d
);
845 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
846 _cleanup_free_
char *p
= NULL
;
848 p
= path_join(path
, fn
);
853 r
= cg_is_empty_recursive(controller
, p
);
864 int cg_split_spec(const char *spec
, char **controller
, char **path
) {
865 char *t
= NULL
, *u
= NULL
;
871 if (!path_is_normalized(spec
))
879 *path
= path_simplify(t
, false);
888 e
= strchr(spec
, ':');
890 if (!cg_controller_is_valid(spec
))
907 t
= strndup(spec
, e
-spec
);
910 if (!cg_controller_is_valid(t
)) {
924 if (!path_is_normalized(u
) ||
925 !path_is_absolute(u
)) {
931 path_simplify(u
, false);
947 int cg_mangle_path(const char *path
, char **result
) {
948 _cleanup_free_
char *c
= NULL
, *p
= NULL
;
955 /* First, check if it already is a filesystem path */
956 if (path_startswith(path
, "/sys/fs/cgroup")) {
962 *result
= path_simplify(t
, false);
966 /* Otherwise, treat it as cg spec */
967 r
= cg_split_spec(path
, &c
, &p
);
971 return cg_get_path(c
?: SYSTEMD_CGROUP_CONTROLLER
, p
?: "/", NULL
, result
);
974 int cg_get_root_path(char **path
) {
980 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 1, &p
);
984 e
= endswith(p
, "/" SPECIAL_INIT_SCOPE
);
986 e
= endswith(p
, "/" SPECIAL_SYSTEM_SLICE
); /* legacy */
988 e
= endswith(p
, "/system"); /* even more legacy */
996 int cg_shift_path(const char *cgroup
, const char *root
, const char **shifted
) {
997 _cleanup_free_
char *rt
= NULL
;
1005 /* If the root was specified let's use that, otherwise
1006 * let's determine it from PID 1 */
1008 r
= cg_get_root_path(&rt
);
1015 p
= path_startswith(cgroup
, root
);
1016 if (p
&& p
> cgroup
)
1024 int cg_pid_get_path_shifted(pid_t pid
, const char *root
, char **cgroup
) {
1025 _cleanup_free_
char *raw
= NULL
;
1032 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &raw
);
1036 r
= cg_shift_path(raw
, root
, &c
);
1041 *cgroup
= TAKE_PTR(raw
);
1055 int cg_path_decode_unit(const char *cgroup
, char **unit
) {
1062 n
= strcspn(cgroup
, "/");
1066 c
= strndupa(cgroup
, n
);
1069 if (!unit_name_is_valid(c
, UNIT_NAME_PLAIN
|UNIT_NAME_INSTANCE
))
1080 static bool valid_slice_name(const char *p
, size_t n
) {
1085 if (n
< STRLEN("x.slice"))
1088 if (memcmp(p
+ n
- 6, ".slice", 6) == 0) {
1094 c
= cg_unescape(buf
);
1096 return unit_name_is_valid(c
, UNIT_NAME_PLAIN
);
1102 static const char *skip_slices(const char *p
) {
1105 /* Skips over all slice assignments */
1110 p
+= strspn(p
, "/");
1112 n
= strcspn(p
, "/");
1113 if (!valid_slice_name(p
, n
))
1120 int cg_path_get_unit(const char *path
, char **ret
) {
1128 e
= skip_slices(path
);
1130 r
= cg_path_decode_unit(e
, &unit
);
1134 /* We skipped over the slices, don't accept any now */
1135 if (endswith(unit
, ".slice")) {
1144 int cg_pid_get_unit(pid_t pid
, char **unit
) {
1145 _cleanup_free_
char *cgroup
= NULL
;
1150 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1154 return cg_path_get_unit(cgroup
, unit
);
1158 * Skip session-*.scope, but require it to be there.
1160 static const char *skip_session(const char *p
) {
1166 p
+= strspn(p
, "/");
1168 n
= strcspn(p
, "/");
1169 if (n
< STRLEN("session-x.scope"))
1172 if (memcmp(p
, "session-", 8) == 0 && memcmp(p
+ n
- 6, ".scope", 6) == 0) {
1173 char buf
[n
- 8 - 6 + 1];
1175 memcpy(buf
, p
+ 8, n
- 8 - 6);
1178 /* Note that session scopes never need unescaping,
1179 * since they cannot conflict with the kernel's own
1180 * names, hence we don't need to call cg_unescape()
1183 if (!session_id_valid(buf
))
1187 p
+= strspn(p
, "/");
1195 * Skip user@*.service, but require it to be there.
1197 static const char *skip_user_manager(const char *p
) {
1203 p
+= strspn(p
, "/");
1205 n
= strcspn(p
, "/");
1206 if (n
< STRLEN("user@x.service"))
1209 if (memcmp(p
, "user@", 5) == 0 && memcmp(p
+ n
- 8, ".service", 8) == 0) {
1210 char buf
[n
- 5 - 8 + 1];
1212 memcpy(buf
, p
+ 5, n
- 5 - 8);
1215 /* Note that user manager services never need unescaping,
1216 * since they cannot conflict with the kernel's own
1217 * names, hence we don't need to call cg_unescape()
1220 if (parse_uid(buf
, NULL
) < 0)
1224 p
+= strspn(p
, "/");
1232 static const char *skip_user_prefix(const char *path
) {
1237 /* Skip slices, if there are any */
1238 e
= skip_slices(path
);
1240 /* Skip the user manager, if it's in the path now... */
1241 t
= skip_user_manager(e
);
1245 /* Alternatively skip the user session if it is in the path... */
1246 return skip_session(e
);
1249 int cg_path_get_user_unit(const char *path
, char **ret
) {
1255 t
= skip_user_prefix(path
);
1259 /* And from here on it looks pretty much the same as for a system unit, hence let's use the same
1261 return cg_path_get_unit(t
, ret
);
1264 int cg_pid_get_user_unit(pid_t pid
, char **unit
) {
1265 _cleanup_free_
char *cgroup
= NULL
;
1270 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1274 return cg_path_get_user_unit(cgroup
, unit
);
1277 int cg_path_get_machine_name(const char *path
, char **machine
) {
1278 _cleanup_free_
char *u
= NULL
;
1282 r
= cg_path_get_unit(path
, &u
);
1286 sl
= strjoina("/run/systemd/machines/unit:", u
);
1287 return readlink_malloc(sl
, machine
);
1290 int cg_pid_get_machine_name(pid_t pid
, char **machine
) {
1291 _cleanup_free_
char *cgroup
= NULL
;
1296 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1300 return cg_path_get_machine_name(cgroup
, machine
);
1303 int cg_path_get_session(const char *path
, char **session
) {
1304 _cleanup_free_
char *unit
= NULL
;
1310 r
= cg_path_get_unit(path
, &unit
);
1314 start
= startswith(unit
, "session-");
1317 end
= endswith(start
, ".scope");
1322 if (!session_id_valid(start
))
1338 int cg_pid_get_session(pid_t pid
, char **session
) {
1339 _cleanup_free_
char *cgroup
= NULL
;
1342 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1346 return cg_path_get_session(cgroup
, session
);
1349 int cg_path_get_owner_uid(const char *path
, uid_t
*uid
) {
1350 _cleanup_free_
char *slice
= NULL
;
1356 r
= cg_path_get_slice(path
, &slice
);
1360 start
= startswith(slice
, "user-");
1363 end
= endswith(start
, ".slice");
1368 if (parse_uid(start
, uid
) < 0)
1374 int cg_pid_get_owner_uid(pid_t pid
, uid_t
*uid
) {
1375 _cleanup_free_
char *cgroup
= NULL
;
1378 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1382 return cg_path_get_owner_uid(cgroup
, uid
);
1385 int cg_path_get_slice(const char *p
, char **slice
) {
1386 const char *e
= NULL
;
1391 /* Finds the right-most slice unit from the beginning, but
1392 * stops before we come to the first non-slice unit. */
1397 p
+= strspn(p
, "/");
1399 n
= strcspn(p
, "/");
1400 if (!valid_slice_name(p
, n
)) {
1405 s
= strdup(SPECIAL_ROOT_SLICE
);
1413 return cg_path_decode_unit(e
, slice
);
1421 int cg_pid_get_slice(pid_t pid
, char **slice
) {
1422 _cleanup_free_
char *cgroup
= NULL
;
1427 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1431 return cg_path_get_slice(cgroup
, slice
);
1434 int cg_path_get_user_slice(const char *p
, char **slice
) {
1439 t
= skip_user_prefix(p
);
1443 /* And now it looks pretty much the same as for a system
1444 * slice, so let's just use the same parser from here on. */
1445 return cg_path_get_slice(t
, slice
);
1448 int cg_pid_get_user_slice(pid_t pid
, char **slice
) {
1449 _cleanup_free_
char *cgroup
= NULL
;
1454 r
= cg_pid_get_path_shifted(pid
, NULL
, &cgroup
);
1458 return cg_path_get_user_slice(cgroup
, slice
);
1461 char *cg_escape(const char *p
) {
1462 bool need_prefix
= false;
1464 /* This implements very minimal escaping for names to be used
1465 * as file names in the cgroup tree: any name which might
1466 * conflict with a kernel name or is prefixed with '_' is
1467 * prefixed with a '_'. That way, when reading cgroup names it
1468 * is sufficient to remove a single prefixing underscore if
1471 /* The return value of this function (unlike cg_unescape())
1474 if (IN_SET(p
[0], 0, '_', '.') ||
1475 STR_IN_SET(p
, "notify_on_release", "release_agent", "tasks") ||
1476 startswith(p
, "cgroup."))
1481 dot
= strrchr(p
, '.');
1486 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1489 n
= cgroup_controller_to_string(c
);
1494 if (memcmp(p
, n
, l
) != 0)
1504 return strjoin("_", p
);
1509 char *cg_unescape(const char *p
) {
1512 /* The return value of this function (unlike cg_escape())
1513 * doesn't need free()! */
1521 #define CONTROLLER_VALID \
1525 bool cg_controller_is_valid(const char *p
) {
1531 if (streq(p
, SYSTEMD_CGROUP_CONTROLLER
))
1534 s
= startswith(p
, "name=");
1538 if (IN_SET(*p
, 0, '_'))
1541 for (t
= p
; *t
; t
++)
1542 if (!strchr(CONTROLLER_VALID
, *t
))
1545 if (t
- p
> FILENAME_MAX
)
1551 int cg_slice_to_path(const char *unit
, char **ret
) {
1552 _cleanup_free_
char *p
= NULL
, *s
= NULL
, *e
= NULL
;
1559 if (streq(unit
, SPECIAL_ROOT_SLICE
)) {
1569 if (!unit_name_is_valid(unit
, UNIT_NAME_PLAIN
))
1572 if (!endswith(unit
, ".slice"))
1575 r
= unit_name_to_prefix(unit
, &p
);
1579 dash
= strchr(p
, '-');
1581 /* Don't allow initial dashes */
1586 _cleanup_free_
char *escaped
= NULL
;
1587 char n
[dash
- p
+ sizeof(".slice")];
1589 #if HAS_FEATURE_MEMORY_SANITIZER
1590 /* msan doesn't instrument stpncpy, so it thinks
1591 * n is later used uninitialized:
1592 * https://github.com/google/sanitizers/issues/926
1597 /* Don't allow trailing or double dashes */
1598 if (IN_SET(dash
[1], 0, '-'))
1601 strcpy(stpncpy(n
, p
, dash
- p
), ".slice");
1602 if (!unit_name_is_valid(n
, UNIT_NAME_PLAIN
))
1605 escaped
= cg_escape(n
);
1609 if (!strextend(&s
, escaped
, "/", NULL
))
1612 dash
= strchr(dash
+1, '-');
1615 e
= cg_escape(unit
);
1619 if (!strextend(&s
, e
, NULL
))
1627 int cg_set_attribute(const char *controller
, const char *path
, const char *attribute
, const char *value
) {
1628 _cleanup_free_
char *p
= NULL
;
1631 r
= cg_get_path(controller
, path
, attribute
, &p
);
1635 return write_string_file(p
, value
, WRITE_STRING_FILE_DISABLE_BUFFER
);
1638 int cg_get_attribute(const char *controller
, const char *path
, const char *attribute
, char **ret
) {
1639 _cleanup_free_
char *p
= NULL
;
1642 r
= cg_get_path(controller
, path
, attribute
, &p
);
1646 return read_one_line_file(p
, ret
);
1649 int cg_get_keyed_attribute(
1650 const char *controller
,
1652 const char *attribute
,
1654 char **ret_values
) {
1656 _cleanup_free_
char *filename
= NULL
, *contents
= NULL
;
1658 size_t n
, i
, n_done
= 0;
1662 /* Reads one or more fields of a cgroup v2 keyed attribute file. The 'keys' parameter should be an strv with
1663 * all keys to retrieve. The 'ret_values' parameter should be passed as string size with the same number of
1664 * entries as 'keys'. On success each entry will be set to the value of the matching key.
1666 * If the attribute file doesn't exist at all returns ENOENT, if any key is not found returns ENXIO. */
1668 r
= cg_get_path(controller
, path
, attribute
, &filename
);
1672 r
= read_full_file(filename
, &contents
, NULL
);
1676 n
= strv_length(keys
);
1677 if (n
== 0) /* No keys to retrieve? That's easy, we are done then */
1680 /* Let's build this up in a temporary array for now in order not to clobber the return parameter on failure */
1681 v
= newa0(char*, n
);
1683 for (p
= contents
; *p
;) {
1684 const char *w
= NULL
;
1686 for (i
= 0; i
< n
; i
++)
1688 w
= first_word(p
, keys
[i
]);
1696 l
= strcspn(w
, NEWLINE
);
1697 v
[i
] = strndup(w
, l
);
1709 p
+= strcspn(p
, NEWLINE
);
1711 p
+= strspn(p
, NEWLINE
);
1717 for (i
= 0; i
< n
; i
++)
1723 memcpy(ret_values
, v
, sizeof(char*) * n
);
1727 int cg_mask_to_string(CGroupMask mask
, char **ret
) {
1728 _cleanup_free_
char *s
= NULL
;
1729 size_t n
= 0, allocated
= 0;
1740 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1744 if (!FLAGS_SET(mask
, CGROUP_CONTROLLER_TO_MASK(c
)))
1747 k
= cgroup_controller_to_string(c
);
1750 if (!GREEDY_REALLOC(s
, allocated
, n
+ space
+ l
+ 1))
1755 memcpy(s
+ n
+ space
, k
, l
);
1769 int cg_mask_from_string(const char *value
, CGroupMask
*ret
) {
1776 _cleanup_free_
char *n
= NULL
;
1780 r
= extract_first_word(&value
, &n
, NULL
, 0);
1786 v
= cgroup_controller_from_string(n
);
1790 m
|= CGROUP_CONTROLLER_TO_MASK(v
);
1797 int cg_mask_supported(CGroupMask
*ret
) {
1801 /* Determines the mask of supported cgroup controllers. Only includes controllers we can make sense of and that
1802 * are actually accessible. Only covers real controllers, i.e. not the CGROUP_CONTROLLER_BPF_xyz
1803 * pseudo-controllers. */
1805 r
= cg_all_unified();
1809 _cleanup_free_
char *root
= NULL
, *controllers
= NULL
, *path
= NULL
;
1811 /* In the unified hierarchy we can read the supported
1812 * and accessible controllers from a the top-level
1813 * cgroup attribute */
1815 r
= cg_get_root_path(&root
);
1819 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, root
, "cgroup.controllers", &path
);
1823 r
= read_one_line_file(path
, &controllers
);
1827 r
= cg_mask_from_string(controllers
, &mask
);
1831 /* Mask controllers that are not supported in unified hierarchy. */
1832 mask
&= CGROUP_MASK_V2
;
1837 /* In the legacy hierarchy, we check which hierarchies are mounted. */
1840 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++) {
1841 CGroupMask bit
= CGROUP_CONTROLLER_TO_MASK(c
);
1844 if (!FLAGS_SET(CGROUP_MASK_V1
, bit
))
1847 n
= cgroup_controller_to_string(c
);
1848 if (controller_is_accessible(n
) >= 0)
1857 int cg_kernel_controllers(Set
**ret
) {
1858 _cleanup_set_free_free_ Set
*controllers
= NULL
;
1859 _cleanup_fclose_
FILE *f
= NULL
;
1864 /* Determines the full list of kernel-known controllers. Might include controllers we don't actually support
1865 * and controllers that aren't currently accessible (because not mounted). This does not include "name="
1866 * pseudo-controllers. */
1868 controllers
= set_new(&string_hash_ops
);
1872 r
= fopen_unlocked("/proc/cgroups", "re", &f
);
1880 /* Ignore the header line */
1881 (void) read_line(f
, (size_t) -1, NULL
);
1888 if (fscanf(f
, "%ms %*i %*i %i", &controller
, &enabled
) != 2) {
1894 return errno_or_else(EIO
);
1904 if (!cg_controller_is_valid(controller
)) {
1909 r
= set_consume(controllers
, controller
);
1914 *ret
= TAKE_PTR(controllers
);
1919 /* The hybrid mode was initially implemented in v232 and simply mounted cgroup2 on
1920 * /sys/fs/cgroup/systemd. This unfortunately broke other tools (such as docker) which expected the v1
1921 * "name=systemd" hierarchy on /sys/fs/cgroup/systemd. From v233 and on, the hybrid mode mounts v2 on
1922 * /sys/fs/cgroup/unified and maintains "name=systemd" hierarchy on /sys/fs/cgroup/systemd for compatibility
1925 * To keep live upgrade working, we detect and support v232 layout. When v232 layout is detected, to keep
1926 * cgroup v2 process management but disable the compat dual layout, we return true on
1927 * cg_unified_controller(SYSTEMD_CGROUP_CONTROLLER) and false on cg_hybrid_unified().
1929 static thread_local
bool unified_systemd_v232
;
1931 int cg_unified_cached(bool flush
) {
1932 static thread_local CGroupUnified unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
1936 /* Checks if we support the unified hierarchy. Returns an
1937 * error when the cgroup hierarchies aren't mounted yet or we
1938 * have any other trouble determining if the unified hierarchy
1942 unified_cache
= CGROUP_UNIFIED_UNKNOWN
;
1943 else if (unified_cache
>= CGROUP_UNIFIED_NONE
)
1944 return unified_cache
;
1946 if (statfs("/sys/fs/cgroup/", &fs
) < 0)
1947 return log_debug_errno(errno
, "statfs(\"/sys/fs/cgroup/\") failed: %m");
1949 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
1950 log_debug("Found cgroup2 on /sys/fs/cgroup/, full unified hierarchy");
1951 unified_cache
= CGROUP_UNIFIED_ALL
;
1952 } else if (F_TYPE_EQUAL(fs
.f_type
, TMPFS_MAGIC
)) {
1953 if (statfs("/sys/fs/cgroup/unified/", &fs
) == 0 &&
1954 F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
1955 log_debug("Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller");
1956 unified_cache
= CGROUP_UNIFIED_SYSTEMD
;
1957 unified_systemd_v232
= false;
1959 if (statfs("/sys/fs/cgroup/systemd/", &fs
) < 0)
1960 return log_debug_errno(errno
, "statfs(\"/sys/fs/cgroup/systemd\" failed: %m");
1962 if (F_TYPE_EQUAL(fs
.f_type
, CGROUP2_SUPER_MAGIC
)) {
1963 log_debug("Found cgroup2 on /sys/fs/cgroup/systemd, unified hierarchy for systemd controller (v232 variant)");
1964 unified_cache
= CGROUP_UNIFIED_SYSTEMD
;
1965 unified_systemd_v232
= true;
1966 } else if (F_TYPE_EQUAL(fs
.f_type
, CGROUP_SUPER_MAGIC
)) {
1967 log_debug("Found cgroup on /sys/fs/cgroup/systemd, legacy hierarchy");
1968 unified_cache
= CGROUP_UNIFIED_NONE
;
1970 log_debug("Unexpected filesystem type %llx mounted on /sys/fs/cgroup/systemd, assuming legacy hierarchy",
1971 (unsigned long long) fs
.f_type
);
1972 unified_cache
= CGROUP_UNIFIED_NONE
;
1976 return log_debug_errno(SYNTHETIC_ERRNO(ENOMEDIUM
),
1977 "Unknown filesystem type %llx mounted on /sys/fs/cgroup.",
1978 (unsigned long long)fs
.f_type
);
1980 return unified_cache
;
1983 int cg_unified_controller(const char *controller
) {
1986 r
= cg_unified_cached(false);
1990 if (r
== CGROUP_UNIFIED_NONE
)
1993 if (r
>= CGROUP_UNIFIED_ALL
)
1996 return streq_ptr(controller
, SYSTEMD_CGROUP_CONTROLLER
);
1999 int cg_all_unified(void) {
2002 r
= cg_unified_cached(false);
2006 return r
>= CGROUP_UNIFIED_ALL
;
2009 int cg_hybrid_unified(void) {
2012 r
= cg_unified_cached(false);
2016 return r
== CGROUP_UNIFIED_SYSTEMD
&& !unified_systemd_v232
;
2019 const uint64_t cgroup_io_limit_defaults
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2020 [CGROUP_IO_RBPS_MAX
] = CGROUP_LIMIT_MAX
,
2021 [CGROUP_IO_WBPS_MAX
] = CGROUP_LIMIT_MAX
,
2022 [CGROUP_IO_RIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2023 [CGROUP_IO_WIOPS_MAX
] = CGROUP_LIMIT_MAX
,
2026 static const char* const cgroup_io_limit_type_table
[_CGROUP_IO_LIMIT_TYPE_MAX
] = {
2027 [CGROUP_IO_RBPS_MAX
] = "IOReadBandwidthMax",
2028 [CGROUP_IO_WBPS_MAX
] = "IOWriteBandwidthMax",
2029 [CGROUP_IO_RIOPS_MAX
] = "IOReadIOPSMax",
2030 [CGROUP_IO_WIOPS_MAX
] = "IOWriteIOPSMax",
2033 DEFINE_STRING_TABLE_LOOKUP(cgroup_io_limit_type
, CGroupIOLimitType
);
2035 bool is_cgroup_fs(const struct statfs
*s
) {
2036 return is_fs_type(s
, CGROUP_SUPER_MAGIC
) ||
2037 is_fs_type(s
, CGROUP2_SUPER_MAGIC
);
2040 bool fd_is_cgroup_fs(int fd
) {
2043 if (fstatfs(fd
, &s
) < 0)
2046 return is_cgroup_fs(&s
);
2049 static const char *const cgroup_controller_table
[_CGROUP_CONTROLLER_MAX
] = {
2050 [CGROUP_CONTROLLER_CPU
] = "cpu",
2051 [CGROUP_CONTROLLER_CPUACCT
] = "cpuacct",
2052 [CGROUP_CONTROLLER_CPUSET
] = "cpuset",
2053 [CGROUP_CONTROLLER_IO
] = "io",
2054 [CGROUP_CONTROLLER_BLKIO
] = "blkio",
2055 [CGROUP_CONTROLLER_MEMORY
] = "memory",
2056 [CGROUP_CONTROLLER_DEVICES
] = "devices",
2057 [CGROUP_CONTROLLER_PIDS
] = "pids",
2058 [CGROUP_CONTROLLER_BPF_FIREWALL
] = "bpf-firewall",
2059 [CGROUP_CONTROLLER_BPF_DEVICES
] = "bpf-devices",
2062 DEFINE_STRING_TABLE_LOOKUP(cgroup_controller
, CGroupController
);
2064 CGroupMask
get_cpu_accounting_mask(void) {
2065 static CGroupMask needed_mask
= (CGroupMask
) -1;
2067 /* On kernel ≥4.15 with unified hierarchy, cpu.stat's usage_usec is
2068 * provided externally from the CPU controller, which means we don't
2069 * need to enable the CPU controller just to get metrics. This is good,
2070 * because enabling the CPU controller comes at a minor performance
2071 * hit, especially when it's propagated deep into large hierarchies.
2072 * There's also no separate CPU accounting controller available within
2073 * a unified hierarchy.
2075 * This combination of factors results in the desired cgroup mask to
2076 * enable for CPU accounting varying as follows:
2078 * ╔═════════════════════╤═════════════════════╗
2079 * ║ Linux ≥4.15 │ Linux <4.15 ║
2080 * ╔═══════════════╬═════════════════════╪═════════════════════╣
2081 * ║ Unified ║ nothing │ CGROUP_MASK_CPU ║
2082 * ╟───────────────╫─────────────────────┼─────────────────────╢
2083 * ║ Hybrid/Legacy ║ CGROUP_MASK_CPUACCT │ CGROUP_MASK_CPUACCT ║
2084 * ╚═══════════════╩═════════════════════╧═════════════════════╝
2086 * We check kernel version here instead of manually checking whether
2087 * cpu.stat is present for every cgroup, as that check in itself would
2088 * already be fairly expensive.
2090 * Kernels where this patch has been backported will therefore have the
2091 * CPU controller enabled unnecessarily. This is more expensive than
2092 * necessary, but harmless. ☺️
2095 if (needed_mask
== (CGroupMask
) -1) {
2096 if (cg_all_unified()) {
2098 assert_se(uname(&u
) >= 0);
2100 if (str_verscmp(u
.release
, "4.15") < 0)
2101 needed_mask
= CGROUP_MASK_CPU
;
2105 needed_mask
= CGROUP_MASK_CPUACCT
;
2111 bool cpu_accounting_is_cheap(void) {
2112 return get_cpu_accounting_mask() == 0;