1 /* SPDX-License-Identifier: LGPL-2.1+ */
4 * cgfs-ng.c: this is a new, simplified implementation of a filesystem
5 * cgroup backend. The original cgfs.c was designed to be as flexible
6 * as possible. It would try to find cgroup filesystems no matter where
7 * or how you had them mounted, and deduce the most usable mount for
10 * This new implementation assumes that cgroup filesystems are mounted
11 * under /sys/fs/cgroup/clist where clist is either the controller, or
12 * a comma-separated list of controllers.
22 #include <linux/kdev_t.h>
23 #include <linux/types.h>
30 #include <sys/types.h>
36 #include "cgroup2_devices.h"
37 #include "cgroup_utils.h"
44 #include "memory_utils.h"
45 #include "storage/storage.h"
49 #include "include/strlcpy.h"
53 #include "include/strlcat.h"
56 lxc_log_define(cgfsng
, cgroup
);
58 /* Given a pointer to a null-terminated array of pointers, realloc to add one
59 * entry, and point the new entry to NULL. Do not fail. Return the index to the
60 * second-to-last entry - that is, the one which is now available for use
61 * (keeping the list null-terminated).
63 static int append_null_to_list(void ***list
)
68 for (; (*list
)[newentry
]; newentry
++)
71 *list
= must_realloc(*list
, (newentry
+ 2) * sizeof(void **));
72 (*list
)[newentry
+ 1] = NULL
;
76 /* Given a null-terminated array of strings, check whether @entry is one of the
79 static bool string_in_list(char **list
, const char *entry
)
84 for (int i
= 0; list
[i
]; i
++)
85 if (strcmp(list
[i
], entry
) == 0)
91 /* Return a copy of @entry prepending "name=", i.e. turn "systemd" into
92 * "name=systemd". Do not fail.
94 static char *cg_legacy_must_prefix_named(char *entry
)
100 prefixed
= must_realloc(NULL
, len
+ 6);
102 memcpy(prefixed
, "name=", STRLITERALLEN("name="));
103 memcpy(prefixed
+ STRLITERALLEN("name="), entry
, len
);
104 prefixed
[len
+ 5] = '\0';
109 /* Append an entry to the clist. Do not fail. @clist must be NULL the first time
112 * We also handle named subsystems here. Any controller which is not a kernel
113 * subsystem, we prefix "name=". Any which is both a kernel and named subsystem,
114 * we refuse to use because we're not sure which we have here.
115 * (TODO: We could work around this in some cases by just remounting to be
116 * unambiguous, or by comparing mountpoint contents with current cgroup.)
118 * The last entry will always be NULL.
120 static void must_append_controller(char **klist
, char **nlist
, char ***clist
,
126 if (string_in_list(klist
, entry
) && string_in_list(nlist
, entry
)) {
127 ERROR("Refusing to use ambiguous controller \"%s\"", entry
);
128 ERROR("It is both a named and kernel subsystem");
132 newentry
= append_null_to_list((void ***)clist
);
134 if (strncmp(entry
, "name=", 5) == 0)
135 copy
= must_copy_string(entry
);
136 else if (string_in_list(klist
, entry
))
137 copy
= must_copy_string(entry
);
139 copy
= cg_legacy_must_prefix_named(entry
);
141 (*clist
)[newentry
] = copy
;
144 /* Given a handler's cgroup data, return the struct hierarchy for the controller
145 * @c, or NULL if there is none.
147 struct hierarchy
*get_hierarchy(struct cgroup_ops
*ops
, const char *controller
)
149 if (!ops
->hierarchies
)
150 return log_trace_errno(NULL
, errno
, "There are no useable cgroup controllers");
152 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
154 /* This is the empty unified hierarchy. */
155 if (ops
->hierarchies
[i
]->controllers
&&
156 !ops
->hierarchies
[i
]->controllers
[0])
157 return ops
->hierarchies
[i
];
159 } else if (pure_unified_layout(ops
) &&
160 strcmp(controller
, "devices") == 0) {
161 if (ops
->unified
->bpf_device_controller
)
166 if (string_in_list(ops
->hierarchies
[i
]->controllers
, controller
))
167 return ops
->hierarchies
[i
];
171 WARN("There is no useable %s controller", controller
);
173 WARN("There is no empty unified cgroup hierarchy");
175 return ret_set_errno(NULL
, ENOENT
);
178 #define BATCH_SIZE 50
179 static void batch_realloc(char **mem
, size_t oldlen
, size_t newlen
)
181 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
182 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
184 if (!*mem
|| newbatches
> oldbatches
)
185 *mem
= must_realloc(*mem
, newbatches
* BATCH_SIZE
);
188 static void append_line(char **dest
, size_t oldlen
, char *new, size_t newlen
)
190 size_t full
= oldlen
+ newlen
;
192 batch_realloc(dest
, oldlen
, full
+ 1);
194 memcpy(*dest
+ oldlen
, new, newlen
+ 1);
197 /* Slurp in a whole file */
198 static char *read_file(const char *fnam
)
200 __do_free
char *buf
= NULL
, *line
= NULL
;
201 __do_fclose
FILE *f
= NULL
;
202 size_t len
= 0, fulllen
= 0;
205 f
= fopen(fnam
, "re");
209 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
210 append_line(&buf
, fulllen
, line
, linelen
);
214 return move_ptr(buf
);
217 /* Taken over modified from the kernel sources. */
218 #define NBITS 32 /* bits in uint32_t */
219 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
220 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
222 static void set_bit(unsigned bit
, uint32_t *bitarr
)
224 bitarr
[bit
/ NBITS
] |= (1 << (bit
% NBITS
));
227 static void clear_bit(unsigned bit
, uint32_t *bitarr
)
229 bitarr
[bit
/ NBITS
] &= ~(1 << (bit
% NBITS
));
232 static bool is_set(unsigned bit
, uint32_t *bitarr
)
234 return (bitarr
[bit
/ NBITS
] & (1 << (bit
% NBITS
))) != 0;
237 /* Create cpumask from cpulist aka turn:
245 static uint32_t *lxc_cpumask(char *buf
, size_t nbits
)
247 __do_free
uint32_t *bitarr
= NULL
;
251 arrlen
= BITS_TO_LONGS(nbits
);
252 bitarr
= calloc(arrlen
, sizeof(uint32_t));
254 return ret_set_errno(NULL
, ENOMEM
);
256 lxc_iterate_parts(token
, buf
, ",") {
261 start
= strtoul(token
, NULL
, 0);
263 range
= strchr(token
, '-');
265 end
= strtoul(range
+ 1, NULL
, 0);
268 return ret_set_errno(NULL
, EINVAL
);
271 return ret_set_errno(NULL
, EINVAL
);
274 set_bit(start
++, bitarr
);
277 return move_ptr(bitarr
);
280 /* Turn cpumask into simple, comma-separated cpulist. */
281 static char *lxc_cpumask_to_cpulist(uint32_t *bitarr
, size_t nbits
)
283 __do_free_string_list
char **cpulist
= NULL
;
284 char numstr
[INTTYPE_TO_STRLEN(size_t)] = {0};
287 for (size_t i
= 0; i
<= nbits
; i
++) {
288 if (!is_set(i
, bitarr
))
291 ret
= snprintf(numstr
, sizeof(numstr
), "%zu", i
);
292 if (ret
< 0 || (size_t)ret
>= sizeof(numstr
))
295 ret
= lxc_append_string(&cpulist
, numstr
);
297 return ret_set_errno(NULL
, ENOMEM
);
301 return ret_set_errno(NULL
, ENOMEM
);
303 return lxc_string_join(",", (const char **)cpulist
, false);
306 static ssize_t
get_max_cpus(char *cpulist
)
309 char *maxcpus
= cpulist
;
312 c1
= strrchr(maxcpus
, ',');
316 c2
= strrchr(maxcpus
, '-');
330 cpus
= strtoul(c1
, NULL
, 0);
337 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
338 #define __OFFLINE_CPUS "/sys/devices/system/cpu/offline"
339 static bool cg_legacy_filter_and_set_cpus(const char *parent_cgroup
,
340 char *child_cgroup
, bool am_initialized
)
342 __do_free
char *cpulist
= NULL
, *fpath
= NULL
, *isolcpus
= NULL
,
343 *offlinecpus
= NULL
, *posscpus
= NULL
;
344 __do_free
uint32_t *isolmask
= NULL
, *offlinemask
= NULL
,
348 ssize_t maxisol
= 0, maxoffline
= 0, maxposs
= 0;
349 bool flipped_bit
= false;
351 fpath
= must_make_path(parent_cgroup
, "cpuset.cpus", NULL
);
352 posscpus
= read_file(fpath
);
354 return log_error_errno(false, errno
, "Failed to read file \"%s\"", fpath
);
356 /* Get maximum number of cpus found in possible cpuset. */
357 maxposs
= get_max_cpus(posscpus
);
358 if (maxposs
< 0 || maxposs
>= INT_MAX
- 1)
361 if (file_exists(__ISOL_CPUS
)) {
362 isolcpus
= read_file(__ISOL_CPUS
);
364 return log_error_errno(false, errno
, "Failed to read file \"%s\"", __ISOL_CPUS
);
366 if (isdigit(isolcpus
[0])) {
367 /* Get maximum number of cpus found in isolated cpuset. */
368 maxisol
= get_max_cpus(isolcpus
);
369 if (maxisol
< 0 || maxisol
>= INT_MAX
- 1)
373 if (maxposs
< maxisol
)
377 TRACE("The path \""__ISOL_CPUS
"\" to read isolated cpus from does not exist");
380 if (file_exists(__OFFLINE_CPUS
)) {
381 offlinecpus
= read_file(__OFFLINE_CPUS
);
383 return log_error_errno(false, errno
, "Failed to read file \"%s\"", __OFFLINE_CPUS
);
385 if (isdigit(offlinecpus
[0])) {
386 /* Get maximum number of cpus found in offline cpuset. */
387 maxoffline
= get_max_cpus(offlinecpus
);
388 if (maxoffline
< 0 || maxoffline
>= INT_MAX
- 1)
392 if (maxposs
< maxoffline
)
393 maxposs
= maxoffline
;
396 TRACE("The path \""__OFFLINE_CPUS
"\" to read offline cpus from does not exist");
399 if ((maxisol
== 0) && (maxoffline
== 0)) {
400 cpulist
= move_ptr(posscpus
);
404 possmask
= lxc_cpumask(posscpus
, maxposs
);
406 return log_error_errno(false, errno
, "Failed to create cpumask for possible cpus");
409 isolmask
= lxc_cpumask(isolcpus
, maxposs
);
411 return log_error_errno(false, errno
, "Failed to create cpumask for isolated cpus");
414 if (maxoffline
> 0) {
415 offlinemask
= lxc_cpumask(offlinecpus
, maxposs
);
417 return log_error_errno(false, errno
, "Failed to create cpumask for offline cpus");
420 for (i
= 0; i
<= maxposs
; i
++) {
421 if ((isolmask
&& !is_set(i
, isolmask
)) ||
422 (offlinemask
&& !is_set(i
, offlinemask
)) ||
423 !is_set(i
, possmask
))
427 clear_bit(i
, possmask
);
431 cpulist
= lxc_cpumask_to_cpulist(possmask
, maxposs
);
432 TRACE("No isolated or offline cpus present in cpuset");
434 cpulist
= move_ptr(posscpus
);
435 TRACE("Removed isolated or offline cpus from cpuset");
438 return log_error_errno(false, errno
, "Failed to create cpu list");
441 if (!am_initialized
) {
442 ret
= lxc_write_openat(child_cgroup
, "cpuset.cpus", cpulist
, strlen(cpulist
));
444 return log_error_errno(false,
445 errno
, "Failed to write cpu list to \"%s/cpuset.cpus\"",
448 TRACE("Copied cpu settings of parent cgroup");
454 /* Copy contents of parent(@path)/@file to @path/@file */
455 static bool copy_parent_file(const char *parent_cgroup
,
456 const char *child_cgroup
, const char *file
)
458 __do_free
char *parent_file
= NULL
, *value
= NULL
;
462 parent_file
= must_make_path(parent_cgroup
, file
, NULL
);
463 len
= lxc_read_from_file(parent_file
, NULL
, 0);
465 return log_error_errno(false, errno
, "Failed to determine buffer size");
467 value
= must_realloc(NULL
, len
+ 1);
469 ret
= lxc_read_from_file(parent_file
, value
, len
);
471 return log_error_errno(false, errno
, "Failed to read from parent file \"%s\"", parent_file
);
473 ret
= lxc_write_openat(child_cgroup
, file
, value
, len
);
474 if (ret
< 0 && errno
!= EACCES
)
475 return log_error_errno(false, errno
, "Failed to write \"%s\" to file \"%s/%s\"",
476 value
, child_cgroup
, file
);
480 static inline bool is_unified_hierarchy(const struct hierarchy
*h
)
482 return h
->version
== CGROUP2_SUPER_MAGIC
;
486 * Initialize the cpuset hierarchy in first directory of @cgroup_leaf and set
487 * cgroup.clone_children so that children inherit settings. Since the
488 * h->base_path is populated by init or ourselves, we know it is already
491 * returns -1 on error, 0 when we didn't created a cgroup, 1 if we created a
494 static int cg_legacy_handle_cpuset_hierarchy(struct hierarchy
*h
,
495 const char *cgroup_leaf
)
497 __do_free
char *parent_cgroup
= NULL
, *child_cgroup
= NULL
, *dup
= NULL
;
498 __do_close
int cgroup_fd
= -EBADF
;
504 if (is_unified_hierarchy(h
))
507 if (!string_in_list(h
->controllers
, "cpuset"))
511 return ret_set_errno(-1, EINVAL
);
513 dup
= strdup(cgroup_leaf
);
515 return ret_set_errno(-1, ENOMEM
);
517 parent_cgroup
= must_make_path(h
->mountpoint
, h
->container_base_path
, NULL
);
520 leaf
+= strspn(leaf
, "/");
521 slash
= strchr(leaf
, '/');
524 child_cgroup
= must_make_path(parent_cgroup
, leaf
, NULL
);
529 ret
= mkdir(child_cgroup
, 0755);
532 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", child_cgroup
);
537 cgroup_fd
= lxc_open_dirfd(child_cgroup
);
541 ret
= lxc_readat(cgroup_fd
, "cgroup.clone_children", &v
, 1);
543 return log_error_errno(-1, errno
, "Failed to read file \"%s/cgroup.clone_children\"", child_cgroup
);
545 /* Make sure any isolated cpus are removed from cpuset.cpus. */
546 if (!cg_legacy_filter_and_set_cpus(parent_cgroup
, child_cgroup
, v
== '1'))
547 return log_error_errno(-1, errno
, "Failed to remove isolated cpus");
549 /* Already set for us by someone else. */
551 TRACE("\"cgroup.clone_children\" was already set to \"1\"");
553 /* copy parent's settings */
554 if (!copy_parent_file(parent_cgroup
, child_cgroup
, "cpuset.mems"))
555 return log_error_errno(-1, errno
, "Failed to copy \"cpuset.mems\" settings");
557 /* Set clone_children so children inherit our settings */
558 ret
= lxc_writeat(cgroup_fd
, "cgroup.clone_children", "1", 1);
560 return log_error_errno(-1, errno
, "Failed to write 1 to \"%s/cgroup.clone_children\"", child_cgroup
);
565 /* Given two null-terminated lists of strings, return true if any string is in
568 static bool controller_lists_intersect(char **l1
, char **l2
)
573 for (int i
= 0; l1
[i
]; i
++)
574 if (string_in_list(l2
, l1
[i
]))
580 /* For a null-terminated list of controllers @clist, return true if any of those
581 * controllers is already listed the null-terminated list of hierarchies @hlist.
582 * Realistically, if one is present, all must be present.
584 static bool controller_list_is_dup(struct hierarchy
**hlist
, char **clist
)
589 for (int i
= 0; hlist
[i
]; i
++)
590 if (controller_lists_intersect(hlist
[i
]->controllers
, clist
))
596 /* Return true if the controller @entry is found in the null-terminated list of
597 * hierarchies @hlist.
599 static bool controller_found(struct hierarchy
**hlist
, char *entry
)
604 for (int i
= 0; hlist
[i
]; i
++)
605 if (string_in_list(hlist
[i
]->controllers
, entry
))
611 /* Return true if all of the controllers which we require have been found. The
612 * required list is freezer and anything in lxc.cgroup.use.
614 static bool all_controllers_found(struct cgroup_ops
*ops
)
616 struct hierarchy
**hlist
;
618 if (!ops
->cgroup_use
)
621 hlist
= ops
->hierarchies
;
622 for (char **cur
= ops
->cgroup_use
; cur
&& *cur
; cur
++)
623 if (!controller_found(hlist
, *cur
))
624 return log_error(false, "No %s controller mountpoint found", *cur
);
629 /* Get the controllers from a mountinfo line There are other ways we could get
630 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
631 * could parse the mount options. But we simply assume that the mountpoint must
632 * be /sys/fs/cgroup/controller-list
634 static char **cg_hybrid_get_controllers(char **klist
, char **nlist
, char *line
,
637 /* The fourth field is /sys/fs/cgroup/comma-delimited-controller-list
638 * for legacy hierarchies.
640 __do_free_string_list
char **aret
= NULL
;
643 char *p
= line
, *sep
= ",";
645 for (i
= 0; i
< 4; i
++) {
652 /* Note, if we change how mountinfo works, then our caller will need to
653 * verify /sys/fs/cgroup/ in this field.
655 if (strncmp(p
, DEFAULT_CGROUP_MOUNTPOINT
"/", 15) != 0)
656 return log_error(NULL
, "Found hierarchy not under " DEFAULT_CGROUP_MOUNTPOINT
": \"%s\"", p
);
661 return log_error(NULL
, "Corrupt mountinfo");
664 if (type
== CGROUP_SUPER_MAGIC
) {
665 __do_free
char *dup
= NULL
;
667 /* strdup() here for v1 hierarchies. Otherwise
668 * lxc_iterate_parts() will destroy mountpoints such as
669 * "/sys/fs/cgroup/cpu,cpuacct".
671 dup
= must_copy_string(p
);
675 lxc_iterate_parts(tok
, dup
, sep
)
676 must_append_controller(klist
, nlist
, &aret
, tok
);
680 return move_ptr(aret
);
683 static char **cg_unified_make_empty_controller(void)
685 __do_free_string_list
char **aret
= NULL
;
688 newentry
= append_null_to_list((void ***)&aret
);
689 aret
[newentry
] = NULL
;
690 return move_ptr(aret
);
693 static char **cg_unified_get_controllers(const char *file
)
695 __do_free
char *buf
= NULL
;
696 __do_free_string_list
char **aret
= NULL
;
700 buf
= read_file(file
);
704 lxc_iterate_parts(tok
, buf
, sep
) {
708 newentry
= append_null_to_list((void ***)&aret
);
709 copy
= must_copy_string(tok
);
710 aret
[newentry
] = copy
;
713 return move_ptr(aret
);
716 static struct hierarchy
*add_hierarchy(struct hierarchy
***h
, char **clist
, char *mountpoint
,
717 char *container_base_path
, int type
)
719 struct hierarchy
*new;
722 new = zalloc(sizeof(*new));
723 new->controllers
= clist
;
724 new->mountpoint
= mountpoint
;
725 new->container_base_path
= container_base_path
;
727 new->cgfd_con
= -EBADF
;
728 new->cgfd_limit
= -EBADF
;
729 new->cgfd_mon
= -EBADF
;
731 newentry
= append_null_to_list((void ***)h
);
732 (*h
)[newentry
] = new;
736 /* Get a copy of the mountpoint from @line, which is a line from
737 * /proc/self/mountinfo.
739 static char *cg_hybrid_get_mountpoint(char *line
)
741 char *p
= line
, *sret
= NULL
;
745 for (int i
= 0; i
< 4; i
++) {
752 if (strncmp(p
, DEFAULT_CGROUP_MOUNTPOINT
"/", 15) != 0)
755 p2
= strchr(p
+ 15, ' ');
761 sret
= must_realloc(NULL
, len
+ 1);
762 memcpy(sret
, p
, len
);
768 /* Given a multi-line string, return a null-terminated copy of the current line. */
769 static char *copy_to_eol(char *p
)
774 p2
= strchr(p
, '\n');
779 sret
= must_realloc(NULL
, len
+ 1);
780 memcpy(sret
, p
, len
);
786 /* cgline: pointer to character after the first ':' in a line in a \n-terminated
787 * /proc/self/cgroup file. Check whether controller c is present.
789 static bool controller_in_clist(char *cgline
, char *c
)
791 __do_free
char *tmp
= NULL
;
795 eol
= strchr(cgline
, ':');
800 tmp
= must_realloc(NULL
, len
+ 1);
801 memcpy(tmp
, cgline
, len
);
804 lxc_iterate_parts(tok
, tmp
, ",")
805 if (strcmp(tok
, c
) == 0)
811 /* @basecginfo is a copy of /proc/$$/cgroup. Return the current cgroup for
814 static char *cg_hybrid_get_current_cgroup(char *basecginfo
, char *controller
,
817 char *p
= basecginfo
;
820 bool is_cgv2_base_cgroup
= false;
822 /* cgroup v2 entry in "/proc/<pid>/cgroup": "0::/some/path" */
823 if ((type
== CGROUP2_SUPER_MAGIC
) && (*p
== '0'))
824 is_cgv2_base_cgroup
= true;
831 if (is_cgv2_base_cgroup
|| (controller
&& controller_in_clist(p
, controller
))) {
836 return copy_to_eol(p
);
846 static void must_append_string(char ***list
, char *entry
)
851 newentry
= append_null_to_list((void ***)list
);
852 copy
= must_copy_string(entry
);
853 (*list
)[newentry
] = copy
;
856 static int get_existing_subsystems(char ***klist
, char ***nlist
)
858 __do_free
char *line
= NULL
;
859 __do_fclose
FILE *f
= NULL
;
862 f
= fopen("/proc/self/cgroup", "re");
866 while (getline(&line
, &len
, f
) != -1) {
868 p
= strchr(line
, ':');
877 /* If the kernel has cgroup v2 support, then /proc/self/cgroup
878 * contains an entry of the form:
882 * In this case we use "cgroup2" as controller name.
885 must_append_string(klist
, "cgroup2");
889 lxc_iterate_parts(tok
, p
, ",") {
890 if (strncmp(tok
, "name=", 5) == 0)
891 must_append_string(nlist
, tok
);
893 must_append_string(klist
, tok
);
900 static char *trim(char *s
)
905 while ((len
> 1) && (s
[len
- 1] == '\n'))
911 static void lxc_cgfsng_print_hierarchies(struct cgroup_ops
*ops
)
914 struct hierarchy
**it
;
916 if (!ops
->hierarchies
) {
917 TRACE(" No hierarchies found");
921 TRACE(" Hierarchies:");
922 for (i
= 0, it
= ops
->hierarchies
; it
&& *it
; it
++, i
++) {
926 TRACE(" %d: base_cgroup: %s", i
, (*it
)->container_base_path
? (*it
)->container_base_path
: "(null)");
927 TRACE(" mountpoint: %s", (*it
)->mountpoint
? (*it
)->mountpoint
: "(null)");
928 TRACE(" controllers:");
929 for (j
= 0, cit
= (*it
)->controllers
; cit
&& *cit
; cit
++, j
++)
930 TRACE(" %d: %s", j
, *cit
);
934 static void lxc_cgfsng_print_basecg_debuginfo(char *basecginfo
, char **klist
,
940 TRACE("basecginfo is:");
941 TRACE("%s", basecginfo
);
943 for (k
= 0, it
= klist
; it
&& *it
; it
++, k
++)
944 TRACE("kernel subsystem %d: %s", k
, *it
);
946 for (k
= 0, it
= nlist
; it
&& *it
; it
++, k
++)
947 TRACE("named subsystem %d: %s", k
, *it
);
950 static int cgroup_tree_remove(struct hierarchy
**hierarchies
,
951 const char *container_cgroup
)
953 if (!container_cgroup
|| !hierarchies
)
956 for (int i
= 0; hierarchies
[i
]; i
++) {
957 struct hierarchy
*h
= hierarchies
[i
];
960 if (!h
->container_limit_path
)
963 ret
= lxc_rm_rf(h
->container_limit_path
);
965 WARN("Failed to destroy \"%s\"", h
->container_limit_path
);
967 if (h
->container_limit_path
!= h
->container_full_path
)
968 free_disarm(h
->container_limit_path
);
969 free_disarm(h
->container_full_path
);
975 struct generic_userns_exec_data
{
976 struct hierarchy
**hierarchies
;
977 const char *container_cgroup
;
978 struct lxc_conf
*conf
;
979 uid_t origuid
; /* target uid in parent namespace */
983 static int cgroup_tree_remove_wrapper(void *data
)
985 struct generic_userns_exec_data
*arg
= data
;
986 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
987 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
990 if (!lxc_setgroups(0, NULL
) && errno
!= EPERM
)
991 return log_error_errno(-1, errno
, "Failed to setgroups(0, NULL)");
993 ret
= setresgid(nsgid
, nsgid
, nsgid
);
995 return log_error_errno(-1, errno
, "Failed to setresgid(%d, %d, %d)",
996 (int)nsgid
, (int)nsgid
, (int)nsgid
);
998 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1000 return log_error_errno(-1, errno
, "Failed to setresuid(%d, %d, %d)",
1001 (int)nsuid
, (int)nsuid
, (int)nsuid
);
1003 return cgroup_tree_remove(arg
->hierarchies
, arg
->container_cgroup
);
1006 __cgfsng_ops
static void cgfsng_payload_destroy(struct cgroup_ops
*ops
,
1007 struct lxc_handler
*handler
)
1012 ERROR("Called with uninitialized cgroup operations");
1016 if (!ops
->hierarchies
)
1020 ERROR("Called with uninitialized handler");
1024 if (!handler
->conf
) {
1025 ERROR("Called with uninitialized conf");
1029 #ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
1030 ret
= bpf_program_cgroup_detach(handler
->conf
->cgroup2_devices
);
1032 WARN("Failed to detach bpf program from cgroup");
1035 if (handler
->conf
&& !lxc_list_empty(&handler
->conf
->id_map
)) {
1036 struct generic_userns_exec_data wrap
= {
1037 .conf
= handler
->conf
,
1038 .container_cgroup
= ops
->container_cgroup
,
1039 .hierarchies
= ops
->hierarchies
,
1042 ret
= userns_exec_1(handler
->conf
, cgroup_tree_remove_wrapper
,
1043 &wrap
, "cgroup_tree_remove_wrapper");
1045 ret
= cgroup_tree_remove(ops
->hierarchies
, ops
->container_cgroup
);
1048 SYSWARN("Failed to destroy cgroups");
1051 __cgfsng_ops
static void cgfsng_monitor_destroy(struct cgroup_ops
*ops
,
1052 struct lxc_handler
*handler
)
1055 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1056 const struct lxc_conf
*conf
;
1059 ERROR("Called with uninitialized cgroup operations");
1063 if (!ops
->hierarchies
)
1067 ERROR("Called with uninitialized handler");
1071 if (!handler
->conf
) {
1072 ERROR("Called with uninitialized conf");
1075 conf
= handler
->conf
;
1077 len
= snprintf(pidstr
, sizeof(pidstr
), "%d", handler
->monitor_pid
);
1078 if (len
< 0 || (size_t)len
>= sizeof(pidstr
))
1081 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1082 __do_free
char *pivot_path
= NULL
;
1083 struct hierarchy
*h
= ops
->hierarchies
[i
];
1086 if (!h
->monitor_full_path
)
1089 /* Monitor might have died before we entered the cgroup. */
1090 if (handler
->monitor_pid
<= 0) {
1091 WARN("No valid monitor process found while destroying cgroups");
1095 if (conf
&& conf
->cgroup_meta
.monitor_dir
)
1096 pivot_path
= must_make_path(h
->mountpoint
,
1097 h
->container_base_path
,
1098 conf
->cgroup_meta
.monitor_dir
,
1099 CGROUP_PIVOT
, NULL
);
1100 else if (conf
&& conf
->cgroup_meta
.dir
)
1101 pivot_path
= must_make_path(h
->mountpoint
,
1102 h
->container_base_path
,
1103 conf
->cgroup_meta
.dir
,
1104 CGROUP_PIVOT
, NULL
);
1106 pivot_path
= must_make_path(h
->mountpoint
,
1107 h
->container_base_path
,
1108 CGROUP_PIVOT
, NULL
);
1110 ret
= mkdir_p(pivot_path
, 0755);
1111 if (ret
< 0 && errno
!= EEXIST
) {
1112 ERROR("Failed to create %s", pivot_path
);
1116 ret
= lxc_write_openat(pivot_path
, "cgroup.procs", pidstr
, len
);
1118 SYSWARN("Failed to move monitor %s to \"%s\"", pidstr
, pivot_path
);
1123 ret
= lxc_rm_rf(h
->monitor_full_path
);
1125 WARN("Failed to destroy \"%s\"", h
->monitor_full_path
);
1129 static int mkdir_eexist_on_last(const char *dir
, mode_t mode
)
1131 const char *tmp
= dir
;
1132 const char *orig
= dir
;
1135 orig_len
= strlen(dir
);
1137 __do_free
char *makeme
= NULL
;
1141 dir
= tmp
+ strspn(tmp
, "/");
1142 tmp
= dir
+ strcspn(dir
, "/");
1144 cur_len
= dir
- orig
;
1145 makeme
= strndup(orig
, cur_len
);
1147 return ret_set_errno(-1, ENOMEM
);
1149 ret
= mkdir(makeme
, mode
);
1150 if (ret
< 0 && ((errno
!= EEXIST
) || (orig_len
== cur_len
)))
1151 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", makeme
);
1152 } while (tmp
!= dir
);
1157 static bool cgroup_tree_create(struct cgroup_ops
*ops
, struct lxc_conf
*conf
,
1158 struct hierarchy
*h
, const char *cgroup_tree
,
1159 const char *cgroup_leaf
, bool payload
,
1160 const char *cgroup_limit_dir
)
1162 __do_free
char *path
= NULL
, *limit_path
= NULL
;
1163 int ret
, ret_cpuset
;
1165 path
= must_make_path(h
->mountpoint
, h
->container_base_path
, cgroup_leaf
, NULL
);
1166 if (dir_exists(path
))
1167 return log_warn_errno(false, errno
, "The %s cgroup already existed", path
);
1169 ret_cpuset
= cg_legacy_handle_cpuset_hierarchy(h
, cgroup_leaf
);
1171 return log_error_errno(false, errno
, "Failed to handle legacy cpuset controller");
1173 if (payload
&& cgroup_limit_dir
) {
1174 /* with isolation both parts need to not already exist */
1175 limit_path
= must_make_path(h
->mountpoint
,
1176 h
->container_base_path
,
1177 cgroup_limit_dir
, NULL
);
1179 ret
= mkdir_eexist_on_last(limit_path
, 0755);
1181 return log_error_errno(false, errno
,
1182 "Failed to create %s limiting cgroup",
1185 h
->cgfd_limit
= lxc_open_dirfd(limit_path
);
1186 if (h
->cgfd_limit
< 0)
1187 return log_error_errno(false, errno
,
1188 "Failed to open %s", path
);
1189 h
->container_limit_path
= move_ptr(limit_path
);
1192 * With isolation the devices legacy cgroup needs to be
1193 * iinitialized early, as it typically contains an 'a' (all)
1194 * line, which is not possible once a subdirectory has been
1197 if (string_in_list(h
->controllers
, "devices")) {
1198 ret
= ops
->setup_limits_legacy(ops
, conf
, true);
1204 ret
= mkdir_eexist_on_last(path
, 0755);
1207 * This is the cpuset controller and
1208 * cg_legacy_handle_cpuset_hierarchy() has created our target
1209 * directory for us to ensure correct initialization.
1211 if (ret_cpuset
!= 1 || cgroup_tree
)
1212 return log_error_errno(false, errno
, "Failed to create %s cgroup", path
);
1216 h
->cgfd_con
= lxc_open_dirfd(path
);
1217 if (h
->cgfd_con
< 0)
1218 return log_error_errno(false, errno
, "Failed to open %s", path
);
1219 h
->container_full_path
= move_ptr(path
);
1220 if (h
->cgfd_limit
< 0)
1221 h
->cgfd_limit
= h
->cgfd_con
;
1222 if (!h
->container_limit_path
)
1223 h
->container_limit_path
= h
->container_full_path
;
1225 h
->cgfd_mon
= lxc_open_dirfd(path
);
1226 if (h
->cgfd_mon
< 0)
1227 return log_error_errno(false, errno
, "Failed to open %s", path
);
1228 h
->monitor_full_path
= move_ptr(path
);
1234 static void cgroup_tree_leaf_remove(struct hierarchy
*h
, bool payload
)
1236 __do_free
char *full_path
= NULL
, *__limit_path
= NULL
;
1237 char *limit_path
= NULL
;
1240 __lxc_unused __do_close
int fd
= move_fd(h
->cgfd_con
);
1241 full_path
= move_ptr(h
->container_full_path
);
1242 limit_path
= move_ptr(h
->container_limit_path
);
1243 if (limit_path
!= full_path
)
1244 __limit_path
= limit_path
;
1246 __lxc_unused __do_close
int fd
= move_fd(h
->cgfd_mon
);
1247 full_path
= move_ptr(h
->monitor_full_path
);
1250 if (full_path
&& rmdir(full_path
))
1251 SYSWARN("Failed to rmdir(\"%s\") cgroup", full_path
);
1252 if (limit_path
&& rmdir(limit_path
))
1253 SYSWARN("Failed to rmdir(\"%s\") cgroup", limit_path
);
1257 * Check we have no lxc.cgroup.dir, and that lxc.cgroup.dir.limit_prefix is a
1258 * proper prefix directory of lxc.cgroup.dir.payload.
1260 * Returns the prefix length if it is set, otherwise zero on success.
1262 static bool check_cgroup_dir_config(struct lxc_conf
*conf
)
1264 const char *monitor_dir
= conf
->cgroup_meta
.monitor_dir
,
1265 *container_dir
= conf
->cgroup_meta
.container_dir
,
1266 *namespace_dir
= conf
->cgroup_meta
.namespace_dir
;
1268 /* none of the new options are set, all is fine */
1269 if (!monitor_dir
&& !container_dir
&& !namespace_dir
)
1272 /* some are set, make sure lxc.cgroup.dir is not also set*/
1273 if (conf
->cgroup_meta
.dir
)
1274 return log_error_errno(false, EINVAL
,
1275 "lxc.cgroup.dir conflicts with lxc.cgroup.dir.payload/monitor");
1277 /* make sure both monitor and payload are set */
1278 if (!monitor_dir
|| !container_dir
)
1279 return log_error_errno(false, EINVAL
,
1280 "lxc.cgroup.dir.payload and lxc.cgroup.dir.monitor must both be set");
1282 /* namespace_dir may be empty */
1286 __cgfsng_ops
static inline bool cgfsng_monitor_create(struct cgroup_ops
*ops
,
1287 struct lxc_handler
*handler
)
1289 __do_free
char *monitor_cgroup
= NULL
, *__cgroup_tree
= NULL
;
1290 const char *cgroup_tree
;
1294 char *suffix
= NULL
;
1295 struct lxc_conf
*conf
;
1298 return ret_set_errno(false, ENOENT
);
1300 if (!ops
->hierarchies
)
1303 if (ops
->monitor_cgroup
)
1304 return ret_set_errno(false, EEXIST
);
1306 if (!handler
|| !handler
->conf
)
1307 return ret_set_errno(false, EINVAL
);
1309 conf
= handler
->conf
;
1311 if (!check_cgroup_dir_config(conf
))
1314 if (conf
->cgroup_meta
.monitor_dir
) {
1316 monitor_cgroup
= strdup(conf
->cgroup_meta
.monitor_dir
);
1317 } else if (conf
->cgroup_meta
.dir
) {
1318 cgroup_tree
= conf
->cgroup_meta
.dir
;
1319 monitor_cgroup
= must_concat(&len
, conf
->cgroup_meta
.dir
, "/",
1320 DEFAULT_MONITOR_CGROUP_PREFIX
,
1322 CGROUP_CREATE_RETRY
, NULL
);
1323 } else if (ops
->cgroup_pattern
) {
1324 __cgroup_tree
= lxc_string_replace("%n", handler
->name
, ops
->cgroup_pattern
);
1326 return ret_set_errno(false, ENOMEM
);
1328 cgroup_tree
= __cgroup_tree
;
1329 monitor_cgroup
= must_concat(&len
, cgroup_tree
, "/",
1330 DEFAULT_MONITOR_CGROUP
,
1331 CGROUP_CREATE_RETRY
, NULL
);
1334 monitor_cgroup
= must_concat(&len
, DEFAULT_MONITOR_CGROUP_PREFIX
,
1336 CGROUP_CREATE_RETRY
, NULL
);
1338 if (!monitor_cgroup
)
1339 return ret_set_errno(false, ENOMEM
);
1341 if (!conf
->cgroup_meta
.monitor_dir
) {
1342 suffix
= monitor_cgroup
+ len
- CGROUP_CREATE_RETRY_LEN
;
1347 sprintf(suffix
, "-%d", idx
);
1349 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1350 if (cgroup_tree_create(ops
, handler
->conf
,
1351 ops
->hierarchies
[i
], cgroup_tree
,
1352 monitor_cgroup
, false, NULL
))
1355 ERROR("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->monitor_full_path
?: "(null)");
1356 for (int j
= 0; j
< i
; j
++)
1357 cgroup_tree_leaf_remove(ops
->hierarchies
[j
], false);
1362 } while (ops
->hierarchies
[i
] && idx
> 0 && idx
< 1000 && suffix
);
1364 if (idx
== 1000 || (!suffix
&& idx
!= 0))
1365 return ret_set_errno(false, ERANGE
);
1367 ops
->monitor_cgroup
= move_ptr(monitor_cgroup
);
1368 return log_info(true, "The monitor process uses \"%s\" as cgroup", ops
->monitor_cgroup
);
1372 * Try to create the same cgroup in all hierarchies. Start with cgroup_pattern;
1373 * next cgroup_pattern-1, -2, ..., -999.
1375 __cgfsng_ops
static inline bool cgfsng_payload_create(struct cgroup_ops
*ops
,
1376 struct lxc_handler
*handler
)
1378 __do_free
char *container_cgroup
= NULL
,
1379 *__cgroup_tree
= NULL
,
1380 *limiting_cgroup
= NULL
;
1381 const char *cgroup_tree
;
1385 char *suffix
= NULL
;
1386 struct lxc_conf
*conf
;
1389 return ret_set_errno(false, ENOENT
);
1391 if (!ops
->hierarchies
)
1394 if (ops
->container_cgroup
)
1395 return ret_set_errno(false, EEXIST
);
1397 if (!handler
|| !handler
->conf
)
1398 return ret_set_errno(false, EINVAL
);
1400 conf
= handler
->conf
;
1402 if (!check_cgroup_dir_config(conf
))
1405 if (conf
->cgroup_meta
.container_dir
) {
1408 limiting_cgroup
= strdup(conf
->cgroup_meta
.container_dir
);
1409 if (!limiting_cgroup
)
1410 return ret_set_errno(false, ENOMEM
);
1412 if (conf
->cgroup_meta
.namespace_dir
) {
1413 container_cgroup
= must_make_path(limiting_cgroup
,
1414 conf
->cgroup_meta
.namespace_dir
,
1417 /* explicit paths but without isolation */
1418 container_cgroup
= move_ptr(limiting_cgroup
);
1420 } else if (conf
->cgroup_meta
.dir
) {
1421 cgroup_tree
= conf
->cgroup_meta
.dir
;
1422 container_cgroup
= must_concat(&len
, cgroup_tree
, "/",
1423 DEFAULT_PAYLOAD_CGROUP_PREFIX
,
1425 CGROUP_CREATE_RETRY
, NULL
);
1426 } else if (ops
->cgroup_pattern
) {
1427 __cgroup_tree
= lxc_string_replace("%n", handler
->name
, ops
->cgroup_pattern
);
1429 return ret_set_errno(false, ENOMEM
);
1431 cgroup_tree
= __cgroup_tree
;
1432 container_cgroup
= must_concat(&len
, cgroup_tree
, "/",
1433 DEFAULT_PAYLOAD_CGROUP
,
1434 CGROUP_CREATE_RETRY
, NULL
);
1437 container_cgroup
= must_concat(&len
, DEFAULT_PAYLOAD_CGROUP_PREFIX
,
1439 CGROUP_CREATE_RETRY
, NULL
);
1441 if (!container_cgroup
)
1442 return ret_set_errno(false, ENOMEM
);
1444 if (!conf
->cgroup_meta
.container_dir
) {
1445 suffix
= container_cgroup
+ len
- CGROUP_CREATE_RETRY_LEN
;
1450 sprintf(suffix
, "-%d", idx
);
1452 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1453 if (cgroup_tree_create(ops
, handler
->conf
,
1454 ops
->hierarchies
[i
], cgroup_tree
,
1455 container_cgroup
, true,
1459 ERROR("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->container_full_path
?: "(null)");
1460 for (int j
= 0; j
< i
; j
++)
1461 cgroup_tree_leaf_remove(ops
->hierarchies
[j
], true);
1466 } while (ops
->hierarchies
[i
] && idx
> 0 && idx
< 1000 && suffix
);
1468 if (idx
== 1000 || (!suffix
&& idx
!= 0))
1469 return ret_set_errno(false, ERANGE
);
1471 ops
->container_cgroup
= move_ptr(container_cgroup
);
1472 INFO("The container process uses \"%s\" as cgroup", ops
->container_cgroup
);
1476 __cgfsng_ops
static bool cgfsng_monitor_enter(struct cgroup_ops
*ops
,
1477 struct lxc_handler
*handler
)
1479 int monitor_len
, transient_len
= 0;
1480 char monitor
[INTTYPE_TO_STRLEN(pid_t
)],
1481 transient
[INTTYPE_TO_STRLEN(pid_t
)];
1484 return ret_set_errno(false, ENOENT
);
1486 if (!ops
->hierarchies
)
1489 if (!ops
->monitor_cgroup
)
1490 return ret_set_errno(false, ENOENT
);
1492 if (!handler
|| !handler
->conf
)
1493 return ret_set_errno(false, EINVAL
);
1495 monitor_len
= snprintf(monitor
, sizeof(monitor
), "%d", handler
->monitor_pid
);
1496 if (handler
->transient_pid
> 0)
1497 transient_len
= snprintf(transient
, sizeof(transient
), "%d", handler
->transient_pid
);
1499 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1500 struct hierarchy
*h
= ops
->hierarchies
[i
];
1503 ret
= lxc_writeat(h
->cgfd_mon
, "cgroup.procs", monitor
, monitor_len
);
1505 return log_error_errno(false, errno
, "Failed to enter cgroup \"%s\"", h
->monitor_full_path
);
1507 if (handler
->transient_pid
<= 0)
1510 ret
= lxc_writeat(h
->cgfd_mon
, "cgroup.procs", transient
, transient_len
);
1512 return log_error_errno(false, errno
, "Failed to enter cgroup \"%s\"", h
->monitor_full_path
);
1515 * we don't keep the fds for non-unified hierarchies around
1516 * mainly because we don't make use of them anymore after the
1517 * core cgroup setup is done but also because there are quite a
1520 if (!is_unified_hierarchy(h
))
1521 close_prot_errno_disarm(h
->cgfd_mon
);
1523 handler
->transient_pid
= -1;
1528 __cgfsng_ops
static bool cgfsng_payload_enter(struct cgroup_ops
*ops
,
1529 struct lxc_handler
*handler
)
1532 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1535 return ret_set_errno(false, ENOENT
);
1537 if (!ops
->hierarchies
)
1540 if (!ops
->container_cgroup
)
1541 return ret_set_errno(false, ENOENT
);
1543 if (!handler
|| !handler
->conf
)
1544 return ret_set_errno(false, EINVAL
);
1546 len
= snprintf(pidstr
, sizeof(pidstr
), "%d", handler
->pid
);
1548 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1549 struct hierarchy
*h
= ops
->hierarchies
[i
];
1552 ret
= lxc_writeat(h
->cgfd_con
, "cgroup.procs", pidstr
, len
);
1554 return log_error_errno(false, errno
, "Failed to enter cgroup \"%s\"", h
->container_full_path
);
1560 static int fchowmodat(int dirfd
, const char *path
, uid_t chown_uid
,
1561 gid_t chown_gid
, mode_t chmod_mode
)
1565 ret
= fchownat(dirfd
, path
, chown_uid
, chown_gid
,
1566 AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
1568 return log_warn_errno(-1,
1569 errno
, "Failed to fchownat(%d, %s, %d, %d, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW )",
1570 dirfd
, path
, (int)chown_uid
,
1573 ret
= fchmodat(dirfd
, (*path
!= '\0') ? path
: ".", chmod_mode
, 0);
1575 return log_warn_errno(-1, errno
, "Failed to fchmodat(%d, %s, %d, AT_SYMLINK_NOFOLLOW)",
1576 dirfd
, path
, (int)chmod_mode
);
1581 /* chgrp the container cgroups to container group. We leave
1582 * the container owner as cgroup owner. So we must make the
1583 * directories 775 so that the container can create sub-cgroups.
1585 * Also chown the tasks and cgroup.procs files. Those may not
1586 * exist depending on kernel version.
1588 static int chown_cgroup_wrapper(void *data
)
1592 struct generic_userns_exec_data
*arg
= data
;
1593 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1594 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1596 if (!lxc_setgroups(0, NULL
) && errno
!= EPERM
)
1597 return log_error_errno(-1, errno
, "Failed to setgroups(0, NULL)");
1599 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1601 return log_error_errno(-1, errno
, "Failed to setresgid(%d, %d, %d)",
1602 (int)nsgid
, (int)nsgid
, (int)nsgid
);
1604 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1606 return log_error_errno(-1, errno
, "Failed to setresuid(%d, %d, %d)",
1607 (int)nsuid
, (int)nsuid
, (int)nsuid
);
1609 destuid
= get_ns_uid(arg
->origuid
);
1610 if (destuid
== LXC_INVALID_UID
)
1613 for (int i
= 0; arg
->hierarchies
[i
]; i
++) {
1614 int dirfd
= arg
->hierarchies
[i
]->cgfd_con
;
1616 (void)fchowmodat(dirfd
, "", destuid
, nsgid
, 0775);
1619 * Failures to chown() these are inconvenient but not
1620 * detrimental We leave these owned by the container launcher,
1621 * so that container root can write to the files to attach. We
1622 * chmod() them 664 so that container systemd can write to the
1623 * files (which systemd in wily insists on doing).
1626 if (arg
->hierarchies
[i
]->version
== CGROUP_SUPER_MAGIC
)
1627 (void)fchowmodat(dirfd
, "tasks", destuid
, nsgid
, 0664);
1629 (void)fchowmodat(dirfd
, "cgroup.procs", destuid
, nsgid
, 0664);
1631 if (arg
->hierarchies
[i
]->version
!= CGROUP2_SUPER_MAGIC
)
1634 for (char **p
= arg
->hierarchies
[i
]->cgroup2_chown
; p
&& *p
; p
++)
1635 (void)fchowmodat(dirfd
, *p
, destuid
, nsgid
, 0664);
1641 __cgfsng_ops
static bool cgfsng_chown(struct cgroup_ops
*ops
,
1642 struct lxc_conf
*conf
)
1644 struct generic_userns_exec_data wrap
;
1647 return ret_set_errno(false, ENOENT
);
1649 if (!ops
->hierarchies
)
1652 if (!ops
->container_cgroup
)
1653 return ret_set_errno(false, ENOENT
);
1656 return ret_set_errno(false, EINVAL
);
1658 if (lxc_list_empty(&conf
->id_map
))
1661 wrap
.origuid
= geteuid();
1663 wrap
.hierarchies
= ops
->hierarchies
;
1666 if (userns_exec_1(conf
, chown_cgroup_wrapper
, &wrap
, "chown_cgroup_wrapper") < 0)
1667 return log_error_errno(false, errno
, "Error requesting cgroup chown in new user namespace");
1672 __cgfsng_ops
void cgfsng_payload_finalize(struct cgroup_ops
*ops
)
1677 if (!ops
->hierarchies
)
1680 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1681 struct hierarchy
*h
= ops
->hierarchies
[i
];
1683 * we don't keep the fds for non-unified hierarchies around
1684 * mainly because we don't make use of them anymore after the
1685 * core cgroup setup is done but also because there are quite a
1688 if (!is_unified_hierarchy(h
))
1689 close_prot_errno_disarm(h
->cgfd_con
);
1693 /* cgroup-full:* is done, no need to create subdirs */
1694 static inline bool cg_mount_needs_subdirs(int type
)
1696 return !(type
>= LXC_AUTO_CGROUP_FULL_RO
);
1699 /* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
1700 * remount controller ro if needed and bindmount the cgroupfs onto
1701 * control/the/cg/path.
1703 static int cg_legacy_mount_controllers(int type
, struct hierarchy
*h
,
1704 char *controllerpath
, char *cgpath
,
1705 const char *container_cgroup
)
1707 __do_free
char *sourcepath
= NULL
;
1708 int ret
, remount_flags
;
1709 int flags
= MS_BIND
;
1711 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_MIXED
) {
1712 ret
= mount(controllerpath
, controllerpath
, "cgroup", MS_BIND
, NULL
);
1714 return log_error_errno(-1, errno
, "Failed to bind mount \"%s\" onto \"%s\"",
1715 controllerpath
, controllerpath
);
1717 remount_flags
= add_required_remount_flags(controllerpath
,
1719 flags
| MS_REMOUNT
);
1720 ret
= mount(controllerpath
, controllerpath
, "cgroup",
1721 remount_flags
| MS_REMOUNT
| MS_BIND
| MS_RDONLY
,
1724 return log_error_errno(-1, errno
, "Failed to remount \"%s\" ro", controllerpath
);
1726 INFO("Remounted %s read-only", controllerpath
);
1729 sourcepath
= must_make_path(h
->mountpoint
, h
->container_base_path
,
1730 container_cgroup
, NULL
);
1731 if (type
== LXC_AUTO_CGROUP_RO
)
1734 ret
= mount(sourcepath
, cgpath
, "cgroup", flags
, NULL
);
1736 return log_error_errno(-1, errno
, "Failed to mount \"%s\" onto \"%s\"",
1737 h
->controllers
[0], cgpath
);
1738 INFO("Mounted \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1740 if (flags
& MS_RDONLY
) {
1741 remount_flags
= add_required_remount_flags(sourcepath
, cgpath
,
1742 flags
| MS_REMOUNT
);
1743 ret
= mount(sourcepath
, cgpath
, "cgroup", remount_flags
, NULL
);
1745 return log_error_errno(-1, errno
, "Failed to remount \"%s\" ro", cgpath
);
1746 INFO("Remounted %s read-only", cgpath
);
1749 INFO("Completed second stage cgroup automounts for \"%s\"", cgpath
);
1753 /* __cg_mount_direct
1755 * Mount cgroup hierarchies directly without using bind-mounts. The main
1756 * uses-cases are mounting cgroup hierarchies in cgroup namespaces and mounting
1757 * cgroups for the LXC_AUTO_CGROUP_FULL option.
1759 static int __cg_mount_direct(int type
, struct hierarchy
*h
,
1760 const char *controllerpath
)
1762 __do_free
char *controllers
= NULL
;
1763 char *fstype
= "cgroup2";
1764 unsigned long flags
= 0;
1770 flags
|= MS_RELATIME
;
1772 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_FULL_RO
)
1775 if (h
->version
!= CGROUP2_SUPER_MAGIC
) {
1776 controllers
= lxc_string_join(",", (const char **)h
->controllers
, false);
1782 ret
= mount("cgroup", controllerpath
, fstype
, flags
, controllers
);
1784 return log_error_errno(-1, errno
, "Failed to mount \"%s\" with cgroup filesystem type %s",
1785 controllerpath
, fstype
);
1787 DEBUG("Mounted \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1791 static inline int cg_mount_in_cgroup_namespace(int type
, struct hierarchy
*h
,
1792 const char *controllerpath
)
1794 return __cg_mount_direct(type
, h
, controllerpath
);
1797 static inline int cg_mount_cgroup_full(int type
, struct hierarchy
*h
,
1798 const char *controllerpath
)
1800 if (type
< LXC_AUTO_CGROUP_FULL_RO
|| type
> LXC_AUTO_CGROUP_FULL_MIXED
)
1803 return __cg_mount_direct(type
, h
, controllerpath
);
1806 __cgfsng_ops
static bool cgfsng_mount(struct cgroup_ops
*ops
,
1807 struct lxc_handler
*handler
,
1808 const char *root
, int type
)
1810 __do_free
char *cgroup_root
= NULL
;
1811 bool has_cgns
= false, wants_force_mount
= false;
1815 return ret_set_errno(false, ENOENT
);
1817 if (!ops
->hierarchies
)
1820 if (!handler
|| !handler
->conf
)
1821 return ret_set_errno(false, EINVAL
);
1823 if ((type
& LXC_AUTO_CGROUP_MASK
) == 0)
1826 if (type
& LXC_AUTO_CGROUP_FORCE
) {
1827 type
&= ~LXC_AUTO_CGROUP_FORCE
;
1828 wants_force_mount
= true;
1831 if (!wants_force_mount
){
1832 if (!lxc_list_empty(&handler
->conf
->keepcaps
))
1833 wants_force_mount
= !in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->keepcaps
);
1835 wants_force_mount
= in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->caps
);
1838 has_cgns
= cgns_supported();
1839 if (has_cgns
&& !wants_force_mount
)
1842 if (type
== LXC_AUTO_CGROUP_NOSPEC
)
1843 type
= LXC_AUTO_CGROUP_MIXED
;
1844 else if (type
== LXC_AUTO_CGROUP_FULL_NOSPEC
)
1845 type
= LXC_AUTO_CGROUP_FULL_MIXED
;
1847 cgroup_root
= must_make_path(root
, DEFAULT_CGROUP_MOUNTPOINT
, NULL
);
1848 if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNIFIED
) {
1849 if (has_cgns
&& wants_force_mount
) {
1851 * If cgroup namespaces are supported but the container
1852 * will not have CAP_SYS_ADMIN after it has started we
1853 * need to mount the cgroups manually.
1855 return cg_mount_in_cgroup_namespace(type
, ops
->unified
, cgroup_root
) == 0;
1858 return cg_mount_cgroup_full(type
, ops
->unified
, cgroup_root
) == 0;
1862 ret
= safe_mount(NULL
, cgroup_root
, "tmpfs",
1863 MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
1864 "size=10240k,mode=755", root
);
1868 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1869 __do_free
char *controllerpath
= NULL
, *path2
= NULL
;
1870 struct hierarchy
*h
= ops
->hierarchies
[i
];
1871 char *controller
= strrchr(h
->mountpoint
, '/');
1877 controllerpath
= must_make_path(cgroup_root
, controller
, NULL
);
1878 if (dir_exists(controllerpath
))
1881 ret
= mkdir(controllerpath
, 0755);
1883 return log_error_errno(false, errno
, "Error creating cgroup path: %s", controllerpath
);
1885 if (has_cgns
&& wants_force_mount
) {
1886 /* If cgroup namespaces are supported but the container
1887 * will not have CAP_SYS_ADMIN after it has started we
1888 * need to mount the cgroups manually.
1890 ret
= cg_mount_in_cgroup_namespace(type
, h
, controllerpath
);
1897 ret
= cg_mount_cgroup_full(type
, h
, controllerpath
);
1901 if (!cg_mount_needs_subdirs(type
))
1904 path2
= must_make_path(controllerpath
, h
->container_base_path
,
1905 ops
->container_cgroup
, NULL
);
1906 ret
= mkdir_p(path2
, 0755);
1910 ret
= cg_legacy_mount_controllers(type
, h
, controllerpath
,
1911 path2
, ops
->container_cgroup
);
1919 /* Only root needs to escape to the cgroup of its init. */
1920 __cgfsng_ops
static bool cgfsng_escape(const struct cgroup_ops
*ops
,
1921 struct lxc_conf
*conf
)
1924 return ret_set_errno(false, ENOENT
);
1926 if (!ops
->hierarchies
)
1930 return ret_set_errno(false, EINVAL
);
1932 if (conf
->cgroup_meta
.relative
|| geteuid())
1935 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1936 __do_free
char *fullpath
= NULL
;
1940 must_make_path(ops
->hierarchies
[i
]->mountpoint
,
1941 ops
->hierarchies
[i
]->container_base_path
,
1942 "cgroup.procs", NULL
);
1943 ret
= lxc_write_to_file(fullpath
, "0", 2, false, 0666);
1945 return log_error_errno(false, errno
, "Failed to escape to cgroup \"%s\"", fullpath
);
1951 __cgfsng_ops
static int cgfsng_num_hierarchies(struct cgroup_ops
*ops
)
1956 return ret_set_errno(-1, ENOENT
);
1958 if (!ops
->hierarchies
)
1961 for (; ops
->hierarchies
[i
]; i
++)
1967 __cgfsng_ops
static bool cgfsng_get_hierarchies(struct cgroup_ops
*ops
, int n
,
1973 return ret_set_errno(false, ENOENT
);
1975 if (!ops
->hierarchies
)
1976 return ret_set_errno(false, ENOENT
);
1978 /* sanity check n */
1979 for (i
= 0; i
< n
; i
++)
1980 if (!ops
->hierarchies
[i
])
1981 return ret_set_errno(false, ENOENT
);
1983 *out
= ops
->hierarchies
[i
]->controllers
;
1988 static bool cg_legacy_freeze(struct cgroup_ops
*ops
)
1990 struct hierarchy
*h
;
1992 h
= get_hierarchy(ops
, "freezer");
1994 return ret_set_errno(-1, ENOENT
);
1996 return lxc_write_openat(h
->container_full_path
, "freezer.state",
1997 "FROZEN", STRLITERALLEN("FROZEN"));
2000 static int freezer_cgroup_events_cb(int fd
, uint32_t events
, void *cbdata
,
2001 struct lxc_epoll_descr
*descr
)
2003 __do_close
int duped_fd
= -EBADF
;
2004 __do_free
char *line
= NULL
;
2005 __do_fclose
FILE *f
= NULL
;
2006 int state
= PTR_TO_INT(cbdata
);
2008 const char *state_string
;
2012 return LXC_MAINLOOP_ERROR
;
2014 if (lseek(duped_fd
, 0, SEEK_SET
) < (off_t
)-1)
2015 return LXC_MAINLOOP_ERROR
;
2017 f
= fdopen(duped_fd
, "re");
2019 return LXC_MAINLOOP_ERROR
;
2023 state_string
= "frozen 1";
2025 state_string
= "frozen 0";
2027 while (getline(&line
, &len
, f
) != -1)
2028 if (strncmp(line
, state_string
, STRLITERALLEN("frozen") + 2) == 0)
2029 return LXC_MAINLOOP_CLOSE
;
2031 return LXC_MAINLOOP_CONTINUE
;
2034 static int cg_unified_freeze(struct cgroup_ops
*ops
, int timeout
)
2036 __do_close
int fd
= -EBADF
;
2037 call_cleaner(lxc_mainloop_close
) struct lxc_epoll_descr
*descr_ptr
= NULL
;
2039 struct lxc_epoll_descr descr
;
2040 struct hierarchy
*h
;
2044 return ret_set_errno(-1, ENOENT
);
2046 if (!h
->container_full_path
)
2047 return ret_set_errno(-1, EEXIST
);
2050 __do_free
char *events_file
= NULL
;
2052 events_file
= must_make_path(h
->container_full_path
, "cgroup.events", NULL
);
2053 fd
= open(events_file
, O_RDONLY
| O_CLOEXEC
);
2055 return log_error_errno(-1, errno
, "Failed to open cgroup.events file");
2057 ret
= lxc_mainloop_open(&descr
);
2059 return log_error_errno(-1, errno
, "Failed to create epoll instance to wait for container freeze");
2061 /* automatically cleaned up now */
2064 ret
= lxc_mainloop_add_handler(&descr
, fd
, freezer_cgroup_events_cb
, INT_TO_PTR((int){1}));
2066 return log_error_errno(-1, errno
, "Failed to add cgroup.events fd handler to mainloop");
2069 ret
= lxc_write_openat(h
->container_full_path
, "cgroup.freeze", "1", 1);
2071 return log_error_errno(-1, errno
, "Failed to open cgroup.freeze file");
2073 if (timeout
!= 0 && lxc_mainloop(&descr
, timeout
))
2074 return log_error_errno(-1, errno
, "Failed to wait for container to be frozen");
2079 __cgfsng_ops
static int cgfsng_freeze(struct cgroup_ops
*ops
, int timeout
)
2081 if (!ops
->hierarchies
)
2082 return ret_set_errno(-1, ENOENT
);
2084 if (ops
->cgroup_layout
!= CGROUP_LAYOUT_UNIFIED
)
2085 return cg_legacy_freeze(ops
);
2087 return cg_unified_freeze(ops
, timeout
);
2090 static int cg_legacy_unfreeze(struct cgroup_ops
*ops
)
2092 struct hierarchy
*h
;
2094 h
= get_hierarchy(ops
, "freezer");
2096 return ret_set_errno(-1, ENOENT
);
2098 return lxc_write_openat(h
->container_full_path
, "freezer.state",
2099 "THAWED", STRLITERALLEN("THAWED"));
2102 static int cg_unified_unfreeze(struct cgroup_ops
*ops
, int timeout
)
2104 __do_close
int fd
= -EBADF
;
2105 call_cleaner(lxc_mainloop_close
)struct lxc_epoll_descr
*descr_ptr
= NULL
;
2107 struct lxc_epoll_descr descr
;
2108 struct hierarchy
*h
;
2112 return ret_set_errno(-1, ENOENT
);
2114 if (!h
->container_full_path
)
2115 return ret_set_errno(-1, EEXIST
);
2118 __do_free
char *events_file
= NULL
;
2120 events_file
= must_make_path(h
->container_full_path
, "cgroup.events", NULL
);
2121 fd
= open(events_file
, O_RDONLY
| O_CLOEXEC
);
2123 return log_error_errno(-1, errno
, "Failed to open cgroup.events file");
2125 ret
= lxc_mainloop_open(&descr
);
2127 return log_error_errno(-1, errno
, "Failed to create epoll instance to wait for container unfreeze");
2129 /* automatically cleaned up now */
2132 ret
= lxc_mainloop_add_handler(&descr
, fd
, freezer_cgroup_events_cb
, INT_TO_PTR((int){0}));
2134 return log_error_errno(-1, errno
, "Failed to add cgroup.events fd handler to mainloop");
2137 ret
= lxc_write_openat(h
->container_full_path
, "cgroup.freeze", "0", 1);
2139 return log_error_errno(-1, errno
, "Failed to open cgroup.freeze file");
2141 if (timeout
!= 0 && lxc_mainloop(&descr
, timeout
))
2142 return log_error_errno(-1, errno
, "Failed to wait for container to be unfrozen");
2147 __cgfsng_ops
static int cgfsng_unfreeze(struct cgroup_ops
*ops
, int timeout
)
2149 if (!ops
->hierarchies
)
2150 return ret_set_errno(-1, ENOENT
);
2152 if (ops
->cgroup_layout
!= CGROUP_LAYOUT_UNIFIED
)
2153 return cg_legacy_unfreeze(ops
);
2155 return cg_unified_unfreeze(ops
, timeout
);
2158 static const char *cgfsng_get_cgroup_do(struct cgroup_ops
*ops
,
2159 const char *controller
, bool limiting
)
2161 struct hierarchy
*h
;
2163 h
= get_hierarchy(ops
, controller
);
2165 return log_warn_errno(NULL
, ENOENT
, "Failed to find hierarchy for controller \"%s\"",
2166 controller
? controller
: "(null)");
2169 return h
->container_limit_path
2170 ? h
->container_limit_path
+ strlen(h
->mountpoint
)
2173 return h
->container_full_path
2174 ? h
->container_full_path
+ strlen(h
->mountpoint
)
2178 __cgfsng_ops
static const char *cgfsng_get_cgroup(struct cgroup_ops
*ops
,
2179 const char *controller
)
2181 return cgfsng_get_cgroup_do(ops
, controller
, false);
2184 __cgfsng_ops
static const char *cgfsng_get_limiting_cgroup(struct cgroup_ops
*ops
,
2185 const char *controller
)
2187 return cgfsng_get_cgroup_do(ops
, controller
, true);
2190 /* Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a full path,
2191 * which must be freed by the caller.
2193 static inline char *build_full_cgpath_from_monitorpath(struct hierarchy
*h
,
2195 const char *filename
)
2197 return must_make_path(h
->mountpoint
, inpath
, filename
, NULL
);
2200 static int cgroup_attach_leaf(const struct lxc_conf
*conf
, int unified_fd
, pid_t pid
)
2204 char pidstr
[INTTYPE_TO_STRLEN(int64_t) + 1];
2207 /* Create leaf cgroup. */
2208 ret
= mkdirat(unified_fd
, ".lxc", 0755);
2209 if (ret
< 0 && errno
!= EEXIST
)
2210 return log_error_errno(-1, errno
, "Failed to create leaf cgroup \".lxc\"");
2212 pidstr_len
= sprintf(pidstr
, INT64_FMT
, (int64_t)pid
);
2213 ret
= lxc_writeat(unified_fd
, ".lxc/cgroup.procs", pidstr
, pidstr_len
);
2215 ret
= lxc_writeat(unified_fd
, "cgroup.procs", pidstr
, pidstr_len
);
2219 /* this is a non-leaf node */
2221 return log_error_errno(-1, errno
, "Failed to attach to unified cgroup");
2225 char attach_cgroup
[STRLITERALLEN(".lxc-1000/cgroup.procs") + 1];
2228 ret
= snprintf(attach_cgroup
, sizeof(attach_cgroup
), ".lxc-%d/cgroup.procs", idx
);
2229 if (ret
< 0 || (size_t)ret
>= sizeof(attach_cgroup
))
2230 return ret_errno(EIO
);
2232 slash
= &attach_cgroup
[ret
] - STRLITERALLEN("/cgroup.procs");
2235 ret
= mkdirat(unified_fd
, attach_cgroup
, 0755);
2236 if (ret
< 0 && errno
!= EEXIST
)
2237 return log_error_errno(-1, errno
, "Failed to create cgroup %s", attach_cgroup
);
2243 ret
= lxc_writeat(unified_fd
, attach_cgroup
, pidstr
, pidstr_len
);
2247 if (rm
&& unlinkat(unified_fd
, attach_cgroup
, AT_REMOVEDIR
))
2248 SYSERROR("Failed to remove cgroup \"%d(%s)\"", unified_fd
, attach_cgroup
);
2250 /* this is a non-leaf node */
2252 return log_error_errno(-1, errno
, "Failed to attach to unified cgroup");
2255 } while (idx
< 1000);
2257 return log_error_errno(-1, errno
, "Failed to attach to unified cgroup");
2260 static int cgroup_attach_create_leaf(const struct lxc_conf
*conf
,
2261 int unified_fd
, int *sk_fd
)
2263 __do_close
int sk
= *sk_fd
, target_fd0
= -EBADF
, target_fd1
= -EBADF
;
2267 /* Create leaf cgroup. */
2268 ret
= mkdirat(unified_fd
, ".lxc", 0755);
2269 if (ret
< 0 && errno
!= EEXIST
)
2270 return log_error_errno(-1, errno
, "Failed to create leaf cgroup \".lxc\"");
2272 target_fd0
= openat(unified_fd
, ".lxc/cgroup.procs", O_WRONLY
| O_CLOEXEC
| O_NOFOLLOW
);
2274 return log_error_errno(-errno
, errno
, "Failed to open \".lxc/cgroup.procs\"");
2275 target_fds
[0] = target_fd0
;
2277 target_fd1
= openat(unified_fd
, "cgroup.procs", O_WRONLY
| O_CLOEXEC
| O_NOFOLLOW
);
2279 return log_error_errno(-errno
, errno
, "Failed to open \".lxc/cgroup.procs\"");
2280 target_fds
[1] = target_fd1
;
2282 ret
= lxc_abstract_unix_send_fds(sk
, target_fds
, 2, NULL
, 0);
2284 return log_error_errno(-errno
, errno
, "Failed to send \".lxc/cgroup.procs\" fds %d and %d",
2285 target_fd0
, target_fd1
);
2287 return log_debug(0, "Sent target cgroup fds %d and %d", target_fd0
, target_fd1
);
2290 static int cgroup_attach_move_into_leaf(const struct lxc_conf
*conf
,
2291 int *sk_fd
, pid_t pid
)
2293 __do_close
int sk
= *sk_fd
, target_fd0
= -EBADF
, target_fd1
= -EBADF
;
2295 char pidstr
[INTTYPE_TO_STRLEN(int64_t) + 1];
2299 ret
= lxc_abstract_unix_recv_fds(sk
, target_fds
, 2, NULL
, 0);
2301 return log_error_errno(-1, errno
, "Failed to receive target cgroup fd");
2302 target_fd0
= target_fds
[0];
2303 target_fd1
= target_fds
[1];
2305 pidstr_len
= sprintf(pidstr
, INT64_FMT
, (int64_t)pid
);
2307 ret
= lxc_write_nointr(target_fd0
, pidstr
, pidstr_len
);
2308 if (ret
> 0 && ret
== pidstr_len
)
2309 return log_debug(0, "Moved process into target cgroup via fd %d", target_fd0
);
2311 ret
= lxc_write_nointr(target_fd1
, pidstr
, pidstr_len
);
2312 if (ret
> 0 && ret
== pidstr_len
)
2313 return log_debug(0, "Moved process into target cgroup via fd %d", target_fd1
);
2315 return log_debug_errno(-1, errno
, "Failed to move process into target cgroup via fd %d and %d",
2316 target_fd0
, target_fd1
);
2319 struct userns_exec_unified_attach_data
{
2320 const struct lxc_conf
*conf
;
2326 static int cgroup_unified_attach_child_wrapper(void *data
)
2328 struct userns_exec_unified_attach_data
*args
= data
;
2330 if (!args
->conf
|| args
->unified_fd
< 0 || args
->pid
<= 0 ||
2331 args
->sk_pair
[0] < 0 || args
->sk_pair
[1] < 0)
2332 return ret_errno(EINVAL
);
2334 close_prot_errno_disarm(args
->sk_pair
[0]);
2335 return cgroup_attach_create_leaf(args
->conf
, args
->unified_fd
,
2339 static int cgroup_unified_attach_parent_wrapper(void *data
)
2341 struct userns_exec_unified_attach_data
*args
= data
;
2343 if (!args
->conf
|| args
->unified_fd
< 0 || args
->pid
<= 0 ||
2344 args
->sk_pair
[0] < 0 || args
->sk_pair
[1] < 0)
2345 return ret_errno(EINVAL
);
2347 close_prot_errno_disarm(args
->sk_pair
[1]);
2348 return cgroup_attach_move_into_leaf(args
->conf
, &args
->sk_pair
[0],
2352 int cgroup_attach(const struct lxc_conf
*conf
, const char *name
,
2353 const char *lxcpath
, pid_t pid
)
2355 __do_close
int unified_fd
= -EBADF
;
2358 if (!conf
|| !name
|| !lxcpath
|| pid
<= 0)
2359 return ret_errno(EINVAL
);
2361 unified_fd
= lxc_cmd_get_cgroup2_fd(name
, lxcpath
);
2363 return ret_errno(EBADF
);
2365 if (!lxc_list_empty(&conf
->id_map
)) {
2366 struct userns_exec_unified_attach_data args
= {
2368 .unified_fd
= unified_fd
,
2372 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, args
.sk_pair
);
2376 ret
= userns_exec_minimal(conf
,
2377 cgroup_unified_attach_parent_wrapper
,
2379 cgroup_unified_attach_child_wrapper
,
2382 ret
= cgroup_attach_leaf(conf
, unified_fd
, pid
);
2388 /* Technically, we're always at a delegation boundary here (This is especially
2389 * true when cgroup namespaces are available.). The reasoning is that in order
2390 * for us to have been able to start a container in the first place the root
2391 * cgroup must have been a leaf node. Now, either the container's init system
2392 * has populated the cgroup and kept it as a leaf node or it has created
2393 * subtrees. In the former case we will simply attach to the leaf node we
2394 * created when we started the container in the latter case we create our own
2395 * cgroup for the attaching process.
2397 static int __cg_unified_attach(const struct hierarchy
*h
,
2398 const struct lxc_conf
*conf
, const char *name
,
2399 const char *lxcpath
, pid_t pid
,
2400 const char *controller
)
2402 __do_close
int unified_fd
= -EBADF
;
2403 __do_free
char *path
= NULL
, *cgroup
= NULL
;
2406 if (!conf
|| !name
|| !lxcpath
|| pid
<= 0)
2407 return ret_errno(EINVAL
);
2409 ret
= cgroup_attach(conf
, name
, lxcpath
, pid
);
2411 return log_trace(0, "Attached to unified cgroup via command handler");
2413 return log_error_errno(ret
, errno
, "Failed to attach to unified cgroup");
2415 /* Fall back to retrieving the path for the unified cgroup. */
2416 cgroup
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2421 path
= must_make_path(h
->mountpoint
, cgroup
, NULL
);
2423 unified_fd
= open(path
, O_PATH
| O_DIRECTORY
| O_CLOEXEC
);
2425 return ret_errno(EBADF
);
2427 if (!lxc_list_empty(&conf
->id_map
)) {
2428 struct userns_exec_unified_attach_data args
= {
2430 .unified_fd
= unified_fd
,
2434 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, args
.sk_pair
);
2438 ret
= userns_exec_minimal(conf
,
2439 cgroup_unified_attach_parent_wrapper
,
2441 cgroup_unified_attach_child_wrapper
,
2444 ret
= cgroup_attach_leaf(conf
, unified_fd
, pid
);
2450 __cgfsng_ops
static bool cgfsng_attach(struct cgroup_ops
*ops
,
2451 const struct lxc_conf
*conf
,
2452 const char *name
, const char *lxcpath
,
2456 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
2459 return ret_set_errno(false, ENOENT
);
2461 if (!ops
->hierarchies
)
2464 len
= snprintf(pidstr
, sizeof(pidstr
), "%d", pid
);
2465 if (len
< 0 || (size_t)len
>= sizeof(pidstr
))
2468 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
2469 __do_free
char *fullpath
= NULL
, *path
= NULL
;
2470 struct hierarchy
*h
= ops
->hierarchies
[i
];
2472 if (h
->version
== CGROUP2_SUPER_MAGIC
) {
2473 ret
= __cg_unified_attach(h
, conf
, name
, lxcpath
, pid
,
2481 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, h
->controllers
[0]);
2486 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, "cgroup.procs");
2487 ret
= lxc_write_to_file(fullpath
, pidstr
, len
, false, 0666);
2489 return log_error_errno(false, errno
, "Failed to attach %d to %s",
2490 (int)pid
, fullpath
);
2496 /* Called externally (i.e. from 'lxc-cgroup') to query cgroup limits. Here we
2497 * don't have a cgroup_data set up, so we ask the running container through the
2498 * commands API for the cgroup path.
2500 __cgfsng_ops
static int cgfsng_get(struct cgroup_ops
*ops
, const char *filename
,
2501 char *value
, size_t len
, const char *name
,
2502 const char *lxcpath
)
2504 __do_free
char *path
= NULL
;
2505 __do_free
char *controller
= NULL
;
2507 struct hierarchy
*h
;
2511 return ret_set_errno(-1, ENOENT
);
2513 controller
= must_copy_string(filename
);
2514 p
= strchr(controller
, '.');
2518 path
= lxc_cmd_get_limiting_cgroup_path(name
, lxcpath
, controller
);
2523 h
= get_hierarchy(ops
, controller
);
2525 __do_free
char *fullpath
= NULL
;
2527 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2528 ret
= lxc_read_from_file(fullpath
, value
, len
);
2534 static int device_cgroup_parse_access(struct device_item
*device
, const char *val
)
2536 for (int count
= 0; count
< 3; count
++, val
++) {
2539 device
->access
[count
] = *val
;
2542 device
->access
[count
] = *val
;
2545 device
->access
[count
] = *val
;
2552 return ret_errno(EINVAL
);
2559 static int device_cgroup_rule_parse(struct device_item
*device
, const char *key
,
2565 if (strcmp("devices.allow", key
) == 0)
2570 if (strcmp(val
, "a") == 0) {
2575 device
->global_rule
= device
->allow
2576 ? LXC_BPF_DEVICE_CGROUP_BLACKLIST
2577 : LXC_BPF_DEVICE_CGROUP_WHITELIST
;
2583 device
->global_rule
= LXC_BPF_DEVICE_CGROUP_LOCAL_RULE
;
2591 device
->type
= *val
;
2604 } else if (isdigit(*val
)) {
2605 memset(temp
, 0, sizeof(temp
));
2606 for (count
= 0; count
< sizeof(temp
) - 1; count
++) {
2612 ret
= lxc_safe_int(temp
, &device
->major
);
2626 } else if (isdigit(*val
)) {
2627 memset(temp
, 0, sizeof(temp
));
2628 for (count
= 0; count
< sizeof(temp
) - 1; count
++) {
2634 ret
= lxc_safe_int(temp
, &device
->minor
);
2643 return device_cgroup_parse_access(device
, ++val
);
2646 /* Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits. Here we
2647 * don't have a cgroup_data set up, so we ask the running container through the
2648 * commands API for the cgroup path.
2650 __cgfsng_ops
static int cgfsng_set(struct cgroup_ops
*ops
,
2651 const char *key
, const char *value
,
2652 const char *name
, const char *lxcpath
)
2654 __do_free
char *path
= NULL
;
2655 __do_free
char *controller
= NULL
;
2657 struct hierarchy
*h
;
2661 return ret_set_errno(-1, ENOENT
);
2663 controller
= must_copy_string(key
);
2664 p
= strchr(controller
, '.');
2668 if (pure_unified_layout(ops
) && strcmp(controller
, "devices") == 0) {
2669 struct device_item device
= {0};
2671 ret
= device_cgroup_rule_parse(&device
, key
, value
);
2673 return log_error_errno(-1, EINVAL
, "Failed to parse device string %s=%s",
2676 ret
= lxc_cmd_add_bpf_device_cgroup(name
, lxcpath
, &device
);
2683 path
= lxc_cmd_get_limiting_cgroup_path(name
, lxcpath
, controller
);
2688 h
= get_hierarchy(ops
, controller
);
2690 __do_free
char *fullpath
= NULL
;
2692 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, key
);
2693 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2699 /* take devices cgroup line
2701 * and convert it to a valid
2702 * type major:minor mode
2703 * line. Return <0 on error. Dest is a preallocated buffer long enough to hold
2706 static int device_cgroup_rule_parse_devpath(struct device_item
*device
,
2707 const char *devpath
)
2709 __do_free
char *path
= NULL
;
2715 path
= must_copy_string(devpath
);
2718 * Read path followed by mode. Ignore any trailing text.
2719 * A ' # comment' would be legal. Technically other text is not
2720 * legal, we could check for that if we cared to.
2722 for (n_parts
= 1, p
= path
; *p
; p
++) {
2738 return ret_set_errno(-1, EINVAL
);
2741 if (device_cgroup_parse_access(device
, mode
) < 0)
2745 return ret_set_errno(-1, EINVAL
);
2747 ret
= stat(path
, &sb
);
2749 return ret_set_errno(-1, errno
);
2751 mode_t m
= sb
.st_mode
& S_IFMT
;
2760 return log_error_errno(-1, EINVAL
, "Unsupported device type %i for \"%s\"", m
, path
);
2763 device
->major
= MAJOR(sb
.st_rdev
);
2764 device
->minor
= MINOR(sb
.st_rdev
);
2766 device
->global_rule
= LXC_BPF_DEVICE_CGROUP_LOCAL_RULE
;
2771 static int convert_devpath(const char *invalue
, char *dest
)
2773 struct device_item device
= {0};
2776 ret
= device_cgroup_rule_parse_devpath(&device
, invalue
);
2780 ret
= snprintf(dest
, 50, "%c %d:%d %s", device
.type
, device
.major
,
2781 device
.minor
, device
.access
);
2782 if (ret
< 0 || ret
>= 50)
2783 return log_error_errno(-1, ENAMETOOLONG
, "Error on configuration value \"%c %d:%d %s\" (max 50 chars)",
2784 device
.type
, device
.major
, device
.minor
, device
.access
);
2789 /* Called from setup_limits - here we have the container's cgroup_data because
2790 * we created the cgroups.
2792 static int cg_legacy_set_data(struct cgroup_ops
*ops
, const char *filename
,
2793 const char *value
, bool is_cpuset
)
2795 __do_free
char *controller
= NULL
;
2797 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2798 char converted_value
[50];
2799 struct hierarchy
*h
;
2801 controller
= must_copy_string(filename
);
2802 p
= strchr(controller
, '.');
2806 if (strcmp("devices.allow", filename
) == 0 && value
[0] == '/') {
2809 ret
= convert_devpath(value
, converted_value
);
2812 value
= converted_value
;
2815 h
= get_hierarchy(ops
, controller
);
2817 return log_error_errno(-ENOENT
, ENOENT
, "Failed to setup limits for the \"%s\" controller. The controller seems to be unused by \"cgfsng\" cgroup driver or not enabled on the cgroup hierarchy", controller
);
2820 int ret
= lxc_write_openat(h
->container_full_path
, filename
, value
, strlen(value
));
2824 return lxc_write_openat(h
->container_limit_path
, filename
, value
, strlen(value
));
2827 __cgfsng_ops
static bool cgfsng_setup_limits_legacy(struct cgroup_ops
*ops
,
2828 struct lxc_conf
*conf
,
2831 __do_free
struct lxc_list
*sorted_cgroup_settings
= NULL
;
2832 struct lxc_list
*cgroup_settings
= &conf
->cgroup
;
2833 struct lxc_list
*iterator
, *next
;
2834 struct lxc_cgroup
*cg
;
2838 return ret_set_errno(false, ENOENT
);
2841 return ret_set_errno(false, EINVAL
);
2843 cgroup_settings
= &conf
->cgroup
;
2844 if (lxc_list_empty(cgroup_settings
))
2847 if (!ops
->hierarchies
)
2848 return ret_set_errno(false, EINVAL
);
2850 if (!pure_unified_layout(ops
))
2851 return log_warn_errno(true, EINVAL
, "Ignoring legacy cgroup limits on pure cgroup2 system");
2853 sorted_cgroup_settings
= sort_cgroup_settings(cgroup_settings
);
2854 if (!sorted_cgroup_settings
)
2857 lxc_list_for_each(iterator
, sorted_cgroup_settings
) {
2858 cg
= iterator
->elem
;
2860 if (do_devices
== !strncmp("devices", cg
->subsystem
, 7)) {
2861 if (cg_legacy_set_data(ops
, cg
->subsystem
, cg
->value
, strncmp("cpuset", cg
->subsystem
, 6) == 0)) {
2862 if (do_devices
&& (errno
== EACCES
|| errno
== EPERM
)) {
2863 SYSWARN("Failed to set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2866 SYSERROR("Failed to set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2869 DEBUG("Set controller \"%s\" set to \"%s\"", cg
->subsystem
, cg
->value
);
2874 INFO("Limits for the legacy cgroup hierarchies have been setup");
2876 lxc_list_for_each_safe(iterator
, sorted_cgroup_settings
, next
) {
2877 lxc_list_del(iterator
);
2885 * Some of the parsing logic comes from the original cgroup device v1
2886 * implementation in the kernel.
2888 static int bpf_device_cgroup_prepare(struct cgroup_ops
*ops
,
2889 struct lxc_conf
*conf
, const char *key
,
2892 #ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
2893 struct device_item device_item
= {0};
2896 if (strcmp("devices.allow", key
) == 0 && *val
== '/')
2897 ret
= device_cgroup_rule_parse_devpath(&device_item
, val
);
2899 ret
= device_cgroup_rule_parse(&device_item
, key
, val
);
2901 return log_error_errno(-1, EINVAL
, "Failed to parse device string %s=%s", key
, val
);
2903 ret
= bpf_list_add_device(conf
, &device_item
);
2910 __cgfsng_ops
static bool cgfsng_setup_limits(struct cgroup_ops
*ops
,
2911 struct lxc_handler
*handler
)
2913 struct lxc_list
*cgroup_settings
, *iterator
;
2914 struct hierarchy
*h
;
2915 struct lxc_conf
*conf
;
2918 return ret_set_errno(false, ENOENT
);
2920 if (!ops
->hierarchies
)
2923 if (!ops
->container_cgroup
)
2924 return ret_set_errno(false, EINVAL
);
2926 if (!handler
|| !handler
->conf
)
2927 return ret_set_errno(false, EINVAL
);
2928 conf
= handler
->conf
;
2930 if (lxc_list_empty(&conf
->cgroup2
))
2932 cgroup_settings
= &conf
->cgroup2
;
2938 lxc_list_for_each (iterator
, cgroup_settings
) {
2939 struct lxc_cgroup
*cg
= iterator
->elem
;
2942 if (strncmp("devices", cg
->subsystem
, 7) == 0) {
2943 ret
= bpf_device_cgroup_prepare(ops
, conf
, cg
->subsystem
,
2946 ret
= lxc_write_openat(h
->container_limit_path
,
2947 cg
->subsystem
, cg
->value
,
2950 return log_error_errno(false, errno
, "Failed to set \"%s\" to \"%s\"",
2951 cg
->subsystem
, cg
->value
);
2953 TRACE("Set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2956 return log_info(true, "Limits for the unified cgroup hierarchy have been setup");
2959 __cgfsng_ops
bool cgfsng_devices_activate(struct cgroup_ops
*ops
,
2960 struct lxc_handler
*handler
)
2962 #ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
2963 __do_bpf_program_free
struct bpf_program
*devices
= NULL
;
2965 struct lxc_conf
*conf
;
2966 struct hierarchy
*unified
;
2967 struct lxc_list
*it
;
2968 struct bpf_program
*devices_old
;
2971 return ret_set_errno(false, ENOENT
);
2973 if (!ops
->hierarchies
)
2976 if (!ops
->container_cgroup
)
2977 return ret_set_errno(false, EEXIST
);
2979 if (!handler
|| !handler
->conf
)
2980 return ret_set_errno(false, EINVAL
);
2981 conf
= handler
->conf
;
2983 unified
= ops
->unified
;
2984 if (!unified
|| !unified
->bpf_device_controller
||
2985 !unified
->container_full_path
|| lxc_list_empty(&conf
->devices
))
2988 devices
= bpf_program_new(BPF_PROG_TYPE_CGROUP_DEVICE
);
2990 return log_error_errno(false, ENOMEM
, "Failed to create new bpf program");
2992 ret
= bpf_program_init(devices
);
2994 return log_error_errno(false, ENOMEM
, "Failed to initialize bpf program");
2996 lxc_list_for_each(it
, &conf
->devices
) {
2997 struct device_item
*cur
= it
->elem
;
2999 ret
= bpf_program_append_device(devices
, cur
);
3001 return log_error_errno(false, ENOMEM
, "Failed to add new rule to bpf device program: type %c, major %d, minor %d, access %s, allow %d, global_rule %d",
3008 TRACE("Added rule to bpf device program: type %c, major %d, minor %d, access %s, allow %d, global_rule %d",
3017 ret
= bpf_program_finalize(devices
);
3019 return log_error_errno(false, ENOMEM
, "Failed to finalize bpf program");
3021 ret
= bpf_program_cgroup_attach(devices
, BPF_CGROUP_DEVICE
,
3022 unified
->container_limit_path
,
3025 return log_error_errno(false, ENOMEM
, "Failed to attach bpf program");
3027 /* Replace old bpf program. */
3028 devices_old
= move_ptr(conf
->cgroup2_devices
);
3029 conf
->cgroup2_devices
= move_ptr(devices
);
3030 devices
= move_ptr(devices_old
);
3035 bool __cgfsng_delegate_controllers(struct cgroup_ops
*ops
, const char *cgroup
)
3037 __do_free
char *add_controllers
= NULL
, *base_path
= NULL
;
3038 __do_free_string_list
char **parts
= NULL
;
3039 struct hierarchy
*unified
= ops
->unified
;
3042 size_t full_len
= 0;
3044 if (!ops
->hierarchies
|| !pure_unified_layout(ops
) ||
3045 !unified
->controllers
[0])
3048 /* For now we simply enable all controllers that we have detected by
3049 * creating a string like "+memory +pids +cpu +io".
3050 * TODO: In the near future we might want to support "-<controller>"
3051 * etc. but whether supporting semantics like this make sense will need
3054 for (it
= unified
->controllers
; it
&& *it
; it
++) {
3055 full_len
+= strlen(*it
) + 2;
3056 add_controllers
= must_realloc(add_controllers
, full_len
+ 1);
3058 if (unified
->controllers
[0] == *it
)
3059 add_controllers
[0] = '\0';
3061 (void)strlcat(add_controllers
, "+", full_len
+ 1);
3062 (void)strlcat(add_controllers
, *it
, full_len
+ 1);
3064 if ((it
+ 1) && *(it
+ 1))
3065 (void)strlcat(add_controllers
, " ", full_len
+ 1);
3068 parts
= lxc_string_split(cgroup
, '/');
3072 parts_len
= lxc_array_len((void **)parts
);
3076 base_path
= must_make_path(unified
->mountpoint
, unified
->container_base_path
, NULL
);
3077 for (ssize_t i
= -1; i
< parts_len
; i
++) {
3079 __do_free
char *target
= NULL
;
3082 base_path
= must_append_path(base_path
, parts
[i
], NULL
);
3083 target
= must_make_path(base_path
, "cgroup.subtree_control", NULL
);
3084 ret
= lxc_writeat(-1, target
, add_controllers
, full_len
);
3086 return log_error_errno(false, errno
, "Could not enable \"%s\" controllers in the unified cgroup \"%s\"",
3087 add_controllers
, target
);
3088 TRACE("Enable \"%s\" controllers in the unified cgroup \"%s\"", add_controllers
, target
);
3094 __cgfsng_ops
bool cgfsng_monitor_delegate_controllers(struct cgroup_ops
*ops
)
3097 return ret_set_errno(false, ENOENT
);
3099 return __cgfsng_delegate_controllers(ops
, ops
->monitor_cgroup
);
3102 __cgfsng_ops
bool cgfsng_payload_delegate_controllers(struct cgroup_ops
*ops
)
3105 return ret_set_errno(false, ENOENT
);
3107 return __cgfsng_delegate_controllers(ops
, ops
->container_cgroup
);
3110 static bool cgroup_use_wants_controllers(const struct cgroup_ops
*ops
,
3113 if (!ops
->cgroup_use
)
3116 for (char **cur_ctrl
= controllers
; cur_ctrl
&& *cur_ctrl
; cur_ctrl
++) {
3119 for (char **cur_use
= ops
->cgroup_use
; cur_use
&& *cur_use
; cur_use
++) {
3120 if (strcmp(*cur_use
, *cur_ctrl
) != 0)
3136 static void cg_unified_delegate(char ***delegate
)
3138 __do_free
char *buf
= NULL
;
3139 char *standard
[] = {"cgroup.subtree_control", "cgroup.threads", NULL
};
3143 buf
= read_file("/sys/kernel/cgroup/delegate");
3145 for (char **p
= standard
; p
&& *p
; p
++) {
3146 idx
= append_null_to_list((void ***)delegate
);
3147 (*delegate
)[idx
] = must_copy_string(*p
);
3149 SYSWARN("Failed to read /sys/kernel/cgroup/delegate");
3153 lxc_iterate_parts(token
, buf
, " \t\n") {
3155 * We always need to chown this for both cgroup and
3158 if (strcmp(token
, "cgroup.procs") == 0)
3161 idx
= append_null_to_list((void ***)delegate
);
3162 (*delegate
)[idx
] = must_copy_string(token
);
3166 /* At startup, parse_hierarchies finds all the info we need about cgroup
3167 * mountpoints and current cgroups, and stores it in @d.
3169 static int cg_hybrid_init(struct cgroup_ops
*ops
, bool relative
, bool unprivileged
)
3171 __do_free
char *basecginfo
= NULL
, *line
= NULL
;
3172 __do_free_string_list
char **klist
= NULL
, **nlist
= NULL
;
3173 __do_fclose
FILE *f
= NULL
;
3177 /* Root spawned containers escape the current cgroup, so use init's
3178 * cgroups as our base in that case.
3180 if (!relative
&& (geteuid() == 0))
3181 basecginfo
= read_file("/proc/1/cgroup");
3183 basecginfo
= read_file("/proc/self/cgroup");
3185 return ret_set_errno(-1, ENOMEM
);
3187 ret
= get_existing_subsystems(&klist
, &nlist
);
3189 return log_error_errno(-1, errno
, "Failed to retrieve available legacy cgroup controllers");
3191 f
= fopen("/proc/self/mountinfo", "re");
3193 return log_error_errno(-1, errno
, "Failed to open \"/proc/self/mountinfo\"");
3195 lxc_cgfsng_print_basecg_debuginfo(basecginfo
, klist
, nlist
);
3197 while (getline(&line
, &len
, f
) != -1) {
3198 __do_free
char *base_cgroup
= NULL
, *mountpoint
= NULL
;
3199 __do_free_string_list
char **controller_list
= NULL
;
3202 struct hierarchy
*new;
3204 type
= get_cgroup_version(line
);
3208 if (type
== CGROUP2_SUPER_MAGIC
&& ops
->unified
)
3211 if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNKNOWN
) {
3212 if (type
== CGROUP2_SUPER_MAGIC
)
3213 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
3214 else if (type
== CGROUP_SUPER_MAGIC
)
3215 ops
->cgroup_layout
= CGROUP_LAYOUT_LEGACY
;
3216 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNIFIED
) {
3217 if (type
== CGROUP_SUPER_MAGIC
)
3218 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
3219 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_LEGACY
) {
3220 if (type
== CGROUP2_SUPER_MAGIC
)
3221 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
3224 controller_list
= cg_hybrid_get_controllers(klist
, nlist
, line
, type
);
3225 if (!controller_list
&& type
== CGROUP_SUPER_MAGIC
)
3228 if (type
== CGROUP_SUPER_MAGIC
)
3229 if (controller_list_is_dup(ops
->hierarchies
, controller_list
)) {
3230 TRACE("Skipping duplicating controller");
3234 mountpoint
= cg_hybrid_get_mountpoint(line
);
3236 ERROR("Failed parsing mountpoint from \"%s\"", line
);
3240 if (type
== CGROUP_SUPER_MAGIC
)
3241 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, controller_list
[0], CGROUP_SUPER_MAGIC
);
3243 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, NULL
, CGROUP2_SUPER_MAGIC
);
3245 ERROR("Failed to find current cgroup");
3250 prune_init_scope(base_cgroup
);
3251 if (type
== CGROUP2_SUPER_MAGIC
)
3252 writeable
= test_writeable_v2(mountpoint
, base_cgroup
);
3254 writeable
= test_writeable_v1(mountpoint
, base_cgroup
);
3256 TRACE("The %s group is not writeable", base_cgroup
);
3260 if (type
== CGROUP2_SUPER_MAGIC
) {
3261 char *cgv2_ctrl_path
;
3263 cgv2_ctrl_path
= must_make_path(mountpoint
, base_cgroup
,
3264 "cgroup.controllers",
3267 controller_list
= cg_unified_get_controllers(cgv2_ctrl_path
);
3268 free(cgv2_ctrl_path
);
3269 if (!controller_list
) {
3270 controller_list
= cg_unified_make_empty_controller();
3271 TRACE("No controllers are enabled for "
3272 "delegation in the unified hierarchy");
3276 /* Exclude all controllers that cgroup use does not want. */
3277 if (!cgroup_use_wants_controllers(ops
, controller_list
)) {
3278 TRACE("Skipping controller");
3282 new = add_hierarchy(&ops
->hierarchies
, move_ptr(controller_list
), move_ptr(mountpoint
), move_ptr(base_cgroup
), type
);
3283 if (type
== CGROUP2_SUPER_MAGIC
&& !ops
->unified
) {
3285 cg_unified_delegate(&new->cgroup2_chown
);
3290 TRACE("Writable cgroup hierarchies:");
3291 lxc_cgfsng_print_hierarchies(ops
);
3293 /* verify that all controllers in cgroup.use and all crucial
3294 * controllers are accounted for
3296 if (!all_controllers_found(ops
))
3297 return log_error_errno(-1, ENOENT
, "Failed to find all required controllers");
3302 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
3303 static char *cg_unified_get_current_cgroup(bool relative
)
3305 __do_free
char *basecginfo
= NULL
;
3309 if (!relative
&& (geteuid() == 0))
3310 basecginfo
= read_file("/proc/1/cgroup");
3312 basecginfo
= read_file("/proc/self/cgroup");
3316 base_cgroup
= strstr(basecginfo
, "0::/");
3320 base_cgroup
= base_cgroup
+ 3;
3321 copy
= copy_to_eol(base_cgroup
);
3328 static int cg_unified_init(struct cgroup_ops
*ops
, bool relative
,
3331 __do_free
char *subtree_path
= NULL
;
3335 struct hierarchy
*new;
3336 char *base_cgroup
= NULL
;
3338 ret
= unified_cgroup_hierarchy();
3339 if (ret
== -ENOMEDIUM
)
3340 return ret_errno(ENOMEDIUM
);
3342 if (ret
!= CGROUP2_SUPER_MAGIC
)
3345 base_cgroup
= cg_unified_get_current_cgroup(relative
);
3347 return ret_errno(EINVAL
);
3349 prune_init_scope(base_cgroup
);
3352 * We assume that the cgroup we're currently in has been delegated to
3353 * us and we are free to further delege all of the controllers listed
3354 * in cgroup.controllers further down the hierarchy.
3356 mountpoint
= must_copy_string(DEFAULT_CGROUP_MOUNTPOINT
);
3357 subtree_path
= must_make_path(mountpoint
, base_cgroup
, "cgroup.controllers", NULL
);
3358 delegatable
= cg_unified_get_controllers(subtree_path
);
3360 delegatable
= cg_unified_make_empty_controller();
3361 if (!delegatable
[0])
3362 TRACE("No controllers are enabled for delegation");
3364 /* TODO: If the user requested specific controllers via lxc.cgroup.use
3365 * we should verify here. The reason I'm not doing it right is that I'm
3366 * not convinced that lxc.cgroup.use will be the future since it is a
3367 * global property. I much rather have an option that lets you request
3368 * controllers per container.
3371 new = add_hierarchy(&ops
->hierarchies
, delegatable
, mountpoint
, base_cgroup
, CGROUP2_SUPER_MAGIC
);
3373 cg_unified_delegate(&new->cgroup2_chown
);
3375 if (bpf_devices_cgroup_supported())
3376 new->bpf_device_controller
= 1;
3378 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
3381 return CGROUP2_SUPER_MAGIC
;
3384 static int cg_init(struct cgroup_ops
*ops
, struct lxc_conf
*conf
)
3388 bool relative
= conf
->cgroup_meta
.relative
;
3390 tmp
= lxc_global_config_value("lxc.cgroup.use");
3392 __do_free
char *pin
= NULL
;
3395 pin
= must_copy_string(tmp
);
3398 lxc_iterate_parts(cur
, chop
, ",")
3399 must_append_string(&ops
->cgroup_use
, cur
);
3402 ret
= cg_unified_init(ops
, relative
, !lxc_list_empty(&conf
->id_map
));
3406 if (ret
== CGROUP2_SUPER_MAGIC
)
3409 return cg_hybrid_init(ops
, relative
, !lxc_list_empty(&conf
->id_map
));
3412 __cgfsng_ops
static int cgfsng_data_init(struct cgroup_ops
*ops
)
3414 const char *cgroup_pattern
;
3417 return ret_set_errno(-1, ENOENT
);
3419 /* copy system-wide cgroup information */
3420 cgroup_pattern
= lxc_global_config_value("lxc.cgroup.pattern");
3421 if (cgroup_pattern
&& strcmp(cgroup_pattern
, "") != 0)
3422 ops
->cgroup_pattern
= must_copy_string(cgroup_pattern
);
3427 struct cgroup_ops
*cgfsng_ops_init(struct lxc_conf
*conf
)
3429 __do_free
struct cgroup_ops
*cgfsng_ops
= NULL
;
3431 cgfsng_ops
= malloc(sizeof(struct cgroup_ops
));
3433 return ret_set_errno(NULL
, ENOMEM
);
3435 memset(cgfsng_ops
, 0, sizeof(struct cgroup_ops
));
3436 cgfsng_ops
->cgroup_layout
= CGROUP_LAYOUT_UNKNOWN
;
3438 if (cg_init(cgfsng_ops
, conf
))
3441 cgfsng_ops
->data_init
= cgfsng_data_init
;
3442 cgfsng_ops
->payload_destroy
= cgfsng_payload_destroy
;
3443 cgfsng_ops
->monitor_destroy
= cgfsng_monitor_destroy
;
3444 cgfsng_ops
->monitor_create
= cgfsng_monitor_create
;
3445 cgfsng_ops
->monitor_enter
= cgfsng_monitor_enter
;
3446 cgfsng_ops
->monitor_delegate_controllers
= cgfsng_monitor_delegate_controllers
;
3447 cgfsng_ops
->payload_delegate_controllers
= cgfsng_payload_delegate_controllers
;
3448 cgfsng_ops
->payload_create
= cgfsng_payload_create
;
3449 cgfsng_ops
->payload_enter
= cgfsng_payload_enter
;
3450 cgfsng_ops
->payload_finalize
= cgfsng_payload_finalize
;
3451 cgfsng_ops
->escape
= cgfsng_escape
;
3452 cgfsng_ops
->num_hierarchies
= cgfsng_num_hierarchies
;
3453 cgfsng_ops
->get_hierarchies
= cgfsng_get_hierarchies
;
3454 cgfsng_ops
->get_cgroup
= cgfsng_get_cgroup
;
3455 cgfsng_ops
->get
= cgfsng_get
;
3456 cgfsng_ops
->set
= cgfsng_set
;
3457 cgfsng_ops
->freeze
= cgfsng_freeze
;
3458 cgfsng_ops
->unfreeze
= cgfsng_unfreeze
;
3459 cgfsng_ops
->setup_limits_legacy
= cgfsng_setup_limits_legacy
;
3460 cgfsng_ops
->setup_limits
= cgfsng_setup_limits
;
3461 cgfsng_ops
->driver
= "cgfsng";
3462 cgfsng_ops
->version
= "1.0.0";
3463 cgfsng_ops
->attach
= cgfsng_attach
;
3464 cgfsng_ops
->chown
= cgfsng_chown
;
3465 cgfsng_ops
->mount
= cgfsng_mount
;
3466 cgfsng_ops
->devices_activate
= cgfsng_devices_activate
;
3467 cgfsng_ops
->get_limiting_cgroup
= cgfsng_get_limiting_cgroup
;
3469 return move_ptr(cgfsng_ops
);