]> git.proxmox.com Git - mirror_lxcfs.git/blob - src/cpuset_parse.c
build: tools: keep trailing newline in jinja2 renderer
[mirror_lxcfs.git] / src / cpuset_parse.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include "config.h"
4
5 #include <stdio.h>
6 #include <string.h>
7 #include <stdbool.h>
8 #include <stdlib.h>
9
10 #include "cgroups/cgroup.h"
11 #include "cgroups/cgroup_utils.h"
12 #include "memory_utils.h"
13
14 /*
15 * Helper functions for cpuset_in-set
16 */
17 static char *cpuset_nexttok(const char *c)
18 {
19 char *r;
20
21 if (!strlen(c))
22 return NULL;
23
24 r = strchr(c + 1, ',');
25 return r ? (r + 1) : NULL;
26 }
27
28 static int cpuset_getrange(const char *c, int *a, int *b)
29 {
30 int ret;
31
32 ret = sscanf(c, "%d-%d", a, b);
33 return ret;
34 }
35
36 /*
37 * cpusets are in format "1,2-3,4"
38 * iow, comma-delimited ranges
39 */
40 bool cpu_in_cpuset(int cpu, const char *cpuset)
41 {
42 for (const char *c = cpuset; c; c = cpuset_nexttok(c)) {
43 int a, b, ret;
44
45 ret = cpuset_getrange(c, &a, &b);
46 if (ret == 1 && cpu == a) /* "1" or "1,6" */
47 return true;
48 else if (ret == 2 && cpu >= a && cpu <= b) /* range match */
49 return true;
50 }
51
52 return false;
53 }
54
55 /*
56 * get cpu number in cpuset
57 */
58 int cpu_number_in_cpuset(const char *cpuset)
59 {
60 int cpu_number = 0;
61
62 for (const char *c = cpuset; c; c = cpuset_nexttok(c)) {
63 int a, b, ret;
64
65 ret = cpuset_getrange(c, &a, &b);
66 if (ret == 1)
67 cpu_number++;
68 else if (ret == 2)
69 cpu_number += a > b ? a - b + 1 : b - a + 1;
70 }
71
72 return cpu_number;
73 }