cpu.cc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/cpu.h"
  5. #include <inttypes.h>
  6. #include <limits.h>
  7. #include <stddef.h>
  8. #include <stdint.h>
  9. #include <string.h>
  10. #include <algorithm>
  11. #include <sstream>
  12. #include <utility>
  13. #include "base/no_destructor.h"
  14. #include "build/build_config.h"
  15. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \
  16. BUILDFLAG(IS_AIX)
  17. #include "base/containers/flat_set.h"
  18. #include "base/files/file_util.h"
  19. #include "base/format_macros.h"
  20. #include "base/notreached.h"
  21. #include "base/process/internal_linux.h"
  22. #include "base/strings/string_number_conversions.h"
  23. #include "base/strings/string_util.h"
  24. #include "base/strings/stringprintf.h"
  25. #include "base/system/sys_info.h"
  26. #include "base/threading/thread_restrictions.h"
  27. #endif
  28. #if defined(ARCH_CPU_ARM_FAMILY) && \
  29. (BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS))
  30. #include <asm/hwcap.h>
  31. #include <sys/auxv.h>
  32. #include "base/files/file_util.h"
  33. #include "base/numerics/checked_math.h"
  34. #include "base/ranges/algorithm.h"
  35. #include "base/strings/string_split.h"
  36. #include "base/strings/string_util.h"
  37. // Temporary definitions until a new hwcap.h is pulled in everywhere.
  38. // https://crbug.com/1265965
  39. #ifndef HWCAP2_MTE
  40. #define HWCAP2_MTE (1 << 18)
  41. #define HWCAP2_BTI (1 << 17)
  42. #endif
  43. struct ProcCpuInfo {
  44. std::string brand;
  45. uint8_t implementer = 0;
  46. uint32_t part_number = 0;
  47. };
  48. #endif
  49. #if defined(ARCH_CPU_X86_FAMILY)
  50. #if defined(COMPILER_MSVC)
  51. #include <intrin.h>
  52. #include <immintrin.h> // For _xgetbv()
  53. #endif
  54. #endif
  55. namespace base {
  56. #if defined(ARCH_CPU_X86_FAMILY)
  57. namespace internal {
  58. X86ModelInfo ComputeX86FamilyAndModel(const std::string& vendor,
  59. int signature) {
  60. X86ModelInfo results;
  61. results.family = (signature >> 8) & 0xf;
  62. results.model = (signature >> 4) & 0xf;
  63. results.ext_family = 0;
  64. results.ext_model = 0;
  65. // The "Intel 64 and IA-32 Architectures Developer's Manual: Vol. 2A"
  66. // specifies the Extended Model is defined only when the Base Family is
  67. // 06h or 0Fh.
  68. // The "AMD CPUID Specification" specifies that the Extended Model is
  69. // defined only when Base Family is 0Fh.
  70. // Both manuals define the display model as
  71. // {ExtendedModel[3:0],BaseModel[3:0]} in that case.
  72. if (results.family == 0xf ||
  73. (results.family == 0x6 && vendor == "GenuineIntel")) {
  74. results.ext_model = (signature >> 16) & 0xf;
  75. results.model += results.ext_model << 4;
  76. }
  77. // Both the "Intel 64 and IA-32 Architectures Developer's Manual: Vol. 2A"
  78. // and the "AMD CPUID Specification" specify that the Extended Family is
  79. // defined only when the Base Family is 0Fh.
  80. // Both manuals define the display family as {0000b,BaseFamily[3:0]} +
  81. // ExtendedFamily[7:0] in that case.
  82. if (results.family == 0xf) {
  83. results.ext_family = (signature >> 20) & 0xff;
  84. results.family += results.ext_family;
  85. }
  86. return results;
  87. }
  88. } // namespace internal
  89. #endif // defined(ARCH_CPU_X86_FAMILY)
  90. CPU::CPU(bool require_branding) {
  91. Initialize(require_branding);
  92. }
  93. CPU::CPU() : CPU(true) {}
  94. CPU::CPU(CPU&&) = default;
  95. namespace {
  96. #if defined(ARCH_CPU_X86_FAMILY)
  97. #if !defined(COMPILER_MSVC)
  98. #if defined(__pic__) && defined(__i386__)
  99. void __cpuid(int cpu_info[4], int info_type) {
  100. __asm__ volatile(
  101. "mov %%ebx, %%edi\n"
  102. "cpuid\n"
  103. "xchg %%edi, %%ebx\n"
  104. : "=a"(cpu_info[0]), "=D"(cpu_info[1]), "=c"(cpu_info[2]),
  105. "=d"(cpu_info[3])
  106. : "a"(info_type), "c"(0));
  107. }
  108. #else
  109. void __cpuid(int cpu_info[4], int info_type) {
  110. __asm__ volatile("cpuid\n"
  111. : "=a"(cpu_info[0]), "=b"(cpu_info[1]), "=c"(cpu_info[2]),
  112. "=d"(cpu_info[3])
  113. : "a"(info_type), "c"(0));
  114. }
  115. #endif
  116. #endif // !defined(COMPILER_MSVC)
  117. // xgetbv returns the value of an Intel Extended Control Register (XCR).
  118. // Currently only XCR0 is defined by Intel so |xcr| should always be zero.
  119. uint64_t xgetbv(uint32_t xcr) {
  120. #if defined(COMPILER_MSVC)
  121. return _xgetbv(xcr);
  122. #else
  123. uint32_t eax, edx;
  124. __asm__ volatile (
  125. "xgetbv" : "=a"(eax), "=d"(edx) : "c"(xcr));
  126. return (static_cast<uint64_t>(edx) << 32) | eax;
  127. #endif // defined(COMPILER_MSVC)
  128. }
  129. #endif // ARCH_CPU_X86_FAMILY
  130. #if defined(ARCH_CPU_ARM_FAMILY) && \
  131. (BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS))
  132. StringPairs::const_iterator FindFirstProcCpuKey(const StringPairs& pairs,
  133. StringPiece key) {
  134. return ranges::find_if(pairs, [key](const StringPairs::value_type& pair) {
  135. return TrimWhitespaceASCII(pair.first, base::TRIM_ALL) == key;
  136. });
  137. }
  138. // Parses information about the ARM processor. Note that depending on the CPU
  139. // package, processor configuration, and/or kernel version, this may only
  140. // report information about the processor on which this thread is running. This
  141. // can happen on heterogeneous-processor SoCs like Snapdragon 808, which has 4
  142. // Cortex-A53 and 2 Cortex-A57. Unfortunately there is not a universally
  143. // reliable way to examine the CPU part information for all cores.
  144. const ProcCpuInfo& ParseProcCpu() {
  145. static const NoDestructor<ProcCpuInfo> info([]() {
  146. // This function finds the value from /proc/cpuinfo under the key "model
  147. // name" or "Processor". "model name" is used in Linux 3.8 and later (3.7
  148. // and later for arm64) and is shown once per CPU. "Processor" is used in
  149. // earler versions and is shown only once at the top of /proc/cpuinfo
  150. // regardless of the number CPUs.
  151. const char kModelNamePrefix[] = "model name";
  152. const char kProcessorPrefix[] = "Processor";
  153. std::string cpuinfo;
  154. ReadFileToString(FilePath("/proc/cpuinfo"), &cpuinfo);
  155. DCHECK(!cpuinfo.empty());
  156. ProcCpuInfo info;
  157. StringPairs pairs;
  158. if (!SplitStringIntoKeyValuePairs(cpuinfo, ':', '\n', &pairs)) {
  159. NOTREACHED();
  160. return info;
  161. }
  162. auto model_name = FindFirstProcCpuKey(pairs, kModelNamePrefix);
  163. if (model_name == pairs.end())
  164. model_name = FindFirstProcCpuKey(pairs, kProcessorPrefix);
  165. if (model_name != pairs.end()) {
  166. info.brand =
  167. std::string(TrimWhitespaceASCII(model_name->second, TRIM_ALL));
  168. }
  169. auto implementer_string = FindFirstProcCpuKey(pairs, "CPU implementer");
  170. if (implementer_string != pairs.end()) {
  171. // HexStringToUInt() handles the leading whitespace on the value.
  172. uint32_t implementer;
  173. HexStringToUInt(implementer_string->second, &implementer);
  174. if (!CheckedNumeric<uint32_t>(implementer)
  175. .AssignIfValid(&info.implementer)) {
  176. info.implementer = 0;
  177. }
  178. }
  179. auto part_number_string = FindFirstProcCpuKey(pairs, "CPU part");
  180. if (part_number_string != pairs.end())
  181. HexStringToUInt(part_number_string->second, &info.part_number);
  182. return info;
  183. }());
  184. return *info;
  185. }
  186. #endif // defined(ARCH_CPU_ARM_FAMILY) && (BUILDFLAG(IS_ANDROID) ||
  187. // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS))
  188. } // namespace
  189. void CPU::Initialize(bool require_branding) {
  190. #if defined(ARCH_CPU_X86_FAMILY)
  191. int cpu_info[4] = {-1};
  192. // This array is used to temporarily hold the vendor name and then the brand
  193. // name. Thus it has to be big enough for both use cases. There are
  194. // static_asserts below for each of the use cases to make sure this array is
  195. // big enough.
  196. char cpu_string[sizeof(cpu_info) * 3 + 1];
  197. // __cpuid with an InfoType argument of 0 returns the number of
  198. // valid Ids in CPUInfo[0] and the CPU identification string in
  199. // the other three array elements. The CPU identification string is
  200. // not in linear order. The code below arranges the information
  201. // in a human readable form. The human readable order is CPUInfo[1] |
  202. // CPUInfo[3] | CPUInfo[2]. CPUInfo[2] and CPUInfo[3] are swapped
  203. // before using memcpy() to copy these three array elements to |cpu_string|.
  204. __cpuid(cpu_info, 0);
  205. int num_ids = cpu_info[0];
  206. std::swap(cpu_info[2], cpu_info[3]);
  207. static constexpr size_t kVendorNameSize = 3 * sizeof(cpu_info[1]);
  208. static_assert(kVendorNameSize < std::size(cpu_string),
  209. "cpu_string too small");
  210. memcpy(cpu_string, &cpu_info[1], kVendorNameSize);
  211. cpu_string[kVendorNameSize] = '\0';
  212. cpu_vendor_ = cpu_string;
  213. // Interpret CPU feature information.
  214. if (num_ids > 0) {
  215. int cpu_info7[4] = {0};
  216. __cpuid(cpu_info, 1);
  217. if (num_ids >= 7) {
  218. __cpuid(cpu_info7, 7);
  219. }
  220. signature_ = cpu_info[0];
  221. stepping_ = cpu_info[0] & 0xf;
  222. type_ = (cpu_info[0] >> 12) & 0x3;
  223. internal::X86ModelInfo results =
  224. internal::ComputeX86FamilyAndModel(cpu_vendor_, signature_);
  225. family_ = results.family;
  226. model_ = results.model;
  227. ext_family_ = results.ext_family;
  228. ext_model_ = results.ext_model;
  229. has_mmx_ = (cpu_info[3] & 0x00800000) != 0;
  230. has_sse_ = (cpu_info[3] & 0x02000000) != 0;
  231. has_sse2_ = (cpu_info[3] & 0x04000000) != 0;
  232. has_sse3_ = (cpu_info[2] & 0x00000001) != 0;
  233. has_ssse3_ = (cpu_info[2] & 0x00000200) != 0;
  234. has_sse41_ = (cpu_info[2] & 0x00080000) != 0;
  235. has_sse42_ = (cpu_info[2] & 0x00100000) != 0;
  236. has_popcnt_ = (cpu_info[2] & 0x00800000) != 0;
  237. // "Hypervisor Present Bit: Bit 31 of ECX of CPUID leaf 0x1."
  238. // See https://lwn.net/Articles/301888/
  239. // This is checking for any hypervisor. Hypervisors may choose not to
  240. // announce themselves. Hypervisors trap CPUID and sometimes return
  241. // different results to underlying hardware.
  242. is_running_in_vm_ = (static_cast<uint32_t>(cpu_info[2]) & 0x80000000) != 0;
  243. // AVX instructions will generate an illegal instruction exception unless
  244. // a) they are supported by the CPU,
  245. // b) XSAVE is supported by the CPU and
  246. // c) XSAVE is enabled by the kernel.
  247. // See http://software.intel.com/en-us/blogs/2011/04/14/is-avx-enabled
  248. //
  249. // In addition, we have observed some crashes with the xgetbv instruction
  250. // even after following Intel's example code. (See crbug.com/375968.)
  251. // Because of that, we also test the XSAVE bit because its description in
  252. // the CPUID documentation suggests that it signals xgetbv support.
  253. has_avx_ =
  254. (cpu_info[2] & 0x10000000) != 0 &&
  255. (cpu_info[2] & 0x04000000) != 0 /* XSAVE */ &&
  256. (cpu_info[2] & 0x08000000) != 0 /* OSXSAVE */ &&
  257. (xgetbv(0) & 6) == 6 /* XSAVE enabled by kernel */;
  258. has_aesni_ = (cpu_info[2] & 0x02000000) != 0;
  259. has_fma3_ = (cpu_info[2] & 0x00001000) != 0;
  260. has_avx2_ = has_avx_ && (cpu_info7[1] & 0x00000020) != 0;
  261. }
  262. // Get the brand string of the cpu.
  263. __cpuid(cpu_info, static_cast<int>(0x80000000));
  264. const uint32_t max_parameter = static_cast<uint32_t>(cpu_info[0]);
  265. static constexpr uint32_t kParameterStart = 0x80000002;
  266. static constexpr uint32_t kParameterEnd = 0x80000004;
  267. static constexpr uint32_t kParameterSize =
  268. kParameterEnd - kParameterStart + 1;
  269. static_assert(kParameterSize * sizeof(cpu_info) + 1 == std::size(cpu_string),
  270. "cpu_string has wrong size");
  271. if (max_parameter >= kParameterEnd) {
  272. size_t i = 0;
  273. for (uint32_t parameter = kParameterStart; parameter <= kParameterEnd;
  274. ++parameter) {
  275. __cpuid(cpu_info, static_cast<int>(parameter));
  276. memcpy(&cpu_string[i], cpu_info, sizeof(cpu_info));
  277. i += sizeof(cpu_info);
  278. }
  279. cpu_string[i] = '\0';
  280. cpu_brand_ = cpu_string;
  281. }
  282. static constexpr uint32_t kParameterContainingNonStopTimeStampCounter =
  283. 0x80000007;
  284. if (max_parameter >= kParameterContainingNonStopTimeStampCounter) {
  285. __cpuid(cpu_info,
  286. static_cast<int>(kParameterContainingNonStopTimeStampCounter));
  287. has_non_stop_time_stamp_counter_ = (cpu_info[3] & (1 << 8)) != 0;
  288. }
  289. if (!has_non_stop_time_stamp_counter_ && is_running_in_vm_) {
  290. int cpu_info_hv[4] = {};
  291. __cpuid(cpu_info_hv, 0x40000000);
  292. if (cpu_info_hv[1] == 0x7263694D && // Micr
  293. cpu_info_hv[2] == 0x666F736F && // osof
  294. cpu_info_hv[3] == 0x76482074) { // t Hv
  295. // If CPUID says we have a variant TSC and a hypervisor has identified
  296. // itself and the hypervisor says it is Microsoft Hyper-V, then treat
  297. // TSC as invariant.
  298. //
  299. // Microsoft Hyper-V hypervisor reports variant TSC as there are some
  300. // scenarios (eg. VM live migration) where the TSC is variant, but for
  301. // our purposes we can treat it as invariant.
  302. has_non_stop_time_stamp_counter_ = true;
  303. }
  304. }
  305. #elif defined(ARCH_CPU_ARM_FAMILY)
  306. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
  307. if (require_branding) {
  308. const ProcCpuInfo& info = ParseProcCpu();
  309. cpu_brand_ = info.brand;
  310. implementer_ = info.implementer;
  311. part_number_ = info.part_number;
  312. }
  313. #if defined(ARCH_CPU_ARM64)
  314. // Check for Armv8.5-A BTI/MTE support, exposed via HWCAP2
  315. unsigned long hwcap2 = getauxval(AT_HWCAP2);
  316. has_mte_ = hwcap2 & HWCAP2_MTE;
  317. has_bti_ = hwcap2 & HWCAP2_BTI;
  318. #endif
  319. #elif BUILDFLAG(IS_WIN)
  320. // Windows makes high-resolution thread timing information available in
  321. // user-space.
  322. has_non_stop_time_stamp_counter_ = true;
  323. #endif
  324. #endif
  325. }
  326. #if defined(ARCH_CPU_X86_FAMILY)
  327. CPU::IntelMicroArchitecture CPU::GetIntelMicroArchitecture() const {
  328. if (has_avx2()) return AVX2;
  329. if (has_fma3()) return FMA3;
  330. if (has_avx()) return AVX;
  331. if (has_sse42()) return SSE42;
  332. if (has_sse41()) return SSE41;
  333. if (has_ssse3()) return SSSE3;
  334. if (has_sse3()) return SSE3;
  335. if (has_sse2()) return SSE2;
  336. if (has_sse()) return SSE;
  337. return PENTIUM;
  338. }
  339. #endif
  340. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \
  341. BUILDFLAG(IS_AIX)
  342. namespace {
  343. constexpr char kTimeInStatePath[] =
  344. "/sys/devices/system/cpu/cpu%" PRIuS "/cpufreq/stats/time_in_state";
  345. constexpr char kPhysicalPackageIdPath[] =
  346. "/sys/devices/system/cpu/cpu%" PRIuS "/topology/physical_package_id";
  347. constexpr char kCoreIdleStateTimePath[] =
  348. "/sys/devices/system/cpu/cpu%" PRIuS "/cpuidle/state%d/time";
  349. bool SupportsTimeInState() {
  350. // Reading from time_in_state doesn't block (it amounts to reading a struct
  351. // from the cpufreq-stats kernel driver).
  352. ThreadRestrictions::ScopedAllowIO allow_io;
  353. // Check if the time_in_state path for the first core is readable.
  354. FilePath time_in_state_path(
  355. StringPrintf(kTimeInStatePath, /*core_index=*/size_t{0}));
  356. ScopedFILE file_stream(OpenFile(time_in_state_path, "rb"));
  357. return static_cast<bool>(file_stream);
  358. }
  359. bool ParseTimeInState(const std::string& content,
  360. CPU::CoreType core_type,
  361. size_t core_index,
  362. CPU::TimeInState& time_in_state) {
  363. const char* begin = content.data();
  364. size_t max_pos = content.size() - 1;
  365. // Example time_in_state content:
  366. // ---
  367. // 300000 1
  368. // 403200 0
  369. // 499200 15
  370. // ---
  371. // Iterate over the individual lines.
  372. for (size_t pos = 0; pos <= max_pos;) {
  373. int num_chars = 0;
  374. // Each line should have two integer fields, frequency (kHz) and time (in
  375. // jiffies), separated by a space, e.g. "2419200 132".
  376. uint64_t frequency;
  377. int64_t time;
  378. int matches = sscanf(begin + pos, "%" PRIu64 " %" PRId64 "\n%n", &frequency,
  379. &time, &num_chars);
  380. if (matches != 2)
  381. return false;
  382. // Skip zero-valued entries in the output list (no time spent at this
  383. // frequency).
  384. if (time > 0) {
  385. time_in_state.push_back({core_type, core_index, frequency,
  386. internal::ClockTicksToTimeDelta(time)});
  387. }
  388. // Advance line.
  389. DCHECK_GT(num_chars, 0);
  390. pos += static_cast<size_t>(num_chars);
  391. }
  392. return true;
  393. }
  394. bool SupportsCoreIdleTimes() {
  395. // Reading from the cpuidle driver doesn't block.
  396. ThreadRestrictions::ScopedAllowIO allow_io;
  397. // Check if the path for the idle time in state 0 for core 0 is readable.
  398. FilePath idle_state0_path(StringPrintf(
  399. kCoreIdleStateTimePath, /*core_index=*/size_t{0}, /*idle_state=*/0));
  400. ScopedFILE file_stream(OpenFile(idle_state0_path, "rb"));
  401. return static_cast<bool>(file_stream);
  402. }
  403. std::vector<CPU::CoreType> GuessCoreTypes() {
  404. // Try to guess the CPU architecture and cores of each cluster by comparing
  405. // the maximum frequencies of the available (online and offline) cores.
  406. const char kCPUMaxFreqPath[] =
  407. "/sys/devices/system/cpu/cpu%" PRIuS "/cpufreq/cpuinfo_max_freq";
  408. size_t num_cpus = static_cast<size_t>(SysInfo::NumberOfProcessors());
  409. std::vector<CPU::CoreType> core_index_to_type(num_cpus,
  410. CPU::CoreType::kUnknown);
  411. std::vector<uint32_t> max_core_frequencies_mhz(num_cpus, 0);
  412. flat_set<uint32_t> frequencies_mhz;
  413. {
  414. // Reading from cpuinfo_max_freq doesn't block (it amounts to reading a
  415. // struct field from the cpufreq kernel driver).
  416. ThreadRestrictions::ScopedAllowIO allow_io;
  417. for (size_t core_index = 0; core_index < num_cpus; ++core_index) {
  418. std::string content;
  419. uint32_t frequency_khz = 0;
  420. auto path = StringPrintf(kCPUMaxFreqPath, core_index);
  421. if (ReadFileToString(FilePath(path), &content))
  422. StringToUint(content, &frequency_khz);
  423. uint32_t frequency_mhz = frequency_khz / 1000;
  424. max_core_frequencies_mhz[core_index] = frequency_mhz;
  425. if (frequency_mhz > 0)
  426. frequencies_mhz.insert(frequency_mhz);
  427. }
  428. }
  429. size_t num_frequencies = frequencies_mhz.size();
  430. for (size_t core_index = 0; core_index < num_cpus; ++core_index) {
  431. uint32_t core_frequency_mhz = max_core_frequencies_mhz[core_index];
  432. CPU::CoreType core_type = CPU::CoreType::kOther;
  433. if (num_frequencies == 1u) {
  434. core_type = CPU::CoreType::kSymmetric;
  435. } else if (num_frequencies == 2u || num_frequencies == 3u) {
  436. auto it = frequencies_mhz.find(core_frequency_mhz);
  437. if (it != frequencies_mhz.end()) {
  438. // flat_set is sorted.
  439. ptrdiff_t frequency_index = it - frequencies_mhz.begin();
  440. switch (frequency_index) {
  441. case 0:
  442. core_type = num_frequencies == 2u
  443. ? CPU::CoreType::kBigLittle_Little
  444. : CPU::CoreType::kBigLittleBigger_Little;
  445. break;
  446. case 1:
  447. core_type = num_frequencies == 2u
  448. ? CPU::CoreType::kBigLittle_Big
  449. : CPU::CoreType::kBigLittleBigger_Big;
  450. break;
  451. case 2:
  452. DCHECK_EQ(num_frequencies, 3u);
  453. core_type = CPU::CoreType::kBigLittleBigger_Bigger;
  454. break;
  455. default:
  456. NOTREACHED();
  457. break;
  458. }
  459. }
  460. }
  461. core_index_to_type[core_index] = core_type;
  462. }
  463. return core_index_to_type;
  464. }
  465. } // namespace
  466. // static
  467. const std::vector<CPU::CoreType>& CPU::GetGuessedCoreTypes() {
  468. static NoDestructor<std::vector<CoreType>> kCoreTypes(GuessCoreTypes());
  469. return *kCoreTypes.get();
  470. }
  471. // static
  472. bool CPU::GetTimeInState(TimeInState& time_in_state) {
  473. time_in_state.clear();
  474. // The kernel may not support the cpufreq-stats driver.
  475. static const bool kSupportsTimeInState = SupportsTimeInState();
  476. if (!kSupportsTimeInState)
  477. return false;
  478. static const std::vector<CoreType>& kCoreTypes = GetGuessedCoreTypes();
  479. // time_in_state is reported per cluster. Identify the first cores of each
  480. // cluster.
  481. static NoDestructor<std::vector<size_t>> kFirstCoresIndexes([]() {
  482. std::vector<size_t> first_cores;
  483. int last_core_package_id = 0;
  484. for (size_t core_index = 0;
  485. core_index < static_cast<size_t>(SysInfo::NumberOfProcessors());
  486. core_index++) {
  487. // Reading from physical_package_id doesn't block (it amounts to reading a
  488. // struct field from the kernel).
  489. ThreadRestrictions::ScopedAllowIO allow_io;
  490. FilePath package_id_path(
  491. StringPrintf(kPhysicalPackageIdPath, core_index));
  492. std::string package_id_str;
  493. if (!ReadFileToString(package_id_path, &package_id_str))
  494. return std::vector<size_t>();
  495. int package_id;
  496. base::StringPiece trimmed = base::TrimWhitespaceASCII(
  497. package_id_str, base::TrimPositions::TRIM_ALL);
  498. if (!base::StringToInt(trimmed, &package_id))
  499. return std::vector<size_t>();
  500. if (last_core_package_id != package_id || core_index == 0)
  501. first_cores.push_back(core_index);
  502. last_core_package_id = package_id;
  503. }
  504. return first_cores;
  505. }());
  506. if (kFirstCoresIndexes->empty())
  507. return false;
  508. // Reading from time_in_state doesn't block (it amounts to reading a struct
  509. // from the cpufreq-stats kernel driver).
  510. ThreadRestrictions::ScopedAllowIO allow_io;
  511. // Read the time_in_state for each cluster from the /sys directory of the
  512. // cluster's first core.
  513. for (size_t cluster_core_index : *kFirstCoresIndexes) {
  514. FilePath time_in_state_path(
  515. StringPrintf(kTimeInStatePath, cluster_core_index));
  516. std::string buffer;
  517. if (!ReadFileToString(time_in_state_path, &buffer))
  518. return false;
  519. if (!ParseTimeInState(buffer, kCoreTypes[cluster_core_index],
  520. cluster_core_index, time_in_state)) {
  521. return false;
  522. }
  523. }
  524. return true;
  525. }
  526. // static
  527. bool CPU::GetCumulativeCoreIdleTimes(CoreIdleTimes& idle_times) {
  528. idle_times.clear();
  529. // The kernel may not support the cpufreq-stats driver.
  530. static const bool kSupportsIdleTimes = SupportsCoreIdleTimes();
  531. if (!kSupportsIdleTimes)
  532. return false;
  533. // Reading from the cpuidle driver doesn't block.
  534. ThreadRestrictions::ScopedAllowIO allow_io;
  535. size_t num_cpus = static_cast<size_t>(SysInfo::NumberOfProcessors());
  536. bool success = false;
  537. for (size_t core_index = 0; core_index < num_cpus; ++core_index) {
  538. std::string content;
  539. TimeDelta idle_time;
  540. // The number of idle states is system/CPU dependent, so we increment and
  541. // try to read each state until we fail.
  542. for (int state_index = 0;; ++state_index) {
  543. auto path = StringPrintf(kCoreIdleStateTimePath, core_index, state_index);
  544. uint64_t idle_state_time = 0;
  545. if (!ReadFileToString(FilePath(path), &content))
  546. break;
  547. StringToUint64(content, &idle_state_time);
  548. idle_time += Microseconds(idle_state_time);
  549. }
  550. idle_times.push_back(idle_time);
  551. // At least one of the cores should have some idle time, otherwise we report
  552. // a failure.
  553. success |= idle_time.is_positive();
  554. }
  555. return success;
  556. }
  557. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
  558. // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_AIX)
  559. const CPU& CPU::GetInstanceNoAllocation() {
  560. static const base::NoDestructor<const CPU> cpu(CPU(false));
  561. return *cpu;
  562. }
  563. } // namespace base