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)
41 static bool cgroup_compat_warned
= false;
43 if (cgroup_compat_warned
)
46 log_warning("cgroup compatibility translation between legacy and unified hierarchy settings activated. See cgroup-compat debug messages for details.");
47 cgroup_compat_warned
= true;
50 #define log_cgroup_compat(unit, fmt, ...) do { \
51 cgroup_compat_warn(); \
52 log_unit_debug(unit, "cgroup-compat: " fmt, ##__VA_ARGS__); \
55 void cgroup_context_init(CGroupContext
*c
) {
58 /* Initialize everything to the kernel defaults, assuming the
59 * structure is preinitialized to 0 */
61 c
->cpu_shares
= CGROUP_CPU_SHARES_INVALID
;
62 c
->startup_cpu_shares
= CGROUP_CPU_SHARES_INVALID
;
63 c
->cpu_quota_per_sec_usec
= USEC_INFINITY
;
65 c
->memory_high
= CGROUP_LIMIT_MAX
;
66 c
->memory_max
= CGROUP_LIMIT_MAX
;
68 c
->memory_limit
= CGROUP_LIMIT_MAX
;
70 c
->io_weight
= CGROUP_WEIGHT_INVALID
;
71 c
->startup_io_weight
= CGROUP_WEIGHT_INVALID
;
73 c
->blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
;
74 c
->startup_blockio_weight
= CGROUP_BLKIO_WEIGHT_INVALID
;
76 c
->tasks_max
= (uint64_t) -1;
79 void cgroup_context_free_device_allow(CGroupContext
*c
, CGroupDeviceAllow
*a
) {
83 LIST_REMOVE(device_allow
, c
->device_allow
, a
);
88 void cgroup_context_free_io_device_weight(CGroupContext
*c
, CGroupIODeviceWeight
*w
) {
92 LIST_REMOVE(device_weights
, c
->io_device_weights
, w
);
97 void cgroup_context_free_io_device_limit(CGroupContext
*c
, CGroupIODeviceLimit
*l
) {
101 LIST_REMOVE(device_limits
, c
->io_device_limits
, l
);
106 void cgroup_context_free_blockio_device_weight(CGroupContext
*c
, CGroupBlockIODeviceWeight
*w
) {
110 LIST_REMOVE(device_weights
, c
->blockio_device_weights
, w
);
115 void cgroup_context_free_blockio_device_bandwidth(CGroupContext
*c
, CGroupBlockIODeviceBandwidth
*b
) {
119 LIST_REMOVE(device_bandwidths
, c
->blockio_device_bandwidths
, b
);
124 void cgroup_context_done(CGroupContext
*c
) {
127 while (c
->io_device_weights
)
128 cgroup_context_free_io_device_weight(c
, c
->io_device_weights
);
130 while (c
->io_device_limits
)
131 cgroup_context_free_io_device_limit(c
, c
->io_device_limits
);
133 while (c
->blockio_device_weights
)
134 cgroup_context_free_blockio_device_weight(c
, c
->blockio_device_weights
);
136 while (c
->blockio_device_bandwidths
)
137 cgroup_context_free_blockio_device_bandwidth(c
, c
->blockio_device_bandwidths
);
139 while (c
->device_allow
)
140 cgroup_context_free_device_allow(c
, c
->device_allow
);
143 void cgroup_context_dump(CGroupContext
*c
, FILE* f
, const char *prefix
) {
144 CGroupIODeviceLimit
*il
;
145 CGroupIODeviceWeight
*iw
;
146 CGroupBlockIODeviceBandwidth
*b
;
147 CGroupBlockIODeviceWeight
*w
;
148 CGroupDeviceAllow
*a
;
149 char u
[FORMAT_TIMESPAN_MAX
];
154 prefix
= strempty(prefix
);
157 "%sCPUAccounting=%s\n"
158 "%sIOAccounting=%s\n"
159 "%sBlockIOAccounting=%s\n"
160 "%sMemoryAccounting=%s\n"
161 "%sTasksAccounting=%s\n"
162 "%sCPUShares=%" PRIu64
"\n"
163 "%sStartupCPUShares=%" PRIu64
"\n"
164 "%sCPUQuotaPerSecSec=%s\n"
165 "%sIOWeight=%" PRIu64
"\n"
166 "%sStartupIOWeight=%" PRIu64
"\n"
167 "%sBlockIOWeight=%" PRIu64
"\n"
168 "%sStartupBlockIOWeight=%" PRIu64
"\n"
169 "%sMemoryLow=%" PRIu64
"\n"
170 "%sMemoryHigh=%" PRIu64
"\n"
171 "%sMemoryMax=%" PRIu64
"\n"
172 "%sMemoryLimit=%" PRIu64
"\n"
173 "%sTasksMax=%" PRIu64
"\n"
174 "%sDevicePolicy=%s\n"
176 prefix
, yes_no(c
->cpu_accounting
),
177 prefix
, yes_no(c
->io_accounting
),
178 prefix
, yes_no(c
->blockio_accounting
),
179 prefix
, yes_no(c
->memory_accounting
),
180 prefix
, yes_no(c
->tasks_accounting
),
181 prefix
, c
->cpu_shares
,
182 prefix
, c
->startup_cpu_shares
,
183 prefix
, format_timespan(u
, sizeof(u
), c
->cpu_quota_per_sec_usec
, 1),
184 prefix
, c
->io_weight
,
185 prefix
, c
->startup_io_weight
,
186 prefix
, c
->blockio_weight
,
187 prefix
, c
->startup_blockio_weight
,
188 prefix
, c
->memory_low
,
189 prefix
, c
->memory_high
,
190 prefix
, c
->memory_max
,
191 prefix
, c
->memory_limit
,
192 prefix
, c
->tasks_max
,
193 prefix
, cgroup_device_policy_to_string(c
->device_policy
),
194 prefix
, yes_no(c
->delegate
));
196 LIST_FOREACH(device_allow
, a
, c
->device_allow
)
198 "%sDeviceAllow=%s %s%s%s\n",
201 a
->r
? "r" : "", a
->w
? "w" : "", a
->m
? "m" : "");
203 LIST_FOREACH(device_weights
, iw
, c
->io_device_weights
)
205 "%sIODeviceWeight=%s %" PRIu64
,
210 LIST_FOREACH(device_limits
, il
, c
->io_device_limits
) {
211 char buf
[FORMAT_BYTES_MAX
];
212 CGroupIOLimitType type
;
214 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
215 if (il
->limits
[type
] != cgroup_io_limit_defaults
[type
])
219 cgroup_io_limit_type_to_string(type
),
221 format_bytes(buf
, sizeof(buf
), il
->limits
[type
]));
224 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
226 "%sBlockIODeviceWeight=%s %" PRIu64
,
231 LIST_FOREACH(device_bandwidths
, b
, c
->blockio_device_bandwidths
) {
232 char buf
[FORMAT_BYTES_MAX
];
234 if (b
->rbps
!= CGROUP_LIMIT_MAX
)
236 "%sBlockIOReadBandwidth=%s %s\n",
239 format_bytes(buf
, sizeof(buf
), b
->rbps
));
240 if (b
->wbps
!= CGROUP_LIMIT_MAX
)
242 "%sBlockIOWriteBandwidth=%s %s\n",
245 format_bytes(buf
, sizeof(buf
), b
->wbps
));
249 static int lookup_block_device(const char *p
, dev_t
*dev
) {
258 return log_warning_errno(errno
, "Couldn't stat device %s: %m", p
);
260 if (S_ISBLK(st
.st_mode
))
262 else if (major(st
.st_dev
) != 0) {
263 /* If this is not a device node then find the block
264 * device this file is stored on */
267 /* If this is a partition, try to get the originating
269 block_get_whole_disk(*dev
, dev
);
271 log_warning("%s is not a block device and file system block device cannot be determined or is not local.", p
);
278 static int whitelist_device(const char *path
, const char *node
, const char *acc
) {
279 char buf
[2+DECIMAL_STR_MAX(dev_t
)*2+2+4];
286 if (stat(node
, &st
) < 0) {
287 log_warning("Couldn't stat device %s", node
);
291 if (!S_ISCHR(st
.st_mode
) && !S_ISBLK(st
.st_mode
)) {
292 log_warning("%s is not a device.", node
);
298 S_ISCHR(st
.st_mode
) ? 'c' : 'b',
299 major(st
.st_rdev
), minor(st
.st_rdev
),
302 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
304 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
305 "Failed to set devices.allow on %s: %m", path
);
310 static int whitelist_major(const char *path
, const char *name
, char type
, const char *acc
) {
311 _cleanup_fclose_
FILE *f
= NULL
;
318 assert(type
== 'b' || type
== 'c');
320 f
= fopen("/proc/devices", "re");
322 return log_warning_errno(errno
, "Cannot open /proc/devices to resolve %s (%c): %m", name
, type
);
324 FOREACH_LINE(line
, f
, goto fail
) {
325 char buf
[2+DECIMAL_STR_MAX(unsigned)+3+4], *p
, *w
;
330 if (type
== 'c' && streq(line
, "Character devices:")) {
335 if (type
== 'b' && streq(line
, "Block devices:")) {
350 w
= strpbrk(p
, WHITESPACE
);
355 r
= safe_atou(p
, &maj
);
362 w
+= strspn(w
, WHITESPACE
);
364 if (fnmatch(name
, w
, 0) != 0)
373 r
= cg_set_attribute("devices", path
, "devices.allow", buf
);
375 log_full_errno(IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
376 "Failed to set devices.allow on %s: %m", path
);
382 log_warning_errno(errno
, "Failed to read /proc/devices: %m");
386 static bool cgroup_context_has_io_config(CGroupContext
*c
) {
387 return c
->io_accounting
||
388 c
->io_weight
!= CGROUP_WEIGHT_INVALID
||
389 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
||
390 c
->io_device_weights
||
394 static bool cgroup_context_has_blockio_config(CGroupContext
*c
) {
395 return c
->blockio_accounting
||
396 c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
397 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
||
398 c
->blockio_device_weights
||
399 c
->blockio_device_bandwidths
;
402 static uint64_t cgroup_context_io_weight(CGroupContext
*c
, ManagerState state
) {
403 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
404 c
->startup_io_weight
!= CGROUP_WEIGHT_INVALID
)
405 return c
->startup_io_weight
;
406 else if (c
->io_weight
!= CGROUP_WEIGHT_INVALID
)
409 return CGROUP_WEIGHT_DEFAULT
;
412 static uint64_t cgroup_context_blkio_weight(CGroupContext
*c
, ManagerState state
) {
413 if (IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) &&
414 c
->startup_blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
415 return c
->startup_blockio_weight
;
416 else if (c
->blockio_weight
!= CGROUP_BLKIO_WEIGHT_INVALID
)
417 return c
->blockio_weight
;
419 return CGROUP_BLKIO_WEIGHT_DEFAULT
;
422 static uint64_t cgroup_weight_blkio_to_io(uint64_t blkio_weight
) {
423 return CLAMP(blkio_weight
* CGROUP_WEIGHT_DEFAULT
/ CGROUP_BLKIO_WEIGHT_DEFAULT
,
424 CGROUP_WEIGHT_MIN
, CGROUP_WEIGHT_MAX
);
427 static uint64_t cgroup_weight_io_to_blkio(uint64_t io_weight
) {
428 return CLAMP(io_weight
* CGROUP_BLKIO_WEIGHT_DEFAULT
/ CGROUP_WEIGHT_DEFAULT
,
429 CGROUP_BLKIO_WEIGHT_MIN
, CGROUP_BLKIO_WEIGHT_MAX
);
432 static void cgroup_apply_io_device_weight(Unit
*u
, const char *dev_path
, uint64_t io_weight
) {
433 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
437 r
= lookup_block_device(dev_path
, &dev
);
441 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), io_weight
);
442 r
= cg_set_attribute("io", u
->cgroup_path
, "io.weight", buf
);
444 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
445 "Failed to set io.weight: %m");
448 static void cgroup_apply_blkio_device_weight(Unit
*u
, const char *dev_path
, uint64_t blkio_weight
) {
449 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
453 r
= lookup_block_device(dev_path
, &dev
);
457 xsprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), blkio_weight
);
458 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.weight_device", buf
);
460 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
461 "Failed to set blkio.weight_device: %m");
464 static unsigned cgroup_apply_io_device_limit(Unit
*u
, const char *dev_path
, uint64_t *limits
) {
465 char limit_bufs
[_CGROUP_IO_LIMIT_TYPE_MAX
][DECIMAL_STR_MAX(uint64_t)];
466 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+(6+DECIMAL_STR_MAX(uint64_t)+1)*4];
467 CGroupIOLimitType type
;
472 r
= lookup_block_device(dev_path
, &dev
);
476 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++) {
477 if (limits
[type
] != cgroup_io_limit_defaults
[type
]) {
478 xsprintf(limit_bufs
[type
], "%" PRIu64
, limits
[type
]);
481 xsprintf(limit_bufs
[type
], "%s", limits
[type
] == CGROUP_LIMIT_MAX
? "max" : "0");
485 xsprintf(buf
, "%u:%u rbps=%s wbps=%s riops=%s wiops=%s\n", major(dev
), minor(dev
),
486 limit_bufs
[CGROUP_IO_RBPS_MAX
], limit_bufs
[CGROUP_IO_WBPS_MAX
],
487 limit_bufs
[CGROUP_IO_RIOPS_MAX
], limit_bufs
[CGROUP_IO_WIOPS_MAX
]);
488 r
= cg_set_attribute("io", u
->cgroup_path
, "io.max", buf
);
490 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
491 "Failed to set io.max: %m");
495 static unsigned cgroup_apply_blkio_device_limit(Unit
*u
, const char *dev_path
, uint64_t rbps
, uint64_t wbps
) {
496 char buf
[DECIMAL_STR_MAX(dev_t
)*2+2+DECIMAL_STR_MAX(uint64_t)+1];
501 r
= lookup_block_device(dev_path
, &dev
);
505 if (rbps
!= CGROUP_LIMIT_MAX
)
507 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), rbps
);
508 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.throttle.read_bps_device", buf
);
510 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
511 "Failed to set blkio.throttle.read_bps_device: %m");
513 if (wbps
!= CGROUP_LIMIT_MAX
)
515 sprintf(buf
, "%u:%u %" PRIu64
"\n", major(dev
), minor(dev
), wbps
);
516 r
= cg_set_attribute("blkio", u
->cgroup_path
, "blkio.throttle.write_bps_device", buf
);
518 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
519 "Failed to set blkio.throttle.write_bps_device: %m");
524 static bool cgroup_context_has_unified_memory_config(CGroupContext
*c
) {
525 return c
->memory_low
> 0 || c
->memory_high
!= CGROUP_LIMIT_MAX
|| c
->memory_max
!= CGROUP_LIMIT_MAX
;
528 static void cgroup_apply_unified_memory_limit(Unit
*u
, const char *file
, uint64_t v
) {
529 char buf
[DECIMAL_STR_MAX(uint64_t) + 1] = "max";
532 if (v
!= CGROUP_LIMIT_MAX
)
533 xsprintf(buf
, "%" PRIu64
"\n", v
);
535 r
= cg_set_attribute("memory", u
->cgroup_path
, file
, buf
);
537 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
538 "Failed to set %s: %m", file
);
541 static void cgroup_context_apply(Unit
*u
, CGroupMask mask
, ManagerState state
) {
549 c
= unit_get_cgroup_context(u
);
550 path
= u
->cgroup_path
;
558 /* Some cgroup attributes are not supported on the root cgroup,
559 * hence silently ignore */
560 is_root
= isempty(path
) || path_equal(path
, "/");
562 /* Make sure we don't try to display messages with an empty path. */
565 /* We generally ignore errors caused by read-only mounted
566 * cgroup trees (assuming we are running in a container then),
567 * and missing cgroups, i.e. EROFS and ENOENT. */
569 if ((mask
& CGROUP_MASK_CPU
) && !is_root
) {
570 char buf
[MAX(DECIMAL_STR_MAX(uint64_t), DECIMAL_STR_MAX(usec_t
)) + 1];
572 sprintf(buf
, "%" PRIu64
"\n",
573 IN_SET(state
, MANAGER_STARTING
, MANAGER_INITIALIZING
) && c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
? c
->startup_cpu_shares
:
574 c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
? c
->cpu_shares
: CGROUP_CPU_SHARES_DEFAULT
);
575 r
= cg_set_attribute("cpu", path
, "cpu.shares", buf
);
577 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
578 "Failed to set cpu.shares: %m");
580 sprintf(buf
, USEC_FMT
"\n", CGROUP_CPU_QUOTA_PERIOD_USEC
);
581 r
= cg_set_attribute("cpu", path
, "cpu.cfs_period_us", buf
);
583 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
584 "Failed to set cpu.cfs_period_us: %m");
586 if (c
->cpu_quota_per_sec_usec
!= USEC_INFINITY
) {
587 sprintf(buf
, USEC_FMT
"\n", c
->cpu_quota_per_sec_usec
* CGROUP_CPU_QUOTA_PERIOD_USEC
/ USEC_PER_SEC
);
588 r
= cg_set_attribute("cpu", path
, "cpu.cfs_quota_us", buf
);
590 r
= cg_set_attribute("cpu", path
, "cpu.cfs_quota_us", "-1");
592 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
593 "Failed to set cpu.cfs_quota_us: %m");
596 if (mask
& CGROUP_MASK_IO
) {
597 bool has_io
= cgroup_context_has_io_config(c
);
598 bool has_blockio
= cgroup_context_has_blockio_config(c
);
601 char buf
[8+DECIMAL_STR_MAX(uint64_t)+1];
605 weight
= cgroup_context_io_weight(c
, state
);
606 else if (has_blockio
) {
607 uint64_t blkio_weight
= cgroup_context_blkio_weight(c
, state
);
609 weight
= cgroup_weight_blkio_to_io(blkio_weight
);
611 log_cgroup_compat(u
, "Applying [Startup]BlockIOWeight %" PRIu64
" as [Startup]IOWeight %" PRIu64
,
612 blkio_weight
, weight
);
614 weight
= CGROUP_WEIGHT_DEFAULT
;
616 xsprintf(buf
, "default %" PRIu64
"\n", weight
);
617 r
= cg_set_attribute("io", path
, "io.weight", buf
);
619 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
620 "Failed to set io.weight: %m");
623 CGroupIODeviceWeight
*w
;
625 /* FIXME: no way to reset this list */
626 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
)
627 cgroup_apply_io_device_weight(u
, w
->path
, w
->weight
);
628 } else if (has_blockio
) {
629 CGroupBlockIODeviceWeight
*w
;
631 /* FIXME: no way to reset this list */
632 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
) {
633 weight
= cgroup_weight_blkio_to_io(w
->weight
);
635 log_cgroup_compat(u
, "Applying BlockIODeviceWeight %" PRIu64
" as IODeviceWeight %" PRIu64
" for %s",
636 w
->weight
, weight
, w
->path
);
638 cgroup_apply_io_device_weight(u
, w
->path
, weight
);
643 /* Apply limits and free ones without config. */
645 CGroupIODeviceLimit
*l
, *next
;
647 LIST_FOREACH_SAFE(device_limits
, l
, next
, c
->io_device_limits
) {
648 if (!cgroup_apply_io_device_limit(u
, l
->path
, l
->limits
))
649 cgroup_context_free_io_device_limit(c
, l
);
651 } else if (has_blockio
) {
652 CGroupBlockIODeviceBandwidth
*b
, *next
;
654 LIST_FOREACH_SAFE(device_bandwidths
, b
, next
, c
->blockio_device_bandwidths
) {
655 uint64_t limits
[_CGROUP_IO_LIMIT_TYPE_MAX
];
656 CGroupIOLimitType type
;
658 for (type
= 0; type
< _CGROUP_IO_LIMIT_TYPE_MAX
; type
++)
659 limits
[type
] = cgroup_io_limit_defaults
[type
];
661 limits
[CGROUP_IO_RBPS_MAX
] = b
->rbps
;
662 limits
[CGROUP_IO_WBPS_MAX
] = b
->wbps
;
664 log_cgroup_compat(u
, "Applying BlockIO{Read|Write}Bandwidth %" PRIu64
" %" PRIu64
" as IO{Read|Write}BandwidthMax for %s",
665 b
->rbps
, b
->wbps
, b
->path
);
667 if (!cgroup_apply_io_device_limit(u
, b
->path
, limits
))
668 cgroup_context_free_blockio_device_bandwidth(c
, b
);
673 if (mask
& CGROUP_MASK_BLKIO
) {
674 bool has_io
= cgroup_context_has_io_config(c
);
675 bool has_blockio
= cgroup_context_has_blockio_config(c
);
678 char buf
[DECIMAL_STR_MAX(uint64_t)+1];
682 weight
= cgroup_context_blkio_weight(c
, state
);
684 uint64_t io_weight
= cgroup_context_io_weight(c
, state
);
686 weight
= cgroup_weight_io_to_blkio(cgroup_context_io_weight(c
, state
));
688 log_cgroup_compat(u
, "Applying [Startup]IOWeight %" PRIu64
" as [Startup]BlockIOWeight %" PRIu64
,
691 weight
= CGROUP_BLKIO_WEIGHT_DEFAULT
;
693 xsprintf(buf
, "%" PRIu64
"\n", weight
);
694 r
= cg_set_attribute("blkio", path
, "blkio.weight", buf
);
696 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
697 "Failed to set blkio.weight: %m");
700 CGroupBlockIODeviceWeight
*w
;
702 /* FIXME: no way to reset this list */
703 LIST_FOREACH(device_weights
, w
, c
->blockio_device_weights
)
704 cgroup_apply_blkio_device_weight(u
, w
->path
, w
->weight
);
706 CGroupIODeviceWeight
*w
;
708 /* FIXME: no way to reset this list */
709 LIST_FOREACH(device_weights
, w
, c
->io_device_weights
) {
710 weight
= cgroup_weight_io_to_blkio(w
->weight
);
712 log_cgroup_compat(u
, "Applying IODeviceWeight %" PRIu64
" as BlockIODeviceWeight %" PRIu64
" for %s",
713 w
->weight
, weight
, w
->path
);
715 cgroup_apply_blkio_device_weight(u
, w
->path
, weight
);
720 /* Apply limits and free ones without config. */
722 CGroupBlockIODeviceBandwidth
*b
, *next
;
724 LIST_FOREACH_SAFE(device_bandwidths
, b
, next
, c
->blockio_device_bandwidths
) {
725 if (!cgroup_apply_blkio_device_limit(u
, b
->path
, b
->rbps
, b
->wbps
))
726 cgroup_context_free_blockio_device_bandwidth(c
, b
);
729 CGroupIODeviceLimit
*l
, *next
;
731 LIST_FOREACH_SAFE(device_limits
, l
, next
, c
->io_device_limits
) {
732 log_cgroup_compat(u
, "Applying IO{Read|Write}Bandwidth %" PRIu64
" %" PRIu64
" as BlockIO{Read|Write}BandwidthMax for %s",
733 l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
], l
->path
);
735 if (!cgroup_apply_blkio_device_limit(u
, l
->path
, l
->limits
[CGROUP_IO_RBPS_MAX
], l
->limits
[CGROUP_IO_WBPS_MAX
]))
736 cgroup_context_free_io_device_limit(c
, l
);
741 if ((mask
& CGROUP_MASK_MEMORY
) && !is_root
) {
742 if (cg_unified() > 0) {
743 uint64_t max
= c
->memory_max
;
745 if (cgroup_context_has_unified_memory_config(c
))
748 max
= c
->memory_limit
;
750 if (max
!= CGROUP_LIMIT_MAX
)
751 log_cgroup_compat(u
, "Applying MemoryLimit %" PRIu64
" as MemoryMax", max
);
754 cgroup_apply_unified_memory_limit(u
, "memory.low", c
->memory_low
);
755 cgroup_apply_unified_memory_limit(u
, "memory.high", c
->memory_high
);
756 cgroup_apply_unified_memory_limit(u
, "memory.max", max
);
758 char buf
[DECIMAL_STR_MAX(uint64_t) + 1];
760 if (c
->memory_limit
!= CGROUP_LIMIT_MAX
)
761 xsprintf(buf
, "%" PRIu64
"\n", c
->memory_limit
);
763 xsprintf(buf
, "%" PRIu64
"\n", c
->memory_max
);
765 if (c
->memory_max
!= CGROUP_LIMIT_MAX
)
766 log_cgroup_compat(u
, "Applying MemoryMax %" PRIu64
" as MemoryLimit", c
->memory_max
);
769 r
= cg_set_attribute("memory", path
, "memory.limit_in_bytes", buf
);
771 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
772 "Failed to set memory.limit_in_bytes: %m");
776 if ((mask
& CGROUP_MASK_DEVICES
) && !is_root
) {
777 CGroupDeviceAllow
*a
;
779 /* Changing the devices list of a populated cgroup
780 * might result in EINVAL, hence ignore EINVAL
783 if (c
->device_allow
|| c
->device_policy
!= CGROUP_AUTO
)
784 r
= cg_set_attribute("devices", path
, "devices.deny", "a");
786 r
= cg_set_attribute("devices", path
, "devices.allow", "a");
788 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EINVAL
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
789 "Failed to reset devices.list: %m");
791 if (c
->device_policy
== CGROUP_CLOSED
||
792 (c
->device_policy
== CGROUP_AUTO
&& c
->device_allow
)) {
793 static const char auto_devices
[] =
794 "/dev/null\0" "rwm\0"
795 "/dev/zero\0" "rwm\0"
796 "/dev/full\0" "rwm\0"
797 "/dev/random\0" "rwm\0"
798 "/dev/urandom\0" "rwm\0"
800 "/dev/pts/ptmx\0" "rw\0"; /* /dev/pts/ptmx may not be duplicated, but accessed */
804 NULSTR_FOREACH_PAIR(x
, y
, auto_devices
)
805 whitelist_device(path
, x
, y
);
807 whitelist_major(path
, "pts", 'c', "rw");
808 whitelist_major(path
, "kdbus", 'c', "rw");
809 whitelist_major(path
, "kdbus/*", 'c', "rw");
812 LIST_FOREACH(device_allow
, a
, c
->device_allow
) {
828 if (startswith(a
->path
, "/dev/"))
829 whitelist_device(path
, a
->path
, acc
);
830 else if (startswith(a
->path
, "block-"))
831 whitelist_major(path
, a
->path
+ 6, 'b', acc
);
832 else if (startswith(a
->path
, "char-"))
833 whitelist_major(path
, a
->path
+ 5, 'c', acc
);
835 log_unit_debug(u
, "Ignoring device %s while writing cgroup attribute.", a
->path
);
839 if ((mask
& CGROUP_MASK_PIDS
) && !is_root
) {
841 if (c
->tasks_max
!= (uint64_t) -1) {
842 char buf
[DECIMAL_STR_MAX(uint64_t) + 2];
844 sprintf(buf
, "%" PRIu64
"\n", c
->tasks_max
);
845 r
= cg_set_attribute("pids", path
, "pids.max", buf
);
847 r
= cg_set_attribute("pids", path
, "pids.max", "max");
850 log_unit_full(u
, IN_SET(r
, -ENOENT
, -EROFS
, -EACCES
) ? LOG_DEBUG
: LOG_WARNING
, r
,
851 "Failed to set pids.max: %m");
855 CGroupMask
cgroup_context_get_mask(CGroupContext
*c
) {
858 /* Figure out which controllers we need */
860 if (c
->cpu_accounting
||
861 c
->cpu_shares
!= CGROUP_CPU_SHARES_INVALID
||
862 c
->startup_cpu_shares
!= CGROUP_CPU_SHARES_INVALID
||
863 c
->cpu_quota_per_sec_usec
!= USEC_INFINITY
)
864 mask
|= CGROUP_MASK_CPUACCT
| CGROUP_MASK_CPU
;
866 if (cgroup_context_has_io_config(c
) || cgroup_context_has_blockio_config(c
))
867 mask
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
869 if (c
->memory_accounting
||
870 c
->memory_limit
!= CGROUP_LIMIT_MAX
||
871 cgroup_context_has_unified_memory_config(c
))
872 mask
|= CGROUP_MASK_MEMORY
;
874 if (c
->device_allow
||
875 c
->device_policy
!= CGROUP_AUTO
)
876 mask
|= CGROUP_MASK_DEVICES
;
878 if (c
->tasks_accounting
||
879 c
->tasks_max
!= (uint64_t) -1)
880 mask
|= CGROUP_MASK_PIDS
;
885 CGroupMask
unit_get_own_mask(Unit
*u
) {
888 /* Returns the mask of controllers the unit needs for itself */
890 c
= unit_get_cgroup_context(u
);
894 /* If delegation is turned on, then turn on all cgroups,
895 * unless we are on the legacy hierarchy and the process we
896 * fork into it is known to drop privileges, and hence
897 * shouldn't get access to the controllers.
899 * Note that on the unified hierarchy it is safe to delegate
900 * controllers to unprivileged services. */
905 e
= unit_get_exec_context(u
);
907 exec_context_maintains_privileges(e
) ||
909 return _CGROUP_MASK_ALL
;
912 return cgroup_context_get_mask(c
);
915 CGroupMask
unit_get_members_mask(Unit
*u
) {
918 /* Returns the mask of controllers all of the unit's children
921 if (u
->cgroup_members_mask_valid
)
922 return u
->cgroup_members_mask
;
924 u
->cgroup_members_mask
= 0;
926 if (u
->type
== UNIT_SLICE
) {
930 SET_FOREACH(member
, u
->dependencies
[UNIT_BEFORE
], i
) {
935 if (UNIT_DEREF(member
->slice
) != u
)
938 u
->cgroup_members_mask
|=
939 unit_get_own_mask(member
) |
940 unit_get_members_mask(member
);
944 u
->cgroup_members_mask_valid
= true;
945 return u
->cgroup_members_mask
;
948 CGroupMask
unit_get_siblings_mask(Unit
*u
) {
951 /* Returns the mask of controllers all of the unit's siblings
952 * require, i.e. the members mask of the unit's parent slice
953 * if there is one. */
955 if (UNIT_ISSET(u
->slice
))
956 return unit_get_members_mask(UNIT_DEREF(u
->slice
));
958 return unit_get_own_mask(u
) | unit_get_members_mask(u
);
961 CGroupMask
unit_get_subtree_mask(Unit
*u
) {
963 /* Returns the mask of this subtree, meaning of the group
964 * itself and its children. */
966 return unit_get_own_mask(u
) | unit_get_members_mask(u
);
969 CGroupMask
unit_get_target_mask(Unit
*u
) {
972 /* This returns the cgroup mask of all controllers to enable
973 * for a specific cgroup, i.e. everything it needs itself,
974 * plus all that its children need, plus all that its siblings
975 * need. This is primarily useful on the legacy cgroup
976 * hierarchy, where we need to duplicate each cgroup in each
977 * hierarchy that shall be enabled for it. */
979 mask
= unit_get_own_mask(u
) | unit_get_members_mask(u
) | unit_get_siblings_mask(u
);
980 mask
&= u
->manager
->cgroup_supported
;
985 CGroupMask
unit_get_enable_mask(Unit
*u
) {
988 /* This returns the cgroup mask of all controllers to enable
989 * for the children of a specific cgroup. This is primarily
990 * useful for the unified cgroup hierarchy, where each cgroup
991 * controls which controllers are enabled for its children. */
993 mask
= unit_get_members_mask(u
);
994 mask
&= u
->manager
->cgroup_supported
;
999 /* Recurse from a unit up through its containing slices, propagating
1000 * mask bits upward. A unit is also member of itself. */
1001 void unit_update_cgroup_members_masks(Unit
*u
) {
1007 /* Calculate subtree mask */
1008 m
= unit_get_subtree_mask(u
);
1010 /* See if anything changed from the previous invocation. If
1011 * not, we're done. */
1012 if (u
->cgroup_subtree_mask_valid
&& m
== u
->cgroup_subtree_mask
)
1016 u
->cgroup_subtree_mask_valid
&&
1017 ((m
& ~u
->cgroup_subtree_mask
) != 0) &&
1018 ((~m
& u
->cgroup_subtree_mask
) == 0);
1020 u
->cgroup_subtree_mask
= m
;
1021 u
->cgroup_subtree_mask_valid
= true;
1023 if (UNIT_ISSET(u
->slice
)) {
1024 Unit
*s
= UNIT_DEREF(u
->slice
);
1027 /* There's more set now than before. We
1028 * propagate the new mask to the parent's mask
1029 * (not caring if it actually was valid or
1032 s
->cgroup_members_mask
|= m
;
1035 /* There's less set now than before (or we
1036 * don't know), we need to recalculate
1037 * everything, so let's invalidate the
1038 * parent's members mask */
1040 s
->cgroup_members_mask_valid
= false;
1042 /* And now make sure that this change also hits our
1044 unit_update_cgroup_members_masks(s
);
1048 static const char *migrate_callback(CGroupMask mask
, void *userdata
) {
1055 if (u
->cgroup_path
&&
1056 u
->cgroup_realized
&&
1057 (u
->cgroup_realized_mask
& mask
) == mask
)
1058 return u
->cgroup_path
;
1060 u
= UNIT_DEREF(u
->slice
);
1066 char *unit_default_cgroup_path(Unit
*u
) {
1067 _cleanup_free_
char *escaped
= NULL
, *slice
= NULL
;
1072 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1073 return strdup(u
->manager
->cgroup_root
);
1075 if (UNIT_ISSET(u
->slice
) && !unit_has_name(UNIT_DEREF(u
->slice
), SPECIAL_ROOT_SLICE
)) {
1076 r
= cg_slice_to_path(UNIT_DEREF(u
->slice
)->id
, &slice
);
1081 escaped
= cg_escape(u
->id
);
1086 return strjoin(u
->manager
->cgroup_root
, "/", slice
, "/", escaped
, NULL
);
1088 return strjoin(u
->manager
->cgroup_root
, "/", escaped
, NULL
);
1091 int unit_set_cgroup_path(Unit
*u
, const char *path
) {
1092 _cleanup_free_
char *p
= NULL
;
1104 if (streq_ptr(u
->cgroup_path
, p
))
1108 r
= hashmap_put(u
->manager
->cgroup_unit
, p
, u
);
1113 unit_release_cgroup(u
);
1121 int unit_watch_cgroup(Unit
*u
) {
1122 _cleanup_free_
char *events
= NULL
;
1127 if (!u
->cgroup_path
)
1130 if (u
->cgroup_inotify_wd
>= 0)
1133 /* Only applies to the unified hierarchy */
1136 return log_unit_error_errno(u
, r
, "Failed detect wether the unified hierarchy is used: %m");
1140 /* Don't watch the root slice, it's pointless. */
1141 if (unit_has_name(u
, SPECIAL_ROOT_SLICE
))
1144 r
= hashmap_ensure_allocated(&u
->manager
->cgroup_inotify_wd_unit
, &trivial_hash_ops
);
1148 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, "cgroup.events", &events
);
1152 u
->cgroup_inotify_wd
= inotify_add_watch(u
->manager
->cgroup_inotify_fd
, events
, IN_MODIFY
);
1153 if (u
->cgroup_inotify_wd
< 0) {
1155 if (errno
== ENOENT
) /* If the directory is already
1156 * gone we don't need to track
1157 * it, so this is not an error */
1160 return log_unit_error_errno(u
, errno
, "Failed to add inotify watch descriptor for control group %s: %m", u
->cgroup_path
);
1163 r
= hashmap_put(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
), u
);
1165 return log_unit_error_errno(u
, r
, "Failed to add inotify watch descriptor to hash map: %m");
1170 static int unit_create_cgroup(
1172 CGroupMask target_mask
,
1173 CGroupMask enable_mask
) {
1180 c
= unit_get_cgroup_context(u
);
1184 if (!u
->cgroup_path
) {
1185 _cleanup_free_
char *path
= NULL
;
1187 path
= unit_default_cgroup_path(u
);
1191 r
= unit_set_cgroup_path(u
, path
);
1193 return log_unit_error_errno(u
, r
, "Control group %s exists already.", path
);
1195 return log_unit_error_errno(u
, r
, "Failed to set unit's control group path to %s: %m", path
);
1198 /* First, create our own group */
1199 r
= cg_create_everywhere(u
->manager
->cgroup_supported
, target_mask
, u
->cgroup_path
);
1201 return log_unit_error_errno(u
, r
, "Failed to create cgroup %s: %m", u
->cgroup_path
);
1203 /* Start watching it */
1204 (void) unit_watch_cgroup(u
);
1206 /* Enable all controllers we need */
1207 r
= cg_enable_everywhere(u
->manager
->cgroup_supported
, enable_mask
, u
->cgroup_path
);
1209 log_unit_warning_errno(u
, r
, "Failed to enable controllers on cgroup %s, ignoring: %m", u
->cgroup_path
);
1211 /* Keep track that this is now realized */
1212 u
->cgroup_realized
= true;
1213 u
->cgroup_realized_mask
= target_mask
;
1214 u
->cgroup_enabled_mask
= enable_mask
;
1216 if (u
->type
!= UNIT_SLICE
&& !c
->delegate
) {
1218 /* Then, possibly move things over, but not if
1219 * subgroups may contain processes, which is the case
1220 * for slice and delegation units. */
1221 r
= cg_migrate_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, u
->cgroup_path
, migrate_callback
, u
);
1223 log_unit_warning_errno(u
, r
, "Failed to migrate cgroup from to %s, ignoring: %m", u
->cgroup_path
);
1229 int unit_attach_pids_to_cgroup(Unit
*u
) {
1233 r
= unit_realize_cgroup(u
);
1237 r
= cg_attach_many_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, u
->pids
, migrate_callback
, u
);
1244 static bool unit_has_mask_realized(Unit
*u
, CGroupMask target_mask
, CGroupMask enable_mask
) {
1247 return u
->cgroup_realized
&& u
->cgroup_realized_mask
== target_mask
&& u
->cgroup_enabled_mask
== enable_mask
;
1250 /* Check if necessary controllers and attributes for a unit are in place.
1252 * If so, do nothing.
1253 * If not, create paths, move processes over, and set attributes.
1255 * Returns 0 on success and < 0 on failure. */
1256 static int unit_realize_cgroup_now(Unit
*u
, ManagerState state
) {
1257 CGroupMask target_mask
, enable_mask
;
1262 if (u
->in_cgroup_queue
) {
1263 LIST_REMOVE(cgroup_queue
, u
->manager
->cgroup_queue
, u
);
1264 u
->in_cgroup_queue
= false;
1267 target_mask
= unit_get_target_mask(u
);
1268 enable_mask
= unit_get_enable_mask(u
);
1270 if (unit_has_mask_realized(u
, target_mask
, enable_mask
))
1273 /* First, realize parents */
1274 if (UNIT_ISSET(u
->slice
)) {
1275 r
= unit_realize_cgroup_now(UNIT_DEREF(u
->slice
), state
);
1280 /* And then do the real work */
1281 r
= unit_create_cgroup(u
, target_mask
, enable_mask
);
1285 /* Finally, apply the necessary attributes. */
1286 cgroup_context_apply(u
, target_mask
, state
);
1291 static void unit_add_to_cgroup_queue(Unit
*u
) {
1293 if (u
->in_cgroup_queue
)
1296 LIST_PREPEND(cgroup_queue
, u
->manager
->cgroup_queue
, u
);
1297 u
->in_cgroup_queue
= true;
1300 unsigned manager_dispatch_cgroup_queue(Manager
*m
) {
1306 state
= manager_state(m
);
1308 while ((i
= m
->cgroup_queue
)) {
1309 assert(i
->in_cgroup_queue
);
1311 r
= unit_realize_cgroup_now(i
, state
);
1313 log_warning_errno(r
, "Failed to realize cgroups for queued unit %s, ignoring: %m", i
->id
);
1321 static void unit_queue_siblings(Unit
*u
) {
1324 /* This adds the siblings of the specified unit and the
1325 * siblings of all parent units to the cgroup queue. (But
1326 * neither the specified unit itself nor the parents.) */
1328 while ((slice
= UNIT_DEREF(u
->slice
))) {
1332 SET_FOREACH(m
, slice
->dependencies
[UNIT_BEFORE
], i
) {
1336 /* Skip units that have a dependency on the slice
1337 * but aren't actually in it. */
1338 if (UNIT_DEREF(m
->slice
) != slice
)
1341 /* No point in doing cgroup application for units
1342 * without active processes. */
1343 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(m
)))
1346 /* If the unit doesn't need any new controllers
1347 * and has current ones realized, it doesn't need
1349 if (unit_has_mask_realized(m
, unit_get_target_mask(m
), unit_get_enable_mask(m
)))
1352 unit_add_to_cgroup_queue(m
);
1359 int unit_realize_cgroup(Unit
*u
) {
1362 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1365 /* So, here's the deal: when realizing the cgroups for this
1366 * unit, we need to first create all parents, but there's more
1367 * actually: for the weight-based controllers we also need to
1368 * make sure that all our siblings (i.e. units that are in the
1369 * same slice as we are) have cgroups, too. Otherwise, things
1370 * would become very uneven as each of their processes would
1371 * get as much resources as all our group together. This call
1372 * will synchronously create the parent cgroups, but will
1373 * defer work on the siblings to the next event loop
1376 /* Add all sibling slices to the cgroup queue. */
1377 unit_queue_siblings(u
);
1379 /* And realize this one now (and apply the values) */
1380 return unit_realize_cgroup_now(u
, manager_state(u
->manager
));
1383 void unit_release_cgroup(Unit
*u
) {
1386 /* Forgets all cgroup details for this cgroup */
1388 if (u
->cgroup_path
) {
1389 (void) hashmap_remove(u
->manager
->cgroup_unit
, u
->cgroup_path
);
1390 u
->cgroup_path
= mfree(u
->cgroup_path
);
1393 if (u
->cgroup_inotify_wd
>= 0) {
1394 if (inotify_rm_watch(u
->manager
->cgroup_inotify_fd
, u
->cgroup_inotify_wd
) < 0)
1395 log_unit_debug_errno(u
, errno
, "Failed to remove cgroup inotify watch %i for %s, ignoring", u
->cgroup_inotify_wd
, u
->id
);
1397 (void) hashmap_remove(u
->manager
->cgroup_inotify_wd_unit
, INT_TO_PTR(u
->cgroup_inotify_wd
));
1398 u
->cgroup_inotify_wd
= -1;
1402 void unit_prune_cgroup(Unit
*u
) {
1408 /* Removes the cgroup, if empty and possible, and stops watching it. */
1410 if (!u
->cgroup_path
)
1413 is_root_slice
= unit_has_name(u
, SPECIAL_ROOT_SLICE
);
1415 r
= cg_trim_everywhere(u
->manager
->cgroup_supported
, u
->cgroup_path
, !is_root_slice
);
1417 log_unit_debug_errno(u
, r
, "Failed to destroy cgroup %s, ignoring: %m", u
->cgroup_path
);
1424 unit_release_cgroup(u
);
1426 u
->cgroup_realized
= false;
1427 u
->cgroup_realized_mask
= 0;
1428 u
->cgroup_enabled_mask
= 0;
1431 int unit_search_main_pid(Unit
*u
, pid_t
*ret
) {
1432 _cleanup_fclose_
FILE *f
= NULL
;
1433 pid_t pid
= 0, npid
, mypid
;
1439 if (!u
->cgroup_path
)
1442 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
, &f
);
1447 while (cg_read_pid(f
, &npid
) > 0) {
1453 /* Ignore processes that aren't our kids */
1454 if (get_process_ppid(npid
, &ppid
) >= 0 && ppid
!= mypid
)
1458 /* Dang, there's more than one daemonized PID
1459 in this group, so we don't know what process
1460 is the main process. */
1471 static int unit_watch_pids_in_path(Unit
*u
, const char *path
) {
1472 _cleanup_closedir_
DIR *d
= NULL
;
1473 _cleanup_fclose_
FILE *f
= NULL
;
1479 r
= cg_enumerate_processes(SYSTEMD_CGROUP_CONTROLLER
, path
, &f
);
1485 while ((r
= cg_read_pid(f
, &pid
)) > 0) {
1486 r
= unit_watch_pid(u
, pid
);
1487 if (r
< 0 && ret
>= 0)
1491 if (r
< 0 && ret
>= 0)
1495 r
= cg_enumerate_subgroups(SYSTEMD_CGROUP_CONTROLLER
, path
, &d
);
1502 while ((r
= cg_read_subgroup(d
, &fn
)) > 0) {
1503 _cleanup_free_
char *p
= NULL
;
1505 p
= strjoin(path
, "/", fn
, NULL
);
1511 r
= unit_watch_pids_in_path(u
, p
);
1512 if (r
< 0 && ret
>= 0)
1516 if (r
< 0 && ret
>= 0)
1523 int unit_watch_all_pids(Unit
*u
) {
1526 /* Adds all PIDs from our cgroup to the set of PIDs we
1527 * watch. This is a fallback logic for cases where we do not
1528 * get reliable cgroup empty notifications: we try to use
1529 * SIGCHLD as replacement. */
1531 if (!u
->cgroup_path
)
1534 if (cg_unified() > 0) /* On unified we can use proper notifications */
1537 return unit_watch_pids_in_path(u
, u
->cgroup_path
);
1540 int unit_notify_cgroup_empty(Unit
*u
) {
1545 if (!u
->cgroup_path
)
1548 r
= cg_is_empty_recursive(SYSTEMD_CGROUP_CONTROLLER
, u
->cgroup_path
);
1552 unit_add_to_gc_queue(u
);
1554 if (UNIT_VTABLE(u
)->notify_cgroup_empty
)
1555 UNIT_VTABLE(u
)->notify_cgroup_empty(u
);
1560 static int on_cgroup_inotify_event(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1561 Manager
*m
= userdata
;
1568 union inotify_event_buffer buffer
;
1569 struct inotify_event
*e
;
1572 l
= read(fd
, &buffer
, sizeof(buffer
));
1574 if (errno
== EINTR
|| errno
== EAGAIN
)
1577 return log_error_errno(errno
, "Failed to read control group inotify events: %m");
1580 FOREACH_INOTIFY_EVENT(e
, buffer
, l
) {
1584 /* Queue overflow has no watch descriptor */
1587 if (e
->mask
& IN_IGNORED
)
1588 /* The watch was just removed */
1591 u
= hashmap_get(m
->cgroup_inotify_wd_unit
, INT_TO_PTR(e
->wd
));
1592 if (!u
) /* Not that inotify might deliver
1593 * events for a watch even after it
1594 * was removed, because it was queued
1595 * before the removal. Let's ignore
1596 * this here safely. */
1599 (void) unit_notify_cgroup_empty(u
);
1604 int manager_setup_cgroup(Manager
*m
) {
1605 _cleanup_free_
char *path
= NULL
;
1612 /* 1. Determine hierarchy */
1613 m
->cgroup_root
= mfree(m
->cgroup_root
);
1614 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, 0, &m
->cgroup_root
);
1616 return log_error_errno(r
, "Cannot determine cgroup we are running in: %m");
1618 /* Chop off the init scope, if we are already located in it */
1619 e
= endswith(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
1621 /* LEGACY: Also chop off the system slice if we are in
1622 * it. This is to support live upgrades from older systemd
1623 * versions where PID 1 was moved there. Also see
1624 * cg_get_root_path(). */
1625 if (!e
&& MANAGER_IS_SYSTEM(m
)) {
1626 e
= endswith(m
->cgroup_root
, "/" SPECIAL_SYSTEM_SLICE
);
1628 e
= endswith(m
->cgroup_root
, "/system"); /* even more legacy */
1633 /* And make sure to store away the root value without trailing
1634 * slash, even for the root dir, so that we can easily prepend
1636 while ((e
= endswith(m
->cgroup_root
, "/")))
1640 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, NULL
, &path
);
1642 return log_error_errno(r
, "Cannot find cgroup mount point: %m");
1644 unified
= cg_unified();
1646 return log_error_errno(r
, "Couldn't determine if we are running in the unified hierarchy: %m");
1648 log_debug("Unified cgroup hierarchy is located at %s.", path
);
1650 log_debug("Using cgroup controller " SYSTEMD_CGROUP_CONTROLLER
". File system hierarchy is at %s.", path
);
1653 const char *scope_path
;
1655 /* 3. Install agent */
1658 /* In the unified hierarchy we can can get
1659 * cgroup empty notifications via inotify. */
1661 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
1662 safe_close(m
->cgroup_inotify_fd
);
1664 m
->cgroup_inotify_fd
= inotify_init1(IN_NONBLOCK
|IN_CLOEXEC
);
1665 if (m
->cgroup_inotify_fd
< 0)
1666 return log_error_errno(errno
, "Failed to create control group inotify object: %m");
1668 r
= sd_event_add_io(m
->event
, &m
->cgroup_inotify_event_source
, m
->cgroup_inotify_fd
, EPOLLIN
, on_cgroup_inotify_event
, m
);
1670 return log_error_errno(r
, "Failed to watch control group inotify object: %m");
1672 /* Process cgroup empty notifications early, but after service notifications and SIGCHLD. Also
1673 * see handling of cgroup agent notifications, for the classic cgroup hierarchy support. */
1674 r
= sd_event_source_set_priority(m
->cgroup_inotify_event_source
, SD_EVENT_PRIORITY_NORMAL
-5);
1676 return log_error_errno(r
, "Failed to set priority of inotify event source: %m");
1678 (void) sd_event_source_set_description(m
->cgroup_inotify_event_source
, "cgroup-inotify");
1680 } else if (MANAGER_IS_SYSTEM(m
)) {
1682 /* On the legacy hierarchy we only get
1683 * notifications via cgroup agents. (Which
1684 * isn't really reliable, since it does not
1685 * generate events when control groups with
1686 * children run empty. */
1688 r
= cg_install_release_agent(SYSTEMD_CGROUP_CONTROLLER
, SYSTEMD_CGROUP_AGENT_PATH
);
1690 log_warning_errno(r
, "Failed to install release agent, ignoring: %m");
1692 log_debug("Installed release agent.");
1694 log_debug("Release agent already installed.");
1697 /* 4. Make sure we are in the special "init.scope" unit in the root slice. */
1698 scope_path
= strjoina(m
->cgroup_root
, "/" SPECIAL_INIT_SCOPE
);
1699 r
= cg_create_and_attach(SYSTEMD_CGROUP_CONTROLLER
, scope_path
, 0);
1701 return log_error_errno(r
, "Failed to create %s control group: %m", scope_path
);
1703 /* also, move all other userspace processes remaining
1704 * in the root cgroup into that scope. */
1705 r
= cg_migrate(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, SYSTEMD_CGROUP_CONTROLLER
, scope_path
, false);
1707 log_warning_errno(r
, "Couldn't move remaining userspace processes, ignoring: %m");
1709 /* 5. And pin it, so that it cannot be unmounted */
1710 safe_close(m
->pin_cgroupfs_fd
);
1711 m
->pin_cgroupfs_fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_DIRECTORY
|O_NOCTTY
|O_NONBLOCK
);
1712 if (m
->pin_cgroupfs_fd
< 0)
1713 return log_error_errno(errno
, "Failed to open pin file: %m");
1715 /* 6. Always enable hierarchical support if it exists... */
1717 (void) cg_set_attribute("memory", "/", "memory.use_hierarchy", "1");
1720 /* 7. Figure out which controllers are supported */
1721 r
= cg_mask_supported(&m
->cgroup_supported
);
1723 return log_error_errno(r
, "Failed to determine supported controllers: %m");
1725 for (c
= 0; c
< _CGROUP_CONTROLLER_MAX
; c
++)
1726 log_debug("Controller '%s' supported: %s", cgroup_controller_to_string(c
), yes_no(m
->cgroup_supported
& CGROUP_CONTROLLER_TO_MASK(c
)));
1731 void manager_shutdown_cgroup(Manager
*m
, bool delete) {
1734 /* We can't really delete the group, since we are in it. But
1736 if (delete && m
->cgroup_root
)
1737 (void) cg_trim(SYSTEMD_CGROUP_CONTROLLER
, m
->cgroup_root
, false);
1739 m
->cgroup_inotify_wd_unit
= hashmap_free(m
->cgroup_inotify_wd_unit
);
1741 m
->cgroup_inotify_event_source
= sd_event_source_unref(m
->cgroup_inotify_event_source
);
1742 m
->cgroup_inotify_fd
= safe_close(m
->cgroup_inotify_fd
);
1744 m
->pin_cgroupfs_fd
= safe_close(m
->pin_cgroupfs_fd
);
1746 m
->cgroup_root
= mfree(m
->cgroup_root
);
1749 Unit
* manager_get_unit_by_cgroup(Manager
*m
, const char *cgroup
) {
1756 u
= hashmap_get(m
->cgroup_unit
, cgroup
);
1760 p
= strdupa(cgroup
);
1764 e
= strrchr(p
, '/');
1766 return hashmap_get(m
->cgroup_unit
, SPECIAL_ROOT_SLICE
);
1770 u
= hashmap_get(m
->cgroup_unit
, p
);
1776 Unit
*manager_get_unit_by_pid_cgroup(Manager
*m
, pid_t pid
) {
1777 _cleanup_free_
char *cgroup
= NULL
;
1785 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, pid
, &cgroup
);
1789 return manager_get_unit_by_cgroup(m
, cgroup
);
1792 Unit
*manager_get_unit_by_pid(Manager
*m
, pid_t pid
) {
1801 return hashmap_get(m
->units
, SPECIAL_INIT_SCOPE
);
1803 u
= hashmap_get(m
->watch_pids1
, PID_TO_PTR(pid
));
1807 u
= hashmap_get(m
->watch_pids2
, PID_TO_PTR(pid
));
1811 return manager_get_unit_by_pid_cgroup(m
, pid
);
1814 int manager_notify_cgroup_empty(Manager
*m
, const char *cgroup
) {
1820 log_debug("Got cgroup empty notification for: %s", cgroup
);
1822 u
= manager_get_unit_by_cgroup(m
, cgroup
);
1826 return unit_notify_cgroup_empty(u
);
1829 int unit_get_memory_current(Unit
*u
, uint64_t *ret
) {
1830 _cleanup_free_
char *v
= NULL
;
1836 if (!u
->cgroup_path
)
1839 if ((u
->cgroup_realized_mask
& CGROUP_MASK_MEMORY
) == 0)
1842 if (cg_unified() <= 0)
1843 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.usage_in_bytes", &v
);
1845 r
= cg_get_attribute("memory", u
->cgroup_path
, "memory.current", &v
);
1851 return safe_atou64(v
, ret
);
1854 int unit_get_tasks_current(Unit
*u
, uint64_t *ret
) {
1855 _cleanup_free_
char *v
= NULL
;
1861 if (!u
->cgroup_path
)
1864 if ((u
->cgroup_realized_mask
& CGROUP_MASK_PIDS
) == 0)
1867 r
= cg_get_attribute("pids", u
->cgroup_path
, "pids.current", &v
);
1873 return safe_atou64(v
, ret
);
1876 static int unit_get_cpu_usage_raw(Unit
*u
, nsec_t
*ret
) {
1877 _cleanup_free_
char *v
= NULL
;
1884 if (!u
->cgroup_path
)
1887 if ((u
->cgroup_realized_mask
& CGROUP_MASK_CPUACCT
) == 0)
1890 r
= cg_get_attribute("cpuacct", u
->cgroup_path
, "cpuacct.usage", &v
);
1896 r
= safe_atou64(v
, &ns
);
1904 int unit_get_cpu_usage(Unit
*u
, nsec_t
*ret
) {
1908 r
= unit_get_cpu_usage_raw(u
, &ns
);
1912 if (ns
> u
->cpuacct_usage_base
)
1913 ns
-= u
->cpuacct_usage_base
;
1921 int unit_reset_cpu_usage(Unit
*u
) {
1927 r
= unit_get_cpu_usage_raw(u
, &ns
);
1929 u
->cpuacct_usage_base
= 0;
1933 u
->cpuacct_usage_base
= ns
;
1937 bool unit_cgroup_delegate(Unit
*u
) {
1942 c
= unit_get_cgroup_context(u
);
1949 void unit_invalidate_cgroup(Unit
*u
, CGroupMask m
) {
1952 if (!UNIT_HAS_CGROUP_CONTEXT(u
))
1958 /* always invalidate compat pairs together */
1959 if (m
& (CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
))
1960 m
|= CGROUP_MASK_IO
| CGROUP_MASK_BLKIO
;
1962 if ((u
->cgroup_realized_mask
& m
) == 0)
1965 u
->cgroup_realized_mask
&= ~m
;
1966 unit_add_to_cgroup_queue(u
);
1969 void manager_invalidate_startup_units(Manager
*m
) {
1975 SET_FOREACH(u
, m
->startup_units
, i
)
1976 unit_invalidate_cgroup(u
, CGROUP_MASK_CPU
|CGROUP_MASK_IO
|CGROUP_MASK_BLKIO
);
1979 static const char* const cgroup_device_policy_table
[_CGROUP_DEVICE_POLICY_MAX
] = {
1980 [CGROUP_AUTO
] = "auto",
1981 [CGROUP_CLOSED
] = "closed",
1982 [CGROUP_STRICT
] = "strict",
1985 DEFINE_STRING_TABLE_LOOKUP(cgroup_device_policy
, CGroupDevicePolicy
);