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
;
69 c
->memory_swap_max
= CGROUP_LIMIT_MAX
;
71 c
->memory_limit
= CGROUP_LIMIT_MAX
;
73 c
->io_weight
= CGROUP_WEIGHT_INVALID
;
74 c
->startup_io_weight
= CGROUP_WEIGHT_INVALID
;
76 c
->blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
;
77 c
->startup_blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
;
79 c
->tasks_max
= (uint64_t) -1;
82 void cgroup_context_free_device_allow(CGroupContext
*c
, CGroupDeviceAllow
*a
) {
86 LIST_REMOVE(device_allow
, c
->device_allow
, a
);
91 void cgroup_context_free_io_device_weight(CGroupContext
*c
, CGroupIODeviceWeight
*w
) {
95 LIST_REMOVE(device_weights
, c
->io_device_weights
, w
);
100 void cgroup_context_free_io_device_limit(CGroupContext
*c
, CGroupIODeviceLimit
*l
) {
104 LIST_REMOVE(device_limits
, c
->io_device_limits
, l
);
109 void cgroup_context_free_blockio_device_weight(CGroupContext
*c
, CGroupBlockIODeviceWeight
*w
) {
113 LIST_REMOVE(device_weights
, c
->blockio_device_weights
, w
);
118 void cgroup_context_free_blockio_device_bandwidth(CGroupContext
*c
, CGroupBlockIODeviceBandwidth
*b
) {
122 LIST_REMOVE(device_bandwidths
, c
->blockio_device_bandwidths
, b
);
127 void cgroup_context_done(CGroupContext
*c
) {
130 while (c
->io_device_weights
)
131 cgroup_context_free_io_device_weight(c
, c
->io_device_weights
);
133 while (c
->io_device_limits
)
134 cgroup_context_free_io_device_limit(c
, c
->io_device_limits
);
136 while (c
->blockio_device_weights
)
137 cgroup_context_free_blockio_device_weight(c
, c
->blockio_device_weights
);
139 while (c
->blockio_device_bandwidths
)
140 cgroup_context_free_blockio_device_bandwidth(c
, c
->blockio_device_bandwidths
);
142 while (c
->device_allow
)
143 cgroup_context_free_device_allow(c
, c
->device_allow
);
146 void cgroup_context_dump(CGroupContext
*c
, FILE* f
, const char *prefix
) {
147 CGroupIODeviceLimit
*il
;
148 CGroupIODeviceWeight
*iw
;
149 CGroupBlockIODeviceBandwidth
*b
;
150 CGroupBlockIODeviceWeight
*w
;
151 CGroupDeviceAllow
*a
;
152 char u
[FORMAT_TIMESPAN_MAX
];
157 prefix
= strempty(prefix
);
160 "%sCPUAccounting=%s\n"
161 "%sIOAccounting=%s\n"
162 "%sBlockIOAccounting=%s\n"
163 "%sMemoryAccounting=%s\n"
164 "%sTasksAccounting=%s\n"
165 "%sCPUWeight=%" PRIu64
"\n"
166 "%sStartupCPUWeight=%" PRIu64
"\n"
167 "%sCPUShares=%" PRIu64
"\n"
168 "%sStartupCPUShares=%" PRIu64
"\n"
169 "%sCPUQuotaPerSecSec=%s\n"
170 "%sIOWeight=%" PRIu64
"\n"
171 "%sStartupIOWeight=%" PRIu64
"\n"
172 "%sBlockIOWeight=%" PRIu64
"\n"
173 "%sStartupBlockIOWeight=%" PRIu64
"\n"
174 "%sMemoryLow=%" PRIu64
"\n"
175 "%sMemoryHigh=%" PRIu64
"\n"
176 "%sMemoryMax=%" PRIu64
"\n"
177 "%sMemorySwapMax=%" PRIu64
"\n"
178 "%sMemoryLimit=%" PRIu64
"\n"
179 "%sTasksMax=%" PRIu64
"\n"
180 "%sDevicePolicy=%s\n"
182 prefix
, yes_no(c
->cpu_accounting
),
183 prefix
, yes_no(c
->io_accounting
),
184 prefix
, yes_no(c
->blockio_accounting
),
185 prefix
, yes_no(c
->memory_accounting
),
186 prefix
, yes_no(c
->tasks_accounting
),
187 prefix
, c
->cpu_weight
,
188 prefix
, c
->startup_cpu_weight
,
189 prefix
, c
->cpu_shares
,
190 prefix
, c
->startup_cpu_shares
,
191 prefix
, format_timespan(u
, sizeof(u
), c
->cpu_quota_per_sec_usec
, 1),
192 prefix
, c
->io_weight
,
193 prefix
, c
->startup_io_weight
,
194 prefix
, c
->blockio_weight
,
195 prefix
, c
->startup_blockio_weight
,
196 prefix
, c
->memory_low
,
197 prefix
, c
->memory_high
,
198 prefix
, c
->memory_max
,
199 prefix
, c
->memory_swap_max
,
200 prefix
, c
->memory_limit
,
201 prefix
, c
->tasks_max
,
202 prefix
, cgroup_device_policy_to_string(c
->device_policy
),
203 prefix
, yes_no(c
->delegate
));
205 LIST_FOREACH(device_allow
, a
, c
->device_allow
)
207 "%sDeviceAllow=%s %s%s%s\n",
210 a
->r
? "r" : "", a
->w
? "w" : "", a
->m
? "m" : "");
212 LIST_FOREACH(device_weights
, iw
, c
->io_device_weights
)
214 "%sIODeviceWeight=%s %" PRIu64
,
219 LIST_FOREACH(device_limits
, il
, c
->io_device_limits
) {
220 char buf
[FORMAT_BYTES_MAX
];
221 CGroupIOLimitType type
;
223 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
224 if (il
->limits
[type
] != cgroup_io_limit_defaults
[type
])
228 cgroup_io_limit_type_to_string(type
),
230 format_bytes(buf
, sizeof(buf
), il
->limits
[type
]));
233 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
235 "%sBlockIODeviceWeight=%s %" PRIu64
,
240 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
) {
241 char buf
[FORMAT_BYTES_MAX
];
243 if (b
->rbps
!= CGROUP_LIMIT_MAX
)
245 "%sBlockIOReadBandwidth=%s %s\n",
248 format_bytes(buf
, sizeof(buf
), b
->rbps
));
249 if (b
->wbps
!= CGROUP_LIMIT_MAX
)
251 "%sBlockIOWriteBandwidth=%s %s\n",
254 format_bytes(buf
, sizeof(buf
), b
->wbps
));
258 static int lookup_block_device(const char *p
, dev_t
*dev
) {
267 return log_warning_errno(errno
, "Couldn't stat device %s: %m", p
);
269 if (S_ISBLK(st
.st_mode
))
271 else if (major(st
.st_dev
) != 0) {
272 /* If this is not a device node then find the block
273 * device this file is stored on */
276 /* If this is a partition, try to get the originating
278 block_get_whole_disk(*dev
, dev
);
280 log_warning("%s is not a block device and file system block device cannot be determined or is not local.", p
);
287 static int whitelist_device(const char *path
, const char *node
, const char *acc
) {
288 char buf
[2+DECIMAL_STR_MAX(dev_t
)*2+2+4];
295 if (stat(node
, &st
) < 0) {
296 log_warning("Couldn't stat device %s", node
);
300 if (!S_ISCHR(st
.st_mode
) && !S_ISBLK(st
.st_mode
)) {
301 log_warning("%s is not a device.", node
);
307 S_ISCHR(st
.st_mode
) ? 'c' : 'b',
308 major(st
.st_rdev
), minor(st
.st_rdev
),
311 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
313 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
314 "Failed to set devices.allow on %s: %m", path
);
319 static int whitelist_major(const char *path
, const char *name
, char type
, const char *acc
) {
320 _cleanup_fclose_
FILE *f
= NULL
;
327 assert(type
== 'b' || type
== 'c');
329 f
= fopen("/proc/devices", "re");
331 return log_warning_errno(errno
, "Cannot open /proc/devices to resolve %s (%c): %m", name
, type
);
333 FOREACH_LINE(line
, f
, goto fail
) {
334 char buf
[2+DECIMAL_STR_MAX(unsigned)+3+4], *p
, *w
;
339 if (type
== 'c' && streq(line
, "Character devices:")) {
344 if (type
== 'b' && streq(line
, "Block devices:")) {
359 w
= strpbrk(p
, WHITESPACE
);
364 r
= safe_atou(p
, &maj
);
371 w
+= strspn(w
, WHITESPACE
);
373 if (fnmatch(name
, w
, 0) != 0)
382 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
384 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
385 "Failed to set devices.allow on %s: %m", path
);
391 log_warning_errno(errno
, "Failed to read /proc/devices: %m");
395 static bool cgroup_context_has_cpu_weight(CGroupContext
*c
) {
396 return c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
||
397 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
;
400 static bool cgroup_context_has_cpu_shares(CGroupContext
*c
) {
401 return c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
||
402 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
;
405 static uint64_t cgroup_context_cpu_weight(CGroupContext
*c
, ManagerState state
) {
406 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
407 c
->startup_cpu_weight
!= CGROUP_WEIGHT_INVALID
)
408 return c
->startup_cpu_weight
;
409 else if (c
->cpu_weight
!= CGROUP_WEIGHT_INVALID
)
410 return c
->cpu_weight
;
412 return CGROUP_WEIGHT_DEFAULT
;
415 static uint64_t cgroup_context_cpu_shares(CGroupContext
*c
, ManagerState state
) {
416 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
417 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
418 return c
->startup_cpu_shares
;
419 else if (c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
)
420 return c
->cpu_shares
;
422 return CGROUP_CPU_SHARES_DEFAULT
;
425 static void cgroup_apply_unified_cpu_config(Unit
*u
, uint64_t weight
, uint64_t quota
) {
426 char buf
[MAX(DECIMAL_STR_MAX(uint64_t) + 1, (DECIMAL_STR_MAX(usec_t
) + 1) * 2)];
429 xsprintf(buf
, "%" PRIu64
"\n", weight
);
430 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.weight", buf
);
432 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
433 "Failed to set cpu.weight: %m");
435 if (quota
!= USEC_INFINITY
)
436 xsprintf(buf
, USEC_FMT
" " USEC_FMT
"\n",
437 quota
* CGROUP_CPU_QUOTA_PERIOD_USEC
/ USEC_PER_SEC
, CGROUP_CPU_QUOTA_PERIOD_USEC
);
439 xsprintf(buf
, "max " USEC_FMT
"\n", CGROUP_CPU_QUOTA_PERIOD_USEC
);
441 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.max", buf
);
444 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
445 "Failed to set cpu.max: %m");
448 static void cgroup_apply_legacy_cpu_config(Unit
*u
, uint64_t shares
, uint64_t quota
) {
449 char buf
[MAX(DECIMAL_STR_MAX(uint64_t), DECIMAL_STR_MAX(usec_t
)) + 1];
452 xsprintf(buf
, "%" PRIu64
"\n", shares
);
453 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.shares", buf
);
455 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
456 "Failed to set cpu.shares: %m");
458 xsprintf(buf
, USEC_FMT
"\n", CGROUP_CPU_QUOTA_PERIOD_USEC
);
459 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_period_us", buf
);
461 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
462 "Failed to set cpu.cfs_period_us: %m");
464 if (quota
!= USEC_INFINITY
) {
465 xsprintf(buf
, USEC_FMT
"\n", quota
* CGROUP_CPU_QUOTA_PERIOD_USEC
/ USEC_PER_SEC
);
466 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_quota_us", buf
);
468 r
= cg_set_attribute("cpu", u
->cgroup_path
, "cpu.cfs_quota_us", "-1");
470 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
471 "Failed to set cpu.cfs_quota_us: %m");
474 static uint64_t cgroup_cpu_shares_to_weight(uint64_t shares
) {
475 return CLAMP(shares
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_CPU_SHARES_DEFAULT
,
476 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
479 static uint64_t cgroup_cpu_weight_to_shares(uint64_t weight
) {
480 return CLAMP(weight
* CGROUP_CPU_SHARES_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
481 CGROUP_CPU_SHARES_MIN
, CGROUP_CPU_SHARES_MAX
);
484 static bool cgroup_context_has_io_config(CGroupContext
*c
) {
485 return c
->io_accounting
||
486 c
->io_weight
!= CGROUP_WEIGHT_INVALID
||
487 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
||
488 c
->io_device_weights
||
492 static bool cgroup_context_has_blockio_config(CGroupContext
*c
) {
493 return c
->blockio_accounting
||
494 c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
495 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
496 c
->blockio_device_weights
||
497 c
->blockio_device_bandwidths
;
500 static uint64_t cgroup_context_io_weight(CGroupContext
*c
, ManagerState state
) {
501 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
502 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
)
503 return c
->startup_io_weight
;
504 else if (c
->io_weight
!= CGROUP_WEIGHT_INVALID
)
507 return CGROUP_WEIGHT_DEFAULT
;
510 static uint64_t cgroup_context_blkio_weight(CGroupContext
*c
, ManagerState state
) {
511 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
512 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
513 return c
->startup_blockio_weight
;
514 else if (c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
515 return c
->blockio_weight
;
517 return CGROUP_BLKIO_WEIGHT_DEFAULT
;
520 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight
) {
521 return CLAMP(blkio_weight
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_BLKIO_WEIGHT_DEFAULT
,
522 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
525 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight
) {
526 return CLAMP(io_weight
* CGROUP_BLKIO_WEIGHT_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
527 CGROUP_BLKIO_WEIGHT_MIN
, CGROUP_BLKIO_WEIGHT_MAX
);
530 static void cgroup_apply_io_device_weight(Unit
*u
, const char *dev_path
, uint64_t io_weight
) {
531 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
535 r
= lookup_block_device(dev_path
, &dev
);
539 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), io_weight
);
540 r
= cg_set_attribute("io", u
->cgroup_path
, "io.weight", buf
);
542 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
543 "Failed to set io.weight: %m");
546 static void cgroup_apply_blkio_device_weight(Unit
*u
, const char *dev_path
, uint64_t blkio_weight
) {
547 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
551 r
= lookup_block_device(dev_path
, &dev
);
555 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), blkio_weight
);
556 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.weight_device", buf
);
558 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
559 "Failed to set blkio.weight_device: %m");
562 static unsigned cgroup_apply_io_device_limit(Unit
*u
, const char *dev_path
, uint64_t *limits
) {
563 char limit_bufs
[_CGROUP_IO_LIMIT_TYPE_MAX
][DECIMAL_STR_MAX(uint64_t)];
564 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
565 CGroupIOLimitType type
;
570 r
= lookup_block_device(dev_path
, &dev
);
574 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++) {
575 if (limits
[type
] != cgroup_io_limit_defaults
[type
]) {
576 xsprintf(limit_bufs
[type
], "%" PRIu64
, limits
[type
]);
579 xsprintf(limit_bufs
[type
], "%s", limits
[type
] == CGROUP_LIMIT_MAX
? "max" : "0");
583 xsprintf(buf
, "%u:%u rbps=%s wbps=%s riops=%s wiops=%s\n", major(dev
), minor(dev
),
584 limit_bufs
[CGROUP_IO_RBPS_MAX
], limit_bufs
[CGROUP_IO_WBPS_MAX
],
585 limit_bufs
[CGROUP_IO_RIOPS_MAX
], limit_bufs
[CGROUP_IO_WIOPS_MAX
]);
586 r
= cg_set_attribute("io", u
->cgroup_path
, "io.max", buf
);
588 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
589 "Failed to set io.max: %m");
593 static unsigned cgroup_apply_blkio_device_limit(Unit
*u
, const char *dev_path
, uint64_t rbps
, uint64_t wbps
) {
594 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
599 r
= lookup_block_device(dev_path
, &dev
);
603 if (rbps
!= CGROUP_LIMIT_MAX
)
605 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), rbps
);
606 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.throttle.read_bps_device", buf
);
608 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
609 "Failed to set blkio.throttle.read_bps_device: %m");
611 if (wbps
!= CGROUP_LIMIT_MAX
)
613 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), wbps
);
614 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.throttle.write_bps_device", buf
);
616 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
617 "Failed to set blkio.throttle.write_bps_device: %m");
622 static bool cgroup_context_has_unified_memory_config(CGroupContext
*c
) {
623 return c
->memory_low
> 0 || c
->memory_high
!= CGROUP_LIMIT_MAX
|| c
->memory_max
!= CGROUP_LIMIT_MAX
|| c
->memory_swap_max
!= CGROUP_LIMIT_MAX
;
626 static void cgroup_apply_unified_memory_limit(Unit
*u
, const char *file
, uint64_t v
) {
627 char buf
[DECIMAL_STR_MAX(uint64_t) + 1] = "max";
630 if (v
!= CGROUP_LIMIT_MAX
)
631 xsprintf(buf
, "%" PRIu64
"\n", v
);
633 r
= cg_set_attribute("memory", u
->cgroup_path
, file
, buf
);
635 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
636 "Failed to set %s: %m", file
);
639 static void cgroup_context_apply(Unit
*u
, CGroupMask mask
, ManagerState state
) {
647 c
= unit_get_cgroup_context(u
);
648 path
= u
->cgroup_path
;
656 /* Some cgroup attributes are not supported on the root cgroup,
657 * hence silently ignore */
658 is_root
= isempty(path
) || path_equal(path
, "/");
660 /* Make sure we don't try to display messages with an empty path. */
663 /* We generally ignore errors caused by read-only mounted
664 * cgroup trees (assuming we are running in a container then),
665 * and missing cgroups, i.e. EROFS and ENOENT. */
667 if ((mask
& CGROUP_MASK_CPU
) && !is_root
) {
668 bool has_weight
= cgroup_context_has_cpu_weight(c
);
669 bool has_shares
= cgroup_context_has_cpu_shares(c
);
671 if (cg_all_unified() > 0) {
675 weight
= cgroup_context_cpu_weight(c
, state
);
676 else if (has_shares
) {
677 uint64_t shares
= cgroup_context_cpu_shares(c
, state
);
679 weight
= cgroup_cpu_shares_to_weight(shares
);
681 log_cgroup_compat(u
, "Applying [Startup]CpuShares %" PRIu64
" as [Startup]CpuWeight %" PRIu64
" on %s",
682 shares
, weight
, path
);
684 weight
= CGROUP_WEIGHT_DEFAULT
;
686 cgroup_apply_unified_cpu_config(u
, weight
, c
->cpu_quota_per_sec_usec
);
691 shares
= cgroup_context_cpu_shares(c
, state
);
692 else if (has_weight
) {
693 uint64_t weight
= cgroup_context_cpu_weight(c
, state
);
695 shares
= cgroup_cpu_weight_to_shares(weight
);
697 log_cgroup_compat(u
, "Applying [Startup]CpuWeight %" PRIu64
" as [Startup]CpuShares %" PRIu64
" on %s",
698 weight
, shares
, path
);
700 shares
= CGROUP_CPU_SHARES_DEFAULT
;
702 cgroup_apply_legacy_cpu_config(u
, shares
, c
->cpu_quota_per_sec_usec
);
706 if (mask
& CGROUP_MASK_IO
) {
707 bool has_io
= cgroup_context_has_io_config(c
);
708 bool has_blockio
= cgroup_context_has_blockio_config(c
);
711 char buf
[8+DECIMAL_STR_MAX(uint64_t)+1];
715 weight
= cgroup_context_io_weight(c
, state
);
716 else if (has_blockio
) {
717 uint64_t blkio_weight
= cgroup_context_blkio_weight(c
, state
);
719 weight
= cgroup_weight_blkio_to_io(blkio_weight
);
721 log_cgroup_compat(u
, "Applying [Startup]BlockIOWeight %" PRIu64
" as [Startup]IOWeight %" PRIu64
,
722 blkio_weight
, weight
);
724 weight
= CGROUP_WEIGHT_DEFAULT
;
726 xsprintf(buf
, "default %" PRIu64
"\n", weight
);
727 r
= cg_set_attribute("io", path
, "io.weight", buf
);
729 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
730 "Failed to set io.weight: %m");
733 CGroupIODeviceWeight
*w
;
735 /* FIXME: no way to reset this list */
736 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
)
737 cgroup_apply_io_device_weight(u
, w
->path
, w
->weight
);
738 } else if (has_blockio
) {
739 CGroupBlockIODeviceWeight
*w
;
741 /* FIXME: no way to reset this list */
742 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
) {
743 weight
= cgroup_weight_blkio_to_io(w
->weight
);
745 log_cgroup_compat(u
, "Applying BlockIODeviceWeight %" PRIu64
" as IODeviceWeight %" PRIu64
" for %s",
746 w
->weight
, weight
, w
->path
);
748 cgroup_apply_io_device_weight(u
, w
->path
, weight
);
753 /* Apply limits and free ones without config. */
755 CGroupIODeviceLimit
*l
, *next
;
757 LIST_FOREACH_SAFE(device_limits
, l
, next
, c
->io_device_limits
) {
758 if (!cgroup_apply_io_device_limit(u
, l
->path
, l
->limits
))
759 cgroup_context_free_io_device_limit(c
, l
);
761 } else if (has_blockio
) {
762 CGroupBlockIODeviceBandwidth
*b
, *next
;
764 LIST_FOREACH_SAFE(device_bandwidths
, b
, next
, c
->blockio_device_bandwidths
) {
765 uint64_t limits
[_CGROUP_IO_LIMIT_TYPE_MAX
];
766 CGroupIOLimitType type
;
768 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
769 limits
[type
] = cgroup_io_limit_defaults
[type
];
771 limits
[CGROUP_IO_RBPS_MAX
] = b
->rbps
;
772 limits
[CGROUP_IO_WBPS_MAX
] = b
->wbps
;
774 log_cgroup_compat(u
, "Applying BlockIO{Read|Write}Bandwidth %" PRIu64
" %" PRIu64
" as IO{Read|Write}BandwidthMax for %s",
775 b
->rbps
, b
->wbps
, b
->path
);
777 if (!cgroup_apply_io_device_limit(u
, b
->path
, limits
))
778 cgroup_context_free_blockio_device_bandwidth(c
, b
);
783 if (mask
& CGROUP_MASK_BLKIO
) {
784 bool has_io
= cgroup_context_has_io_config(c
);
785 bool has_blockio
= cgroup_context_has_blockio_config(c
);
788 char buf
[DECIMAL_STR_MAX(uint64_t)+1];
792 weight
= cgroup_context_blkio_weight(c
, state
);
794 uint64_t io_weight
= cgroup_context_io_weight(c
, state
);
796 weight
= cgroup_weight_io_to_blkio(cgroup_context_io_weight(c
, state
));
798 log_cgroup_compat(u
, "Applying [Startup]IOWeight %" PRIu64
" as [Startup]BlockIOWeight %" PRIu64
,
801 weight
= CGROUP_BLKIO_WEIGHT_DEFAULT
;
803 xsprintf(buf
, "%" PRIu64
"\n", weight
);
804 r
= cg_set_attribute("blkio", path
, "blkio.weight", buf
);
806 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
807 "Failed to set blkio.weight: %m");
810 CGroupBlockIODeviceWeight
*w
;
812 /* FIXME: no way to reset this list */
813 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
814 cgroup_apply_blkio_device_weight(u
, w
->path
, w
->weight
);
816 CGroupIODeviceWeight
*w
;
818 /* FIXME: no way to reset this list */
819 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
) {
820 weight
= cgroup_weight_io_to_blkio(w
->weight
);
822 log_cgroup_compat(u
, "Applying IODeviceWeight %" PRIu64
" as BlockIODeviceWeight %" PRIu64
" for %s",
823 w
->weight
, weight
, w
->path
);
825 cgroup_apply_blkio_device_weight(u
, w
->path
, weight
);
830 /* Apply limits and free ones without config. */
832 CGroupBlockIODeviceBandwidth
*b
, *next
;
834 LIST_FOREACH_SAFE(device_bandwidths
, b
, next
, c
->blockio_device_bandwidths
) {
835 if (!cgroup_apply_blkio_device_limit(u
, b
->path
, b
->rbps
, b
->wbps
))
836 cgroup_context_free_blockio_device_bandwidth(c
, b
);
839 CGroupIODeviceLimit
*l
, *next
;
841 LIST_FOREACH_SAFE(device_limits
, l
, next
, c
->io_device_limits
) {
842 log_cgroup_compat(u
, "Applying IO{Read|Write}Bandwidth %" PRIu64
" %" PRIu64
" as BlockIO{Read|Write}BandwidthMax for %s",
843 l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
], l
->path
);
845 if (!cgroup_apply_blkio_device_limit(u
, l
->path
, l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
]))
846 cgroup_context_free_io_device_limit(c
, l
);
851 if ((mask
& CGROUP_MASK_MEMORY
) && !is_root
) {
852 if (cg_all_unified() > 0) {
853 uint64_t max
= c
->memory_max
;
854 uint64_t swap_max
= c
->memory_swap_max
;
856 if (cgroup_context_has_unified_memory_config(c
)) {
858 swap_max
= c
->memory_swap_max
;
860 max
= c
->memory_limit
;
862 if (max
!= CGROUP_LIMIT_MAX
)
863 log_cgroup_compat(u
, "Applying MemoryLimit %" PRIu64
" as MemoryMax", max
);
866 cgroup_apply_unified_memory_limit(u
, "memory.low", c
->memory_low
);
867 cgroup_apply_unified_memory_limit(u
, "memory.high", c
->memory_high
);
868 cgroup_apply_unified_memory_limit(u
, "memory.max", max
);
869 cgroup_apply_unified_memory_limit(u
, "memory.swap.max", swap_max
);
871 char buf
[DECIMAL_STR_MAX(uint64_t) + 1];
872 uint64_t val
= c
->memory_limit
;
874 if (val
== CGROUP_LIMIT_MAX
) {
877 if (val
!= CGROUP_LIMIT_MAX
)
878 log_cgroup_compat(u
, "Applying MemoryMax %" PRIi64
" as MemoryLimit", c
->memory_max
);
881 if (val
== CGROUP_LIMIT_MAX
)
882 strncpy(buf
, "-1\n", sizeof(buf
));
884 xsprintf(buf
, "%" PRIu64
"\n", val
);
886 r
= cg_set_attribute("memory", path
, "memory.limit_in_bytes", buf
);
888 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
889 "Failed to set memory.limit_in_bytes: %m");
893 if ((mask
& CGROUP_MASK_DEVICES
) && !is_root
) {
894 CGroupDeviceAllow
*a
;
896 /* Changing the devices list of a populated cgroup
897 * might result in EINVAL, hence ignore EINVAL
900 if (c
->device_allow
|| c
->device_policy
!= CGROUP_AUTO
)
901 r
= cg_set_attribute("devices", path
, "devices.deny", "a");
903 r
= cg_set_attribute("devices", path
, "devices.allow", "a");
905 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
906 "Failed to reset devices.list: %m");
908 if (c
->device_policy
== CGROUP_CLOSED
||
909 (c
->device_policy
== CGROUP_AUTO
&& c
->device_allow
)) {
910 static const char auto_devices
[] =
911 "/dev/null\0" "rwm\0"
912 "/dev/zero\0" "rwm\0"
913 "/dev/full\0" "rwm\0"
914 "/dev/random\0" "rwm\0"
915 "/dev/urandom\0" "rwm\0"
917 "/dev/pts/ptmx\0" "rw\0" /* /dev/pts/ptmx may not be duplicated, but accessed */
918 /* Allow /run/systemd/inaccessible/{chr,blk} devices for mapping InaccessiblePaths */
919 "/run/systemd/inaccessible/chr\0" "rwm\0"
920 "/run/systemd/inaccessible/blk\0" "rwm\0";
924 NULSTR_FOREACH_PAIR(x
, y
, auto_devices
)
925 whitelist_device(path
, x
, y
);
927 whitelist_major(path
, "pts", 'c', "rw");
928 whitelist_major(path
, "kdbus", 'c', "rw");
929 whitelist_major(path
, "kdbus/*", 'c', "rw");
932 LIST_FOREACH(device_allow
, a
, c
->device_allow
) {
948 if (startswith(a
->path
, "/dev/"))
949 whitelist_device(path
, a
->path
, acc
);
950 else if (startswith(a
->path
, "block-"))
951 whitelist_major(path
, a
->path
+ 6, 'b', acc
);
952 else if (startswith(a
->path
, "char-"))
953 whitelist_major(path
, a
->path
+ 5, 'c', acc
);
955 log_unit_debug(u
, "Ignoring device %s while writing cgroup attribute.", a
->path
);
959 if ((mask
& CGROUP_MASK_PIDS
) && !is_root
) {
961 if (c
->tasks_max
!= CGROUP_LIMIT_MAX
) {
962 char buf
[DECIMAL_STR_MAX(uint64_t) + 2];
964 sprintf(buf
, "%" PRIu64
"\n", c
->tasks_max
);
965 r
= cg_set_attribute("pids", path
, "pids.max", buf
);
967 r
= cg_set_attribute("pids", path
, "pids.max", "max");
970 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
971 "Failed to set pids.max: %m");
975 CGroupMask
cgroup_context_get_mask(CGroupContext
*c
) {
978 /* Figure out which controllers we need */
980 if (c
->cpu_accounting
||
981 cgroup_context_has_cpu_weight(c
) ||
982 cgroup_context_has_cpu_shares(c
) ||
983 c
->cpu_quota_per_sec_usec
!= USEC_INFINITY
)
984 mask
|= CGROUP_MASK_CPUACCT
| CGROUP_MASK_CPU
;
986 if (cgroup_context_has_io_config(c
) || cgroup_context_has_blockio_config(c
))
987 mask
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
989 if (c
->memory_accounting
||
990 c
->memory_limit
!= CGROUP_LIMIT_MAX
||
991 cgroup_context_has_unified_memory_config(c
))
992 mask
|= CGROUP_MASK_MEMORY
;
994 if (c
->device_allow
||
995 c
->device_policy
!= CGROUP_AUTO
)
996 mask
|= CGROUP_MASK_DEVICES
;
998 if (c
->tasks_accounting
||
999 c
->tasks_max
!= (uint64_t) -1)
1000 mask
|= CGROUP_MASK_PIDS
;
1005 CGroupMask
unit_get_own_mask(Unit
*u
) {
1008 /* Returns the mask of controllers the unit needs for itself */
1010 c
= unit_get_cgroup_context(u
);
1014 /* If delegation is turned on, then turn on all cgroups,
1015 * unless we are on the legacy hierarchy and the process we
1016 * fork into it is known to drop privileges, and hence
1017 * shouldn't get access to the controllers.
1019 * Note that on the unified hierarchy it is safe to delegate
1020 * controllers to unprivileged services. */
1025 e
= unit_get_exec_context(u
);
1027 exec_context_maintains_privileges(e
) ||
1028 cg_all_unified() > 0)
1029 return _CGROUP_MASK_ALL
;
1032 return cgroup_context_get_mask(c
);
1035 CGroupMask
unit_get_members_mask(Unit
*u
) {
1038 /* Returns the mask of controllers all of the unit's children
1039 * require, merged */
1041 if (u
->cgroup_members_mask_valid
)
1042 return u
->cgroup_members_mask
;
1044 u
->cgroup_members_mask
= 0;
1046 if (u
->type
== UNIT_SLICE
) {
1050 SET_FOREACH(member
, u
->dependencies
[UNIT_BEFORE
], i
) {
1055 if (UNIT_DEREF(member
->slice
) != u
)
1058 u
->cgroup_members_mask
|=
1059 unit_get_own_mask(member
) |
1060 unit_get_members_mask(member
);
1064 u
->cgroup_members_mask_valid
= true;
1065 return u
->cgroup_members_mask
;
1068 CGroupMask
unit_get_siblings_mask(Unit
*u
) {
1071 /* Returns the mask of controllers all of the unit's siblings
1072 * require, i.e. the members mask of the unit's parent slice
1073 * if there is one. */
1075 if (UNIT_ISSET(u
->slice
))
1076 return unit_get_members_mask(UNIT_DEREF(u
->slice
));
1078 return unit_get_own_mask(u
) | unit_get_members_mask(u
);
1081 CGroupMask
unit_get_subtree_mask(Unit
*u
) {
1083 /* Returns the mask of this subtree, meaning of the group
1084 * itself and its children. */
1086 return unit_get_own_mask(u
) | unit_get_members_mask(u
);
1089 CGroupMask
unit_get_target_mask(Unit
*u
) {
1092 /* This returns the cgroup mask of all controllers to enable
1093 * for a specific cgroup, i.e. everything it needs itself,
1094 * plus all that its children need, plus all that its siblings
1095 * need. This is primarily useful on the legacy cgroup
1096 * hierarchy, where we need to duplicate each cgroup in each
1097 * hierarchy that shall be enabled for it. */
1099 mask
= unit_get_own_mask(u
) | unit_get_members_mask(u
) | unit_get_siblings_mask(u
);
1100 mask
&= u
->manager
->cgroup_supported
;
1105 CGroupMask
unit_get_enable_mask(Unit
*u
) {
1108 /* This returns the cgroup mask of all controllers to enable
1109 * for the children of a specific cgroup. This is primarily
1110 * useful for the unified cgroup hierarchy, where each cgroup
1111 * controls which controllers are enabled for its children. */
1113 mask
= unit_get_members_mask(u
);
1114 mask
&= u
->manager
->cgroup_supported
;
1119 /* Recurse from a unit up through its containing slices, propagating
1120 * mask bits upward. A unit is also member of itself. */
1121 void unit_update_cgroup_members_masks(Unit
*u
) {
1127 /* Calculate subtree mask */
1128 m
= unit_get_subtree_mask(u
);
1130 /* See if anything changed from the previous invocation. If
1131 * not, we're done. */
1132 if (u
->cgroup_subtree_mask_valid
&& m
== u
->cgroup_subtree_mask
)
1136 u
->cgroup_subtree_mask_valid
&&
1137 ((m
& ~u
->cgroup_subtree_mask
) != 0) &&
1138 ((~m
& u
->cgroup_subtree_mask
) == 0);
1140 u
->cgroup_subtree_mask
= m
;
1141 u
->cgroup_subtree_mask_valid
= true;
1143 if (UNIT_ISSET(u
->slice
)) {
1144 Unit
*s
= UNIT_DEREF(u
->slice
);
1147 /* There's more set now than before. We
1148 * propagate the new mask to the parent's mask
1149 * (not caring if it actually was valid or
1152 s
->cgroup_members_mask
|= m
;
1155 /* There's less set now than before (or we
1156 * don't know), we need to recalculate
1157 * everything, so let's invalidate the
1158 * parent's members mask */
1160 s
->cgroup_members_mask_valid
= false;
1162 /* And now make sure that this change also hits our
1164 unit_update_cgroup_members_masks(s
);
1168 static const char *migrate_callback(CGroupMask mask
, void *userdata
) {
1175 if (u
->cgroup_path
&&
1176 u
->cgroup_realized
&&
1177 (u
->cgroup_realized_mask
& mask
) == mask
)
1178 return u
->cgroup_path
;
1180 u
= UNIT_DEREF(u
->slice
);
1186 char *unit_default_cgroup_path(Unit
*u
) {
1187 _cleanup_free_
char *escaped
= NULL
, *slice
= NULL
;
1192 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1193 return strdup(u
->manager
->cgroup_root
);
1195 if (UNIT_ISSET(u
->slice
) && !unit_has_name(UNIT_DEREF(u
->slice
), SPECIAL_ROOT_SLICE
)) {
1196 r
= cg_slice_to_path(UNIT_DEREF(u
->slice
)->id
, &slice
);
1201 escaped
= cg_escape(u
->id
);
1206 return strjoin(u
->manager
->cgroup_root
, "/", slice
, "/", escaped
, NULL
);
1208 return strjoin(u
->manager
->cgroup_root
, "/", escaped
, NULL
);
1211 int unit_set_cgroup_path(Unit
*u
, const char *path
) {
1212 _cleanup_free_
char *p
= NULL
;
1224 if (streq_ptr(u
->cgroup_path
, p
))
1228 r
= hashmap_put(u
->manager
->cgroup_unit
, p
, u
);
1233 unit_release_cgroup(u
);
1241 int unit_watch_cgroup(Unit
*u
) {
1242 _cleanup_free_
char *events
= NULL
;
1247 if (!u
->cgroup_path
)
1250 if (u
->cgroup_inotify_wd
>= 0)
1253 /* Only applies to the unified hierarchy */
1254 r
= cg_unified(SYSTEMD_CGROUP_CONTROLLER
);
1256 return log_unit_error_errno(u
, r
, "Failed detect whether the unified hierarchy is used: %m");
1260 /* Don't watch the root slice, it's pointless. */
1261 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1264 r
= hashmap_ensure_allocated(&u
->manager
->cgroup_inotify_wd_unit
, &trivial_hash_ops
);
1268 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "cgroup.events", &events
);
1272 u
->cgroup_inotify_wd
= inotify_add_watch(u
->manager
->cgroup_inotify_fd
, events
, IN_MODIFY
);
1273 if (u
->cgroup_inotify_wd
< 0) {
1275 if (errno
== ENOENT
) /* If the directory is already
1276 * gone we don't need to track
1277 * it, so this is not an error */
1280 return log_unit_error_errno(u
, errno
, "Failed to add inotify watch descriptor for control group %s: %m", u
->cgroup_path
);
1283 r
= hashmap_put(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
), u
);
1285 return log_unit_error_errno(u
, r
, "Failed to add inotify watch descriptor to hash map: %m");
1290 static int unit_create_cgroup(
1292 CGroupMask target_mask
,
1293 CGroupMask enable_mask
) {
1300 c
= unit_get_cgroup_context(u
);
1304 if (!u
->cgroup_path
) {
1305 _cleanup_free_
char *path
= NULL
;
1307 path
= unit_default_cgroup_path(u
);
1311 r
= unit_set_cgroup_path(u
, path
);
1313 return log_unit_error_errno(u
, r
, "Control group %s exists already.", path
);
1315 return log_unit_error_errno(u
, r
, "Failed to set unit's control group path to %s: %m", path
);
1318 /* First, create our own group */
1319 r
= cg_create_everywhere(u
->manager
->cgroup_supported
, target_mask
, u
->cgroup_path
);
1321 return log_unit_error_errno(u
, r
, "Failed to create cgroup %s: %m", u
->cgroup_path
);
1323 /* Start watching it */
1324 (void) unit_watch_cgroup(u
);
1326 /* Enable all controllers we need */
1327 r
= cg_enable_everywhere(u
->manager
->cgroup_supported
, enable_mask
, u
->cgroup_path
);
1329 log_unit_warning_errno(u
, r
, "Failed to enable controllers on cgroup %s, ignoring: %m", u
->cgroup_path
);
1331 /* Keep track that this is now realized */
1332 u
->cgroup_realized
= true;
1333 u
->cgroup_realized_mask
= target_mask
;
1334 u
->cgroup_enabled_mask
= enable_mask
;
1336 if (u
->type
!= UNIT_SLICE
&& !c
->delegate
) {
1338 /* Then, possibly move things over, but not if
1339 * subgroups may contain processes, which is the case
1340 * for slice and delegation units. */
1341 r
= cg_migrate_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, u
->cgroup_path
, migrate_callback
, u
);
1343 log_unit_warning_errno(u
, r
, "Failed to migrate cgroup from to %s, ignoring: %m", u
->cgroup_path
);
1349 int unit_attach_pids_to_cgroup(Unit
*u
) {
1353 r
= unit_realize_cgroup(u
);
1357 r
= cg_attach_many_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, u
->pids
, migrate_callback
, u
);
1364 static void cgroup_xattr_apply(Unit
*u
) {
1365 char ids
[SD_ID128_STRING_MAX
];
1370 if (!MANAGER_IS_SYSTEM(u
->manager
))
1373 if (sd_id128_is_null(u
->invocation_id
))
1376 r
= cg_set_xattr(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
,
1377 "trusted.invocation_id",
1378 sd_id128_to_string(u
->invocation_id
, ids
), 32,
1381 log_unit_warning_errno(u
, r
, "Failed to set invocation ID on control group %s, ignoring: %m", u
->cgroup_path
);
1384 static bool unit_has_mask_realized(Unit
*u
, CGroupMask target_mask
, CGroupMask enable_mask
) {
1387 return u
->cgroup_realized
&& u
->cgroup_realized_mask
== target_mask
&& u
->cgroup_enabled_mask
== enable_mask
;
1390 /* Check if necessary controllers and attributes for a unit are in place.
1392 * If so, do nothing.
1393 * If not, create paths, move processes over, and set attributes.
1395 * Returns 0 on success and < 0 on failure. */
1396 static int unit_realize_cgroup_now(Unit
*u
, ManagerState state
) {
1397 CGroupMask target_mask
, enable_mask
;
1402 if (u
->in_cgroup_queue
) {
1403 LIST_REMOVE(cgroup_queue
, u
->manager
->cgroup_queue
, u
);
1404 u
->in_cgroup_queue
= false;
1407 target_mask
= unit_get_target_mask(u
);
1408 enable_mask
= unit_get_enable_mask(u
);
1410 if (unit_has_mask_realized(u
, target_mask
, enable_mask
))
1413 /* First, realize parents */
1414 if (UNIT_ISSET(u
->slice
)) {
1415 r
= unit_realize_cgroup_now(UNIT_DEREF(u
->slice
), state
);
1420 /* And then do the real work */
1421 r
= unit_create_cgroup(u
, target_mask
, enable_mask
);
1425 /* Finally, apply the necessary attributes. */
1426 cgroup_context_apply(u
, target_mask
, state
);
1427 cgroup_xattr_apply(u
);
1432 static void unit_add_to_cgroup_queue(Unit
*u
) {
1434 if (u
->in_cgroup_queue
)
1437 LIST_PREPEND(cgroup_queue
, u
->manager
->cgroup_queue
, u
);
1438 u
->in_cgroup_queue
= true;
1441 unsigned manager_dispatch_cgroup_queue(Manager
*m
) {
1447 state
= manager_state(m
);
1449 while ((i
= m
->cgroup_queue
)) {
1450 assert(i
->in_cgroup_queue
);
1452 r
= unit_realize_cgroup_now(i
, state
);
1454 log_warning_errno(r
, "Failed to realize cgroups for queued unit %s, ignoring: %m", i
->id
);
1462 static void unit_queue_siblings(Unit
*u
) {
1465 /* This adds the siblings of the specified unit and the
1466 * siblings of all parent units to the cgroup queue. (But
1467 * neither the specified unit itself nor the parents.) */
1469 while ((slice
= UNIT_DEREF(u
->slice
))) {
1473 SET_FOREACH(m
, slice
->dependencies
[UNIT_BEFORE
], i
) {
1477 /* Skip units that have a dependency on the slice
1478 * but aren't actually in it. */
1479 if (UNIT_DEREF(m
->slice
) != slice
)
1482 /* No point in doing cgroup application for units
1483 * without active processes. */
1484 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m
)))
1487 /* If the unit doesn't need any new controllers
1488 * and has current ones realized, it doesn't need
1490 if (unit_has_mask_realized(m
, unit_get_target_mask(m
), unit_get_enable_mask(m
)))
1493 unit_add_to_cgroup_queue(m
);
1500 int unit_realize_cgroup(Unit
*u
) {
1503 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1506 /* So, here's the deal: when realizing the cgroups for this
1507 * unit, we need to first create all parents, but there's more
1508 * actually: for the weight-based controllers we also need to
1509 * make sure that all our siblings (i.e. units that are in the
1510 * same slice as we are) have cgroups, too. Otherwise, things
1511 * would become very uneven as each of their processes would
1512 * get as much resources as all our group together. This call
1513 * will synchronously create the parent cgroups, but will
1514 * defer work on the siblings to the next event loop
1517 /* Add all sibling slices to the cgroup queue. */
1518 unit_queue_siblings(u
);
1520 /* And realize this one now (and apply the values) */
1521 return unit_realize_cgroup_now(u
, manager_state(u
->manager
));
1524 void unit_release_cgroup(Unit
*u
) {
1527 /* Forgets all cgroup details for this cgroup */
1529 if (u
->cgroup_path
) {
1530 (void) hashmap_remove(u
->manager
->cgroup_unit
, u
->cgroup_path
);
1531 u
->cgroup_path
= mfree(u
->cgroup_path
);
1534 if (u
->cgroup_inotify_wd
>= 0) {
1535 if (inotify_rm_watch(u
->manager
->cgroup_inotify_fd
, u
->cgroup_inotify_wd
) < 0)
1536 log_unit_debug_errno(u
, errno
, "Failed to remove cgroup inotify watch %i for %s, ignoring", u
->cgroup_inotify_wd
, u
->id
);
1538 (void) hashmap_remove(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
));
1539 u
->cgroup_inotify_wd
= -1;
1543 void unit_prune_cgroup(Unit
*u
) {
1549 /* Removes the cgroup, if empty and possible, and stops watching it. */
1551 if (!u
->cgroup_path
)
1554 (void) unit_get_cpu_usage(u
, NULL
); /* Cache the last CPU usage value before we destroy the cgroup */
1556 is_root_slice
= unit_has_name(u
, SPECIAL_ROOT_SLICE
);
1558 r
= cg_trim_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, !is_root_slice
);
1560 log_unit_debug_errno(u
, r
, "Failed to destroy cgroup %s, ignoring: %m", u
->cgroup_path
);
1567 unit_release_cgroup(u
);
1569 u
->cgroup_realized
= false;
1570 u
->cgroup_realized_mask
= 0;
1571 u
->cgroup_enabled_mask
= 0;
1574 int unit_search_main_pid(Unit
*u
, pid_t
*ret
) {
1575 _cleanup_fclose_
FILE *f
= NULL
;
1576 pid_t pid
= 0, npid
, mypid
;
1582 if (!u
->cgroup_path
)
1585 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, &f
);
1590 while (cg_read_pid(f
, &npid
) > 0) {
1596 /* Ignore processes that aren't our kids */
1597 if (get_process_ppid(npid
, &ppid
) >= 0 && ppid
!= mypid
)
1601 /* Dang, there's more than one daemonized PID
1602 in this group, so we don't know what process
1603 is the main process. */
1614 static int unit_watch_pids_in_path(Unit
*u
, const char *path
) {
1615 _cleanup_closedir_
DIR *d
= NULL
;
1616 _cleanup_fclose_
FILE *f
= NULL
;
1622 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, path
, &f
);
1628 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
1629 r
= unit_watch_pid(u
, pid
);
1630 if (r
< 0 && ret
>= 0)
1634 if (r
< 0 && ret
>= 0)
1638 r
= cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER
, path
, &d
);
1645 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
1646 _cleanup_free_
char *p
= NULL
;
1648 p
= strjoin(path
, "/", fn
, NULL
);
1654 r
= unit_watch_pids_in_path(u
, p
);
1655 if (r
< 0 && ret
>= 0)
1659 if (r
< 0 && ret
>= 0)
1666 int unit_watch_all_pids(Unit
*u
) {
1669 /* Adds all PIDs from our cgroup to the set of PIDs we
1670 * watch. This is a fallback logic for cases where we do not
1671 * get reliable cgroup empty notifications: we try to use
1672 * SIGCHLD as replacement. */
1674 if (!u
->cgroup_path
)
1677 if (cg_unified(SYSTEMD_CGROUP_CONTROLLER
) > 0) /* On unified we can use proper notifications */
1680 return unit_watch_pids_in_path(u
, u
->cgroup_path
);
1683 int unit_notify_cgroup_empty(Unit
*u
) {
1688 if (!u
->cgroup_path
)
1691 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
);
1695 unit_add_to_gc_queue(u
);
1697 if (UNIT_VTABLE(u
)->notify_cgroup_empty
)
1698 UNIT_VTABLE(u
)->notify_cgroup_empty(u
);
1703 static int on_cgroup_inotify_event(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1704 Manager
*m
= userdata
;
1711 union inotify_event_buffer buffer
;
1712 struct inotify_event
*e
;
1715 l
= read(fd
, &buffer
, sizeof(buffer
));
1717 if (errno
== EINTR
|| errno
== EAGAIN
)
1720 return log_error_errno(errno
, "Failed to read control group inotify events: %m");
1723 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
1727 /* Queue overflow has no watch descriptor */
1730 if (e
->mask
& IN_IGNORED
)
1731 /* The watch was just removed */
1734 u
= hashmap_get(m
->cgroup_inotify_wd_unit
, INT_TO_PTR(e
->wd
));
1735 if (!u
) /* Not that inotify might deliver
1736 * events for a watch even after it
1737 * was removed, because it was queued
1738 * before the removal. Let's ignore
1739 * this here safely. */
1742 (void) unit_notify_cgroup_empty(u
);
1747 int manager_setup_cgroup(Manager
*m
) {
1748 _cleanup_free_
char *path
= NULL
;
1750 int r
, all_unified
, systemd_unified
;
1755 /* 1. Determine hierarchy */
1756 m
->cgroup_root
= mfree(m
->cgroup_root
);
1757 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 0, &m
->cgroup_root
);
1759 return log_error_errno(r
, "Cannot determine cgroup we are running in: %m");
1761 /* Chop off the init scope, if we are already located in it */
1762 e
= endswith(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
1764 /* LEGACY: Also chop off the system slice if we are in
1765 * it. This is to support live upgrades from older systemd
1766 * versions where PID 1 was moved there. Also see
1767 * cg_get_root_path(). */
1768 if (!e
&& MANAGER_IS_SYSTEM(m
)) {
1769 e
= endswith(m
->cgroup_root
, "/" SPECIAL_SYSTEM_SLICE
);
1771 e
= endswith(m
->cgroup_root
, "/system"); /* even more legacy */
1776 /* And make sure to store away the root value without trailing
1777 * slash, even for the root dir, so that we can easily prepend
1779 while ((e
= endswith(m
->cgroup_root
, "/")))
1783 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, NULL
, &path
);
1785 return log_error_errno(r
, "Cannot find cgroup mount point: %m");
1787 all_unified
= cg_all_unified();
1788 systemd_unified
= cg_unified(SYSTEMD_CGROUP_CONTROLLER
);
1790 if (all_unified
< 0 || systemd_unified
< 0)
1791 return log_error_errno(all_unified
< 0 ? all_unified
: systemd_unified
,
1792 "Couldn't determine if we are running in the unified hierarchy: %m");
1794 if (all_unified
> 0)
1795 log_debug("Unified cgroup hierarchy is located at %s.", path
);
1796 else if (systemd_unified
> 0)
1797 log_debug("Unified cgroup hierarchy is located at %s. Controllers are on legacy hierarchies.", path
);
1799 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER
". File system hierarchy is at %s.", path
);
1802 const char *scope_path
;
1804 /* 3. Install agent */
1805 if (systemd_unified
) {
1807 /* In the unified hierarchy we can get
1808 * cgroup empty notifications via inotify. */
1810 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
1811 safe_close(m
->cgroup_inotify_fd
);
1813 m
->cgroup_inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
1814 if (m
->cgroup_inotify_fd
< 0)
1815 return log_error_errno(errno
, "Failed to create control group inotify object: %m");
1817 r
= sd_event_add_io(m
->event
, &m
->cgroup_inotify_event_source
, m
->cgroup_inotify_fd
, EPOLLIN
, on_cgroup_inotify_event
, m
);
1819 return log_error_errno(r
, "Failed to watch control group inotify object: %m");
1821 /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
1822 * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
1823 r
= sd_event_source_set_priority(m
->cgroup_inotify_event_source
, SD_EVENT_PRIORITY_NORMAL
-5);
1825 return log_error_errno(r
, "Failed to set priority of inotify event source: %m");
1827 (void) sd_event_source_set_description(m
->cgroup_inotify_event_source
, "cgroup-inotify");
1829 } else if (MANAGER_IS_SYSTEM(m
)) {
1831 /* On the legacy hierarchy we only get
1832 * notifications via cgroup agents. (Which
1833 * isn't really reliable, since it does not
1834 * generate events when control groups with
1835 * children run empty. */
1837 r
= cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER
, SYSTEMD_CGROUP_AGENT_PATH
);
1839 log_warning_errno(r
, "Failed to install release agent, ignoring: %m");
1841 log_debug("Installed release agent.");
1843 log_debug("Release agent already installed.");
1846 /* 4. Make sure we are in the special "init.scope" unit in the root slice. */
1847 scope_path
= strjoina(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
1848 r
= cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
1850 return log_error_errno(r
, "Failed to create %s control group: %m", scope_path
);
1852 /* also, move all other userspace processes remaining
1853 * in the root cgroup into that scope. */
1854 r
= cg_migrate(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
1856 log_warning_errno(r
, "Couldn't move remaining userspace processes, ignoring: %m");
1858 /* 5. And pin it, so that it cannot be unmounted */
1859 safe_close(m
->pin_cgroupfs_fd
);
1860 m
->pin_cgroupfs_fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOCTTY
|O_NONBLOCK
);
1861 if (m
->pin_cgroupfs_fd
< 0)
1862 return log_error_errno(errno
, "Failed to open pin file: %m");
1864 /* 6. Always enable hierarchical support if it exists... */
1866 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
1869 /* 7. Figure out which controllers are supported */
1870 r
= cg_mask_supported(&m
->cgroup_supported
);
1872 return log_error_errno(r
, "Failed to determine supported controllers: %m");
1874 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++)
1875 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c
), yes_no(m
->cgroup_supported
& CGROUP_CONTROLLER_TO_MASK(c
)));
1880 void manager_shutdown_cgroup(Manager
*m
, bool delete) {
1883 /* We can't really delete the group, since we are in it. But
1885 if (delete && m
->cgroup_root
)
1886 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, false);
1888 m
->cgroup_inotify_wd_unit
= hashmap_free(m
->cgroup_inotify_wd_unit
);
1890 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
1891 m
->cgroup_inotify_fd
= safe_close(m
->cgroup_inotify_fd
);
1893 m
->pin_cgroupfs_fd
= safe_close(m
->pin_cgroupfs_fd
);
1895 m
->cgroup_root
= mfree(m
->cgroup_root
);
1898 Unit
* manager_get_unit_by_cgroup(Manager
*m
, const char *cgroup
) {
1905 u
= hashmap_get(m
->cgroup_unit
, cgroup
);
1909 p
= strdupa(cgroup
);
1913 e
= strrchr(p
, '/');
1915 return hashmap_get(m
->cgroup_unit
, SPECIAL_ROOT_SLICE
);
1919 u
= hashmap_get(m
->cgroup_unit
, p
);
1925 Unit
*manager_get_unit_by_pid_cgroup(Manager
*m
, pid_t pid
) {
1926 _cleanup_free_
char *cgroup
= NULL
;
1934 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &cgroup
);
1938 return manager_get_unit_by_cgroup(m
, cgroup
);
1941 Unit
*manager_get_unit_by_pid(Manager
*m
, pid_t pid
) {
1950 return hashmap_get(m
->units
, SPECIAL_INIT_SCOPE
);
1952 u
= hashmap_get(m
->watch_pids1
, PID_TO_PTR(pid
));
1956 u
= hashmap_get(m
->watch_pids2
, PID_TO_PTR(pid
));
1960 return manager_get_unit_by_pid_cgroup(m
, pid
);
1963 int manager_notify_cgroup_empty(Manager
*m
, const char *cgroup
) {
1969 log_debug("Got cgroup empty notification for: %s", cgroup
);
1971 u
= manager_get_unit_by_cgroup(m
, cgroup
);
1975 return unit_notify_cgroup_empty(u
);
1978 int unit_get_memory_current(Unit
*u
, uint64_t *ret
) {
1979 _cleanup_free_
char *v
= NULL
;
1985 if (!u
->cgroup_path
)
1988 if ((u
->cgroup_realized_mask
& CGROUP_MASK_MEMORY
) == 0)
1991 if (cg_all_unified() <= 0)
1992 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.usage_in_bytes", &v
);
1994 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.current", &v
);
2000 return safe_atou64(v
, ret
);
2003 int unit_get_tasks_current(Unit
*u
, uint64_t *ret
) {
2004 _cleanup_free_
char *v
= NULL
;
2010 if (!u
->cgroup_path
)
2013 if ((u
->cgroup_realized_mask
& CGROUP_MASK_PIDS
) == 0)
2016 r
= cg_get_attribute("pids", u
->cgroup_path
, "pids.current", &v
);
2022 return safe_atou64(v
, ret
);
2025 static int unit_get_cpu_usage_raw(Unit
*u
, nsec_t
*ret
) {
2026 _cleanup_free_
char *v
= NULL
;
2033 if (!u
->cgroup_path
)
2036 if (cg_all_unified() > 0) {
2037 const char *keys
[] = { "usage_usec", NULL
};
2038 _cleanup_free_
char *val
= NULL
;
2041 if ((u
->cgroup_realized_mask
& CGROUP_MASK_CPU
) == 0)
2044 r
= cg_get_keyed_attribute("cpu", u
->cgroup_path
, "cpu.stat", keys
, &val
);
2048 r
= safe_atou64(val
, &us
);
2052 ns
= us
* NSEC_PER_USEC
;
2054 if ((u
->cgroup_realized_mask
& CGROUP_MASK_CPUACCT
) == 0)
2057 r
= cg_get_attribute("cpuacct", u
->cgroup_path
, "cpuacct.usage", &v
);
2063 r
= safe_atou64(v
, &ns
);
2072 int unit_get_cpu_usage(Unit
*u
, nsec_t
*ret
) {
2078 /* Retrieve the current CPU usage counter. This will subtract the CPU counter taken when the unit was
2079 * started. If the cgroup has been removed already, returns the last cached value. To cache the value, simply
2080 * call this function with a NULL return value. */
2082 r
= unit_get_cpu_usage_raw(u
, &ns
);
2083 if (r
== -ENODATA
&& u
->cpu_usage_last
!= NSEC_INFINITY
) {
2084 /* If we can't get the CPU usage anymore (because the cgroup was already removed, for example), use our
2088 *ret
= u
->cpu_usage_last
;
2094 if (ns
> u
->cpu_usage_base
)
2095 ns
-= u
->cpu_usage_base
;
2099 u
->cpu_usage_last
= ns
;
2106 int unit_reset_cpu_usage(Unit
*u
) {
2112 u
->cpu_usage_last
= NSEC_INFINITY
;
2114 r
= unit_get_cpu_usage_raw(u
, &ns
);
2116 u
->cpu_usage_base
= 0;
2120 u
->cpu_usage_base
= ns
;
2124 bool unit_cgroup_delegate(Unit
*u
) {
2129 c
= unit_get_cgroup_context(u
);
2136 void unit_invalidate_cgroup(Unit
*u
, CGroupMask m
) {
2139 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
2145 /* always invalidate compat pairs together */
2146 if (m
& (CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
))
2147 m
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
2149 if ((u
->cgroup_realized_mask
& m
) == 0)
2152 u
->cgroup_realized_mask
&= ~m
;
2153 unit_add_to_cgroup_queue(u
);
2156 void manager_invalidate_startup_units(Manager
*m
) {
2162 SET_FOREACH(u
, m
->startup_units
, i
)
2163 unit_invalidate_cgroup(u
, CGROUP_MASK_CPU
|CGROUP_MASK_IO
|CGROUP_MASK_BLKIO
);
2166 static const char* const cgroup_device_policy_table
[_CGROUP_DEVICE_POLICY_MAX
] = {
2167 [CGROUP_AUTO
] = "auto",
2168 [CGROUP_CLOSED
] = "closed",
2169 [CGROUP_STRICT
] = "strict",
2172 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy
, CGroupDevicePolicy
);