sysinfo.cc 16 KB

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