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 !ops
->setup_limits_legacy(ops
, conf
, true))
1199 return log_error(false, "Failed to setup legacy device limits");
1202 ret
= mkdir_eexist_on_last(path
, 0755);
1205 * This is the cpuset controller and
1206 * cg_legacy_handle_cpuset_hierarchy() has created our target
1207 * directory for us to ensure correct initialization.
1209 if (ret_cpuset
!= 1 || cgroup_tree
)
1210 return log_error_errno(false, errno
, "Failed to create %s cgroup", path
);
1214 h
->cgfd_con
= lxc_open_dirfd(path
);
1215 if (h
->cgfd_con
< 0)
1216 return log_error_errno(false, errno
, "Failed to open %s", path
);
1217 h
->container_full_path
= move_ptr(path
);
1218 if (h
->cgfd_limit
< 0)
1219 h
->cgfd_limit
= h
->cgfd_con
;
1220 if (!h
->container_limit_path
)
1221 h
->container_limit_path
= h
->container_full_path
;
1223 h
->cgfd_mon
= lxc_open_dirfd(path
);
1224 if (h
->cgfd_mon
< 0)
1225 return log_error_errno(false, errno
, "Failed to open %s", path
);
1226 h
->monitor_full_path
= move_ptr(path
);
1232 static void cgroup_tree_leaf_remove(struct hierarchy
*h
, bool payload
)
1234 __do_free
char *full_path
= NULL
, *__limit_path
= NULL
;
1235 char *limit_path
= NULL
;
1238 __lxc_unused __do_close
int fd
= move_fd(h
->cgfd_con
);
1239 full_path
= move_ptr(h
->container_full_path
);
1240 limit_path
= move_ptr(h
->container_limit_path
);
1241 if (limit_path
!= full_path
)
1242 __limit_path
= limit_path
;
1244 __lxc_unused __do_close
int fd
= move_fd(h
->cgfd_mon
);
1245 full_path
= move_ptr(h
->monitor_full_path
);
1248 if (full_path
&& rmdir(full_path
))
1249 SYSWARN("Failed to rmdir(\"%s\") cgroup", full_path
);
1250 if (limit_path
&& rmdir(limit_path
))
1251 SYSWARN("Failed to rmdir(\"%s\") cgroup", limit_path
);
1255 * Check we have no lxc.cgroup.dir, and that lxc.cgroup.dir.limit_prefix is a
1256 * proper prefix directory of lxc.cgroup.dir.payload.
1258 * Returns the prefix length if it is set, otherwise zero on success.
1260 static bool check_cgroup_dir_config(struct lxc_conf
*conf
)
1262 const char *monitor_dir
= conf
->cgroup_meta
.monitor_dir
,
1263 *container_dir
= conf
->cgroup_meta
.container_dir
,
1264 *namespace_dir
= conf
->cgroup_meta
.namespace_dir
;
1266 /* none of the new options are set, all is fine */
1267 if (!monitor_dir
&& !container_dir
&& !namespace_dir
)
1270 /* some are set, make sure lxc.cgroup.dir is not also set*/
1271 if (conf
->cgroup_meta
.dir
)
1272 return log_error_errno(false, EINVAL
,
1273 "lxc.cgroup.dir conflicts with lxc.cgroup.dir.payload/monitor");
1275 /* make sure both monitor and payload are set */
1276 if (!monitor_dir
|| !container_dir
)
1277 return log_error_errno(false, EINVAL
,
1278 "lxc.cgroup.dir.payload and lxc.cgroup.dir.monitor must both be set");
1280 /* namespace_dir may be empty */
1284 __cgfsng_ops
static inline bool cgfsng_monitor_create(struct cgroup_ops
*ops
,
1285 struct lxc_handler
*handler
)
1287 __do_free
char *monitor_cgroup
= NULL
, *__cgroup_tree
= NULL
;
1288 const char *cgroup_tree
;
1292 char *suffix
= NULL
;
1293 struct lxc_conf
*conf
;
1296 return ret_set_errno(false, ENOENT
);
1298 if (!ops
->hierarchies
)
1301 if (ops
->monitor_cgroup
)
1302 return ret_set_errno(false, EEXIST
);
1304 if (!handler
|| !handler
->conf
)
1305 return ret_set_errno(false, EINVAL
);
1307 conf
= handler
->conf
;
1309 if (!check_cgroup_dir_config(conf
))
1312 if (conf
->cgroup_meta
.monitor_dir
) {
1314 monitor_cgroup
= strdup(conf
->cgroup_meta
.monitor_dir
);
1315 } else if (conf
->cgroup_meta
.dir
) {
1316 cgroup_tree
= conf
->cgroup_meta
.dir
;
1317 monitor_cgroup
= must_concat(&len
, conf
->cgroup_meta
.dir
, "/",
1318 DEFAULT_MONITOR_CGROUP_PREFIX
,
1320 CGROUP_CREATE_RETRY
, NULL
);
1321 } else if (ops
->cgroup_pattern
) {
1322 __cgroup_tree
= lxc_string_replace("%n", handler
->name
, ops
->cgroup_pattern
);
1324 return ret_set_errno(false, ENOMEM
);
1326 cgroup_tree
= __cgroup_tree
;
1327 monitor_cgroup
= must_concat(&len
, cgroup_tree
, "/",
1328 DEFAULT_MONITOR_CGROUP
,
1329 CGROUP_CREATE_RETRY
, NULL
);
1332 monitor_cgroup
= must_concat(&len
, DEFAULT_MONITOR_CGROUP_PREFIX
,
1334 CGROUP_CREATE_RETRY
, NULL
);
1336 if (!monitor_cgroup
)
1337 return ret_set_errno(false, ENOMEM
);
1339 if (!conf
->cgroup_meta
.monitor_dir
) {
1340 suffix
= monitor_cgroup
+ len
- CGROUP_CREATE_RETRY_LEN
;
1345 sprintf(suffix
, "-%d", idx
);
1347 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1348 if (cgroup_tree_create(ops
, handler
->conf
,
1349 ops
->hierarchies
[i
], cgroup_tree
,
1350 monitor_cgroup
, false, NULL
))
1353 ERROR("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->monitor_full_path
?: "(null)");
1354 for (int j
= 0; j
< i
; j
++)
1355 cgroup_tree_leaf_remove(ops
->hierarchies
[j
], false);
1360 } while (ops
->hierarchies
[i
] && idx
> 0 && idx
< 1000 && suffix
);
1362 if (idx
== 1000 || (!suffix
&& idx
!= 0))
1363 return ret_set_errno(false, ERANGE
);
1365 ops
->monitor_cgroup
= move_ptr(monitor_cgroup
);
1366 return log_info(true, "The monitor process uses \"%s\" as cgroup", ops
->monitor_cgroup
);
1370 * Try to create the same cgroup in all hierarchies. Start with cgroup_pattern;
1371 * next cgroup_pattern-1, -2, ..., -999.
1373 __cgfsng_ops
static inline bool cgfsng_payload_create(struct cgroup_ops
*ops
,
1374 struct lxc_handler
*handler
)
1376 __do_free
char *container_cgroup
= NULL
,
1377 *__cgroup_tree
= NULL
,
1378 *limiting_cgroup
= NULL
;
1379 const char *cgroup_tree
;
1383 char *suffix
= NULL
;
1384 struct lxc_conf
*conf
;
1387 return ret_set_errno(false, ENOENT
);
1389 if (!ops
->hierarchies
)
1392 if (ops
->container_cgroup
)
1393 return ret_set_errno(false, EEXIST
);
1395 if (!handler
|| !handler
->conf
)
1396 return ret_set_errno(false, EINVAL
);
1398 conf
= handler
->conf
;
1400 if (!check_cgroup_dir_config(conf
))
1403 if (conf
->cgroup_meta
.container_dir
) {
1406 limiting_cgroup
= strdup(conf
->cgroup_meta
.container_dir
);
1407 if (!limiting_cgroup
)
1408 return ret_set_errno(false, ENOMEM
);
1410 if (conf
->cgroup_meta
.namespace_dir
) {
1411 container_cgroup
= must_make_path(limiting_cgroup
,
1412 conf
->cgroup_meta
.namespace_dir
,
1415 /* explicit paths but without isolation */
1416 container_cgroup
= move_ptr(limiting_cgroup
);
1418 } else if (conf
->cgroup_meta
.dir
) {
1419 cgroup_tree
= conf
->cgroup_meta
.dir
;
1420 container_cgroup
= must_concat(&len
, cgroup_tree
, "/",
1421 DEFAULT_PAYLOAD_CGROUP_PREFIX
,
1423 CGROUP_CREATE_RETRY
, NULL
);
1424 } else if (ops
->cgroup_pattern
) {
1425 __cgroup_tree
= lxc_string_replace("%n", handler
->name
, ops
->cgroup_pattern
);
1427 return ret_set_errno(false, ENOMEM
);
1429 cgroup_tree
= __cgroup_tree
;
1430 container_cgroup
= must_concat(&len
, cgroup_tree
, "/",
1431 DEFAULT_PAYLOAD_CGROUP
,
1432 CGROUP_CREATE_RETRY
, NULL
);
1435 container_cgroup
= must_concat(&len
, DEFAULT_PAYLOAD_CGROUP_PREFIX
,
1437 CGROUP_CREATE_RETRY
, NULL
);
1439 if (!container_cgroup
)
1440 return ret_set_errno(false, ENOMEM
);
1442 if (!conf
->cgroup_meta
.container_dir
) {
1443 suffix
= container_cgroup
+ len
- CGROUP_CREATE_RETRY_LEN
;
1448 sprintf(suffix
, "-%d", idx
);
1450 for (i
= 0; ops
->hierarchies
[i
]; i
++) {
1451 if (cgroup_tree_create(ops
, handler
->conf
,
1452 ops
->hierarchies
[i
], cgroup_tree
,
1453 container_cgroup
, true,
1457 ERROR("Failed to create cgroup \"%s\"", ops
->hierarchies
[i
]->container_full_path
?: "(null)");
1458 for (int j
= 0; j
< i
; j
++)
1459 cgroup_tree_leaf_remove(ops
->hierarchies
[j
], true);
1464 } while (ops
->hierarchies
[i
] && idx
> 0 && idx
< 1000 && suffix
);
1466 if (idx
== 1000 || (!suffix
&& idx
!= 0))
1467 return ret_set_errno(false, ERANGE
);
1469 ops
->container_cgroup
= move_ptr(container_cgroup
);
1470 INFO("The container process uses \"%s\" as cgroup", ops
->container_cgroup
);
1474 __cgfsng_ops
static bool cgfsng_monitor_enter(struct cgroup_ops
*ops
,
1475 struct lxc_handler
*handler
)
1477 int monitor_len
, transient_len
= 0;
1478 char monitor
[INTTYPE_TO_STRLEN(pid_t
)],
1479 transient
[INTTYPE_TO_STRLEN(pid_t
)];
1482 return ret_set_errno(false, ENOENT
);
1484 if (!ops
->hierarchies
)
1487 if (!ops
->monitor_cgroup
)
1488 return ret_set_errno(false, ENOENT
);
1490 if (!handler
|| !handler
->conf
)
1491 return ret_set_errno(false, EINVAL
);
1493 monitor_len
= snprintf(monitor
, sizeof(monitor
), "%d", handler
->monitor_pid
);
1494 if (handler
->transient_pid
> 0)
1495 transient_len
= snprintf(transient
, sizeof(transient
), "%d", handler
->transient_pid
);
1497 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1498 struct hierarchy
*h
= ops
->hierarchies
[i
];
1501 ret
= lxc_writeat(h
->cgfd_mon
, "cgroup.procs", monitor
, monitor_len
);
1503 return log_error_errno(false, errno
, "Failed to enter cgroup \"%s\"", h
->monitor_full_path
);
1505 if (handler
->transient_pid
<= 0)
1508 ret
= lxc_writeat(h
->cgfd_mon
, "cgroup.procs", transient
, transient_len
);
1510 return log_error_errno(false, errno
, "Failed to enter cgroup \"%s\"", h
->monitor_full_path
);
1513 * we don't keep the fds for non-unified hierarchies around
1514 * mainly because we don't make use of them anymore after the
1515 * core cgroup setup is done but also because there are quite a
1518 if (!is_unified_hierarchy(h
))
1519 close_prot_errno_disarm(h
->cgfd_mon
);
1521 handler
->transient_pid
= -1;
1526 __cgfsng_ops
static bool cgfsng_payload_enter(struct cgroup_ops
*ops
,
1527 struct lxc_handler
*handler
)
1530 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
1533 return ret_set_errno(false, ENOENT
);
1535 if (!ops
->hierarchies
)
1538 if (!ops
->container_cgroup
)
1539 return ret_set_errno(false, ENOENT
);
1541 if (!handler
|| !handler
->conf
)
1542 return ret_set_errno(false, EINVAL
);
1544 len
= snprintf(pidstr
, sizeof(pidstr
), "%d", handler
->pid
);
1546 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1547 struct hierarchy
*h
= ops
->hierarchies
[i
];
1550 ret
= lxc_writeat(h
->cgfd_con
, "cgroup.procs", pidstr
, len
);
1552 return log_error_errno(false, errno
, "Failed to enter cgroup \"%s\"", h
->container_full_path
);
1558 static int fchowmodat(int dirfd
, const char *path
, uid_t chown_uid
,
1559 gid_t chown_gid
, mode_t chmod_mode
)
1563 ret
= fchownat(dirfd
, path
, chown_uid
, chown_gid
,
1564 AT_EMPTY_PATH
| AT_SYMLINK_NOFOLLOW
);
1566 return log_warn_errno(-1,
1567 errno
, "Failed to fchownat(%d, %s, %d, %d, AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW )",
1568 dirfd
, path
, (int)chown_uid
,
1571 ret
= fchmodat(dirfd
, (*path
!= '\0') ? path
: ".", chmod_mode
, 0);
1573 return log_warn_errno(-1, errno
, "Failed to fchmodat(%d, %s, %d, AT_SYMLINK_NOFOLLOW)",
1574 dirfd
, path
, (int)chmod_mode
);
1579 /* chgrp the container cgroups to container group. We leave
1580 * the container owner as cgroup owner. So we must make the
1581 * directories 775 so that the container can create sub-cgroups.
1583 * Also chown the tasks and cgroup.procs files. Those may not
1584 * exist depending on kernel version.
1586 static int chown_cgroup_wrapper(void *data
)
1590 struct generic_userns_exec_data
*arg
= data
;
1591 uid_t nsuid
= (arg
->conf
->root_nsuid_map
!= NULL
) ? 0 : arg
->conf
->init_uid
;
1592 gid_t nsgid
= (arg
->conf
->root_nsgid_map
!= NULL
) ? 0 : arg
->conf
->init_gid
;
1594 if (!lxc_setgroups(0, NULL
) && errno
!= EPERM
)
1595 return log_error_errno(-1, errno
, "Failed to setgroups(0, NULL)");
1597 ret
= setresgid(nsgid
, nsgid
, nsgid
);
1599 return log_error_errno(-1, errno
, "Failed to setresgid(%d, %d, %d)",
1600 (int)nsgid
, (int)nsgid
, (int)nsgid
);
1602 ret
= setresuid(nsuid
, nsuid
, nsuid
);
1604 return log_error_errno(-1, errno
, "Failed to setresuid(%d, %d, %d)",
1605 (int)nsuid
, (int)nsuid
, (int)nsuid
);
1607 destuid
= get_ns_uid(arg
->origuid
);
1608 if (destuid
== LXC_INVALID_UID
)
1611 for (int i
= 0; arg
->hierarchies
[i
]; i
++) {
1612 int dirfd
= arg
->hierarchies
[i
]->cgfd_con
;
1614 (void)fchowmodat(dirfd
, "", destuid
, nsgid
, 0775);
1617 * Failures to chown() these are inconvenient but not
1618 * detrimental We leave these owned by the container launcher,
1619 * so that container root can write to the files to attach. We
1620 * chmod() them 664 so that container systemd can write to the
1621 * files (which systemd in wily insists on doing).
1624 if (arg
->hierarchies
[i
]->version
== CGROUP_SUPER_MAGIC
)
1625 (void)fchowmodat(dirfd
, "tasks", destuid
, nsgid
, 0664);
1627 (void)fchowmodat(dirfd
, "cgroup.procs", destuid
, nsgid
, 0664);
1629 if (arg
->hierarchies
[i
]->version
!= CGROUP2_SUPER_MAGIC
)
1632 for (char **p
= arg
->hierarchies
[i
]->cgroup2_chown
; p
&& *p
; p
++)
1633 (void)fchowmodat(dirfd
, *p
, destuid
, nsgid
, 0664);
1639 __cgfsng_ops
static bool cgfsng_chown(struct cgroup_ops
*ops
,
1640 struct lxc_conf
*conf
)
1642 struct generic_userns_exec_data wrap
;
1645 return ret_set_errno(false, ENOENT
);
1647 if (!ops
->hierarchies
)
1650 if (!ops
->container_cgroup
)
1651 return ret_set_errno(false, ENOENT
);
1654 return ret_set_errno(false, EINVAL
);
1656 if (lxc_list_empty(&conf
->id_map
))
1659 wrap
.origuid
= geteuid();
1661 wrap
.hierarchies
= ops
->hierarchies
;
1664 if (userns_exec_1(conf
, chown_cgroup_wrapper
, &wrap
, "chown_cgroup_wrapper") < 0)
1665 return log_error_errno(false, errno
, "Error requesting cgroup chown in new user namespace");
1670 __cgfsng_ops
void cgfsng_payload_finalize(struct cgroup_ops
*ops
)
1675 if (!ops
->hierarchies
)
1678 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1679 struct hierarchy
*h
= ops
->hierarchies
[i
];
1681 * we don't keep the fds for non-unified hierarchies around
1682 * mainly because we don't make use of them anymore after the
1683 * core cgroup setup is done but also because there are quite a
1686 if (!is_unified_hierarchy(h
))
1687 close_prot_errno_disarm(h
->cgfd_con
);
1691 /* cgroup-full:* is done, no need to create subdirs */
1692 static inline bool cg_mount_needs_subdirs(int type
)
1694 return !(type
>= LXC_AUTO_CGROUP_FULL_RO
);
1697 /* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
1698 * remount controller ro if needed and bindmount the cgroupfs onto
1699 * control/the/cg/path.
1701 static int cg_legacy_mount_controllers(int type
, struct hierarchy
*h
,
1702 char *controllerpath
, char *cgpath
,
1703 const char *container_cgroup
)
1705 __do_free
char *sourcepath
= NULL
;
1706 int ret
, remount_flags
;
1707 int flags
= MS_BIND
;
1709 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_MIXED
) {
1710 ret
= mount(controllerpath
, controllerpath
, "cgroup", MS_BIND
, NULL
);
1712 return log_error_errno(-1, errno
, "Failed to bind mount \"%s\" onto \"%s\"",
1713 controllerpath
, controllerpath
);
1715 remount_flags
= add_required_remount_flags(controllerpath
,
1717 flags
| MS_REMOUNT
);
1718 ret
= mount(controllerpath
, controllerpath
, "cgroup",
1719 remount_flags
| MS_REMOUNT
| MS_BIND
| MS_RDONLY
,
1722 return log_error_errno(-1, errno
, "Failed to remount \"%s\" ro", controllerpath
);
1724 INFO("Remounted %s read-only", controllerpath
);
1727 sourcepath
= must_make_path(h
->mountpoint
, h
->container_base_path
,
1728 container_cgroup
, NULL
);
1729 if (type
== LXC_AUTO_CGROUP_RO
)
1732 ret
= mount(sourcepath
, cgpath
, "cgroup", flags
, NULL
);
1734 return log_error_errno(-1, errno
, "Failed to mount \"%s\" onto \"%s\"",
1735 h
->controllers
[0], cgpath
);
1736 INFO("Mounted \"%s\" onto \"%s\"", h
->controllers
[0], cgpath
);
1738 if (flags
& MS_RDONLY
) {
1739 remount_flags
= add_required_remount_flags(sourcepath
, cgpath
,
1740 flags
| MS_REMOUNT
);
1741 ret
= mount(sourcepath
, cgpath
, "cgroup", remount_flags
, NULL
);
1743 return log_error_errno(-1, errno
, "Failed to remount \"%s\" ro", cgpath
);
1744 INFO("Remounted %s read-only", cgpath
);
1747 INFO("Completed second stage cgroup automounts for \"%s\"", cgpath
);
1751 /* __cg_mount_direct
1753 * Mount cgroup hierarchies directly without using bind-mounts. The main
1754 * uses-cases are mounting cgroup hierarchies in cgroup namespaces and mounting
1755 * cgroups for the LXC_AUTO_CGROUP_FULL option.
1757 static int __cg_mount_direct(int type
, struct hierarchy
*h
,
1758 const char *controllerpath
)
1760 __do_free
char *controllers
= NULL
;
1761 char *fstype
= "cgroup2";
1762 unsigned long flags
= 0;
1768 flags
|= MS_RELATIME
;
1770 if (type
== LXC_AUTO_CGROUP_RO
|| type
== LXC_AUTO_CGROUP_FULL_RO
)
1773 if (h
->version
!= CGROUP2_SUPER_MAGIC
) {
1774 controllers
= lxc_string_join(",", (const char **)h
->controllers
, false);
1780 ret
= mount("cgroup", controllerpath
, fstype
, flags
, controllers
);
1782 return log_error_errno(-1, errno
, "Failed to mount \"%s\" with cgroup filesystem type %s",
1783 controllerpath
, fstype
);
1785 DEBUG("Mounted \"%s\" with cgroup filesystem type %s", controllerpath
, fstype
);
1789 static inline int cg_mount_in_cgroup_namespace(int type
, struct hierarchy
*h
,
1790 const char *controllerpath
)
1792 return __cg_mount_direct(type
, h
, controllerpath
);
1795 static inline int cg_mount_cgroup_full(int type
, struct hierarchy
*h
,
1796 const char *controllerpath
)
1798 if (type
< LXC_AUTO_CGROUP_FULL_RO
|| type
> LXC_AUTO_CGROUP_FULL_MIXED
)
1801 return __cg_mount_direct(type
, h
, controllerpath
);
1804 __cgfsng_ops
static bool cgfsng_mount(struct cgroup_ops
*ops
,
1805 struct lxc_handler
*handler
,
1806 const char *root
, int type
)
1808 __do_free
char *cgroup_root
= NULL
;
1809 bool has_cgns
= false, wants_force_mount
= false;
1813 return ret_set_errno(false, ENOENT
);
1815 if (!ops
->hierarchies
)
1818 if (!handler
|| !handler
->conf
)
1819 return ret_set_errno(false, EINVAL
);
1821 if ((type
& LXC_AUTO_CGROUP_MASK
) == 0)
1824 if (type
& LXC_AUTO_CGROUP_FORCE
) {
1825 type
&= ~LXC_AUTO_CGROUP_FORCE
;
1826 wants_force_mount
= true;
1829 if (!wants_force_mount
) {
1830 if (!lxc_list_empty(&handler
->conf
->keepcaps
))
1831 wants_force_mount
= !in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->keepcaps
);
1833 wants_force_mount
= in_caplist(CAP_SYS_ADMIN
, &handler
->conf
->caps
);
1836 * Most recent distro versions currently have init system that
1837 * do support cgroup2 but do not mount it by default unless
1838 * explicitly told so even if the host is cgroup2 only. That
1839 * means they often will fail to boot. Fix this by pre-mounting
1840 * cgroup2 by default. We will likely need to be doing this a
1841 * few years until all distros have switched over to cgroup2 at
1842 * which point we can safely assume that their init systems
1843 * will mount it themselves.
1845 if (pure_unified_layout(ops
))
1846 wants_force_mount
= true;
1849 has_cgns
= cgns_supported();
1850 if (has_cgns
&& !wants_force_mount
)
1853 if (type
== LXC_AUTO_CGROUP_NOSPEC
)
1854 type
= LXC_AUTO_CGROUP_MIXED
;
1855 else if (type
== LXC_AUTO_CGROUP_FULL_NOSPEC
)
1856 type
= LXC_AUTO_CGROUP_FULL_MIXED
;
1858 cgroup_root
= must_make_path(root
, DEFAULT_CGROUP_MOUNTPOINT
, NULL
);
1859 if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNIFIED
) {
1860 if (has_cgns
&& wants_force_mount
) {
1862 * If cgroup namespaces are supported but the container
1863 * will not have CAP_SYS_ADMIN after it has started we
1864 * need to mount the cgroups manually.
1866 return cg_mount_in_cgroup_namespace(type
, ops
->unified
, cgroup_root
) == 0;
1869 return cg_mount_cgroup_full(type
, ops
->unified
, cgroup_root
) == 0;
1873 ret
= safe_mount(NULL
, cgroup_root
, "tmpfs",
1874 MS_NOSUID
| MS_NODEV
| MS_NOEXEC
| MS_RELATIME
,
1875 "size=10240k,mode=755", root
);
1879 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1880 __do_free
char *controllerpath
= NULL
, *path2
= NULL
;
1881 struct hierarchy
*h
= ops
->hierarchies
[i
];
1882 char *controller
= strrchr(h
->mountpoint
, '/');
1888 controllerpath
= must_make_path(cgroup_root
, controller
, NULL
);
1889 if (dir_exists(controllerpath
))
1892 ret
= mkdir(controllerpath
, 0755);
1894 return log_error_errno(false, errno
, "Error creating cgroup path: %s", controllerpath
);
1896 if (has_cgns
&& wants_force_mount
) {
1897 /* If cgroup namespaces are supported but the container
1898 * will not have CAP_SYS_ADMIN after it has started we
1899 * need to mount the cgroups manually.
1901 ret
= cg_mount_in_cgroup_namespace(type
, h
, controllerpath
);
1908 ret
= cg_mount_cgroup_full(type
, h
, controllerpath
);
1912 if (!cg_mount_needs_subdirs(type
))
1915 path2
= must_make_path(controllerpath
, h
->container_base_path
,
1916 ops
->container_cgroup
, NULL
);
1917 ret
= mkdir_p(path2
, 0755);
1921 ret
= cg_legacy_mount_controllers(type
, h
, controllerpath
,
1922 path2
, ops
->container_cgroup
);
1930 /* Only root needs to escape to the cgroup of its init. */
1931 __cgfsng_ops
static bool cgfsng_escape(const struct cgroup_ops
*ops
,
1932 struct lxc_conf
*conf
)
1935 return ret_set_errno(false, ENOENT
);
1937 if (!ops
->hierarchies
)
1941 return ret_set_errno(false, EINVAL
);
1943 if (conf
->cgroup_meta
.relative
|| geteuid())
1946 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
1947 __do_free
char *fullpath
= NULL
;
1951 must_make_path(ops
->hierarchies
[i
]->mountpoint
,
1952 ops
->hierarchies
[i
]->container_base_path
,
1953 "cgroup.procs", NULL
);
1954 ret
= lxc_write_to_file(fullpath
, "0", 2, false, 0666);
1956 return log_error_errno(false, errno
, "Failed to escape to cgroup \"%s\"", fullpath
);
1962 __cgfsng_ops
static int cgfsng_num_hierarchies(struct cgroup_ops
*ops
)
1967 return ret_set_errno(-1, ENOENT
);
1969 if (!ops
->hierarchies
)
1972 for (; ops
->hierarchies
[i
]; i
++)
1978 __cgfsng_ops
static bool cgfsng_get_hierarchies(struct cgroup_ops
*ops
, int n
,
1984 return ret_set_errno(false, ENOENT
);
1986 if (!ops
->hierarchies
)
1987 return ret_set_errno(false, ENOENT
);
1989 /* sanity check n */
1990 for (i
= 0; i
< n
; i
++)
1991 if (!ops
->hierarchies
[i
])
1992 return ret_set_errno(false, ENOENT
);
1994 *out
= ops
->hierarchies
[i
]->controllers
;
1999 static bool cg_legacy_freeze(struct cgroup_ops
*ops
)
2001 struct hierarchy
*h
;
2003 h
= get_hierarchy(ops
, "freezer");
2005 return ret_set_errno(-1, ENOENT
);
2007 return lxc_write_openat(h
->container_full_path
, "freezer.state",
2008 "FROZEN", STRLITERALLEN("FROZEN"));
2011 static int freezer_cgroup_events_cb(int fd
, uint32_t events
, void *cbdata
,
2012 struct lxc_epoll_descr
*descr
)
2014 __do_close
int duped_fd
= -EBADF
;
2015 __do_free
char *line
= NULL
;
2016 __do_fclose
FILE *f
= NULL
;
2017 int state
= PTR_TO_INT(cbdata
);
2019 const char *state_string
;
2023 return LXC_MAINLOOP_ERROR
;
2025 if (lseek(duped_fd
, 0, SEEK_SET
) < (off_t
)-1)
2026 return LXC_MAINLOOP_ERROR
;
2028 f
= fdopen(duped_fd
, "re");
2030 return LXC_MAINLOOP_ERROR
;
2034 state_string
= "frozen 1";
2036 state_string
= "frozen 0";
2038 while (getline(&line
, &len
, f
) != -1)
2039 if (strncmp(line
, state_string
, STRLITERALLEN("frozen") + 2) == 0)
2040 return LXC_MAINLOOP_CLOSE
;
2042 return LXC_MAINLOOP_CONTINUE
;
2045 static int cg_unified_freeze(struct cgroup_ops
*ops
, int timeout
)
2047 __do_close
int fd
= -EBADF
;
2048 call_cleaner(lxc_mainloop_close
) struct lxc_epoll_descr
*descr_ptr
= NULL
;
2050 struct lxc_epoll_descr descr
;
2051 struct hierarchy
*h
;
2055 return ret_set_errno(-1, ENOENT
);
2057 if (!h
->container_full_path
)
2058 return ret_set_errno(-1, EEXIST
);
2061 __do_free
char *events_file
= NULL
;
2063 events_file
= must_make_path(h
->container_full_path
, "cgroup.events", NULL
);
2064 fd
= open(events_file
, O_RDONLY
| O_CLOEXEC
);
2066 return log_error_errno(-1, errno
, "Failed to open cgroup.events file");
2068 ret
= lxc_mainloop_open(&descr
);
2070 return log_error_errno(-1, errno
, "Failed to create epoll instance to wait for container freeze");
2072 /* automatically cleaned up now */
2075 ret
= lxc_mainloop_add_handler(&descr
, fd
, freezer_cgroup_events_cb
, INT_TO_PTR((int){1}));
2077 return log_error_errno(-1, errno
, "Failed to add cgroup.events fd handler to mainloop");
2080 ret
= lxc_write_openat(h
->container_full_path
, "cgroup.freeze", "1", 1);
2082 return log_error_errno(-1, errno
, "Failed to open cgroup.freeze file");
2084 if (timeout
!= 0 && lxc_mainloop(&descr
, timeout
))
2085 return log_error_errno(-1, errno
, "Failed to wait for container to be frozen");
2090 __cgfsng_ops
static int cgfsng_freeze(struct cgroup_ops
*ops
, int timeout
)
2092 if (!ops
->hierarchies
)
2093 return ret_set_errno(-1, ENOENT
);
2095 if (ops
->cgroup_layout
!= CGROUP_LAYOUT_UNIFIED
)
2096 return cg_legacy_freeze(ops
);
2098 return cg_unified_freeze(ops
, timeout
);
2101 static int cg_legacy_unfreeze(struct cgroup_ops
*ops
)
2103 struct hierarchy
*h
;
2105 h
= get_hierarchy(ops
, "freezer");
2107 return ret_set_errno(-1, ENOENT
);
2109 return lxc_write_openat(h
->container_full_path
, "freezer.state",
2110 "THAWED", STRLITERALLEN("THAWED"));
2113 static int cg_unified_unfreeze(struct cgroup_ops
*ops
, int timeout
)
2115 __do_close
int fd
= -EBADF
;
2116 call_cleaner(lxc_mainloop_close
)struct lxc_epoll_descr
*descr_ptr
= NULL
;
2118 struct lxc_epoll_descr descr
;
2119 struct hierarchy
*h
;
2123 return ret_set_errno(-1, ENOENT
);
2125 if (!h
->container_full_path
)
2126 return ret_set_errno(-1, EEXIST
);
2129 __do_free
char *events_file
= NULL
;
2131 events_file
= must_make_path(h
->container_full_path
, "cgroup.events", NULL
);
2132 fd
= open(events_file
, O_RDONLY
| O_CLOEXEC
);
2134 return log_error_errno(-1, errno
, "Failed to open cgroup.events file");
2136 ret
= lxc_mainloop_open(&descr
);
2138 return log_error_errno(-1, errno
, "Failed to create epoll instance to wait for container unfreeze");
2140 /* automatically cleaned up now */
2143 ret
= lxc_mainloop_add_handler(&descr
, fd
, freezer_cgroup_events_cb
, INT_TO_PTR((int){0}));
2145 return log_error_errno(-1, errno
, "Failed to add cgroup.events fd handler to mainloop");
2148 ret
= lxc_write_openat(h
->container_full_path
, "cgroup.freeze", "0", 1);
2150 return log_error_errno(-1, errno
, "Failed to open cgroup.freeze file");
2152 if (timeout
!= 0 && lxc_mainloop(&descr
, timeout
))
2153 return log_error_errno(-1, errno
, "Failed to wait for container to be unfrozen");
2158 __cgfsng_ops
static int cgfsng_unfreeze(struct cgroup_ops
*ops
, int timeout
)
2160 if (!ops
->hierarchies
)
2161 return ret_set_errno(-1, ENOENT
);
2163 if (ops
->cgroup_layout
!= CGROUP_LAYOUT_UNIFIED
)
2164 return cg_legacy_unfreeze(ops
);
2166 return cg_unified_unfreeze(ops
, timeout
);
2169 static const char *cgfsng_get_cgroup_do(struct cgroup_ops
*ops
,
2170 const char *controller
, bool limiting
)
2172 struct hierarchy
*h
;
2174 h
= get_hierarchy(ops
, controller
);
2176 return log_warn_errno(NULL
, ENOENT
, "Failed to find hierarchy for controller \"%s\"",
2177 controller
? controller
: "(null)");
2180 return h
->container_limit_path
2181 ? h
->container_limit_path
+ strlen(h
->mountpoint
)
2184 return h
->container_full_path
2185 ? h
->container_full_path
+ strlen(h
->mountpoint
)
2189 __cgfsng_ops
static const char *cgfsng_get_cgroup(struct cgroup_ops
*ops
,
2190 const char *controller
)
2192 return cgfsng_get_cgroup_do(ops
, controller
, false);
2195 __cgfsng_ops
static const char *cgfsng_get_limiting_cgroup(struct cgroup_ops
*ops
,
2196 const char *controller
)
2198 return cgfsng_get_cgroup_do(ops
, controller
, true);
2201 /* Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a full path,
2202 * which must be freed by the caller.
2204 static inline char *build_full_cgpath_from_monitorpath(struct hierarchy
*h
,
2206 const char *filename
)
2208 return must_make_path(h
->mountpoint
, inpath
, filename
, NULL
);
2211 static int cgroup_attach_leaf(const struct lxc_conf
*conf
, int unified_fd
, pid_t pid
)
2215 char pidstr
[INTTYPE_TO_STRLEN(int64_t) + 1];
2218 /* Create leaf cgroup. */
2219 ret
= mkdirat(unified_fd
, ".lxc", 0755);
2220 if (ret
< 0 && errno
!= EEXIST
)
2221 return log_error_errno(-1, errno
, "Failed to create leaf cgroup \".lxc\"");
2223 pidstr_len
= sprintf(pidstr
, INT64_FMT
, (int64_t)pid
);
2224 ret
= lxc_writeat(unified_fd
, ".lxc/cgroup.procs", pidstr
, pidstr_len
);
2226 ret
= lxc_writeat(unified_fd
, "cgroup.procs", pidstr
, pidstr_len
);
2230 /* this is a non-leaf node */
2232 return log_error_errno(-1, errno
, "Failed to attach to unified cgroup");
2236 char attach_cgroup
[STRLITERALLEN(".lxc-1000/cgroup.procs") + 1];
2239 ret
= snprintf(attach_cgroup
, sizeof(attach_cgroup
), ".lxc-%d/cgroup.procs", idx
);
2240 if (ret
< 0 || (size_t)ret
>= sizeof(attach_cgroup
))
2241 return ret_errno(EIO
);
2243 slash
= &attach_cgroup
[ret
] - STRLITERALLEN("/cgroup.procs");
2246 ret
= mkdirat(unified_fd
, attach_cgroup
, 0755);
2247 if (ret
< 0 && errno
!= EEXIST
)
2248 return log_error_errno(-1, errno
, "Failed to create cgroup %s", attach_cgroup
);
2254 ret
= lxc_writeat(unified_fd
, attach_cgroup
, pidstr
, pidstr_len
);
2258 if (rm
&& unlinkat(unified_fd
, attach_cgroup
, AT_REMOVEDIR
))
2259 SYSERROR("Failed to remove cgroup \"%d(%s)\"", unified_fd
, attach_cgroup
);
2261 /* this is a non-leaf node */
2263 return log_error_errno(-1, errno
, "Failed to attach to unified cgroup");
2266 } while (idx
< 1000);
2268 return log_error_errno(-1, errno
, "Failed to attach to unified cgroup");
2271 static int cgroup_attach_create_leaf(const struct lxc_conf
*conf
,
2272 int unified_fd
, int *sk_fd
)
2274 __do_close
int sk
= *sk_fd
, target_fd0
= -EBADF
, target_fd1
= -EBADF
;
2278 /* Create leaf cgroup. */
2279 ret
= mkdirat(unified_fd
, ".lxc", 0755);
2280 if (ret
< 0 && errno
!= EEXIST
)
2281 return log_error_errno(-1, errno
, "Failed to create leaf cgroup \".lxc\"");
2283 target_fd0
= openat(unified_fd
, ".lxc/cgroup.procs", O_WRONLY
| O_CLOEXEC
| O_NOFOLLOW
);
2285 return log_error_errno(-errno
, errno
, "Failed to open \".lxc/cgroup.procs\"");
2286 target_fds
[0] = target_fd0
;
2288 target_fd1
= openat(unified_fd
, "cgroup.procs", O_WRONLY
| O_CLOEXEC
| O_NOFOLLOW
);
2290 return log_error_errno(-errno
, errno
, "Failed to open \".lxc/cgroup.procs\"");
2291 target_fds
[1] = target_fd1
;
2293 ret
= lxc_abstract_unix_send_fds(sk
, target_fds
, 2, NULL
, 0);
2295 return log_error_errno(-errno
, errno
, "Failed to send \".lxc/cgroup.procs\" fds %d and %d",
2296 target_fd0
, target_fd1
);
2298 return log_debug(0, "Sent target cgroup fds %d and %d", target_fd0
, target_fd1
);
2301 static int cgroup_attach_move_into_leaf(const struct lxc_conf
*conf
,
2302 int *sk_fd
, pid_t pid
)
2304 __do_close
int sk
= *sk_fd
, target_fd0
= -EBADF
, target_fd1
= -EBADF
;
2306 char pidstr
[INTTYPE_TO_STRLEN(int64_t) + 1];
2310 ret
= lxc_abstract_unix_recv_fds(sk
, target_fds
, 2, NULL
, 0);
2312 return log_error_errno(-1, errno
, "Failed to receive target cgroup fd");
2313 target_fd0
= target_fds
[0];
2314 target_fd1
= target_fds
[1];
2316 pidstr_len
= sprintf(pidstr
, INT64_FMT
, (int64_t)pid
);
2318 ret
= lxc_write_nointr(target_fd0
, pidstr
, pidstr_len
);
2319 if (ret
> 0 && ret
== pidstr_len
)
2320 return log_debug(0, "Moved process into target cgroup via fd %d", target_fd0
);
2322 ret
= lxc_write_nointr(target_fd1
, pidstr
, pidstr_len
);
2323 if (ret
> 0 && ret
== pidstr_len
)
2324 return log_debug(0, "Moved process into target cgroup via fd %d", target_fd1
);
2326 return log_debug_errno(-1, errno
, "Failed to move process into target cgroup via fd %d and %d",
2327 target_fd0
, target_fd1
);
2330 struct userns_exec_unified_attach_data
{
2331 const struct lxc_conf
*conf
;
2337 static int cgroup_unified_attach_child_wrapper(void *data
)
2339 struct userns_exec_unified_attach_data
*args
= data
;
2341 if (!args
->conf
|| args
->unified_fd
< 0 || args
->pid
<= 0 ||
2342 args
->sk_pair
[0] < 0 || args
->sk_pair
[1] < 0)
2343 return ret_errno(EINVAL
);
2345 close_prot_errno_disarm(args
->sk_pair
[0]);
2346 return cgroup_attach_create_leaf(args
->conf
, args
->unified_fd
,
2350 static int cgroup_unified_attach_parent_wrapper(void *data
)
2352 struct userns_exec_unified_attach_data
*args
= data
;
2354 if (!args
->conf
|| args
->unified_fd
< 0 || args
->pid
<= 0 ||
2355 args
->sk_pair
[0] < 0 || args
->sk_pair
[1] < 0)
2356 return ret_errno(EINVAL
);
2358 close_prot_errno_disarm(args
->sk_pair
[1]);
2359 return cgroup_attach_move_into_leaf(args
->conf
, &args
->sk_pair
[0],
2363 int cgroup_attach(const struct lxc_conf
*conf
, const char *name
,
2364 const char *lxcpath
, pid_t pid
)
2366 __do_close
int unified_fd
= -EBADF
;
2369 if (!conf
|| !name
|| !lxcpath
|| pid
<= 0)
2370 return ret_errno(EINVAL
);
2372 unified_fd
= lxc_cmd_get_cgroup2_fd(name
, lxcpath
);
2374 return ret_errno(EBADF
);
2376 if (!lxc_list_empty(&conf
->id_map
)) {
2377 struct userns_exec_unified_attach_data args
= {
2379 .unified_fd
= unified_fd
,
2383 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, args
.sk_pair
);
2387 ret
= userns_exec_minimal(conf
,
2388 cgroup_unified_attach_parent_wrapper
,
2390 cgroup_unified_attach_child_wrapper
,
2393 ret
= cgroup_attach_leaf(conf
, unified_fd
, pid
);
2399 /* Technically, we're always at a delegation boundary here (This is especially
2400 * true when cgroup namespaces are available.). The reasoning is that in order
2401 * for us to have been able to start a container in the first place the root
2402 * cgroup must have been a leaf node. Now, either the container's init system
2403 * has populated the cgroup and kept it as a leaf node or it has created
2404 * subtrees. In the former case we will simply attach to the leaf node we
2405 * created when we started the container in the latter case we create our own
2406 * cgroup for the attaching process.
2408 static int __cg_unified_attach(const struct hierarchy
*h
,
2409 const struct lxc_conf
*conf
, const char *name
,
2410 const char *lxcpath
, pid_t pid
,
2411 const char *controller
)
2413 __do_close
int unified_fd
= -EBADF
;
2414 __do_free
char *path
= NULL
, *cgroup
= NULL
;
2417 if (!conf
|| !name
|| !lxcpath
|| pid
<= 0)
2418 return ret_errno(EINVAL
);
2420 ret
= cgroup_attach(conf
, name
, lxcpath
, pid
);
2422 return log_trace(0, "Attached to unified cgroup via command handler");
2424 return log_error_errno(ret
, errno
, "Failed to attach to unified cgroup");
2426 /* Fall back to retrieving the path for the unified cgroup. */
2427 cgroup
= lxc_cmd_get_cgroup_path(name
, lxcpath
, controller
);
2432 path
= must_make_path(h
->mountpoint
, cgroup
, NULL
);
2434 unified_fd
= open(path
, O_PATH
| O_DIRECTORY
| O_CLOEXEC
);
2436 return ret_errno(EBADF
);
2438 if (!lxc_list_empty(&conf
->id_map
)) {
2439 struct userns_exec_unified_attach_data args
= {
2441 .unified_fd
= unified_fd
,
2445 ret
= socketpair(PF_LOCAL
, SOCK_STREAM
| SOCK_CLOEXEC
, 0, args
.sk_pair
);
2449 ret
= userns_exec_minimal(conf
,
2450 cgroup_unified_attach_parent_wrapper
,
2452 cgroup_unified_attach_child_wrapper
,
2455 ret
= cgroup_attach_leaf(conf
, unified_fd
, pid
);
2461 __cgfsng_ops
static bool cgfsng_attach(struct cgroup_ops
*ops
,
2462 const struct lxc_conf
*conf
,
2463 const char *name
, const char *lxcpath
,
2467 char pidstr
[INTTYPE_TO_STRLEN(pid_t
)];
2470 return ret_set_errno(false, ENOENT
);
2472 if (!ops
->hierarchies
)
2475 len
= snprintf(pidstr
, sizeof(pidstr
), "%d", pid
);
2476 if (len
< 0 || (size_t)len
>= sizeof(pidstr
))
2479 for (int i
= 0; ops
->hierarchies
[i
]; i
++) {
2480 __do_free
char *fullpath
= NULL
, *path
= NULL
;
2481 struct hierarchy
*h
= ops
->hierarchies
[i
];
2483 if (h
->version
== CGROUP2_SUPER_MAGIC
) {
2484 ret
= __cg_unified_attach(h
, conf
, name
, lxcpath
, pid
,
2492 path
= lxc_cmd_get_cgroup_path(name
, lxcpath
, h
->controllers
[0]);
2497 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, "cgroup.procs");
2498 ret
= lxc_write_to_file(fullpath
, pidstr
, len
, false, 0666);
2500 return log_error_errno(false, errno
, "Failed to attach %d to %s",
2501 (int)pid
, fullpath
);
2507 /* Called externally (i.e. from 'lxc-cgroup') to query cgroup limits. Here we
2508 * don't have a cgroup_data set up, so we ask the running container through the
2509 * commands API for the cgroup path.
2511 __cgfsng_ops
static int cgfsng_get(struct cgroup_ops
*ops
, const char *filename
,
2512 char *value
, size_t len
, const char *name
,
2513 const char *lxcpath
)
2515 __do_free
char *path
= NULL
;
2516 __do_free
char *controller
= NULL
;
2518 struct hierarchy
*h
;
2522 return ret_set_errno(-1, ENOENT
);
2524 controller
= must_copy_string(filename
);
2525 p
= strchr(controller
, '.');
2529 path
= lxc_cmd_get_limiting_cgroup_path(name
, lxcpath
, controller
);
2534 h
= get_hierarchy(ops
, controller
);
2536 __do_free
char *fullpath
= NULL
;
2538 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, filename
);
2539 ret
= lxc_read_from_file(fullpath
, value
, len
);
2545 static int device_cgroup_parse_access(struct device_item
*device
, const char *val
)
2547 for (int count
= 0; count
< 3; count
++, val
++) {
2550 device
->access
[count
] = *val
;
2553 device
->access
[count
] = *val
;
2556 device
->access
[count
] = *val
;
2563 return ret_errno(EINVAL
);
2570 static int device_cgroup_rule_parse(struct device_item
*device
, const char *key
,
2576 if (strcmp("devices.allow", key
) == 0)
2581 if (strcmp(val
, "a") == 0) {
2586 device
->global_rule
= device
->allow
2587 ? LXC_BPF_DEVICE_CGROUP_BLACKLIST
2588 : LXC_BPF_DEVICE_CGROUP_WHITELIST
;
2594 device
->global_rule
= LXC_BPF_DEVICE_CGROUP_LOCAL_RULE
;
2602 device
->type
= *val
;
2615 } else if (isdigit(*val
)) {
2616 memset(temp
, 0, sizeof(temp
));
2617 for (count
= 0; count
< sizeof(temp
) - 1; count
++) {
2623 ret
= lxc_safe_int(temp
, &device
->major
);
2637 } else if (isdigit(*val
)) {
2638 memset(temp
, 0, sizeof(temp
));
2639 for (count
= 0; count
< sizeof(temp
) - 1; count
++) {
2645 ret
= lxc_safe_int(temp
, &device
->minor
);
2654 return device_cgroup_parse_access(device
, ++val
);
2657 /* Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits. Here we
2658 * don't have a cgroup_data set up, so we ask the running container through the
2659 * commands API for the cgroup path.
2661 __cgfsng_ops
static int cgfsng_set(struct cgroup_ops
*ops
,
2662 const char *key
, const char *value
,
2663 const char *name
, const char *lxcpath
)
2665 __do_free
char *path
= NULL
;
2666 __do_free
char *controller
= NULL
;
2668 struct hierarchy
*h
;
2672 return ret_set_errno(-1, ENOENT
);
2674 controller
= must_copy_string(key
);
2675 p
= strchr(controller
, '.');
2679 if (pure_unified_layout(ops
) && strcmp(controller
, "devices") == 0) {
2680 struct device_item device
= {0};
2682 ret
= device_cgroup_rule_parse(&device
, key
, value
);
2684 return log_error_errno(-1, EINVAL
, "Failed to parse device string %s=%s",
2687 ret
= lxc_cmd_add_bpf_device_cgroup(name
, lxcpath
, &device
);
2694 path
= lxc_cmd_get_limiting_cgroup_path(name
, lxcpath
, controller
);
2699 h
= get_hierarchy(ops
, controller
);
2701 __do_free
char *fullpath
= NULL
;
2703 fullpath
= build_full_cgpath_from_monitorpath(h
, path
, key
);
2704 ret
= lxc_write_to_file(fullpath
, value
, strlen(value
), false, 0666);
2710 /* take devices cgroup line
2712 * and convert it to a valid
2713 * type major:minor mode
2714 * line. Return <0 on error. Dest is a preallocated buffer long enough to hold
2717 static int device_cgroup_rule_parse_devpath(struct device_item
*device
,
2718 const char *devpath
)
2720 __do_free
char *path
= NULL
;
2726 path
= must_copy_string(devpath
);
2729 * Read path followed by mode. Ignore any trailing text.
2730 * A ' # comment' would be legal. Technically other text is not
2731 * legal, we could check for that if we cared to.
2733 for (n_parts
= 1, p
= path
; *p
; p
++) {
2749 return ret_set_errno(-1, EINVAL
);
2753 return ret_errno(EINVAL
);
2755 if (device_cgroup_parse_access(device
, mode
) < 0)
2759 return ret_set_errno(-1, EINVAL
);
2761 ret
= stat(path
, &sb
);
2763 return ret_set_errno(-1, errno
);
2765 mode_t m
= sb
.st_mode
& S_IFMT
;
2774 return log_error_errno(-1, EINVAL
, "Unsupported device type %i for \"%s\"", m
, path
);
2777 device
->major
= MAJOR(sb
.st_rdev
);
2778 device
->minor
= MINOR(sb
.st_rdev
);
2780 device
->global_rule
= LXC_BPF_DEVICE_CGROUP_LOCAL_RULE
;
2785 static int convert_devpath(const char *invalue
, char *dest
)
2787 struct device_item device
= {0};
2790 ret
= device_cgroup_rule_parse_devpath(&device
, invalue
);
2794 ret
= snprintf(dest
, 50, "%c %d:%d %s", device
.type
, device
.major
,
2795 device
.minor
, device
.access
);
2796 if (ret
< 0 || ret
>= 50)
2797 return log_error_errno(-1, ENAMETOOLONG
, "Error on configuration value \"%c %d:%d %s\" (max 50 chars)",
2798 device
.type
, device
.major
, device
.minor
, device
.access
);
2803 /* Called from setup_limits - here we have the container's cgroup_data because
2804 * we created the cgroups.
2806 static int cg_legacy_set_data(struct cgroup_ops
*ops
, const char *filename
,
2807 const char *value
, bool is_cpuset
)
2809 __do_free
char *controller
= NULL
;
2811 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2812 char converted_value
[50];
2813 struct hierarchy
*h
;
2815 controller
= must_copy_string(filename
);
2816 p
= strchr(controller
, '.');
2820 if (strcmp("devices.allow", filename
) == 0 && value
[0] == '/') {
2823 ret
= convert_devpath(value
, converted_value
);
2826 value
= converted_value
;
2829 h
= get_hierarchy(ops
, controller
);
2831 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
);
2834 int ret
= lxc_write_openat(h
->container_full_path
, filename
, value
, strlen(value
));
2838 return lxc_write_openat(h
->container_limit_path
, filename
, value
, strlen(value
));
2841 __cgfsng_ops
static bool cgfsng_setup_limits_legacy(struct cgroup_ops
*ops
,
2842 struct lxc_conf
*conf
,
2845 __do_free
struct lxc_list
*sorted_cgroup_settings
= NULL
;
2846 struct lxc_list
*cgroup_settings
= &conf
->cgroup
;
2847 struct lxc_list
*iterator
, *next
;
2848 struct lxc_cgroup
*cg
;
2852 return ret_set_errno(false, ENOENT
);
2855 return ret_set_errno(false, EINVAL
);
2857 cgroup_settings
= &conf
->cgroup
;
2858 if (lxc_list_empty(cgroup_settings
))
2861 if (!ops
->hierarchies
)
2862 return ret_set_errno(false, EINVAL
);
2864 if (pure_unified_layout(ops
))
2865 return log_warn_errno(true, EINVAL
, "Ignoring legacy cgroup limits on pure cgroup2 system");
2867 sorted_cgroup_settings
= sort_cgroup_settings(cgroup_settings
);
2868 if (!sorted_cgroup_settings
)
2871 lxc_list_for_each(iterator
, sorted_cgroup_settings
) {
2872 cg
= iterator
->elem
;
2874 if (do_devices
== !strncmp("devices", cg
->subsystem
, 7)) {
2875 if (cg_legacy_set_data(ops
, cg
->subsystem
, cg
->value
, strncmp("cpuset", cg
->subsystem
, 6) == 0)) {
2876 if (do_devices
&& (errno
== EACCES
|| errno
== EPERM
)) {
2877 SYSWARN("Failed to set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2880 SYSERROR("Failed to set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2883 DEBUG("Set controller \"%s\" set to \"%s\"", cg
->subsystem
, cg
->value
);
2888 INFO("Limits for the legacy cgroup hierarchies have been setup");
2890 lxc_list_for_each_safe(iterator
, sorted_cgroup_settings
, next
) {
2891 lxc_list_del(iterator
);
2899 * Some of the parsing logic comes from the original cgroup device v1
2900 * implementation in the kernel.
2902 static int bpf_device_cgroup_prepare(struct cgroup_ops
*ops
,
2903 struct lxc_conf
*conf
, const char *key
,
2906 #ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
2907 struct device_item device_item
= {0};
2910 if (strcmp("devices.allow", key
) == 0 && *val
== '/')
2911 ret
= device_cgroup_rule_parse_devpath(&device_item
, val
);
2913 ret
= device_cgroup_rule_parse(&device_item
, key
, val
);
2915 return log_error_errno(-1, EINVAL
, "Failed to parse device string %s=%s", key
, val
);
2917 ret
= bpf_list_add_device(conf
, &device_item
);
2924 __cgfsng_ops
static bool cgfsng_setup_limits(struct cgroup_ops
*ops
,
2925 struct lxc_handler
*handler
)
2927 struct lxc_list
*cgroup_settings
, *iterator
;
2928 struct hierarchy
*h
;
2929 struct lxc_conf
*conf
;
2932 return ret_set_errno(false, ENOENT
);
2934 if (!ops
->hierarchies
)
2937 if (!ops
->container_cgroup
)
2938 return ret_set_errno(false, EINVAL
);
2940 if (!handler
|| !handler
->conf
)
2941 return ret_set_errno(false, EINVAL
);
2942 conf
= handler
->conf
;
2944 cgroup_settings
= &conf
->cgroup2
;
2945 if (lxc_list_empty(cgroup_settings
))
2948 if (!pure_unified_layout(ops
))
2949 return log_warn_errno(true, EINVAL
, "Ignoring cgroup2 limits on legacy cgroup system");
2955 lxc_list_for_each (iterator
, cgroup_settings
) {
2956 struct lxc_cgroup
*cg
= iterator
->elem
;
2959 if (strncmp("devices", cg
->subsystem
, 7) == 0) {
2960 ret
= bpf_device_cgroup_prepare(ops
, conf
, cg
->subsystem
,
2963 ret
= lxc_write_openat(h
->container_limit_path
,
2964 cg
->subsystem
, cg
->value
,
2967 return log_error_errno(false, errno
, "Failed to set \"%s\" to \"%s\"",
2968 cg
->subsystem
, cg
->value
);
2970 TRACE("Set \"%s\" to \"%s\"", cg
->subsystem
, cg
->value
);
2973 return log_info(true, "Limits for the unified cgroup hierarchy have been setup");
2976 __cgfsng_ops
bool cgfsng_devices_activate(struct cgroup_ops
*ops
,
2977 struct lxc_handler
*handler
)
2979 #ifdef HAVE_STRUCT_BPF_CGROUP_DEV_CTX
2980 __do_bpf_program_free
struct bpf_program
*devices
= NULL
;
2982 struct lxc_conf
*conf
;
2983 struct hierarchy
*unified
;
2984 struct lxc_list
*it
;
2985 struct bpf_program
*devices_old
;
2988 return ret_set_errno(false, ENOENT
);
2990 if (!ops
->hierarchies
)
2993 if (!ops
->container_cgroup
)
2994 return ret_set_errno(false, EEXIST
);
2996 if (!handler
|| !handler
->conf
)
2997 return ret_set_errno(false, EINVAL
);
2998 conf
= handler
->conf
;
3000 unified
= ops
->unified
;
3001 if (!unified
|| !unified
->bpf_device_controller
||
3002 !unified
->container_full_path
|| lxc_list_empty(&conf
->devices
))
3005 devices
= bpf_program_new(BPF_PROG_TYPE_CGROUP_DEVICE
);
3007 return log_error_errno(false, ENOMEM
, "Failed to create new bpf program");
3009 ret
= bpf_program_init(devices
);
3011 return log_error_errno(false, ENOMEM
, "Failed to initialize bpf program");
3013 lxc_list_for_each(it
, &conf
->devices
) {
3014 struct device_item
*cur
= it
->elem
;
3016 ret
= bpf_program_append_device(devices
, cur
);
3018 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",
3025 TRACE("Added rule to bpf device program: type %c, major %d, minor %d, access %s, allow %d, global_rule %d",
3034 ret
= bpf_program_finalize(devices
);
3036 return log_error_errno(false, ENOMEM
, "Failed to finalize bpf program");
3038 ret
= bpf_program_cgroup_attach(devices
, BPF_CGROUP_DEVICE
,
3039 unified
->container_limit_path
,
3042 return log_error_errno(false, ENOMEM
, "Failed to attach bpf program");
3044 /* Replace old bpf program. */
3045 devices_old
= move_ptr(conf
->cgroup2_devices
);
3046 conf
->cgroup2_devices
= move_ptr(devices
);
3047 devices
= move_ptr(devices_old
);
3052 bool __cgfsng_delegate_controllers(struct cgroup_ops
*ops
, const char *cgroup
)
3054 __do_free
char *add_controllers
= NULL
, *base_path
= NULL
;
3055 __do_free_string_list
char **parts
= NULL
;
3056 struct hierarchy
*unified
= ops
->unified
;
3059 size_t full_len
= 0;
3061 if (!ops
->hierarchies
|| !pure_unified_layout(ops
) ||
3062 !unified
->controllers
[0])
3065 /* For now we simply enable all controllers that we have detected by
3066 * creating a string like "+memory +pids +cpu +io".
3067 * TODO: In the near future we might want to support "-<controller>"
3068 * etc. but whether supporting semantics like this make sense will need
3071 for (it
= unified
->controllers
; it
&& *it
; it
++) {
3072 full_len
+= strlen(*it
) + 2;
3073 add_controllers
= must_realloc(add_controllers
, full_len
+ 1);
3075 if (unified
->controllers
[0] == *it
)
3076 add_controllers
[0] = '\0';
3078 (void)strlcat(add_controllers
, "+", full_len
+ 1);
3079 (void)strlcat(add_controllers
, *it
, full_len
+ 1);
3081 if ((it
+ 1) && *(it
+ 1))
3082 (void)strlcat(add_controllers
, " ", full_len
+ 1);
3085 parts
= lxc_string_split(cgroup
, '/');
3089 parts_len
= lxc_array_len((void **)parts
);
3093 base_path
= must_make_path(unified
->mountpoint
, unified
->container_base_path
, NULL
);
3094 for (ssize_t i
= -1; i
< parts_len
; i
++) {
3096 __do_free
char *target
= NULL
;
3099 base_path
= must_append_path(base_path
, parts
[i
], NULL
);
3100 target
= must_make_path(base_path
, "cgroup.subtree_control", NULL
);
3101 ret
= lxc_writeat(-1, target
, add_controllers
, full_len
);
3103 return log_error_errno(false, errno
, "Could not enable \"%s\" controllers in the unified cgroup \"%s\"",
3104 add_controllers
, target
);
3105 TRACE("Enable \"%s\" controllers in the unified cgroup \"%s\"", add_controllers
, target
);
3111 __cgfsng_ops
bool cgfsng_monitor_delegate_controllers(struct cgroup_ops
*ops
)
3114 return ret_set_errno(false, ENOENT
);
3116 return __cgfsng_delegate_controllers(ops
, ops
->monitor_cgroup
);
3119 __cgfsng_ops
bool cgfsng_payload_delegate_controllers(struct cgroup_ops
*ops
)
3122 return ret_set_errno(false, ENOENT
);
3124 return __cgfsng_delegate_controllers(ops
, ops
->container_cgroup
);
3127 static bool cgroup_use_wants_controllers(const struct cgroup_ops
*ops
,
3130 if (!ops
->cgroup_use
)
3133 for (char **cur_ctrl
= controllers
; cur_ctrl
&& *cur_ctrl
; cur_ctrl
++) {
3136 for (char **cur_use
= ops
->cgroup_use
; cur_use
&& *cur_use
; cur_use
++) {
3137 if (strcmp(*cur_use
, *cur_ctrl
) != 0)
3153 static void cg_unified_delegate(char ***delegate
)
3155 __do_free
char *buf
= NULL
;
3156 char *standard
[] = {"cgroup.subtree_control", "cgroup.threads", NULL
};
3160 buf
= read_file("/sys/kernel/cgroup/delegate");
3162 for (char **p
= standard
; p
&& *p
; p
++) {
3163 idx
= append_null_to_list((void ***)delegate
);
3164 (*delegate
)[idx
] = must_copy_string(*p
);
3166 SYSWARN("Failed to read /sys/kernel/cgroup/delegate");
3170 lxc_iterate_parts(token
, buf
, " \t\n") {
3172 * We always need to chown this for both cgroup and
3175 if (strcmp(token
, "cgroup.procs") == 0)
3178 idx
= append_null_to_list((void ***)delegate
);
3179 (*delegate
)[idx
] = must_copy_string(token
);
3183 /* At startup, parse_hierarchies finds all the info we need about cgroup
3184 * mountpoints and current cgroups, and stores it in @d.
3186 static int cg_hybrid_init(struct cgroup_ops
*ops
, bool relative
, bool unprivileged
)
3188 __do_free
char *basecginfo
= NULL
, *line
= NULL
;
3189 __do_free_string_list
char **klist
= NULL
, **nlist
= NULL
;
3190 __do_fclose
FILE *f
= NULL
;
3194 /* Root spawned containers escape the current cgroup, so use init's
3195 * cgroups as our base in that case.
3197 if (!relative
&& (geteuid() == 0))
3198 basecginfo
= read_file("/proc/1/cgroup");
3200 basecginfo
= read_file("/proc/self/cgroup");
3202 return ret_set_errno(-1, ENOMEM
);
3204 ret
= get_existing_subsystems(&klist
, &nlist
);
3206 return log_error_errno(-1, errno
, "Failed to retrieve available legacy cgroup controllers");
3208 f
= fopen("/proc/self/mountinfo", "re");
3210 return log_error_errno(-1, errno
, "Failed to open \"/proc/self/mountinfo\"");
3212 lxc_cgfsng_print_basecg_debuginfo(basecginfo
, klist
, nlist
);
3214 while (getline(&line
, &len
, f
) != -1) {
3215 __do_free
char *base_cgroup
= NULL
, *mountpoint
= NULL
;
3216 __do_free_string_list
char **controller_list
= NULL
;
3219 struct hierarchy
*new;
3221 type
= get_cgroup_version(line
);
3225 if (type
== CGROUP2_SUPER_MAGIC
&& ops
->unified
)
3228 if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNKNOWN
) {
3229 if (type
== CGROUP2_SUPER_MAGIC
)
3230 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
3231 else if (type
== CGROUP_SUPER_MAGIC
)
3232 ops
->cgroup_layout
= CGROUP_LAYOUT_LEGACY
;
3233 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_UNIFIED
) {
3234 if (type
== CGROUP_SUPER_MAGIC
)
3235 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
3236 } else if (ops
->cgroup_layout
== CGROUP_LAYOUT_LEGACY
) {
3237 if (type
== CGROUP2_SUPER_MAGIC
)
3238 ops
->cgroup_layout
= CGROUP_LAYOUT_HYBRID
;
3241 controller_list
= cg_hybrid_get_controllers(klist
, nlist
, line
, type
);
3242 if (!controller_list
&& type
== CGROUP_SUPER_MAGIC
)
3245 if (type
== CGROUP_SUPER_MAGIC
)
3246 if (controller_list_is_dup(ops
->hierarchies
, controller_list
)) {
3247 TRACE("Skipping duplicating controller");
3251 mountpoint
= cg_hybrid_get_mountpoint(line
);
3253 ERROR("Failed parsing mountpoint from \"%s\"", line
);
3257 if (type
== CGROUP_SUPER_MAGIC
)
3258 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, controller_list
[0], CGROUP_SUPER_MAGIC
);
3260 base_cgroup
= cg_hybrid_get_current_cgroup(basecginfo
, NULL
, CGROUP2_SUPER_MAGIC
);
3262 ERROR("Failed to find current cgroup");
3267 prune_init_scope(base_cgroup
);
3268 if (type
== CGROUP2_SUPER_MAGIC
)
3269 writeable
= test_writeable_v2(mountpoint
, base_cgroup
);
3271 writeable
= test_writeable_v1(mountpoint
, base_cgroup
);
3273 TRACE("The %s group is not writeable", base_cgroup
);
3277 if (type
== CGROUP2_SUPER_MAGIC
) {
3278 char *cgv2_ctrl_path
;
3280 cgv2_ctrl_path
= must_make_path(mountpoint
, base_cgroup
,
3281 "cgroup.controllers",
3284 controller_list
= cg_unified_get_controllers(cgv2_ctrl_path
);
3285 free(cgv2_ctrl_path
);
3286 if (!controller_list
) {
3287 controller_list
= cg_unified_make_empty_controller();
3288 TRACE("No controllers are enabled for "
3289 "delegation in the unified hierarchy");
3293 /* Exclude all controllers that cgroup use does not want. */
3294 if (!cgroup_use_wants_controllers(ops
, controller_list
)) {
3295 TRACE("Skipping controller");
3299 new = add_hierarchy(&ops
->hierarchies
, move_ptr(controller_list
), move_ptr(mountpoint
), move_ptr(base_cgroup
), type
);
3300 if (type
== CGROUP2_SUPER_MAGIC
&& !ops
->unified
) {
3302 cg_unified_delegate(&new->cgroup2_chown
);
3307 TRACE("Writable cgroup hierarchies:");
3308 lxc_cgfsng_print_hierarchies(ops
);
3310 /* verify that all controllers in cgroup.use and all crucial
3311 * controllers are accounted for
3313 if (!all_controllers_found(ops
))
3314 return log_error_errno(-1, ENOENT
, "Failed to find all required controllers");
3319 /* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
3320 static char *cg_unified_get_current_cgroup(bool relative
)
3322 __do_free
char *basecginfo
= NULL
;
3326 if (!relative
&& (geteuid() == 0))
3327 basecginfo
= read_file("/proc/1/cgroup");
3329 basecginfo
= read_file("/proc/self/cgroup");
3333 base_cgroup
= strstr(basecginfo
, "0::/");
3337 base_cgroup
= base_cgroup
+ 3;
3338 copy
= copy_to_eol(base_cgroup
);
3345 static int cg_unified_init(struct cgroup_ops
*ops
, bool relative
,
3348 __do_free
char *subtree_path
= NULL
;
3352 struct hierarchy
*new;
3353 char *base_cgroup
= NULL
;
3355 ret
= unified_cgroup_hierarchy();
3356 if (ret
== -ENOMEDIUM
)
3357 return ret_errno(ENOMEDIUM
);
3359 if (ret
!= CGROUP2_SUPER_MAGIC
)
3362 base_cgroup
= cg_unified_get_current_cgroup(relative
);
3364 return ret_errno(EINVAL
);
3366 prune_init_scope(base_cgroup
);
3369 * We assume that the cgroup we're currently in has been delegated to
3370 * us and we are free to further delege all of the controllers listed
3371 * in cgroup.controllers further down the hierarchy.
3373 mountpoint
= must_copy_string(DEFAULT_CGROUP_MOUNTPOINT
);
3374 subtree_path
= must_make_path(mountpoint
, base_cgroup
, "cgroup.controllers", NULL
);
3375 delegatable
= cg_unified_get_controllers(subtree_path
);
3377 delegatable
= cg_unified_make_empty_controller();
3378 if (!delegatable
[0])
3379 TRACE("No controllers are enabled for delegation");
3381 /* TODO: If the user requested specific controllers via lxc.cgroup.use
3382 * we should verify here. The reason I'm not doing it right is that I'm
3383 * not convinced that lxc.cgroup.use will be the future since it is a
3384 * global property. I much rather have an option that lets you request
3385 * controllers per container.
3388 new = add_hierarchy(&ops
->hierarchies
, delegatable
, mountpoint
, base_cgroup
, CGROUP2_SUPER_MAGIC
);
3390 cg_unified_delegate(&new->cgroup2_chown
);
3392 if (bpf_devices_cgroup_supported())
3393 new->bpf_device_controller
= 1;
3395 ops
->cgroup_layout
= CGROUP_LAYOUT_UNIFIED
;
3398 return CGROUP2_SUPER_MAGIC
;
3401 static int cg_init(struct cgroup_ops
*ops
, struct lxc_conf
*conf
)
3405 bool relative
= conf
->cgroup_meta
.relative
;
3407 tmp
= lxc_global_config_value("lxc.cgroup.use");
3409 __do_free
char *pin
= NULL
;
3412 pin
= must_copy_string(tmp
);
3415 lxc_iterate_parts(cur
, chop
, ",")
3416 must_append_string(&ops
->cgroup_use
, cur
);
3419 ret
= cg_unified_init(ops
, relative
, !lxc_list_empty(&conf
->id_map
));
3423 if (ret
== CGROUP2_SUPER_MAGIC
)
3426 return cg_hybrid_init(ops
, relative
, !lxc_list_empty(&conf
->id_map
));
3429 __cgfsng_ops
static int cgfsng_data_init(struct cgroup_ops
*ops
)
3431 const char *cgroup_pattern
;
3434 return ret_set_errno(-1, ENOENT
);
3436 /* copy system-wide cgroup information */
3437 cgroup_pattern
= lxc_global_config_value("lxc.cgroup.pattern");
3438 if (cgroup_pattern
&& strcmp(cgroup_pattern
, "") != 0)
3439 ops
->cgroup_pattern
= must_copy_string(cgroup_pattern
);
3444 struct cgroup_ops
*cgfsng_ops_init(struct lxc_conf
*conf
)
3446 __do_free
struct cgroup_ops
*cgfsng_ops
= NULL
;
3448 cgfsng_ops
= malloc(sizeof(struct cgroup_ops
));
3450 return ret_set_errno(NULL
, ENOMEM
);
3452 memset(cgfsng_ops
, 0, sizeof(struct cgroup_ops
));
3453 cgfsng_ops
->cgroup_layout
= CGROUP_LAYOUT_UNKNOWN
;
3455 if (cg_init(cgfsng_ops
, conf
))
3458 cgfsng_ops
->data_init
= cgfsng_data_init
;
3459 cgfsng_ops
->payload_destroy
= cgfsng_payload_destroy
;
3460 cgfsng_ops
->monitor_destroy
= cgfsng_monitor_destroy
;
3461 cgfsng_ops
->monitor_create
= cgfsng_monitor_create
;
3462 cgfsng_ops
->monitor_enter
= cgfsng_monitor_enter
;
3463 cgfsng_ops
->monitor_delegate_controllers
= cgfsng_monitor_delegate_controllers
;
3464 cgfsng_ops
->payload_delegate_controllers
= cgfsng_payload_delegate_controllers
;
3465 cgfsng_ops
->payload_create
= cgfsng_payload_create
;
3466 cgfsng_ops
->payload_enter
= cgfsng_payload_enter
;
3467 cgfsng_ops
->payload_finalize
= cgfsng_payload_finalize
;
3468 cgfsng_ops
->escape
= cgfsng_escape
;
3469 cgfsng_ops
->num_hierarchies
= cgfsng_num_hierarchies
;
3470 cgfsng_ops
->get_hierarchies
= cgfsng_get_hierarchies
;
3471 cgfsng_ops
->get_cgroup
= cgfsng_get_cgroup
;
3472 cgfsng_ops
->get
= cgfsng_get
;
3473 cgfsng_ops
->set
= cgfsng_set
;
3474 cgfsng_ops
->freeze
= cgfsng_freeze
;
3475 cgfsng_ops
->unfreeze
= cgfsng_unfreeze
;
3476 cgfsng_ops
->setup_limits_legacy
= cgfsng_setup_limits_legacy
;
3477 cgfsng_ops
->setup_limits
= cgfsng_setup_limits
;
3478 cgfsng_ops
->driver
= "cgfsng";
3479 cgfsng_ops
->version
= "1.0.0";
3480 cgfsng_ops
->attach
= cgfsng_attach
;
3481 cgfsng_ops
->chown
= cgfsng_chown
;
3482 cgfsng_ops
->mount
= cgfsng_mount
;
3483 cgfsng_ops
->devices_activate
= cgfsng_devices_activate
;
3484 cgfsng_ops
->get_limiting_cgroup
= cgfsng_get_limiting_cgroup
;
3486 return move_ptr(cgfsng_ops
);