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