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