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
27 int __num_possible_cpus
;
29 #if (defined(__GLIBC__) || defined( __UCLIBC__))
30 void _get_num_possible_cpus(void)
34 /* On Linux, when some processors are offline
35 * _SC_NPROCESSORS_CONF counts the offline
36 * processors, whereas _SC_NPROCESSORS_ONLN
37 * does not. If we used _SC_NPROCESSORS_ONLN,
38 * getcpu() could return a value greater than
39 * this sysconf, in which case the arrays
40 * indexed by processor would overflow.
42 result
= sysconf(_SC_NPROCESSORS_CONF
);
45 __num_possible_cpus
= result
;
51 * The MUSL libc implementation of the _SC_NPROCESSORS_CONF sysconf does not
52 * return the number of configured CPUs in the system but relies on the cpu
53 * affinity mask of the current task.
55 * So instead we use a strategy similar to GLIBC's, counting the cpu
56 * directories in "/sys/devices/system/cpu" and fallback on the value from
57 * sysconf if it fails.
64 #include <sys/types.h>
66 #define __max(a,b) ((a)>(b)?(a):(b))
68 void _get_num_possible_cpus(void)
70 int result
, count
= 0;
74 cpudir
= opendir("/sys/devices/system/cpu");
79 * Count the number of directories named "cpu" followed by and
80 * integer. This is the same strategy as glibc uses.
82 while ((entry
= readdir(cpudir
))) {
83 if (entry
->d_type
== DT_DIR
&&
84 strncmp(entry
->d_name
, "cpu", 3) == 0) {
87 unsigned long cpu_num
;
89 cpu_num
= strtoul(entry
->d_name
+ 3, &endptr
, 10);
90 if ((cpu_num
< ULONG_MAX
) && (endptr
!= entry
->d_name
+ 3)
91 && (*endptr
== '\0')) {
99 * Get the sysconf value as a fallback. Keep the highest number.
101 result
= __max(sysconf(_SC_NPROCESSORS_CONF
), count
);
104 * If both methods failed, don't store the value.
108 __num_possible_cpus
= result
;
This page took 0.038554 seconds and 4 git commands to generate.