• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "absl/base/internal/sysinfo.h"
16 
17 #include "absl/base/attributes.h"
18 
19 #ifdef _WIN32
20 #include <windows.h>
21 #else
22 #include <fcntl.h>
23 #include <pthread.h>
24 #include <sys/stat.h>
25 #include <sys/types.h>
26 #include <unistd.h>
27 #endif
28 
29 #ifdef __linux__
30 #include <sys/syscall.h>
31 #endif
32 
33 #if defined(__APPLE__) || defined(__FreeBSD__)
34 #include <sys/sysctl.h>
35 #endif
36 
37 #if defined(__myriad2__)
38 #include <rtems.h>
39 #endif
40 
41 #include <string.h>
42 
43 #include <cassert>
44 #include <cstdint>
45 #include <cstdio>
46 #include <cstdlib>
47 #include <ctime>
48 #include <limits>
49 #include <thread>  // NOLINT(build/c++11)
50 #include <utility>
51 #include <vector>
52 
53 #include "absl/base/call_once.h"
54 #include "absl/base/config.h"
55 #include "absl/base/internal/raw_logging.h"
56 #include "absl/base/internal/spinlock.h"
57 #include "absl/base/internal/unscaledcycleclock.h"
58 #include "absl/base/thread_annotations.h"
59 
60 namespace absl {
61 ABSL_NAMESPACE_BEGIN
62 namespace base_internal {
63 
64 namespace {
65 
66 #if defined(_WIN32)
67 
68 // Returns number of bits set in `bitMask`
Win32CountSetBits(ULONG_PTR bitMask)69 DWORD Win32CountSetBits(ULONG_PTR bitMask) {
70   for (DWORD bitSetCount = 0; ; ++bitSetCount) {
71     if (bitMask == 0) return bitSetCount;
72     bitMask &= bitMask - 1;
73   }
74 }
75 
76 // Returns the number of logical CPUs using GetLogicalProcessorInformation(), or
77 // 0 if the number of processors is not available or can not be computed.
78 // https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getlogicalprocessorinformation
Win32NumCPUs()79 int Win32NumCPUs() {
80 #pragma comment(lib, "kernel32.lib")
81   using Info = SYSTEM_LOGICAL_PROCESSOR_INFORMATION;
82 
83   DWORD info_size = sizeof(Info);
84   Info* info(static_cast<Info*>(malloc(info_size)));
85   if (info == nullptr) return 0;
86 
87   bool success = GetLogicalProcessorInformation(info, &info_size);
88   if (!success && GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
89     free(info);
90     info = static_cast<Info*>(malloc(info_size));
91     if (info == nullptr) return 0;
92     success = GetLogicalProcessorInformation(info, &info_size);
93   }
94 
95   DWORD logicalProcessorCount = 0;
96   if (success) {
97     Info* ptr = info;
98     DWORD byteOffset = 0;
99     while (byteOffset + sizeof(Info) <= info_size) {
100       switch (ptr->Relationship) {
101         case RelationProcessorCore:
102           logicalProcessorCount += Win32CountSetBits(ptr->ProcessorMask);
103           break;
104 
105         case RelationNumaNode:
106         case RelationCache:
107         case RelationProcessorPackage:
108           // Ignore other entries
109           break;
110 
111         default:
112           // Ignore unknown entries
113           break;
114       }
115       byteOffset += sizeof(Info);
116       ptr++;
117     }
118   }
119   free(info);
120   return logicalProcessorCount;
121 }
122 
123 #endif
124 
125 }  // namespace
126 
127 
GetNumCPUs()128 static int GetNumCPUs() {
129 #if defined(__myriad2__)
130   return 1;
131 #elif defined(_WIN32)
132   const unsigned hardware_concurrency = Win32NumCPUs();
133   return hardware_concurrency ? hardware_concurrency : 1;
134 #else
135   // Other possibilities:
136   //  - Read /sys/devices/system/cpu/online and use cpumask_parse()
137   //  - sysconf(_SC_NPROCESSORS_ONLN)
138   return std::thread::hardware_concurrency();
139 #endif
140 }
141 
142 #if defined(_WIN32)
143 
GetNominalCPUFrequency()144 static double GetNominalCPUFrequency() {
145 #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && \
146     !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
147   // UWP apps don't have access to the registry and currently don't provide an
148   // API informing about CPU nominal frequency.
149   return 1.0;
150 #else
151 #pragma comment(lib, "advapi32.lib")  // For Reg* functions.
152   HKEY key;
153   // Use the Reg* functions rather than the SH functions because shlwapi.dll
154   // pulls in gdi32.dll which makes process destruction much more costly.
155   if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,
156                     "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", 0,
157                     KEY_READ, &key) == ERROR_SUCCESS) {
158     DWORD type = 0;
159     DWORD data = 0;
160     DWORD data_size = sizeof(data);
161     auto result = RegQueryValueExA(key, "~MHz", 0, &type,
162                                    reinterpret_cast<LPBYTE>(&data), &data_size);
163     RegCloseKey(key);
164     if (result == ERROR_SUCCESS && type == REG_DWORD &&
165         data_size == sizeof(data)) {
166       return data * 1e6;  // Value is MHz.
167     }
168   }
169   return 1.0;
170 #endif  // WINAPI_PARTITION_APP && !WINAPI_PARTITION_DESKTOP
171 }
172 
173 #elif defined(CTL_HW) && defined(HW_CPU_FREQ)
174 
GetNominalCPUFrequency()175 static double GetNominalCPUFrequency() {
176   unsigned freq;
177   size_t size = sizeof(freq);
178   int mib[2] = {CTL_HW, HW_CPU_FREQ};
179   if (sysctl(mib, 2, &freq, &size, nullptr, 0) == 0) {
180     return static_cast<double>(freq);
181   }
182   return 1.0;
183 }
184 
185 #else
186 
187 // Helper function for reading a long from a file. Returns true if successful
188 // and the memory location pointed to by value is set to the value read.
ReadLongFromFile(const char * file,long * value)189 static bool ReadLongFromFile(const char *file, long *value) {
190   bool ret = false;
191   int fd = open(file, O_RDONLY);
192   if (fd != -1) {
193     char line[1024];
194     char *err;
195     memset(line, '\0', sizeof(line));
196     int len = read(fd, line, sizeof(line) - 1);
197     if (len <= 0) {
198       ret = false;
199     } else {
200       const long temp_value = strtol(line, &err, 10);
201       if (line[0] != '\0' && (*err == '\n' || *err == '\0')) {
202         *value = temp_value;
203         ret = true;
204       }
205     }
206     close(fd);
207   }
208   return ret;
209 }
210 
211 #if defined(ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY)
212 
213 // Reads a monotonic time source and returns a value in
214 // nanoseconds. The returned value uses an arbitrary epoch, not the
215 // Unix epoch.
ReadMonotonicClockNanos()216 static int64_t ReadMonotonicClockNanos() {
217   struct timespec t;
218 #ifdef CLOCK_MONOTONIC_RAW
219   int rc = clock_gettime(CLOCK_MONOTONIC_RAW, &t);
220 #else
221   int rc = clock_gettime(CLOCK_MONOTONIC, &t);
222 #endif
223   if (rc != 0) {
224     perror("clock_gettime() failed");
225     abort();
226   }
227   return int64_t{t.tv_sec} * 1000000000 + t.tv_nsec;
228 }
229 
230 class UnscaledCycleClockWrapperForInitializeFrequency {
231  public:
Now()232   static int64_t Now() { return base_internal::UnscaledCycleClock::Now(); }
233 };
234 
235 struct TimeTscPair {
236   int64_t time;  // From ReadMonotonicClockNanos().
237   int64_t tsc;   // From UnscaledCycleClock::Now().
238 };
239 
240 // Returns a pair of values (monotonic kernel time, TSC ticks) that
241 // approximately correspond to each other.  This is accomplished by
242 // doing several reads and picking the reading with the lowest
243 // latency.  This approach is used to minimize the probability that
244 // our thread was preempted between clock reads.
GetTimeTscPair()245 static TimeTscPair GetTimeTscPair() {
246   int64_t best_latency = std::numeric_limits<int64_t>::max();
247   TimeTscPair best;
248   for (int i = 0; i < 10; ++i) {
249     int64_t t0 = ReadMonotonicClockNanos();
250     int64_t tsc = UnscaledCycleClockWrapperForInitializeFrequency::Now();
251     int64_t t1 = ReadMonotonicClockNanos();
252     int64_t latency = t1 - t0;
253     if (latency < best_latency) {
254       best_latency = latency;
255       best.time = t0;
256       best.tsc = tsc;
257     }
258   }
259   return best;
260 }
261 
262 // Measures and returns the TSC frequency by taking a pair of
263 // measurements approximately `sleep_nanoseconds` apart.
MeasureTscFrequencyWithSleep(int sleep_nanoseconds)264 static double MeasureTscFrequencyWithSleep(int sleep_nanoseconds) {
265   auto t0 = GetTimeTscPair();
266   struct timespec ts;
267   ts.tv_sec = 0;
268   ts.tv_nsec = sleep_nanoseconds;
269   while (nanosleep(&ts, &ts) != 0 && errno == EINTR) {}
270   auto t1 = GetTimeTscPair();
271   double elapsed_ticks = t1.tsc - t0.tsc;
272   double elapsed_time = (t1.time - t0.time) * 1e-9;
273   return elapsed_ticks / elapsed_time;
274 }
275 
276 // Measures and returns the TSC frequency by calling
277 // MeasureTscFrequencyWithSleep(), doubling the sleep interval until the
278 // frequency measurement stabilizes.
MeasureTscFrequency()279 static double MeasureTscFrequency() {
280   double last_measurement = -1.0;
281   int sleep_nanoseconds = 1000000;  // 1 millisecond.
282   for (int i = 0; i < 8; ++i) {
283     double measurement = MeasureTscFrequencyWithSleep(sleep_nanoseconds);
284     if (measurement * 0.99 < last_measurement &&
285         last_measurement < measurement * 1.01) {
286       // Use the current measurement if it is within 1% of the
287       // previous measurement.
288       return measurement;
289     }
290     last_measurement = measurement;
291     sleep_nanoseconds *= 2;
292   }
293   return last_measurement;
294 }
295 
296 #endif  // ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY
297 
GetNominalCPUFrequency()298 static double GetNominalCPUFrequency() {
299   long freq = 0;
300 
301   // Google's production kernel has a patch to export the TSC
302   // frequency through sysfs. If the kernel is exporting the TSC
303   // frequency use that. There are issues where cpuinfo_max_freq
304   // cannot be relied on because the BIOS may be exporting an invalid
305   // p-state (on x86) or p-states may be used to put the processor in
306   // a new mode (turbo mode). Essentially, those frequencies cannot
307   // always be relied upon. The same reasons apply to /proc/cpuinfo as
308   // well.
309   if (ReadLongFromFile("/sys/devices/system/cpu/cpu0/tsc_freq_khz", &freq)) {
310     return freq * 1e3;  // Value is kHz.
311   }
312 
313 #if defined(ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY)
314   // On these platforms, the TSC frequency is the nominal CPU
315   // frequency.  But without having the kernel export it directly
316   // though /sys/devices/system/cpu/cpu0/tsc_freq_khz, there is no
317   // other way to reliably get the TSC frequency, so we have to
318   // measure it ourselves.  Some CPUs abuse cpuinfo_max_freq by
319   // exporting "fake" frequencies for implementing new features. For
320   // example, Intel's turbo mode is enabled by exposing a p-state
321   // value with a higher frequency than that of the real TSC
322   // rate. Because of this, we prefer to measure the TSC rate
323   // ourselves on i386 and x86-64.
324   return MeasureTscFrequency();
325 #else
326 
327   // If CPU scaling is in effect, we want to use the *maximum*
328   // frequency, not whatever CPU speed some random processor happens
329   // to be using now.
330   if (ReadLongFromFile("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq",
331                        &freq)) {
332     return freq * 1e3;  // Value is kHz.
333   }
334 
335   return 1.0;
336 #endif  // !ABSL_INTERNAL_UNSCALED_CYCLECLOCK_FREQUENCY_IS_CPU_FREQUENCY
337 }
338 
339 #endif
340 
341 ABSL_CONST_INIT static once_flag init_num_cpus_once;
342 ABSL_CONST_INIT static int num_cpus = 0;
343 
344 // NumCPUs() may be called before main() and before malloc is properly
345 // initialized, therefore this must not allocate memory.
NumCPUs()346 int NumCPUs() {
347   base_internal::LowLevelCallOnce(
348       &init_num_cpus_once, []() { num_cpus = GetNumCPUs(); });
349   return num_cpus;
350 }
351 
352 // A default frequency of 0.0 might be dangerous if it is used in division.
353 ABSL_CONST_INIT static once_flag init_nominal_cpu_frequency_once;
354 ABSL_CONST_INIT static double nominal_cpu_frequency = 1.0;
355 
356 // NominalCPUFrequency() may be called before main() and before malloc is
357 // properly initialized, therefore this must not allocate memory.
NominalCPUFrequency()358 double NominalCPUFrequency() {
359   base_internal::LowLevelCallOnce(
360       &init_nominal_cpu_frequency_once,
361       []() { nominal_cpu_frequency = GetNominalCPUFrequency(); });
362   return nominal_cpu_frequency;
363 }
364 
365 #if defined(_WIN32)
366 
GetTID()367 pid_t GetTID() {
368   return pid_t{GetCurrentThreadId()};
369 }
370 
371 #elif defined(__linux__)
372 
373 #ifndef SYS_gettid
374 #define SYS_gettid __NR_gettid
375 #endif
376 
GetTID()377 pid_t GetTID() {
378   return syscall(SYS_gettid);
379 }
380 
381 #elif defined(__akaros__)
382 
GetTID()383 pid_t GetTID() {
384   // Akaros has a concept of "vcore context", which is the state the program
385   // is forced into when we need to make a user-level scheduling decision, or
386   // run a signal handler.  This is analogous to the interrupt context that a
387   // CPU might enter if it encounters some kind of exception.
388   //
389   // There is no current thread context in vcore context, but we need to give
390   // a reasonable answer if asked for a thread ID (e.g., in a signal handler).
391   // Thread 0 always exists, so if we are in vcore context, we return that.
392   //
393   // Otherwise, we know (since we are using pthreads) that the uthread struct
394   // current_uthread is pointing to is the first element of a
395   // struct pthread_tcb, so we extract and return the thread ID from that.
396   //
397   // TODO(dcross): Akaros anticipates moving the thread ID to the uthread
398   // structure at some point. We should modify this code to remove the cast
399   // when that happens.
400   if (in_vcore_context())
401     return 0;
402   return reinterpret_cast<struct pthread_tcb *>(current_uthread)->id;
403 }
404 
405 #elif defined(__myriad2__)
406 
GetTID()407 pid_t GetTID() {
408   uint32_t tid;
409   rtems_task_ident(RTEMS_SELF, 0, &tid);
410   return tid;
411 }
412 
413 #else
414 
415 // Fallback implementation of GetTID using pthread_getspecific.
416 ABSL_CONST_INIT static once_flag tid_once;
417 ABSL_CONST_INIT static pthread_key_t tid_key;
418 ABSL_CONST_INIT static absl::base_internal::SpinLock tid_lock(
419     absl::kConstInit, base_internal::SCHEDULE_KERNEL_ONLY);
420 
421 // We set a bit per thread in this array to indicate that an ID is in
422 // use. ID 0 is unused because it is the default value returned by
423 // pthread_getspecific().
424 ABSL_CONST_INIT static std::vector<uint32_t> *tid_array
425     ABSL_GUARDED_BY(tid_lock) = nullptr;
426 static constexpr int kBitsPerWord = 32;  // tid_array is uint32_t.
427 
428 // Returns the TID to tid_array.
FreeTID(void * v)429 static void FreeTID(void *v) {
430   intptr_t tid = reinterpret_cast<intptr_t>(v);
431   int word = tid / kBitsPerWord;
432   uint32_t mask = ~(1u << (tid % kBitsPerWord));
433   absl::base_internal::SpinLockHolder lock(&tid_lock);
434   assert(0 <= word && static_cast<size_t>(word) < tid_array->size());
435   (*tid_array)[word] &= mask;
436 }
437 
InitGetTID()438 static void InitGetTID() {
439   if (pthread_key_create(&tid_key, FreeTID) != 0) {
440     // The logging system calls GetTID() so it can't be used here.
441     perror("pthread_key_create failed");
442     abort();
443   }
444 
445   // Initialize tid_array.
446   absl::base_internal::SpinLockHolder lock(&tid_lock);
447   tid_array = new std::vector<uint32_t>(1);
448   (*tid_array)[0] = 1;  // ID 0 is never-allocated.
449 }
450 
451 // Return a per-thread small integer ID from pthread's thread-specific data.
GetTID()452 pid_t GetTID() {
453   absl::call_once(tid_once, InitGetTID);
454 
455   intptr_t tid = reinterpret_cast<intptr_t>(pthread_getspecific(tid_key));
456   if (tid != 0) {
457     return tid;
458   }
459 
460   int bit;  // tid_array[word] = 1u << bit;
461   size_t word;
462   {
463     // Search for the first unused ID.
464     absl::base_internal::SpinLockHolder lock(&tid_lock);
465     // First search for a word in the array that is not all ones.
466     word = 0;
467     while (word < tid_array->size() && ~(*tid_array)[word] == 0) {
468       ++word;
469     }
470     if (word == tid_array->size()) {
471       tid_array->push_back(0);  // No space left, add kBitsPerWord more IDs.
472     }
473     // Search for a zero bit in the word.
474     bit = 0;
475     while (bit < kBitsPerWord && (((*tid_array)[word] >> bit) & 1) != 0) {
476       ++bit;
477     }
478     tid = (word * kBitsPerWord) + bit;
479     (*tid_array)[word] |= 1u << bit;  // Mark the TID as allocated.
480   }
481 
482   if (pthread_setspecific(tid_key, reinterpret_cast<void *>(tid)) != 0) {
483     perror("pthread_setspecific failed");
484     abort();
485   }
486 
487   return static_cast<pid_t>(tid);
488 }
489 
490 #endif
491 
492 // GetCachedTID() caches the thread ID in thread-local storage (which is a
493 // userspace construct) to avoid unnecessary system calls. Without this caching,
494 // it can take roughly 98ns, while it takes roughly 1ns with this caching.
GetCachedTID()495 pid_t GetCachedTID() {
496 #ifdef ABSL_HAVE_THREAD_LOCAL
497   static thread_local pid_t thread_id = GetTID();
498   return thread_id;
499 #else
500   return GetTID();
501 #endif  // ABSL_HAVE_THREAD_LOCAL
502 }
503 
504 }  // namespace base_internal
505 ABSL_NAMESPACE_END
506 }  // namespace absl
507