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