]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/cpu-set-util.c
pkgconfig: define variables relative to ${prefix}/${rootprefix}/${sysconfdir}
[thirdparty/systemd.git] / src / basic / cpu-set-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <stddef.h>
5 #include <syslog.h>
6
7 #include "alloc-util.h"
8 #include "cpu-set-util.h"
9 #include "extract-word.h"
10 #include "log.h"
11 #include "macro.h"
12 #include "parse-util.h"
13 #include "string-util.h"
14
15 cpu_set_t* cpu_set_malloc(unsigned *ncpus) {
16 cpu_set_t *c;
17 unsigned n = 1024;
18
19 /* Allocates the cpuset in the right size */
20
21 for (;;) {
22 c = CPU_ALLOC(n);
23 if (!c)
24 return NULL;
25
26 if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), c) >= 0) {
27 CPU_ZERO_S(CPU_ALLOC_SIZE(n), c);
28
29 if (ncpus)
30 *ncpus = n;
31
32 return c;
33 }
34
35 CPU_FREE(c);
36
37 if (errno != EINVAL)
38 return NULL;
39
40 n *= 2;
41 }
42 }
43
44 int parse_cpu_set_internal(
45 const char *rvalue,
46 cpu_set_t **cpu_set,
47 bool warn,
48 const char *unit,
49 const char *filename,
50 unsigned line,
51 const char *lvalue) {
52
53 _cleanup_cpu_free_ cpu_set_t *c = NULL;
54 const char *p = rvalue;
55 unsigned ncpus = 0;
56
57 assert(rvalue);
58
59 for (;;) {
60 _cleanup_free_ char *word = NULL;
61 unsigned cpu, cpu_lower, cpu_upper;
62 int r;
63
64 r = extract_first_word(&p, &word, WHITESPACE ",", EXTRACT_QUOTES);
65 if (r == -ENOMEM)
66 return warn ? log_oom() : -ENOMEM;
67 if (r < 0)
68 return warn ? log_syntax(unit, LOG_ERR, filename, line, r, "Invalid value for %s: %s", lvalue, rvalue) : r;
69 if (r == 0)
70 break;
71
72 if (!c) {
73 c = cpu_set_malloc(&ncpus);
74 if (!c)
75 return warn ? log_oom() : -ENOMEM;
76 }
77
78 r = parse_range(word, &cpu_lower, &cpu_upper);
79 if (r < 0)
80 return warn ? log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse CPU affinity '%s'", word) : r;
81 if (cpu_lower >= ncpus || cpu_upper >= ncpus)
82 return warn ? log_syntax(unit, LOG_ERR, filename, line, EINVAL, "CPU out of range '%s' ncpus is %u", word, ncpus) : -EINVAL;
83
84 if (cpu_lower > cpu_upper) {
85 if (warn)
86 log_syntax(unit, LOG_WARNING, filename, line, 0, "Range '%s' is invalid, %u > %u, ignoring", word, cpu_lower, cpu_upper);
87 continue;
88 }
89
90 for (cpu = cpu_lower; cpu <= cpu_upper; cpu++)
91 CPU_SET_S(cpu, CPU_ALLOC_SIZE(ncpus), c);
92 }
93
94 /* On success, sets *cpu_set and returns ncpus for the system. */
95 if (c)
96 *cpu_set = TAKE_PTR(c);
97
98 return (int) ncpus;
99 }