]> git.proxmox.com Git - mirror_lxc.git/blame - src/lxc/cgroups/cgfsng.c
cgfsng: controller_found()
[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
829/*
c30b61c3
SH
830 * Return true if all of the controllers which we require have been found.
831 * The required list is freezer and anything in * lxc.cgroup.use.
ccb4cabe 832 */
457ca9aa 833static bool all_controllers_found(void)
ccb4cabe
SH
834{
835 char *p, *saveptr = NULL;
457ca9aa 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;
ccb4cabe
SH
847 p = strtok_r(NULL, ",", &saveptr)) {
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
ccb4cabe
SH
857/*
858 * Get the controllers from a mountinfo line
859 * There are other ways we could get this info. For lxcfs, field 3
860 * is /cgroup/controller-list. For cgroupfs, we could parse the mount
861 * options. But we simply assume that the mountpoint must be
862 * /sys/fs/cgroup/controller-list
863 */
a3926f6a
CB
864static char **cg_hybrid_get_controllers(char **klist, char **nlist, char *line,
865 int type)
ccb4cabe 866{
6328fd9c 867 /* the fourth field is /sys/fs/cgroup/comma-delimited-controller-list */
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
ccb4cabe
SH
880 /* note - if we change how mountinfo works, then our caller
881 * will need to verify /sys/fs/cgroup/ in this field */
c2712f64 882 if (strncmp(p, "/sys/fs/cgroup/", 15)) {
65d78313 883 CGFSNG_DEBUG("Found hierarchy not under /sys/fs/cgroup: \"%s\"\n", p);
ccb4cabe 884 return NULL;
5059aae9 885 }
d6337a5f 886
ccb4cabe 887 p += 15;
235f1815 888 p2 = strchr(p, ' ');
ccb4cabe 889 if (!p2) {
65d78313 890 CGFSNG_DEBUG("Corrupt mountinfo\n");
ccb4cabe
SH
891 return NULL;
892 }
893 *p2 = '\0';
6328fd9c 894
d6337a5f
CB
895 if (type == CGROUP_SUPER_MAGIC) {
896 /* strdup() here for v1 hierarchies. Otherwise strtok_r() will
897 * destroy mountpoints such as "/sys/fs/cgroup/cpu,cpuacct".
898 */
899 dup = strdup(p);
900 if (!dup)
901 return NULL;
902
903 for (tok = strtok_r(dup, sep, &saveptr); tok;
904 tok = strtok_r(NULL, sep, &saveptr))
905 must_append_controller(klist, nlist, &aret, tok);
906
907 free(dup);
411ac6d8 908 }
d6337a5f
CB
909 *p2 = ' ';
910 return aret;
911}
411ac6d8 912
d6337a5f
CB
913static char **cg_unified_make_empty_controller(void)
914{
915 int newentry;
916 char **aret = NULL;
917
918 newentry = append_null_to_list((void ***)&aret);
919 aret[newentry] = NULL;
920 return aret;
921}
922
923static char **cg_unified_get_controllers(const char *file)
924{
925 char *buf, *tok;
926 char *saveptr = NULL, *sep = " \t\n";
927 char **aret = NULL;
928
929 buf = read_file(file);
930 if (!buf)
411ac6d8 931 return NULL;
6328fd9c 932
d6337a5f
CB
933 for (tok = strtok_r(buf, sep, &saveptr); tok;
934 tok = strtok_r(NULL, sep, &saveptr)) {
935 int newentry;
936 char *copy;
937
938 newentry = append_null_to_list((void ***)&aret);
939 copy = must_copy_string(tok);
940 aret[newentry] = copy;
ccb4cabe
SH
941 }
942
d6337a5f 943 free(buf);
ccb4cabe
SH
944 return aret;
945}
946
d6337a5f
CB
947static struct hierarchy *add_hierarchy(char **clist, char *mountpoint,
948 char *base_cgroup, int type)
ccb4cabe
SH
949{
950 struct hierarchy *new;
951 int newentry;
952
953 new = must_alloc(sizeof(*new));
954 new->controllers = clist;
955 new->mountpoint = mountpoint;
956 new->base_cgroup = base_cgroup;
957 new->fullcgpath = NULL;
d6337a5f 958 new->version = type;
6328fd9c 959
457ca9aa
SH
960 newentry = append_null_to_list((void ***)&hierarchies);
961 hierarchies[newentry] = new;
d6337a5f 962 return new;
ccb4cabe
SH
963}
964
965/*
966 * Get a copy of the mountpoint from @line, which is a line from
967 * /proc/self/mountinfo
968 */
a3926f6a 969static char *cg_hybrid_get_mountpoint(char *line)
ccb4cabe
SH
970{
971 int i;
d6337a5f 972 char *p2;
ccb4cabe 973 size_t len;
d6337a5f
CB
974 char *p = line;
975 char *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
CB
983
984 if (strncmp(p, "/sys/fs/cgroup/", 15))
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
999/*
1000 * Given a multi-line string, return a null-terminated copy of the
1001 * current line.
1002 */
1003static char *copy_to_eol(char *p)
1004{
235f1815 1005 char *p2 = strchr(p, '\n'), *sret;
ccb4cabe
SH
1006 size_t len;
1007
1008 if (!p2)
1009 return NULL;
1010
1011 len = p2 - p;
1012 sret = must_alloc(len + 1);
1013 memcpy(sret, p, len);
1014 sret[len] = '\0';
1015 return sret;
1016}
1017
1018/*
1019 * cgline: pointer to character after the first ':' in a line in a
1020 * \n-terminated /proc/self/cgroup file. Check whether * controller c is
1021 * present.
1022 */
1023static bool controller_in_clist(char *cgline, char *c)
1024{
1025 char *tok, *saveptr = NULL, *eol, *tmp;
1026 size_t len;
1027
235f1815 1028 eol = strchr(cgline, ':');
ccb4cabe
SH
1029 if (!eol)
1030 return false;
1031
1032 len = eol - cgline;
1033 tmp = alloca(len + 1);
1034 memcpy(tmp, cgline, len);
1035 tmp[len] = '\0';
1036
1037 for (tok = strtok_r(tmp, ",", &saveptr); tok;
d6337a5f 1038 tok = strtok_r(NULL, ",", &saveptr)) {
ccb4cabe
SH
1039 if (strcmp(tok, c) == 0)
1040 return true;
1041 }
d6337a5f 1042
ccb4cabe
SH
1043 return false;
1044}
1045
1046/*
1047 * @basecginfo is a copy of /proc/$$/cgroup. Return the current
1048 * cgroup for @controller
1049 */
a3926f6a 1050static char *cg_hybrid_get_current_cgroup(char *basecginfo, char *controller, int type)
ccb4cabe
SH
1051{
1052 char *p = basecginfo;
6328fd9c 1053
d6337a5f
CB
1054 for (;;) {
1055 bool is_cgv2_base_cgroup = false;
1056
6328fd9c 1057 /* cgroup v2 entry in "/proc/<pid>/cgroup": "0::/some/path" */
d6337a5f
CB
1058 if ((type == CGROUP2_SUPER_MAGIC) && (*p == '0'))
1059 is_cgv2_base_cgroup = true;
ccb4cabe 1060
235f1815 1061 p = strchr(p, ':');
ccb4cabe
SH
1062 if (!p)
1063 return NULL;
1064 p++;
d6337a5f
CB
1065
1066 if (is_cgv2_base_cgroup || (controller && controller_in_clist(p, controller))) {
235f1815 1067 p = strchr(p, ':');
ccb4cabe
SH
1068 if (!p)
1069 return NULL;
1070 p++;
1071 return copy_to_eol(p);
1072 }
1073
235f1815 1074 p = strchr(p, '\n');
ccb4cabe
SH
1075 if (!p)
1076 return NULL;
1077 p++;
1078 }
1079}
1080
ccb4cabe
SH
1081static void must_append_string(char ***list, char *entry)
1082{
1083 int newentry = append_null_to_list((void ***)list);
1084 char *copy;
1085
1086 copy = must_copy_string(entry);
1087 (*list)[newentry] = copy;
1088}
1089
d6337a5f 1090static int get_existing_subsystems(char ***klist, char ***nlist)
ccb4cabe
SH
1091{
1092 FILE *f;
1093 char *line = NULL;
1094 size_t len = 0;
1095
d6337a5f
CB
1096 f = fopen("/proc/self/cgroup", "r");
1097 if (!f)
1098 return -1;
1099
ccb4cabe
SH
1100 while (getline(&line, &len, f) != -1) {
1101 char *p, *p2, *tok, *saveptr = NULL;
235f1815 1102 p = strchr(line, ':');
ccb4cabe
SH
1103 if (!p)
1104 continue;
1105 p++;
235f1815 1106 p2 = strchr(p, ':');
ccb4cabe
SH
1107 if (!p2)
1108 continue;
1109 *p2 = '\0';
ff8d6ee9 1110
6328fd9c
CB
1111 /* If the kernel has cgroup v2 support, then /proc/self/cgroup
1112 * contains an entry of the form:
ff8d6ee9
CB
1113 *
1114 * 0::/some/path
1115 *
6328fd9c 1116 * In this case we use "cgroup2" as controller name.
ff8d6ee9 1117 */
6328fd9c
CB
1118 if ((p2 - p) == 0) {
1119 must_append_string(klist, "cgroup2");
ff8d6ee9 1120 continue;
6328fd9c 1121 }
ff8d6ee9 1122
ccb4cabe 1123 for (tok = strtok_r(p, ",", &saveptr); tok;
d6337a5f 1124 tok = strtok_r(NULL, ",", &saveptr)) {
ccb4cabe
SH
1125 if (strncmp(tok, "name=", 5) == 0)
1126 must_append_string(nlist, tok);
1127 else
1128 must_append_string(klist, tok);
1129 }
1130 }
1131
1132 free(line);
1133 fclose(f);
d6337a5f 1134 return 0;
ccb4cabe
SH
1135}
1136
1137static void trim(char *s)
1138{
1139 size_t len = strlen(s);
2c28d76b 1140 while ((len > 1) && (s[len - 1] == '\n'))
ccb4cabe
SH
1141 s[--len] = '\0';
1142}
1143
e4aeecf5
CB
1144static void lxc_cgfsng_print_handler_data(const struct cgfsng_handler_data *d)
1145{
1146 printf("Cgroup information:\n");
1147 printf(" container name: %s\n", d->name ? d->name : "(null)");
1148 printf(" lxc.cgroup.use: %s\n", cgroup_use ? cgroup_use : "(null)");
43654d34
CB
1149 printf(" lxc.cgroup.pattern: %s\n",
1150 d->cgroup_pattern ? d->cgroup_pattern : "(null)");
1151 printf(" lxc.cgroup.dir: %s\n",
1152 d->cgroup_meta.dir ? d->cgroup_meta.dir : "(null)");
1153 printf(" cgroup: %s\n",
1154 d->container_cgroup ? d->container_cgroup : "(null)");
e4aeecf5
CB
1155}
1156
1157static void lxc_cgfsng_print_hierarchies()
ccb4cabe 1158{
a7b0cc4c 1159 struct hierarchy **it;
ccb4cabe 1160 int i;
41c33dbe 1161
457ca9aa 1162 if (!hierarchies) {
c2712f64 1163 printf(" No hierarchies found\n");
ccb4cabe
SH
1164 return;
1165 }
e4aeecf5 1166 printf(" Hierarchies:\n");
a7b0cc4c
CB
1167 for (i = 0, it = hierarchies; it && *it; it++, i++) {
1168 char **cit;
ccb4cabe 1169 int j;
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);
1189 for (k = 0, it = nlist; it && *it; it++, k++)
1190 printf("named subsystem %d: %s\n", k, *it);
41c33dbe 1191}
ccb4cabe 1192
e4aeecf5
CB
1193static void lxc_cgfsng_print_debuginfo(const struct cgfsng_handler_data *d)
1194{
1195 lxc_cgfsng_print_handler_data(d);
1196 lxc_cgfsng_print_hierarchies();
1197}
1198
ccb4cabe
SH
1199/*
1200 * At startup, parse_hierarchies finds all the info we need about
1201 * cgroup mountpoints and current cgroups, and stores it in @d.
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
d30ec4cb
SH
1213 /*
1214 * Root spawned containers escape the current cgroup, so use init's
1215 * cgroups as our base in that case.
1216 */
d6337a5f
CB
1217 will_escape = (geteuid() == 0);
1218 if (will_escape)
ccb4cabe 1219 basecginfo = read_file("/proc/1/cgroup");
d6337a5f
CB
1220 else
1221 basecginfo = read_file("/proc/self/cgroup");
ccb4cabe
SH
1222 if (!basecginfo)
1223 return false;
1224
d6337a5f
CB
1225 ret = get_existing_subsystems(&klist, &nlist);
1226 if (ret < 0) {
1227 CGFSNG_DEBUG("Failed to retrieve available cgroup v1 controllers\n");
1228 free(basecginfo);
ccb4cabe
SH
1229 return false;
1230 }
1231
d6337a5f
CB
1232 f = fopen("/proc/self/mountinfo", "r");
1233 if (!f) {
1234 CGFSNG_DEBUG("Failed to open \"/proc/self/mountinfo\"\n");
bd01b7d5 1235 free(basecginfo);
d6337a5f
CB
1236 return false;
1237 }
41c33dbe 1238
e4aeecf5
CB
1239 if (lxc_cgfsng_debug)
1240 lxc_cgfsng_print_basecg_debuginfo(basecginfo, klist, nlist);
ccb4cabe 1241
ccb4cabe 1242 while (getline(&line, &len, f) != -1) {
49ff3958 1243 int type;
d6337a5f
CB
1244 bool writeable;
1245 struct hierarchy *new;
1246 char *mountpoint = NULL, *base_cgroup = NULL;
1247 char **controller_list = NULL;
ccb4cabe 1248
49ff3958 1249 type = get_cgroup_version(line);
d6337a5f 1250 if (type == 0)
ccb4cabe
SH
1251 continue;
1252
d6337a5f 1253 if (type == CGROUP2_SUPER_MAGIC && unified)
ccb4cabe
SH
1254 continue;
1255
d6337a5f
CB
1256 if (cgroup_layout == CGROUP_LAYOUT_UNKNOWN) {
1257 if (type == CGROUP2_SUPER_MAGIC)
1258 cgroup_layout = CGROUP_LAYOUT_UNIFIED;
1259 else if (type == CGROUP_SUPER_MAGIC)
1260 cgroup_layout = CGROUP_LAYOUT_LEGACY;
1261 } else if (cgroup_layout == CGROUP_LAYOUT_UNIFIED) {
1262 if (type == CGROUP_SUPER_MAGIC)
1263 cgroup_layout = CGROUP_LAYOUT_HYBRID;
1264 } else if (cgroup_layout == CGROUP_LAYOUT_LEGACY) {
1265 if (type == CGROUP2_SUPER_MAGIC)
1266 cgroup_layout = CGROUP_LAYOUT_HYBRID;
ccb4cabe
SH
1267 }
1268
a3926f6a 1269 controller_list = cg_hybrid_get_controllers(klist, nlist, line, type);
d6337a5f
CB
1270 if (!controller_list && type == CGROUP_SUPER_MAGIC)
1271 continue;
1272
1273 if (type == CGROUP_SUPER_MAGIC)
1274 if (controller_list_is_dup(hierarchies, controller_list))
1275 goto next;
1276
a3926f6a 1277 mountpoint = cg_hybrid_get_mountpoint(line);
ccb4cabe 1278 if (!mountpoint) {
65d78313 1279 CGFSNG_DEBUG("Failed parsing mountpoint from \"%s\"\n", line);
d6337a5f 1280 goto next;
ccb4cabe
SH
1281 }
1282
d6337a5f 1283 if (type == CGROUP_SUPER_MAGIC)
a3926f6a 1284 base_cgroup = cg_hybrid_get_current_cgroup(basecginfo, controller_list[0], CGROUP_SUPER_MAGIC);
d6337a5f 1285 else
a3926f6a 1286 base_cgroup = cg_hybrid_get_current_cgroup(basecginfo, NULL, CGROUP2_SUPER_MAGIC);
ccb4cabe 1287 if (!base_cgroup) {
d6337a5f
CB
1288 CGFSNG_DEBUG("Failed to find current cgroup\n");
1289 goto next;
ccb4cabe 1290 }
6328fd9c 1291
ccb4cabe
SH
1292 trim(base_cgroup);
1293 prune_init_scope(base_cgroup);
d6337a5f 1294 if (type == CGROUP2_SUPER_MAGIC)
6328fd9c
CB
1295 writeable = test_writeable_v2(mountpoint, base_cgroup);
1296 else
1297 writeable = test_writeable_v1(mountpoint, base_cgroup);
d6337a5f
CB
1298 if (!writeable)
1299 goto next;
1300
1301 if (type == CGROUP2_SUPER_MAGIC) {
1302 char *cgv2_ctrl_path;
1303
1304 cgv2_ctrl_path = must_make_path(mountpoint, base_cgroup,
1305 "cgroup.controllers",
1306 NULL);
1307
1308 controller_list = cg_unified_get_controllers(cgv2_ctrl_path);
1309 free(cgv2_ctrl_path);
1310 if (!controller_list)
1311 controller_list = cg_unified_make_empty_controller();
ccb4cabe 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
CB
1333 if (lxc_cgfsng_debug) {
1334 printf("writeable subsystems:\n");
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
d6337a5f
CB
1347static int cg_is_pure_unified(void) {
1348
1349 int ret;
1350 struct statfs fs;
1351
1352 ret = statfs("/sys/fs/cgroup", &fs);
1353 if (ret < 0)
1354 return -ENOMEDIUM;
1355
1356 if (is_fs_type(&fs, CGROUP2_SUPER_MAGIC))
1357 return CGROUP2_SUPER_MAGIC;
1358
1359 return 0;
1360}
1361
1362/* Get current cgroup from /proc/self/cgroup for the cgroupfs v2 hierarchy. */
a3926f6a 1363static char *cg_unified_get_current_cgroup(void)
457ca9aa 1364{
d6337a5f
CB
1365 char *basecginfo;
1366 char *base_cgroup;
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. */
ccb4cabe
SH
1488 ERROR("Error getting cgroup pattern");
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)
a17f8b3f 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)
bd8ef4e4
CB
1555 WARN("%s - Failed to delete \"%s\"", strerror(errno),
1556 dirname);
ccb4cabe
SH
1557 r = -1;
1558 }
1559
a17f8b3f
CB
1560 ret = closedir(dir);
1561 if (ret < 0) {
ccb4cabe 1562 if (!r)
bd8ef4e4
CB
1563 WARN("%s - Failed to delete \"%s\"", strerror(errno),
1564 dirname);
ccb4cabe
SH
1565 r = -1;
1566 }
a17f8b3f 1567
ccb4cabe
SH
1568 return r;
1569}
1570
bd8ef4e4
CB
1571static int cgroup_rmdir(char *container_cgroup)
1572{
1573 int i;
1574
1575 if (!container_cgroup || !hierarchies)
1576 return 0;
1577
1578 for (i = 0; hierarchies[i]; i++) {
1579 int ret;
1580 struct hierarchy *h = hierarchies[i];
1581
1582 if (!h->fullcgpath)
1583 continue;
1584
1585 ret = recursive_destroy(h->fullcgpath);
1586 if (ret < 0)
1587 WARN("Failed to destroy \"%s\"", h->fullcgpath);
1588
1589 free(h->fullcgpath);
1590 h->fullcgpath = NULL;
1591 }
1592
1593 return 0;
1594}
1595
4160c3a0
CB
1596struct generic_userns_exec_data {
1597 struct cgfsng_handler_data *d;
1598 struct lxc_conf *conf;
1599 uid_t origuid; /* target uid in parent namespace */
1600 char *path;
1601};
1602
bd8ef4e4 1603static int cgroup_rmdir_wrapper(void *data)
ccb4cabe 1604{
6efacf80 1605 int ret;
4160c3a0
CB
1606 struct generic_userns_exec_data *arg = data;
1607 uid_t nsuid = (arg->conf->root_nsuid_map != NULL) ? 0 : arg->conf->init_uid;
1608 gid_t nsgid = (arg->conf->root_nsgid_map != NULL) ? 0 : arg->conf->init_gid;
ccb4cabe 1609
6efacf80
CB
1610 ret = setresgid(nsgid, nsgid, nsgid);
1611 if (ret < 0) {
1612 SYSERROR("Failed to setresgid(%d, %d, %d)", (int)nsgid,
1613 (int)nsgid, (int)nsgid);
1614 return -1;
1615 }
1616
1617 ret = setresuid(nsuid, nsuid, nsuid);
1618 if (ret < 0) {
1619 SYSERROR("Failed to setresuid(%d, %d, %d)", (int)nsuid,
1620 (int)nsuid, (int)nsuid);
1621 return -1;
1622 }
1623
1624 ret = setgroups(0, NULL);
1625 if (ret < 0 && errno != EPERM) {
1626 SYSERROR("Failed to setgroups(0, NULL)");
1627 return -1;
1628 }
ccb4cabe 1629
bd8ef4e4 1630 return cgroup_rmdir(arg->d->container_cgroup);
ccb4cabe
SH
1631}
1632
bd8ef4e4 1633static void cgfsng_destroy(void *hdata, struct lxc_conf *conf)
ccb4cabe 1634{
bd8ef4e4
CB
1635 int ret;
1636 struct cgfsng_handler_data *d = hdata;
4160c3a0
CB
1637 struct generic_userns_exec_data wrap;
1638
bd8ef4e4
CB
1639 if (!d)
1640 return;
1641
4160c3a0 1642 wrap.origuid = 0;
bd8ef4e4 1643 wrap.d = hdata;
4160c3a0
CB
1644 wrap.conf = conf;
1645
ccb4cabe 1646 if (conf && !lxc_list_empty(&conf->id_map))
bd8ef4e4
CB
1647 ret = userns_exec_1(conf, cgroup_rmdir_wrapper, &wrap,
1648 "cgroup_rmdir_wrapper");
ccb4cabe 1649 else
bd8ef4e4
CB
1650 ret = cgroup_rmdir(d->container_cgroup);
1651 if (ret < 0) {
1652 WARN("Failed to destroy cgroups");
ccb4cabe 1653 return;
ccb4cabe
SH
1654 }
1655
1656 free_handler_data(d);
1657}
1658
1659struct cgroup_ops *cgfsng_ops_init(void)
1660{
e4aeecf5
CB
1661 if (getenv("LXC_DEBUG_CGFSNG"))
1662 lxc_cgfsng_debug = true;
1663
d6337a5f 1664 if (!cg_init())
457ca9aa 1665 return NULL;
e4aeecf5 1666
ccb4cabe
SH
1667 return &cgfsng_ops;
1668}
1669
a3926f6a 1670static bool cg_unified_create_cgroup(struct hierarchy *h, char *cgname)
0c3deb94
CB
1671{
1672 char **it;
1673 size_t i, parts_len;
1674 size_t full_len = 0;
1675 char *add_controllers = NULL, *cgroup = NULL;
1676 char **parts = NULL;
1677 bool bret = false;
1678
1679 if (h->version != CGROUP2_SUPER_MAGIC)
1680 return true;
1681
1682 if (!h->controllers)
1683 return true;
1684
1685 /* For now we simply enable all controllers that we have detected by
1686 * creating a string like "+memory +pids +cpu +io".
1687 * TODO: In the near future we might want to support "-<controller>"
1688 * etc. but whether supporting semantics like this make sense will need
1689 * some thinking.
1690 */
1691 for (it = h->controllers; it && *it; it++) {
1692 full_len += strlen(*it) + 2;
1693 add_controllers = must_realloc(add_controllers, full_len + 1);
1694 if (h->controllers[0] == *it)
1695 add_controllers[0] = '\0';
1696 strcat(add_controllers, "+");
1697 strcat(add_controllers, *it);
1698 if ((it + 1) && *(it + 1))
1699 strcat(add_controllers, " ");
1700 }
1701
1702 parts = lxc_string_split(cgname, '/');
1703 if (!parts)
1704 goto on_error;
1705 parts_len = lxc_array_len((void **)parts);
1706 if (parts_len > 0)
1707 parts_len--;
1708
1709 cgroup = must_make_path(h->mountpoint, h->base_cgroup, NULL);
1710 for (i = 0; i < parts_len; i++) {
1711 int ret;
1712 char *target;
1713
1714 cgroup = must_append_path(cgroup, parts[i], NULL);
1715 target = must_make_path(cgroup, "cgroup.subtree_control", NULL);
1716 ret = lxc_write_to_file(target, add_controllers, full_len, false);
1717 free(target);
1718 if (ret < 0) {
1719 SYSERROR("Could not enable \"%s\" controllers in the "
1720 "unified cgroup \"%s\"", add_controllers, cgroup);
1721 goto on_error;
1722 }
1723 }
1724
1725 bret = true;
1726
1727on_error:
1728 lxc_free_array((void **)parts, free);
1729 free(add_controllers);
1730 free(cgroup);
1731 return bret;
1732}
1733
ccb4cabe
SH
1734static bool create_path_for_hierarchy(struct hierarchy *h, char *cgname)
1735{
0c3deb94
CB
1736 int ret;
1737
e3a3fecf 1738 h->fullcgpath = must_make_path(h->mountpoint, h->base_cgroup, cgname, NULL);
1a0e70ac 1739 if (dir_exists(h->fullcgpath)) { /* it must not already exist */
0c3deb94 1740 ERROR("cgroup \"%s\" already existed", h->fullcgpath);
d8da679e 1741 return false;
6f9584d8 1742 }
0c3deb94 1743
a3926f6a 1744 if (!cg_legacy_handle_cpuset_hierarchy(h, cgname)) {
0c3deb94
CB
1745 ERROR("Failed to handle cgroupfs v1 cpuset controller");
1746 return false;
1747 }
1748
1749 ret = mkdir_p(h->fullcgpath, 0755);
1750 if (ret < 0) {
1751 ERROR("Failed to create cgroup \"%s\"", h->fullcgpath);
e3a3fecf 1752 return false;
6f9584d8 1753 }
0c3deb94 1754
a3926f6a 1755 return cg_unified_create_cgroup(h, cgname);
ccb4cabe
SH
1756}
1757
1758static void remove_path_for_hierarchy(struct hierarchy *h, char *cgname)
1759{
1760 if (rmdir(h->fullcgpath) < 0)
1761 SYSERROR("Failed to clean up cgroup %s from failed creation attempt", h->fullcgpath);
1762 free(h->fullcgpath);
1763 h->fullcgpath = NULL;
1764}
1765
1766/*
d30ec4cb 1767 * Try to create the same cgroup in all hierarchies.
ccb4cabe
SH
1768 * Start with cgroup_pattern; next cgroup_pattern-1, -2, ..., -999
1769 */
1770static inline bool cgfsng_create(void *hdata)
1771{
bb30b52a 1772 int i;
ccb4cabe 1773 size_t len;
0c3deb94 1774 char *container_cgroup, *offset, *tmp;
7d531e9b
CB
1775 int idx = 0;
1776 struct cgfsng_handler_data *d = hdata;
ccb4cabe
SH
1777
1778 if (!d)
1779 return false;
43654d34 1780
ccb4cabe
SH
1781 if (d->container_cgroup) {
1782 WARN("cgfsng_create called a second time");
1783 return false;
1784 }
1785
43654d34 1786 if (d->cgroup_meta.dir)
7d531e9b 1787 tmp = lxc_string_join("/", (const char *[]){d->cgroup_meta.dir, d->name, NULL}, false);
43654d34
CB
1788 else
1789 tmp = lxc_string_replace("%n", d->name, d->cgroup_pattern);
ccb4cabe
SH
1790 if (!tmp) {
1791 ERROR("Failed expanding cgroup name pattern");
1792 return false;
1793 }
1a0e70ac 1794 len = strlen(tmp) + 5; /* leave room for -NNN\0 */
0c3deb94
CB
1795 container_cgroup = must_alloc(len);
1796 strcpy(container_cgroup, tmp);
ccb4cabe 1797 free(tmp);
0c3deb94 1798 offset = container_cgroup + len - 5;
ccb4cabe
SH
1799
1800again:
95adfe93
SH
1801 if (idx == 1000) {
1802 ERROR("Too many conflicting cgroup names");
ccb4cabe 1803 goto out_free;
95adfe93 1804 }
66b66624 1805 if (idx) {
bb30b52a
CB
1806 int ret;
1807
66b66624
CB
1808 ret = snprintf(offset, 5, "-%d", idx);
1809 if (ret < 0 || (size_t)ret >= 5) {
1810 FILE *f = fopen("/dev/null", "w");
97ebced3 1811 if (f) {
66b66624
CB
1812 fprintf(f, "Workaround for GCC7 bug: "
1813 "https://gcc.gnu.org/bugzilla/"
1814 "show_bug.cgi?id=78969");
1815 fclose(f);
1816 }
1817 }
1818 }
457ca9aa 1819 for (i = 0; hierarchies[i]; i++) {
0c3deb94 1820 if (!create_path_for_hierarchy(hierarchies[i], container_cgroup)) {
ccb4cabe 1821 int j;
1a0e70ac 1822 ERROR("Failed to create \"%s\"", hierarchies[i]->fullcgpath);
457ca9aa
SH
1823 free(hierarchies[i]->fullcgpath);
1824 hierarchies[i]->fullcgpath = NULL;
ccb4cabe 1825 for (j = 0; j < i; j++)
0c3deb94 1826 remove_path_for_hierarchy(hierarchies[j], container_cgroup);
ccb4cabe
SH
1827 idx++;
1828 goto again;
1829 }
1830 }
1831 /* Done */
0c3deb94 1832 d->container_cgroup = container_cgroup;
ccb4cabe
SH
1833 return true;
1834
1835out_free:
0c3deb94 1836 free(container_cgroup);
ccb4cabe
SH
1837 return false;
1838}
1839
ccb4cabe
SH
1840static bool cgfsng_enter(void *hdata, pid_t pid)
1841{
ccb4cabe
SH
1842 char pidstr[25];
1843 int i, len;
1844
1845 len = snprintf(pidstr, 25, "%d", pid);
1846 if (len < 0 || len > 25)
1847 return false;
1848
457ca9aa
SH
1849 for (i = 0; hierarchies[i]; i++) {
1850 char *fullpath = must_make_path(hierarchies[i]->fullcgpath,
ccb4cabe
SH
1851 "cgroup.procs", NULL);
1852 if (lxc_write_to_file(fullpath, pidstr, len, false) != 0) {
d3b00a8f 1853 SYSERROR("Failed to enter %s", fullpath);
ccb4cabe
SH
1854 free(fullpath);
1855 return false;
1856 }
1857 free(fullpath);
1858 }
1859
1860 return true;
1861}
1862
6efacf80
CB
1863static int chowmod(char *path, uid_t chown_uid, gid_t chown_gid,
1864 mode_t chmod_mode)
1865{
1866 int ret;
1867
1868 ret = chown(path, chown_uid, chown_gid);
1869 if (ret < 0) {
1870 WARN("%s - Failed to chown(%s, %d, %d)", strerror(errno), path,
1871 (int)chown_uid, (int)chown_gid);
1872 return -1;
1873 }
1874
1875 ret = chmod(path, chmod_mode);
1876 if (ret < 0) {
1877 WARN("%s - Failed to chmod(%s, %d)", strerror(errno), path,
1878 (int)chmod_mode);
1879 return -1;
1880 }
1881
1882 return 0;
1883}
1884
1885/* chgrp the container cgroups to container group. We leave
c0888dfe
SH
1886 * the container owner as cgroup owner. So we must make the
1887 * directories 775 so that the container can create sub-cgroups.
43647298
SH
1888 *
1889 * Also chown the tasks and cgroup.procs files. Those may not
1890 * exist depending on kernel version.
c0888dfe 1891 */
ccb4cabe
SH
1892static int chown_cgroup_wrapper(void *data)
1893{
6efacf80 1894 int i, ret;
4160c3a0
CB
1895 uid_t destuid;
1896 struct generic_userns_exec_data *arg = data;
1897 uid_t nsuid = (arg->conf->root_nsuid_map != NULL) ? 0 : arg->conf->init_uid;
1898 gid_t nsgid = (arg->conf->root_nsgid_map != NULL) ? 0 : arg->conf->init_gid;
ccb4cabe 1899
6efacf80
CB
1900 ret = setresgid(nsgid, nsgid, nsgid);
1901 if (ret < 0) {
1902 SYSERROR("Failed to setresgid(%d, %d, %d)",
1903 (int)nsgid, (int)nsgid, (int)nsgid);
1904 return -1;
1905 }
1906
1907 ret = setresuid(nsuid, nsuid, nsuid);
1908 if (ret < 0) {
1909 SYSERROR("Failed to setresuid(%d, %d, %d)",
1910 (int)nsuid, (int)nsuid, (int)nsuid);
1911 return -1;
1912 }
1913
1914 ret = setgroups(0, NULL);
1915 if (ret < 0 && errno != EPERM) {
1916 SYSERROR("Failed to setgroups(0, NULL)");
1917 return -1;
1918 }
ccb4cabe
SH
1919
1920 destuid = get_ns_uid(arg->origuid);
1921
457ca9aa 1922 for (i = 0; hierarchies[i]; i++) {
6efacf80
CB
1923 char *fullpath;
1924 char *path = hierarchies[i]->fullcgpath;
43647298 1925
63e42fee 1926 ret = chowmod(path, destuid, nsgid, 0775);
6efacf80 1927 if (ret < 0)
ccb4cabe 1928 return -1;
c0888dfe 1929
6efacf80
CB
1930 /* Failures to chown() these are inconvenient but not
1931 * detrimental We leave these owned by the container launcher,
1932 * so that container root can write to the files to attach. We
1933 * chmod() them 664 so that container systemd can write to the
1934 * files (which systemd in wily insists on doing).
ab8f5424 1935 */
6efacf80
CB
1936
1937 if (hierarchies[i]->version == CGROUP_SUPER_MAGIC) {
1938 fullpath = must_make_path(path, "tasks", NULL);
1939 (void)chowmod(fullpath, destuid, nsgid, 0664);
1940 free(fullpath);
1941 }
43647298
SH
1942
1943 fullpath = must_make_path(path, "cgroup.procs", NULL);
6efacf80 1944 (void)chowmod(fullpath, destuid, 0, 0664);
ccb4cabe 1945 free(fullpath);
0e17357c 1946
d6337a5f 1947 if (hierarchies[i]->version != CGROUP2_SUPER_MAGIC)
0e17357c
CB
1948 continue;
1949
1950 fullpath = must_make_path(path, "cgroup.subtree_control", NULL);
6efacf80 1951 (void)chowmod(fullpath, destuid, nsgid, 0664);
0e17357c
CB
1952 free(fullpath);
1953
1954 fullpath = must_make_path(path, "cgroup.threads", NULL);
6efacf80 1955 (void)chowmod(fullpath, destuid, nsgid, 0664);
0e17357c 1956 free(fullpath);
ccb4cabe
SH
1957 }
1958
1959 return 0;
1960}
1961
058c1cb6 1962static bool cgfsng_chown(void *hdata, struct lxc_conf *conf)
ccb4cabe
SH
1963{
1964 struct cgfsng_handler_data *d = hdata;
4160c3a0 1965 struct generic_userns_exec_data wrap;
ccb4cabe
SH
1966
1967 if (!d)
1968 return false;
1969
1970 if (lxc_list_empty(&conf->id_map))
1971 return true;
1972
ccb4cabe 1973 wrap.origuid = geteuid();
4160c3a0
CB
1974 wrap.path = NULL;
1975 wrap.d = d;
1976 wrap.conf = conf;
ccb4cabe 1977
c9b7c33e
CB
1978 if (userns_exec_1(conf, chown_cgroup_wrapper, &wrap,
1979 "chown_cgroup_wrapper") < 0) {
ccb4cabe
SH
1980 ERROR("Error requesting cgroup chown in new namespace");
1981 return false;
1982 }
1983
1984 return true;
1985}
1986
8aa1044f
SH
1987/*
1988 * We've safe-mounted a tmpfs as parent, so we don't need to protect against
1989 * symlinks any more - just use mount
1990 */
1991
1992/* mount cgroup-full if requested */
1993static int mount_cgroup_full(int type, struct hierarchy *h, char *dest,
a3926f6a 1994 char *container_cgroup)
8aa1044f
SH
1995{
1996 if (type < LXC_AUTO_CGROUP_FULL_RO || type > LXC_AUTO_CGROUP_FULL_MIXED)
1997 return 0;
1998 if (mount(h->mountpoint, dest, "cgroup", MS_BIND, NULL) < 0) {
1999 SYSERROR("Error bind-mounting %s cgroup onto %s", h->mountpoint,
2000 dest);
2001 return -1;
2002 }
2003 if (type != LXC_AUTO_CGROUP_FULL_RW) {
5b6f9369
SH
2004 unsigned long flags = MS_BIND | MS_NOSUID | MS_NOEXEC | MS_NODEV |
2005 MS_REMOUNT | MS_RDONLY;
2006 if (mount(NULL, dest, "cgroup", flags, NULL) < 0) {
8aa1044f
SH
2007 SYSERROR("Error remounting %s readonly", dest);
2008 return -1;
2009 }
2010 }
2011
2012 INFO("Bind mounted %s onto %s", h->mountpoint, dest);
2013 if (type != LXC_AUTO_CGROUP_FULL_MIXED)
2014 return 0;
2015
2016 /* mount just the container path rw */
2017 char *source = must_make_path(h->mountpoint, h->base_cgroup, container_cgroup, NULL);
5b6f9369 2018 char *rwpath = must_make_path(dest, h->base_cgroup, container_cgroup, NULL);
8aa1044f 2019 if (mount(source, rwpath, "cgroup", MS_BIND, NULL) < 0)
13277ec4 2020 WARN("Failed to mount %s read-write: %s", rwpath,
2021 strerror(errno));
8aa1044f
SH
2022 INFO("Made %s read-write", rwpath);
2023 free(rwpath);
2024 free(source);
2025 return 0;
2026}
2027
2028/* cgroup-full:* is done, no need to create subdirs */
2029static bool cg_mount_needs_subdirs(int type)
2030{
2031 if (type >= LXC_AUTO_CGROUP_FULL_RO)
2032 return false;
a3926f6a 2033
8aa1044f
SH
2034 return true;
2035}
2036
886cac86
CB
2037/* After $rootfs/sys/fs/container/controller/the/cg/path has been created,
2038 * remount controller ro if needed and bindmount the cgroupfs onto
2039 * controll/the/cg/path.
8aa1044f 2040 */
a3926f6a
CB
2041static int do_secondstage_mounts_if_needed(int type, struct hierarchy *h,
2042 char *controllerpath, char *cgpath,
2043 const char *container_cgroup)
8aa1044f 2044{
5285689c 2045 int ret, remount_flags;
886cac86
CB
2046 char *sourcepath;
2047 int flags = MS_BIND;
2048
8aa1044f 2049 if (type == LXC_AUTO_CGROUP_RO || type == LXC_AUTO_CGROUP_MIXED) {
886cac86
CB
2050 ret = mount(controllerpath, controllerpath, "cgroup", MS_BIND, NULL);
2051 if (ret < 0) {
2052 SYSERROR("Failed to bind mount \"%s\" onto \"%s\"",
2053 controllerpath, controllerpath);
8aa1044f
SH
2054 return -1;
2055 }
886cac86 2056
5285689c
CB
2057 remount_flags = add_required_remount_flags(controllerpath,
2058 controllerpath,
2059 flags | MS_REMOUNT);
886cac86
CB
2060 ret = mount(controllerpath, controllerpath, "cgroup",
2061 MS_REMOUNT | MS_BIND | MS_RDONLY, NULL);
2062 if (ret < 0) {
2063 SYSERROR("Failed to remount \"%s\" ro", controllerpath);
8aa1044f
SH
2064 return -1;
2065 }
886cac86 2066
8aa1044f
SH
2067 INFO("Remounted %s read-only", controllerpath);
2068 }
886cac86
CB
2069
2070 sourcepath = must_make_path(h->mountpoint, h->base_cgroup,
2071 container_cgroup, NULL);
8aa1044f
SH
2072 if (type == LXC_AUTO_CGROUP_RO)
2073 flags |= MS_RDONLY;
886cac86
CB
2074
2075 ret = mount(sourcepath, cgpath, "cgroup", flags, NULL);
2076 if (ret < 0) {
2077 SYSERROR("Failed to mount \"%s\" onto \"%s\"", h->controllers[0], cgpath);
8aa1044f 2078 free(sourcepath);
8aa1044f
SH
2079 return -1;
2080 }
886cac86 2081 INFO("Mounted \"%s\" onto \"%s\"", h->controllers[0], cgpath);
f8c40ffa
L
2082
2083 if (flags & MS_RDONLY) {
5285689c
CB
2084 remount_flags = add_required_remount_flags(sourcepath, cgpath,
2085 flags | MS_REMOUNT);
2086 ret = mount(sourcepath, cgpath, "cgroup", remount_flags, NULL);
886cac86
CB
2087 if (ret < 0) {
2088 SYSERROR("Failed to remount \"%s\" ro", cgpath);
f8c40ffa 2089 free(sourcepath);
f8c40ffa
L
2090 return -1;
2091 }
5285689c 2092 INFO("Remounted %s read-only", cgpath);
f8c40ffa
L
2093 }
2094
8aa1044f 2095 free(sourcepath);
886cac86 2096 INFO("Completed second stage cgroup automounts for \"%s\"", cgpath);
8aa1044f
SH
2097 return 0;
2098}
2099
5285689c
CB
2100static int cg_mount_in_cgroup_namespace(int type, struct hierarchy *h,
2101 const char *controllerpath)
b635e92d
CB
2102{
2103 int ret;
2104 char *controllers = NULL;
a760603e
CB
2105 char *fstype = "cgroup2";
2106 unsigned long flags = 0;
b635e92d 2107
a760603e
CB
2108 flags |= MS_NOSUID;
2109 flags |= MS_NOEXEC;
2110 flags |= MS_NODEV;
2111 flags |= MS_RELATIME;
2112
2113 if (type == LXC_AUTO_CGROUP_RO || type == LXC_AUTO_CGROUP_FULL_RO)
2114 flags |= MS_RDONLY;
2115
d6337a5f 2116 if (h->version != CGROUP2_SUPER_MAGIC) {
a760603e
CB
2117 controllers = lxc_string_join(",", (const char **)h->controllers, false);
2118 if (!controllers)
2119 return -ENOMEM;
2120 fstype = "cgroup";
b635e92d
CB
2121 }
2122
a760603e 2123 ret = mount("cgroup", controllerpath, fstype, flags, controllers);
b635e92d
CB
2124 free(controllers);
2125 if (ret < 0) {
a760603e 2126 SYSERROR("Failed to mount %s with cgroup filesystem type %s", controllerpath, fstype);
b635e92d
CB
2127 return -1;
2128 }
2129
a760603e 2130 DEBUG("Mounted %s with cgroup filesystem type %s", controllerpath, fstype);
b635e92d
CB
2131 return 0;
2132}
2133
ccb4cabe
SH
2134static bool cgfsng_mount(void *hdata, const char *root, int type)
2135{
3f69fb12 2136 int i, ret;
8aa1044f
SH
2137 char *tmpfspath = NULL;
2138 bool retval = false;
b635e92d
CB
2139 struct lxc_handler *handler = hdata;
2140 struct cgfsng_handler_data *d = handler->cgroup_data;
3f69fb12 2141 bool has_cgns = false, wants_force_mount = false;
8aa1044f
SH
2142
2143 if ((type & LXC_AUTO_CGROUP_MASK) == 0)
2144 return true;
2145
3f69fb12
SY
2146 if (type & LXC_AUTO_CGROUP_FORCE) {
2147 type &= ~LXC_AUTO_CGROUP_FORCE;
2148 wants_force_mount = true;
2149 }
b635e92d 2150
3f69fb12
SY
2151 if (!wants_force_mount){
2152 if (!lxc_list_empty(&handler->conf->keepcaps))
2153 wants_force_mount = !in_caplist(CAP_SYS_ADMIN, &handler->conf->keepcaps);
2154 else
2155 wants_force_mount = in_caplist(CAP_SYS_ADMIN, &handler->conf->caps);
2156 }
8aa1044f 2157
3f69fb12
SY
2158 has_cgns = cgns_supported();
2159 if (has_cgns && !wants_force_mount)
2160 return true;
8aa1044f
SH
2161
2162 if (type == LXC_AUTO_CGROUP_NOSPEC)
2163 type = LXC_AUTO_CGROUP_MIXED;
2164 else if (type == LXC_AUTO_CGROUP_FULL_NOSPEC)
2165 type = LXC_AUTO_CGROUP_FULL_MIXED;
2166
2167 /* Mount tmpfs */
3f69fb12
SY
2168 tmpfspath = must_make_path(root, "/sys/fs/cgroup", NULL);
2169 ret = safe_mount("cgroup_root", tmpfspath, "tmpfs",
2170 MS_NOSUID | MS_NODEV | MS_NOEXEC | MS_RELATIME,
2171 "size=10240k,mode=755", root);
2172 if (ret < 0)
2173 goto on_error;
8aa1044f 2174
457ca9aa 2175 for (i = 0; hierarchies[i]; i++) {
8aa1044f 2176 char *controllerpath, *path2;
457ca9aa 2177 struct hierarchy *h = hierarchies[i];
8aa1044f 2178 char *controller = strrchr(h->mountpoint, '/');
8aa1044f
SH
2179
2180 if (!controller)
2181 continue;
2182 controller++;
2183 controllerpath = must_make_path(tmpfspath, controller, NULL);
2184 if (dir_exists(controllerpath)) {
2185 free(controllerpath);
2186 continue;
2187 }
3f69fb12
SY
2188 ret = mkdir(controllerpath, 0755);
2189 if (ret < 0) {
8aa1044f
SH
2190 SYSERROR("Error creating cgroup path: %s", controllerpath);
2191 free(controllerpath);
3f69fb12 2192 goto on_error;
8aa1044f 2193 }
b635e92d 2194
3f69fb12 2195 if (has_cgns && wants_force_mount) {
b635e92d
CB
2196 /* If cgroup namespaces are supported but the container
2197 * will not have CAP_SYS_ADMIN after it has started we
2198 * need to mount the cgroups manually.
2199 */
3f69fb12 2200 ret = cg_mount_in_cgroup_namespace(type, h, controllerpath);
b635e92d 2201 free(controllerpath);
3f69fb12
SY
2202 if (ret < 0)
2203 goto on_error;
2204
b635e92d
CB
2205 continue;
2206 }
2207
3f69fb12
SY
2208 ret = mount_cgroup_full(type, h, controllerpath, d->container_cgroup);
2209 if (ret < 0) {
8aa1044f 2210 free(controllerpath);
3f69fb12 2211 goto on_error;
8aa1044f 2212 }
3f69fb12 2213
8aa1044f
SH
2214 if (!cg_mount_needs_subdirs(type)) {
2215 free(controllerpath);
2216 continue;
2217 }
3f69fb12
SY
2218
2219 path2 = must_make_path(controllerpath, h->base_cgroup,
2220 d->container_cgroup, NULL);
2221 ret = mkdir_p(path2, 0755);
2222 if (ret < 0) {
8aa1044f 2223 free(controllerpath);
8e0c6620 2224 free(path2);
3f69fb12 2225 goto on_error;
8aa1044f 2226 }
2f62fb00 2227
3f69fb12
SY
2228 ret = do_secondstage_mounts_if_needed(
2229 type, h, controllerpath, path2, d->container_cgroup);
8aa1044f
SH
2230 free(controllerpath);
2231 free(path2);
3f69fb12
SY
2232 if (ret < 0)
2233 goto on_error;
8aa1044f
SH
2234 }
2235 retval = true;
2236
3f69fb12 2237on_error:
8aa1044f
SH
2238 free(tmpfspath);
2239 return retval;
ccb4cabe
SH
2240}
2241
2242static int recursive_count_nrtasks(char *dirname)
2243{
74f96976 2244 struct dirent *direntp;
ccb4cabe
SH
2245 DIR *dir;
2246 int count = 0, ret;
2247 char *path;
2248
2249 dir = opendir(dirname);
2250 if (!dir)
2251 return 0;
2252
74f96976 2253 while ((direntp = readdir(dir))) {
ccb4cabe
SH
2254 struct stat mystat;
2255
2256 if (!direntp)
2257 break;
2258
2259 if (!strcmp(direntp->d_name, ".") ||
2260 !strcmp(direntp->d_name, ".."))
2261 continue;
2262
2263 path = must_make_path(dirname, direntp->d_name, NULL);
2264
2265 if (lstat(path, &mystat))
2266 goto next;
2267
2268 if (!S_ISDIR(mystat.st_mode))
2269 goto next;
2270
2271 count += recursive_count_nrtasks(path);
2272next:
2273 free(path);
2274 }
2275
2276 path = must_make_path(dirname, "cgroup.procs", NULL);
2277 ret = lxc_count_file_lines(path);
2278 if (ret != -1)
2279 count += ret;
2280 free(path);
2281
2282 (void) closedir(dir);
2283
2284 return count;
2285}
2286
2287static int cgfsng_nrtasks(void *hdata) {
2288 struct cgfsng_handler_data *d = hdata;
2289 char *path;
2290 int count;
2291
457ca9aa 2292 if (!d || !d->container_cgroup || !hierarchies)
ccb4cabe 2293 return -1;
a3926f6a 2294
457ca9aa 2295 path = must_make_path(hierarchies[0]->fullcgpath, NULL);
ccb4cabe
SH
2296 count = recursive_count_nrtasks(path);
2297 free(path);
2298 return count;
2299}
2300
2301/* Only root needs to escape to the cgroup of its init */
7103fe6f 2302static bool cgfsng_escape()
ccb4cabe 2303{
ccb4cabe
SH
2304 int i;
2305
2306 if (geteuid())
2307 return true;
2308
457ca9aa
SH
2309 for (i = 0; hierarchies[i]; i++) {
2310 char *fullpath = must_make_path(hierarchies[i]->mountpoint,
2311 hierarchies[i]->base_cgroup,
ccb4cabe
SH
2312 "cgroup.procs", NULL);
2313 if (lxc_write_to_file(fullpath, "0", 2, false) != 0) {
d3b00a8f 2314 SYSERROR("Failed to escape to %s", fullpath);
ccb4cabe 2315 free(fullpath);
6df334d1 2316 return false;
ccb4cabe
SH
2317 }
2318 free(fullpath);
2319 }
2320
6df334d1 2321 return true;
ccb4cabe
SH
2322}
2323
36662416
TA
2324static int cgfsng_num_hierarchies(void)
2325{
2326 int i;
2327
2328 for (i = 0; hierarchies[i]; i++)
2329 ;
2330
2331 return i;
2332}
2333
2334static bool cgfsng_get_hierarchies(int n, char ***out)
2335{
2336 int i;
2337
2338 /* sanity check n */
6b38e644 2339 for (i = 0; i < n; i++)
36662416
TA
2340 if (!hierarchies[i])
2341 return false;
36662416
TA
2342
2343 *out = hierarchies[i]->controllers;
2344
2345 return true;
2346}
2347
ccb4cabe
SH
2348#define THAWED "THAWED"
2349#define THAWED_LEN (strlen(THAWED))
2350
d6337a5f
CB
2351/* TODO: If the unified cgroup hierarchy grows a freezer controller this needs
2352 * to be adapted.
2353 */
ccb4cabe
SH
2354static bool cgfsng_unfreeze(void *hdata)
2355{
d6337a5f 2356 int ret;
ccb4cabe 2357 char *fullpath;
d6337a5f 2358 struct hierarchy *h;
ccb4cabe 2359
d6337a5f 2360 h = get_hierarchy("freezer");
457ca9aa 2361 if (!h)
ccb4cabe 2362 return false;
d6337a5f 2363
ccb4cabe 2364 fullpath = must_make_path(h->fullcgpath, "freezer.state", NULL);
d6337a5f 2365 ret = lxc_write_to_file(fullpath, THAWED, THAWED_LEN, false);
ccb4cabe 2366 free(fullpath);
d6337a5f
CB
2367 if (ret < 0)
2368 return false;
2369
ccb4cabe
SH
2370 return true;
2371}
2372
2373static const char *cgfsng_get_cgroup(void *hdata, const char *subsystem)
2374{
d6337a5f
CB
2375 struct hierarchy *h;
2376
2377 h = get_hierarchy(subsystem);
ccb4cabe
SH
2378 if (!h)
2379 return NULL;
2380
371f834d
SH
2381 return h->fullcgpath ? h->fullcgpath + strlen(h->mountpoint) : NULL;
2382}
2383
2384/*
2385 * Given a cgroup path returned from lxc_cmd_get_cgroup_path, build a
2386 * full path, which must be freed by the caller.
2387 */
2388static char *build_full_cgpath_from_monitorpath(struct hierarchy *h,
2389 const char *inpath,
2390 const char *filename)
2391{
371f834d 2392 return must_make_path(h->mountpoint, inpath, filename, NULL);
ccb4cabe
SH
2393}
2394
c2aed66d
CB
2395/* Technically, we're always at a delegation boundary here. (This is especially
2396 * true when cgroup namespaces are available.) The reasoning is that in order
2397 * for us to have been able to start a container in the first place the root
2398 * cgroup must have been a leaf node. Now, either the container's init system
2399 * has populated the cgroup and kept it as a leaf node or it has created
2400 * subtrees. In the former case we will simply attach to the leaf node we
2401 * created when we started the container in the latter case we create our own
2402 * cgroup for the attaching process.
2403 */
a3926f6a
CB
2404static int __cg_unified_attach(const struct hierarchy *h, const char *name,
2405 const char *lxcpath, const char *pidstr,
2406 size_t pidstr_len, const char *controller)
c2aed66d
CB
2407{
2408 int ret;
2409 size_t len;
2410 int fret = -1, idx = 0;
2411 char *base_path = NULL, *container_cgroup = NULL, *full_path = NULL;
2412
2413 container_cgroup = lxc_cmd_get_cgroup_path(name, lxcpath, controller);
2414 /* not running */
2415 if (!container_cgroup)
2416 return 0;
2417
2418 base_path = must_make_path(h->mountpoint, container_cgroup, NULL);
2419 full_path = must_make_path(base_path, "cgroup.procs", NULL);
2420 /* cgroup is populated */
2421 ret = lxc_write_to_file(full_path, pidstr, pidstr_len, false);
2422 if (ret < 0 && errno != EBUSY)
2423 goto on_error;
2424
2425 if (ret == 0)
2426 goto on_success;
2427
2428 free(full_path);
2429
2430 len = strlen(base_path) + sizeof("/lxc-1000") - 1 +
2431 sizeof("/cgroup-procs") - 1;
2432 full_path = must_alloc(len + 1);
2433 do {
2434 if (idx)
2435 ret = snprintf(full_path, len + 1, "%s/lxc-%d",
2436 base_path, idx);
2437 else
2438 ret = snprintf(full_path, len + 1, "%s/lxc", base_path);
2439 if (ret < 0 || (size_t)ret >= len + 1)
2440 goto on_error;
2441
2442 ret = mkdir_p(full_path, 0755);
2443 if (ret < 0 && errno != EEXIST)
2444 goto on_error;
2445
2446 strcat(full_path, "/cgroup.procs");
2447 ret = lxc_write_to_file(full_path, pidstr, len, false);
2448 if (ret == 0)
2449 goto on_success;
2450
2451 /* this is a non-leaf node */
2452 if (errno != EBUSY)
2453 goto on_error;
2454
2455 } while (++idx > 0 && idx < 1000);
2456
2457on_success:
2458 if (idx < 1000)
2459 fret = 0;
2460
2461on_error:
2462 free(base_path);
2463 free(container_cgroup);
2464 free(full_path);
2465
2466 return fret;
2467}
2468
ccb4cabe
SH
2469static bool cgfsng_attach(const char *name, const char *lxcpath, pid_t pid)
2470{
c2aed66d 2471 int i, len, ret;
ccb4cabe 2472 char pidstr[25];
ccb4cabe
SH
2473
2474 len = snprintf(pidstr, 25, "%d", pid);
2475 if (len < 0 || len > 25)
2476 return false;
2477
457ca9aa 2478 for (i = 0; hierarchies[i]; i++) {
c2aed66d
CB
2479 char *path;
2480 char *fullpath = NULL;
457ca9aa 2481 struct hierarchy *h = hierarchies[i];
ccb4cabe 2482
c2aed66d 2483 if (h->version == CGROUP2_SUPER_MAGIC) {
a3926f6a
CB
2484 ret = __cg_unified_attach(h, name, lxcpath, pidstr, len,
2485 h->controllers[0]);
c2aed66d
CB
2486 if (ret < 0)
2487 return false;
2488
2489 continue;
2490 }
2491
ccb4cabe 2492 path = lxc_cmd_get_cgroup_path(name, lxcpath, h->controllers[0]);
c2aed66d
CB
2493 /* not running */
2494 if (!path)
ccb4cabe
SH
2495 continue;
2496
371f834d 2497 fullpath = build_full_cgpath_from_monitorpath(h, path, "cgroup.procs");
c2aed66d
CB
2498 ret = lxc_write_to_file(fullpath, pidstr, len, false);
2499 if (ret < 0) {
ccb4cabe
SH
2500 SYSERROR("Failed to attach %d to %s", (int)pid, fullpath);
2501 free(fullpath);
ccb4cabe
SH
2502 return false;
2503 }
ccb4cabe
SH
2504 free(fullpath);
2505 }
2506
ccb4cabe
SH
2507 return true;
2508}
2509
2510/*
2511 * Called externally (i.e. from 'lxc-cgroup') to query cgroup limits.
2512 * Here we don't have a cgroup_data set up, so we ask the running
2513 * container through the commands API for the cgroup path
2514 */
0069cc61
CB
2515static int cgfsng_get(const char *filename, char *value, size_t len,
2516 const char *name, const char *lxcpath)
ccb4cabe 2517{
ccb4cabe 2518 int ret = -1;
0069cc61
CB
2519 size_t controller_len;
2520 char *controller, *p, *path;
2521 struct hierarchy *h;
ccb4cabe 2522
0069cc61
CB
2523 controller_len = strlen(filename);
2524 controller = alloca(controller_len + 1);
2525 strcpy(controller, filename);
2526 p = strchr(controller, '.');
2527 if (p)
ccb4cabe
SH
2528 *p = '\0';
2529
0069cc61
CB
2530 path = lxc_cmd_get_cgroup_path(name, lxcpath, controller);
2531 /* not running */
2532 if (!path)
ccb4cabe
SH
2533 return -1;
2534
0069cc61 2535 h = get_hierarchy(controller);
ccb4cabe 2536 if (h) {
0069cc61
CB
2537 char *fullpath;
2538
2539 fullpath = build_full_cgpath_from_monitorpath(h, path, filename);
ccb4cabe
SH
2540 ret = lxc_read_from_file(fullpath, value, len);
2541 free(fullpath);
2542 }
ccb4cabe
SH
2543 free(path);
2544
2545 return ret;
2546}
2547
2548/*
2549 * Called externally (i.e. from 'lxc-cgroup') to set new cgroup limits.
2550 * Here we don't have a cgroup_data set up, so we ask the running
2551 * container through the commands API for the cgroup path
2552 */
87777968
CB
2553static int cgfsng_set(const char *filename, const char *value, const char *name,
2554 const char *lxcpath)
ccb4cabe 2555{
ccb4cabe 2556 int ret = -1;
87777968
CB
2557 size_t controller_len;
2558 char *controller, *p, *path;
2559 struct hierarchy *h;
ccb4cabe 2560
87777968
CB
2561 controller_len = strlen(filename);
2562 controller = alloca(controller_len + 1);
2563 strcpy(controller, filename);
2564 p = strchr(controller, '.');
2565 if (p)
ccb4cabe
SH
2566 *p = '\0';
2567
87777968
CB
2568 path = lxc_cmd_get_cgroup_path(name, lxcpath, controller);
2569 /* not running */
2570 if (!path)
ccb4cabe
SH
2571 return -1;
2572
87777968 2573 h = get_hierarchy(controller);
ccb4cabe 2574 if (h) {
87777968
CB
2575 char *fullpath;
2576
2577 fullpath = build_full_cgpath_from_monitorpath(h, path, filename);
ccb4cabe
SH
2578 ret = lxc_write_to_file(fullpath, value, strlen(value), false);
2579 free(fullpath);
2580 }
ccb4cabe
SH
2581 free(path);
2582
2583 return ret;
2584}
2585
72add155
SH
2586/*
2587 * take devices cgroup line
2588 * /dev/foo rwx
2589 * and convert it to a valid
2590 * type major:minor mode
2591 * line. Return <0 on error. Dest is a preallocated buffer
2592 * long enough to hold the output.
2593 */
2594static int convert_devpath(const char *invalue, char *dest)
2595{
2a06d041
CB
2596 int n_parts;
2597 char *p, *path, type;
72add155
SH
2598 struct stat sb;
2599 unsigned long minor, major;
2a06d041
CB
2600 int ret = -EINVAL;
2601 char *mode = NULL;
72add155
SH
2602
2603 path = must_copy_string(invalue);
2604
2605 /*
2606 * read path followed by mode; ignore any trailing text.
2607 * A ' # comment' would be legal. Technically other text
2608 * is not legal, we could check for that if we cared to
2609 */
2610 for (n_parts = 1, p = path; *p && n_parts < 3; p++) {
2c2d6c49
SH
2611 if (*p != ' ')
2612 continue;
2613 *p = '\0';
2614 if (n_parts != 1)
2615 break;
2616 p++;
2617 n_parts++;
2618 while (*p == ' ')
2619 p++;
2620 mode = p;
2621 if (*p == '\0')
2622 goto out;
72add155 2623 }
2c2d6c49
SH
2624
2625 if (n_parts == 1)
72add155 2626 goto out;
72add155
SH
2627
2628 ret = stat(path, &sb);
2629 if (ret < 0)
2630 goto out;
2631
72add155
SH
2632 mode_t m = sb.st_mode & S_IFMT;
2633 switch (m) {
2634 case S_IFBLK:
2635 type = 'b';
2636 break;
2637 case S_IFCHR:
2638 type = 'c';
2639 break;
2c2d6c49 2640 default:
72add155
SH
2641 ERROR("Unsupported device type %i for %s", m, path);
2642 ret = -EINVAL;
2643 goto out;
2644 }
2c2d6c49
SH
2645
2646 major = MAJOR(sb.st_rdev);
2647 minor = MINOR(sb.st_rdev);
2648 ret = snprintf(dest, 50, "%c %lu:%lu %s", type, major, minor, mode);
72add155 2649 if (ret < 0 || ret >= 50) {
2a06d041
CB
2650 ERROR("Error on configuration value \"%c %lu:%lu %s\" (max 50 "
2651 "chars)", type, major, minor, mode);
72add155
SH
2652 ret = -ENAMETOOLONG;
2653 goto out;
2654 }
2655 ret = 0;
2656
2657out:
2658 free(path);
2659 return ret;
2660}
2661
ccb4cabe
SH
2662/*
2663 * Called from setup_limits - here we have the container's cgroup_data because
2664 * we created the cgroups
2665 */
a3926f6a
CB
2666static int cg_legacy_set_data(const char *filename, const char *value,
2667 struct cgfsng_handler_data *d)
ccb4cabe 2668{
b3646d7e 2669 char *fullpath, *p;
ab1a6cac 2670 size_t len;
1a0e70ac
CB
2671 /* "b|c <2^64-1>:<2^64-1> r|w|m" = 47 chars max */
2672 char converted_value[50];
b3646d7e
CB
2673 struct hierarchy *h;
2674 int ret = 0;
2675 char *controller = NULL;
ccb4cabe 2676
ab1a6cac
CB
2677 len = strlen(filename);
2678 controller = alloca(len + 1);
b3646d7e 2679 strcpy(controller, filename);
ab1a6cac
CB
2680 p = strchr(controller, '.');
2681 if (p)
ccb4cabe
SH
2682 *p = '\0';
2683
c8bf519d 2684 if (strcmp("devices.allow", filename) == 0 && value[0] == '/') {
72add155
SH
2685 ret = convert_devpath(value, converted_value);
2686 if (ret < 0)
c8bf519d 2687 return ret;
72add155 2688 value = converted_value;
c8bf519d 2689 }
2690
b3646d7e
CB
2691 h = get_hierarchy(controller);
2692 if (!h) {
2693 ERROR("Failed to setup limits for the \"%s\" controller. "
2694 "The controller seems to be unused by \"cgfsng\" cgroup "
2695 "driver or not enabled on the cgroup hierarchy",
2696 controller);
d1953b26 2697 errno = ENOENT;
ab1a6cac 2698 return -ENOENT;
ccb4cabe 2699 }
b3646d7e
CB
2700
2701 fullpath = must_make_path(h->fullcgpath, filename, NULL);
2702 ret = lxc_write_to_file(fullpath, value, strlen(value), false);
2703 free(fullpath);
ccb4cabe
SH
2704 return ret;
2705}
2706
a3926f6a
CB
2707static bool __cg_legacy_setup_limits(void *hdata,
2708 struct lxc_list *cgroup_settings,
2709 bool do_devices)
ccb4cabe
SH
2710{
2711 struct cgfsng_handler_data *d = hdata;
2712 struct lxc_list *iterator, *sorted_cgroup_settings, *next;
2713 struct lxc_cgroup *cg;
ccb4cabe
SH
2714 bool ret = false;
2715
2716 if (lxc_list_empty(cgroup_settings))
2717 return true;
2718
2719 sorted_cgroup_settings = sort_cgroup_settings(cgroup_settings);
6b38e644 2720 if (!sorted_cgroup_settings)
ccb4cabe 2721 return false;
ccb4cabe 2722
ccb4cabe
SH
2723 lxc_list_for_each(iterator, sorted_cgroup_settings) {
2724 cg = iterator->elem;
2725
2726 if (do_devices == !strncmp("devices", cg->subsystem, 7)) {
a3926f6a 2727 if (cg_legacy_set_data(cg->subsystem, cg->value, d)) {
ccb4cabe
SH
2728 if (do_devices && (errno == EACCES || errno == EPERM)) {
2729 WARN("Error setting %s to %s for %s",
2730 cg->subsystem, cg->value, d->name);
2731 continue;
2732 }
2733 SYSERROR("Error setting %s to %s for %s",
2734 cg->subsystem, cg->value, d->name);
2735 goto out;
2736 }
6a628f4a 2737 DEBUG("cgroup '%s' set to '%s'", cg->subsystem, cg->value);
ccb4cabe 2738 }
ccb4cabe
SH
2739 }
2740
2741 ret = true;
6b38e644 2742 INFO("Limits for the legacy cgroup hierarchies have been setup");
ccb4cabe 2743out:
ccb4cabe
SH
2744 lxc_list_for_each_safe(iterator, sorted_cgroup_settings, next) {
2745 lxc_list_del(iterator);
2746 free(iterator);
2747 }
2748 free(sorted_cgroup_settings);
2749 return ret;
2750}
2751
a3926f6a
CB
2752static bool __cg_unified_setup_limits(void *hdata,
2753 struct lxc_list *cgroup_settings)
6b38e644
CB
2754{
2755 struct lxc_list *iterator;
2756 struct hierarchy *h = unified;
2757
2758 if (lxc_list_empty(cgroup_settings))
2759 return true;
2760
2761 if (!h)
2762 return false;
2763
2764 lxc_list_for_each(iterator, cgroup_settings) {
2765 int ret;
2766 char *fullpath;
2767 struct lxc_cgroup *cg = iterator->elem;
2768
2769 fullpath = must_make_path(h->fullcgpath, cg->subsystem, NULL);
2770 ret = lxc_write_to_file(fullpath, cg->value, strlen(cg->value), false);
2771 free(fullpath);
2772 if (ret < 0) {
2773 SYSERROR("Failed to set \"%s\" to \"%s\"", cg->subsystem, cg->value);
2774 return false;
2775 }
2776 TRACE("Set \"%s\" to \"%s\"", cg->subsystem, cg->value);
2777 }
2778
2779 INFO("Limits for the unified cgroup hierarchy have been setup");
2780 return true;
2781}
2782
2783static bool cgfsng_setup_limits(void *hdata, struct lxc_conf *conf,
2784 bool do_devices)
2785{
2786 bool bret;
2787
a3926f6a 2788 bret = __cg_legacy_setup_limits(hdata, &conf->cgroup, do_devices);
6b38e644
CB
2789 if (!bret)
2790 return false;
2791
a3926f6a 2792 return __cg_unified_setup_limits(hdata, &conf->cgroup2);
6b38e644
CB
2793}
2794
ccb4cabe
SH
2795static struct cgroup_ops cgfsng_ops = {
2796 .init = cgfsng_init,
2797 .destroy = cgfsng_destroy,
2798 .create = cgfsng_create,
2799 .enter = cgfsng_enter,
ccb4cabe 2800 .escape = cgfsng_escape,
36662416
TA
2801 .num_hierarchies = cgfsng_num_hierarchies,
2802 .get_hierarchies = cgfsng_get_hierarchies,
ccb4cabe
SH
2803 .get_cgroup = cgfsng_get_cgroup,
2804 .get = cgfsng_get,
2805 .set = cgfsng_set,
2806 .unfreeze = cgfsng_unfreeze,
2807 .setup_limits = cgfsng_setup_limits,
2808 .name = "cgroupfs-ng",
2809 .attach = cgfsng_attach,
058c1cb6 2810 .chown = cgfsng_chown,
ccb4cabe
SH
2811 .mount_cgroup = cgfsng_mount,
2812 .nrtasks = cgfsng_nrtasks,
2813 .driver = CGFSNG,
2814
2815 /* unsupported */
2816 .create_legacy = NULL,
2817};