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