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/epoll.h>
31 #include <sys/types.h>
37 #include "cgroup2_devices.h"
38 #include "cgroup_utils.h"
45 #include "memory_utils.h"
46 #include "storage/storage.h"
50 #include "include/strlcpy.h"
54 #include "include/strlcat.h"
57 lxc_log_define(cgfsng
, cgroup
);
59 /* Given a pointer to a null-terminated array of pointers, realloc to add one
60 * entry, and point the new entry to NULL. Do not fail. Return the index to the
61 * second-to-last entry - that is, the one which is now available for use
62 * (keeping the list null-terminated).
64 static int append_null_to_list(void ***list
)
69 for (; (*list
)[newentry
]; newentry
++)
72 *list
= must_realloc(*list
, (newentry
+ 2) * sizeof(void **));
73 (*list
)[newentry
+ 1] = NULL
;
77 /* Given a null-terminated array of strings, check whether @entry is one of the
80 static bool string_in_list(char **list
, const char *entry
)
85 for (int i
= 0; list
[i
]; i
++)
86 if (strcmp(list
[i
], entry
) == 0)
92 /* Return a copy of @entry prepending "name=", i.e. turn "systemd" into
93 * "name=systemd". Do not fail.
95 static char *cg_legacy_must_prefix_named(char *entry
)
101 prefixed
= must_realloc(NULL
, len
+ 6);
103 memcpy(prefixed
, "name=", STRLITERALLEN("name="));
104 memcpy(prefixed
+ STRLITERALLEN("name="), entry
, len
);
105 prefixed
[len
+ 5] = '\0';
110 /* Append an entry to the clist. Do not fail. @clist must be NULL the first time
113 * We also handle named subsystems here. Any controller which is not a kernel
114 * subsystem, we prefix "name=". Any which is both a kernel and named subsystem,
115 * we refuse to use because we're not sure which we have here.
116 * (TODO: We could work around this in some cases by just remounting to be
117 * unambiguous, or by comparing mountpoint contents with current cgroup.)
119 * The last entry will always be NULL.
121 static void must_append_controller(char **klist
, char **nlist
, char ***clist
,
127 if (string_in_list(klist
, entry
) && string_in_list(nlist
, entry
)) {
128 ERROR("Refusing to use ambiguous controller \"%s\"", entry
);
129 ERROR("It is both a named and kernel subsystem");
133 newentry
= append_null_to_list((void ***)clist
);
135 if (strncmp(entry
, "name=", 5) == 0)
136 copy
= must_copy_string(entry
);
137 else if (string_in_list(klist
, entry
))
138 copy
= must_copy_string(entry
);
140 copy
= cg_legacy_must_prefix_named(entry
);
142 (*clist
)[newentry
] = copy
;
145 /* Given a handler's cgroup data, return the struct hierarchy for the controller
146 * @c, or NULL if there is none.
148 static struct hierarchy
*get_hierarchy(struct cgroup_ops
*ops
, const char *controller
)
150 if (!ops
->hierarchies
)
151 return log_trace_errno(NULL
, errno
, "There are no useable cgroup controllers");
153 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
155 /* This is the empty unified hierarchy. */
156 if (ops
->hierarchies
[i
]->controllers
&&
157 !ops
->hierarchies
[i
]->controllers
[0])
158 return ops
->hierarchies
[i
];
160 } else if (pure_unified_layout(ops
) &&
161 strcmp(controller
, "devices") == 0) {
162 if (ops
->unified
->bpf_device_controller
)
167 if (string_in_list(ops
->hierarchies
[i
]->controllers
, controller
))
168 return ops
->hierarchies
[i
];
172 WARN("There is no useable %s controller", controller
);
174 WARN("There is no empty unified cgroup hierarchy");
176 return ret_set_errno(NULL
, ENOENT
);
179 #define BATCH_SIZE 50
180 static void batch_realloc(char **mem
, size_t oldlen
, size_t newlen
)
182 int newbatches
= (newlen
/ BATCH_SIZE
) + 1;
183 int oldbatches
= (oldlen
/ BATCH_SIZE
) + 1;
185 if (!*mem
|| newbatches
> oldbatches
)
186 *mem
= must_realloc(*mem
, newbatches
* BATCH_SIZE
);
189 static void append_line(char **dest
, size_t oldlen
, char *new, size_t newlen
)
191 size_t full
= oldlen
+ newlen
;
193 batch_realloc(dest
, oldlen
, full
+ 1);
195 memcpy(*dest
+ oldlen
, new, newlen
+ 1);
198 /* Slurp in a whole file */
199 static char *read_file(const char *fnam
)
201 __do_free
char *buf
= NULL
, *line
= NULL
;
202 __do_fclose
FILE *f
= NULL
;
203 size_t len
= 0, fulllen
= 0;
206 f
= fopen(fnam
, "re");
210 while ((linelen
= getline(&line
, &len
, f
)) != -1) {
211 append_line(&buf
, fulllen
, line
, linelen
);
215 return move_ptr(buf
);
218 /* Taken over modified from the kernel sources. */
219 #define NBITS 32 /* bits in uint32_t */
220 #define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
221 #define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
223 static void set_bit(unsigned bit
, uint32_t *bitarr
)
225 bitarr
[bit
/ NBITS
] |= (1 << (bit
% NBITS
));
228 static void clear_bit(unsigned bit
, uint32_t *bitarr
)
230 bitarr
[bit
/ NBITS
] &= ~(1 << (bit
% NBITS
));
233 static bool is_set(unsigned bit
, uint32_t *bitarr
)
235 return (bitarr
[bit
/ NBITS
] & (1 << (bit
% NBITS
))) != 0;
238 /* Create cpumask from cpulist aka turn:
246 static uint32_t *lxc_cpumask(char *buf
, size_t nbits
)
248 __do_free
uint32_t *bitarr
= NULL
;
252 arrlen
= BITS_TO_LONGS(nbits
);
253 bitarr
= calloc(arrlen
, sizeof(uint32_t));
255 return ret_set_errno(NULL
, ENOMEM
);
257 lxc_iterate_parts(token
, buf
, ",") {
262 start
= strtoul(token
, NULL
, 0);
264 range
= strchr(token
, '-');
266 end
= strtoul(range
+ 1, NULL
, 0);
269 return ret_set_errno(NULL
, EINVAL
);
272 return ret_set_errno(NULL
, EINVAL
);
275 set_bit(start
++, bitarr
);
278 return move_ptr(bitarr
);
281 /* Turn cpumask into simple, comma-separated cpulist. */
282 static char *lxc_cpumask_to_cpulist(uint32_t *bitarr
, size_t nbits
)
284 __do_free_string_list
char **cpulist
= NULL
;
285 char numstr
[INTTYPE_TO_STRLEN(size_t)] = {0};
288 for (size_t i
= 0; i
<= nbits
; i
++) {
289 if (!is_set(i
, bitarr
))
292 ret
= snprintf(numstr
, sizeof(numstr
), "%zu", i
);
293 if (ret
< 0 || (size_t)ret
>= sizeof(numstr
))
296 ret
= lxc_append_string(&cpulist
, numstr
);
298 return ret_set_errno(NULL
, ENOMEM
);
302 return ret_set_errno(NULL
, ENOMEM
);
304 return lxc_string_join(",", (const char **)cpulist
, false);
307 static ssize_t
get_max_cpus(char *cpulist
)
310 char *maxcpus
= cpulist
;
313 c1
= strrchr(maxcpus
, ',');
317 c2
= strrchr(maxcpus
, '-');
331 cpus
= strtoul(c1
, NULL
, 0);
338 #define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
339 #define __OFFLINE_CPUS "/sys/devices/system/cpu/offline"
340 static bool cg_legacy_filter_and_set_cpus(const char *parent_cgroup
,
341 char *child_cgroup
, bool am_initialized
)
343 __do_free
char *cpulist
= NULL
, *fpath
= NULL
, *isolcpus
= NULL
,
344 *offlinecpus
= NULL
, *posscpus
= NULL
;
345 __do_free
uint32_t *isolmask
= NULL
, *offlinemask
= NULL
,
349 ssize_t maxisol
= 0, maxoffline
= 0, maxposs
= 0;
350 bool flipped_bit
= false;
352 fpath
= must_make_path(parent_cgroup
, "cpuset.cpus", NULL
);
353 posscpus
= read_file(fpath
);
355 return log_error_errno(false, errno
, "Failed to read file \"%s\"", fpath
);
357 /* Get maximum number of cpus found in possible cpuset. */
358 maxposs
= get_max_cpus(posscpus
);
359 if (maxposs
< 0 || maxposs
>= INT_MAX
- 1)
362 if (file_exists(__ISOL_CPUS
)) {
363 isolcpus
= read_file(__ISOL_CPUS
);
365 return log_error_errno(false, errno
, "Failed to read file \"%s\"", __ISOL_CPUS
);
367 if (isdigit(isolcpus
[0])) {
368 /* Get maximum number of cpus found in isolated cpuset. */
369 maxisol
= get_max_cpus(isolcpus
);
370 if (maxisol
< 0 || maxisol
>= INT_MAX
- 1)
374 if (maxposs
< maxisol
)
378 TRACE("The path \""__ISOL_CPUS
"\" to read isolated cpus from does not exist");
381 if (file_exists(__OFFLINE_CPUS
)) {
382 offlinecpus
= read_file(__OFFLINE_CPUS
);
384 return log_error_errno(false, errno
, "Failed to read file \"%s\"", __OFFLINE_CPUS
);
386 if (isdigit(offlinecpus
[0])) {
387 /* Get maximum number of cpus found in offline cpuset. */
388 maxoffline
= get_max_cpus(offlinecpus
);
389 if (maxoffline
< 0 || maxoffline
>= INT_MAX
- 1)
393 if (maxposs
< maxoffline
)
394 maxposs
= maxoffline
;
397 TRACE("The path \""__OFFLINE_CPUS
"\" to read offline cpus from does not exist");
400 if ((maxisol
== 0) && (maxoffline
== 0)) {
401 cpulist
= move_ptr(posscpus
);
405 possmask
= lxc_cpumask(posscpus
, maxposs
);
407 return log_error_errno(false, errno
, "Failed to create cpumask for possible cpus");
410 isolmask
= lxc_cpumask(isolcpus
, maxposs
);
412 return log_error_errno(false, errno
, "Failed to create cpumask for isolated cpus");
415 if (maxoffline
> 0) {
416 offlinemask
= lxc_cpumask(offlinecpus
, maxposs
);
418 return log_error_errno(false, errno
, "Failed to create cpumask for offline cpus");
421 for (i
= 0; i
<= maxposs
; i
++) {
422 if ((isolmask
&& !is_set(i
, isolmask
)) ||
423 (offlinemask
&& !is_set(i
, offlinemask
)) ||
424 !is_set(i
, possmask
))
428 clear_bit(i
, possmask
);
432 cpulist
= lxc_cpumask_to_cpulist(possmask
, maxposs
);
433 TRACE("No isolated or offline cpus present in cpuset");
435 cpulist
= move_ptr(posscpus
);
436 TRACE("Removed isolated or offline cpus from cpuset");
439 return log_error_errno(false, errno
, "Failed to create cpu list");
442 if (!am_initialized
) {
443 ret
= lxc_write_openat(child_cgroup
, "cpuset.cpus", cpulist
, strlen(cpulist
));
445 return log_error_errno(false,
446 errno
, "Failed to write cpu list to \"%s/cpuset.cpus\"",
449 TRACE("Copied cpu settings of parent cgroup");
455 /* Copy contents of parent(@path)/@file to @path/@file */
456 static bool copy_parent_file(const char *parent_cgroup
,
457 const char *child_cgroup
, const char *file
)
459 __do_free
char *parent_file
= NULL
, *value
= NULL
;
463 parent_file
= must_make_path(parent_cgroup
, file
, NULL
);
464 len
= lxc_read_from_file(parent_file
, NULL
, 0);
466 return log_error_errno(false, errno
, "Failed to determine buffer size");
468 value
= must_realloc(NULL
, len
+ 1);
470 ret
= lxc_read_from_file(parent_file
, value
, len
);
472 return log_error_errno(false, errno
, "Failed to read from parent file \"%s\"", parent_file
);
474 ret
= lxc_write_openat(child_cgroup
, file
, value
, len
);
475 if (ret
< 0 && errno
!= EACCES
)
476 return log_error_errno(false, errno
, "Failed to write \"%s\" to file \"%s/%s\"",
477 value
, child_cgroup
, file
);
481 static inline bool is_unified_hierarchy(const struct hierarchy
*h
)
483 return h
->version
== CGROUP2_SUPER_MAGIC
;
487 * Initialize the cpuset hierarchy in first directory of @cgroup_leaf and set
488 * cgroup.clone_children so that children inherit settings. Since the
489 * h->base_path is populated by init or ourselves, we know it is already
492 * returns -1 on error, 0 when we didn't created a cgroup, 1 if we created a
495 static int cg_legacy_handle_cpuset_hierarchy(struct hierarchy
*h
,
496 const char *cgroup_leaf
)
498 __do_free
char *parent_cgroup
= NULL
, *child_cgroup
= NULL
, *dup
= NULL
;
499 __do_close
int cgroup_fd
= -EBADF
;
505 if (is_unified_hierarchy(h
))
508 if (!string_in_list(h
->controllers
, "cpuset"))
512 return ret_set_errno(-1, EINVAL
);
514 dup
= strdup(cgroup_leaf
);
516 return ret_set_errno(-1, ENOMEM
);
518 parent_cgroup
= must_make_path(h
->mountpoint
, h
->container_base_path
, NULL
);
521 leaf
+= strspn(leaf
, "/");
522 slash
= strchr(leaf
, '/');
525 child_cgroup
= must_make_path(parent_cgroup
, leaf
, NULL
);
530 ret
= mkdir(child_cgroup
, 0755);
533 return log_error_errno(-1, errno
, "Failed to create directory \"%s\"", child_cgroup
);
538 cgroup_fd
= lxc_open_dirfd(child_cgroup
);
542 ret
= lxc_readat(cgroup_fd
, "cgroup.clone_children", &v
, 1);
544 return log_error_errno(-1, errno
, "Failed to read file \"%s/cgroup.clone_children\"", child_cgroup
);
546 /* Make sure any isolated cpus are removed from cpuset.cpus. */
547 if (!cg_legacy_filter_and_set_cpus(parent_cgroup
, child_cgroup
, v
== '1'))
548 return log_error_errno(-1, errno
, "Failed to remove isolated cpus");
550 /* Already set for us by someone else. */
552 TRACE("\"cgroup.clone_children\" was already set to \"1\"");
554 /* copy parent's settings */
555 if (!copy_parent_file(parent_cgroup
, child_cgroup
, "cpuset.mems"))
556 return log_error_errno(-1, errno
, "Failed to copy \"cpuset.mems\" settings");
558 /* Set clone_children so children inherit our settings */
559 ret
= lxc_writeat(cgroup_fd
, "cgroup.clone_children", "1", 1);
561 return log_error_errno(-1, errno
, "Failed to write 1 to \"%s/cgroup.clone_children\"", child_cgroup
);
566 /* Given two null-terminated lists of strings, return true if any string is in
569 static bool controller_lists_intersect(char **l1
, char **l2
)
574 for (int i
= 0; l1
[i
]; i
++)
575 if (string_in_list(l2
, l1
[i
]))
581 /* For a null-terminated list of controllers @clist, return true if any of those
582 * controllers is already listed the null-terminated list of hierarchies @hlist.
583 * Realistically, if one is present, all must be present.
585 static bool controller_list_is_dup(struct hierarchy
**hlist
, char **clist
)
590 for (int i
= 0; hlist
[i
]; i
++)
591 if (controller_lists_intersect(hlist
[i
]->controllers
, clist
))
597 /* Return true if the controller @entry is found in the null-terminated list of
598 * hierarchies @hlist.
600 static bool controller_found(struct hierarchy
**hlist
, char *entry
)
605 for (int i
= 0; hlist
[i
]; i
++)
606 if (string_in_list(hlist
[i
]->controllers
, entry
))
612 /* Return true if all of the controllers which we require have been found. The
613 * required list is freezer and anything in lxc.cgroup.use.
615 static bool all_controllers_found(struct cgroup_ops
*ops
)
617 struct hierarchy
**hlist
;
619 if (!ops
->cgroup_use
)
622 hlist
= ops
->hierarchies
;
623 for (char **cur
= ops
->cgroup_use
; cur
&& *cur
; cur
++)
624 if (!controller_found(hlist
, *cur
))
625 return log_error(false, "No %s controller mountpoint found", *cur
);
630 /* Get the controllers from a mountinfo line There are other ways we could get
631 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
632 * could parse the mount options. But we simply assume that the mountpoint must
633 * be /sys/fs/cgroup/controller-list
635 static char **cg_hybrid_get_controllers(char **klist
, char **nlist
, char *line
,
638 /* The fourth field is /sys/fs/cgroup/comma-delimited-controller-list
639 * for legacy hierarchies.
641 __do_free_string_list
char **aret
= NULL
;
644 char *p
= line
, *sep
= ",";
646 for (i
= 0; i
< 4; i
++) {
653 /* Note, if we change how mountinfo works, then our caller will need to
654 * verify /sys/fs/cgroup/ in this field.
656 if (strncmp(p
, DEFAULT_CGROUP_MOUNTPOINT
"/", 15) != 0)
657 return log_warn(NULL
, "Found hierarchy not under " DEFAULT_CGROUP_MOUNTPOINT
": \"%s\"", p
);
662 return log_error(NULL
, "Corrupt mountinfo");
665 if (type
== CGROUP_SUPER_MAGIC
) {
666 __do_free
char *dup
= NULL
;
668 /* strdup() here for v1 hierarchies. Otherwise
669 * lxc_iterate_parts() will destroy mountpoints such as
670 * "/sys/fs/cgroup/cpu,cpuacct".
672 dup
= must_copy_string(p
);
676 lxc_iterate_parts(tok
, dup
, sep
)
677 must_append_controller(klist
, nlist
, &aret
, tok
);
681 return move_ptr(aret
);
684 static char **cg_unified_make_empty_controller(void)
686 __do_free_string_list
char **aret
= NULL
;
689 newentry
= append_null_to_list((void ***)&aret
);
690 aret
[newentry
] = NULL
;
691 return move_ptr(aret
);
694 static char **cg_unified_get_controllers(const char *file
)
696 __do_free
char *buf
= NULL
;
697 __do_free_string_list
char **aret
= NULL
;
701 buf
= read_file(file
);
705 lxc_iterate_parts(tok
, buf
, sep
) {
709 newentry
= append_null_to_list((void ***)&aret
);
710 copy
= must_copy_string(tok
);
711 aret
[newentry
] = copy
;
714 return move_ptr(aret
);
717 static struct hierarchy
*add_hierarchy(struct hierarchy
***h
, char **clist
, char *mountpoint
,
718 char *container_base_path
, int type
)
720 struct hierarchy
*new;
723 new = zalloc(sizeof(*new));
724 new->controllers
= clist
;
725 new->mountpoint
= mountpoint
;
726 new->container_base_path
= container_base_path
;
728 new->cgfd_con
= -EBADF
;
729 new->cgfd_limit
= -EBADF
;
730 new->cgfd_mon
= -EBADF
;
732 newentry
= append_null_to_list((void ***)h
);
733 (*h
)[newentry
] = new;
737 /* Get a copy of the mountpoint from @line, which is a line from
738 * /proc/self/mountinfo.
740 static char *cg_hybrid_get_mountpoint(char *line
)
742 char *p
= line
, *sret
= NULL
;
746 for (int i
= 0; i
< 4; i
++) {
753 if (strncmp(p
, DEFAULT_CGROUP_MOUNTPOINT
"/", 15) != 0)
756 p2
= strchr(p
+ 15, ' ');
762 sret
= must_realloc(NULL
, len
+ 1);
763 memcpy(sret
, p
, len
);
769 /* Given a multi-line string, return a null-terminated copy of the current line. */
770 static char *copy_to_eol(char *p
)
775 p2
= strchr(p
, '\n');
780 sret
= must_realloc(NULL
, len
+ 1);
781 memcpy(sret
, p
, len
);
787 /* cgline: pointer to character after the first ':' in a line in a \n-terminated
788 * /proc/self/cgroup file. Check whether controller c is present.
790 static bool controller_in_clist(char *cgline
, char *c
)
792 __do_free
char *tmp
= NULL
;
796 eol
= strchr(cgline
, ':');
801 tmp
= must_realloc(NULL
, len
+ 1);
802 memcpy(tmp
, cgline
, len
);
805 lxc_iterate_parts(tok
, tmp
, ",")
806 if (strcmp(tok
, c
) == 0)
812 /* @basecginfo is a copy of /proc/$$/cgroup. Return the current cgroup for
815 static char *cg_hybrid_get_current_cgroup(char *basecginfo
, char *controller
,
818 char *p
= basecginfo
;
821 bool is_cgv2_base_cgroup
= false;
823 /* cgroup v2 entry in "/proc/<pid>/cgroup": "0::/some/path" */
824 if ((type
== CGROUP2_SUPER_MAGIC
) && (*p
== '0'))
825 is_cgv2_base_cgroup
= true;
832 if (is_cgv2_base_cgroup
|| (controller
&& controller_in_clist(p
, controller
))) {
837 return copy_to_eol(p
);
847 static void must_append_string(char ***list
, char *entry
)
852 newentry
= append_null_to_list((void ***)list
);
853 copy
= must_copy_string(entry
);
854 (*list
)[newentry
] = copy
;
857 static int get_existing_subsystems(char ***klist
, char ***nlist
)
859 __do_free
char *line
= NULL
;
860 __do_fclose
FILE *f
= NULL
;
863 f
= fopen("/proc/self/cgroup", "re");
867 while (getline(&line
, &len
, f
) != -1) {
869 p
= strchr(line
, ':');
878 /* If the kernel has cgroup v2 support, then /proc/self/cgroup
879 * contains an entry of the form:
883 * In this case we use "cgroup2" as controller name.
886 must_append_string(klist
, "cgroup2");
890 lxc_iterate_parts(tok
, p
, ",") {
891 if (strncmp(tok
, "name=", 5) == 0)
892 must_append_string(nlist
, tok
);
894 must_append_string(klist
, tok
);
901 static char *trim(char *s
)
906 while ((len
> 1) && (s
[len
- 1] == '\n'))
912 static void lxc_cgfsng_print_hierarchies(struct cgroup_ops
*ops
)
915 struct hierarchy
**it
;
917 if (!ops
->hierarchies
) {
918 TRACE(" No hierarchies found");
922 TRACE(" Hierarchies:");
923 for (i
= 0, it
= ops
->hierarchies
; it
&& *it
; it
++, i
++) {
927 TRACE(" %d: base_cgroup: %s", i
, (*it
)->container_base_path
? (*it
)->container_base_path
: "(null)");
928 TRACE(" mountpoint: %s", (*it
)->mountpoint
? (*it
)->mountpoint
: "(null)");
929 TRACE(" controllers:");
930 for (j
= 0, cit
= (*it
)->controllers
; cit
&& *cit
; cit
++, j
++)
931 TRACE(" %d: %s", j
, *cit
);
935 static void lxc_cgfsng_print_basecg_debuginfo(char *basecginfo
, char **klist
,
941 TRACE("basecginfo is:");
942 TRACE("%s", basecginfo
);
944 for (k
= 0, it
= klist
; it
&& *it
; it
++, k
++)
945 TRACE("kernel subsystem %d: %s", k
, *it
);
947 for (k
= 0, it
= nlist
; it
&& *it
; it
++, k
++)
948 TRACE("named subsystem %d: %s", k
, *it
);
951 static int cgroup_tree_remove(struct hierarchy
**hierarchies
, 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
];
1087 if (!h
->monitor_full_path
)
1090 /* Monitor might have died before we entered the cgroup. */
1091 if (handler
->monitor_pid
<= 0) {
1092 WARN("No valid monitor process found while destroying cgroups");
1096 if (conf
&& conf
->cgroup_meta
.monitor_pivot_dir
)
1097 pivot_path
= must_make_path(h
->mountpoint
, h
->container_base_path
,
1098 conf
->cgroup_meta
.monitor_pivot_dir
, CGROUP_PIVOT
, NULL
);
1099 else if (conf
&& conf
->cgroup_meta
.monitor_dir
)
1100 pivot_path
= must_make_path(h
->mountpoint
, h
->container_base_path
,
1101 conf
->cgroup_meta
.monitor_dir
, CGROUP_PIVOT
, NULL
);
1102 else if (conf
&& conf
->cgroup_meta
.dir
)
1103 pivot_path
= must_make_path(h
->mountpoint
, h
->container_base_path
,
1104 conf
->cgroup_meta
.dir
, CGROUP_PIVOT
, NULL
);
1106 pivot_path
= must_make_path(h
->mountpoint
, h
->container_base_path
,
1107 CGROUP_PIVOT
, NULL
);
1109 offset
= strlen(h
->mountpoint
) + strlen(h
->container_base_path
);
1111 if (cg_legacy_handle_cpuset_hierarchy(h
, pivot_path
+ offset
))
1112 SYSWARN("Failed to initialize cpuset %s/" CGROUP_PIVOT
, pivot_path
);
1114 ret
= mkdir_p(pivot_path
, 0755);
1115 if (ret
< 0 && errno
!= EEXIST
) {
1116 ERROR("Failed to create %s", pivot_path
);
1120 ret
= lxc_write_openat(pivot_path
, "cgroup.procs", pidstr
, len
);
1122 SYSWARN("Failed to move monitor %s to \"%s\"", pidstr
, pivot_path
);
1127 ret
= lxc_rm_rf(h
->monitor_full_path
);
1129 WARN("Failed to destroy \"%s\"", h
->monitor_full_path
);
1133 static int mkdir_eexist_on_last(const char *dir
, mode_t mode
)
1135 const char *tmp
= dir
;
1136 const char *orig
= dir
;
1139 orig_len
= strlen(dir
);
1141 __do_free
char *makeme
= NULL
;
1145 dir
= tmp
+ strspn(tmp
, "/");
1146 tmp
= dir
+ strcspn(dir
, "/");
1148 cur_len
= dir
- orig
;
1149 makeme
= strndup(orig
, cur_len
);
1151 return ret_set_errno(-1, ENOMEM
);
1153 ret
= mkdir(makeme
, mode
);
1154 if (ret
< 0 && ((errno
!= EEXIST
) || (orig_len
== cur_len
)))
1155 return log_warn_errno(-1, errno
, "Failed to create directory \"%s\"", makeme
);
1156 } while (tmp
!= dir
);
1161 static bool cgroup_tree_create(struct cgroup_ops
*ops
, struct lxc_conf
*conf
,
1162 struct hierarchy
*h
, const char *cgroup_tree
,
1163 const char *cgroup_leaf
, bool payload
,
1164 const char *cgroup_limit_dir
)
1166 __do_free
char *path
= NULL
, *limit_path
= NULL
;
1167 int ret
, ret_cpuset
;
1169 path
= must_make_path(h
->mountpoint
, h
->container_base_path
, cgroup_leaf
, NULL
);
1170 if (dir_exists(path
))
1171 return log_warn_errno(false, errno
, "The %s cgroup already existed", path
);
1173 ret_cpuset
= cg_legacy_handle_cpuset_hierarchy(h
, cgroup_leaf
);
1175 return log_error_errno(false, errno
, "Failed to handle legacy cpuset controller");
1177 if (payload
&& cgroup_limit_dir
) {
1178 /* with isolation both parts need to not already exist */
1179 limit_path
= must_make_path(h
->mountpoint
,
1180 h
->container_base_path
,
1181 cgroup_limit_dir
, NULL
);
1183 ret
= mkdir_eexist_on_last(limit_path
, 0755);
1185 return log_debug_errno(false,
1186 errno
, "Failed to create %s limiting cgroup",
1189 h
->cgfd_limit
= lxc_open_dirfd(limit_path
);
1190 if (h
->cgfd_limit
< 0)
1191 return log_error_errno(false, errno
,
1192 "Failed to open %s", path
);
1193 h
->container_limit_path
= move_ptr(limit_path
);
1196 * With isolation the devices legacy cgroup needs to be
1197 * iinitialized early, as it typically contains an 'a' (all)
1198 * line, which is not possible once a subdirectory has been
1201 if (string_in_list(h
->controllers
, "devices") &&
1202 !ops
->setup_limits_legacy(ops
, conf
, true))
1203 return log_error(false, "Failed to setup legacy device limits");
1206 ret
= mkdir_eexist_on_last(path
, 0755);
1209 * This is the cpuset controller and
1210 * cg_legacy_handle_cpuset_hierarchy() has created our target
1211 * directory for us to ensure correct initialization.
1213 if (ret_cpuset
!= 1 || cgroup_tree
)
1214 return log_debug_errno(false, errno
, "Failed to create %s cgroup", path
);
1218 h
->cgfd_con
= lxc_open_dirfd(path
);
1219 if (h
->cgfd_con
< 0)
1220 return log_error_errno(false, errno
, "Failed to open %s", path
);
1221 h
->container_full_path
= move_ptr(path
);
1222 if (h
->cgfd_limit
< 0)
1223 h
->cgfd_limit
= h
->cgfd_con
;
1224 if (!h
->container_limit_path
)
1225 h
->container_limit_path
= h
->container_full_path
;
1227 h
->cgfd_mon
= lxc_open_dirfd(path
);
1228 if (h
->cgfd_mon
< 0)
1229 return log_error_errno(false, errno
, "Failed to open %s", path
);
1230 h
->monitor_full_path
= move_ptr(path
);
1236 static void cgroup_tree_leaf_remove(struct hierarchy
*h
, bool payload
)
1238 __do_free
char *full_path
= NULL
, *__limit_path
= NULL
;
1239 char *limit_path
= NULL
;
1242 __lxc_unused __do_close
int fd
= move_fd(h
->cgfd_con
);
1243 full_path
= move_ptr(h
->container_full_path
);
1244 limit_path
= move_ptr(h
->container_limit_path
);
1245 if (limit_path
!= full_path
)
1246 __limit_path
= limit_path
;
1248 __lxc_unused __do_close
int fd
= move_fd(h
->cgfd_mon
);
1249 full_path
= move_ptr(h
->monitor_full_path
);
1252 if (full_path
&& rmdir(full_path
))
1253 SYSWARN("Failed to rmdir(\"%s\") cgroup", full_path
);
1254 if (limit_path
&& rmdir(limit_path
))
1255 SYSWARN("Failed to rmdir(\"%s\") cgroup", limit_path
);
1259 * Check we have no lxc.cgroup.dir, and that lxc.cgroup.dir.limit_prefix is a
1260 * proper prefix directory of lxc.cgroup.dir.payload.
1262 * Returns the prefix length if it is set, otherwise zero on success.
1264 static bool check_cgroup_dir_config(struct lxc_conf
*conf
)
1266 const char *monitor_dir
= conf
->cgroup_meta
.monitor_dir
,
1267 *container_dir
= conf
->cgroup_meta
.container_dir
,
1268 *namespace_dir
= conf
->cgroup_meta
.namespace_dir
;
1270 /* none of the new options are set, all is fine */
1271 if (!monitor_dir
&& !container_dir
&& !namespace_dir
)
1274 /* some are set, make sure lxc.cgroup.dir is not also set*/
1275 if (conf
->cgroup_meta
.dir
)
1276 return log_error_errno(false, EINVAL
,
1277 "lxc.cgroup.dir conflicts with lxc.cgroup.dir.payload/monitor");
1279 /* make sure both monitor and payload are set */
1280 if (!monitor_dir
|| !container_dir
)
1281 return log_error_errno(false, EINVAL
,
1282 "lxc.cgroup.dir.payload and lxc.cgroup.dir.monitor must both be set");
1284 /* namespace_dir may be empty */
1288 __cgfsng_ops
static bool cgfsng_monitor_create(struct cgroup_ops
*ops
, struct lxc_handler
*handler
)
1290 __do_free
char *monitor_cgroup
= NULL
, *__cgroup_tree
= NULL
;
1291 const char *cgroup_tree
;
1295 char *suffix
= NULL
;
1296 struct lxc_conf
*conf
;
1299 return ret_set_errno(false, ENOENT
);
1301 if (!ops
->hierarchies
)
1304 if (ops
->monitor_cgroup
)
1305 return ret_set_errno(false, EEXIST
);
1307 if (!handler
|| !handler
->conf
)
1308 return ret_set_errno(false, EINVAL
);
1310 conf
= handler
->conf
;
1312 if (!check_cgroup_dir_config(conf
))
1315 if (conf
->cgroup_meta
.monitor_dir
) {
1317 monitor_cgroup
= strdup(conf
->cgroup_meta
.monitor_dir
);
1318 } else if (conf
->cgroup_meta
.dir
) {
1319 cgroup_tree
= conf
->cgroup_meta
.dir
;
1320 monitor_cgroup
= must_concat(&len
, conf
->cgroup_meta
.dir
, "/",
1321 DEFAULT_MONITOR_CGROUP_PREFIX
,
1323 CGROUP_CREATE_RETRY
, NULL
);
1324 } else if (ops
->cgroup_pattern
) {
1325 __cgroup_tree
= lxc_string_replace("%n", handler
->name
, ops
->cgroup_pattern
);
1327 return ret_set_errno(false, ENOMEM
);
1329 cgroup_tree
= __cgroup_tree
;
1330 monitor_cgroup
= must_concat(&len
, cgroup_tree
, "/",
1331 DEFAULT_MONITOR_CGROUP
,
1332 CGROUP_CREATE_RETRY
, NULL
);
1335 monitor_cgroup
= must_concat(&len
, DEFAULT_MONITOR_CGROUP_PREFIX
,
1337 CGROUP_CREATE_RETRY
, NULL
);
1339 if (!monitor_cgroup
)
1340 return ret_set_errno(false, ENOMEM
);
1342 if (!conf
->cgroup_meta
.monitor_dir
) {
1343 suffix
= monitor_cgroup
+ len
- CGROUP_CREATE_RETRY_LEN
;
1348 sprintf(suffix
, "-%d", idx
);
1350 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1351 if (cgroup_tree_create(ops
, handler
->conf
,
1352 ops
->hierarchies
[i
], cgroup_tree
,
1353 monitor_cgroup
, false, NULL
))
1356 DEBUG("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->monitor_full_path
?: "(null)");
1357 for (int j
= 0; j
< i
; j
++)
1358 cgroup_tree_leaf_remove(ops
->hierarchies
[j
], false);
1363 } while (ops
->hierarchies
[i
] && idx
> 0 && idx
< 1000 && suffix
);
1365 if (idx
== 1000 || (!suffix
&& idx
!= 0))
1366 return log_error_errno(false, ERANGE
, "Failed to create monitor cgroup");
1368 ops
->monitor_cgroup
= move_ptr(monitor_cgroup
);
1369 return log_info(true, "The monitor process uses \"%s\" as cgroup", ops
->monitor_cgroup
);
1373 * Try to create the same cgroup in all hierarchies. Start with cgroup_pattern;
1374 * next cgroup_pattern-1, -2, ..., -999.
1376 __cgfsng_ops
static bool cgfsng_payload_create(struct cgroup_ops
*ops
, 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 DEBUG("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 log_error_errno(false, ERANGE
, "Failed to create container cgroup");
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 if (is_unified_hierarchy(h
) && handler
->clone_flags
& CLONE_INTO_CGROUP
)
1555 ret
= lxc_writeat(h
->cgfd_con
, "cgroup.procs", pidstr
, len
);
1557 return log_error_errno(false, errno
, "Failed to enter cgroup \"%s\"", h
->container_full_path
);
1563 static int fchowmodat(int dirfd
, const char *path
, uid_t chown_uid
,
1564 gid_t chown_gid
, mode_t chmod_mode
)
1568 ret
= fchownat(dirfd
, path
, chown_uid
, chown_gid
,
1569 AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
1571 return log_warn_errno(-1,
1572 errno
, "Failed to fchownat(%d, %s, %d, %d, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW )",
1573 dirfd
, path
, (int)chown_uid
,
1576 ret
= fchmodat(dirfd
, (*path
!= '\0') ? path
: ".", chmod_mode
, 0);
1578 return log_warn_errno(-1, errno
, "Failed to fchmodat(%d, %s, %d, AT_SYMLINK_NOFOLLOW)",
1579 dirfd
, path
, (int)chmod_mode
);
1584 /* chgrp the container cgroups to container group. We leave
1585 * the container owner as cgroup owner. So we must make the
1586 * directories 775 so that the container can create sub-cgroups.
1588 * Also chown the tasks and cgroup.procs files. Those may not
1589 * exist depending on kernel version.
1591 static int chown_cgroup_wrapper(void *data
)
1595 struct generic_userns_exec_data
*arg
= data
;
1596 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1597 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1599 if (!lxc_setgroups(0, NULL
) && errno
!= EPERM
)
1600 return log_error_errno(-1, errno
, "Failed to setgroups(0, NULL)");
1602 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1604 return log_error_errno(-1, errno
, "Failed to setresgid(%d, %d, %d)",
1605 (int)nsgid
, (int)nsgid
, (int)nsgid
);
1607 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1609 return log_error_errno(-1, errno
, "Failed to setresuid(%d, %d, %d)",
1610 (int)nsuid
, (int)nsuid
, (int)nsuid
);
1612 destuid
= get_ns_uid(arg
->origuid
);
1613 if (destuid
== LXC_INVALID_UID
)
1616 for (int i
= 0; arg
->hierarchies
[i
]; i
++) {
1617 int dirfd
= arg
->hierarchies
[i
]->cgfd_con
;
1619 (void)fchowmodat(dirfd
, "", destuid
, nsgid
, 0775);
1622 * Failures to chown() these are inconvenient but not
1623 * detrimental We leave these owned by the container launcher,
1624 * so that container root can write to the files to attach. We
1625 * chmod() them 664 so that container systemd can write to the
1626 * files (which systemd in wily insists on doing).
1629 if (arg
->hierarchies
[i
]->version
== CGROUP_SUPER_MAGIC
)
1630 (void)fchowmodat(dirfd
, "tasks", destuid
, nsgid
, 0664);
1632 (void)fchowmodat(dirfd
, "cgroup.procs", destuid
, nsgid
, 0664);
1634 if (arg
->hierarchies
[i
]->version
!= CGROUP2_SUPER_MAGIC
)
1637 for (char **p
= arg
->hierarchies
[i
]->cgroup2_chown
; p
&& *p
; p
++)
1638 (void)fchowmodat(dirfd
, *p
, destuid
, nsgid
, 0664);
1644 __cgfsng_ops
static bool cgfsng_chown(struct cgroup_ops
*ops
,
1645 struct lxc_conf
*conf
)
1647 struct generic_userns_exec_data wrap
;
1650 return ret_set_errno(false, ENOENT
);
1652 if (!ops
->hierarchies
)
1655 if (!ops
->container_cgroup
)
1656 return ret_set_errno(false, ENOENT
);
1659 return ret_set_errno(false, EINVAL
);
1661 if (lxc_list_empty(&conf
->id_map
))
1664 wrap
.origuid
= geteuid();
1666 wrap
.hierarchies
= ops
->hierarchies
;
1669 if (userns_exec_1(conf
, chown_cgroup_wrapper
, &wrap
, "chown_cgroup_wrapper") < 0)
1670 return log_error_errno(false, errno
, "Error requesting cgroup chown in new user namespace");
1675 __cgfsng_ops
static void cgfsng_payload_finalize(struct cgroup_ops
*ops
)
1680 if (!ops
->hierarchies
)
1683 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1684 struct hierarchy
*h
= ops
->hierarchies
[i
];
1686 * we don't keep the fds for non-unified hierarchies around
1687 * mainly because we don't make use of them anymore after the
1688 * core cgroup setup is done but also because there are quite a
1691 if (!is_unified_hierarchy(h
))
1692 close_prot_errno_disarm(h
->cgfd_con
);
1696 /* cgroup-full:* is done, no need to create subdirs */
1697 static inline bool cg_mount_needs_subdirs(int type
)
1699 return !(type
>= LXC_AUTO_CGROUP_FULL_RO
);
1702 /* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
1703 * remount controller ro if needed and bindmount the cgroupfs onto
1704 * control/the/cg/path.
1706 static int cg_legacy_mount_controllers(int type
, struct hierarchy
*h
,
1707 char *controllerpath
, char *cgpath
,
1708 const char *container_cgroup
)
1710 __do_free
char *sourcepath
= NULL
;
1711 int ret
, remount_flags
;
1712 int flags
= MS_BIND
;
1714 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_MIXED
) {
1715 ret
= mount(controllerpath
, controllerpath
, "cgroup", MS_BIND
, NULL
);
1717 return log_error_errno(-1, errno
, "Failed to bind mount \"%s\" onto \"%s\"",
1718 controllerpath
, controllerpath
);
1720 remount_flags
= add_required_remount_flags(controllerpath
,
1722 flags
| MS_REMOUNT
);
1723 ret
= mount(controllerpath
, controllerpath
, "cgroup",
1724 remount_flags
| MS_REMOUNT
| MS_BIND
| MS_RDONLY
,
1727 return log_error_errno(-1, errno
, "Failed to remount \"%s\" ro", controllerpath
);
1729 INFO("Remounted %s read-only", controllerpath
);
1732 sourcepath
= must_make_path(h
->mountpoint
, h
->container_base_path
,
1733 container_cgroup
, NULL
);
1734 if (type
== LXC_AUTO_CGROUP_RO
)
1737 ret
= mount(sourcepath
, cgpath
, "cgroup", flags
, NULL
);
1739 return log_error_errno(-1, errno
, "Failed to mount \"%s\" onto \"%s\"",
1740 h
->controllers
[0], cgpath
);
1741 INFO("Mounted \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1743 if (flags
& MS_RDONLY
) {
1744 remount_flags
= add_required_remount_flags(sourcepath
, cgpath
,
1745 flags
| MS_REMOUNT
);
1746 ret
= mount(sourcepath
, cgpath
, "cgroup", remount_flags
, NULL
);
1748 return log_error_errno(-1, errno
, "Failed to remount \"%s\" ro", cgpath
);
1749 INFO("Remounted %s read-only", cgpath
);
1752 INFO("Completed second stage cgroup automounts for \"%s\"", cgpath
);
1756 /* __cg_mount_direct
1758 * Mount cgroup hierarchies directly without using bind-mounts. The main
1759 * uses-cases are mounting cgroup hierarchies in cgroup namespaces and mounting
1760 * cgroups for the LXC_AUTO_CGROUP_FULL option.
1762 static int __cg_mount_direct(int type
, struct hierarchy
*h
,
1763 const char *controllerpath
)
1765 __do_free
char *controllers
= NULL
;
1766 char *fstype
= "cgroup2";
1767 unsigned long flags
= 0;
1773 flags
|= MS_RELATIME
;
1775 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_FULL_RO
)
1778 if (h
->version
!= CGROUP2_SUPER_MAGIC
) {
1779 controllers
= lxc_string_join(",", (const char **)h
->controllers
, false);
1785 ret
= mount("cgroup", controllerpath
, fstype
, flags
, controllers
);
1787 return log_error_errno(-1, errno
, "Failed to mount \"%s\" with cgroup filesystem type %s",
1788 controllerpath
, fstype
);
1790 DEBUG("Mounted \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1794 static inline int cg_mount_in_cgroup_namespace(int type
, struct hierarchy
*h
,
1795 const char *controllerpath
)
1797 return __cg_mount_direct(type
, h
, controllerpath
);
1800 static inline int cg_mount_cgroup_full(int type
, struct hierarchy
*h
,
1801 const char *controllerpath
)
1803 if (type
< LXC_AUTO_CGROUP_FULL_RO
|| type
> LXC_AUTO_CGROUP_FULL_MIXED
)
1806 return __cg_mount_direct(type
, h
, controllerpath
);
1809 __cgfsng_ops
static bool cgfsng_mount(struct cgroup_ops
*ops
,
1810 struct lxc_handler
*handler
,
1811 const char *root
, int type
)
1813 __do_free
char *cgroup_root
= NULL
;
1814 bool has_cgns
= false, wants_force_mount
= false;
1818 return ret_set_errno(false, ENOENT
);
1820 if (!ops
->hierarchies
)
1823 if (!handler
|| !handler
->conf
)
1824 return ret_set_errno(false, EINVAL
);
1826 if ((type
& LXC_AUTO_CGROUP_MASK
) == 0)
1829 if (type
& LXC_AUTO_CGROUP_FORCE
) {
1830 type
&= ~LXC_AUTO_CGROUP_FORCE
;
1831 wants_force_mount
= true;
1834 if (!wants_force_mount
) {
1835 if (!lxc_list_empty(&handler
->conf
->keepcaps
))
1836 wants_force_mount
= !in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->keepcaps
);
1838 wants_force_mount
= in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->caps
);
1841 * Most recent distro versions currently have init system that
1842 * do support cgroup2 but do not mount it by default unless
1843 * explicitly told so even if the host is cgroup2 only. That
1844 * means they often will fail to boot. Fix this by pre-mounting
1845 * cgroup2 by default. We will likely need to be doing this a
1846 * few years until all distros have switched over to cgroup2 at
1847 * which point we can safely assume that their init systems
1848 * will mount it themselves.
1850 if (pure_unified_layout(ops
))
1851 wants_force_mount
= true;
1854 has_cgns
= cgns_supported();
1855 if (has_cgns
&& !wants_force_mount
)
1858 if (type
== LXC_AUTO_CGROUP_NOSPEC
)
1859 type
= LXC_AUTO_CGROUP_MIXED
;
1860 else if (type
== LXC_AUTO_CGROUP_FULL_NOSPEC
)
1861 type
= LXC_AUTO_CGROUP_FULL_MIXED
;
1863 cgroup_root
= must_make_path(root
, DEFAULT_CGROUP_MOUNTPOINT
, NULL
);
1864 if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNIFIED
) {
1865 if (has_cgns
&& wants_force_mount
) {
1867 * If cgroup namespaces are supported but the container
1868 * will not have CAP_SYS_ADMIN after it has started we
1869 * need to mount the cgroups manually.
1871 return cg_mount_in_cgroup_namespace(type
, ops
->unified
, cgroup_root
) == 0;
1874 return cg_mount_cgroup_full(type
, ops
->unified
, cgroup_root
) == 0;
1878 ret
= safe_mount_beneath(root
, NULL
, DEFAULT_CGROUP_MOUNTPOINT
, "tmpfs",
1879 MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
1880 "size=10240k,mode=755");
1882 if (errno
!= ENOSYS
)
1885 ret
= safe_mount(NULL
, cgroup_root
, "tmpfs",
1886 MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
1887 "size=10240k,mode=755", root
);
1892 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1893 __do_free
char *controllerpath
= NULL
, *path2
= NULL
;
1894 struct hierarchy
*h
= ops
->hierarchies
[i
];
1895 char *controller
= strrchr(h
->mountpoint
, '/');
1901 controllerpath
= must_make_path(cgroup_root
, controller
, NULL
);
1902 if (dir_exists(controllerpath
))
1905 ret
= mkdir(controllerpath
, 0755);
1907 return log_error_errno(false, errno
, "Error creating cgroup path: %s", controllerpath
);
1909 if (has_cgns
&& wants_force_mount
) {
1910 /* If cgroup namespaces are supported but the container
1911 * will not have CAP_SYS_ADMIN after it has started we
1912 * need to mount the cgroups manually.
1914 ret
= cg_mount_in_cgroup_namespace(type
, h
, controllerpath
);
1921 ret
= cg_mount_cgroup_full(type
, h
, controllerpath
);
1925 if (!cg_mount_needs_subdirs(type
))
1928 path2
= must_make_path(controllerpath
, h
->container_base_path
,
1929 ops
->container_cgroup
, NULL
);
1930 ret
= mkdir_p(path2
, 0755);
1934 ret
= cg_legacy_mount_controllers(type
, h
, controllerpath
,
1935 path2
, ops
->container_cgroup
);
1943 /* Only root needs to escape to the cgroup of its init. */
1944 __cgfsng_ops
static bool cgfsng_escape(const struct cgroup_ops
*ops
,
1945 struct lxc_conf
*conf
)
1948 return ret_set_errno(false, ENOENT
);
1950 if (!ops
->hierarchies
)
1954 return ret_set_errno(false, EINVAL
);
1956 if (conf
->cgroup_meta
.relative
|| geteuid())
1959 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1960 __do_free
char *fullpath
= NULL
;
1964 must_make_path(ops
->hierarchies
[i
]->mountpoint
,
1965 ops
->hierarchies
[i
]->container_base_path
,
1966 "cgroup.procs", NULL
);
1967 ret
= lxc_write_to_file(fullpath
, "0", 2, false, 0666);
1969 return log_error_errno(false, errno
, "Failed to escape to cgroup \"%s\"", fullpath
);
1975 __cgfsng_ops
static int cgfsng_num_hierarchies(struct cgroup_ops
*ops
)
1980 return ret_set_errno(-1, ENOENT
);
1982 if (!ops
->hierarchies
)
1985 for (; ops
->hierarchies
[i
]; i
++)
1991 __cgfsng_ops
static bool cgfsng_get_hierarchies(struct cgroup_ops
*ops
, int n
,
1997 return ret_set_errno(false, ENOENT
);
1999 if (!ops
->hierarchies
)
2000 return ret_set_errno(false, ENOENT
);
2002 /* sanity check n */
2003 for (i
= 0; i
< n
; i
++)
2004 if (!ops
->hierarchies
[i
])
2005 return ret_set_errno(false, ENOENT
);
2007 *out
= ops
->hierarchies
[i
]->controllers
;
2012 static bool cg_legacy_freeze(struct cgroup_ops
*ops
)
2014 struct hierarchy
*h
;
2016 h
= get_hierarchy(ops
, "freezer");
2018 return ret_set_errno(-1, ENOENT
);
2020 return lxc_write_openat(h
->container_full_path
, "freezer.state",
2021 "FROZEN", STRLITERALLEN("FROZEN"));
2024 static int freezer_cgroup_events_cb(int fd
, uint32_t events
, void *cbdata
,
2025 struct lxc_epoll_descr
*descr
)
2027 __do_close
int duped_fd
= -EBADF
;
2028 __do_free
char *line
= NULL
;
2029 __do_fclose
FILE *f
= NULL
;
2030 int state
= PTR_TO_INT(cbdata
);
2032 const char *state_string
;
2036 return LXC_MAINLOOP_ERROR
;
2038 if (lseek(duped_fd
, 0, SEEK_SET
) < (off_t
)-1)
2039 return LXC_MAINLOOP_ERROR
;
2041 f
= fdopen(duped_fd
, "re");
2043 return LXC_MAINLOOP_ERROR
;
2047 state_string
= "frozen 1";
2049 state_string
= "frozen 0";
2051 while (getline(&line
, &len
, f
) != -1)
2052 if (strncmp(line
, state_string
, STRLITERALLEN("frozen") + 2) == 0)
2053 return LXC_MAINLOOP_CLOSE
;
2055 return LXC_MAINLOOP_CONTINUE
;
2058 static int cg_unified_freeze_do(struct cgroup_ops
*ops
, int timeout
,
2059 const char *state_string
,
2061 const char *epoll_error
,
2062 const char *wait_error
)
2064 __do_close
int fd
= -EBADF
;
2065 call_cleaner(lxc_mainloop_close
) struct lxc_epoll_descr
*descr_ptr
= NULL
;
2067 struct lxc_epoll_descr descr
;
2068 struct hierarchy
*h
;
2072 return ret_set_errno(-1, ENOENT
);
2074 if (!h
->container_full_path
)
2075 return ret_set_errno(-1, EEXIST
);
2078 __do_free
char *events_file
= NULL
;
2080 events_file
= must_make_path(h
->container_full_path
, "cgroup.events", NULL
);
2081 fd
= open(events_file
, O_RDONLY
| O_CLOEXEC
);
2083 return log_error_errno(-1, errno
, "Failed to open cgroup.events file");
2085 ret
= lxc_mainloop_open(&descr
);
2087 return log_error_errno(-1, errno
, "%s", epoll_error
);
2089 /* automatically cleaned up now */
2092 ret
= lxc_mainloop_add_handler_events(&descr
, fd
, EPOLLPRI
, freezer_cgroup_events_cb
, INT_TO_PTR(state_num
));
2094 return log_error_errno(-1, errno
, "Failed to add cgroup.events fd handler to mainloop");
2097 ret
= lxc_write_openat(h
->container_full_path
, "cgroup.freeze", state_string
, 1);
2099 return log_error_errno(-1, errno
, "Failed to open cgroup.freeze file");
2101 if (timeout
!= 0 && lxc_mainloop(&descr
, timeout
))
2102 return log_error_errno(-1, errno
, "%s", wait_error
);
2107 static int cg_unified_freeze(struct cgroup_ops
*ops
, int timeout
)
2109 return cg_unified_freeze_do(ops
, timeout
, "1", 1,
2110 "Failed to create epoll instance to wait for container freeze",
2111 "Failed to wait for container to be frozen");
2114 __cgfsng_ops
static int cgfsng_freeze(struct cgroup_ops
*ops
, int timeout
)
2116 if (!ops
->hierarchies
)
2117 return ret_set_errno(-1, ENOENT
);
2119 if (ops
->cgroup_layout
!= CGROUP_LAYOUT_UNIFIED
)
2120 return cg_legacy_freeze(ops
);
2122 return cg_unified_freeze(ops
, timeout
);
2125 static int cg_legacy_unfreeze(struct cgroup_ops
*ops
)
2127 struct hierarchy
*h
;
2129 h
= get_hierarchy(ops
, "freezer");
2131 return ret_set_errno(-1, ENOENT
);
2133 return lxc_write_openat(h
->container_full_path
, "freezer.state",
2134 "THAWED", STRLITERALLEN("THAWED"));
2137 static int cg_unified_unfreeze(struct cgroup_ops
*ops
, int timeout
)
2139 return cg_unified_freeze_do(ops
, timeout
, "0", 0,
2140 "Failed to create epoll instance to wait for container unfreeze",
2141 "Failed to wait for container to be unfrozen");
2144 __cgfsng_ops
static int cgfsng_unfreeze(struct cgroup_ops
*ops
, int timeout
)
2146 if (!ops
->hierarchies
)
2147 return ret_set_errno(-1, ENOENT
);
2149 if (ops
->cgroup_layout
!= CGROUP_LAYOUT_UNIFIED
)
2150 return cg_legacy_unfreeze(ops
);
2152 return cg_unified_unfreeze(ops
, timeout
);
2155 static const char *cgfsng_get_cgroup_do(struct cgroup_ops
*ops
,
2156 const char *controller
, bool limiting
)
2158 struct hierarchy
*h
;
2160 h
= get_hierarchy(ops
, controller
);
2162 return log_warn_errno(NULL
, ENOENT
, "Failed to find hierarchy for controller \"%s\"",
2163 controller
? controller
: "(null)");
2166 return h
->container_limit_path
2167 ? h
->container_limit_path
+ strlen(h
->mountpoint
)
2170 return h
->container_full_path
2171 ? h
->container_full_path
+ strlen(h
->mountpoint
)
2175 __cgfsng_ops
static const char *cgfsng_get_cgroup(struct cgroup_ops
*ops
,
2176 const char *controller
)
2178 return cgfsng_get_cgroup_do(ops
, controller
, false);
2181 __cgfsng_ops
static const char *cgfsng_get_limiting_cgroup(struct cgroup_ops
*ops
,
2182 const char *controller
)
2184 return cgfsng_get_cgroup_do(ops
, controller
, true);
2187 /* Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a full path,
2188 * which must be freed by the caller.
2190 static inline char *build_full_cgpath_from_monitorpath(struct hierarchy
*h
,
2192 const char *filename
)
2194 return must_make_path(h
->mountpoint
, inpath
, filename
, NULL
);
2197 static int cgroup_attach_leaf(const struct lxc_conf
*conf
, int unified_fd
, pid_t pid
)
2201 char pidstr
[INTTYPE_TO_STRLEN(int64_t) + 1];
2204 /* Create leaf cgroup. */
2205 ret
= mkdirat(unified_fd
, ".lxc", 0755);
2206 if (ret
< 0 && errno
!= EEXIST
)
2207 return log_error_errno(-1, errno
, "Failed to create leaf cgroup \".lxc\"");
2209 pidstr_len
= sprintf(pidstr
, INT64_FMT
, (int64_t)pid
);
2210 ret
= lxc_writeat(unified_fd
, ".lxc/cgroup.procs", pidstr
, pidstr_len
);
2212 ret
= lxc_writeat(unified_fd
, "cgroup.procs", pidstr
, pidstr_len
);
2216 /* this is a non-leaf node */
2218 return log_error_errno(-1, errno
, "Failed to attach to unified cgroup");
2222 char attach_cgroup
[STRLITERALLEN(".lxc-/cgroup.procs") + INTTYPE_TO_STRLEN(int) + 1];
2223 char *slash
= attach_cgroup
;
2225 ret
= snprintf(attach_cgroup
, sizeof(attach_cgroup
), ".lxc-%d/cgroup.procs", idx
);
2226 if (ret
< 0 || (size_t)ret
>= sizeof(attach_cgroup
))
2227 return ret_errno(EIO
);
2230 * This shouldn't really happen but the compiler might complain
2231 * that a short write would cause a buffer overrun. So be on
2234 if (ret
< STRLITERALLEN(".lxc-/cgroup.procs"))
2235 return log_error_errno(-EINVAL
, EINVAL
, "Unexpected short write would cause buffer-overrun");
2237 slash
+= (ret
- STRLITERALLEN("/cgroup.procs"));
2240 ret
= mkdirat(unified_fd
, attach_cgroup
, 0755);
2241 if (ret
< 0 && errno
!= EEXIST
)
2242 return log_error_errno(-1, errno
, "Failed to create cgroup %s", attach_cgroup
);
2248 ret
= lxc_writeat(unified_fd
, attach_cgroup
, pidstr
, pidstr_len
);
2252 if (rm
&& unlinkat(unified_fd
, attach_cgroup
, AT_REMOVEDIR
))
2253 SYSERROR("Failed to remove cgroup \"%d(%s)\"", unified_fd
, attach_cgroup
);
2255 /* this is a non-leaf node */
2257 return log_error_errno(-1, errno
, "Failed to attach to unified cgroup");
2260 } while (idx
< 1000);
2262 return log_error_errno(-1, errno
, "Failed to attach to unified cgroup");
2265 static int cgroup_attach_create_leaf(const struct lxc_conf
*conf
,
2266 int unified_fd
, int *sk_fd
)
2268 __do_close
int sk
= *sk_fd
, target_fd0
= -EBADF
, target_fd1
= -EBADF
;
2272 /* Create leaf cgroup. */
2273 ret
= mkdirat(unified_fd
, ".lxc", 0755);
2274 if (ret
< 0 && errno
!= EEXIST
)
2275 return log_error_errno(-1, errno
, "Failed to create leaf cgroup \".lxc\"");
2277 target_fd0
= openat(unified_fd
, ".lxc/cgroup.procs", O_WRONLY
| O_CLOEXEC
| O_NOFOLLOW
);
2279 return log_error_errno(-errno
, errno
, "Failed to open \".lxc/cgroup.procs\"");
2280 target_fds
[0] = target_fd0
;
2282 target_fd1
= openat(unified_fd
, "cgroup.procs", O_WRONLY
| O_CLOEXEC
| O_NOFOLLOW
);
2284 return log_error_errno(-errno
, errno
, "Failed to open \".lxc/cgroup.procs\"");
2285 target_fds
[1] = target_fd1
;
2287 ret
= lxc_abstract_unix_send_fds(sk
, target_fds
, 2, NULL
, 0);
2289 return log_error_errno(-errno
, errno
, "Failed to send \".lxc/cgroup.procs\" fds %d and %d",
2290 target_fd0
, target_fd1
);
2292 return log_debug(0, "Sent target cgroup fds %d and %d", target_fd0
, target_fd1
);
2295 static int cgroup_attach_move_into_leaf(const struct lxc_conf
*conf
,
2296 int *sk_fd
, pid_t pid
)
2298 __do_close
int sk
= *sk_fd
, target_fd0
= -EBADF
, target_fd1
= -EBADF
;
2300 char pidstr
[INTTYPE_TO_STRLEN(int64_t) + 1];
2304 ret
= lxc_abstract_unix_recv_fds(sk
, target_fds
, 2, NULL
, 0);
2306 return log_error_errno(-1, errno
, "Failed to receive target cgroup fd");
2307 target_fd0
= target_fds
[0];
2308 target_fd1
= target_fds
[1];
2310 pidstr_len
= sprintf(pidstr
, INT64_FMT
, (int64_t)pid
);
2312 ret
= lxc_write_nointr(target_fd0
, pidstr
, pidstr_len
);
2313 if (ret
> 0 && ret
== pidstr_len
)
2314 return log_debug(0, "Moved process into target cgroup via fd %d", target_fd0
);
2316 ret
= lxc_write_nointr(target_fd1
, pidstr
, pidstr_len
);
2317 if (ret
> 0 && ret
== pidstr_len
)
2318 return log_debug(0, "Moved process into target cgroup via fd %d", target_fd1
);
2320 return log_debug_errno(-1, errno
, "Failed to move process into target cgroup via fd %d and %d",
2321 target_fd0
, target_fd1
);
2324 struct userns_exec_unified_attach_data
{
2325 const struct lxc_conf
*conf
;
2331 static int cgroup_unified_attach_child_wrapper(void *data
)
2333 struct userns_exec_unified_attach_data
*args
= data
;
2335 if (!args
->conf
|| args
->unified_fd
< 0 || args
->pid
<= 0 ||
2336 args
->sk_pair
[0] < 0 || args
->sk_pair
[1] < 0)
2337 return ret_errno(EINVAL
);
2339 close_prot_errno_disarm(args
->sk_pair
[0]);
2340 return cgroup_attach_create_leaf(args
->conf
, args
->unified_fd
,
2344 static int cgroup_unified_attach_parent_wrapper(void *data
)
2346 struct userns_exec_unified_attach_data
*args
= data
;
2348 if (!args
->conf
|| args
->unified_fd
< 0 || args
->pid
<= 0 ||
2349 args
->sk_pair
[0] < 0 || args
->sk_pair
[1] < 0)
2350 return ret_errno(EINVAL
);
2352 close_prot_errno_disarm(args
->sk_pair
[1]);
2353 return cgroup_attach_move_into_leaf(args
->conf
, &args
->sk_pair
[0],
2357 int cgroup_attach(const struct lxc_conf
*conf
, const char *name
,
2358 const char *lxcpath
, pid_t pid
)
2360 __do_close
int unified_fd
= -EBADF
;
2363 if (!conf
|| !name
|| !lxcpath
|| pid
<= 0)
2364 return ret_errno(EINVAL
);
2366 unified_fd
= lxc_cmd_get_cgroup2_fd(name
, lxcpath
);
2368 return ret_errno(EBADF
);
2370 if (!lxc_list_empty(&conf
->id_map
)) {
2371 struct userns_exec_unified_attach_data args
= {
2373 .unified_fd
= unified_fd
,
2377 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, args
.sk_pair
);
2381 ret
= userns_exec_minimal(conf
,
2382 cgroup_unified_attach_parent_wrapper
,
2384 cgroup_unified_attach_child_wrapper
,
2387 ret
= cgroup_attach_leaf(conf
, unified_fd
, pid
);
2393 /* Technically, we're always at a delegation boundary here (This is especially
2394 * true when cgroup namespaces are available.). The reasoning is that in order
2395 * for us to have been able to start a container in the first place the root
2396 * cgroup must have been a leaf node. Now, either the container's init system
2397 * has populated the cgroup and kept it as a leaf node or it has created
2398 * subtrees. In the former case we will simply attach to the leaf node we
2399 * created when we started the container in the latter case we create our own
2400 * cgroup for the attaching process.
2402 static int __cg_unified_attach(const struct hierarchy
*h
,
2403 const struct lxc_conf
*conf
, const char *name
,
2404 const char *lxcpath
, pid_t pid
,
2405 const char *controller
)
2407 __do_close
int unified_fd
= -EBADF
;
2408 __do_free
char *path
= NULL
, *cgroup
= NULL
;
2411 if (!conf
|| !name
|| !lxcpath
|| pid
<= 0)
2412 return ret_errno(EINVAL
);
2414 ret
= cgroup_attach(conf
, name
, lxcpath
, pid
);
2416 return log_trace(0, "Attached to unified cgroup via command handler");
2418 return log_error_errno(ret
, errno
, "Failed to attach to unified cgroup");
2420 /* Fall back to retrieving the path for the unified cgroup. */
2421 cgroup
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2426 path
= must_make_path(h
->mountpoint
, cgroup
, NULL
);
2428 unified_fd
= open(path
, O_PATH
| O_DIRECTORY
| O_CLOEXEC
);
2430 return ret_errno(EBADF
);
2432 if (!lxc_list_empty(&conf
->id_map
)) {
2433 struct userns_exec_unified_attach_data args
= {
2435 .unified_fd
= unified_fd
,
2439 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, args
.sk_pair
);
2443 ret
= userns_exec_minimal(conf
,
2444 cgroup_unified_attach_parent_wrapper
,
2446 cgroup_unified_attach_child_wrapper
,
2449 ret
= cgroup_attach_leaf(conf
, unified_fd
, pid
);
2455 __cgfsng_ops
static bool cgfsng_attach(struct cgroup_ops
*ops
,
2456 const struct lxc_conf
*conf
,
2457 const char *name
, const char *lxcpath
,
2461 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
2464 return ret_set_errno(false, ENOENT
);
2466 if (!ops
->hierarchies
)
2469 len
= snprintf(pidstr
, sizeof(pidstr
), "%d", pid
);
2470 if (len
< 0 || (size_t)len
>= sizeof(pidstr
))
2473 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
2474 __do_free
char *fullpath
= NULL
, *path
= NULL
;
2475 struct hierarchy
*h
= ops
->hierarchies
[i
];
2477 if (h
->version
== CGROUP2_SUPER_MAGIC
) {
2478 ret
= __cg_unified_attach(h
, conf
, name
, lxcpath
, pid
,
2486 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, h
->controllers
[0]);
2491 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, "cgroup.procs");
2492 ret
= lxc_write_to_file(fullpath
, pidstr
, len
, false, 0666);
2494 return log_error_errno(false, errno
, "Failed to attach %d to %s",
2495 (int)pid
, fullpath
);
2501 /* Called externally (i.e. from 'lxc-cgroup') to query cgroup limits. Here we
2502 * don't have a cgroup_data set up, so we ask the running container through the
2503 * commands API for the cgroup path.
2505 __cgfsng_ops
static int cgfsng_get(struct cgroup_ops
*ops
, const char *filename
,
2506 char *value
, size_t len
, const char *name
,
2507 const char *lxcpath
)
2509 __do_free
char *path
= NULL
;
2510 __do_free
char *controller
= NULL
;
2512 struct hierarchy
*h
;
2516 return ret_set_errno(-1, ENOENT
);
2518 controller
= must_copy_string(filename
);
2519 p
= strchr(controller
, '.');
2523 path
= lxc_cmd_get_limiting_cgroup_path(name
, lxcpath
, controller
);
2528 h
= get_hierarchy(ops
, controller
);
2530 __do_free
char *fullpath
= NULL
;
2532 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2533 ret
= lxc_read_from_file(fullpath
, value
, len
);
2539 static int device_cgroup_parse_access(struct device_item
*device
, const char *val
)
2541 for (int count
= 0; count
< 3; count
++, val
++) {
2544 device
->access
[count
] = *val
;
2547 device
->access
[count
] = *val
;
2550 device
->access
[count
] = *val
;
2557 return ret_errno(EINVAL
);
2564 static int device_cgroup_rule_parse(struct device_item
*device
, const char *key
,
2570 if (strcmp("devices.allow", key
) == 0)
2575 if (strcmp(val
, "a") == 0) {
2580 device
->global_rule
= device
->allow
2581 ? LXC_BPF_DEVICE_CGROUP_DENYLIST
2582 : LXC_BPF_DEVICE_CGROUP_ALLOWLIST
;
2588 device
->global_rule
= LXC_BPF_DEVICE_CGROUP_LOCAL_RULE
;
2596 device
->type
= *val
;
2609 } else if (isdigit(*val
)) {
2610 memset(temp
, 0, sizeof(temp
));
2611 for (count
= 0; count
< sizeof(temp
) - 1; count
++) {
2617 ret
= lxc_safe_int(temp
, &device
->major
);
2631 } else if (isdigit(*val
)) {
2632 memset(temp
, 0, sizeof(temp
));
2633 for (count
= 0; count
< sizeof(temp
) - 1; count
++) {
2639 ret
= lxc_safe_int(temp
, &device
->minor
);
2648 return device_cgroup_parse_access(device
, ++val
);
2651 /* Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits. Here we
2652 * don't have a cgroup_data set up, so we ask the running container through the
2653 * commands API for the cgroup path.
2655 __cgfsng_ops
static int cgfsng_set(struct cgroup_ops
*ops
,
2656 const char *key
, const char *value
,
2657 const char *name
, const char *lxcpath
)
2659 __do_free
char *path
= NULL
;
2660 __do_free
char *controller
= NULL
;
2662 struct hierarchy
*h
;
2666 return ret_set_errno(-1, ENOENT
);
2668 controller
= must_copy_string(key
);
2669 p
= strchr(controller
, '.');
2673 if (pure_unified_layout(ops
) && strcmp(controller
, "devices") == 0) {
2674 struct device_item device
= {};
2676 ret
= device_cgroup_rule_parse(&device
, key
, value
);
2678 return log_error_errno(-1, EINVAL
, "Failed to parse device string %s=%s",
2681 ret
= lxc_cmd_add_bpf_device_cgroup(name
, lxcpath
, &device
);
2688 path
= lxc_cmd_get_limiting_cgroup_path(name
, lxcpath
, controller
);
2693 h
= get_hierarchy(ops
, controller
);
2695 __do_free
char *fullpath
= NULL
;
2697 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, key
);
2698 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2704 /* take devices cgroup line
2706 * and convert it to a valid
2707 * type major:minor mode
2708 * line. Return <0 on error. Dest is a preallocated buffer long enough to hold
2711 static int device_cgroup_rule_parse_devpath(struct device_item
*device
,
2712 const char *devpath
)
2714 __do_free
char *path
= NULL
;
2720 path
= must_copy_string(devpath
);
2723 * Read path followed by mode. Ignore any trailing text.
2724 * A ' # comment' would be legal. Technically other text is not
2725 * legal, we could check for that if we cared to.
2727 for (n_parts
= 1, p
= path
; *p
; p
++) {
2743 return ret_set_errno(-1, EINVAL
);
2747 return ret_errno(EINVAL
);
2749 if (device_cgroup_parse_access(device
, mode
) < 0)
2753 return ret_set_errno(-1, EINVAL
);
2755 ret
= stat(path
, &sb
);
2757 return ret_set_errno(-1, errno
);
2759 mode_t m
= sb
.st_mode
& S_IFMT
;
2768 return log_error_errno(-1, EINVAL
, "Unsupported device type %i for \"%s\"", m
, path
);
2771 device
->major
= MAJOR(sb
.st_rdev
);
2772 device
->minor
= MINOR(sb
.st_rdev
);
2774 device
->global_rule
= LXC_BPF_DEVICE_CGROUP_LOCAL_RULE
;
2779 static int convert_devpath(const char *invalue
, char *dest
)
2781 struct device_item device
= {};
2784 ret
= device_cgroup_rule_parse_devpath(&device
, invalue
);
2788 ret
= snprintf(dest
, 50, "%c %d:%d %s", device
.type
, device
.major
,
2789 device
.minor
, device
.access
);
2790 if (ret
< 0 || ret
>= 50)
2791 return log_error_errno(-1, ENAMETOOLONG
, "Error on configuration value \"%c %d:%d %s\" (max 50 chars)",
2792 device
.type
, device
.major
, device
.minor
, device
.access
);
2797 /* Called from setup_limits - here we have the container's cgroup_data because
2798 * we created the cgroups.
2800 static int cg_legacy_set_data(struct cgroup_ops
*ops
, const char *filename
,
2801 const char *value
, bool is_cpuset
)
2803 __do_free
char *controller
= NULL
;
2805 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2806 char converted_value
[50];
2807 struct hierarchy
*h
;
2809 controller
= must_copy_string(filename
);
2810 p
= strchr(controller
, '.');
2814 if (strcmp("devices.allow", filename
) == 0 && value
[0] == '/') {
2817 ret
= convert_devpath(value
, converted_value
);
2820 value
= converted_value
;
2823 h
= get_hierarchy(ops
, controller
);
2825 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
);
2828 int ret
= lxc_write_openat(h
->container_full_path
, filename
, value
, strlen(value
));
2832 return lxc_write_openat(h
->container_limit_path
, filename
, value
, strlen(value
));
2835 __cgfsng_ops
static bool cgfsng_setup_limits_legacy(struct cgroup_ops
*ops
,
2836 struct lxc_conf
*conf
,
2839 __do_free
struct lxc_list
*sorted_cgroup_settings
= NULL
;
2840 struct lxc_list
*cgroup_settings
= &conf
->cgroup
;
2841 struct lxc_list
*iterator
, *next
;
2842 struct lxc_cgroup
*cg
;
2846 return ret_set_errno(false, ENOENT
);
2849 return ret_set_errno(false, EINVAL
);
2851 cgroup_settings
= &conf
->cgroup
;
2852 if (lxc_list_empty(cgroup_settings
))
2855 if (!ops
->hierarchies
)
2856 return ret_set_errno(false, EINVAL
);
2858 if (pure_unified_layout(ops
))
2859 return log_warn_errno(true, EINVAL
, "Ignoring legacy cgroup limits on pure cgroup2 system");
2861 sorted_cgroup_settings
= sort_cgroup_settings(cgroup_settings
);
2862 if (!sorted_cgroup_settings
)
2865 lxc_list_for_each(iterator
, sorted_cgroup_settings
) {
2866 cg
= iterator
->elem
;
2868 if (do_devices
== !strncmp("devices", cg
->subsystem
, 7)) {
2869 if (cg_legacy_set_data(ops
, cg
->subsystem
, cg
->value
, strncmp("cpuset", cg
->subsystem
, 6) == 0)) {
2870 if (do_devices
&& (errno
== EACCES
|| errno
== EPERM
)) {
2871 SYSWARN("Failed to set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2874 SYSERROR("Failed to set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2877 DEBUG("Set controller \"%s\" set to \"%s\"", cg
->subsystem
, cg
->value
);
2882 INFO("Limits for the legacy cgroup hierarchies have been setup");
2884 lxc_list_for_each_safe(iterator
, sorted_cgroup_settings
, next
) {
2885 lxc_list_del(iterator
);
2893 * Some of the parsing logic comes from the original cgroup device v1
2894 * implementation in the kernel.
2896 static int bpf_device_cgroup_prepare(struct cgroup_ops
*ops
,
2897 struct lxc_conf
*conf
, const char *key
,
2900 #ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
2901 struct device_item device_item
= {};
2904 if (strcmp("devices.allow", key
) == 0 && *val
== '/')
2905 ret
= device_cgroup_rule_parse_devpath(&device_item
, val
);
2907 ret
= device_cgroup_rule_parse(&device_item
, key
, val
);
2909 return log_error_errno(-1, EINVAL
, "Failed to parse device string %s=%s", key
, val
);
2911 ret
= bpf_list_add_device(conf
, &device_item
);
2918 __cgfsng_ops
static bool cgfsng_setup_limits(struct cgroup_ops
*ops
,
2919 struct lxc_handler
*handler
)
2921 struct lxc_list
*cgroup_settings
, *iterator
;
2922 struct hierarchy
*h
;
2923 struct lxc_conf
*conf
;
2926 return ret_set_errno(false, ENOENT
);
2928 if (!ops
->hierarchies
)
2931 if (!ops
->container_cgroup
)
2932 return ret_set_errno(false, EINVAL
);
2934 if (!handler
|| !handler
->conf
)
2935 return ret_set_errno(false, EINVAL
);
2936 conf
= handler
->conf
;
2938 cgroup_settings
= &conf
->cgroup2
;
2939 if (lxc_list_empty(cgroup_settings
))
2942 if (!pure_unified_layout(ops
))
2943 return log_warn_errno(true, EINVAL
, "Ignoring cgroup2 limits on legacy cgroup system");
2949 lxc_list_for_each (iterator
, cgroup_settings
) {
2950 struct lxc_cgroup
*cg
= iterator
->elem
;
2953 if (strncmp("devices", cg
->subsystem
, 7) == 0)
2954 ret
= bpf_device_cgroup_prepare(ops
, conf
, cg
->subsystem
, cg
->value
);
2956 ret
= lxc_write_openat(h
->container_limit_path
, cg
->subsystem
, cg
->value
, strlen(cg
->value
));
2958 return log_error_errno(false, errno
, "Failed to set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2960 TRACE("Set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2963 return log_info(true, "Limits for the unified cgroup hierarchy have been setup");
2966 __cgfsng_ops
static bool cgfsng_devices_activate(struct cgroup_ops
*ops
, struct lxc_handler
*handler
)
2968 #ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
2969 __do_bpf_program_free
struct bpf_program
*devices
= NULL
;
2971 struct lxc_conf
*conf
;
2972 struct hierarchy
*unified
;
2973 struct lxc_list
*it
;
2974 struct bpf_program
*devices_old
;
2977 return ret_set_errno(false, ENOENT
);
2979 if (!ops
->hierarchies
)
2982 if (!ops
->container_cgroup
)
2983 return ret_set_errno(false, EEXIST
);
2985 if (!handler
|| !handler
->conf
)
2986 return ret_set_errno(false, EINVAL
);
2987 conf
= handler
->conf
;
2989 unified
= ops
->unified
;
2990 if (!unified
|| !unified
->bpf_device_controller
||
2991 !unified
->container_full_path
|| lxc_list_empty(&conf
->devices
))
2994 devices
= bpf_program_new(BPF_PROG_TYPE_CGROUP_DEVICE
);
2996 return log_error_errno(false, ENOMEM
, "Failed to create new bpf program");
2998 ret
= bpf_program_init(devices
);
3000 return log_error_errno(false, ENOMEM
, "Failed to initialize bpf program");
3002 lxc_list_for_each(it
, &conf
->devices
) {
3003 struct device_item
*cur
= it
->elem
;
3005 ret
= bpf_program_append_device(devices
, cur
);
3007 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",
3014 TRACE("Added rule to bpf device program: type %c, major %d, minor %d, access %s, allow %d, global_rule %d",
3023 ret
= bpf_program_finalize(devices
);
3025 return log_error_errno(false, ENOMEM
, "Failed to finalize bpf program");
3027 ret
= bpf_program_cgroup_attach(devices
, BPF_CGROUP_DEVICE
,
3028 unified
->container_limit_path
,
3031 return log_error_errno(false, ENOMEM
, "Failed to attach bpf program");
3033 /* Replace old bpf program. */
3034 devices_old
= move_ptr(conf
->cgroup2_devices
);
3035 conf
->cgroup2_devices
= move_ptr(devices
);
3036 devices
= move_ptr(devices_old
);
3041 static bool __cgfsng_delegate_controllers(struct cgroup_ops
*ops
, const char *cgroup
)
3043 __do_free
char *add_controllers
= NULL
, *base_path
= NULL
;
3044 __do_free_string_list
char **parts
= NULL
;
3045 struct hierarchy
*unified
= ops
->unified
;
3048 size_t full_len
= 0;
3050 if (!ops
->hierarchies
|| !pure_unified_layout(ops
) ||
3051 !unified
->controllers
[0])
3054 /* For now we simply enable all controllers that we have detected by
3055 * creating a string like "+memory +pids +cpu +io".
3056 * TODO: In the near future we might want to support "-<controller>"
3057 * etc. but whether supporting semantics like this make sense will need
3060 for (it
= unified
->controllers
; it
&& *it
; it
++) {
3061 full_len
+= strlen(*it
) + 2;
3062 add_controllers
= must_realloc(add_controllers
, full_len
+ 1);
3064 if (unified
->controllers
[0] == *it
)
3065 add_controllers
[0] = '\0';
3067 (void)strlcat(add_controllers
, "+", full_len
+ 1);
3068 (void)strlcat(add_controllers
, *it
, full_len
+ 1);
3070 if ((it
+ 1) && *(it
+ 1))
3071 (void)strlcat(add_controllers
, " ", full_len
+ 1);
3074 parts
= lxc_string_split(cgroup
, '/');
3078 parts_len
= lxc_array_len((void **)parts
);
3082 base_path
= must_make_path(unified
->mountpoint
, unified
->container_base_path
, NULL
);
3083 for (ssize_t i
= -1; i
< parts_len
; i
++) {
3085 __do_free
char *target
= NULL
;
3088 base_path
= must_append_path(base_path
, parts
[i
], NULL
);
3089 target
= must_make_path(base_path
, "cgroup.subtree_control", NULL
);
3090 ret
= lxc_writeat(-1, target
, add_controllers
, full_len
);
3092 return log_error_errno(false, errno
, "Could not enable \"%s\" controllers in the unified cgroup \"%s\"",
3093 add_controllers
, target
);
3094 TRACE("Enable \"%s\" controllers in the unified cgroup \"%s\"", add_controllers
, target
);
3100 __cgfsng_ops
static bool cgfsng_monitor_delegate_controllers(struct cgroup_ops
*ops
)
3103 return ret_set_errno(false, ENOENT
);
3105 return __cgfsng_delegate_controllers(ops
, ops
->monitor_cgroup
);
3108 __cgfsng_ops
static bool cgfsng_payload_delegate_controllers(struct cgroup_ops
*ops
)
3111 return ret_set_errno(false, ENOENT
);
3113 return __cgfsng_delegate_controllers(ops
, ops
->container_cgroup
);
3116 static bool cgroup_use_wants_controllers(const struct cgroup_ops
*ops
,
3119 if (!ops
->cgroup_use
)
3122 for (char **cur_ctrl
= controllers
; cur_ctrl
&& *cur_ctrl
; cur_ctrl
++) {
3125 for (char **cur_use
= ops
->cgroup_use
; cur_use
&& *cur_use
; cur_use
++) {
3126 if (strcmp(*cur_use
, *cur_ctrl
) != 0)
3142 static void cg_unified_delegate(char ***delegate
)
3144 __do_free
char *buf
= NULL
;
3145 char *standard
[] = {"cgroup.subtree_control", "cgroup.threads", NULL
};
3149 buf
= read_file("/sys/kernel/cgroup/delegate");
3151 for (char **p
= standard
; p
&& *p
; p
++) {
3152 idx
= append_null_to_list((void ***)delegate
);
3153 (*delegate
)[idx
] = must_copy_string(*p
);
3155 SYSWARN("Failed to read /sys/kernel/cgroup/delegate");
3159 lxc_iterate_parts(token
, buf
, " \t\n") {
3161 * We always need to chown this for both cgroup and
3164 if (strcmp(token
, "cgroup.procs") == 0)
3167 idx
= append_null_to_list((void ***)delegate
);
3168 (*delegate
)[idx
] = must_copy_string(token
);
3172 /* At startup, parse_hierarchies finds all the info we need about cgroup
3173 * mountpoints and current cgroups, and stores it in @d.
3175 static int cg_hybrid_init(struct cgroup_ops
*ops
, bool relative
, bool unprivileged
)
3177 __do_free
char *basecginfo
= NULL
, *line
= NULL
;
3178 __do_free_string_list
char **klist
= NULL
, **nlist
= NULL
;
3179 __do_fclose
FILE *f
= NULL
;
3183 /* Root spawned containers escape the current cgroup, so use init's
3184 * cgroups as our base in that case.
3186 if (!relative
&& (geteuid() == 0))
3187 basecginfo
= read_file("/proc/1/cgroup");
3189 basecginfo
= read_file("/proc/self/cgroup");
3191 return ret_set_errno(-1, ENOMEM
);
3193 ret
= get_existing_subsystems(&klist
, &nlist
);
3195 return log_error_errno(-1, errno
, "Failed to retrieve available legacy cgroup controllers");
3197 f
= fopen("/proc/self/mountinfo", "re");
3199 return log_error_errno(-1, errno
, "Failed to open \"/proc/self/mountinfo\"");
3201 lxc_cgfsng_print_basecg_debuginfo(basecginfo
, klist
, nlist
);
3203 while (getline(&line
, &len
, f
) != -1) {
3204 __do_free
char *base_cgroup
= NULL
, *mountpoint
= NULL
;
3205 __do_free_string_list
char **controller_list
= NULL
;
3208 struct hierarchy
*new;
3210 type
= get_cgroup_version(line
);
3214 if (type
== CGROUP2_SUPER_MAGIC
&& ops
->unified
)
3217 if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNKNOWN
) {
3218 if (type
== CGROUP2_SUPER_MAGIC
)
3219 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
3220 else if (type
== CGROUP_SUPER_MAGIC
)
3221 ops
->cgroup_layout
= CGROUP_LAYOUT_LEGACY
;
3222 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNIFIED
) {
3223 if (type
== CGROUP_SUPER_MAGIC
)
3224 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
3225 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_LEGACY
) {
3226 if (type
== CGROUP2_SUPER_MAGIC
)
3227 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
3230 controller_list
= cg_hybrid_get_controllers(klist
, nlist
, line
, type
);
3231 if (!controller_list
&& type
== CGROUP_SUPER_MAGIC
)
3234 if (type
== CGROUP_SUPER_MAGIC
)
3235 if (controller_list_is_dup(ops
->hierarchies
, controller_list
)) {
3236 TRACE("Skipping duplicating controller");
3240 mountpoint
= cg_hybrid_get_mountpoint(line
);
3242 WARN("Failed parsing mountpoint from \"%s\"", line
);
3246 if (type
== CGROUP_SUPER_MAGIC
)
3247 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, controller_list
[0], CGROUP_SUPER_MAGIC
);
3249 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, NULL
, CGROUP2_SUPER_MAGIC
);
3251 WARN("Failed to find current cgroup");
3256 prune_init_scope(base_cgroup
);
3257 if (type
== CGROUP2_SUPER_MAGIC
)
3258 writeable
= test_writeable_v2(mountpoint
, base_cgroup
);
3260 writeable
= test_writeable_v1(mountpoint
, base_cgroup
);
3262 TRACE("The %s group is not writeable", base_cgroup
);
3266 if (type
== CGROUP2_SUPER_MAGIC
) {
3267 char *cgv2_ctrl_path
;
3269 cgv2_ctrl_path
= must_make_path(mountpoint
, base_cgroup
,
3270 "cgroup.controllers",
3273 controller_list
= cg_unified_get_controllers(cgv2_ctrl_path
);
3274 free(cgv2_ctrl_path
);
3275 if (!controller_list
) {
3276 controller_list
= cg_unified_make_empty_controller();
3277 TRACE("No controllers are enabled for "
3278 "delegation in the unified hierarchy");
3282 /* Exclude all controllers that cgroup use does not want. */
3283 if (!cgroup_use_wants_controllers(ops
, controller_list
)) {
3284 TRACE("Skipping controller");
3288 new = add_hierarchy(&ops
->hierarchies
, move_ptr(controller_list
), move_ptr(mountpoint
), move_ptr(base_cgroup
), type
);
3289 if (type
== CGROUP2_SUPER_MAGIC
&& !ops
->unified
) {
3291 cg_unified_delegate(&new->cgroup2_chown
);
3296 TRACE("Writable cgroup hierarchies:");
3297 lxc_cgfsng_print_hierarchies(ops
);
3299 /* verify that all controllers in cgroup.use and all crucial
3300 * controllers are accounted for
3302 if (!all_controllers_found(ops
))
3303 return log_error_errno(-1, ENOENT
, "Failed to find all required controllers");
3308 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
3309 static char *cg_unified_get_current_cgroup(bool relative
)
3311 __do_free
char *basecginfo
= NULL
;
3315 if (!relative
&& (geteuid() == 0))
3316 basecginfo
= read_file("/proc/1/cgroup");
3318 basecginfo
= read_file("/proc/self/cgroup");
3322 base_cgroup
= strstr(basecginfo
, "0::/");
3326 base_cgroup
= base_cgroup
+ 3;
3327 copy
= copy_to_eol(base_cgroup
);
3334 static int cg_unified_init(struct cgroup_ops
*ops
, bool relative
,
3337 __do_free
char *subtree_path
= NULL
;
3341 struct hierarchy
*new;
3342 char *base_cgroup
= NULL
;
3344 ret
= unified_cgroup_hierarchy();
3345 if (ret
== -ENOMEDIUM
)
3346 return ret_errno(ENOMEDIUM
);
3348 if (ret
!= CGROUP2_SUPER_MAGIC
)
3351 base_cgroup
= cg_unified_get_current_cgroup(relative
);
3353 return ret_errno(EINVAL
);
3355 prune_init_scope(base_cgroup
);
3358 * We assume that the cgroup we're currently in has been delegated to
3359 * us and we are free to further delege all of the controllers listed
3360 * in cgroup.controllers further down the hierarchy.
3362 mountpoint
= must_copy_string(DEFAULT_CGROUP_MOUNTPOINT
);
3363 subtree_path
= must_make_path(mountpoint
, base_cgroup
, "cgroup.controllers", NULL
);
3364 delegatable
= cg_unified_get_controllers(subtree_path
);
3366 delegatable
= cg_unified_make_empty_controller();
3367 if (!delegatable
[0])
3368 TRACE("No controllers are enabled for delegation");
3370 /* TODO: If the user requested specific controllers via lxc.cgroup.use
3371 * we should verify here. The reason I'm not doing it right is that I'm
3372 * not convinced that lxc.cgroup.use will be the future since it is a
3373 * global property. I much rather have an option that lets you request
3374 * controllers per container.
3377 new = add_hierarchy(&ops
->hierarchies
, delegatable
, mountpoint
, base_cgroup
, CGROUP2_SUPER_MAGIC
);
3379 cg_unified_delegate(&new->cgroup2_chown
);
3381 if (bpf_devices_cgroup_supported())
3382 new->bpf_device_controller
= 1;
3384 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
3387 return CGROUP2_SUPER_MAGIC
;
3390 static int cg_init(struct cgroup_ops
*ops
, struct lxc_conf
*conf
)
3394 bool relative
= conf
->cgroup_meta
.relative
;
3396 tmp
= lxc_global_config_value("lxc.cgroup.use");
3398 __do_free
char *pin
= NULL
;
3401 pin
= must_copy_string(tmp
);
3404 lxc_iterate_parts(cur
, chop
, ",")
3405 must_append_string(&ops
->cgroup_use
, cur
);
3408 ret
= cg_unified_init(ops
, relative
, !lxc_list_empty(&conf
->id_map
));
3412 if (ret
== CGROUP2_SUPER_MAGIC
)
3415 return cg_hybrid_init(ops
, relative
, !lxc_list_empty(&conf
->id_map
));
3418 __cgfsng_ops
static int cgfsng_data_init(struct cgroup_ops
*ops
)
3420 const char *cgroup_pattern
;
3423 return ret_set_errno(-1, ENOENT
);
3425 /* copy system-wide cgroup information */
3426 cgroup_pattern
= lxc_global_config_value("lxc.cgroup.pattern");
3427 if (cgroup_pattern
&& strcmp(cgroup_pattern
, "") != 0)
3428 ops
->cgroup_pattern
= must_copy_string(cgroup_pattern
);
3433 struct cgroup_ops
*cgfsng_ops_init(struct lxc_conf
*conf
)
3435 __do_free
struct cgroup_ops
*cgfsng_ops
= NULL
;
3437 cgfsng_ops
= malloc(sizeof(struct cgroup_ops
));
3439 return ret_set_errno(NULL
, ENOMEM
);
3441 memset(cgfsng_ops
, 0, sizeof(struct cgroup_ops
));
3442 cgfsng_ops
->cgroup_layout
= CGROUP_LAYOUT_UNKNOWN
;
3444 if (cg_init(cgfsng_ops
, conf
))
3447 cgfsng_ops
->data_init
= cgfsng_data_init
;
3448 cgfsng_ops
->payload_destroy
= cgfsng_payload_destroy
;
3449 cgfsng_ops
->monitor_destroy
= cgfsng_monitor_destroy
;
3450 cgfsng_ops
->monitor_create
= cgfsng_monitor_create
;
3451 cgfsng_ops
->monitor_enter
= cgfsng_monitor_enter
;
3452 cgfsng_ops
->monitor_delegate_controllers
= cgfsng_monitor_delegate_controllers
;
3453 cgfsng_ops
->payload_delegate_controllers
= cgfsng_payload_delegate_controllers
;
3454 cgfsng_ops
->payload_create
= cgfsng_payload_create
;
3455 cgfsng_ops
->payload_enter
= cgfsng_payload_enter
;
3456 cgfsng_ops
->payload_finalize
= cgfsng_payload_finalize
;
3457 cgfsng_ops
->escape
= cgfsng_escape
;
3458 cgfsng_ops
->num_hierarchies
= cgfsng_num_hierarchies
;
3459 cgfsng_ops
->get_hierarchies
= cgfsng_get_hierarchies
;
3460 cgfsng_ops
->get_cgroup
= cgfsng_get_cgroup
;
3461 cgfsng_ops
->get
= cgfsng_get
;
3462 cgfsng_ops
->set
= cgfsng_set
;
3463 cgfsng_ops
->freeze
= cgfsng_freeze
;
3464 cgfsng_ops
->unfreeze
= cgfsng_unfreeze
;
3465 cgfsng_ops
->setup_limits_legacy
= cgfsng_setup_limits_legacy
;
3466 cgfsng_ops
->setup_limits
= cgfsng_setup_limits
;
3467 cgfsng_ops
->driver
= "cgfsng";
3468 cgfsng_ops
->version
= "1.0.0";
3469 cgfsng_ops
->attach
= cgfsng_attach
;
3470 cgfsng_ops
->chown
= cgfsng_chown
;
3471 cgfsng_ops
->mount
= cgfsng_mount
;
3472 cgfsng_ops
->devices_activate
= cgfsng_devices_activate
;
3473 cgfsng_ops
->get_limiting_cgroup
= cgfsng_get_limiting_cgroup
;
3475 return move_ptr(cgfsng_ops
);