2 * SPDX-License-Identifier: LGPL-2.1-only
4 * Copyright (C) 2011-2012 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
5 * Copyright (C) 2019 Michael Jeanson <mjeanson@efficios.com>
15 int __lttng_counter_num_possible_cpus
;
17 #if (defined(__GLIBC__) || defined( __UCLIBC__))
18 void _lttng_counter_get_num_possible_cpus(void)
22 /* On Linux, when some processors are offline
23 * _SC_NPROCESSORS_CONF counts the offline
24 * processors, whereas _SC_NPROCESSORS_ONLN
25 * does not. If we used _SC_NPROCESSORS_ONLN,
26 * getcpu() could return a value greater than
27 * this sysconf, in which case the arrays
28 * indexed by processor would overflow.
30 result
= sysconf(_SC_NPROCESSORS_CONF
);
33 __lttng_counter_num_possible_cpus
= result
;
39 * The MUSL libc implementation of the _SC_NPROCESSORS_CONF sysconf does not
40 * return the number of configured CPUs in the system but relies on the cpu
41 * affinity mask of the current task.
43 * So instead we use a strategy similar to GLIBC's, counting the cpu
44 * directories in "/sys/devices/system/cpu" and fallback on the value from
45 * sysconf if it fails.
52 #include <sys/types.h>
54 #define __max(a,b) ((a)>(b)?(a):(b))
56 void _lttng_counter_get_num_possible_cpus(void)
58 int result
, count
= 0;
62 cpudir
= opendir("/sys/devices/system/cpu");
67 * Count the number of directories named "cpu" followed by and
68 * integer. This is the same strategy as glibc uses.
70 while ((entry
= readdir(cpudir
))) {
71 if (entry
->d_type
== DT_DIR
&&
72 strncmp(entry
->d_name
, "cpu", 3) == 0) {
75 unsigned long cpu_num
;
77 cpu_num
= strtoul(entry
->d_name
+ 3, &endptr
, 10);
78 if ((cpu_num
< ULONG_MAX
) && (endptr
!= entry
->d_name
+ 3)
79 && (*endptr
== '\0')) {
87 * Get the sysconf value as a fallback. Keep the highest number.
89 result
= __max(sysconf(_SC_NPROCESSORS_CONF
), count
);
92 * If both methods failed, don't store the value.
96 __lttng_counter_num_possible_cpus
= result
;