process_metrics_mac.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. // Copyright (c) 2013 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/process/process_metrics.h"
  5. #include <libproc.h>
  6. #include <mach/mach.h>
  7. #include <mach/mach_time.h>
  8. #include <mach/mach_vm.h>
  9. #include <mach/shared_region.h>
  10. #include <stddef.h>
  11. #include <stdint.h>
  12. #include <sys/sysctl.h>
  13. #include "base/logging.h"
  14. #include "base/mac/mac_util.h"
  15. #include "base/mac/mach_logging.h"
  16. #include "base/mac/scoped_mach_port.h"
  17. #include "base/memory/ptr_util.h"
  18. #include "base/numerics/safe_conversions.h"
  19. #include "base/numerics/safe_math.h"
  20. #include "base/process/process_metrics_iocounters.h"
  21. #include "base/time/time.h"
  22. #include "build/build_config.h"
  23. namespace {
  24. // This is a standin for the private pm_task_energy_data_t struct.
  25. struct OpaquePMTaskEnergyData {
  26. // Empirical size of the private struct.
  27. uint8_t data[408];
  28. };
  29. // Sample everything but network usage, since fetching network
  30. // usage can hang.
  31. static constexpr uint8_t kPMSampleFlags = 0xff & ~0x8;
  32. } // namespace
  33. extern "C" {
  34. // From libpmsample.dylib
  35. int pm_sample_task(mach_port_t task,
  36. OpaquePMTaskEnergyData* pm_energy,
  37. uint64_t mach_time,
  38. uint8_t flags);
  39. // From libpmenergy.dylib
  40. double pm_energy_impact(OpaquePMTaskEnergyData* pm_energy);
  41. } // extern "C"
  42. namespace base {
  43. namespace {
  44. bool GetTaskInfo(mach_port_t task, task_basic_info_64* task_info_data) {
  45. if (task == MACH_PORT_NULL)
  46. return false;
  47. mach_msg_type_number_t count = TASK_BASIC_INFO_64_COUNT;
  48. kern_return_t kr = task_info(task,
  49. TASK_BASIC_INFO_64,
  50. reinterpret_cast<task_info_t>(task_info_data),
  51. &count);
  52. // Most likely cause for failure: |task| is a zombie.
  53. return kr == KERN_SUCCESS;
  54. }
  55. MachVMRegionResult ParseOutputFromMachVMRegion(kern_return_t kr) {
  56. if (kr == KERN_INVALID_ADDRESS) {
  57. // We're at the end of the address space.
  58. return MachVMRegionResult::Finished;
  59. } else if (kr != KERN_SUCCESS) {
  60. return MachVMRegionResult::Error;
  61. }
  62. return MachVMRegionResult::Success;
  63. }
  64. bool GetPowerInfo(mach_port_t task, task_power_info* power_info_data) {
  65. if (task == MACH_PORT_NULL)
  66. return false;
  67. mach_msg_type_number_t power_info_count = TASK_POWER_INFO_COUNT;
  68. kern_return_t kr = task_info(task, TASK_POWER_INFO,
  69. reinterpret_cast<task_info_t>(power_info_data),
  70. &power_info_count);
  71. // Most likely cause for failure: |task| is a zombie.
  72. return kr == KERN_SUCCESS;
  73. }
  74. double GetEnergyImpactInternal(mach_port_t task, uint64_t mach_time) {
  75. OpaquePMTaskEnergyData energy_info{};
  76. if (pm_sample_task(task, &energy_info, mach_time, kPMSampleFlags) != 0)
  77. return 0.0;
  78. return pm_energy_impact(&energy_info);
  79. }
  80. } // namespace
  81. // Getting a mach task from a pid for another process requires permissions in
  82. // general, so there doesn't really seem to be a way to do these (and spinning
  83. // up ps to fetch each stats seems dangerous to put in a base api for anyone to
  84. // call). Child processes ipc their port, so return something if available,
  85. // otherwise return 0.
  86. // static
  87. std::unique_ptr<ProcessMetrics> ProcessMetrics::CreateProcessMetrics(
  88. ProcessHandle process,
  89. PortProvider* port_provider) {
  90. return WrapUnique(new ProcessMetrics(process, port_provider));
  91. }
  92. #define TIME_VALUE_TO_TIMEVAL(a, r) do { \
  93. (r)->tv_sec = (a)->seconds; \
  94. (r)->tv_usec = (a)->microseconds; \
  95. } while (0)
  96. TimeDelta ProcessMetrics::GetCumulativeCPUUsage() {
  97. mach_port_t task = TaskForPid(process_);
  98. if (task == MACH_PORT_NULL)
  99. return TimeDelta();
  100. // Libtop explicitly loops over the threads (libtop_pinfo_update_cpu_usage()
  101. // in libtop.c), but this is more concise and gives the same results:
  102. task_thread_times_info thread_info_data;
  103. mach_msg_type_number_t thread_info_count = TASK_THREAD_TIMES_INFO_COUNT;
  104. kern_return_t kr = task_info(task,
  105. TASK_THREAD_TIMES_INFO,
  106. reinterpret_cast<task_info_t>(&thread_info_data),
  107. &thread_info_count);
  108. if (kr != KERN_SUCCESS) {
  109. // Most likely cause: |task| is a zombie.
  110. return TimeDelta();
  111. }
  112. task_basic_info_64 task_info_data;
  113. if (!GetTaskInfo(task, &task_info_data))
  114. return TimeDelta();
  115. /* Set total_time. */
  116. // thread info contains live time...
  117. struct timeval user_timeval, system_timeval, task_timeval;
  118. TIME_VALUE_TO_TIMEVAL(&thread_info_data.user_time, &user_timeval);
  119. TIME_VALUE_TO_TIMEVAL(&thread_info_data.system_time, &system_timeval);
  120. timeradd(&user_timeval, &system_timeval, &task_timeval);
  121. // ... task info contains terminated time.
  122. TIME_VALUE_TO_TIMEVAL(&task_info_data.user_time, &user_timeval);
  123. TIME_VALUE_TO_TIMEVAL(&task_info_data.system_time, &system_timeval);
  124. timeradd(&user_timeval, &task_timeval, &task_timeval);
  125. timeradd(&system_timeval, &task_timeval, &task_timeval);
  126. return Microseconds(TimeValToMicroseconds(task_timeval));
  127. }
  128. int ProcessMetrics::GetPackageIdleWakeupsPerSecond() {
  129. mach_port_t task = TaskForPid(process_);
  130. task_power_info power_info_data;
  131. GetPowerInfo(task, &power_info_data);
  132. // The task_power_info struct contains two wakeup counters:
  133. // task_interrupt_wakeups and task_platform_idle_wakeups.
  134. // task_interrupt_wakeups is the total number of wakeups generated by the
  135. // process, and is the number that Activity Monitor reports.
  136. // task_platform_idle_wakeups is a subset of task_interrupt_wakeups that
  137. // tallies the number of times the processor was taken out of its low-power
  138. // idle state to handle a wakeup. task_platform_idle_wakeups therefore result
  139. // in a greater power increase than the other interrupts which occur while the
  140. // CPU is already working, and reducing them has a greater overall impact on
  141. // power usage. See the powermetrics man page for more info.
  142. return CalculatePackageIdleWakeupsPerSecond(
  143. power_info_data.task_platform_idle_wakeups);
  144. }
  145. int ProcessMetrics::GetIdleWakeupsPerSecond() {
  146. mach_port_t task = TaskForPid(process_);
  147. task_power_info power_info_data;
  148. GetPowerInfo(task, &power_info_data);
  149. return CalculateIdleWakeupsPerSecond(power_info_data.task_interrupt_wakeups);
  150. }
  151. int ProcessMetrics::GetEnergyImpact() {
  152. uint64_t now = mach_absolute_time();
  153. if (last_energy_impact_ == 0) {
  154. last_energy_impact_ = GetEnergyImpactInternal(TaskForPid(process_), now);
  155. last_energy_impact_time_ = now;
  156. return 0;
  157. }
  158. double total_energy_impact =
  159. GetEnergyImpactInternal(TaskForPid(process_), now);
  160. uint64_t delta = now - last_energy_impact_time_;
  161. if (delta == 0)
  162. return 0;
  163. // Scale by 100 since the histogram is integral.
  164. double seconds_since_last_measurement =
  165. base::TimeTicks::FromMachAbsoluteTime(delta).since_origin().InSecondsF();
  166. int energy_impact = 100 * (total_energy_impact - last_energy_impact_) /
  167. seconds_since_last_measurement;
  168. last_energy_impact_ = total_energy_impact;
  169. last_energy_impact_time_ = now;
  170. return energy_impact;
  171. }
  172. int ProcessMetrics::GetOpenFdCount() const {
  173. // In order to get a true count of the open number of FDs, PROC_PIDLISTFDS
  174. // is used. This is done twice: first to get the appropriate size of a
  175. // buffer, and then secondly to fill the buffer with the actual FD info.
  176. //
  177. // The buffer size returned in the first call is an estimate, based on the
  178. // number of allocated fileproc structures in the kernel. This number can be
  179. // greater than the actual number of open files, since the structures are
  180. // allocated in slabs. The value returned in proc_bsdinfo::pbi_nfiles is
  181. // also the number of allocated fileprocs, not the number in use.
  182. //
  183. // However, the buffer size returned in the second call is an accurate count
  184. // of the open number of descriptors. The contents of the buffer are unused.
  185. int rv = proc_pidinfo(process_, PROC_PIDLISTFDS, 0, nullptr, 0);
  186. if (rv < 0)
  187. return -1;
  188. std::unique_ptr<char[]> buffer(new char[static_cast<size_t>(rv)]);
  189. rv = proc_pidinfo(process_, PROC_PIDLISTFDS, 0, buffer.get(), rv);
  190. if (rv < 0)
  191. return -1;
  192. return static_cast<int>(static_cast<unsigned long>(rv) / PROC_PIDLISTFD_SIZE);
  193. }
  194. int ProcessMetrics::GetOpenFdSoftLimit() const {
  195. return checked_cast<int>(GetMaxFds());
  196. }
  197. bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
  198. return false;
  199. }
  200. ProcessMetrics::ProcessMetrics(ProcessHandle process,
  201. PortProvider* port_provider)
  202. : process_(process),
  203. last_absolute_idle_wakeups_(0),
  204. last_absolute_package_idle_wakeups_(0),
  205. last_energy_impact_(0),
  206. port_provider_(port_provider) {}
  207. mach_port_t ProcessMetrics::TaskForPid(ProcessHandle process) const {
  208. mach_port_t task = MACH_PORT_NULL;
  209. if (port_provider_)
  210. task = port_provider_->TaskForPid(process_);
  211. if (task == MACH_PORT_NULL && process_ == getpid())
  212. task = mach_task_self();
  213. return task;
  214. }
  215. // Bytes committed by the system.
  216. size_t GetSystemCommitCharge() {
  217. base::mac::ScopedMachSendRight host(mach_host_self());
  218. mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
  219. vm_statistics_data_t data;
  220. kern_return_t kr = host_statistics(host.get(), HOST_VM_INFO,
  221. reinterpret_cast<host_info_t>(&data),
  222. &count);
  223. if (kr != KERN_SUCCESS) {
  224. MACH_DLOG(WARNING, kr) << "host_statistics";
  225. return 0;
  226. }
  227. return (data.active_count * PAGE_SIZE) / 1024;
  228. }
  229. bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
  230. struct host_basic_info hostinfo;
  231. mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
  232. base::mac::ScopedMachSendRight host(mach_host_self());
  233. int result = host_info(host.get(), HOST_BASIC_INFO,
  234. reinterpret_cast<host_info_t>(&hostinfo), &count);
  235. if (result != KERN_SUCCESS)
  236. return false;
  237. DCHECK_EQ(HOST_BASIC_INFO_COUNT, count);
  238. meminfo->total = static_cast<int>(hostinfo.max_mem / 1024);
  239. vm_statistics64_data_t vm_info;
  240. count = HOST_VM_INFO64_COUNT;
  241. if (host_statistics64(host.get(), HOST_VM_INFO64,
  242. reinterpret_cast<host_info64_t>(&vm_info),
  243. &count) != KERN_SUCCESS) {
  244. return false;
  245. }
  246. DCHECK_EQ(HOST_VM_INFO64_COUNT, count);
  247. #if defined(ARCH_CPU_ARM64)
  248. // PAGE_SIZE is vm_page_size on arm, which isn't constexpr.
  249. DCHECK_EQ(PAGE_SIZE % 1024, 0u) << "Invalid page size";
  250. #else
  251. static_assert(PAGE_SIZE % 1024 == 0, "Invalid page size");
  252. #endif
  253. meminfo->free = saturated_cast<int>(
  254. PAGE_SIZE / 1024 * (vm_info.free_count - vm_info.speculative_count));
  255. meminfo->speculative =
  256. saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.speculative_count);
  257. meminfo->file_backed =
  258. saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.external_page_count);
  259. meminfo->purgeable =
  260. saturated_cast<int>(PAGE_SIZE / 1024 * vm_info.purgeable_count);
  261. return true;
  262. }
  263. // Both |size| and |address| are in-out parameters.
  264. // |info| is an output parameter, only valid on Success.
  265. MachVMRegionResult GetTopInfo(mach_port_t task,
  266. mach_vm_size_t* size,
  267. mach_vm_address_t* address,
  268. vm_region_top_info_data_t* info) {
  269. mach_msg_type_number_t info_count = VM_REGION_TOP_INFO_COUNT;
  270. // The kernel always returns a null object for VM_REGION_TOP_INFO, but
  271. // balance it with a deallocate in case this ever changes. See 10.9.2
  272. // xnu-2422.90.20/osfmk/vm/vm_map.c vm_map_region.
  273. mac::ScopedMachSendRight object_name;
  274. kern_return_t kr =
  275. mach_vm_region(task, address, size, VM_REGION_TOP_INFO,
  276. reinterpret_cast<vm_region_info_t>(info), &info_count,
  277. mac::ScopedMachSendRight::Receiver(object_name).get());
  278. return ParseOutputFromMachVMRegion(kr);
  279. }
  280. MachVMRegionResult GetBasicInfo(mach_port_t task,
  281. mach_vm_size_t* size,
  282. mach_vm_address_t* address,
  283. vm_region_basic_info_64* info) {
  284. mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT_64;
  285. // The kernel always returns a null object for VM_REGION_BASIC_INFO_64, but
  286. // balance it with a deallocate in case this ever changes. See 10.9.2
  287. // xnu-2422.90.20/osfmk/vm/vm_map.c vm_map_region.
  288. mac::ScopedMachSendRight object_name;
  289. kern_return_t kr =
  290. mach_vm_region(task, address, size, VM_REGION_BASIC_INFO_64,
  291. reinterpret_cast<vm_region_info_t>(info), &info_count,
  292. mac::ScopedMachSendRight::Receiver(object_name).get());
  293. return ParseOutputFromMachVMRegion(kr);
  294. }
  295. } // namespace base