]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/cgroups/cgfsng.c
cgfsng: create_path_for_hierarchy()
[mirror_lxc.git] / src / lxc / cgroups / cgfsng.c
CommitLineData
ccb4cabe
SH
1/*
2 * lxc: linux Container library
3 *
4 * Copyright © 2016 Canonical Ltd.
5 *
6 * Authors:
7 * Serge Hallyn <serge.hallyn@ubuntu.com>
3fd0de4d 8 * Christian Brauner <christian.brauner@ubuntu.com>
ccb4cabe
SH
9 *
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
14 *
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23 */
24
25/*
26 * cgfs-ng.c: this is a new, simplified implementation of a filesystem
27 * cgroup backend. The original cgfs.c was designed to be as flexible
28 * as possible. It would try to find cgroup filesystems no matter where
29 * or how you had them mounted, and deduce the most usable mount for
0e7ff52c 30 * each controller.
ccb4cabe
SH
31 *
32 * This new implementation assumes that cgroup filesystems are mounted
33 * under /sys/fs/cgroup/clist where clist is either the controller, or
34 * a comman-separated list of controllers.
35 */
a54694f8 36
ccb4cabe 37#include "config.h"
a54694f8
CB
38
39#include <ctype.h>
40#include <dirent.h>
41#include <errno.h>
42#include <grp.h>
43#include <stdint.h>
ccb4cabe
SH
44#include <stdio.h>
45#include <stdlib.h>
a54694f8 46#include <string.h>
ccb4cabe 47#include <unistd.h>
c8bf519d 48#include <linux/kdev_t.h>
438c4581
CB
49#include <linux/types.h>
50#include <sys/types.h>
c8bf519d 51
b635e92d 52#include "caps.h"
ccb4cabe 53#include "cgroup.h"
6328fd9c 54#include "cgroup_utils.h"
ccb4cabe 55#include "commands.h"
43654d34 56#include "conf.h"
a54694f8 57#include "log.h"
43654d34 58#include "storage/storage.h"
a54694f8 59#include "utils.h"
ccb4cabe
SH
60
61lxc_log_define(lxc_cgfsng, lxc);
62
63static struct cgroup_ops cgfsng_ops;
64
9e288301 65/* A descriptor for a mounted hierarchy
16a2cde9
CB
66 *
67 * @controllers
68 * - legacy hierarchy
9e288301 69 * Either NULL, or a null-terminated list of all the co-mounted controllers.
16a2cde9 70 * - unified hierarchy
9e288301 71 * Either NULL, or a null-terminated list of all enabled controllers.
16a2cde9
CB
72 *
73 * @mountpoint
9e288301 74 * - The mountpoint we will use.
16a2cde9 75 * - legacy hierarchy
9e288301
CB
76 * It will be either /sys/fs/cgroup/controller or
77 * /sys/fs/cgroup/controllerlist.
16a2cde9 78 * - unified hierarchy
9e288301
CB
79 * It will either be /sys/fs/cgroup or /sys/fs/cgroup/<mountpoint-name>
80 * depending on whether this is a hybrid cgroup layout (mix of legacy and
81 * unified hierarchies) or a pure unified cgroup layout.
16a2cde9
CB
82 *
83 * @base_cgroup
9e288301
CB
84 * - The cgroup under which the container cgroup path
85 * is created. This will be either the caller's cgroup (if not root), or
86 * init's cgroup (if root).
16a2cde9
CB
87 *
88 * @fullcgpath
9e288301 89 * - The full path to the containers cgroup.
16a2cde9
CB
90 *
91 * @version
92 * - legacy hierarchy
9e288301
CB
93 * If the hierarchy is a legacy hierarchy this will be set to
94 * CGROUP_SUPER_MAGIC.
16a2cde9 95 * - unified hierarchy
9e288301
CB
96 * If the hierarchy is a legacy hierarchy this will be set to
97 * CGROUP2_SUPER_MAGIC.
ccb4cabe
SH
98 */
99struct hierarchy {
100 char **controllers;
101 char *mountpoint;
102 char *base_cgroup;
103 char *fullcgpath;
d6337a5f 104 int version;
ccb4cabe
SH
105};
106
16a2cde9
CB
107/* The cgroup data which is attached to the lxc_handler.
108 *
109 * @cgroup_pattern
110 * - A copy of lxc.cgroup.pattern.
111 *
112 * @container_cgroup
113 * - If not null, the cgroup which was created for the container. For each
114 * hierarchy, it is created under the @hierarchy->base_cgroup directory.
115 * Relative to the base_cgroup it is the same for all hierarchies.
116 *
117 * @name
118 * - The name of the container.
119 *
120 * @cgroup_meta
121 * - A copy of the container's cgroup information. This overrides
122 * @cgroup_pattern.
123 *
09f3bb13
CB
124 * @cgroup_layout
125 * - What cgroup layout the container is running with.
16a2cde9
CB
126 * - CGROUP_LAYOUT_UNKNOWN
127 * The cgroup layout could not be determined. This should be treated as an
128 * error condition.
129 * - CGROUP_LAYOUT_LEGACY
130 * The container is running with all controllers mounted into legacy cgroup
131 * hierarchies.
132 * - CGROUP_LAYOUT_HYBRID
133 * The container is running with at least one controller mounted into a
134 * legacy cgroup hierarchy and a mountpoint for the unified hierarchy. The
135 * unified hierarchy can be empty (no controllers enabled) or non-empty
136 * (controllers enabled).
137 * - CGROUP_LAYOUT_UNIFIED
138 * The container is running on a pure unified cgroup hierarchy. The unified
139 * hierarchy can be empty (no controllers enabled) or non-empty (controllers
140 * enabled).
ccb4cabe
SH
141 */
142struct cgfsng_handler_data {
ccb4cabe 143 char *cgroup_pattern;
1a0e70ac
CB
144 char *container_cgroup; /* cgroup we created for the container */
145 char *name; /* container name */
43654d34
CB
146 /* per-container cgroup information */
147 struct lxc_cgroup cgroup_meta;
d6337a5f 148 cgroup_layout_t cgroup_layout;
ccb4cabe
SH
149};
150
09f3bb13
CB
151/* @hierarchies
152 * - A NULL-terminated array of struct hierarchy, one per legacy hierarchy. No
153 * duplicates. First sufficient, writeable mounted hierarchy wins.
457ca9aa
SH
154 */
155struct hierarchy **hierarchies;
09f3bb13
CB
156/* Pointer to the unified hierarchy in the null terminated list @hierarchies.
157 * This is merely a convenience for hybrid cgroup layouts to easily retrieve the
158 * unified hierarchy without iterating throught @hierarchies.
159 */
d6337a5f 160struct hierarchy *unified;
457ca9aa 161/*
09f3bb13
CB
162 * @cgroup_layout
163 * - What cgroup layout the container is running with.
164 * - CGROUP_LAYOUT_UNKNOWN
165 * The cgroup layout could not be determined. This should be treated as an
166 * error condition.
167 * - CGROUP_LAYOUT_LEGACY
168 * The container is running with all controllers mounted into legacy cgroup
169 * hierarchies.
170 * - CGROUP_LAYOUT_HYBRID
171 * The container is running with at least one controller mounted into a
172 * legacy cgroup hierarchy and a mountpoint for the unified hierarchy. The
173 * unified hierarchy can be empty (no controllers enabled) or non-empty
174 * (controllers enabled).
175 * - CGROUP_LAYOUT_UNIFIED
176 * The container is running on a pure unified cgroup hierarchy. The unified
177 * hierarchy can be empty (no controllers enabled) or non-empty (controllers
178 * enabled).
457ca9aa 179 */
09f3bb13
CB
180cgroup_layout_t cgroup_layout;
181/* What controllers is the container supposed to use. */
457ca9aa
SH
182char *cgroup_use;
183
09f3bb13
CB
184/* @lxc_cgfsng_debug
185 * - Whether to print debug info to stdout for the cgfsng driver.
e4aeecf5
CB
186 */
187static bool lxc_cgfsng_debug;
188
09f3bb13
CB
189#define CGFSNG_DEBUG(format, ...) \
190 do { \
191 if (lxc_cgfsng_debug) \
192 printf("cgfsng: " format, ##__VA_ARGS__); \
193 } while (0)
65d78313 194
ccb4cabe
SH
195static void free_string_list(char **clist)
196{
2d5fe5ba 197 int i;
ccb4cabe 198
2d5fe5ba
CB
199 if (!clist)
200 return;
201
202 for (i = 0; clist[i]; i++)
203 free(clist[i]);
204
205 free(clist);
ccb4cabe
SH
206}
207
7745483d 208/* Allocate a pointer, do not fail. */
ccb4cabe
SH
209static void *must_alloc(size_t sz)
210{
211 return must_realloc(NULL, sz);
212}
213
8b8db2f6
CB
214/* Given a pointer to a null-terminated array of pointers, realloc to add one
215 * entry, and point the new entry to NULL. Do not fail. Return the index to the
216 * second-to-last entry - that is, the one which is now available for use
217 * (keeping the list null-terminated).
ccb4cabe
SH
218 */
219static int append_null_to_list(void ***list)
220{
221 int newentry = 0;
222
223 if (*list)
8b8db2f6
CB
224 for (; (*list)[newentry]; newentry++)
225 ;
ccb4cabe
SH
226
227 *list = must_realloc(*list, (newentry + 2) * sizeof(void **));
228 (*list)[newentry + 1] = NULL;
229 return newentry;
230}
231
8073018d
CB
232/* Given a null-terminated array of strings, check whether @entry is one of the
233 * strings.
ccb4cabe
SH
234 */
235static bool string_in_list(char **list, const char *entry)
236{
237 int i;
238
239 if (!list)
240 return false;
d6337a5f 241
ccb4cabe
SH
242 for (i = 0; list[i]; i++)
243 if (strcmp(list[i], entry) == 0)
244 return true;
245
246 return false;
247}
248
ac010944
CB
249/* Return a copy of @entry prepending "name=", i.e. turn "systemd" into
250 * "name=systemd". Do not fail.
251 */
252static char *cg_legacy_must_prefix_named(char *entry)
253{
254 size_t len;
255 char *prefixed;
256
257 len = strlen(entry);
258 prefixed = must_alloc(len + 6);
259
260 memcpy(prefixed, "name=", sizeof("name="));
261 memcpy(prefixed + sizeof("name="), entry, len);
262 prefixed[len + 5] = '\0';
263 return prefixed;
264}
265
42a993b4
CB
266/* Append an entry to the clist. Do not fail. @clist must be NULL the first time
267 * we are called.
ccb4cabe 268 *
42a993b4
CB
269 * We also handle named subsystems here. Any controller which is not a kernel
270 * subsystem, we prefix "name=". Any which is both a kernel and named subsystem,
271 * we refuse to use because we're not sure which we have here.
272 * (TODO: We could work around this in some cases by just remounting to be
273 * unambiguous, or by comparing mountpoint contents with current cgroup.)
ccb4cabe
SH
274 *
275 * The last entry will always be NULL.
276 */
42a993b4
CB
277static void must_append_controller(char **klist, char **nlist, char ***clist,
278 char *entry)
ccb4cabe
SH
279{
280 int newentry;
281 char *copy;
282
283 if (string_in_list(klist, entry) && string_in_list(nlist, entry)) {
c2712f64 284 ERROR("Refusing to use ambiguous controller \"%s\"", entry);
ccb4cabe
SH
285 ERROR("It is both a named and kernel subsystem");
286 return;
287 }
288
289 newentry = append_null_to_list((void ***)clist);
290
291 if (strncmp(entry, "name=", 5) == 0)
292 copy = must_copy_string(entry);
293 else if (string_in_list(klist, entry))
294 copy = must_copy_string(entry);
295 else
7745483d 296 copy = cg_legacy_must_prefix_named(entry);
ccb4cabe
SH
297
298 (*clist)[newentry] = copy;
299}
300
ccb4cabe
SH
301static void free_handler_data(struct cgfsng_handler_data *d)
302{
ccb4cabe
SH
303 free(d->cgroup_pattern);
304 free(d->container_cgroup);
305 free(d->name);
43654d34
CB
306 if (d->cgroup_meta.dir)
307 free(d->cgroup_meta.dir);
308 if (d->cgroup_meta.controllers)
309 free(d->cgroup_meta.controllers);
ccb4cabe
SH
310 free(d);
311}
312
5ae0207c
CB
313/* Given a handler's cgroup data, return the struct hierarchy for the controller
314 * @c, or NULL if there is none.
ccb4cabe 315 */
457ca9aa 316struct hierarchy *get_hierarchy(const char *c)
ccb4cabe
SH
317{
318 int i;
319
457ca9aa 320 if (!hierarchies)
ccb4cabe 321 return NULL;
d6337a5f 322
457ca9aa 323 for (i = 0; hierarchies[i]; i++) {
d6337a5f
CB
324 if (!c) {
325 /* This is the empty unified hierarchy. */
326 if (hierarchies[i]->controllers &&
327 !hierarchies[i]->controllers[0])
328 return hierarchies[i];
329
330 return NULL;
331 }
332
457ca9aa
SH
333 if (string_in_list(hierarchies[i]->controllers, c))
334 return hierarchies[i];
ccb4cabe 335 }
d6337a5f 336
ccb4cabe
SH
337 return NULL;
338}
339
a54694f8
CB
340#define BATCH_SIZE 50
341static void batch_realloc(char **mem, size_t oldlen, size_t newlen)
342{
343 int newbatches = (newlen / BATCH_SIZE) + 1;
344 int oldbatches = (oldlen / BATCH_SIZE) + 1;
345
346 if (!*mem || newbatches > oldbatches) {
347 *mem = must_realloc(*mem, newbatches * BATCH_SIZE);
348 }
349}
350
351static void append_line(char **dest, size_t oldlen, char *new, size_t newlen)
352{
353 size_t full = oldlen + newlen;
354
355 batch_realloc(dest, oldlen, full + 1);
356
357 memcpy(*dest + oldlen, new, newlen + 1);
358}
359
360/* Slurp in a whole file */
d6337a5f 361static char *read_file(const char *fnam)
a54694f8
CB
362{
363 FILE *f;
364 char *line = NULL, *buf = NULL;
365 size_t len = 0, fulllen = 0;
366 int linelen;
367
368 f = fopen(fnam, "r");
369 if (!f)
370 return NULL;
371 while ((linelen = getline(&line, &len, f)) != -1) {
372 append_line(&buf, fulllen, line, linelen);
373 fulllen += linelen;
374 }
375 fclose(f);
376 free(line);
377 return buf;
378}
379
380/* Taken over modified from the kernel sources. */
381#define NBITS 32 /* bits in uint32_t */
382#define DIV_ROUND_UP(n, d) (((n) + (d)-1) / (d))
383#define BITS_TO_LONGS(nr) DIV_ROUND_UP(nr, NBITS)
384
385static void set_bit(unsigned bit, uint32_t *bitarr)
386{
387 bitarr[bit / NBITS] |= (1 << (bit % NBITS));
388}
389
390static void clear_bit(unsigned bit, uint32_t *bitarr)
391{
392 bitarr[bit / NBITS] &= ~(1 << (bit % NBITS));
393}
394
395static bool is_set(unsigned bit, uint32_t *bitarr)
396{
397 return (bitarr[bit / NBITS] & (1 << (bit % NBITS))) != 0;
398}
399
400/* Create cpumask from cpulist aka turn:
401 *
402 * 0,2-3
403 *
d5d468f6 404 * into bit array
a54694f8
CB
405 *
406 * 1 0 1 1
407 */
408static uint32_t *lxc_cpumask(char *buf, size_t nbits)
409{
410 char *token;
d5d468f6
CB
411 size_t arrlen;
412 uint32_t *bitarr;
a54694f8 413 char *saveptr = NULL;
d5d468f6
CB
414
415 arrlen = BITS_TO_LONGS(nbits);
416 bitarr = calloc(arrlen, sizeof(uint32_t));
a54694f8
CB
417 if (!bitarr)
418 return NULL;
419
420 for (; (token = strtok_r(buf, ",", &saveptr)); buf = NULL) {
421 errno = 0;
d5d468f6
CB
422 unsigned end, start;
423 char *range;
a54694f8 424
d5d468f6
CB
425 start = strtoul(token, NULL, 0);
426 end = start;
427 range = strchr(token, '-');
a54694f8
CB
428 if (range)
429 end = strtoul(range + 1, NULL, 0);
d5d468f6 430
a54694f8
CB
431 if (!(start <= end)) {
432 free(bitarr);
433 return NULL;
434 }
435
436 if (end >= nbits) {
437 free(bitarr);
438 return NULL;
439 }
440
441 while (start <= end)
442 set_bit(start++, bitarr);
443 }
444
445 return bitarr;
446}
447
a54694f8
CB
448/* Turn cpumask into simple, comma-separated cpulist. */
449static char *lxc_cpumask_to_cpulist(uint32_t *bitarr, size_t nbits)
450{
a54694f8 451 int ret;
414c6719 452 size_t i;
a54694f8 453 char **cpulist = NULL;
414c6719 454 char numstr[LXC_NUMSTRLEN64] = {0};
a54694f8
CB
455
456 for (i = 0; i <= nbits; i++) {
414c6719
CB
457 if (!is_set(i, bitarr))
458 continue;
459
460 ret = snprintf(numstr, LXC_NUMSTRLEN64, "%zu", i);
461 if (ret < 0 || (size_t)ret >= LXC_NUMSTRLEN64) {
462 lxc_free_array((void **)cpulist, free);
463 return NULL;
464 }
465
466 ret = lxc_append_string(&cpulist, numstr);
467 if (ret < 0) {
468 lxc_free_array((void **)cpulist, free);
469 return NULL;
a54694f8
CB
470 }
471 }
414c6719
CB
472
473 if (!cpulist)
474 return NULL;
475
a54694f8
CB
476 return lxc_string_join(",", (const char **)cpulist, false);
477}
478
479static ssize_t get_max_cpus(char *cpulist)
480{
481 char *c1, *c2;
482 char *maxcpus = cpulist;
483 size_t cpus = 0;
484
485 c1 = strrchr(maxcpus, ',');
486 if (c1)
487 c1++;
488
489 c2 = strrchr(maxcpus, '-');
490 if (c2)
491 c2++;
492
493 if (!c1 && !c2)
494 c1 = maxcpus;
495 else if (c1 > c2)
496 c2 = c1;
497 else if (c1 < c2)
498 c1 = c2;
333987b9 499 else if (!c1 && c2)
a54694f8
CB
500 c1 = c2;
501
a54694f8
CB
502 errno = 0;
503 cpus = strtoul(c1, NULL, 0);
504 if (errno != 0)
505 return -1;
506
507 return cpus;
508}
509
6f9584d8 510#define __ISOL_CPUS "/sys/devices/system/cpu/isolated"
a3926f6a 511static bool cg_legacy_filter_and_set_cpus(char *path, bool am_initialized)
a54694f8 512{
a54694f8
CB
513 int ret;
514 ssize_t i;
59ac3b88
CB
515 char *lastslash, *fpath, oldv;
516 ssize_t maxisol = 0, maxposs = 0;
517 char *cpulist = NULL, *isolcpus = NULL, *posscpus = NULL;
518 uint32_t *isolmask = NULL, *possmask = NULL;
6f9584d8 519 bool bret = false, flipped_bit = false;
a54694f8
CB
520
521 lastslash = strrchr(path, '/');
59ac3b88
CB
522 if (!lastslash) {
523 ERROR("Failed to detect \"/\" in \"%s\"", path);
a54694f8
CB
524 return bret;
525 }
526 oldv = *lastslash;
527 *lastslash = '\0';
528 fpath = must_make_path(path, "cpuset.cpus", NULL);
529 posscpus = read_file(fpath);
6f9584d8 530 if (!posscpus) {
59ac3b88 531 SYSERROR("Failed to read file \"%s\"", fpath);
6f9584d8
CB
532 goto on_error;
533 }
a54694f8
CB
534
535 /* Get maximum number of cpus found in possible cpuset. */
536 maxposs = get_max_cpus(posscpus);
537 if (maxposs < 0)
6f9584d8 538 goto on_error;
a54694f8 539
6f9584d8
CB
540 if (!file_exists(__ISOL_CPUS)) {
541 /* This system doesn't expose isolated cpus. */
59ac3b88 542 DEBUG("The path \""__ISOL_CPUS"\" to read isolated cpus from does not exist");
65d29cbc
CB
543 cpulist = posscpus;
544 /* No isolated cpus but we weren't already initialized by
545 * someone. We should simply copy the parents cpuset.cpus
546 * values.
547 */
548 if (!am_initialized) {
59ac3b88 549 DEBUG("Copying cpu settings of parent cgroup");
65d29cbc
CB
550 goto copy_parent;
551 }
552 /* No isolated cpus but we were already initialized by someone.
553 * Nothing more to do for us.
554 */
6f9584d8
CB
555 goto on_success;
556 }
557
558 isolcpus = read_file(__ISOL_CPUS);
559 if (!isolcpus) {
59ac3b88 560 SYSERROR("Failed to read file \""__ISOL_CPUS"\"");
6f9584d8
CB
561 goto on_error;
562 }
a54694f8 563 if (!isdigit(isolcpus[0])) {
59ac3b88 564 TRACE("No isolated cpus detected");
a54694f8
CB
565 cpulist = posscpus;
566 /* No isolated cpus but we weren't already initialized by
567 * someone. We should simply copy the parents cpuset.cpus
568 * values.
569 */
6f9584d8 570 if (!am_initialized) {
59ac3b88 571 DEBUG("Copying cpu settings of parent cgroup");
a54694f8 572 goto copy_parent;
6f9584d8 573 }
a54694f8
CB
574 /* No isolated cpus but we were already initialized by someone.
575 * Nothing more to do for us.
576 */
6f9584d8 577 goto on_success;
a54694f8
CB
578 }
579
580 /* Get maximum number of cpus found in isolated cpuset. */
581 maxisol = get_max_cpus(isolcpus);
582 if (maxisol < 0)
6f9584d8 583 goto on_error;
a54694f8
CB
584
585 if (maxposs < maxisol)
586 maxposs = maxisol;
587 maxposs++;
588
589 possmask = lxc_cpumask(posscpus, maxposs);
6f9584d8 590 if (!possmask) {
59ac3b88 591 ERROR("Failed to create cpumask for possible cpus");
6f9584d8
CB
592 goto on_error;
593 }
a54694f8
CB
594
595 isolmask = lxc_cpumask(isolcpus, maxposs);
6f9584d8 596 if (!isolmask) {
59ac3b88 597 ERROR("Failed to create cpumask for isolated cpus");
6f9584d8
CB
598 goto on_error;
599 }
a54694f8
CB
600
601 for (i = 0; i <= maxposs; i++) {
59ac3b88
CB
602 if (!is_set(i, isolmask) || !is_set(i, possmask))
603 continue;
604
605 flipped_bit = true;
606 clear_bit(i, possmask);
a54694f8
CB
607 }
608
6f9584d8 609 if (!flipped_bit) {
59ac3b88 610 DEBUG("No isolated cpus present in cpuset");
6f9584d8
CB
611 goto on_success;
612 }
59ac3b88 613 DEBUG("Removed isolated cpus from cpuset");
6f9584d8 614
a54694f8 615 cpulist = lxc_cpumask_to_cpulist(possmask, maxposs);
6f9584d8 616 if (!cpulist) {
59ac3b88 617 ERROR("Failed to create cpu list");
6f9584d8
CB
618 goto on_error;
619 }
a54694f8
CB
620
621copy_parent:
622 *lastslash = oldv;
dcbc861e 623 free(fpath);
a54694f8
CB
624 fpath = must_make_path(path, "cpuset.cpus", NULL);
625 ret = lxc_write_to_file(fpath, cpulist, strlen(cpulist), false);
6f9584d8 626 if (ret < 0) {
59ac3b88 627 SYSERROR("Failed to write cpu list to \"%s\"", fpath);
6f9584d8
CB
628 goto on_error;
629 }
630
631on_success:
632 bret = true;
a54694f8 633
6f9584d8 634on_error:
a54694f8
CB
635 free(fpath);
636
637 free(isolcpus);
638 free(isolmask);
639
640 if (posscpus != cpulist)
641 free(posscpus);
642 free(possmask);
643
644 free(cpulist);
645 return bret;
646}
647
e3a3fecf
SH
648/* Copy contents of parent(@path)/@file to @path/@file */
649static bool copy_parent_file(char *path, char *file)
650{
e3a3fecf 651 int ret;
b095a8eb
CB
652 char *fpath, *lastslash, oldv;
653 int len = 0;
654 char *value = NULL;
e3a3fecf
SH
655
656 lastslash = strrchr(path, '/');
b095a8eb
CB
657 if (!lastslash) {
658 ERROR("Failed to detect \"/\" in \"%s\"", path);
e3a3fecf
SH
659 return false;
660 }
661 oldv = *lastslash;
662 *lastslash = '\0';
663 fpath = must_make_path(path, file, NULL);
664 len = lxc_read_from_file(fpath, NULL, 0);
665 if (len <= 0)
b095a8eb
CB
666 goto on_error;
667
e3a3fecf 668 value = must_alloc(len + 1);
b095a8eb
CB
669 ret = lxc_read_from_file(fpath, value, len);
670 if (ret != len)
671 goto on_error;
e3a3fecf 672 free(fpath);
b095a8eb 673
e3a3fecf
SH
674 *lastslash = oldv;
675 fpath = must_make_path(path, file, NULL);
676 ret = lxc_write_to_file(fpath, value, len, false);
677 if (ret < 0)
b095a8eb 678 SYSERROR("Failed to write \"%s\" to file \"%s\"", value, fpath);
e3a3fecf
SH
679 free(fpath);
680 free(value);
681 return ret >= 0;
682
b095a8eb
CB
683on_error:
684 SYSERROR("Failed to read file \"%s\"", fpath);
e3a3fecf
SH
685 free(fpath);
686 free(value);
687 return false;
688}
689
7793add3
CB
690/* Initialize the cpuset hierarchy in first directory of @gname and set
691 * cgroup.clone_children so that children inherit settings. Since the
692 * h->base_path is populated by init or ourselves, we know it is already
693 * initialized.
e3a3fecf 694 */
a3926f6a 695static bool cg_legacy_handle_cpuset_hierarchy(struct hierarchy *h, char *cgname)
e3a3fecf 696{
7793add3
CB
697 int ret;
698 char v;
699 char *cgpath, *clonechildrenpath, *slash;
e3a3fecf
SH
700
701 if (!string_in_list(h->controllers, "cpuset"))
702 return true;
703
704 if (*cgname == '/')
705 cgname++;
706 slash = strchr(cgname, '/');
707 if (slash)
708 *slash = '\0';
709
710 cgpath = must_make_path(h->mountpoint, h->base_cgroup, cgname, NULL);
711 if (slash)
712 *slash = '/';
7793add3
CB
713
714 ret = mkdir(cgpath, 0755);
715 if (ret < 0) {
716 if (errno != EEXIST) {
717 SYSERROR("Failed to create directory \"%s\"", cgpath);
718 free(cgpath);
719 return false;
720 }
e3a3fecf 721 }
6f9584d8 722
7793add3
CB
723 clonechildrenpath =
724 must_make_path(cgpath, "cgroup.clone_children", NULL);
6328fd9c
CB
725 /* unified hierarchy doesn't have clone_children */
726 if (!file_exists(clonechildrenpath)) {
e3a3fecf
SH
727 free(clonechildrenpath);
728 free(cgpath);
729 return true;
730 }
7793add3
CB
731
732 ret = lxc_read_from_file(clonechildrenpath, &v, 1);
733 if (ret < 0) {
734 SYSERROR("Failed to read file \"%s\"", clonechildrenpath);
e3a3fecf
SH
735 free(clonechildrenpath);
736 free(cgpath);
737 return false;
738 }
739
a54694f8 740 /* Make sure any isolated cpus are removed from cpuset.cpus. */
a3926f6a 741 if (!cg_legacy_filter_and_set_cpus(cgpath, v == '1')) {
7793add3 742 SYSERROR("Failed to remove isolated cpus");
6f9584d8
CB
743 free(clonechildrenpath);
744 free(cgpath);
a54694f8 745 return false;
6f9584d8 746 }
a54694f8 747
7793add3
CB
748 /* Already set for us by someone else. */
749 if (v == '1') {
750 DEBUG("\"cgroup.clone_children\" was already set to \"1\"");
e3a3fecf
SH
751 free(clonechildrenpath);
752 free(cgpath);
753 return true;
754 }
755
756 /* copy parent's settings */
a54694f8 757 if (!copy_parent_file(cgpath, "cpuset.mems")) {
7793add3 758 SYSERROR("Failed to copy \"cpuset.mems\" settings");
e3a3fecf
SH
759 free(cgpath);
760 free(clonechildrenpath);
761 return false;
762 }
763 free(cgpath);
764
7793add3
CB
765 ret = lxc_write_to_file(clonechildrenpath, "1", 1, false);
766 if (ret < 0) {
e3a3fecf 767 /* Set clone_children so children inherit our settings */
7793add3 768 SYSERROR("Failed to write 1 to \"%s\"", clonechildrenpath);
e3a3fecf
SH
769 free(clonechildrenpath);
770 return false;
771 }
772 free(clonechildrenpath);
773 return true;
774}
775
5c0089ae
CB
776/* Given two null-terminated lists of strings, return true if any string is in
777 * both.
ccb4cabe
SH
778 */
779static bool controller_lists_intersect(char **l1, char **l2)
780{
781 int i;
782
783 if (!l1 || !l2)
784 return false;
785
786 for (i = 0; l1[i]; i++) {
787 if (string_in_list(l2, l1[i]))
788 return true;
789 }
5c0089ae 790
ccb4cabe
SH
791 return false;
792}
793
258449e5
CB
794/* For a null-terminated list of controllers @clist, return true if any of those
795 * controllers is already listed the null-terminated list of hierarchies @hlist.
796 * Realistically, if one is present, all must be present.
ccb4cabe
SH
797 */
798static bool controller_list_is_dup(struct hierarchy **hlist, char **clist)
799{
800 int i;
801
802 if (!hlist)
803 return false;
258449e5 804
ccb4cabe
SH
805 for (i = 0; hlist[i]; i++)
806 if (controller_lists_intersect(hlist[i]->controllers, clist))
807 return true;
ccb4cabe 808
258449e5 809 return false;
ccb4cabe
SH
810}
811
f57ac67f
CB
812/* Return true if the controller @entry is found in the null-terminated list of
813 * hierarchies @hlist.
ccb4cabe
SH
814 */
815static bool controller_found(struct hierarchy **hlist, char *entry)
816{
817 int i;
d6337a5f 818
ccb4cabe
SH
819 if (!hlist)
820 return false;
821
822 for (i = 0; hlist[i]; i++)
823 if (string_in_list(hlist[i]->controllers, entry))
824 return true;
d6337a5f 825
ccb4cabe
SH
826 return false;
827}
828
e1c27ab0
CB
829/* Return true if all of the controllers which we require have been found. The
830 * required list is freezer and anything in lxc.cgroup.use.
ccb4cabe 831 */
457ca9aa 832static bool all_controllers_found(void)
ccb4cabe 833{
e1c27ab0
CB
834 char *p;
835 char *saveptr = NULL;
836 struct hierarchy **hlist = hierarchies;
ccb4cabe 837
ccb4cabe 838 if (!controller_found(hlist, "freezer")) {
65d78313 839 CGFSNG_DEBUG("No freezer controller mountpoint found\n");
ccb4cabe
SH
840 return false;
841 }
842
457ca9aa 843 if (!cgroup_use)
ccb4cabe 844 return true;
c2712f64 845
457ca9aa 846 for (p = strtok_r(cgroup_use, ",", &saveptr); p;
e1c27ab0 847 p = strtok_r(NULL, ",", &saveptr)) {
ccb4cabe 848 if (!controller_found(hlist, p)) {
65d78313 849 CGFSNG_DEBUG("No %s controller mountpoint found\n", p);
ccb4cabe
SH
850 return false;
851 }
852 }
c2712f64 853
ccb4cabe
SH
854 return true;
855}
856
f205f10c
CB
857/* Get the controllers from a mountinfo line There are other ways we could get
858 * this info. For lxcfs, field 3 is /cgroup/controller-list. For cgroupfs, we
859 * could parse the mount options. But we simply assume that the mountpoint must
860 * be /sys/fs/cgroup/controller-list
ccb4cabe 861 */
a3926f6a
CB
862static char **cg_hybrid_get_controllers(char **klist, char **nlist, char *line,
863 int type)
ccb4cabe 864{
f205f10c
CB
865 /* The fourth field is /sys/fs/cgroup/comma-delimited-controller-list
866 * for legacy hierarchies.
867 */
ccb4cabe 868 int i;
411ac6d8 869 char *dup, *p2, *tok;
d6337a5f 870 char *p = line, *saveptr = NULL, *sep = ",";
411ac6d8 871 char **aret = NULL;
6328fd9c 872
ccb4cabe 873 for (i = 0; i < 4; i++) {
235f1815 874 p = strchr(p, ' ');
ccb4cabe
SH
875 if (!p)
876 return NULL;
877 p++;
878 }
a55f31bd 879
f205f10c
CB
880 /* Note, if we change how mountinfo works, then our caller will need to
881 * verify /sys/fs/cgroup/ in this field.
882 */
883 if (strncmp(p, "/sys/fs/cgroup/", 15) != 0) {
65d78313 884 CGFSNG_DEBUG("Found hierarchy not under /sys/fs/cgroup: \"%s\"\n", p);
ccb4cabe 885 return NULL;
5059aae9 886 }
d6337a5f 887
ccb4cabe 888 p += 15;
235f1815 889 p2 = strchr(p, ' ');
ccb4cabe 890 if (!p2) {
65d78313 891 CGFSNG_DEBUG("Corrupt mountinfo\n");
ccb4cabe
SH
892 return NULL;
893 }
894 *p2 = '\0';
6328fd9c 895
d6337a5f
CB
896 if (type == CGROUP_SUPER_MAGIC) {
897 /* strdup() here for v1 hierarchies. Otherwise strtok_r() will
898 * destroy mountpoints such as "/sys/fs/cgroup/cpu,cpuacct".
899 */
900 dup = strdup(p);
901 if (!dup)
902 return NULL;
903
904 for (tok = strtok_r(dup, sep, &saveptr); tok;
905 tok = strtok_r(NULL, sep, &saveptr))
906 must_append_controller(klist, nlist, &aret, tok);
907
908 free(dup);
411ac6d8 909 }
d6337a5f 910 *p2 = ' ';
f205f10c 911
d6337a5f
CB
912 return aret;
913}
411ac6d8 914
d6337a5f
CB
915static char **cg_unified_make_empty_controller(void)
916{
917 int newentry;
918 char **aret = NULL;
919
920 newentry = append_null_to_list((void ***)&aret);
921 aret[newentry] = NULL;
922 return aret;
923}
924
925static char **cg_unified_get_controllers(const char *file)
926{
927 char *buf, *tok;
928 char *saveptr = NULL, *sep = " \t\n";
929 char **aret = NULL;
930
931 buf = read_file(file);
932 if (!buf)
411ac6d8 933 return NULL;
6328fd9c 934
d6337a5f
CB
935 for (tok = strtok_r(buf, sep, &saveptr); tok;
936 tok = strtok_r(NULL, sep, &saveptr)) {
937 int newentry;
938 char *copy;
939
940 newentry = append_null_to_list((void ***)&aret);
941 copy = must_copy_string(tok);
942 aret[newentry] = copy;
ccb4cabe
SH
943 }
944
d6337a5f 945 free(buf);
ccb4cabe
SH
946 return aret;
947}
948
d6337a5f
CB
949static struct hierarchy *add_hierarchy(char **clist, char *mountpoint,
950 char *base_cgroup, int type)
ccb4cabe
SH
951{
952 struct hierarchy *new;
953 int newentry;
954
955 new = must_alloc(sizeof(*new));
956 new->controllers = clist;
957 new->mountpoint = mountpoint;
958 new->base_cgroup = base_cgroup;
959 new->fullcgpath = NULL;
d6337a5f 960 new->version = type;
6328fd9c 961
457ca9aa
SH
962 newentry = append_null_to_list((void ***)&hierarchies);
963 hierarchies[newentry] = new;
d6337a5f 964 return new;
ccb4cabe
SH
965}
966
798c3b33
CB
967/* Get a copy of the mountpoint from @line, which is a line from
968 * /proc/self/mountinfo.
ccb4cabe 969 */
a3926f6a 970static char *cg_hybrid_get_mountpoint(char *line)
ccb4cabe
SH
971{
972 int i;
ccb4cabe 973 size_t len;
798c3b33
CB
974 char *p2;
975 char *p = line, *sret = NULL;
ccb4cabe
SH
976
977 for (i = 0; i < 4; i++) {
235f1815 978 p = strchr(p, ' ');
ccb4cabe
SH
979 if (!p)
980 return NULL;
981 p++;
982 }
d6337a5f 983
798c3b33 984 if (strncmp(p, "/sys/fs/cgroup/", 15) != 0)
d6337a5f
CB
985 return NULL;
986
987 p2 = strchr(p + 15, ' ');
988 if (!p2)
989 return NULL;
990 *p2 = '\0';
991
ccb4cabe
SH
992 len = strlen(p);
993 sret = must_alloc(len + 1);
994 memcpy(sret, p, len);
995 sret[len] = '\0';
996 return sret;
997}
998
f523291e 999/* Given a multi-line string, return a null-terminated copy of the current line. */
ccb4cabe
SH
1000static char *copy_to_eol(char *p)
1001{
235f1815 1002 char *p2 = strchr(p, '\n'), *sret;
ccb4cabe
SH
1003 size_t len;
1004
1005 if (!p2)
1006 return NULL;
1007
1008 len = p2 - p;
1009 sret = must_alloc(len + 1);
1010 memcpy(sret, p, len);
1011 sret[len] = '\0';
1012 return sret;
1013}
1014
bced39de
CB
1015/* cgline: pointer to character after the first ':' in a line in a \n-terminated
1016 * /proc/self/cgroup file. Check whether controller c is present.
ccb4cabe
SH
1017 */
1018static bool controller_in_clist(char *cgline, char *c)
1019{
1020 char *tok, *saveptr = NULL, *eol, *tmp;
1021 size_t len;
1022
235f1815 1023 eol = strchr(cgline, ':');
ccb4cabe
SH
1024 if (!eol)
1025 return false;
1026
1027 len = eol - cgline;
1028 tmp = alloca(len + 1);
1029 memcpy(tmp, cgline, len);
1030 tmp[len] = '\0';
1031
1032 for (tok = strtok_r(tmp, ",", &saveptr); tok;
d6337a5f 1033 tok = strtok_r(NULL, ",", &saveptr)) {
ccb4cabe
SH
1034 if (strcmp(tok, c) == 0)
1035 return true;
1036 }
d6337a5f 1037
ccb4cabe
SH
1038 return false;
1039}
1040
c3ef912e
CB
1041/* @basecginfo is a copy of /proc/$$/cgroup. Return the current cgroup for
1042 * @controller.
ccb4cabe 1043 */
c3ef912e
CB
1044static char *cg_hybrid_get_current_cgroup(char *basecginfo, char *controller,
1045 int type)
ccb4cabe
SH
1046{
1047 char *p = basecginfo;
6328fd9c 1048
d6337a5f
CB
1049 for (;;) {
1050 bool is_cgv2_base_cgroup = false;
1051
6328fd9c 1052 /* cgroup v2 entry in "/proc/<pid>/cgroup": "0::/some/path" */
d6337a5f
CB
1053 if ((type == CGROUP2_SUPER_MAGIC) && (*p == '0'))
1054 is_cgv2_base_cgroup = true;
ccb4cabe 1055
235f1815 1056 p = strchr(p, ':');
ccb4cabe
SH
1057 if (!p)
1058 return NULL;
1059 p++;
d6337a5f
CB
1060
1061 if (is_cgv2_base_cgroup || (controller && controller_in_clist(p, controller))) {
235f1815 1062 p = strchr(p, ':');
ccb4cabe
SH
1063 if (!p)
1064 return NULL;
1065 p++;
1066 return copy_to_eol(p);
1067 }
1068
235f1815 1069 p = strchr(p, '\n');
ccb4cabe
SH
1070 if (!p)
1071 return NULL;
1072 p++;
1073 }
1074}
1075
ccb4cabe
SH
1076static void must_append_string(char ***list, char *entry)
1077{
6dfb18bf 1078 int newentry;
ccb4cabe
SH
1079 char *copy;
1080
6dfb18bf 1081 newentry = append_null_to_list((void ***)list);
ccb4cabe
SH
1082 copy = must_copy_string(entry);
1083 (*list)[newentry] = copy;
1084}
1085
d6337a5f 1086static int get_existing_subsystems(char ***klist, char ***nlist)
ccb4cabe
SH
1087{
1088 FILE *f;
1089 char *line = NULL;
1090 size_t len = 0;
1091
d6337a5f
CB
1092 f = fopen("/proc/self/cgroup", "r");
1093 if (!f)
1094 return -1;
1095
ccb4cabe
SH
1096 while (getline(&line, &len, f) != -1) {
1097 char *p, *p2, *tok, *saveptr = NULL;
235f1815 1098 p = strchr(line, ':');
ccb4cabe
SH
1099 if (!p)
1100 continue;
1101 p++;
235f1815 1102 p2 = strchr(p, ':');
ccb4cabe
SH
1103 if (!p2)
1104 continue;
1105 *p2 = '\0';
ff8d6ee9 1106
6328fd9c
CB
1107 /* If the kernel has cgroup v2 support, then /proc/self/cgroup
1108 * contains an entry of the form:
ff8d6ee9
CB
1109 *
1110 * 0::/some/path
1111 *
6328fd9c 1112 * In this case we use "cgroup2" as controller name.
ff8d6ee9 1113 */
6328fd9c
CB
1114 if ((p2 - p) == 0) {
1115 must_append_string(klist, "cgroup2");
ff8d6ee9 1116 continue;
6328fd9c 1117 }
ff8d6ee9 1118
ccb4cabe 1119 for (tok = strtok_r(p, ",", &saveptr); tok;
d6337a5f 1120 tok = strtok_r(NULL, ",", &saveptr)) {
ccb4cabe
SH
1121 if (strncmp(tok, "name=", 5) == 0)
1122 must_append_string(nlist, tok);
1123 else
1124 must_append_string(klist, tok);
1125 }
1126 }
1127
1128 free(line);
1129 fclose(f);
d6337a5f 1130 return 0;
ccb4cabe
SH
1131}
1132
1133static void trim(char *s)
1134{
7689dfd7
CB
1135 size_t len;
1136
1137 len = strlen(s);
2c28d76b 1138 while ((len > 1) && (s[len - 1] == '\n'))
ccb4cabe
SH
1139 s[--len] = '\0';
1140}
1141
e4aeecf5
CB
1142static void lxc_cgfsng_print_handler_data(const struct cgfsng_handler_data *d)
1143{
1144 printf("Cgroup information:\n");
1145 printf(" container name: %s\n", d->name ? d->name : "(null)");
1146 printf(" lxc.cgroup.use: %s\n", cgroup_use ? cgroup_use : "(null)");
43654d34
CB
1147 printf(" lxc.cgroup.pattern: %s\n",
1148 d->cgroup_pattern ? d->cgroup_pattern : "(null)");
1149 printf(" lxc.cgroup.dir: %s\n",
1150 d->cgroup_meta.dir ? d->cgroup_meta.dir : "(null)");
1151 printf(" cgroup: %s\n",
1152 d->container_cgroup ? d->container_cgroup : "(null)");
e4aeecf5
CB
1153}
1154
1155static void lxc_cgfsng_print_hierarchies()
ccb4cabe
SH
1156{
1157 int i;
27d84737 1158 struct hierarchy **it;
41c33dbe 1159
457ca9aa 1160 if (!hierarchies) {
c2712f64 1161 printf(" No hierarchies found\n");
ccb4cabe
SH
1162 return;
1163 }
27d84737 1164
e4aeecf5 1165 printf(" Hierarchies:\n");
a7b0cc4c 1166 for (i = 0, it = hierarchies; it && *it; it++, i++) {
ccb4cabe 1167 int j;
27d84737
CB
1168 char **cit;
1169
c2712f64
CB
1170 printf(" %d: base_cgroup: %s\n", i, (*it)->base_cgroup ? (*it)->base_cgroup : "(null)");
1171 printf(" mountpoint: %s\n", (*it)->mountpoint ? (*it)->mountpoint : "(null)");
e4aeecf5 1172 printf(" controllers:\n");
a7b0cc4c 1173 for (j = 0, cit = (*it)->controllers; cit && *cit; cit++, j++)
e4aeecf5 1174 printf(" %d: %s\n", j, *cit);
ccb4cabe
SH
1175 }
1176}
41c33dbe 1177
a3926f6a
CB
1178static void lxc_cgfsng_print_basecg_debuginfo(char *basecginfo, char **klist,
1179 char **nlist)
41c33dbe
SH
1180{
1181 int k;
a7b0cc4c 1182 char **it;
41c33dbe 1183
a7b0cc4c
CB
1184 printf("basecginfo is:\n");
1185 printf("%s\n", basecginfo);
41c33dbe 1186
a7b0cc4c
CB
1187 for (k = 0, it = klist; it && *it; it++, k++)
1188 printf("kernel subsystem %d: %s\n", k, *it);
0f71dd9b 1189
a7b0cc4c
CB
1190 for (k = 0, it = nlist; it && *it; it++, k++)
1191 printf("named subsystem %d: %s\n", k, *it);
41c33dbe 1192}
ccb4cabe 1193
e4aeecf5
CB
1194static void lxc_cgfsng_print_debuginfo(const struct cgfsng_handler_data *d)
1195{
1196 lxc_cgfsng_print_handler_data(d);
1197 lxc_cgfsng_print_hierarchies();
1198}
1199
96e6f37f
CB
1200/* At startup, parse_hierarchies finds all the info we need about cgroup
1201 * mountpoints and current cgroups, and stores it in @d.
ccb4cabe 1202 */
a3926f6a 1203static bool cg_hybrid_init(void)
ccb4cabe 1204{
d6337a5f
CB
1205 int ret;
1206 char *basecginfo;
1207 bool will_escape;
ccb4cabe 1208 FILE *f;
ccb4cabe 1209 size_t len = 0;
d6337a5f
CB
1210 char *line = NULL;
1211 char **klist = NULL, **nlist = NULL;
ccb4cabe 1212
96e6f37f 1213 /* Root spawned containers escape the current cgroup, so use init's
d30ec4cb
SH
1214 * cgroups as our base in that case.
1215 */
d6337a5f
CB
1216 will_escape = (geteuid() == 0);
1217 if (will_escape)
ccb4cabe 1218 basecginfo = read_file("/proc/1/cgroup");
d6337a5f
CB
1219 else
1220 basecginfo = read_file("/proc/self/cgroup");
ccb4cabe
SH
1221 if (!basecginfo)
1222 return false;
1223
d6337a5f
CB
1224 ret = get_existing_subsystems(&klist, &nlist);
1225 if (ret < 0) {
96e6f37f 1226 CGFSNG_DEBUG("Failed to retrieve available legacy cgroup controllers\n");
d6337a5f 1227 free(basecginfo);
ccb4cabe
SH
1228 return false;
1229 }
1230
d6337a5f
CB
1231 f = fopen("/proc/self/mountinfo", "r");
1232 if (!f) {
1233 CGFSNG_DEBUG("Failed to open \"/proc/self/mountinfo\"\n");
bd01b7d5 1234 free(basecginfo);
d6337a5f
CB
1235 return false;
1236 }
41c33dbe 1237
e4aeecf5
CB
1238 if (lxc_cgfsng_debug)
1239 lxc_cgfsng_print_basecg_debuginfo(basecginfo, klist, nlist);
ccb4cabe 1240
ccb4cabe 1241 while (getline(&line, &len, f) != -1) {
49ff3958 1242 int type;
d6337a5f
CB
1243 bool writeable;
1244 struct hierarchy *new;
96e6f37f 1245 char *base_cgroup = NULL, *mountpoint = NULL;
d6337a5f 1246 char **controller_list = NULL;
ccb4cabe 1247
49ff3958 1248 type = get_cgroup_version(line);
d6337a5f 1249 if (type == 0)
ccb4cabe
SH
1250 continue;
1251
d6337a5f 1252 if (type == CGROUP2_SUPER_MAGIC && unified)
ccb4cabe
SH
1253 continue;
1254
d6337a5f
CB
1255 if (cgroup_layout == CGROUP_LAYOUT_UNKNOWN) {
1256 if (type == CGROUP2_SUPER_MAGIC)
1257 cgroup_layout = CGROUP_LAYOUT_UNIFIED;
1258 else if (type == CGROUP_SUPER_MAGIC)
1259 cgroup_layout = CGROUP_LAYOUT_LEGACY;
1260 } else if (cgroup_layout == CGROUP_LAYOUT_UNIFIED) {
1261 if (type == CGROUP_SUPER_MAGIC)
1262 cgroup_layout = CGROUP_LAYOUT_HYBRID;
1263 } else if (cgroup_layout == CGROUP_LAYOUT_LEGACY) {
1264 if (type == CGROUP2_SUPER_MAGIC)
1265 cgroup_layout = CGROUP_LAYOUT_HYBRID;
ccb4cabe
SH
1266 }
1267
a3926f6a 1268 controller_list = cg_hybrid_get_controllers(klist, nlist, line, type);
d6337a5f
CB
1269 if (!controller_list && type == CGROUP_SUPER_MAGIC)
1270 continue;
1271
1272 if (type == CGROUP_SUPER_MAGIC)
1273 if (controller_list_is_dup(hierarchies, controller_list))
1274 goto next;
1275
a3926f6a 1276 mountpoint = cg_hybrid_get_mountpoint(line);
ccb4cabe 1277 if (!mountpoint) {
65d78313 1278 CGFSNG_DEBUG("Failed parsing mountpoint from \"%s\"\n", line);
d6337a5f 1279 goto next;
ccb4cabe
SH
1280 }
1281
d6337a5f 1282 if (type == CGROUP_SUPER_MAGIC)
a3926f6a 1283 base_cgroup = cg_hybrid_get_current_cgroup(basecginfo, controller_list[0], CGROUP_SUPER_MAGIC);
d6337a5f 1284 else
a3926f6a 1285 base_cgroup = cg_hybrid_get_current_cgroup(basecginfo, NULL, CGROUP2_SUPER_MAGIC);
ccb4cabe 1286 if (!base_cgroup) {
d6337a5f
CB
1287 CGFSNG_DEBUG("Failed to find current cgroup\n");
1288 goto next;
ccb4cabe 1289 }
6328fd9c 1290
ccb4cabe
SH
1291 trim(base_cgroup);
1292 prune_init_scope(base_cgroup);
d6337a5f 1293 if (type == CGROUP2_SUPER_MAGIC)
6328fd9c
CB
1294 writeable = test_writeable_v2(mountpoint, base_cgroup);
1295 else
1296 writeable = test_writeable_v1(mountpoint, base_cgroup);
d6337a5f
CB
1297 if (!writeable)
1298 goto next;
1299
1300 if (type == CGROUP2_SUPER_MAGIC) {
1301 char *cgv2_ctrl_path;
1302
1303 cgv2_ctrl_path = must_make_path(mountpoint, base_cgroup,
1304 "cgroup.controllers",
1305 NULL);
1306
1307 controller_list = cg_unified_get_controllers(cgv2_ctrl_path);
1308 free(cgv2_ctrl_path);
1309 if (!controller_list)
1310 controller_list = cg_unified_make_empty_controller();
ccb4cabe 1311 }
96e6f37f 1312
d6337a5f
CB
1313 new = add_hierarchy(controller_list, mountpoint, base_cgroup, type);
1314 if (type == CGROUP2_SUPER_MAGIC && !unified)
1315 unified = new;
1316
1317 continue;
1318
1319 next:
1320 free_string_list(controller_list);
1321 free(mountpoint);
1322 free(base_cgroup);
ccb4cabe
SH
1323 }
1324
1325 free_string_list(klist);
1326 free_string_list(nlist);
1327
1328 free(basecginfo);
1329
1330 fclose(f);
1331 free(line);
1332
e4aeecf5 1333 if (lxc_cgfsng_debug) {
96e6f37f 1334 printf("Writable cgroup hierarchies:\n");
e4aeecf5
CB
1335 lxc_cgfsng_print_hierarchies();
1336 }
1337
ccb4cabe
SH
1338 /* verify that all controllers in cgroup.use and all crucial
1339 * controllers are accounted for
1340 */
c2712f64 1341 if (!all_controllers_found())
ccb4cabe
SH
1342 return false;
1343
1344 return true;
1345}
1346
c71d83e1
CB
1347static int cg_is_pure_unified(void)
1348{
d6337a5f
CB
1349
1350 int ret;
c71d83e1 1351 struct statfs fs;
d6337a5f 1352
c71d83e1
CB
1353 ret = statfs("/sys/fs/cgroup", &fs);
1354 if (ret < 0)
1355 return -ENOMEDIUM;
d6337a5f 1356
c71d83e1 1357 if (is_fs_type(&fs, CGROUP2_SUPER_MAGIC))
d6337a5f
CB
1358 return CGROUP2_SUPER_MAGIC;
1359
c71d83e1 1360 return 0;
d6337a5f
CB
1361}
1362
1363/* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
a3926f6a 1364static char *cg_unified_get_current_cgroup(void)
457ca9aa 1365{
165dc510 1366 char *basecginfo, *base_cgroup;
d6337a5f
CB
1367 bool will_escape;
1368 char *copy = NULL;
1369
1370 will_escape = (geteuid() == 0);
1371 if (will_escape)
1372 basecginfo = read_file("/proc/1/cgroup");
1373 else
1374 basecginfo = read_file("/proc/self/cgroup");
1375 if (!basecginfo)
1376 return NULL;
1377
1378 base_cgroup = strstr(basecginfo, "0::/");
1379 if (!base_cgroup)
1380 goto cleanup_on_err;
1381
1382 base_cgroup = base_cgroup + 3;
1383 copy = copy_to_eol(base_cgroup);
1384 if (!copy)
1385 goto cleanup_on_err;
1386
1387cleanup_on_err:
1388 free(basecginfo);
1389 if (copy)
1390 trim(copy);
1391
1392 return copy;
1393}
1394
a3926f6a 1395static int cg_unified_init(void)
d6337a5f
CB
1396{
1397 int ret;
1398 char *mountpoint, *subtree_path;
1399 char **delegatable;
1400 char *base_cgroup = NULL;
1401
1402 ret = cg_is_pure_unified();
1403 if (ret == -ENOMEDIUM)
1404 return -ENOMEDIUM;
1405
1406 if (ret != CGROUP2_SUPER_MAGIC)
1407 return 0;
1408
a3926f6a 1409 base_cgroup = cg_unified_get_current_cgroup();
d6337a5f
CB
1410 if (!base_cgroup)
1411 return -EINVAL;
1412 prune_init_scope(base_cgroup);
1413
1414 /* We assume that we have already been given controllers to delegate
1415 * further down the hierarchy. If not it is up to the user to delegate
1416 * them to us.
1417 */
1418 mountpoint = must_copy_string("/sys/fs/cgroup");
1419 subtree_path = must_make_path(mountpoint, base_cgroup,
1420 "cgroup.subtree_control", NULL);
1421 delegatable = cg_unified_get_controllers(subtree_path);
1422 free(subtree_path);
1423 if (!delegatable)
1424 delegatable = cg_unified_make_empty_controller();
1425 if (!delegatable[0])
1426 CGFSNG_DEBUG("No controllers are enabled for delegation\n");
1427
1428 /* TODO: If the user requested specific controllers via lxc.cgroup.use
1429 * we should verify here. The reason I'm not doing it right is that I'm
1430 * not convinced that lxc.cgroup.use will be the future since it is a
1431 * global property. I much rather have an option that lets you request
1432 * controllers per container.
1433 */
1434
1435 add_hierarchy(delegatable, mountpoint, base_cgroup, CGROUP2_SUPER_MAGIC);
1436 unified = hierarchies[0];
1437
1438 cgroup_layout = CGROUP_LAYOUT_UNIFIED;
1439 return CGROUP2_SUPER_MAGIC;
1440}
1441
1442static bool cg_init(void)
1443{
1444 int ret;
457ca9aa 1445 const char *tmp;
d6337a5f 1446
457ca9aa
SH
1447 errno = 0;
1448 tmp = lxc_global_config_value("lxc.cgroup.use");
1a0e70ac 1449 if (!cgroup_use && errno != 0) { /* lxc.cgroup.use can be NULL */
65d78313 1450 CGFSNG_DEBUG("Failed to retrieve list of cgroups to use\n");
457ca9aa
SH
1451 return false;
1452 }
1453 cgroup_use = must_copy_string(tmp);
1454
a3926f6a 1455 ret = cg_unified_init();
d6337a5f
CB
1456 if (ret < 0)
1457 return false;
1458
1459 if (ret == CGROUP2_SUPER_MAGIC)
1460 return true;
1461
a3926f6a 1462 return cg_hybrid_init();
457ca9aa
SH
1463}
1464
43654d34 1465static void *cgfsng_init(struct lxc_handler *handler)
ccb4cabe 1466{
457ca9aa 1467 const char *cgroup_pattern;
43654d34 1468 struct cgfsng_handler_data *d;
ccb4cabe
SH
1469
1470 d = must_alloc(sizeof(*d));
1471 memset(d, 0, sizeof(*d));
1472
43654d34
CB
1473 /* copy container name */
1474 d->name = must_copy_string(handler->name);
1475
1476 /* copy per-container cgroup information */
ae5e6c08
CB
1477 d->cgroup_meta.dir = NULL;
1478 d->cgroup_meta.controllers = NULL;
9b5396f9
CB
1479 if (handler->conf) {
1480 d->cgroup_meta.dir = must_copy_string(handler->conf->cgroup_meta.dir);
1481 d->cgroup_meta.controllers = must_copy_string(handler->conf->cgroup_meta.controllers);
1482 }
ccb4cabe 1483
43654d34 1484 /* copy system-wide cgroup information */
ccb4cabe 1485 cgroup_pattern = lxc_global_config_value("lxc.cgroup.pattern");
43654d34
CB
1486 if (!cgroup_pattern) {
1487 /* lxc.cgroup.pattern is only NULL on error. */
3d7a68f7 1488 ERROR("Failed to retrieve cgroup pattern");
ccb4cabe
SH
1489 goto out_free;
1490 }
1491 d->cgroup_pattern = must_copy_string(cgroup_pattern);
1492
d6337a5f
CB
1493 d->cgroup_layout = cgroup_layout;
1494 if (d->cgroup_layout == CGROUP_LAYOUT_LEGACY)
1495 TRACE("Running with legacy cgroup layout");
1496 else if (d->cgroup_layout == CGROUP_LAYOUT_HYBRID)
1497 TRACE("Running with hybrid cgroup layout");
1498 else if (d->cgroup_layout == CGROUP_LAYOUT_UNIFIED)
1499 TRACE("Running with unified cgroup layout");
1500 else
1501 WARN("Running with unknown cgroup layout");
1502
e4aeecf5
CB
1503 if (lxc_cgfsng_debug)
1504 lxc_cgfsng_print_debuginfo(d);
ccb4cabe
SH
1505
1506 return d;
1507
1508out_free:
1509 free_handler_data(d);
1510 return NULL;
1511}
1512
bd8ef4e4 1513static int recursive_destroy(char *dirname)
ccb4cabe 1514{
a17f8b3f 1515 int ret;
74f96976 1516 struct dirent *direntp;
ccb4cabe
SH
1517 DIR *dir;
1518 int r = 0;
1519
1520 dir = opendir(dirname);
1521 if (!dir)
1522 return -1;
1523
74f96976 1524 while ((direntp = readdir(dir))) {
ccb4cabe 1525 char *pathname;
a17f8b3f 1526 struct stat mystat;
ccb4cabe 1527
ccb4cabe
SH
1528 if (!strcmp(direntp->d_name, ".") ||
1529 !strcmp(direntp->d_name, ".."))
1530 continue;
1531
1532 pathname = must_make_path(dirname, direntp->d_name, NULL);
1533
a17f8b3f
CB
1534 ret = lstat(pathname, &mystat);
1535 if (ret < 0) {
ccb4cabe 1536 if (!r)
4adf9bd3 1537 WARN("Failed to stat \"%s\"", pathname);
ccb4cabe
SH
1538 r = -1;
1539 goto next;
1540 }
1541
1542 if (!S_ISDIR(mystat.st_mode))
1543 goto next;
a17f8b3f 1544
bd8ef4e4 1545 ret = recursive_destroy(pathname);
a17f8b3f 1546 if (ret < 0)
ccb4cabe 1547 r = -1;
bd8ef4e4 1548 next:
ccb4cabe
SH
1549 free(pathname);
1550 }
1551
a17f8b3f
CB
1552 ret = rmdir(dirname);
1553 if (ret < 0) {
ccb4cabe 1554 if (!r)
4adf9bd3 1555 WARN("%s - Failed to delete \"%s\"", strerror(errno), dirname);
ccb4cabe
SH
1556 r = -1;
1557 }
1558
a17f8b3f
CB
1559 ret = closedir(dir);
1560 if (ret < 0) {
ccb4cabe 1561 if (!r)
4adf9bd3 1562 WARN("%s - Failed to delete \"%s\"", strerror(errno), dirname);
ccb4cabe
SH
1563 r = -1;
1564 }
a17f8b3f 1565
ccb4cabe
SH
1566 return r;
1567}
1568
bd8ef4e4
CB
1569static int cgroup_rmdir(char *container_cgroup)
1570{
1571 int i;
1572
1573 if (!container_cgroup || !hierarchies)
1574 return 0;
1575
1576 for (i = 0; hierarchies[i]; i++) {
1577 int ret;
1578 struct hierarchy *h = hierarchies[i];
1579
1580 if (!h->fullcgpath)
1581 continue;
1582
1583 ret = recursive_destroy(h->fullcgpath);
1584 if (ret < 0)
1585 WARN("Failed to destroy \"%s\"", h->fullcgpath);
1586
1587 free(h->fullcgpath);
1588 h->fullcgpath = NULL;
1589 }
1590
1591 return 0;
1592}
1593
4160c3a0
CB
1594struct generic_userns_exec_data {
1595 struct cgfsng_handler_data *d;
1596 struct lxc_conf *conf;
1597 uid_t origuid; /* target uid in parent namespace */
1598 char *path;
1599};
1600
bd8ef4e4 1601static int cgroup_rmdir_wrapper(void *data)
ccb4cabe 1602{
6efacf80 1603 int ret;
4160c3a0
CB
1604 struct generic_userns_exec_data *arg = data;
1605 uid_t nsuid = (arg->conf->root_nsuid_map != NULL) ? 0 : arg->conf->init_uid;
1606 gid_t nsgid = (arg->conf->root_nsgid_map != NULL) ? 0 : arg->conf->init_gid;
ccb4cabe 1607
6efacf80
CB
1608 ret = setresgid(nsgid, nsgid, nsgid);
1609 if (ret < 0) {
1610 SYSERROR("Failed to setresgid(%d, %d, %d)", (int)nsgid,
1611 (int)nsgid, (int)nsgid);
1612 return -1;
1613 }
1614
1615 ret = setresuid(nsuid, nsuid, nsuid);
1616 if (ret < 0) {
1617 SYSERROR("Failed to setresuid(%d, %d, %d)", (int)nsuid,
1618 (int)nsuid, (int)nsuid);
1619 return -1;
1620 }
1621
1622 ret = setgroups(0, NULL);
1623 if (ret < 0 && errno != EPERM) {
1624 SYSERROR("Failed to setgroups(0, NULL)");
1625 return -1;
1626 }
ccb4cabe 1627
bd8ef4e4 1628 return cgroup_rmdir(arg->d->container_cgroup);
ccb4cabe
SH
1629}
1630
bd8ef4e4 1631static void cgfsng_destroy(void *hdata, struct lxc_conf *conf)
ccb4cabe 1632{
bd8ef4e4
CB
1633 int ret;
1634 struct cgfsng_handler_data *d = hdata;
4160c3a0
CB
1635 struct generic_userns_exec_data wrap;
1636
bd8ef4e4
CB
1637 if (!d)
1638 return;
1639
4160c3a0 1640 wrap.origuid = 0;
bd8ef4e4 1641 wrap.d = hdata;
4160c3a0
CB
1642 wrap.conf = conf;
1643
ccb4cabe 1644 if (conf && !lxc_list_empty(&conf->id_map))
bd8ef4e4
CB
1645 ret = userns_exec_1(conf, cgroup_rmdir_wrapper, &wrap,
1646 "cgroup_rmdir_wrapper");
ccb4cabe 1647 else
bd8ef4e4
CB
1648 ret = cgroup_rmdir(d->container_cgroup);
1649 if (ret < 0) {
1650 WARN("Failed to destroy cgroups");
ccb4cabe 1651 return;
ccb4cabe
SH
1652 }
1653
1654 free_handler_data(d);
1655}
1656
1657struct cgroup_ops *cgfsng_ops_init(void)
1658{
e4aeecf5
CB
1659 if (getenv("LXC_DEBUG_CGFSNG"))
1660 lxc_cgfsng_debug = true;
1661
d6337a5f 1662 if (!cg_init())
457ca9aa 1663 return NULL;
e4aeecf5 1664
ccb4cabe
SH
1665 return &cgfsng_ops;
1666}
1667
a3926f6a 1668static bool cg_unified_create_cgroup(struct hierarchy *h, char *cgname)
0c3deb94 1669{
0c3deb94 1670 size_t i, parts_len;
389d44ec 1671 char **it;
0c3deb94
CB
1672 size_t full_len = 0;
1673 char *add_controllers = NULL, *cgroup = NULL;
1674 char **parts = NULL;
1675 bool bret = false;
1676
1677 if (h->version != CGROUP2_SUPER_MAGIC)
1678 return true;
1679
1680 if (!h->controllers)
1681 return true;
1682
1683 /* For now we simply enable all controllers that we have detected by
1684 * creating a string like "+memory +pids +cpu +io".
1685 * TODO: In the near future we might want to support "-<controller>"
1686 * etc. but whether supporting semantics like this make sense will need
1687 * some thinking.
1688 */
1689 for (it = h->controllers; it && *it; it++) {
1690 full_len += strlen(*it) + 2;
1691 add_controllers = must_realloc(add_controllers, full_len + 1);
1692 if (h->controllers[0] == *it)
1693 add_controllers[0] = '\0';
1694 strcat(add_controllers, "+");
1695 strcat(add_controllers, *it);
1696 if ((it + 1) && *(it + 1))
1697 strcat(add_controllers, " ");
1698 }
1699
1700 parts = lxc_string_split(cgname, '/');
1701 if (!parts)
1702 goto on_error;
1703 parts_len = lxc_array_len((void **)parts);
1704 if (parts_len > 0)
1705 parts_len--;
1706
1707 cgroup = must_make_path(h->mountpoint, h->base_cgroup, NULL);
1708 for (i = 0; i < parts_len; i++) {
1709 int ret;
1710 char *target;
1711
1712 cgroup = must_append_path(cgroup, parts[i], NULL);
1713 target = must_make_path(cgroup, "cgroup.subtree_control", NULL);
1714 ret = lxc_write_to_file(target, add_controllers, full_len, false);
1715 free(target);
1716 if (ret < 0) {
1717 SYSERROR("Could not enable \"%s\" controllers in the "
1718 "unified cgroup \"%s\"", add_controllers, cgroup);
1719 goto on_error;
1720 }
1721 }
1722
1723 bret = true;
1724
1725on_error:
1726 lxc_free_array((void **)parts, free);
1727 free(add_controllers);
1728 free(cgroup);
1729 return bret;
1730}
1731
ccb4cabe
SH
1732static bool create_path_for_hierarchy(struct hierarchy *h, char *cgname)
1733{
0c3deb94
CB
1734 int ret;
1735
e3a3fecf 1736 h->fullcgpath = must_make_path(h->mountpoint, h->base_cgroup, cgname, NULL);
4b4205e3
CB
1737 if (dir_exists(h->fullcgpath)) {
1738 ERROR("The cgroup \"%s\" already existed", h->fullcgpath);
d8da679e 1739 return false;
6f9584d8 1740 }
0c3deb94 1741
a3926f6a 1742 if (!cg_legacy_handle_cpuset_hierarchy(h, cgname)) {
4b4205e3 1743 ERROR("Failed to handle legacy cpuset controller");
0c3deb94
CB
1744 return false;
1745 }
1746
1747 ret = mkdir_p(h->fullcgpath, 0755);
1748 if (ret < 0) {
1749 ERROR("Failed to create cgroup \"%s\"", h->fullcgpath);
e3a3fecf 1750 return false;
6f9584d8 1751 }
0c3deb94 1752
a3926f6a 1753 return cg_unified_create_cgroup(h, cgname);
ccb4cabe
SH
1754}
1755
1756static void remove_path_for_hierarchy(struct hierarchy *h, char *cgname)
1757{
1758 if (rmdir(h->fullcgpath) < 0)
1759 SYSERROR("Failed to clean up cgroup %s from failed creation attempt", h->fullcgpath);
1760 free(h->fullcgpath);
1761 h->fullcgpath = NULL;
1762}
1763
1764/*
d30ec4cb 1765 * Try to create the same cgroup in all hierarchies.
ccb4cabe
SH
1766 * Start with cgroup_pattern; next cgroup_pattern-1, -2, ..., -999
1767 */
1768static inline bool cgfsng_create(void *hdata)
1769{
bb30b52a 1770 int i;
ccb4cabe 1771 size_t len;
0c3deb94 1772 char *container_cgroup, *offset, *tmp;
7d531e9b
CB
1773 int idx = 0;
1774 struct cgfsng_handler_data *d = hdata;
ccb4cabe
SH
1775
1776 if (!d)
1777 return false;
43654d34 1778
ccb4cabe
SH
1779 if (d->container_cgroup) {
1780 WARN("cgfsng_create called a second time");
1781 return false;
1782 }
1783
43654d34 1784 if (d->cgroup_meta.dir)
7d531e9b 1785 tmp = lxc_string_join("/", (const char *[]){d->cgroup_meta.dir, d->name, NULL}, false);
43654d34
CB
1786 else
1787 tmp = lxc_string_replace("%n", d->name, d->cgroup_pattern);
ccb4cabe
SH
1788 if (!tmp) {
1789 ERROR("Failed expanding cgroup name pattern");
1790 return false;
1791 }
1a0e70ac 1792 len = strlen(tmp) + 5; /* leave room for -NNN\0 */
0c3deb94
CB
1793 container_cgroup = must_alloc(len);
1794 strcpy(container_cgroup, tmp);
ccb4cabe 1795 free(tmp);
0c3deb94 1796 offset = container_cgroup + len - 5;
ccb4cabe
SH
1797
1798again:
95adfe93
SH
1799 if (idx == 1000) {
1800 ERROR("Too many conflicting cgroup names");
ccb4cabe 1801 goto out_free;
95adfe93 1802 }
66b66624 1803 if (idx) {
bb30b52a
CB
1804 int ret;
1805
66b66624
CB
1806 ret = snprintf(offset, 5, "-%d", idx);
1807 if (ret < 0 || (size_t)ret >= 5) {
1808 FILE *f = fopen("/dev/null", "w");
97ebced3 1809 if (f) {
66b66624
CB
1810 fprintf(f, "Workaround for GCC7 bug: "
1811 "https://gcc.gnu.org/bugzilla/"
1812 "show_bug.cgi?id=78969");
1813 fclose(f);
1814 }
1815 }
1816 }
457ca9aa 1817 for (i = 0; hierarchies[i]; i++) {
0c3deb94 1818 if (!create_path_for_hierarchy(hierarchies[i], container_cgroup)) {
ccb4cabe 1819 int j;
1a0e70ac 1820 ERROR("Failed to create \"%s\"", hierarchies[i]->fullcgpath);
457ca9aa
SH
1821 free(hierarchies[i]->fullcgpath);
1822 hierarchies[i]->fullcgpath = NULL;
ccb4cabe 1823 for (j = 0; j < i; j++)
0c3deb94 1824 remove_path_for_hierarchy(hierarchies[j], container_cgroup);
ccb4cabe
SH
1825 idx++;
1826 goto again;
1827 }
1828 }
1829 /* Done */
0c3deb94 1830 d->container_cgroup = container_cgroup;
ccb4cabe
SH
1831 return true;
1832
1833out_free:
0c3deb94 1834 free(container_cgroup);
ccb4cabe
SH
1835 return false;
1836}
1837
ccb4cabe
SH
1838static bool cgfsng_enter(void *hdata, pid_t pid)
1839{
ccb4cabe
SH
1840 char pidstr[25];
1841 int i, len;
1842
1843 len = snprintf(pidstr, 25, "%d", pid);
1844 if (len < 0 || len > 25)
1845 return false;
1846
457ca9aa
SH
1847 for (i = 0; hierarchies[i]; i++) {
1848 char *fullpath = must_make_path(hierarchies[i]->fullcgpath,
ccb4cabe
SH
1849 "cgroup.procs", NULL);
1850 if (lxc_write_to_file(fullpath, pidstr, len, false) != 0) {
d3b00a8f 1851 SYSERROR("Failed to enter %s", fullpath);
ccb4cabe
SH
1852 free(fullpath);
1853 return false;
1854 }
1855 free(fullpath);
1856 }
1857
1858 return true;
1859}
1860
6efacf80
CB
1861static int chowmod(char *path, uid_t chown_uid, gid_t chown_gid,
1862 mode_t chmod_mode)
1863{
1864 int ret;
1865
1866 ret = chown(path, chown_uid, chown_gid);
1867 if (ret < 0) {
1868 WARN("%s - Failed to chown(%s, %d, %d)", strerror(errno), path,
1869 (int)chown_uid, (int)chown_gid);
1870 return -1;
1871 }
1872
1873 ret = chmod(path, chmod_mode);
1874 if (ret < 0) {
1875 WARN("%s - Failed to chmod(%s, %d)", strerror(errno), path,
1876 (int)chmod_mode);
1877 return -1;
1878 }
1879
1880 return 0;
1881}
1882
1883/* chgrp the container cgroups to container group. We leave
c0888dfe
SH
1884 * the container owner as cgroup owner. So we must make the
1885 * directories 775 so that the container can create sub-cgroups.
43647298
SH
1886 *
1887 * Also chown the tasks and cgroup.procs files. Those may not
1888 * exist depending on kernel version.
c0888dfe 1889 */
ccb4cabe
SH
1890static int chown_cgroup_wrapper(void *data)
1891{
6efacf80 1892 int i, ret;
4160c3a0
CB
1893 uid_t destuid;
1894 struct generic_userns_exec_data *arg = data;
1895 uid_t nsuid = (arg->conf->root_nsuid_map != NULL) ? 0 : arg->conf->init_uid;
1896 gid_t nsgid = (arg->conf->root_nsgid_map != NULL) ? 0 : arg->conf->init_gid;
ccb4cabe 1897
6efacf80
CB
1898 ret = setresgid(nsgid, nsgid, nsgid);
1899 if (ret < 0) {
1900 SYSERROR("Failed to setresgid(%d, %d, %d)",
1901 (int)nsgid, (int)nsgid, (int)nsgid);
1902 return -1;
1903 }
1904
1905 ret = setresuid(nsuid, nsuid, nsuid);
1906 if (ret < 0) {
1907 SYSERROR("Failed to setresuid(%d, %d, %d)",
1908 (int)nsuid, (int)nsuid, (int)nsuid);
1909 return -1;
1910 }
1911
1912 ret = setgroups(0, NULL);
1913 if (ret < 0 && errno != EPERM) {
1914 SYSERROR("Failed to setgroups(0, NULL)");
1915 return -1;
1916 }
ccb4cabe
SH
1917
1918 destuid = get_ns_uid(arg->origuid);
1919
457ca9aa 1920 for (i = 0; hierarchies[i]; i++) {
6efacf80
CB
1921 char *fullpath;
1922 char *path = hierarchies[i]->fullcgpath;
43647298 1923
63e42fee 1924 ret = chowmod(path, destuid, nsgid, 0775);
6efacf80 1925 if (ret < 0)
ccb4cabe 1926 return -1;
c0888dfe 1927
6efacf80
CB
1928 /* Failures to chown() these are inconvenient but not
1929 * detrimental We leave these owned by the container launcher,
1930 * so that container root can write to the files to attach. We
1931 * chmod() them 664 so that container systemd can write to the
1932 * files (which systemd in wily insists on doing).
ab8f5424 1933 */
6efacf80
CB
1934
1935 if (hierarchies[i]->version == CGROUP_SUPER_MAGIC) {
1936 fullpath = must_make_path(path, "tasks", NULL);
1937 (void)chowmod(fullpath, destuid, nsgid, 0664);
1938 free(fullpath);
1939 }
43647298
SH
1940
1941 fullpath = must_make_path(path, "cgroup.procs", NULL);
6efacf80 1942 (void)chowmod(fullpath, destuid, 0, 0664);
ccb4cabe 1943 free(fullpath);
0e17357c 1944
d6337a5f 1945 if (hierarchies[i]->version != CGROUP2_SUPER_MAGIC)
0e17357c
CB
1946 continue;
1947
1948 fullpath = must_make_path(path, "cgroup.subtree_control", NULL);
6efacf80 1949 (void)chowmod(fullpath, destuid, nsgid, 0664);
0e17357c
CB
1950 free(fullpath);
1951
1952 fullpath = must_make_path(path, "cgroup.threads", NULL);
6efacf80 1953 (void)chowmod(fullpath, destuid, nsgid, 0664);
0e17357c 1954 free(fullpath);
ccb4cabe
SH
1955 }
1956
1957 return 0;
1958}
1959
058c1cb6 1960static bool cgfsng_chown(void *hdata, struct lxc_conf *conf)
ccb4cabe
SH
1961{
1962 struct cgfsng_handler_data *d = hdata;
4160c3a0 1963 struct generic_userns_exec_data wrap;
ccb4cabe
SH
1964
1965 if (!d)
1966 return false;
1967
1968 if (lxc_list_empty(&conf->id_map))
1969 return true;
1970
ccb4cabe 1971 wrap.origuid = geteuid();
4160c3a0
CB
1972 wrap.path = NULL;
1973 wrap.d = d;
1974 wrap.conf = conf;
ccb4cabe 1975
c9b7c33e
CB
1976 if (userns_exec_1(conf, chown_cgroup_wrapper, &wrap,
1977 "chown_cgroup_wrapper") < 0) {
ccb4cabe
SH
1978 ERROR("Error requesting cgroup chown in new namespace");
1979 return false;
1980 }
1981
1982 return true;
1983}
1984
8aa1044f
SH
1985/*
1986 * We've safe-mounted a tmpfs as parent, so we don't need to protect against
1987 * symlinks any more - just use mount
1988 */
1989
1990/* mount cgroup-full if requested */
1991static int mount_cgroup_full(int type, struct hierarchy *h, char *dest,
a3926f6a 1992 char *container_cgroup)
8aa1044f
SH
1993{
1994 if (type < LXC_AUTO_CGROUP_FULL_RO || type > LXC_AUTO_CGROUP_FULL_MIXED)
1995 return 0;
1996 if (mount(h->mountpoint, dest, "cgroup", MS_BIND, NULL) < 0) {
1997 SYSERROR("Error bind-mounting %s cgroup onto %s", h->mountpoint,
1998 dest);
1999 return -1;
2000 }
2001 if (type != LXC_AUTO_CGROUP_FULL_RW) {
5b6f9369
SH
2002 unsigned long flags = MS_BIND | MS_NOSUID | MS_NOEXEC | MS_NODEV |
2003 MS_REMOUNT | MS_RDONLY;
2004 if (mount(NULL, dest, "cgroup", flags, NULL) < 0) {
8aa1044f
SH
2005 SYSERROR("Error remounting %s readonly", dest);
2006 return -1;
2007 }
2008 }
2009
2010 INFO("Bind mounted %s onto %s", h->mountpoint, dest);
2011 if (type != LXC_AUTO_CGROUP_FULL_MIXED)
2012 return 0;
2013
2014 /* mount just the container path rw */
2015 char *source = must_make_path(h->mountpoint, h->base_cgroup, container_cgroup, NULL);
5b6f9369 2016 char *rwpath = must_make_path(dest, h->base_cgroup, container_cgroup, NULL);
8aa1044f 2017 if (mount(source, rwpath, "cgroup", MS_BIND, NULL) < 0)
13277ec4 2018 WARN("Failed to mount %s read-write: %s", rwpath,
2019 strerror(errno));
8aa1044f
SH
2020 INFO("Made %s read-write", rwpath);
2021 free(rwpath);
2022 free(source);
2023 return 0;
2024}
2025
2026/* cgroup-full:* is done, no need to create subdirs */
2027static bool cg_mount_needs_subdirs(int type)
2028{
2029 if (type >= LXC_AUTO_CGROUP_FULL_RO)
2030 return false;
a3926f6a 2031
8aa1044f
SH
2032 return true;
2033}
2034
886cac86
CB
2035/* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
2036 * remount controller ro if needed and bindmount the cgroupfs onto
2037 * controll/the/cg/path.
8aa1044f 2038 */
a3926f6a
CB
2039static int do_secondstage_mounts_if_needed(int type, struct hierarchy *h,
2040 char *controllerpath, char *cgpath,
2041 const char *container_cgroup)
8aa1044f 2042{
5285689c 2043 int ret, remount_flags;
886cac86
CB
2044 char *sourcepath;
2045 int flags = MS_BIND;
2046
8aa1044f 2047 if (type == LXC_AUTO_CGROUP_RO || type == LXC_AUTO_CGROUP_MIXED) {
886cac86
CB
2048 ret = mount(controllerpath, controllerpath, "cgroup", MS_BIND, NULL);
2049 if (ret < 0) {
2050 SYSERROR("Failed to bind mount \"%s\" onto \"%s\"",
2051 controllerpath, controllerpath);
8aa1044f
SH
2052 return -1;
2053 }
886cac86 2054
5285689c
CB
2055 remount_flags = add_required_remount_flags(controllerpath,
2056 controllerpath,
2057 flags | MS_REMOUNT);
886cac86
CB
2058 ret = mount(controllerpath, controllerpath, "cgroup",
2059 MS_REMOUNT | MS_BIND | MS_RDONLY, NULL);
2060 if (ret < 0) {
2061 SYSERROR("Failed to remount \"%s\" ro", controllerpath);
8aa1044f
SH
2062 return -1;
2063 }
886cac86 2064
8aa1044f
SH
2065 INFO("Remounted %s read-only", controllerpath);
2066 }
886cac86
CB
2067
2068 sourcepath = must_make_path(h->mountpoint, h->base_cgroup,
2069 container_cgroup, NULL);
8aa1044f
SH
2070 if (type == LXC_AUTO_CGROUP_RO)
2071 flags |= MS_RDONLY;
886cac86
CB
2072
2073 ret = mount(sourcepath, cgpath, "cgroup", flags, NULL);
2074 if (ret < 0) {
2075 SYSERROR("Failed to mount \"%s\" onto \"%s\"", h->controllers[0], cgpath);
8aa1044f 2076 free(sourcepath);
8aa1044f
SH
2077 return -1;
2078 }
886cac86 2079 INFO("Mounted \"%s\" onto \"%s\"", h->controllers[0], cgpath);
f8c40ffa
L
2080
2081 if (flags & MS_RDONLY) {
5285689c
CB
2082 remount_flags = add_required_remount_flags(sourcepath, cgpath,
2083 flags | MS_REMOUNT);
2084 ret = mount(sourcepath, cgpath, "cgroup", remount_flags, NULL);
886cac86
CB
2085 if (ret < 0) {
2086 SYSERROR("Failed to remount \"%s\" ro", cgpath);
f8c40ffa 2087 free(sourcepath);
f8c40ffa
L
2088 return -1;
2089 }
5285689c 2090 INFO("Remounted %s read-only", cgpath);
f8c40ffa
L
2091 }
2092
8aa1044f 2093 free(sourcepath);
886cac86 2094 INFO("Completed second stage cgroup automounts for \"%s\"", cgpath);
8aa1044f
SH
2095 return 0;
2096}
2097
5285689c
CB
2098static int cg_mount_in_cgroup_namespace(int type, struct hierarchy *h,
2099 const char *controllerpath)
b635e92d
CB
2100{
2101 int ret;
2102 char *controllers = NULL;
a760603e
CB
2103 char *fstype = "cgroup2";
2104 unsigned long flags = 0;
b635e92d 2105
a760603e
CB
2106 flags |= MS_NOSUID;
2107 flags |= MS_NOEXEC;
2108 flags |= MS_NODEV;
2109 flags |= MS_RELATIME;
2110
2111 if (type == LXC_AUTO_CGROUP_RO || type == LXC_AUTO_CGROUP_FULL_RO)
2112 flags |= MS_RDONLY;
2113
d6337a5f 2114 if (h->version != CGROUP2_SUPER_MAGIC) {
a760603e
CB
2115 controllers = lxc_string_join(",", (const char **)h->controllers, false);
2116 if (!controllers)
2117 return -ENOMEM;
2118 fstype = "cgroup";
b635e92d
CB
2119 }
2120
a760603e 2121 ret = mount("cgroup", controllerpath, fstype, flags, controllers);
b635e92d
CB
2122 free(controllers);
2123 if (ret < 0) {
a760603e 2124 SYSERROR("Failed to mount %s with cgroup filesystem type %s", controllerpath, fstype);
b635e92d
CB
2125 return -1;
2126 }
2127
a760603e 2128 DEBUG("Mounted %s with cgroup filesystem type %s", controllerpath, fstype);
b635e92d
CB
2129 return 0;
2130}
2131
ccb4cabe
SH
2132static bool cgfsng_mount(void *hdata, const char *root, int type)
2133{
3f69fb12 2134 int i, ret;
8aa1044f
SH
2135 char *tmpfspath = NULL;
2136 bool retval = false;
b635e92d
CB
2137 struct lxc_handler *handler = hdata;
2138 struct cgfsng_handler_data *d = handler->cgroup_data;
3f69fb12 2139 bool has_cgns = false, wants_force_mount = false;
8aa1044f
SH
2140
2141 if ((type & LXC_AUTO_CGROUP_MASK) == 0)
2142 return true;
2143
3f69fb12
SY
2144 if (type & LXC_AUTO_CGROUP_FORCE) {
2145 type &= ~LXC_AUTO_CGROUP_FORCE;
2146 wants_force_mount = true;
2147 }
b635e92d 2148
3f69fb12
SY
2149 if (!wants_force_mount){
2150 if (!lxc_list_empty(&handler->conf->keepcaps))
2151 wants_force_mount = !in_caplist(CAP_SYS_ADMIN, &handler->conf->keepcaps);
2152 else
2153 wants_force_mount = in_caplist(CAP_SYS_ADMIN, &handler->conf->caps);
2154 }
8aa1044f 2155
3f69fb12
SY
2156 has_cgns = cgns_supported();
2157 if (has_cgns && !wants_force_mount)
2158 return true;
8aa1044f
SH
2159
2160 if (type == LXC_AUTO_CGROUP_NOSPEC)
2161 type = LXC_AUTO_CGROUP_MIXED;
2162 else if (type == LXC_AUTO_CGROUP_FULL_NOSPEC)
2163 type = LXC_AUTO_CGROUP_FULL_MIXED;
2164
2165 /* Mount tmpfs */
3f69fb12
SY
2166 tmpfspath = must_make_path(root, "/sys/fs/cgroup", NULL);
2167 ret = safe_mount("cgroup_root", tmpfspath, "tmpfs",
2168 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_RELATIME,
2169 "size=10240k,mode=755", root);
2170 if (ret < 0)
2171 goto on_error;
8aa1044f 2172
457ca9aa 2173 for (i = 0; hierarchies[i]; i++) {
8aa1044f 2174 char *controllerpath, *path2;
457ca9aa 2175 struct hierarchy *h = hierarchies[i];
8aa1044f 2176 char *controller = strrchr(h->mountpoint, '/');
8aa1044f
SH
2177
2178 if (!controller)
2179 continue;
2180 controller++;
2181 controllerpath = must_make_path(tmpfspath, controller, NULL);
2182 if (dir_exists(controllerpath)) {
2183 free(controllerpath);
2184 continue;
2185 }
3f69fb12
SY
2186 ret = mkdir(controllerpath, 0755);
2187 if (ret < 0) {
8aa1044f
SH
2188 SYSERROR("Error creating cgroup path: %s", controllerpath);
2189 free(controllerpath);
3f69fb12 2190 goto on_error;
8aa1044f 2191 }
b635e92d 2192
3f69fb12 2193 if (has_cgns && wants_force_mount) {
b635e92d
CB
2194 /* If cgroup namespaces are supported but the container
2195 * will not have CAP_SYS_ADMIN after it has started we
2196 * need to mount the cgroups manually.
2197 */
3f69fb12 2198 ret = cg_mount_in_cgroup_namespace(type, h, controllerpath);
b635e92d 2199 free(controllerpath);
3f69fb12
SY
2200 if (ret < 0)
2201 goto on_error;
2202
b635e92d
CB
2203 continue;
2204 }
2205
3f69fb12
SY
2206 ret = mount_cgroup_full(type, h, controllerpath, d->container_cgroup);
2207 if (ret < 0) {
8aa1044f 2208 free(controllerpath);
3f69fb12 2209 goto on_error;
8aa1044f 2210 }
3f69fb12 2211
8aa1044f
SH
2212 if (!cg_mount_needs_subdirs(type)) {
2213 free(controllerpath);
2214 continue;
2215 }
3f69fb12
SY
2216
2217 path2 = must_make_path(controllerpath, h->base_cgroup,
2218 d->container_cgroup, NULL);
2219 ret = mkdir_p(path2, 0755);
2220 if (ret < 0) {
8aa1044f 2221 free(controllerpath);
8e0c6620 2222 free(path2);
3f69fb12 2223 goto on_error;
8aa1044f 2224 }
2f62fb00 2225
3f69fb12
SY
2226 ret = do_secondstage_mounts_if_needed(
2227 type, h, controllerpath, path2, d->container_cgroup);
8aa1044f
SH
2228 free(controllerpath);
2229 free(path2);
3f69fb12
SY
2230 if (ret < 0)
2231 goto on_error;
8aa1044f
SH
2232 }
2233 retval = true;
2234
3f69fb12 2235on_error:
8aa1044f
SH
2236 free(tmpfspath);
2237 return retval;
ccb4cabe
SH
2238}
2239
2240static int recursive_count_nrtasks(char *dirname)
2241{
74f96976 2242 struct dirent *direntp;
ccb4cabe
SH
2243 DIR *dir;
2244 int count = 0, ret;
2245 char *path;
2246
2247 dir = opendir(dirname);
2248 if (!dir)
2249 return 0;
2250
74f96976 2251 while ((direntp = readdir(dir))) {
ccb4cabe
SH
2252 struct stat mystat;
2253
2254 if (!direntp)
2255 break;
2256
2257 if (!strcmp(direntp->d_name, ".") ||
2258 !strcmp(direntp->d_name, ".."))
2259 continue;
2260
2261 path = must_make_path(dirname, direntp->d_name, NULL);
2262
2263 if (lstat(path, &mystat))
2264 goto next;
2265
2266 if (!S_ISDIR(mystat.st_mode))
2267 goto next;
2268
2269 count += recursive_count_nrtasks(path);
2270next:
2271 free(path);
2272 }
2273
2274 path = must_make_path(dirname, "cgroup.procs", NULL);
2275 ret = lxc_count_file_lines(path);
2276 if (ret != -1)
2277 count += ret;
2278 free(path);
2279
2280 (void) closedir(dir);
2281
2282 return count;
2283}
2284
2285static int cgfsng_nrtasks(void *hdata) {
2286 struct cgfsng_handler_data *d = hdata;
2287 char *path;
2288 int count;
2289
457ca9aa 2290 if (!d || !d->container_cgroup || !hierarchies)
ccb4cabe 2291 return -1;
a3926f6a 2292
457ca9aa 2293 path = must_make_path(hierarchies[0]->fullcgpath, NULL);
ccb4cabe
SH
2294 count = recursive_count_nrtasks(path);
2295 free(path);
2296 return count;
2297}
2298
2299/* Only root needs to escape to the cgroup of its init */
7103fe6f 2300static bool cgfsng_escape()
ccb4cabe 2301{
ccb4cabe
SH
2302 int i;
2303
2304 if (geteuid())
2305 return true;
2306
457ca9aa
SH
2307 for (i = 0; hierarchies[i]; i++) {
2308 char *fullpath = must_make_path(hierarchies[i]->mountpoint,
2309 hierarchies[i]->base_cgroup,
ccb4cabe
SH
2310 "cgroup.procs", NULL);
2311 if (lxc_write_to_file(fullpath, "0", 2, false) != 0) {
d3b00a8f 2312 SYSERROR("Failed to escape to %s", fullpath);
ccb4cabe 2313 free(fullpath);
6df334d1 2314 return false;
ccb4cabe
SH
2315 }
2316 free(fullpath);
2317 }
2318
6df334d1 2319 return true;
ccb4cabe
SH
2320}
2321
36662416
TA
2322static int cgfsng_num_hierarchies(void)
2323{
2324 int i;
2325
2326 for (i = 0; hierarchies[i]; i++)
2327 ;
2328
2329 return i;
2330}
2331
2332static bool cgfsng_get_hierarchies(int n, char ***out)
2333{
2334 int i;
2335
2336 /* sanity check n */
6b38e644 2337 for (i = 0; i < n; i++)
36662416
TA
2338 if (!hierarchies[i])
2339 return false;
36662416
TA
2340
2341 *out = hierarchies[i]->controllers;
2342
2343 return true;
2344}
2345
ccb4cabe
SH
2346#define THAWED "THAWED"
2347#define THAWED_LEN (strlen(THAWED))
2348
d6337a5f
CB
2349/* TODO: If the unified cgroup hierarchy grows a freezer controller this needs
2350 * to be adapted.
2351 */
ccb4cabe
SH
2352static bool cgfsng_unfreeze(void *hdata)
2353{
d6337a5f 2354 int ret;
ccb4cabe 2355 char *fullpath;
d6337a5f 2356 struct hierarchy *h;
ccb4cabe 2357
d6337a5f 2358 h = get_hierarchy("freezer");
457ca9aa 2359 if (!h)
ccb4cabe 2360 return false;
d6337a5f 2361
ccb4cabe 2362 fullpath = must_make_path(h->fullcgpath, "freezer.state", NULL);
d6337a5f 2363 ret = lxc_write_to_file(fullpath, THAWED, THAWED_LEN, false);
ccb4cabe 2364 free(fullpath);
d6337a5f
CB
2365 if (ret < 0)
2366 return false;
2367
ccb4cabe
SH
2368 return true;
2369}
2370
2371static const char *cgfsng_get_cgroup(void *hdata, const char *subsystem)
2372{
d6337a5f
CB
2373 struct hierarchy *h;
2374
2375 h = get_hierarchy(subsystem);
ccb4cabe
SH
2376 if (!h)
2377 return NULL;
2378
371f834d
SH
2379 return h->fullcgpath ? h->fullcgpath + strlen(h->mountpoint) : NULL;
2380}
2381
2382/*
2383 * Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a
2384 * full path, which must be freed by the caller.
2385 */
2386static char *build_full_cgpath_from_monitorpath(struct hierarchy *h,
2387 const char *inpath,
2388 const char *filename)
2389{
371f834d 2390 return must_make_path(h->mountpoint, inpath, filename, NULL);
ccb4cabe
SH
2391}
2392
c2aed66d
CB
2393/* Technically, we're always at a delegation boundary here. (This is especially
2394 * true when cgroup namespaces are available.) The reasoning is that in order
2395 * for us to have been able to start a container in the first place the root
2396 * cgroup must have been a leaf node. Now, either the container's init system
2397 * has populated the cgroup and kept it as a leaf node or it has created
2398 * subtrees. In the former case we will simply attach to the leaf node we
2399 * created when we started the container in the latter case we create our own
2400 * cgroup for the attaching process.
2401 */
a3926f6a
CB
2402static int __cg_unified_attach(const struct hierarchy *h, const char *name,
2403 const char *lxcpath, const char *pidstr,
2404 size_t pidstr_len, const char *controller)
c2aed66d
CB
2405{
2406 int ret;
2407 size_t len;
2408 int fret = -1, idx = 0;
2409 char *base_path = NULL, *container_cgroup = NULL, *full_path = NULL;
2410
2411 container_cgroup = lxc_cmd_get_cgroup_path(name, lxcpath, controller);
2412 /* not running */
2413 if (!container_cgroup)
2414 return 0;
2415
2416 base_path = must_make_path(h->mountpoint, container_cgroup, NULL);
2417 full_path = must_make_path(base_path, "cgroup.procs", NULL);
2418 /* cgroup is populated */
2419 ret = lxc_write_to_file(full_path, pidstr, pidstr_len, false);
2420 if (ret < 0 && errno != EBUSY)
2421 goto on_error;
2422
2423 if (ret == 0)
2424 goto on_success;
2425
2426 free(full_path);
2427
2428 len = strlen(base_path) + sizeof("/lxc-1000") - 1 +
2429 sizeof("/cgroup-procs") - 1;
2430 full_path = must_alloc(len + 1);
2431 do {
2432 if (idx)
2433 ret = snprintf(full_path, len + 1, "%s/lxc-%d",
2434 base_path, idx);
2435 else
2436 ret = snprintf(full_path, len + 1, "%s/lxc", base_path);
2437 if (ret < 0 || (size_t)ret >= len + 1)
2438 goto on_error;
2439
2440 ret = mkdir_p(full_path, 0755);
2441 if (ret < 0 && errno != EEXIST)
2442 goto on_error;
2443
2444 strcat(full_path, "/cgroup.procs");
2445 ret = lxc_write_to_file(full_path, pidstr, len, false);
2446 if (ret == 0)
2447 goto on_success;
2448
2449 /* this is a non-leaf node */
2450 if (errno != EBUSY)
2451 goto on_error;
2452
2453 } while (++idx > 0 && idx < 1000);
2454
2455on_success:
2456 if (idx < 1000)
2457 fret = 0;
2458
2459on_error:
2460 free(base_path);
2461 free(container_cgroup);
2462 free(full_path);
2463
2464 return fret;
2465}
2466
ccb4cabe
SH
2467static bool cgfsng_attach(const char *name, const char *lxcpath, pid_t pid)
2468{
c2aed66d 2469 int i, len, ret;
ccb4cabe 2470 char pidstr[25];
ccb4cabe
SH
2471
2472 len = snprintf(pidstr, 25, "%d", pid);
2473 if (len < 0 || len > 25)
2474 return false;
2475
457ca9aa 2476 for (i = 0; hierarchies[i]; i++) {
c2aed66d
CB
2477 char *path;
2478 char *fullpath = NULL;
457ca9aa 2479 struct hierarchy *h = hierarchies[i];
ccb4cabe 2480
c2aed66d 2481 if (h->version == CGROUP2_SUPER_MAGIC) {
a3926f6a
CB
2482 ret = __cg_unified_attach(h, name, lxcpath, pidstr, len,
2483 h->controllers[0]);
c2aed66d
CB
2484 if (ret < 0)
2485 return false;
2486
2487 continue;
2488 }
2489
ccb4cabe 2490 path = lxc_cmd_get_cgroup_path(name, lxcpath, h->controllers[0]);
c2aed66d
CB
2491 /* not running */
2492 if (!path)
ccb4cabe
SH
2493 continue;
2494
371f834d 2495 fullpath = build_full_cgpath_from_monitorpath(h, path, "cgroup.procs");
c2aed66d
CB
2496 ret = lxc_write_to_file(fullpath, pidstr, len, false);
2497 if (ret < 0) {
ccb4cabe
SH
2498 SYSERROR("Failed to attach %d to %s", (int)pid, fullpath);
2499 free(fullpath);
ccb4cabe
SH
2500 return false;
2501 }
ccb4cabe
SH
2502 free(fullpath);
2503 }
2504
ccb4cabe
SH
2505 return true;
2506}
2507
2508/*
2509 * Called externally (i.e. from 'lxc-cgroup') to query cgroup limits.
2510 * Here we don't have a cgroup_data set up, so we ask the running
2511 * container through the commands API for the cgroup path
2512 */
0069cc61
CB
2513static int cgfsng_get(const char *filename, char *value, size_t len,
2514 const char *name, const char *lxcpath)
ccb4cabe 2515{
ccb4cabe 2516 int ret = -1;
0069cc61
CB
2517 size_t controller_len;
2518 char *controller, *p, *path;
2519 struct hierarchy *h;
ccb4cabe 2520
0069cc61
CB
2521 controller_len = strlen(filename);
2522 controller = alloca(controller_len + 1);
2523 strcpy(controller, filename);
2524 p = strchr(controller, '.');
2525 if (p)
ccb4cabe
SH
2526 *p = '\0';
2527
0069cc61
CB
2528 path = lxc_cmd_get_cgroup_path(name, lxcpath, controller);
2529 /* not running */
2530 if (!path)
ccb4cabe
SH
2531 return -1;
2532
0069cc61 2533 h = get_hierarchy(controller);
ccb4cabe 2534 if (h) {
0069cc61
CB
2535 char *fullpath;
2536
2537 fullpath = build_full_cgpath_from_monitorpath(h, path, filename);
ccb4cabe
SH
2538 ret = lxc_read_from_file(fullpath, value, len);
2539 free(fullpath);
2540 }
ccb4cabe
SH
2541 free(path);
2542
2543 return ret;
2544}
2545
2546/*
2547 * Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits.
2548 * Here we don't have a cgroup_data set up, so we ask the running
2549 * container through the commands API for the cgroup path
2550 */
87777968
CB
2551static int cgfsng_set(const char *filename, const char *value, const char *name,
2552 const char *lxcpath)
ccb4cabe 2553{
ccb4cabe 2554 int ret = -1;
87777968
CB
2555 size_t controller_len;
2556 char *controller, *p, *path;
2557 struct hierarchy *h;
ccb4cabe 2558
87777968
CB
2559 controller_len = strlen(filename);
2560 controller = alloca(controller_len + 1);
2561 strcpy(controller, filename);
2562 p = strchr(controller, '.');
2563 if (p)
ccb4cabe
SH
2564 *p = '\0';
2565
87777968
CB
2566 path = lxc_cmd_get_cgroup_path(name, lxcpath, controller);
2567 /* not running */
2568 if (!path)
ccb4cabe
SH
2569 return -1;
2570
87777968 2571 h = get_hierarchy(controller);
ccb4cabe 2572 if (h) {
87777968
CB
2573 char *fullpath;
2574
2575 fullpath = build_full_cgpath_from_monitorpath(h, path, filename);
ccb4cabe
SH
2576 ret = lxc_write_to_file(fullpath, value, strlen(value), false);
2577 free(fullpath);
2578 }
ccb4cabe
SH
2579 free(path);
2580
2581 return ret;
2582}
2583
72add155
SH
2584/*
2585 * take devices cgroup line
2586 * /dev/foo rwx
2587 * and convert it to a valid
2588 * type major:minor mode
2589 * line. Return <0 on error. Dest is a preallocated buffer
2590 * long enough to hold the output.
2591 */
2592static int convert_devpath(const char *invalue, char *dest)
2593{
2a06d041
CB
2594 int n_parts;
2595 char *p, *path, type;
72add155
SH
2596 struct stat sb;
2597 unsigned long minor, major;
2a06d041
CB
2598 int ret = -EINVAL;
2599 char *mode = NULL;
72add155
SH
2600
2601 path = must_copy_string(invalue);
2602
2603 /*
2604 * read path followed by mode; ignore any trailing text.
2605 * A ' # comment' would be legal. Technically other text
2606 * is not legal, we could check for that if we cared to
2607 */
2608 for (n_parts = 1, p = path; *p && n_parts < 3; p++) {
2c2d6c49
SH
2609 if (*p != ' ')
2610 continue;
2611 *p = '\0';
2612 if (n_parts != 1)
2613 break;
2614 p++;
2615 n_parts++;
2616 while (*p == ' ')
2617 p++;
2618 mode = p;
2619 if (*p == '\0')
2620 goto out;
72add155 2621 }
2c2d6c49
SH
2622
2623 if (n_parts == 1)
72add155 2624 goto out;
72add155
SH
2625
2626 ret = stat(path, &sb);
2627 if (ret < 0)
2628 goto out;
2629
72add155
SH
2630 mode_t m = sb.st_mode & S_IFMT;
2631 switch (m) {
2632 case S_IFBLK:
2633 type = 'b';
2634 break;
2635 case S_IFCHR:
2636 type = 'c';
2637 break;
2c2d6c49 2638 default:
72add155
SH
2639 ERROR("Unsupported device type %i for %s", m, path);
2640 ret = -EINVAL;
2641 goto out;
2642 }
2c2d6c49
SH
2643
2644 major = MAJOR(sb.st_rdev);
2645 minor = MINOR(sb.st_rdev);
2646 ret = snprintf(dest, 50, "%c %lu:%lu %s", type, major, minor, mode);
72add155 2647 if (ret < 0 || ret >= 50) {
2a06d041
CB
2648 ERROR("Error on configuration value \"%c %lu:%lu %s\" (max 50 "
2649 "chars)", type, major, minor, mode);
72add155
SH
2650 ret = -ENAMETOOLONG;
2651 goto out;
2652 }
2653 ret = 0;
2654
2655out:
2656 free(path);
2657 return ret;
2658}
2659
ccb4cabe
SH
2660/*
2661 * Called from setup_limits - here we have the container's cgroup_data because
2662 * we created the cgroups
2663 */
a3926f6a
CB
2664static int cg_legacy_set_data(const char *filename, const char *value,
2665 struct cgfsng_handler_data *d)
ccb4cabe 2666{
b3646d7e 2667 char *fullpath, *p;
ab1a6cac 2668 size_t len;
1a0e70ac
CB
2669 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2670 char converted_value[50];
b3646d7e
CB
2671 struct hierarchy *h;
2672 int ret = 0;
2673 char *controller = NULL;
ccb4cabe 2674
ab1a6cac
CB
2675 len = strlen(filename);
2676 controller = alloca(len + 1);
b3646d7e 2677 strcpy(controller, filename);
ab1a6cac
CB
2678 p = strchr(controller, '.');
2679 if (p)
ccb4cabe
SH
2680 *p = '\0';
2681
c8bf519d 2682 if (strcmp("devices.allow", filename) == 0 && value[0] == '/') {
72add155
SH
2683 ret = convert_devpath(value, converted_value);
2684 if (ret < 0)
c8bf519d 2685 return ret;
72add155 2686 value = converted_value;
c8bf519d 2687 }
2688
b3646d7e
CB
2689 h = get_hierarchy(controller);
2690 if (!h) {
2691 ERROR("Failed to setup limits for the \"%s\" controller. "
2692 "The controller seems to be unused by \"cgfsng\" cgroup "
2693 "driver or not enabled on the cgroup hierarchy",
2694 controller);
d1953b26 2695 errno = ENOENT;
ab1a6cac 2696 return -ENOENT;
ccb4cabe 2697 }
b3646d7e
CB
2698
2699 fullpath = must_make_path(h->fullcgpath, filename, NULL);
2700 ret = lxc_write_to_file(fullpath, value, strlen(value), false);
2701 free(fullpath);
ccb4cabe
SH
2702 return ret;
2703}
2704
a3926f6a
CB
2705static bool __cg_legacy_setup_limits(void *hdata,
2706 struct lxc_list *cgroup_settings,
2707 bool do_devices)
ccb4cabe
SH
2708{
2709 struct cgfsng_handler_data *d = hdata;
2710 struct lxc_list *iterator, *sorted_cgroup_settings, *next;
2711 struct lxc_cgroup *cg;
ccb4cabe
SH
2712 bool ret = false;
2713
2714 if (lxc_list_empty(cgroup_settings))
2715 return true;
2716
2717 sorted_cgroup_settings = sort_cgroup_settings(cgroup_settings);
6b38e644 2718 if (!sorted_cgroup_settings)
ccb4cabe 2719 return false;
ccb4cabe 2720
ccb4cabe
SH
2721 lxc_list_for_each(iterator, sorted_cgroup_settings) {
2722 cg = iterator->elem;
2723
2724 if (do_devices == !strncmp("devices", cg->subsystem, 7)) {
a3926f6a 2725 if (cg_legacy_set_data(cg->subsystem, cg->value, d)) {
ccb4cabe
SH
2726 if (do_devices && (errno == EACCES || errno == EPERM)) {
2727 WARN("Error setting %s to %s for %s",
2728 cg->subsystem, cg->value, d->name);
2729 continue;
2730 }
2731 SYSERROR("Error setting %s to %s for %s",
2732 cg->subsystem, cg->value, d->name);
2733 goto out;
2734 }
6a628f4a 2735 DEBUG("cgroup '%s' set to '%s'", cg->subsystem, cg->value);
ccb4cabe 2736 }
ccb4cabe
SH
2737 }
2738
2739 ret = true;
6b38e644 2740 INFO("Limits for the legacy cgroup hierarchies have been setup");
ccb4cabe 2741out:
ccb4cabe
SH
2742 lxc_list_for_each_safe(iterator, sorted_cgroup_settings, next) {
2743 lxc_list_del(iterator);
2744 free(iterator);
2745 }
2746 free(sorted_cgroup_settings);
2747 return ret;
2748}
2749
a3926f6a
CB
2750static bool __cg_unified_setup_limits(void *hdata,
2751 struct lxc_list *cgroup_settings)
6b38e644
CB
2752{
2753 struct lxc_list *iterator;
2754 struct hierarchy *h = unified;
2755
2756 if (lxc_list_empty(cgroup_settings))
2757 return true;
2758
2759 if (!h)
2760 return false;
2761
2762 lxc_list_for_each(iterator, cgroup_settings) {
2763 int ret;
2764 char *fullpath;
2765 struct lxc_cgroup *cg = iterator->elem;
2766
2767 fullpath = must_make_path(h->fullcgpath, cg->subsystem, NULL);
2768 ret = lxc_write_to_file(fullpath, cg->value, strlen(cg->value), false);
2769 free(fullpath);
2770 if (ret < 0) {
2771 SYSERROR("Failed to set \"%s\" to \"%s\"", cg->subsystem, cg->value);
2772 return false;
2773 }
2774 TRACE("Set \"%s\" to \"%s\"", cg->subsystem, cg->value);
2775 }
2776
2777 INFO("Limits for the unified cgroup hierarchy have been setup");
2778 return true;
2779}
2780
2781static bool cgfsng_setup_limits(void *hdata, struct lxc_conf *conf,
2782 bool do_devices)
2783{
2784 bool bret;
2785
a3926f6a 2786 bret = __cg_legacy_setup_limits(hdata, &conf->cgroup, do_devices);
6b38e644
CB
2787 if (!bret)
2788 return false;
2789
a3926f6a 2790 return __cg_unified_setup_limits(hdata, &conf->cgroup2);
6b38e644
CB
2791}
2792
ccb4cabe
SH
2793static struct cgroup_ops cgfsng_ops = {
2794 .init = cgfsng_init,
2795 .destroy = cgfsng_destroy,
2796 .create = cgfsng_create,
2797 .enter = cgfsng_enter,
ccb4cabe 2798 .escape = cgfsng_escape,
36662416
TA
2799 .num_hierarchies = cgfsng_num_hierarchies,
2800 .get_hierarchies = cgfsng_get_hierarchies,
ccb4cabe
SH
2801 .get_cgroup = cgfsng_get_cgroup,
2802 .get = cgfsng_get,
2803 .set = cgfsng_set,
2804 .unfreeze = cgfsng_unfreeze,
2805 .setup_limits = cgfsng_setup_limits,
2806 .name = "cgroupfs-ng",
2807 .attach = cgfsng_attach,
058c1cb6 2808 .chown = cgfsng_chown,
ccb4cabe
SH
2809 .mount_cgroup = cgfsng_mount,
2810 .nrtasks = cgfsng_nrtasks,
2811 .driver = CGFSNG,
2812
2813 /* unsupported */
2814 .create_legacy = NULL,
2815};