4 * Copyright (C) 2011-2012 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
5 * Copyright (C) 2019 Michael Jeanson <mjeanson@efficios.com>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; only
10 * version 2.1 of the License.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
28 int __num_possible_cpus
;
30 #if (defined(__GLIBC__) || defined( __UCLIBC__))
31 void _get_num_possible_cpus(void)
35 /* On Linux, when some processors are offline
36 * _SC_NPROCESSORS_CONF counts the offline
37 * processors, whereas _SC_NPROCESSORS_ONLN
38 * does not. If we used _SC_NPROCESSORS_ONLN,
39 * getcpu() could return a value greater than
40 * this sysconf, in which case the arrays
41 * indexed by processor would overflow.
43 result
= sysconf(_SC_NPROCESSORS_CONF
);
46 __num_possible_cpus
= result
;
52 * The MUSL libc implementation of the _SC_NPROCESSORS_CONF sysconf does not
53 * return the number of configured CPUs in the system but relies on the cpu
54 * affinity mask of the current task.
56 * So instead we use a strategy similar to GLIBC's, counting the cpu
57 * directories in "/sys/devices/system/cpu" and fallback on the value from
58 * sysconf if it fails.
65 #include <sys/types.h>
67 #define __max(a,b) ((a)>(b)?(a):(b))
69 void _get_num_possible_cpus(void)
71 int result
, count
= 0;
75 cpudir
= opendir("/sys/devices/system/cpu");
80 * Count the number of directories named "cpu" followed by and
81 * integer. This is the same strategy as glibc uses.
83 while ((entry
= readdir(cpudir
))) {
84 if (entry
->d_type
== DT_DIR
&&
85 strncmp(entry
->d_name
, "cpu", 3) == 0) {
88 unsigned long cpu_num
;
90 cpu_num
= strtoul(entry
->d_name
+ 3, &endptr
, 10);
91 if ((cpu_num
< ULONG_MAX
) && (endptr
!= entry
->d_name
+ 3)
92 && (*endptr
== '\0')) {
100 * Get the sysconf value as a fallback. Keep the highest number.
102 result
= __max(sysconf(_SC_NPROCESSORS_CONF
), count
);
105 * If both methods failed, don't store the value.
109 __num_possible_cpus
= result
;
This page took 0.034863 seconds and 4 git commands to generate.