Move libcounter to 'src/common/'
[lttng-ust.git] / src / common / counter / smp.c
1 /*
2 * SPDX-License-Identifier: LGPL-2.1-only
3 *
4 * Copyright (C) 2011-2012 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
5 * Copyright (C) 2019 Michael Jeanson <mjeanson@efficios.com>
6 */
7
8 #define _LGPL_SOURCE
9
10 #include <unistd.h>
11 #include <pthread.h>
12 #include "smp.h"
13
14 int __lttng_counter_num_possible_cpus;
15
16 #if (defined(__GLIBC__) || defined( __UCLIBC__))
17 void _lttng_counter_get_num_possible_cpus(void)
18 {
19 int result;
20
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.
28 */
29 result = sysconf(_SC_NPROCESSORS_CONF);
30 if (result == -1)
31 return;
32 __lttng_counter_num_possible_cpus = result;
33 }
34
35 #else
36
37 /*
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.
41 *
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.
45 */
46
47 #include <dirent.h>
48 #include <limits.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <sys/types.h>
52
53 #define __max(a,b) ((a)>(b)?(a):(b))
54
55 void _lttng_counter_get_num_possible_cpus(void)
56 {
57 int result, count = 0;
58 DIR *cpudir;
59 struct dirent *entry;
60
61 cpudir = opendir("/sys/devices/system/cpu");
62 if (cpudir == NULL)
63 goto end;
64
65 /*
66 * Count the number of directories named "cpu" followed by and
67 * integer. This is the same strategy as glibc uses.
68 */
69 while ((entry = readdir(cpudir))) {
70 if (entry->d_type == DT_DIR &&
71 strncmp(entry->d_name, "cpu", 3) == 0) {
72
73 char *endptr;
74 unsigned long cpu_num;
75
76 cpu_num = strtoul(entry->d_name + 3, &endptr, 10);
77 if ((cpu_num < ULONG_MAX) && (endptr != entry->d_name + 3)
78 && (*endptr == '\0')) {
79 count++;
80 }
81 }
82 }
83
84 end:
85 /*
86 * Get the sysconf value as a fallback. Keep the highest number.
87 */
88 result = __max(sysconf(_SC_NPROCESSORS_CONF), count);
89
90 /*
91 * If both methods failed, don't store the value.
92 */
93 if (result < 1)
94 return;
95 __lttng_counter_num_possible_cpus = result;
96 }
97 #endif
This page took 0.032137 seconds and 4 git commands to generate.