Skip to content

Commit 1bb54c4

Browse files
brbborkmann
authored andcommitted
bpf, selftests: fix handling of sparse CPU allocations
Previously, bpf_num_possible_cpus() had a bug when calculating a number of possible CPUs in the case of sparse CPU allocations, as it was considering only the first range or element of /sys/devices/system/cpu/possible. E.g. in the case of "0,2-3" (CPU 1 is not available), the function returned 1 instead of 3. This patch fixes the function by making it parse all CPU ranges and elements. Signed-off-by: Martynas Pumputis <m@lambda.lt> Acked-by: Yonghong Song <yhs@fb.com> Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
1 parent 9d90436 commit 1bb54c4

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

tools/testing/selftests/bpf/bpf_util.h

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,25 +13,35 @@ static inline unsigned int bpf_num_possible_cpus(void)
1313
unsigned int start, end, possible_cpus = 0;
1414
char buff[128];
1515
FILE *fp;
16-
int n;
16+
int len, n, i, j = 0;
1717

1818
fp = fopen(fcpu, "r");
1919
if (!fp) {
2020
printf("Failed to open %s: '%s'!\n", fcpu, strerror(errno));
2121
exit(1);
2222
}
2323

24-
while (fgets(buff, sizeof(buff), fp)) {
25-
n = sscanf(buff, "%u-%u", &start, &end);
26-
if (n == 0) {
27-
printf("Failed to retrieve # possible CPUs!\n");
28-
exit(1);
29-
} else if (n == 1) {
30-
end = start;
24+
if (!fgets(buff, sizeof(buff), fp)) {
25+
printf("Failed to read %s!\n", fcpu);
26+
exit(1);
27+
}
28+
29+
len = strlen(buff);
30+
for (i = 0; i <= len; i++) {
31+
if (buff[i] == ',' || buff[i] == '\0') {
32+
buff[i] = '\0';
33+
n = sscanf(&buff[j], "%u-%u", &start, &end);
34+
if (n <= 0) {
35+
printf("Failed to retrieve # possible CPUs!\n");
36+
exit(1);
37+
} else if (n == 1) {
38+
end = start;
39+
}
40+
possible_cpus += end - start + 1;
41+
j = i + 1;
3142
}
32-
possible_cpus = start == 0 ? end + 1 : 0;
33-
break;
3443
}
44+
3545
fclose(fp);
3646

3747
return possible_cpus;

0 commit comments

Comments
 (0)