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>
14 int __lttng_counter_num_possible_cpus
;
16 #if (defined(__GLIBC__) || defined( __UCLIBC__))
17 void _lttng_counter_get_num_possible_cpus(void)
21 /* On Linux, when some processors are offline
22 * _SC_NPROCESSORS_CONF counts the offline
23 * processors, whereas _SC_NPROCESSORS_ONLN
24 * does not. If we used _SC_NPROCESSORS_ONLN,
25 * getcpu() could return a value greater than
26 * this sysconf, in which case the arrays
27 * indexed by processor would overflow.
29 result
= sysconf(_SC_NPROCESSORS_CONF
);
32 __lttng_counter_num_possible_cpus
= result
;
38 * The MUSL libc implementation of the _SC_NPROCESSORS_CONF sysconf does not
39 * return the number of configured CPUs in the system but relies on the cpu
40 * affinity mask of the current task.
42 * So instead we use a strategy similar to GLIBC's, counting the cpu
43 * directories in "/sys/devices/system/cpu" and fallback on the value from
44 * sysconf if it fails.
51 #include <sys/types.h>
53 #define __max(a,b) ((a)>(b)?(a):(b))
55 void _lttng_counter_get_num_possible_cpus(void)
57 int result
, count
= 0;
61 cpudir
= opendir("/sys/devices/system/cpu");
66 * Count the number of directories named "cpu" followed by and
67 * integer. This is the same strategy as glibc uses.
69 while ((entry
= readdir(cpudir
))) {
70 if (entry
->d_type
== DT_DIR
&&
71 strncmp(entry
->d_name
, "cpu", 3) == 0) {
74 unsigned long cpu_num
;
76 cpu_num
= strtoul(entry
->d_name
+ 3, &endptr
, 10);
77 if ((cpu_num
< ULONG_MAX
) && (endptr
!= entry
->d_name
+ 3)
78 && (*endptr
== '\0')) {
86 * Get the sysconf value as a fallback. Keep the highest number.
88 result
= __max(sysconf(_SC_NPROCESSORS_CONF
), count
);
91 * If both methods failed, don't store the value.
95 __lttng_counter_num_possible_cpus
= result
;