host_processor_info_scanner.cc 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2022 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 "services/device/compute_pressure/host_processor_info_scanner.h"
  5. #include <mach/mach.h>
  6. #include <mach/mach_host.h>
  7. #include <stdint.h>
  8. #include "base/mac/mac_util.h"
  9. #include "base/mac/scoped_mach_port.h"
  10. #include "base/mac/scoped_mach_vm.h"
  11. #include "base/system/sys_info.h"
  12. #include "services/device/compute_pressure/core_times.h"
  13. namespace device {
  14. HostProcessorInfoScanner::HostProcessorInfoScanner() {
  15. core_times_.reserve(base::SysInfo::NumberOfProcessors());
  16. DETACH_FROM_SEQUENCE(sequence_checker_);
  17. }
  18. HostProcessorInfoScanner::~HostProcessorInfoScanner() {
  19. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  20. }
  21. bool HostProcessorInfoScanner::Update() {
  22. DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  23. if (base::mac::GetCPUType() == base::mac::CPUType::kTranslatedIntel) {
  24. // ARM-based macs are not supported because Rosetta's simulation is not
  25. // complete. We will skip obtaining CPU usage information. See
  26. // https://crbug.com/1138707#c42 for details.
  27. return false;
  28. }
  29. natural_t number_of_processors;
  30. base::mac::ScopedMachSendRight host(mach_host_self());
  31. mach_msg_type_number_t type;
  32. processor_cpu_load_info_data_t* cpu_infos;
  33. if (host_processor_info(host.get(), PROCESSOR_CPU_LOAD_INFO,
  34. &number_of_processors,
  35. reinterpret_cast<processor_info_array_t*>(&cpu_infos),
  36. &type) != KERN_SUCCESS) {
  37. return false;
  38. }
  39. base::mac::ScopedMachVM vm_owner(
  40. reinterpret_cast<vm_address_t>(cpu_infos),
  41. mach_vm_round_page(number_of_processors *
  42. sizeof(processor_cpu_load_info)));
  43. for (natural_t i = 0; i < number_of_processors; ++i) {
  44. DCHECK_GE(core_times_.size(), i);
  45. if (core_times_.size() <= i) {
  46. core_times_.resize(i + 1);
  47. CoreTimes core_time;
  48. core_times_[i] = std::move(core_time);
  49. }
  50. core_times_[i].set_user(cpu_infos[i].cpu_ticks[CPU_STATE_USER]);
  51. core_times_[i].set_nice(cpu_infos[i].cpu_ticks[CPU_STATE_NICE]);
  52. core_times_[i].set_system(cpu_infos[i].cpu_ticks[CPU_STATE_SYSTEM]);
  53. core_times_[i].set_idle(cpu_infos[i].cpu_ticks[CPU_STATE_IDLE]);
  54. }
  55. return true;
  56. }
  57. } // namespace device