• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 13753893467

09 Mar 2025 10:51PM UTC coverage: 71.913% (+0.1%) from 71.816%
13753893467

push

github

web-flow
meson: bump required minimum version to 0.62.0 (#36610)

- bump the requred minimum version of meson to 0.62.0,
- use install_symlink(), which is supported since meson-0.61.0,
- use more features provided by newer meson with careful
conditionalization.

Follow-up for 8442ac9c0.
Closes #35967.

295857 of 411410 relevant lines covered (71.91%)

717151.89 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

35.78
/src/shared/mount-setup.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <errno.h>
4
#include <stdlib.h>
5
#include <sys/mount.h>
6
#include <sys/statvfs.h>
7
#include <unistd.h>
8

9
#include "alloc-util.h"
10
#include "bus-util.h"
11
#include "cgroup-setup.h"
12
#include "cgroup-util.h"
13
#include "conf-files.h"
14
#include "dev-setup.h"
15
#include "dirent-util.h"
16
#include "efi-loader.h"
17
#include "fd-util.h"
18
#include "fileio.h"
19
#include "fs-util.h"
20
#include "label-util.h"
21
#include "log.h"
22
#include "macro.h"
23
#include "mkdir-label.h"
24
#include "mount-setup.h"
25
#include "mount-util.h"
26
#include "mountpoint-util.h"
27
#include "nulstr-util.h"
28
#include "path-util.h"
29
#include "recurse-dir.h"
30
#include "set.h"
31
#include "smack-util.h"
32
#include "strv.h"
33
#include "user-util.h"
34
#include "virt.h"
35

36
typedef enum MountMode {
37
        MNT_NONE              = 0,
38
        MNT_FATAL             = 1 << 0,
39
        MNT_IN_CONTAINER      = 1 << 1,
40
        MNT_CHECK_WRITABLE    = 1 << 2,
41
        MNT_FOLLOW_SYMLINK    = 1 << 3,
42
        MNT_USRQUOTA_GRACEFUL = 1 << 4,
43
} MountMode;
44

45
typedef struct MountPoint {
46
        const char *what;
47
        const char *where;
48
        const char *type;
49
        const char *options;
50
        unsigned long flags;
51
        bool (*condition_fn)(void);
52
        MountMode mode;
53
} MountPoint;
54

55
/* The first three entries we might need before SELinux is up. The
56
 * fourth (securityfs) is needed by IMA to load a custom policy. The
57
 * other ones we can delay until SELinux and IMA are loaded. When
58
 * SMACK is enabled we need smackfs, too, so it's a fifth one. */
59
#if ENABLE_SMACK
60
#define N_EARLY_MOUNT 5
61
#else
62
#define N_EARLY_MOUNT 4
63
#endif
64

65
static bool check_recursiveprot_supported(void) {
112✔
66
        int r;
112✔
67

68
        if (!cg_is_unified_wanted())
112✔
69
                return false;
70

71
        r = mount_option_supported("cgroup2", "memory_recursiveprot", NULL);
112✔
72
        if (r < 0)
112✔
73
                log_debug_errno(r, "Failed to determine whether the 'memory_recursiveprot' mount option is supported, assuming not: %m");
×
74
        else if (r == 0)
112✔
75
                log_debug("This kernel version does not support 'memory_recursiveprot', not using mount option.");
×
76

77
        return r > 0;
112✔
78
}
79

80
static const MountPoint mount_table[] = {
81
        { "proc",        "/proc",                     "proc",       NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
82
          NULL,          MNT_FATAL|MNT_IN_CONTAINER|MNT_FOLLOW_SYMLINK },
83
        { "sysfs",       "/sys",                      "sysfs",      NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
84
          NULL,          MNT_FATAL|MNT_IN_CONTAINER },
85
        { "devtmpfs",    "/dev",                      "devtmpfs",   "mode=0755" TMPFS_LIMITS_DEV,               MS_NOSUID|MS_STRICTATIME,
86
          NULL,          MNT_FATAL|MNT_IN_CONTAINER },
87
        { "securityfs",  "/sys/kernel/security",      "securityfs", NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
88
          NULL,          MNT_NONE                   },
89
#if ENABLE_SMACK
90
        { "smackfs",     "/sys/fs/smackfs",           "smackfs",    "smackfsdef=*",                             MS_NOSUID|MS_NOEXEC|MS_NODEV,
91
          mac_smack_use, MNT_FATAL                  },
92
        { "tmpfs",       "/dev/shm",                  "tmpfs",      "mode=01777,smackfsroot=*",                 MS_NOSUID|MS_NODEV|MS_STRICTATIME,
93
          mac_smack_use, MNT_FATAL|MNT_USRQUOTA_GRACEFUL },
94
#endif
95
        { "tmpfs",       "/dev/shm",                  "tmpfs",      "mode=01777",                               MS_NOSUID|MS_NODEV|MS_STRICTATIME,
96
          NULL,          MNT_FATAL|MNT_IN_CONTAINER|MNT_USRQUOTA_GRACEFUL },
97
        { "devpts",      "/dev/pts",                  "devpts",     "mode=" STRINGIFY(TTY_MODE) ",gid=" STRINGIFY(TTY_GID), MS_NOSUID|MS_NOEXEC,
98
          NULL,          MNT_IN_CONTAINER           },
99
#if ENABLE_SMACK
100
        { "tmpfs",       "/run",                      "tmpfs",      "mode=0755,smackfsroot=*" TMPFS_LIMITS_RUN, MS_NOSUID|MS_NODEV|MS_STRICTATIME,
101
          mac_smack_use, MNT_FATAL                  },
102
#endif
103
        { "tmpfs",       "/run",                      "tmpfs",      "mode=0755" TMPFS_LIMITS_RUN,               MS_NOSUID|MS_NODEV|MS_STRICTATIME,
104
          NULL,          MNT_FATAL|MNT_IN_CONTAINER },
105
        { "cgroup2",     "/sys/fs/cgroup",            "cgroup2",    "nsdelegate,memory_recursiveprot",          MS_NOSUID|MS_NOEXEC|MS_NODEV,
106
          check_recursiveprot_supported, MNT_IN_CONTAINER|MNT_CHECK_WRITABLE },
107
        { "cgroup2",     "/sys/fs/cgroup",            "cgroup2",    "nsdelegate",                               MS_NOSUID|MS_NOEXEC|MS_NODEV,
108
          cg_is_unified_wanted, MNT_IN_CONTAINER|MNT_CHECK_WRITABLE },
109
        { "cgroup2",     "/sys/fs/cgroup",            "cgroup2",    NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
110
          cg_is_unified_wanted, MNT_IN_CONTAINER|MNT_CHECK_WRITABLE },
111
#if ENABLE_PSTORE
112
        { "pstore",      "/sys/fs/pstore",            "pstore",     NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
113
          NULL,          MNT_NONE                   },
114
#endif
115
#if ENABLE_EFI
116
        { "efivarfs",    "/sys/firmware/efi/efivars", "efivarfs",   NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
117
          is_efi_boot,   MNT_NONE                   },
118
#endif
119
        { "bpf",         "/sys/fs/bpf",               "bpf",        "mode=0700",                                MS_NOSUID|MS_NOEXEC|MS_NODEV,
120
          NULL,          MNT_NONE,                  },
121
};
122

123
assert_cc(N_EARLY_MOUNT <= ELEMENTSOF(mount_table));
124

125
bool mount_point_is_api(const char *path) {
110,760✔
126
        /* Checks if this mount point is considered "API", and hence
127
         * should be ignored */
128

129
        FOREACH_ELEMENT(i, mount_table)
1,571,135✔
130
                if (path_equal(path, i->where))
1,491,678✔
131
                        return true;
132

133
        return path_startswith(path, "/sys/fs/cgroup/");
79,457✔
134
}
135

136
bool mount_point_ignore(const char *path) {
79,445✔
137
        /* These are API file systems that might be mounted by other software, we just list them here so that
138
         * we know that we should ignore them. */
139
        FOREACH_STRING(i,
468,858✔
140
                       /* SELinux file systems */
141
                       "/sys/fs/selinux",
142
                       /* Container bind mounts */
143
                       "/dev/console",
144
                       "/proc/kmsg",
145
                       "/proc/sys",
146
                       "/proc/sys/kernel/random/boot_id")
147
                if (path_equal(path, i))
393,877✔
148
                        return true;
4,464✔
149

150
        if (path_startswith(path, "/run/host")) /* All mounts passed in from the container manager are
74,981✔
151
                                                 * something we better ignore. */
152
                return true;
6,696✔
153

154
        return false;
155
}
156

157
static int mount_one(const MountPoint *p, bool relabel) {
2,127✔
158
        int r, priority;
2,127✔
159

160
        assert(p);
2,127✔
161
        assert(p->what);
2,127✔
162
        assert(p->where);
2,127✔
163
        assert(p->type);
2,127✔
164

165
        priority = FLAGS_SET(p->mode, MNT_FATAL) ? LOG_ERR : LOG_DEBUG;
2,127✔
166

167
        if (p->condition_fn && !p->condition_fn())
2,127✔
168
                return 0;
2,127✔
169

170
        /* Relabel first, just in case */
171
        if (relabel)
1,623✔
172
                (void) label_fix(p->where, LABEL_IGNORE_ENOENT|LABEL_IGNORE_EROFS);
×
173

174
        r = path_is_mount_point_full(p->where, /* root = */ NULL, AT_SYMLINK_FOLLOW);
1,623✔
175
        if (r < 0 && r != -ENOENT) {
1,623✔
176
                log_full_errno(priority, r, "Failed to determine whether %s is a mount point: %m", p->where);
×
177
                return FLAGS_SET(p->mode, MNT_FATAL) ? r : 0;
×
178
        }
179
        if (r > 0)
1,623✔
180
                return 0;
181

182
        if (!FLAGS_SET(p->mode, MNT_IN_CONTAINER) && detect_container() > 0)
738✔
183
                return 0;
184

185
        /* The access mode here doesn't really matter too much, since
186
         * the mounted file system will take precedence anyway. */
187
        if (relabel)
618✔
188
                (void) mkdir_p_label(p->where, 0755);
×
189
        else
190
                (void) mkdir_p(p->where, 0755);
618✔
191

192
        _cleanup_free_ char *extend_options = NULL;
618✔
193
        const char *o = p->options;
618✔
194
        if (FLAGS_SET(p->mode, MNT_USRQUOTA_GRACEFUL)) {
618✔
195
                r = mount_option_supported(p->type, "usrquota", /* value= */ NULL);
61✔
196
                if (r < 0)
61✔
197
                        log_full_errno(priority, r, "Unable to determine whether %s supports 'usrquota' mount option, assuming not: %m", p->type);
×
198
                else if (r == 0)
61✔
199
                        log_debug("Not enabling 'usrquota' on '%s' as kernel lacks support for it.", p->where);
×
200
                else {
201
                        if (!strextend_with_separator(&extend_options, ",", p->options ?: POINTER_MAX, "usrquota"))
122✔
202
                                return log_oom();
×
203

204
                        o = extend_options;
61✔
205
                }
206
        }
207

208
        log_debug("Mounting %s to %s of type %s with options %s.",
992✔
209
                  p->what,
210
                  p->where,
211
                  p->type,
212
                  strna(o));
213

214
        r = mount_verbose_full(priority, p->what, p->where, p->type, p->flags, o, FLAGS_SET(p->mode, MNT_FOLLOW_SYMLINK));
618✔
215
        if (r < 0)
618✔
216
                return FLAGS_SET(p->mode, MNT_FATAL) ? r : 0;
×
217

218
        /* Relabel again, since we now mounted something fresh here */
219
        if (relabel)
618✔
220
                (void) label_fix(p->where, 0);
×
221

222
        if (FLAGS_SET(p->mode, MNT_CHECK_WRITABLE))
618✔
223
                if (access(p->where, W_OK) < 0) {
61✔
224
                        r = -errno;
×
225

226
                        (void) umount2(p->where, UMOUNT_NOFOLLOW);
×
227
                        (void) rmdir(p->where);
×
228

229
                        log_full_errno(priority, r, "Mount point '%s' not writable after mounting, undoing: %m", p->where);
×
230
                        return FLAGS_SET(p->mode, MNT_FATAL) ? r : 0;
×
231
                }
232

233
        return 1;
234
}
235

236
static int mount_points_setup(size_t n, bool loaded_policy) {
179✔
237
        int r = 0;
179✔
238

239
        assert(n <= ELEMENTSOF(mount_table));
179✔
240

241
        FOREACH_ARRAY(mp, mount_table, n)
2,306✔
242
                RET_GATHER(r, mount_one(mp, loaded_policy));
2,127✔
243

244
        return r;
179✔
245
}
246

247
int mount_setup_early(void) {
67✔
248
        /* Do a minimal mount of /proc and friends to enable the most basic stuff, such as SELinux */
249
        return mount_points_setup(N_EARLY_MOUNT, /* loaded_policy= */ false);
67✔
250
}
251

252
static const char *join_with(const char *controller) {
×
253

254
        static const char* const pairs[] = {
×
255
                "cpu", "cpuacct",
256
                "net_cls", "net_prio",
257
                NULL
258
        };
259

260
        assert(controller);
×
261

262
        /* This will lookup which controller to mount another controller with. Input is a controller name, and output
263
         * is the other controller name. The function works both ways: you can input one and get the other, and input
264
         * the other to get the one. */
265

266
        STRV_FOREACH_PAIR(x, y, pairs) {
×
267
                if (streq(controller, *x))
×
268
                        return *y;
269
                if (streq(controller, *y))
×
270
                        return *x;
271
        }
272

273
        return NULL;
274
}
275

276
static int symlink_controller(const char *target, const char *alias) {
×
277
        const char *a;
×
278
        int r;
×
279

280
        assert(target);
×
281
        assert(alias);
×
282

283
        a = strjoina("/sys/fs/cgroup/", alias);
×
284

285
        r = symlink_idempotent(target, a, false);
×
286
        if (r < 0)
×
287
                return log_error_errno(r, "Failed to create symlink %s: %m", a);
×
288

289
#if HAVE_SMACK_RUN_LABEL
290
        const char *p;
291

292
        p = strjoina("/sys/fs/cgroup/", target);
293

294
        r = mac_smack_copy(a, p);
295
        if (r < 0 && !ERRNO_IS_NOT_SUPPORTED(r))
296
                return log_error_errno(r, "Failed to copy smack label from %s to %s: %m", p, a);
297
#endif
298

299
        return 0;
300
}
301

302
#if HAVE_SELINUX || ENABLE_SMACK
303
static int relabel_cb(
×
304
                RecurseDirEvent event,
305
                const char *path,
306
                int dir_fd,
307
                int inode_fd,
308
                const struct dirent *de,
309
                const struct statx *sx,
310
                void *userdata) {
311

312
        switch (event) {
×
313

314
        case RECURSE_DIR_LEAVE:
315
        case RECURSE_DIR_SKIP_MOUNT:
316
                /* If we already saw this dirent when entering it or this is a dirent that on a different
317
                 * mount, don't relabel it. */
318
                return RECURSE_DIR_CONTINUE;
319

320
        case RECURSE_DIR_ENTER:
×
321
                /* /run/initramfs/ + /run/nextroot/ are static data and big, no need to dynamically relabel
322
                 * its contents at boot... */
323
                if (PATH_STARTSWITH_SET(path, "/run/initramfs", "/run/nextroot"))
×
324
                        return RECURSE_DIR_SKIP_ENTRY;
×
325

326
                _fallthrough_;
×
327

328
        default:
329
                /* Otherwise, label it, even if we had trouble stat()ing it and similar. SELinux can figure this out */
330
                (void) label_fix(path, 0);
×
331
                return RECURSE_DIR_CONTINUE;
×
332
        }
333
}
334

335
static int relabel_tree(const char *path) {
×
336
        int r;
×
337

338
        r = recurse_dir_at(AT_FDCWD, path, 0, UINT_MAX, RECURSE_DIR_ENSURE_TYPE|RECURSE_DIR_SAME_MOUNT, relabel_cb, NULL);
×
339
        if (r < 0)
×
340
                log_debug_errno(r, "Failed to recursively relabel '%s': %m", path);
×
341

342
        return r;
×
343
}
344

345
static int relabel_extra(void) {
×
346
        _cleanup_strv_free_ char **files = NULL;
×
347
        int r, c = 0;
×
348

349
        /* Support for relabelling additional files or directories after loading the policy. For this, code in the
350
         * initrd simply has to drop in *.relabel files into /run/systemd/relabel-extra.d/. We'll read all such files
351
         * expecting one absolute path by line and will relabel each (and everyone below that in case the path refers
352
         * to a directory). These drop-in files are supposed to be absolutely minimal, and do not understand comments
353
         * and such. After the operation succeeded the files are removed, and the drop-in directory as well, if
354
         * possible.
355
         */
356

357
        r = conf_files_list(&files, ".relabel", NULL,
×
358
                            CONF_FILES_FILTER_MASKED | CONF_FILES_REGULAR,
359
                            "/run/systemd/relabel-extra.d/");
360
        if (r < 0)
×
361
                return log_error_errno(r, "Failed to enumerate /run/systemd/relabel-extra.d/, ignoring: %m");
×
362

363
        STRV_FOREACH(file, files) {
×
364
                _cleanup_fclose_ FILE *f = NULL;
×
365

366
                f = fopen(*file, "re");
×
367
                if (!f) {
×
368
                        log_warning_errno(errno, "Failed to open %s, ignoring: %m", *file);
×
369
                        continue;
×
370
                }
371

372
                for (;;) {
×
373
                        _cleanup_free_ char *line = NULL;
×
374

375
                        r = read_line(f, LONG_LINE_MAX, &line);
×
376
                        if (r < 0) {
×
377
                                log_warning_errno(r, "Failed to read %s, ignoring: %m", *file);
×
378
                                break;
379
                        }
380
                        if (r == 0) /* EOF */
×
381
                                break;
382

383
                        path_simplify(line);
×
384

385
                        if (!path_is_normalized(line)) {
×
386
                                log_warning("Path to relabel is not normalized, ignoring: %s", line);
×
387
                                continue;
×
388
                        }
389

390
                        if (!path_is_absolute(line)) {
×
391
                                log_warning("Path to relabel is not absolute, ignoring: %s", line);
×
392
                                continue;
×
393
                        }
394

395
                        log_debug("Relabelling additional file/directory '%s'.", line);
×
396
                        (void) label_fix(line, 0);
×
397
                        (void) relabel_tree(line);
×
398
                        c++;
×
399
                }
400

401
                if (unlink(*file) < 0)
×
402
                        log_warning_errno(errno, "Failed to remove %s, ignoring: %m", *file);
×
403
        }
404

405
        /* Remove when we complete things. */
406
        if (rmdir("/run/systemd/relabel-extra.d") < 0 &&
×
407
            errno != ENOENT)
×
408
                log_warning_errno(errno, "Failed to remove /run/systemd/relabel-extra.d/ directory: %m");
×
409

410
        return c;
411
}
412
#endif
413

414
int mount_setup(bool loaded_policy, bool leave_propagation) {
112✔
415
        int r;
112✔
416

417
        r = mount_points_setup(ELEMENTSOF(mount_table), loaded_policy);
112✔
418
        if (r < 0)
112✔
419
                return r;
420

421
#if HAVE_SELINUX || ENABLE_SMACK
422
        /* Nodes in devtmpfs and /run need to be manually updated for
423
         * the appropriate labels, after mounting. The other virtual
424
         * API file systems like /sys and /proc do not need that, they
425
         * use the same label for all their files. */
426
        if (loaded_policy) {
112✔
427
                usec_t before_relabel, after_relabel;
×
428
                int n_extra;
×
429

430
                before_relabel = now(CLOCK_MONOTONIC);
×
431

432
                FOREACH_STRING(i, "/dev", "/dev/shm", "/run")
×
433
                        (void) relabel_tree(i);
×
434

435
                n_extra = relabel_extra();
×
436

437
                after_relabel = now(CLOCK_MONOTONIC);
×
438

439
                log_info("Relabeled /dev/, /dev/shm/, /run/%s in %s.",
×
440
                         n_extra > 0 ? ", and additional files" : "",
441
                         FORMAT_TIMESPAN(after_relabel - before_relabel, 0));
442
        }
443
#endif
444

445
        /* Create a few default symlinks, which are normally created
446
         * by udevd, but some scripts might need them before we start
447
         * udevd. */
448
        dev_setup(NULL, UID_INVALID, GID_INVALID);
112✔
449

450
        /* Mark the root directory as shared in regards to mount propagation. The kernel defaults to "private", but we
451
         * think it makes more sense to have a default of "shared" so that nspawn and the container tools work out of
452
         * the box. If specific setups need other settings they can reset the propagation mode to private if
453
         * needed. Note that we set this only when we are invoked directly by the kernel. If we are invoked by a
454
         * container manager we assume the container manager knows what it is doing (for example, because it set up
455
         * some directories with different propagation modes). */
456
        if (detect_container() <= 0 && !leave_propagation)
112✔
457
                if (mount(NULL, "/", NULL, MS_REC|MS_SHARED, NULL) < 0)
67✔
458
                        log_warning_errno(errno, "Failed to set up the root directory for shared mount propagation: %m");
×
459

460
        /* Create a few directories we always want around, Note that sd_booted() checks for /run/systemd/system, so
461
         * this mkdir really needs to stay for good, otherwise software that copied sd-daemon.c into their sources will
462
         * misdetect systemd. */
463
        (void) mkdir_label("/run/systemd", 0755);
112✔
464
        (void) mkdir_label("/run/systemd/system", 0755);
112✔
465

466
        /* Make sure there's always a place where sandboxed environments can mount root file systems they are
467
         * about to move into, even when unprivileged, without having to create a temporary one in /tmp/
468
         * (which they then have to keep track of and clean) */
469
        (void) mkdir_label("/run/systemd/mount-rootfs", 0555);
112✔
470

471
        /* Make sure we have a mount point to hide in sandboxes */
472
        (void) mkdir_label("/run/credentials", 0755);
112✔
473

474
        /* Also create /run/systemd/inaccessible nodes, so that we always have something to mount
475
         * inaccessible nodes from. If we run in a container the host might have created these for us already
476
         * in /run/host/inaccessible/. Use those if we can, since that way we likely get access to block/char
477
         * device nodes that are inaccessible, and if userns is used to nodes that are on mounts owned by a
478
         * userns outside the container and thus nicely read-only and not remountable. */
479
        if (access("/run/host/inaccessible/", F_OK) < 0) {
112✔
480
                if (errno != ENOENT)
72✔
481
                        log_debug_errno(errno, "Failed to check if /run/host/inaccessible exists, ignoring: %m");
×
482

483
                (void) make_inaccessible_nodes("/run/systemd", UID_INVALID, GID_INVALID);
72✔
484
        } else
485
                (void) symlink("../host/inaccessible", "/run/systemd/inaccessible");
40✔
486

487
        return 0;
488
}
489

490
static const MountPoint cgroupv1_mount_table[] = {
491
        { "tmpfs",       "/sys/fs/cgroup",            "tmpfs",      "mode=0755" TMPFS_LIMITS_SYS_FS_CGROUP,     MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME,
492
          cg_is_legacy_wanted, MNT_FATAL|MNT_IN_CONTAINER },
493
        { "cgroup2",     "/sys/fs/cgroup/unified",    "cgroup2",    "nsdelegate",                               MS_NOSUID|MS_NOEXEC|MS_NODEV,
494
          cg_is_hybrid_wanted, MNT_IN_CONTAINER|MNT_CHECK_WRITABLE },
495
        { "cgroup2",     "/sys/fs/cgroup/unified",    "cgroup2",    NULL,                                       MS_NOSUID|MS_NOEXEC|MS_NODEV,
496
          cg_is_hybrid_wanted, MNT_IN_CONTAINER|MNT_CHECK_WRITABLE },
497
        { "cgroup",      "/sys/fs/cgroup/systemd",    "cgroup",     "none,name=systemd,xattr",                  MS_NOSUID|MS_NOEXEC|MS_NODEV,
498
          cg_is_legacy_wanted, MNT_IN_CONTAINER     },
499
        { "cgroup",      "/sys/fs/cgroup/systemd",    "cgroup",     "none,name=systemd",                        MS_NOSUID|MS_NOEXEC|MS_NODEV,
500
          cg_is_legacy_wanted, MNT_FATAL|MNT_IN_CONTAINER },
501
};
502

503
static void relabel_cgroup_legacy_hierarchy(void) {
×
504
#if HAVE_SELINUX || ENABLE_SMACK
505
        struct statfs st;
×
506

507
        assert(cg_is_legacy_wanted());
×
508

509
        /* Temporarily remount the root cgroup filesystem to give it a proper label. Do this
510
           only when the filesystem has been already populated by a previous instance of systemd
511
           running from initrd. Otherwise don't remount anything and leave the filesystem read-write
512
           for the cgroup filesystems to be mounted inside. */
513
        if (statfs("/sys/fs/cgroup", &st) < 0)
×
514
                return (void) log_error_errno(errno, "Failed to determine mount flags for /sys/fs/cgroup/: %m");
×
515

516
        if (st.f_flags & ST_RDONLY)
×
517
                (void) mount_nofollow(NULL, "/sys/fs/cgroup", NULL, MS_REMOUNT, NULL);
×
518

519
        (void) label_fix("/sys/fs/cgroup", 0);
×
520
        (void) relabel_tree("/sys/fs/cgroup");
×
521

522
        if (st.f_flags & ST_RDONLY)
×
523
                (void) mount_nofollow(NULL, "/sys/fs/cgroup", NULL, MS_REMOUNT|MS_RDONLY, NULL);
×
524
#endif
525
}
526

527
int mount_cgroup_legacy_controllers(bool loaded_policy) {
85✔
528
        _cleanup_set_free_ Set *controllers = NULL;
85✔
529
        int r;
85✔
530

531
        /* Before we actually start deleting cgroup v1 code, make it harder to boot in cgroupv1 mode first.
532
         * See also #30852. */
533

534
        if (detect_container() <= 0) { /* If in container, we have to follow host's cgroup hierarchy. Only
85✔
535
                                        * do the deprecation checks below if we're not in a container. */
536
                if (cg_is_legacy_force_enabled())
67✔
537
                        log_warning("Legacy support for cgroup v1 enabled via SYSTEMD_CGROUP_ENABLE_LEGACY_FORCE=1.");
×
538
                else if (cg_is_legacy_enabled()) {
67✔
539
                        log_full(LOG_CRIT,
×
540
                                 "Legacy cgroup v1 configured. This will stop being supported soon.\n"
541
                                 "Will proceed with cgroup v2 after 30 s.\n"
542
                                 "Set systemd.unified_cgroup_hierarchy=1 to switch to cgroup v2 "
543
                                 "or set SYSTEMD_CGROUP_ENABLE_LEGACY_FORCE=1 to reenable v1 temporarily.");
544
                        (void) usleep_safe(30 * USEC_PER_SEC);
×
545

546
                        return 0;
547
                }
548
        }
549

550
        if (!cg_is_legacy_wanted())
85✔
551
                return 0;
552

553
        FOREACH_ELEMENT(mp, cgroupv1_mount_table) {
×
554
                r = mount_one(mp, loaded_policy);
×
555
                if (r < 0)
×
556
                        return r;
557
        }
558

559
        if (loaded_policy)
×
560
                relabel_cgroup_legacy_hierarchy();
×
561

562
        /* Mount all available cgroup controllers that are built into the kernel. */
563
        r = cg_kernel_controllers(&controllers);
×
564
        if (r < 0)
×
565
                return log_error_errno(r, "Failed to enumerate cgroup controllers: %m");
×
566

567
        for (;;) {
×
568
                _cleanup_free_ char *options = NULL, *controller = NULL, *where = NULL;
×
569
                const char *other_controller;
×
570
                MountPoint p = {
×
571
                        .what = "cgroup",
572
                        .type = "cgroup",
573
                        .flags = MS_NOSUID|MS_NOEXEC|MS_NODEV,
574
                        .mode = MNT_IN_CONTAINER,
575
                };
576

577
                controller = set_steal_first(controllers);
×
578
                if (!controller)
×
579
                        break;
580

581
                /* Check if we shall mount this together with another controller */
582
                other_controller = join_with(controller);
×
583
                if (other_controller) {
×
584
                        _cleanup_free_ char *c = NULL;
×
585

586
                        /* Check if the other controller is actually available in the kernel too */
587
                        c = set_remove(controllers, other_controller);
×
588
                        if (c) {
×
589

590
                                /* Join the two controllers into one string, and maintain a stable ordering */
591
                                if (strcmp(controller, other_controller) < 0)
×
592
                                        options = strjoin(controller, ",", other_controller);
×
593
                                else
594
                                        options = strjoin(other_controller, ",", controller);
×
595
                                if (!options)
×
596
                                        return log_oom();
×
597
                        }
598
                }
599

600
                /* The simple case, where there's only one controller to mount together */
601
                if (!options)
×
602
                        options = TAKE_PTR(controller);
603

604
                where = path_join("/sys/fs/cgroup", options);
×
605
                if (!where)
×
606
                        return log_oom();
×
607

608
                p.where = where;
×
609
                p.options = options;
×
610

611
                r = mount_one(&p, true);
×
612
                if (r < 0)
×
613
                        return r;
614

615
                /* Create symlinks from the individual controller names, in case we have a joined mount */
616
                if (controller)
×
617
                        (void) symlink_controller(options, controller);
×
618
                if (other_controller)
×
619
                        (void) symlink_controller(options, other_controller);
×
620
        }
621

622
        /* Now that we mounted everything, let's make the tmpfs the cgroup file systems are mounted into read-only. */
623
        (void) mount_nofollow("tmpfs", "/sys/fs/cgroup", "tmpfs",
×
624
                              MS_REMOUNT|MS_NOSUID|MS_NOEXEC|MS_NODEV|MS_STRICTATIME|MS_RDONLY,
625
                              "mode=0755" TMPFS_LIMITS_SYS_FS_CGROUP);
626

627
        return 1;
628
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc