2 This file is part of systemd.
4 Copyright 2013 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
23 #include "alloc-util.h"
24 #include "cgroup-util.h"
29 #include "parse-util.h"
30 #include "path-util.h"
31 #include "process-util.h"
33 #include "string-table.h"
34 #include "string-util.h"
35 #include "stdio-util.h"
37 #define CGROUP_CPU_QUOTA_PERIOD_USEC ((usec_t) 100 * USEC_PER_MSEC)
39 static void cgroup_compat_warn(void) {
40 static bool cgroup_compat_warned
= false;
42 if (cgroup_compat_warned
)
45 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. See cgroup-compat debug messages for details.");
46 cgroup_compat_warned
= true;
49 #define log_cgroup_compat(unit, fmt, ...) do { \
50 cgroup_compat_warn(); \
51 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
54 void cgroup_context_init(CGroupContext
*c
) {
57 /* Initialize everything to the kernel defaults, assuming the
58 * structure is preinitialized to 0 */
60 c
->cpu_weight
= CGROUP_WEIGHT_INVALID
;
61 c
->startup_cpu_weight
= CGROUP_WEIGHT_INVALID
;
62 c
->cpu_quota_per_sec_usec
= USEC_INFINITY
;
64 c
->cpu_shares
= CGROUP_CPU_SHARES_INVALID
;
65 c
->startup_cpu_shares
= CGROUP_CPU_SHARES_INVALID
;
67 c
->memory_high
= CGROUP_LIMIT_MAX
;
68 c
->memory_max
= CGROUP_LIMIT_MAX
;
70 c
->memory_limit
= CGROUP_LIMIT_MAX
;
72 c
->io_weight
= CGROUP_WEIGHT_INVALID
;
73 c
->startup_io_weight
= CGROUP_WEIGHT_INVALID
;
75 c
->blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
;
76 c
->startup_blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
;
78 c
->tasks_max
= (uint64_t) -1;
81 void cgroup_context_free_device_allow(CGroupContext
*c
, CGroupDeviceAllow
*a
) {
85 LIST_REMOVE(device_allow
, c
->device_allow
, a
);
90 void cgroup_context_free_io_device_weight(CGroupContext
*c
, CGroupIODeviceWeight
*w
) {
94 LIST_REMOVE(device_weights
, c
->io_device_weights
, w
);
99 void cgroup_context_free_io_device_limit(CGroupContext
*c
, CGroupIODeviceLimit
*l
) {
103 LIST_REMOVE(device_limits
, c
->io_device_limits
, l
);
108 void cgroup_context_free_blockio_device_weight(CGroupContext
*c
, CGroupBlockIODeviceWeight
*w
) {
112 LIST_REMOVE(device_weights
, c
->blockio_device_weights
, w
);
117 void cgroup_context_free_blockio_device_bandwidth(CGroupContext
*c
, CGroupBlockIODeviceBandwidth
*b
) {
121 LIST_REMOVE(device_bandwidths
, c
->blockio_device_bandwidths
, b
);
126 void cgroup_context_done(CGroupContext
*c
) {
129 while (c
->io_device_weights
)
130 cgroup_context_free_io_device_weight(c
, c
->io_device_weights
);
132 while (c
->io_device_limits
)
133 cgroup_context_free_io_device_limit(c
, c
->io_device_limits
);
135 while (c
->blockio_device_weights
)
136 cgroup_context_free_blockio_device_weight(c
, c
->blockio_device_weights
);
138 while (c
->blockio_device_bandwidths
)
139 cgroup_context_free_blockio_device_bandwidth(c
, c
->blockio_device_bandwidths
);
141 while (c
->device_allow
)
142 cgroup_context_free_device_allow(c
, c
->device_allow
);
145 void cgroup_context_dump(CGroupContext
*c
, FILE* f
, const char *prefix
) {
146 CGroupIODeviceLimit
*il
;
147 CGroupIODeviceWeight
*iw
;
148 CGroupBlockIODeviceBandwidth
*b
;
149 CGroupBlockIODeviceWeight
*w
;
150 CGroupDeviceAllow
*a
;
151 char u
[FORMAT_TIMESPAN_MAX
];
156 prefix
= strempty(prefix
);
159 "%sCPUAccounting=%s\n"
160 "%sIOAccounting=%s\n"
161 "%sBlockIOAccounting=%s\n"
162 "%sMemoryAccounting=%s\n"
163 "%sTasksAccounting=%s\n"
164 "%sCPUWeight=%" PRIu64
"\n"
165 "%sStartupCPUWeight=%" PRIu64
"\n"
166 "%sCPUShares=%" PRIu64
"\n"
167 "%sStartupCPUShares=%" PRIu64
"\n"
168 "%sCPUQuotaPerSecSec=%s\n"
169 "%sIOWeight=%" PRIu64
"\n"
170 "%sStartupIOWeight=%" PRIu64
"\n"
171 "%sBlockIOWeight=%" PRIu64
"\n"
172 "%sStartupBlockIOWeight=%" PRIu64
"\n"
173 "%sMemoryLow=%" PRIu64
"\n"
174 "%sMemoryHigh=%" PRIu64
"\n"
175 "%sMemoryMax=%" PRIu64
"\n"
176 "%sMemoryLimit=%" PRIu64
"\n"
177 "%sTasksMax=%" PRIu64
"\n"
178 "%sDevicePolicy=%s\n"
180 prefix
, yes_no(c
->cpu_accounting
),
181 prefix
, yes_no(c
->io_accounting
),
182 prefix
, yes_no(c
->blockio_accounting
),
183 prefix
, yes_no(c
->memory_accounting
),
184 prefix
, yes_no(c
->tasks_accounting
),
185 prefix
, c
->cpu_weight
,
186 prefix
, c
->startup_cpu_weight
,
187 prefix
, c
->cpu_shares
,
188 prefix
, c
->startup_cpu_shares
,
189 prefix
, format_timespan(u
, sizeof(u
), c
->cpu_quota_per_sec_usec
, 1),
190 prefix
, c
->io_weight
,
191 prefix
, c
->startup_io_weight
,
192 prefix
, c
->blockio_weight
,
193 prefix
, c
->startup_blockio_weight
,
194 prefix
, c
->memory_low
,
195 prefix
, c
->memory_high
,
196 prefix
, c
->memory_max
,
197 prefix
, c
->memory_limit
,
198 prefix
, c
->tasks_max
,
199 prefix
, cgroup_device_policy_to_string(c
->device_policy
),
200 prefix
, yes_no(c
->delegate
));
202 LIST_FOREACH(device_allow
, a
, c
->device_allow
)
204 "%sDeviceAllow=%s %s%s%s\n",
207 a
->r
? "r" : "", a
->w
? "w" : "", a
->m
? "m" : "");
209 LIST_FOREACH(device_weights
, iw
, c
->io_device_weights
)
211 "%sIODeviceWeight=%s %" PRIu64
,
216 LIST_FOREACH(device_limits
, il
, c
->io_device_limits
) {
217 char buf
[FORMAT_BYTES_MAX
];
218 CGroupIOLimitType type
;
220 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
221 if (il
->limits
[type
] != cgroup_io_limit_defaults
[type
])
225 cgroup_io_limit_type_to_string(type
),
227 format_bytes(buf
, sizeof(buf
), il
->limits
[type
]));
230 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
232 "%sBlockIODeviceWeight=%s %" PRIu64
,
237 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
) {
238 char buf
[FORMAT_BYTES_MAX
];
240 if (b
->rbps
!= CGROUP_LIMIT_MAX
)
242 "%sBlockIOReadBandwidth=%s %s\n",
245 format_bytes(buf
, sizeof(buf
), b
->rbps
));
246 if (b
->wbps
!= CGROUP_LIMIT_MAX
)
248 "%sBlockIOWriteBandwidth=%s %s\n",
251 format_bytes(buf
, sizeof(buf
), b
->wbps
));
255 static int lookup_block_device(const char *p
, dev_t
*dev
) {
264 return log_warning_errno(errno
, "Couldn't stat device %s: %m", p
);
266 if (S_ISBLK(st
.st_mode
))
268 else if (major(st
.st_dev
) != 0) {
269 /* If this is not a device node then find the block
270 * device this file is stored on */
273 /* If this is a partition, try to get the originating
275 block_get_whole_disk(*dev
, dev
);
277 log_warning("%s is not a block device and file system block device cannot be determined or is not local.", p
);
284 static int whitelist_device(const char *path
, const char *node
, const char *acc
) {
285 char buf
[2+DECIMAL_STR_MAX(dev_t
)*2+2+4];
292 if (stat(node
, &st
) < 0) {
293 log_warning("Couldn't stat device %s", node
);
297 if (!S_ISCHR(st
.st_mode
) && !S_ISBLK(st
.st_mode
)) {
298 log_warning("%s is not a device.", node
);
304 S_ISCHR(st
.st_mode
) ? 'c' : 'b',
305 major(st
.st_rdev
), minor(st
.st_rdev
),
308 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
310 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
311 "Failed to set devices.allow on %s: %m", path
);
316 static int whitelist_major(const char *path
, const char *name
, char type
, const char *acc
) {
317 _cleanup_fclose_
FILE *f
= NULL
;
324 assert(type
== 'b' || type
== 'c');
326 f
= fopen("/proc/devices", "re");
328 return log_warning_errno(errno
, "Cannot open /proc/devices to resolve %s (%c): %m", name
, type
);
330 FOREACH_LINE(line
, f
, goto fail
) {
331 char buf
[2+DECIMAL_STR_MAX(unsigned)+3+4], *p
, *w
;
336 if (type
== 'c' && streq(line
, "Character devices:")) {
341 if (type
== 'b' && streq(line
, "Block devices:")) {
356 w
= strpbrk(p
, WHITESPACE
);
361 r
= safe_atou(p
, &maj
);
368 w
+= strspn(w
, WHITESPACE
);
370 if (fnmatch(name
, w
, 0) != 0)
379 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
381 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
382 "Failed to set devices.allow on %s: %m", path
);
388 log_warning_errno(errno
, "Failed to read /proc/devices: %m");
392 static bool cgroup_context_has_cpu_weight(CGroupContext
*c
) {
393 return c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
||
394 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
;
397 static bool cgroup_context_has_cpu_shares(CGroupContext
*c
) {
398 return c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
||
399 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
;
402 static uint64_t cgroup_context_cpu_weight(CGroupContext
*c
, ManagerState state
) {
403 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
404 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
)
405 return c
->startup_cpu_weight
;
406 else if (c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
)
407 return c
->cpu_weight
;
409 return CGROUP_WEIGHT_DEFAULT
;
412 static uint64_t cgroup_context_cpu_shares(CGroupContext
*c
, ManagerState state
) {
413 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
414 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
415 return c
->startup_cpu_shares
;
416 else if (c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
417 return c
->cpu_shares
;
419 return CGROUP_CPU_SHARES_DEFAULT
;
422 static void cgroup_apply_unified_cpu_config(Unit
*u
, uint64_t weight
, uint64_t quota
) {
423 char buf
[MAX(DECIMAL_STR_MAX(uint64_t) + 1, (DECIMAL_STR_MAX(usec_t
) + 1) * 2)];
426 xsprintf(buf
, "%" PRIu64
"\n", weight
);
427 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.weight", buf
);
429 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
430 "Failed to set cpu.weight: %m");
432 if (quota
!= USEC_INFINITY
)
433 xsprintf(buf
, USEC_FMT
" " USEC_FMT
"\n",
434 quota
* CGROUP_CPU_QUOTA_PERIOD_USEC
/ USEC_PER_SEC
, CGROUP_CPU_QUOTA_PERIOD_USEC
);
436 xsprintf(buf
, "max " USEC_FMT
"\n", CGROUP_CPU_QUOTA_PERIOD_USEC
);
438 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.max", buf
);
441 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
442 "Failed to set cpu.max: %m");
445 static void cgroup_apply_legacy_cpu_config(Unit
*u
, uint64_t shares
, uint64_t quota
) {
446 char buf
[MAX(DECIMAL_STR_MAX(uint64_t), DECIMAL_STR_MAX(usec_t
)) + 1];
449 xsprintf(buf
, "%" PRIu64
"\n", shares
);
450 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.shares", buf
);
452 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
453 "Failed to set cpu.shares: %m");
455 xsprintf(buf
, USEC_FMT
"\n", CGROUP_CPU_QUOTA_PERIOD_USEC
);
456 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_period_us", buf
);
458 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
459 "Failed to set cpu.cfs_period_us: %m");
461 if (quota
!= USEC_INFINITY
) {
462 xsprintf(buf
, USEC_FMT
"\n", quota
* CGROUP_CPU_QUOTA_PERIOD_USEC
/ USEC_PER_SEC
);
463 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_quota_us", buf
);
465 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_quota_us", "-1");
467 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
468 "Failed to set cpu.cfs_quota_us: %m");
471 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares
) {
472 return CLAMP(shares
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_CPU_SHARES_DEFAULT
,
473 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
476 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight
) {
477 return CLAMP(weight
* CGROUP_CPU_SHARES_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
478 CGROUP_CPU_SHARES_MIN
, CGROUP_CPU_SHARES_MAX
);
481 static bool cgroup_context_has_io_config(CGroupContext
*c
) {
482 return c
->io_accounting
||
483 c
->io_weight
!= CGROUP_WEIGHT_INVALID
||
484 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
||
485 c
->io_device_weights
||
489 static bool cgroup_context_has_blockio_config(CGroupContext
*c
) {
490 return c
->blockio_accounting
||
491 c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
492 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
493 c
->blockio_device_weights
||
494 c
->blockio_device_bandwidths
;
497 static uint64_t cgroup_context_io_weight(CGroupContext
*c
, ManagerState state
) {
498 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
499 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
)
500 return c
->startup_io_weight
;
501 else if (c
->io_weight
!= CGROUP_WEIGHT_INVALID
)
504 return CGROUP_WEIGHT_DEFAULT
;
507 static uint64_t cgroup_context_blkio_weight(CGroupContext
*c
, ManagerState state
) {
508 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
509 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
510 return c
->startup_blockio_weight
;
511 else if (c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
512 return c
->blockio_weight
;
514 return CGROUP_BLKIO_WEIGHT_DEFAULT
;
517 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight
) {
518 return CLAMP(blkio_weight
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_BLKIO_WEIGHT_DEFAULT
,
519 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
522 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight
) {
523 return CLAMP(io_weight
* CGROUP_BLKIO_WEIGHT_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
524 CGROUP_BLKIO_WEIGHT_MIN
, CGROUP_BLKIO_WEIGHT_MAX
);
527 static void cgroup_apply_io_device_weight(Unit
*u
, const char *dev_path
, uint64_t io_weight
) {
528 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
532 r
= lookup_block_device(dev_path
, &dev
);
536 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), io_weight
);
537 r
= cg_set_attribute("io", u
->cgroup_path
, "io.weight", buf
);
539 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
540 "Failed to set io.weight: %m");
543 static void cgroup_apply_blkio_device_weight(Unit
*u
, const char *dev_path
, uint64_t blkio_weight
) {
544 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
548 r
= lookup_block_device(dev_path
, &dev
);
552 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), blkio_weight
);
553 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.weight_device", buf
);
555 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
556 "Failed to set blkio.weight_device: %m");
559 static unsigned cgroup_apply_io_device_limit(Unit
*u
, const char *dev_path
, uint64_t *limits
) {
560 char limit_bufs
[_CGROUP_IO_LIMIT_TYPE_MAX
][DECIMAL_STR_MAX(uint64_t)];
561 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
562 CGroupIOLimitType type
;
567 r
= lookup_block_device(dev_path
, &dev
);
571 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++) {
572 if (limits
[type
] != cgroup_io_limit_defaults
[type
]) {
573 xsprintf(limit_bufs
[type
], "%" PRIu64
, limits
[type
]);
576 xsprintf(limit_bufs
[type
], "%s", limits
[type
] == CGROUP_LIMIT_MAX
? "max" : "0");
580 xsprintf(buf
, "%u:%u rbps=%s wbps=%s riops=%s wiops=%s\n", major(dev
), minor(dev
),
581 limit_bufs
[CGROUP_IO_RBPS_MAX
], limit_bufs
[CGROUP_IO_WBPS_MAX
],
582 limit_bufs
[CGROUP_IO_RIOPS_MAX
], limit_bufs
[CGROUP_IO_WIOPS_MAX
]);
583 r
= cg_set_attribute("io", u
->cgroup_path
, "io.max", buf
);
585 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
586 "Failed to set io.max: %m");
590 static unsigned cgroup_apply_blkio_device_limit(Unit
*u
, const char *dev_path
, uint64_t rbps
, uint64_t wbps
) {
591 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
596 r
= lookup_block_device(dev_path
, &dev
);
600 if (rbps
!= CGROUP_LIMIT_MAX
)
602 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), rbps
);
603 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.throttle.read_bps_device", buf
);
605 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
606 "Failed to set blkio.throttle.read_bps_device: %m");
608 if (wbps
!= CGROUP_LIMIT_MAX
)
610 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), wbps
);
611 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.throttle.write_bps_device", buf
);
613 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
614 "Failed to set blkio.throttle.write_bps_device: %m");
619 static bool cgroup_context_has_unified_memory_config(CGroupContext
*c
) {
620 return c
->memory_low
> 0 || c
->memory_high
!= CGROUP_LIMIT_MAX
|| c
->memory_max
!= CGROUP_LIMIT_MAX
;
623 static void cgroup_apply_unified_memory_limit(Unit
*u
, const char *file
, uint64_t v
) {
624 char buf
[DECIMAL_STR_MAX(uint64_t) + 1] = "max";
627 if (v
!= CGROUP_LIMIT_MAX
)
628 xsprintf(buf
, "%" PRIu64
"\n", v
);
630 r
= cg_set_attribute("memory", u
->cgroup_path
, file
, buf
);
632 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
633 "Failed to set %s: %m", file
);
636 static void cgroup_context_apply(Unit
*u
, CGroupMask mask
, ManagerState state
) {
644 c
= unit_get_cgroup_context(u
);
645 path
= u
->cgroup_path
;
653 /* Some cgroup attributes are not supported on the root cgroup,
654 * hence silently ignore */
655 is_root
= isempty(path
) || path_equal(path
, "/");
657 /* Make sure we don't try to display messages with an empty path. */
660 /* We generally ignore errors caused by read-only mounted
661 * cgroup trees (assuming we are running in a container then),
662 * and missing cgroups, i.e. EROFS and ENOENT. */
664 if ((mask
& CGROUP_MASK_CPU
) && !is_root
) {
665 bool has_weight
= cgroup_context_has_cpu_weight(c
);
666 bool has_shares
= cgroup_context_has_cpu_shares(c
);
668 if (cg_unified() > 0) {
672 weight
= cgroup_context_cpu_weight(c
, state
);
673 else if (has_shares
) {
674 uint64_t shares
= cgroup_context_cpu_shares(c
, state
);
676 weight
= cgroup_cpu_shares_to_weight(shares
);
678 log_cgroup_compat(u
, "Applying [Startup]CpuShares %" PRIu64
" as [Startup]CpuWeight %" PRIu64
" on %s",
679 shares
, weight
, path
);
681 weight
= CGROUP_WEIGHT_DEFAULT
;
683 cgroup_apply_unified_cpu_config(u
, weight
, c
->cpu_quota_per_sec_usec
);
688 shares
= cgroup_context_cpu_shares(c
, state
);
689 else if (has_weight
) {
690 uint64_t weight
= cgroup_context_cpu_weight(c
, state
);
692 shares
= cgroup_cpu_weight_to_shares(weight
);
694 log_cgroup_compat(u
, "Applying [Startup]CpuWeight %" PRIu64
" as [Startup]CpuShares %" PRIu64
" on %s",
695 weight
, shares
, path
);
697 shares
= CGROUP_CPU_SHARES_DEFAULT
;
699 cgroup_apply_legacy_cpu_config(u
, shares
, c
->cpu_quota_per_sec_usec
);
703 if (mask
& CGROUP_MASK_IO
) {
704 bool has_io
= cgroup_context_has_io_config(c
);
705 bool has_blockio
= cgroup_context_has_blockio_config(c
);
708 char buf
[8+DECIMAL_STR_MAX(uint64_t)+1];
712 weight
= cgroup_context_io_weight(c
, state
);
713 else if (has_blockio
) {
714 uint64_t blkio_weight
= cgroup_context_blkio_weight(c
, state
);
716 weight
= cgroup_weight_blkio_to_io(blkio_weight
);
718 log_cgroup_compat(u
, "Applying [Startup]BlockIOWeight %" PRIu64
" as [Startup]IOWeight %" PRIu64
,
719 blkio_weight
, weight
);
721 weight
= CGROUP_WEIGHT_DEFAULT
;
723 xsprintf(buf
, "default %" PRIu64
"\n", weight
);
724 r
= cg_set_attribute("io", path
, "io.weight", buf
);
726 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
727 "Failed to set io.weight: %m");
730 CGroupIODeviceWeight
*w
;
732 /* FIXME: no way to reset this list */
733 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
)
734 cgroup_apply_io_device_weight(u
, w
->path
, w
->weight
);
735 } else if (has_blockio
) {
736 CGroupBlockIODeviceWeight
*w
;
738 /* FIXME: no way to reset this list */
739 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
) {
740 weight
= cgroup_weight_blkio_to_io(w
->weight
);
742 log_cgroup_compat(u
, "Applying BlockIODeviceWeight %" PRIu64
" as IODeviceWeight %" PRIu64
" for %s",
743 w
->weight
, weight
, w
->path
);
745 cgroup_apply_io_device_weight(u
, w
->path
, weight
);
750 /* Apply limits and free ones without config. */
752 CGroupIODeviceLimit
*l
, *next
;
754 LIST_FOREACH_SAFE(device_limits
, l
, next
, c
->io_device_limits
) {
755 if (!cgroup_apply_io_device_limit(u
, l
->path
, l
->limits
))
756 cgroup_context_free_io_device_limit(c
, l
);
758 } else if (has_blockio
) {
759 CGroupBlockIODeviceBandwidth
*b
, *next
;
761 LIST_FOREACH_SAFE(device_bandwidths
, b
, next
, c
->blockio_device_bandwidths
) {
762 uint64_t limits
[_CGROUP_IO_LIMIT_TYPE_MAX
];
763 CGroupIOLimitType type
;
765 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
766 limits
[type
] = cgroup_io_limit_defaults
[type
];
768 limits
[CGROUP_IO_RBPS_MAX
] = b
->rbps
;
769 limits
[CGROUP_IO_WBPS_MAX
] = b
->wbps
;
771 log_cgroup_compat(u
, "Applying BlockIO{Read|Write}Bandwidth %" PRIu64
" %" PRIu64
" as IO{Read|Write}BandwidthMax for %s",
772 b
->rbps
, b
->wbps
, b
->path
);
774 if (!cgroup_apply_io_device_limit(u
, b
->path
, limits
))
775 cgroup_context_free_blockio_device_bandwidth(c
, b
);
780 if (mask
& CGROUP_MASK_BLKIO
) {
781 bool has_io
= cgroup_context_has_io_config(c
);
782 bool has_blockio
= cgroup_context_has_blockio_config(c
);
785 char buf
[DECIMAL_STR_MAX(uint64_t)+1];
789 weight
= cgroup_context_blkio_weight(c
, state
);
791 uint64_t io_weight
= cgroup_context_io_weight(c
, state
);
793 weight
= cgroup_weight_io_to_blkio(cgroup_context_io_weight(c
, state
));
795 log_cgroup_compat(u
, "Applying [Startup]IOWeight %" PRIu64
" as [Startup]BlockIOWeight %" PRIu64
,
798 weight
= CGROUP_BLKIO_WEIGHT_DEFAULT
;
800 xsprintf(buf
, "%" PRIu64
"\n", weight
);
801 r
= cg_set_attribute("blkio", path
, "blkio.weight", buf
);
803 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
804 "Failed to set blkio.weight: %m");
807 CGroupBlockIODeviceWeight
*w
;
809 /* FIXME: no way to reset this list */
810 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
811 cgroup_apply_blkio_device_weight(u
, w
->path
, w
->weight
);
813 CGroupIODeviceWeight
*w
;
815 /* FIXME: no way to reset this list */
816 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
) {
817 weight
= cgroup_weight_io_to_blkio(w
->weight
);
819 log_cgroup_compat(u
, "Applying IODeviceWeight %" PRIu64
" as BlockIODeviceWeight %" PRIu64
" for %s",
820 w
->weight
, weight
, w
->path
);
822 cgroup_apply_blkio_device_weight(u
, w
->path
, weight
);
827 /* Apply limits and free ones without config. */
829 CGroupBlockIODeviceBandwidth
*b
, *next
;
831 LIST_FOREACH_SAFE(device_bandwidths
, b
, next
, c
->blockio_device_bandwidths
) {
832 if (!cgroup_apply_blkio_device_limit(u
, b
->path
, b
->rbps
, b
->wbps
))
833 cgroup_context_free_blockio_device_bandwidth(c
, b
);
836 CGroupIODeviceLimit
*l
, *next
;
838 LIST_FOREACH_SAFE(device_limits
, l
, next
, c
->io_device_limits
) {
839 log_cgroup_compat(u
, "Applying IO{Read|Write}Bandwidth %" PRIu64
" %" PRIu64
" as BlockIO{Read|Write}BandwidthMax for %s",
840 l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
], l
->path
);
842 if (!cgroup_apply_blkio_device_limit(u
, l
->path
, l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
]))
843 cgroup_context_free_io_device_limit(c
, l
);
848 if ((mask
& CGROUP_MASK_MEMORY
) && !is_root
) {
849 if (cg_unified() > 0) {
850 uint64_t max
= c
->memory_max
;
852 if (cgroup_context_has_unified_memory_config(c
))
855 max
= c
->memory_limit
;
857 if (max
!= CGROUP_LIMIT_MAX
)
858 log_cgroup_compat(u
, "Applying MemoryLimit %" PRIu64
" as MemoryMax", max
);
861 cgroup_apply_unified_memory_limit(u
, "memory.low", c
->memory_low
);
862 cgroup_apply_unified_memory_limit(u
, "memory.high", c
->memory_high
);
863 cgroup_apply_unified_memory_limit(u
, "memory.max", max
);
865 char buf
[DECIMAL_STR_MAX(uint64_t) + 1];
866 uint64_t val
= c
->memory_limit
;
868 if (val
== CGROUP_LIMIT_MAX
) {
871 if (val
!= CGROUP_LIMIT_MAX
)
872 log_cgroup_compat(u
, "Applying MemoryMax %" PRIi64
" as MemoryLimit", c
->memory_max
);
875 if (val
== CGROUP_LIMIT_MAX
)
876 strncpy(buf
, "-1\n", sizeof(buf
));
878 xsprintf(buf
, "%" PRIu64
"\n", val
);
880 r
= cg_set_attribute("memory", path
, "memory.limit_in_bytes", buf
);
882 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
883 "Failed to set memory.limit_in_bytes: %m");
887 if ((mask
& CGROUP_MASK_DEVICES
) && !is_root
) {
888 CGroupDeviceAllow
*a
;
890 /* Changing the devices list of a populated cgroup
891 * might result in EINVAL, hence ignore EINVAL
894 if (c
->device_allow
|| c
->device_policy
!= CGROUP_AUTO
)
895 r
= cg_set_attribute("devices", path
, "devices.deny", "a");
897 r
= cg_set_attribute("devices", path
, "devices.allow", "a");
899 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
900 "Failed to reset devices.list: %m");
902 if (c
->device_policy
== CGROUP_CLOSED
||
903 (c
->device_policy
== CGROUP_AUTO
&& c
->device_allow
)) {
904 static const char auto_devices
[] =
905 "/dev/null\0" "rwm\0"
906 "/dev/zero\0" "rwm\0"
907 "/dev/full\0" "rwm\0"
908 "/dev/random\0" "rwm\0"
909 "/dev/urandom\0" "rwm\0"
911 "/dev/pts/ptmx\0" "rw\0" /* /dev/pts/ptmx may not be duplicated, but accessed */
912 /* Allow /run/systemd/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
913 "/run/systemd/inaccessible/chr\0" "rwm\0"
914 "/run/systemd/inaccessible/blk\0" "rwm\0";
918 NULSTR_FOREACH_PAIR(x
, y
, auto_devices
)
919 whitelist_device(path
, x
, y
);
921 whitelist_major(path
, "pts", 'c', "rw");
922 whitelist_major(path
, "kdbus", 'c', "rw");
923 whitelist_major(path
, "kdbus/*", 'c', "rw");
926 LIST_FOREACH(device_allow
, a
, c
->device_allow
) {
942 if (startswith(a
->path
, "/dev/"))
943 whitelist_device(path
, a
->path
, acc
);
944 else if (startswith(a
->path
, "block-"))
945 whitelist_major(path
, a
->path
+ 6, 'b', acc
);
946 else if (startswith(a
->path
, "char-"))
947 whitelist_major(path
, a
->path
+ 5, 'c', acc
);
949 log_unit_debug(u
, "Ignoring device %s while writing cgroup attribute.", a
->path
);
953 if ((mask
& CGROUP_MASK_PIDS
) && !is_root
) {
955 if (c
->tasks_max
!= (uint64_t) -1) {
956 char buf
[DECIMAL_STR_MAX(uint64_t) + 2];
958 sprintf(buf
, "%" PRIu64
"\n", c
->tasks_max
);
959 r
= cg_set_attribute("pids", path
, "pids.max", buf
);
961 r
= cg_set_attribute("pids", path
, "pids.max", "max");
964 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
965 "Failed to set pids.max: %m");
969 CGroupMask
cgroup_context_get_mask(CGroupContext
*c
) {
972 /* Figure out which controllers we need */
974 if (c
->cpu_accounting
||
975 cgroup_context_has_cpu_weight(c
) ||
976 cgroup_context_has_cpu_shares(c
) ||
977 c
->cpu_quota_per_sec_usec
!= USEC_INFINITY
)
978 mask
|= CGROUP_MASK_CPUACCT
| CGROUP_MASK_CPU
;
980 if (cgroup_context_has_io_config(c
) || cgroup_context_has_blockio_config(c
))
981 mask
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
983 if (c
->memory_accounting
||
984 c
->memory_limit
!= CGROUP_LIMIT_MAX
||
985 cgroup_context_has_unified_memory_config(c
))
986 mask
|= CGROUP_MASK_MEMORY
;
988 if (c
->device_allow
||
989 c
->device_policy
!= CGROUP_AUTO
)
990 mask
|= CGROUP_MASK_DEVICES
;
992 if (c
->tasks_accounting
||
993 c
->tasks_max
!= (uint64_t) -1)
994 mask
|= CGROUP_MASK_PIDS
;
999 CGroupMask
unit_get_own_mask(Unit
*u
) {
1002 /* Returns the mask of controllers the unit needs for itself */
1004 c
= unit_get_cgroup_context(u
);
1008 /* If delegation is turned on, then turn on all cgroups,
1009 * unless we are on the legacy hierarchy and the process we
1010 * fork into it is known to drop privileges, and hence
1011 * shouldn't get access to the controllers.
1013 * Note that on the unified hierarchy it is safe to delegate
1014 * controllers to unprivileged services. */
1019 e
= unit_get_exec_context(u
);
1021 exec_context_maintains_privileges(e
) ||
1023 return _CGROUP_MASK_ALL
;
1026 return cgroup_context_get_mask(c
);
1029 CGroupMask
unit_get_members_mask(Unit
*u
) {
1032 /* Returns the mask of controllers all of the unit's children
1033 * require, merged */
1035 if (u
->cgroup_members_mask_valid
)
1036 return u
->cgroup_members_mask
;
1038 u
->cgroup_members_mask
= 0;
1040 if (u
->type
== UNIT_SLICE
) {
1044 SET_FOREACH(member
, u
->dependencies
[UNIT_BEFORE
], i
) {
1049 if (UNIT_DEREF(member
->slice
) != u
)
1052 u
->cgroup_members_mask
|=
1053 unit_get_own_mask(member
) |
1054 unit_get_members_mask(member
);
1058 u
->cgroup_members_mask_valid
= true;
1059 return u
->cgroup_members_mask
;
1062 CGroupMask
unit_get_siblings_mask(Unit
*u
) {
1065 /* Returns the mask of controllers all of the unit's siblings
1066 * require, i.e. the members mask of the unit's parent slice
1067 * if there is one. */
1069 if (UNIT_ISSET(u
->slice
))
1070 return unit_get_members_mask(UNIT_DEREF(u
->slice
));
1072 return unit_get_own_mask(u
) | unit_get_members_mask(u
);
1075 CGroupMask
unit_get_subtree_mask(Unit
*u
) {
1077 /* Returns the mask of this subtree, meaning of the group
1078 * itself and its children. */
1080 return unit_get_own_mask(u
) | unit_get_members_mask(u
);
1083 CGroupMask
unit_get_target_mask(Unit
*u
) {
1086 /* This returns the cgroup mask of all controllers to enable
1087 * for a specific cgroup, i.e. everything it needs itself,
1088 * plus all that its children need, plus all that its siblings
1089 * need. This is primarily useful on the legacy cgroup
1090 * hierarchy, where we need to duplicate each cgroup in each
1091 * hierarchy that shall be enabled for it. */
1093 mask
= unit_get_own_mask(u
) | unit_get_members_mask(u
) | unit_get_siblings_mask(u
);
1094 mask
&= u
->manager
->cgroup_supported
;
1099 CGroupMask
unit_get_enable_mask(Unit
*u
) {
1102 /* This returns the cgroup mask of all controllers to enable
1103 * for the children of a specific cgroup. This is primarily
1104 * useful for the unified cgroup hierarchy, where each cgroup
1105 * controls which controllers are enabled for its children. */
1107 mask
= unit_get_members_mask(u
);
1108 mask
&= u
->manager
->cgroup_supported
;
1113 /* Recurse from a unit up through its containing slices, propagating
1114 * mask bits upward. A unit is also member of itself. */
1115 void unit_update_cgroup_members_masks(Unit
*u
) {
1121 /* Calculate subtree mask */
1122 m
= unit_get_subtree_mask(u
);
1124 /* See if anything changed from the previous invocation. If
1125 * not, we're done. */
1126 if (u
->cgroup_subtree_mask_valid
&& m
== u
->cgroup_subtree_mask
)
1130 u
->cgroup_subtree_mask_valid
&&
1131 ((m
& ~u
->cgroup_subtree_mask
) != 0) &&
1132 ((~m
& u
->cgroup_subtree_mask
) == 0);
1134 u
->cgroup_subtree_mask
= m
;
1135 u
->cgroup_subtree_mask_valid
= true;
1137 if (UNIT_ISSET(u
->slice
)) {
1138 Unit
*s
= UNIT_DEREF(u
->slice
);
1141 /* There's more set now than before. We
1142 * propagate the new mask to the parent's mask
1143 * (not caring if it actually was valid or
1146 s
->cgroup_members_mask
|= m
;
1149 /* There's less set now than before (or we
1150 * don't know), we need to recalculate
1151 * everything, so let's invalidate the
1152 * parent's members mask */
1154 s
->cgroup_members_mask_valid
= false;
1156 /* And now make sure that this change also hits our
1158 unit_update_cgroup_members_masks(s
);
1162 static const char *migrate_callback(CGroupMask mask
, void *userdata
) {
1169 if (u
->cgroup_path
&&
1170 u
->cgroup_realized
&&
1171 (u
->cgroup_realized_mask
& mask
) == mask
)
1172 return u
->cgroup_path
;
1174 u
= UNIT_DEREF(u
->slice
);
1180 char *unit_default_cgroup_path(Unit
*u
) {
1181 _cleanup_free_
char *escaped
= NULL
, *slice
= NULL
;
1186 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1187 return strdup(u
->manager
->cgroup_root
);
1189 if (UNIT_ISSET(u
->slice
) && !unit_has_name(UNIT_DEREF(u
->slice
), SPECIAL_ROOT_SLICE
)) {
1190 r
= cg_slice_to_path(UNIT_DEREF(u
->slice
)->id
, &slice
);
1195 escaped
= cg_escape(u
->id
);
1200 return strjoin(u
->manager
->cgroup_root
, "/", slice
, "/", escaped
, NULL
);
1202 return strjoin(u
->manager
->cgroup_root
, "/", escaped
, NULL
);
1205 int unit_set_cgroup_path(Unit
*u
, const char *path
) {
1206 _cleanup_free_
char *p
= NULL
;
1218 if (streq_ptr(u
->cgroup_path
, p
))
1222 r
= hashmap_put(u
->manager
->cgroup_unit
, p
, u
);
1227 unit_release_cgroup(u
);
1235 int unit_watch_cgroup(Unit
*u
) {
1236 _cleanup_free_
char *events
= NULL
;
1241 if (!u
->cgroup_path
)
1244 if (u
->cgroup_inotify_wd
>= 0)
1247 /* Only applies to the unified hierarchy */
1250 return log_unit_error_errno(u
, r
, "Failed detect whether the unified hierarchy is used: %m");
1254 /* Don't watch the root slice, it's pointless. */
1255 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1258 r
= hashmap_ensure_allocated(&u
->manager
->cgroup_inotify_wd_unit
, &trivial_hash_ops
);
1262 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "cgroup.events", &events
);
1266 u
->cgroup_inotify_wd
= inotify_add_watch(u
->manager
->cgroup_inotify_fd
, events
, IN_MODIFY
);
1267 if (u
->cgroup_inotify_wd
< 0) {
1269 if (errno
== ENOENT
) /* If the directory is already
1270 * gone we don't need to track
1271 * it, so this is not an error */
1274 return log_unit_error_errno(u
, errno
, "Failed to add inotify watch descriptor for control group %s: %m", u
->cgroup_path
);
1277 r
= hashmap_put(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
), u
);
1279 return log_unit_error_errno(u
, r
, "Failed to add inotify watch descriptor to hash map: %m");
1284 static int unit_create_cgroup(
1286 CGroupMask target_mask
,
1287 CGroupMask enable_mask
) {
1294 c
= unit_get_cgroup_context(u
);
1298 if (!u
->cgroup_path
) {
1299 _cleanup_free_
char *path
= NULL
;
1301 path
= unit_default_cgroup_path(u
);
1305 r
= unit_set_cgroup_path(u
, path
);
1307 return log_unit_error_errno(u
, r
, "Control group %s exists already.", path
);
1309 return log_unit_error_errno(u
, r
, "Failed to set unit's control group path to %s: %m", path
);
1312 /* First, create our own group */
1313 r
= cg_create_everywhere(u
->manager
->cgroup_supported
, target_mask
, u
->cgroup_path
);
1315 return log_unit_error_errno(u
, r
, "Failed to create cgroup %s: %m", u
->cgroup_path
);
1317 /* Start watching it */
1318 (void) unit_watch_cgroup(u
);
1320 /* Enable all controllers we need */
1321 r
= cg_enable_everywhere(u
->manager
->cgroup_supported
, enable_mask
, u
->cgroup_path
);
1323 log_unit_warning_errno(u
, r
, "Failed to enable controllers on cgroup %s, ignoring: %m", u
->cgroup_path
);
1325 /* Keep track that this is now realized */
1326 u
->cgroup_realized
= true;
1327 u
->cgroup_realized_mask
= target_mask
;
1328 u
->cgroup_enabled_mask
= enable_mask
;
1330 if (u
->type
!= UNIT_SLICE
&& !c
->delegate
) {
1332 /* Then, possibly move things over, but not if
1333 * subgroups may contain processes, which is the case
1334 * for slice and delegation units. */
1335 r
= cg_migrate_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, u
->cgroup_path
, migrate_callback
, u
);
1337 log_unit_warning_errno(u
, r
, "Failed to migrate cgroup from to %s, ignoring: %m", u
->cgroup_path
);
1343 int unit_attach_pids_to_cgroup(Unit
*u
) {
1347 r
= unit_realize_cgroup(u
);
1351 r
= cg_attach_many_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, u
->pids
, migrate_callback
, u
);
1358 static bool unit_has_mask_realized(Unit
*u
, CGroupMask target_mask
, CGroupMask enable_mask
) {
1361 return u
->cgroup_realized
&& u
->cgroup_realized_mask
== target_mask
&& u
->cgroup_enabled_mask
== enable_mask
;
1364 /* Check if necessary controllers and attributes for a unit are in place.
1366 * If so, do nothing.
1367 * If not, create paths, move processes over, and set attributes.
1369 * Returns 0 on success and < 0 on failure. */
1370 static int unit_realize_cgroup_now(Unit
*u
, ManagerState state
) {
1371 CGroupMask target_mask
, enable_mask
;
1376 if (u
->in_cgroup_queue
) {
1377 LIST_REMOVE(cgroup_queue
, u
->manager
->cgroup_queue
, u
);
1378 u
->in_cgroup_queue
= false;
1381 target_mask
= unit_get_target_mask(u
);
1382 enable_mask
= unit_get_enable_mask(u
);
1384 if (unit_has_mask_realized(u
, target_mask
, enable_mask
))
1387 /* First, realize parents */
1388 if (UNIT_ISSET(u
->slice
)) {
1389 r
= unit_realize_cgroup_now(UNIT_DEREF(u
->slice
), state
);
1394 /* And then do the real work */
1395 r
= unit_create_cgroup(u
, target_mask
, enable_mask
);
1399 /* Finally, apply the necessary attributes. */
1400 cgroup_context_apply(u
, target_mask
, state
);
1405 static void unit_add_to_cgroup_queue(Unit
*u
) {
1407 if (u
->in_cgroup_queue
)
1410 LIST_PREPEND(cgroup_queue
, u
->manager
->cgroup_queue
, u
);
1411 u
->in_cgroup_queue
= true;
1414 unsigned manager_dispatch_cgroup_queue(Manager
*m
) {
1420 state
= manager_state(m
);
1422 while ((i
= m
->cgroup_queue
)) {
1423 assert(i
->in_cgroup_queue
);
1425 r
= unit_realize_cgroup_now(i
, state
);
1427 log_warning_errno(r
, "Failed to realize cgroups for queued unit %s, ignoring: %m", i
->id
);
1435 static void unit_queue_siblings(Unit
*u
) {
1438 /* This adds the siblings of the specified unit and the
1439 * siblings of all parent units to the cgroup queue. (But
1440 * neither the specified unit itself nor the parents.) */
1442 while ((slice
= UNIT_DEREF(u
->slice
))) {
1446 SET_FOREACH(m
, slice
->dependencies
[UNIT_BEFORE
], i
) {
1450 /* Skip units that have a dependency on the slice
1451 * but aren't actually in it. */
1452 if (UNIT_DEREF(m
->slice
) != slice
)
1455 /* No point in doing cgroup application for units
1456 * without active processes. */
1457 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m
)))
1460 /* If the unit doesn't need any new controllers
1461 * and has current ones realized, it doesn't need
1463 if (unit_has_mask_realized(m
, unit_get_target_mask(m
), unit_get_enable_mask(m
)))
1466 unit_add_to_cgroup_queue(m
);
1473 int unit_realize_cgroup(Unit
*u
) {
1476 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1479 /* So, here's the deal: when realizing the cgroups for this
1480 * unit, we need to first create all parents, but there's more
1481 * actually: for the weight-based controllers we also need to
1482 * make sure that all our siblings (i.e. units that are in the
1483 * same slice as we are) have cgroups, too. Otherwise, things
1484 * would become very uneven as each of their processes would
1485 * get as much resources as all our group together. This call
1486 * will synchronously create the parent cgroups, but will
1487 * defer work on the siblings to the next event loop
1490 /* Add all sibling slices to the cgroup queue. */
1491 unit_queue_siblings(u
);
1493 /* And realize this one now (and apply the values) */
1494 return unit_realize_cgroup_now(u
, manager_state(u
->manager
));
1497 void unit_release_cgroup(Unit
*u
) {
1500 /* Forgets all cgroup details for this cgroup */
1502 if (u
->cgroup_path
) {
1503 (void) hashmap_remove(u
->manager
->cgroup_unit
, u
->cgroup_path
);
1504 u
->cgroup_path
= mfree(u
->cgroup_path
);
1507 if (u
->cgroup_inotify_wd
>= 0) {
1508 if (inotify_rm_watch(u
->manager
->cgroup_inotify_fd
, u
->cgroup_inotify_wd
) < 0)
1509 log_unit_debug_errno(u
, errno
, "Failed to remove cgroup inotify watch %i for %s, ignoring", u
->cgroup_inotify_wd
, u
->id
);
1511 (void) hashmap_remove(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
));
1512 u
->cgroup_inotify_wd
= -1;
1516 void unit_prune_cgroup(Unit
*u
) {
1522 /* Removes the cgroup, if empty and possible, and stops watching it. */
1524 if (!u
->cgroup_path
)
1527 is_root_slice
= unit_has_name(u
, SPECIAL_ROOT_SLICE
);
1529 r
= cg_trim_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, !is_root_slice
);
1531 log_unit_debug_errno(u
, r
, "Failed to destroy cgroup %s, ignoring: %m", u
->cgroup_path
);
1538 unit_release_cgroup(u
);
1540 u
->cgroup_realized
= false;
1541 u
->cgroup_realized_mask
= 0;
1542 u
->cgroup_enabled_mask
= 0;
1545 int unit_search_main_pid(Unit
*u
, pid_t
*ret
) {
1546 _cleanup_fclose_
FILE *f
= NULL
;
1547 pid_t pid
= 0, npid
, mypid
;
1553 if (!u
->cgroup_path
)
1556 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, &f
);
1561 while (cg_read_pid(f
, &npid
) > 0) {
1567 /* Ignore processes that aren't our kids */
1568 if (get_process_ppid(npid
, &ppid
) >= 0 && ppid
!= mypid
)
1572 /* Dang, there's more than one daemonized PID
1573 in this group, so we don't know what process
1574 is the main process. */
1585 static int unit_watch_pids_in_path(Unit
*u
, const char *path
) {
1586 _cleanup_closedir_
DIR *d
= NULL
;
1587 _cleanup_fclose_
FILE *f
= NULL
;
1593 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, path
, &f
);
1599 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
1600 r
= unit_watch_pid(u
, pid
);
1601 if (r
< 0 && ret
>= 0)
1605 if (r
< 0 && ret
>= 0)
1609 r
= cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER
, path
, &d
);
1616 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
1617 _cleanup_free_
char *p
= NULL
;
1619 p
= strjoin(path
, "/", fn
, NULL
);
1625 r
= unit_watch_pids_in_path(u
, p
);
1626 if (r
< 0 && ret
>= 0)
1630 if (r
< 0 && ret
>= 0)
1637 int unit_watch_all_pids(Unit
*u
) {
1640 /* Adds all PIDs from our cgroup to the set of PIDs we
1641 * watch. This is a fallback logic for cases where we do not
1642 * get reliable cgroup empty notifications: we try to use
1643 * SIGCHLD as replacement. */
1645 if (!u
->cgroup_path
)
1648 if (cg_unified() > 0) /* On unified we can use proper notifications */
1651 return unit_watch_pids_in_path(u
, u
->cgroup_path
);
1654 int unit_notify_cgroup_empty(Unit
*u
) {
1659 if (!u
->cgroup_path
)
1662 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
);
1666 unit_add_to_gc_queue(u
);
1668 if (UNIT_VTABLE(u
)->notify_cgroup_empty
)
1669 UNIT_VTABLE(u
)->notify_cgroup_empty(u
);
1674 static int on_cgroup_inotify_event(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1675 Manager
*m
= userdata
;
1682 union inotify_event_buffer buffer
;
1683 struct inotify_event
*e
;
1686 l
= read(fd
, &buffer
, sizeof(buffer
));
1688 if (errno
== EINTR
|| errno
== EAGAIN
)
1691 return log_error_errno(errno
, "Failed to read control group inotify events: %m");
1694 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
1698 /* Queue overflow has no watch descriptor */
1701 if (e
->mask
& IN_IGNORED
)
1702 /* The watch was just removed */
1705 u
= hashmap_get(m
->cgroup_inotify_wd_unit
, INT_TO_PTR(e
->wd
));
1706 if (!u
) /* Not that inotify might deliver
1707 * events for a watch even after it
1708 * was removed, because it was queued
1709 * before the removal. Let's ignore
1710 * this here safely. */
1713 (void) unit_notify_cgroup_empty(u
);
1718 int manager_setup_cgroup(Manager
*m
) {
1719 _cleanup_free_
char *path
= NULL
;
1726 /* 1. Determine hierarchy */
1727 m
->cgroup_root
= mfree(m
->cgroup_root
);
1728 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 0, &m
->cgroup_root
);
1730 return log_error_errno(r
, "Cannot determine cgroup we are running in: %m");
1732 /* Chop off the init scope, if we are already located in it */
1733 e
= endswith(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
1735 /* LEGACY: Also chop off the system slice if we are in
1736 * it. This is to support live upgrades from older systemd
1737 * versions where PID 1 was moved there. Also see
1738 * cg_get_root_path(). */
1739 if (!e
&& MANAGER_IS_SYSTEM(m
)) {
1740 e
= endswith(m
->cgroup_root
, "/" SPECIAL_SYSTEM_SLICE
);
1742 e
= endswith(m
->cgroup_root
, "/system"); /* even more legacy */
1747 /* And make sure to store away the root value without trailing
1748 * slash, even for the root dir, so that we can easily prepend
1750 while ((e
= endswith(m
->cgroup_root
, "/")))
1754 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, NULL
, &path
);
1756 return log_error_errno(r
, "Cannot find cgroup mount point: %m");
1758 unified
= cg_unified();
1760 return log_error_errno(r
, "Couldn't determine if we are running in the unified hierarchy: %m");
1762 log_debug("Unified cgroup hierarchy is located at %s.", path
);
1764 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER
". File system hierarchy is at %s.", path
);
1767 const char *scope_path
;
1769 /* 3. Install agent */
1772 /* In the unified hierarchy we can get
1773 * cgroup empty notifications via inotify. */
1775 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
1776 safe_close(m
->cgroup_inotify_fd
);
1778 m
->cgroup_inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
1779 if (m
->cgroup_inotify_fd
< 0)
1780 return log_error_errno(errno
, "Failed to create control group inotify object: %m");
1782 r
= sd_event_add_io(m
->event
, &m
->cgroup_inotify_event_source
, m
->cgroup_inotify_fd
, EPOLLIN
, on_cgroup_inotify_event
, m
);
1784 return log_error_errno(r
, "Failed to watch control group inotify object: %m");
1786 /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
1787 * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
1788 r
= sd_event_source_set_priority(m
->cgroup_inotify_event_source
, SD_EVENT_PRIORITY_NORMAL
-5);
1790 return log_error_errno(r
, "Failed to set priority of inotify event source: %m");
1792 (void) sd_event_source_set_description(m
->cgroup_inotify_event_source
, "cgroup-inotify");
1794 } else if (MANAGER_IS_SYSTEM(m
)) {
1796 /* On the legacy hierarchy we only get
1797 * notifications via cgroup agents. (Which
1798 * isn't really reliable, since it does not
1799 * generate events when control groups with
1800 * children run empty. */
1802 r
= cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER
, SYSTEMD_CGROUP_AGENT_PATH
);
1804 log_warning_errno(r
, "Failed to install release agent, ignoring: %m");
1806 log_debug("Installed release agent.");
1808 log_debug("Release agent already installed.");
1811 /* 4. Make sure we are in the special "init.scope" unit in the root slice. */
1812 scope_path
= strjoina(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
1813 r
= cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
1815 return log_error_errno(r
, "Failed to create %s control group: %m", scope_path
);
1817 /* also, move all other userspace processes remaining
1818 * in the root cgroup into that scope. */
1819 r
= cg_migrate(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
1821 log_warning_errno(r
, "Couldn't move remaining userspace processes, ignoring: %m");
1823 /* 5. And pin it, so that it cannot be unmounted */
1824 safe_close(m
->pin_cgroupfs_fd
);
1825 m
->pin_cgroupfs_fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOCTTY
|O_NONBLOCK
);
1826 if (m
->pin_cgroupfs_fd
< 0)
1827 return log_error_errno(errno
, "Failed to open pin file: %m");
1829 /* 6. Always enable hierarchical support if it exists... */
1831 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
1834 /* 7. Figure out which controllers are supported */
1835 r
= cg_mask_supported(&m
->cgroup_supported
);
1837 return log_error_errno(r
, "Failed to determine supported controllers: %m");
1839 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++)
1840 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c
), yes_no(m
->cgroup_supported
& CGROUP_CONTROLLER_TO_MASK(c
)));
1845 void manager_shutdown_cgroup(Manager
*m
, bool delete) {
1848 /* We can't really delete the group, since we are in it. But
1850 if (delete && m
->cgroup_root
)
1851 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, false);
1853 m
->cgroup_inotify_wd_unit
= hashmap_free(m
->cgroup_inotify_wd_unit
);
1855 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
1856 m
->cgroup_inotify_fd
= safe_close(m
->cgroup_inotify_fd
);
1858 m
->pin_cgroupfs_fd
= safe_close(m
->pin_cgroupfs_fd
);
1860 m
->cgroup_root
= mfree(m
->cgroup_root
);
1863 Unit
* manager_get_unit_by_cgroup(Manager
*m
, const char *cgroup
) {
1870 u
= hashmap_get(m
->cgroup_unit
, cgroup
);
1874 p
= strdupa(cgroup
);
1878 e
= strrchr(p
, '/');
1880 return hashmap_get(m
->cgroup_unit
, SPECIAL_ROOT_SLICE
);
1884 u
= hashmap_get(m
->cgroup_unit
, p
);
1890 Unit
*manager_get_unit_by_pid_cgroup(Manager
*m
, pid_t pid
) {
1891 _cleanup_free_
char *cgroup
= NULL
;
1899 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &cgroup
);
1903 return manager_get_unit_by_cgroup(m
, cgroup
);
1906 Unit
*manager_get_unit_by_pid(Manager
*m
, pid_t pid
) {
1915 return hashmap_get(m
->units
, SPECIAL_INIT_SCOPE
);
1917 u
= hashmap_get(m
->watch_pids1
, PID_TO_PTR(pid
));
1921 u
= hashmap_get(m
->watch_pids2
, PID_TO_PTR(pid
));
1925 return manager_get_unit_by_pid_cgroup(m
, pid
);
1928 int manager_notify_cgroup_empty(Manager
*m
, const char *cgroup
) {
1934 log_debug("Got cgroup empty notification for: %s", cgroup
);
1936 u
= manager_get_unit_by_cgroup(m
, cgroup
);
1940 return unit_notify_cgroup_empty(u
);
1943 int unit_get_memory_current(Unit
*u
, uint64_t *ret
) {
1944 _cleanup_free_
char *v
= NULL
;
1950 if (!u
->cgroup_path
)
1953 if ((u
->cgroup_realized_mask
& CGROUP_MASK_MEMORY
) == 0)
1956 if (cg_unified() <= 0)
1957 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.usage_in_bytes", &v
);
1959 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.current", &v
);
1965 return safe_atou64(v
, ret
);
1968 int unit_get_tasks_current(Unit
*u
, uint64_t *ret
) {
1969 _cleanup_free_
char *v
= NULL
;
1975 if (!u
->cgroup_path
)
1978 if ((u
->cgroup_realized_mask
& CGROUP_MASK_PIDS
) == 0)
1981 r
= cg_get_attribute("pids", u
->cgroup_path
, "pids.current", &v
);
1987 return safe_atou64(v
, ret
);
1990 static int unit_get_cpu_usage_raw(Unit
*u
, nsec_t
*ret
) {
1991 _cleanup_free_
char *v
= NULL
;
1998 if (!u
->cgroup_path
)
2001 if (cg_unified() > 0) {
2002 const char *keys
[] = { "usage_usec", NULL
};
2003 _cleanup_free_
char *val
= NULL
;
2006 if ((u
->cgroup_realized_mask
& CGROUP_MASK_CPU
) == 0)
2009 r
= cg_get_keyed_attribute("cpu", u
->cgroup_path
, "cpu.stat", keys
, &val
);
2013 r
= safe_atou64(val
, &us
);
2017 ns
= us
* NSEC_PER_USEC
;
2019 if ((u
->cgroup_realized_mask
& CGROUP_MASK_CPUACCT
) == 0)
2022 r
= cg_get_attribute("cpuacct", u
->cgroup_path
, "cpuacct.usage", &v
);
2028 r
= safe_atou64(v
, &ns
);
2037 int unit_get_cpu_usage(Unit
*u
, nsec_t
*ret
) {
2041 r
= unit_get_cpu_usage_raw(u
, &ns
);
2045 if (ns
> u
->cpu_usage_base
)
2046 ns
-= u
->cpu_usage_base
;
2054 int unit_reset_cpu_usage(Unit
*u
) {
2060 r
= unit_get_cpu_usage_raw(u
, &ns
);
2062 u
->cpu_usage_base
= 0;
2066 u
->cpu_usage_base
= ns
;
2070 bool unit_cgroup_delegate(Unit
*u
) {
2075 c
= unit_get_cgroup_context(u
);
2082 void unit_invalidate_cgroup(Unit
*u
, CGroupMask m
) {
2085 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2091 /* always invalidate compat pairs together */
2092 if (m
& (CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
))
2093 m
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
2095 if ((u
->cgroup_realized_mask
& m
) == 0)
2098 u
->cgroup_realized_mask
&= ~m
;
2099 unit_add_to_cgroup_queue(u
);
2102 void manager_invalidate_startup_units(Manager
*m
) {
2108 SET_FOREACH(u
, m
->startup_units
, i
)
2109 unit_invalidate_cgroup(u
, CGROUP_MASK_CPU
|CGROUP_MASK_IO
|CGROUP_MASK_BLKIO
);
2112 static const char* const cgroup_device_policy_table
[_CGROUP_DEVICE_POLICY_MAX
] = {
2113 [CGROUP_AUTO
] = "auto",
2114 [CGROUP_CLOSED
] = "closed",
2115 [CGROUP_STRICT
] = "strict",
2118 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy
, CGroupDevicePolicy
);