Skip to content

Commit e6d3eb2

Browse files
committed
Handle already-mounted cgroups in cgroup_init()
Add handling for EBUSY when mounting cgroup2 filesystem, which occurs when cgroups are already mounted. This can happen after switch_root when cgroups were moved from the initramfs, or in container environments. Verify the existing mount is actually cgroup2 before proceeding, and track whether we mounted to avoid unmounting on error if we didn't.
1 parent d7fd5bc commit e6d3eb2

File tree

1 file changed

+32
-6
lines changed

1 file changed

+32
-6
lines changed

src/cgroup.c

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@
3434
#endif
3535
#include <sys/mount.h>
3636
#include <sys/sysinfo.h> /* get_nprocs_conf() */
37+
#include <sys/vfs.h>
38+
#include <linux/magic.h>
3739

3840
#include "cgroup.h"
3941
#include "finit.h"
@@ -841,6 +843,7 @@ void cgroup_config(void)
841843
void cgroup_init(uev_ctx_t *ctx)
842844
{
843845
int opts = MS_NODEV | MS_NOEXEC | MS_NOSUID;
846+
int mounted = 0;
844847
char buf[80];
845848
FILE *fp;
846849
int fd;
@@ -851,14 +854,36 @@ void cgroup_init(uev_ctx_t *ctx)
851854
#endif
852855

853856
if (mount("none", FINIT_CGPATH, "cgroup2", opts, NULL)) {
854-
if (errno == ENOENT)
857+
if (errno == EBUSY) {
858+
/*
859+
* Already mounted - this happens after switch_root
860+
* when cgroups were moved from the initramfs.
861+
* Verify it's actually cgroup2 before proceeding.
862+
*/
863+
struct statfs sfs;
864+
865+
if (statfs(FINIT_CGPATH, &sfs) || sfs.f_type != CGROUP2_SUPER_MAGIC) {
866+
logit(LOG_ERR, "Mount point %s busy but not cgroup2", FINIT_CGPATH);
867+
avail = 0;
868+
return;
869+
}
870+
dbg("cgroup2 already mounted at %s, reusing", FINIT_CGPATH);
871+
} else if (errno == ENOENT) {
855872
logit(LOG_INFO, "Kernel does not support cgroups v2, disabling.");
856-
else if (errno == EPERM) /* Probably inside an unprivileged container */
873+
avail = 0;
874+
return;
875+
} else if (errno == EPERM) {
876+
/* Probably inside an unprivileged container */
857877
logit(LOG_INFO, "Not allowed to mount cgroups v2, disabling.");
858-
else
878+
avail = 0;
879+
return;
880+
} else {
859881
err(1, "Failed mounting cgroup v2");
860-
avail = 0;
861-
return;
882+
avail = 0;
883+
return;
884+
}
885+
} else {
886+
mounted = 1;
862887
}
863888
avail = 1;
864889

@@ -867,7 +892,8 @@ void cgroup_init(uev_ctx_t *ctx)
867892
if (!fp) {
868893
err(1, "Failed opening %s", FINIT_CGPATH "/cgroup.controllers");
869894
abort:
870-
umount(FINIT_CGPATH);
895+
if (mounted)
896+
umount(FINIT_CGPATH);
871897
avail = 0;
872898
return;
873899
}

0 commit comments

Comments
 (0)