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>
12 #include <urcu/compiler.h>
14 #include "common/smp.h"
16 static int num_possible_cpus_cache
;
18 #if (defined(__GLIBC__) || defined( __UCLIBC__))
19 static void _get_num_possible_cpus(void)
23 /* On Linux, when some processors are offline
24 * _SC_NPROCESSORS_CONF counts the offline
25 * processors, whereas _SC_NPROCESSORS_ONLN
26 * does not. If we used _SC_NPROCESSORS_ONLN,
27 * getcpu() could return a value greater than
28 * this sysconf, in which case the arrays
29 * indexed by processor would overflow.
31 result
= sysconf(_SC_NPROCESSORS_CONF
);
34 num_possible_cpus_cache
= result
;
40 * The MUSL libc implementation of the _SC_NPROCESSORS_CONF sysconf does not
41 * return the number of configured CPUs in the system but relies on the cpu
42 * affinity mask of the current task.
44 * So instead we use a strategy similar to GLIBC's, counting the cpu
45 * directories in "/sys/devices/system/cpu" and fallback on the value from
46 * sysconf if it fails.
53 #include <sys/types.h>
55 #define __max(a,b) ((a)>(b)?(a):(b))
57 static void _get_num_possible_cpus(void)
59 int result
, count
= 0;
63 cpudir
= opendir("/sys/devices/system/cpu");
68 * Count the number of directories named "cpu" followed by and
69 * integer. This is the same strategy as glibc uses.
71 while ((entry
= readdir(cpudir
))) {
72 if (entry
->d_type
== DT_DIR
&&
73 strncmp(entry
->d_name
, "cpu", 3) == 0) {
76 unsigned long cpu_num
;
78 cpu_num
= strtoul(entry
->d_name
+ 3, &endptr
, 10);
79 if ((cpu_num
< ULONG_MAX
) && (endptr
!= entry
->d_name
+ 3)
80 && (*endptr
== '\0')) {
88 * Get the sysconf value as a fallback. Keep the highest number.
90 result
= __max(sysconf(_SC_NPROCESSORS_CONF
), count
);
93 * If both methods failed, don't store the value.
97 num_possible_cpus_cache
= result
;
102 * Returns the total number of CPUs in the system. If the cache is not yet
103 * initialized, get the value from the system through sysconf and cache it.
105 * If the sysconf call fails, don't populate the cache and return 0.
107 int num_possible_cpus(void)
109 if (caa_unlikely(!num_possible_cpus_cache
))
110 _get_num_possible_cpus();
112 return num_possible_cpus_cache
;
This page took 0.030992 seconds and 4 git commands to generate.