process_metrics.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  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. // This file contains routines for gathering resource statistics for processes
  5. // running on the system.
  6. #ifndef BASE_PROCESS_PROCESS_METRICS_H_
  7. #define BASE_PROCESS_PROCESS_METRICS_H_
  8. #include <stddef.h>
  9. #include <stdint.h>
  10. #include <memory>
  11. #include "base/base_export.h"
  12. #include "base/gtest_prod_util.h"
  13. #include "base/memory/raw_ptr.h"
  14. #include "base/process/process_handle.h"
  15. #include "base/strings/string_piece.h"
  16. #include "base/time/time.h"
  17. #include "build/build_config.h"
  18. #if BUILDFLAG(IS_APPLE)
  19. #include <mach/mach.h>
  20. #include "base/process/port_provider_mac.h"
  21. #if !BUILDFLAG(IS_IOS)
  22. #include <mach/mach_vm.h>
  23. #endif
  24. #endif
  25. #if BUILDFLAG(IS_WIN)
  26. #include "base/win/scoped_handle.h"
  27. #include "base/win/windows_types.h"
  28. #endif
  29. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \
  30. BUILDFLAG(IS_AIX)
  31. #include <string>
  32. #include <utility>
  33. #include <vector>
  34. #include "base/cpu.h"
  35. #include "base/threading/platform_thread.h"
  36. #endif
  37. namespace base {
  38. class Value;
  39. // Full declaration is in process_metrics_iocounters.h.
  40. struct IoCounters;
  41. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  42. // Minor and major page fault counts since the process creation.
  43. // Both counts are process-wide, and exclude child processes.
  44. //
  45. // minor: Number of page faults that didn't require disk IO.
  46. // major: Number of page faults that required disk IO.
  47. struct PageFaultCounts {
  48. int64_t minor;
  49. int64_t major;
  50. };
  51. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
  52. // BUILDFLAG(IS_ANDROID)
  53. // Convert a POSIX timeval to microseconds.
  54. BASE_EXPORT int64_t TimeValToMicroseconds(const struct timeval& tv);
  55. // Provides performance metrics for a specified process (CPU usage and IO
  56. // counters). Use CreateCurrentProcessMetrics() to get an instance for the
  57. // current process, or CreateProcessMetrics() to get an instance for an
  58. // arbitrary process. Then, access the information with the different get
  59. // methods.
  60. //
  61. // This class exposes a few platform-specific APIs for parsing memory usage, but
  62. // these are not intended to generalize to other platforms, since the memory
  63. // models differ substantially.
  64. //
  65. // To obtain consistent memory metrics, use the memory_instrumentation service.
  66. //
  67. // For further documentation on memory, see
  68. // https://chromium.googlesource.com/chromium/src/+/HEAD/docs/README.md#Memory
  69. class BASE_EXPORT ProcessMetrics {
  70. public:
  71. ProcessMetrics(const ProcessMetrics&) = delete;
  72. ProcessMetrics& operator=(const ProcessMetrics&) = delete;
  73. ~ProcessMetrics();
  74. // Creates a ProcessMetrics for the specified process.
  75. #if !BUILDFLAG(IS_MAC)
  76. static std::unique_ptr<ProcessMetrics> CreateProcessMetrics(
  77. ProcessHandle process);
  78. #else
  79. // The port provider needs to outlive the ProcessMetrics object returned by
  80. // this function. If NULL is passed as provider, the returned object
  81. // only returns valid metrics if |process| is the current process.
  82. static std::unique_ptr<ProcessMetrics> CreateProcessMetrics(
  83. ProcessHandle process,
  84. PortProvider* port_provider);
  85. #endif // !BUILDFLAG(IS_MAC)
  86. // Creates a ProcessMetrics for the current process. This a cross-platform
  87. // convenience wrapper for CreateProcessMetrics().
  88. static std::unique_ptr<ProcessMetrics> CreateCurrentProcessMetrics();
  89. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  90. // Resident Set Size is a Linux/Android specific memory concept. Do not
  91. // attempt to extend this to other platforms.
  92. BASE_EXPORT size_t GetResidentSetSize() const;
  93. #endif
  94. // Returns the percentage of time spent executing, across all threads of the
  95. // process, in the interval since the last time the method was called. Since
  96. // this considers the total execution time across all threads in a process,
  97. // the result can easily exceed 100% in multi-thread processes running on
  98. // multi-core systems. In general the result is therefore a value in the
  99. // range 0% to SysInfo::NumberOfProcessors() * 100%.
  100. //
  101. // To obtain the percentage of total available CPU resources consumed by this
  102. // process over the interval, the caller must divide by NumberOfProcessors().
  103. //
  104. // Since this API measures usage over an interval, it will return zero on the
  105. // first call, and an actual value only on the second and subsequent calls.
  106. [[nodiscard]] double GetPlatformIndependentCPUUsage();
  107. // Returns the cumulative CPU usage across all threads of the process since
  108. // process start. In case of multi-core processors, a process can consume CPU
  109. // at a rate higher than wall-clock time, e.g. two cores at full utilization
  110. // will result in a time delta of 2 seconds/per 1 wall-clock second.
  111. [[nodiscard]] TimeDelta GetCumulativeCPUUsage();
  112. #if BUILDFLAG(IS_WIN)
  113. // TODO(pmonette): Remove the precise version of the CPU usage functions once
  114. // we're validated that they are indeed better than the regular version above
  115. // and that they can replace the old implementation.
  116. // Returns the percentage of time spent executing, across all threads of the
  117. // process, in the interval since the last time the method was called.
  118. //
  119. // Same as GetPlatformIndependentCPUUSage() but implemented using
  120. // `QueryProcessCycleTime` for higher precision.
  121. [[nodiscard]] double GetPreciseCPUUsage();
  122. // Returns the cumulative CPU usage across all threads of the process since
  123. // process start. In case of multi-core processors, a process can consume CPU
  124. // at a rate higher than wall-clock time, e.g. two cores at full utilization
  125. // will result in a time delta of 2 seconds/per 1 wall-clock second.
  126. //
  127. // This is implemented using `QueryProcessCycleTime` for higher precision.
  128. [[nodiscard]] TimeDelta GetPreciseCumulativeCPUUsage();
  129. #endif // BUILDFLAG(IS_WIN)
  130. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \
  131. BUILDFLAG(IS_AIX)
  132. // Emits the cumulative CPU usage for all currently active threads since they
  133. // were started into the output parameter (replacing its current contents).
  134. // Threads that have already terminated will not be reported. Thus, the sum of
  135. // these times may not equal the value returned by GetCumulativeCPUUsage().
  136. // Returns false on failure. We return the usage via an output parameter to
  137. // allow reuse of CPUUsagePerThread's std::vector by the caller, e.g. to avoid
  138. // allocations between repeated calls to this method.
  139. // NOTE: Currently only supported on Linux/Android.
  140. using CPUUsagePerThread = std::vector<std::pair<PlatformThreadId, TimeDelta>>;
  141. bool GetCumulativeCPUUsagePerThread(CPUUsagePerThread&);
  142. // Similar to GetCumulativeCPUUsagePerThread, but also splits the cumulative
  143. // CPU usage by CPU cluster frequency states. One entry in the output
  144. // parameter is added for each thread + cluster core index + frequency state
  145. // combination with a non-zero CPU time value.
  146. // NOTE: Currently only supported on Linux/Android, and only on devices that
  147. // expose per-pid/tid time_in_state files in /proc.
  148. struct ThreadTimeInState {
  149. PlatformThreadId thread_id;
  150. CPU::CoreType core_type; // type of the cores in this cluster.
  151. uint32_t cluster_core_index; // index of the first core in the cluster.
  152. uint64_t core_frequency_khz;
  153. TimeDelta cumulative_cpu_time;
  154. };
  155. using TimeInStatePerThread = std::vector<ThreadTimeInState>;
  156. bool GetPerThreadCumulativeCPUTimeInState(TimeInStatePerThread&);
  157. // Parse the data found in /proc/<pid>/task/<tid>/time_in_state into
  158. // TimeInStatePerThread (adding to existing entries). Returns false on error.
  159. // Exposed for testing.
  160. bool ParseProcTimeInState(const std::string& content,
  161. PlatformThreadId tid,
  162. TimeInStatePerThread& time_in_state_per_thread);
  163. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
  164. // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_AIX)
  165. // Returns the number of average idle cpu wakeups per second since the last
  166. // call.
  167. int GetIdleWakeupsPerSecond();
  168. #if BUILDFLAG(IS_APPLE)
  169. // Returns the number of average "package idle exits" per second, which have
  170. // a higher energy impact than a regular wakeup, since the last call.
  171. //
  172. // From the powermetrics man page:
  173. // "With the exception of some Mac Pro systems, Mac and
  174. // iOS systems are typically single package systems, wherein all CPUs are
  175. // part of a single processor complex (typically a single IC die) with shared
  176. // logic that can include (depending on system specifics) shared last level
  177. // caches, an integrated memory controller etc. When all CPUs in the package
  178. // are idle, the hardware can power-gate significant portions of the shared
  179. // logic in addition to each individual processor's logic, as well as take
  180. // measures such as placing DRAM in to self-refresh (also referred to as
  181. // auto-refresh), place interconnects into lower-power states etc"
  182. int GetPackageIdleWakeupsPerSecond();
  183. // Returns "Energy Impact", a synthetic power estimation metric displayed by
  184. // macOS in Activity Monitor and the battery menu.
  185. int GetEnergyImpact();
  186. #endif
  187. // Retrieves accounting information for all I/O operations performed by the
  188. // process.
  189. // If IO information is retrieved successfully, the function returns true
  190. // and fills in the IO_COUNTERS passed in. The function returns false
  191. // otherwise.
  192. bool GetIOCounters(IoCounters* io_counters) const;
  193. // Returns the cumulative disk usage in bytes across all threads of the
  194. // process since process start.
  195. uint64_t GetCumulativeDiskUsageInBytes();
  196. #if BUILDFLAG(IS_POSIX)
  197. // Returns the number of file descriptors currently open by the process, or
  198. // -1 on error.
  199. int GetOpenFdCount() const;
  200. // Returns the soft limit of file descriptors that can be opened by the
  201. // process, or -1 on error.
  202. int GetOpenFdSoftLimit() const;
  203. #endif // BUILDFLAG(IS_POSIX)
  204. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  205. // Bytes of swap as reported by /proc/[pid]/status.
  206. uint64_t GetVmSwapBytes() const;
  207. // Minor and major page fault count as reported by /proc/[pid]/stat.
  208. // Returns true for success.
  209. bool GetPageFaultCounts(PageFaultCounts* counts) const;
  210. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
  211. // BUILDFLAG(IS_ANDROID)
  212. // Returns total memory usage of malloc.
  213. size_t GetMallocUsage();
  214. private:
  215. #if !BUILDFLAG(IS_MAC)
  216. explicit ProcessMetrics(ProcessHandle process);
  217. #else
  218. ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
  219. #endif // !BUILDFLAG(IS_MAC)
  220. #if BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \
  221. BUILDFLAG(IS_AIX)
  222. int CalculateIdleWakeupsPerSecond(uint64_t absolute_idle_wakeups);
  223. #endif
  224. #if BUILDFLAG(IS_APPLE)
  225. // The subset of wakeups that cause a "package exit" can be tracked on macOS.
  226. // See |GetPackageIdleWakeupsForSecond| comment for more info.
  227. int CalculatePackageIdleWakeupsPerSecond(
  228. uint64_t absolute_package_idle_wakeups);
  229. #endif
  230. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \
  231. BUILDFLAG(IS_AIX)
  232. CPU::CoreType GetCoreType(uint32_t core_index);
  233. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
  234. // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_AIX)
  235. #if BUILDFLAG(IS_WIN)
  236. win::ScopedHandle process_;
  237. #else
  238. ProcessHandle process_;
  239. #endif
  240. // Used to store the previous times and CPU usage counts so we can
  241. // compute the CPU usage between calls.
  242. TimeTicks last_cpu_time_;
  243. #if !BUILDFLAG(IS_FREEBSD) || !BUILDFLAG(IS_POSIX)
  244. TimeDelta last_cumulative_cpu_;
  245. #endif
  246. #if BUILDFLAG(IS_WIN)
  247. TimeTicks last_cpu_time_for_precise_cpu_usage_;
  248. TimeDelta last_precise_cumulative_cpu_;
  249. #endif
  250. #if BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \
  251. BUILDFLAG(IS_AIX)
  252. // Same thing for idle wakeups.
  253. TimeTicks last_idle_wakeups_time_;
  254. uint64_t last_absolute_idle_wakeups_;
  255. #endif
  256. #if BUILDFLAG(IS_APPLE)
  257. // And same thing for package idle exit wakeups.
  258. TimeTicks last_package_idle_wakeups_time_;
  259. uint64_t last_absolute_package_idle_wakeups_;
  260. double last_energy_impact_;
  261. // In mach_absolute_time units.
  262. uint64_t last_energy_impact_time_;
  263. #endif
  264. #if BUILDFLAG(IS_MAC)
  265. // Queries the port provider if it's set.
  266. mach_port_t TaskForPid(ProcessHandle process) const;
  267. raw_ptr<PortProvider> port_provider_;
  268. #endif // BUILDFLAG(IS_MAC)
  269. };
  270. // Returns the memory committed by the system in KBytes.
  271. // Returns 0 if it can't compute the commit charge.
  272. BASE_EXPORT size_t GetSystemCommitCharge();
  273. // Returns the maximum number of file descriptors that can be open by a process
  274. // at once. If the number is unavailable, a conservative best guess is returned.
  275. BASE_EXPORT size_t GetMaxFds();
  276. // Returns the maximum number of handles that can be open at once per process.
  277. BASE_EXPORT size_t GetHandleLimit();
  278. #if BUILDFLAG(IS_POSIX)
  279. // Increases the file descriptor soft limit to |max_descriptors| or the OS hard
  280. // limit, whichever is lower. If the limit is already higher than
  281. // |max_descriptors|, then nothing happens.
  282. BASE_EXPORT void IncreaseFdLimitTo(unsigned int max_descriptors);
  283. #endif // BUILDFLAG(IS_POSIX)
  284. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_LINUX) || \
  285. BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_AIX) || \
  286. BUILDFLAG(IS_FUCHSIA)
  287. // Data about system-wide memory consumption. Values are in KB. Available on
  288. // Windows, Mac, Linux, Android and Chrome OS.
  289. //
  290. // Total memory are available on all platforms that implement
  291. // GetSystemMemoryInfo(). Total/free swap memory are available on all platforms
  292. // except on Mac. Buffers/cached/active_anon/inactive_anon/active_file/
  293. // inactive_file/dirty/reclaimable/pswpin/pswpout/pgmajfault are available on
  294. // Linux/Android/Chrome OS. Shmem/slab are Chrome OS only.
  295. // Speculative/file_backed/purgeable are Mac and iOS only.
  296. // Free is absent on Windows (see "avail_phys" below).
  297. struct BASE_EXPORT SystemMemoryInfoKB {
  298. SystemMemoryInfoKB();
  299. SystemMemoryInfoKB(const SystemMemoryInfoKB& other);
  300. SystemMemoryInfoKB& operator=(const SystemMemoryInfoKB& other);
  301. // Serializes the platform specific fields to value.
  302. Value ToValue() const;
  303. int total = 0;
  304. #if !BUILDFLAG(IS_WIN)
  305. int free = 0;
  306. #endif
  307. #if BUILDFLAG(IS_WIN)
  308. // "This is the amount of physical memory that can be immediately reused
  309. // without having to write its contents to disk first. It is the sum of the
  310. // size of the standby, free, and zero lists." (MSDN).
  311. // Standby: not modified pages of physical ram (file-backed memory) that are
  312. // not actively being used.
  313. int avail_phys = 0;
  314. #endif
  315. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \
  316. BUILDFLAG(IS_AIX)
  317. // This provides an estimate of available memory as described here:
  318. // https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
  319. // NOTE: this is ONLY valid in kernels 3.14 and up. Its value will always
  320. // be 0 in earlier kernel versions.
  321. // Note: it includes _all_ file-backed memory (active + inactive).
  322. int available = 0;
  323. #endif
  324. #if !BUILDFLAG(IS_APPLE)
  325. int swap_total = 0;
  326. int swap_free = 0;
  327. #endif
  328. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || \
  329. BUILDFLAG(IS_AIX) || BUILDFLAG(IS_FUCHSIA)
  330. int buffers = 0;
  331. int cached = 0;
  332. int active_anon = 0;
  333. int inactive_anon = 0;
  334. int active_file = 0;
  335. int inactive_file = 0;
  336. int dirty = 0;
  337. int reclaimable = 0;
  338. #endif // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_LINUX) ||
  339. // BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_AIX) BUILDFLAG(IS_FUCHSIA)
  340. #if BUILDFLAG(IS_CHROMEOS)
  341. int shmem = 0;
  342. int slab = 0;
  343. #endif // BUILDFLAG(IS_CHROMEOS)
  344. #if BUILDFLAG(IS_APPLE)
  345. int speculative = 0;
  346. int file_backed = 0;
  347. int purgeable = 0;
  348. #endif // BUILDFLAG(IS_APPLE)
  349. };
  350. // On Linux/Android/Chrome OS, system-wide memory consumption data is parsed
  351. // from /proc/meminfo and /proc/vmstat. On Windows/Mac, it is obtained using
  352. // system API calls.
  353. //
  354. // Fills in the provided |meminfo| structure. Returns true on success.
  355. // Exposed for memory debugging widget.
  356. BASE_EXPORT bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo);
  357. #endif // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_APPLE) || BUILDFLAG(IS_LINUX) ||
  358. // BUILDFLAG(IS_CHROMEOS) BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_AIX) ||
  359. // BUILDFLAG(IS_FUCHSIA)
  360. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID) || \
  361. BUILDFLAG(IS_AIX)
  362. // Parse the data found in /proc/<pid>/stat and return the sum of the
  363. // CPU-related ticks. Returns -1 on parse error.
  364. // Exposed for testing.
  365. BASE_EXPORT int ParseProcStatCPU(StringPiece input);
  366. // Get the number of threads of |process| as available in /proc/<pid>/stat.
  367. // This should be used with care as no synchronization with running threads is
  368. // done. This is mostly useful to guarantee being single-threaded.
  369. // Returns 0 on failure.
  370. BASE_EXPORT int64_t GetNumberOfThreads(ProcessHandle process);
  371. // /proc/self/exe refers to the current executable.
  372. BASE_EXPORT extern const char kProcSelfExe[];
  373. // Parses a string containing the contents of /proc/meminfo
  374. // returns true on success or false for a parsing error
  375. // Exposed for testing.
  376. BASE_EXPORT bool ParseProcMeminfo(StringPiece input,
  377. SystemMemoryInfoKB* meminfo);
  378. // Data from /proc/vmstat.
  379. struct BASE_EXPORT VmStatInfo {
  380. // Serializes the platform specific fields to value.
  381. Value ToValue() const;
  382. uint64_t pswpin = 0;
  383. uint64_t pswpout = 0;
  384. uint64_t pgmajfault = 0;
  385. uint64_t oom_kill = 0;
  386. };
  387. // Retrieves data from /proc/vmstat about system-wide vm operations.
  388. // Fills in the provided |vmstat| structure. Returns true on success.
  389. BASE_EXPORT bool GetVmStatInfo(VmStatInfo* vmstat);
  390. // Parses a string containing the contents of /proc/vmstat
  391. // returns true on success or false for a parsing error
  392. // Exposed for testing.
  393. BASE_EXPORT bool ParseProcVmstat(StringPiece input, VmStatInfo* vmstat);
  394. // Data from /proc/diskstats about system-wide disk I/O.
  395. struct BASE_EXPORT SystemDiskInfo {
  396. SystemDiskInfo();
  397. SystemDiskInfo(const SystemDiskInfo&);
  398. SystemDiskInfo& operator=(const SystemDiskInfo&);
  399. // Serializes the platform specific fields to value.
  400. Value ToValue() const;
  401. uint64_t reads = 0;
  402. uint64_t reads_merged = 0;
  403. uint64_t sectors_read = 0;
  404. uint64_t read_time = 0;
  405. uint64_t writes = 0;
  406. uint64_t writes_merged = 0;
  407. uint64_t sectors_written = 0;
  408. uint64_t write_time = 0;
  409. uint64_t io = 0;
  410. uint64_t io_time = 0;
  411. uint64_t weighted_io_time = 0;
  412. };
  413. // Checks whether the candidate string is a valid disk name, [hsv]d[a-z]+
  414. // for a generic disk or mmcblk[0-9]+ for the MMC case.
  415. // Names of disk partitions (e.g. sda1) are not valid.
  416. BASE_EXPORT bool IsValidDiskName(StringPiece candidate);
  417. // Retrieves data from /proc/diskstats about system-wide disk I/O.
  418. // Fills in the provided |diskinfo| structure. Returns true on success.
  419. BASE_EXPORT bool GetSystemDiskInfo(SystemDiskInfo* diskinfo);
  420. // Returns the amount of time spent in user space since boot across all CPUs.
  421. BASE_EXPORT TimeDelta GetUserCpuTimeSinceBoot();
  422. #endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
  423. // BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_AIX)
  424. #if BUILDFLAG(IS_CHROMEOS)
  425. // Data from files in directory /sys/block/zram0 about ZRAM usage.
  426. struct BASE_EXPORT SwapInfo {
  427. SwapInfo()
  428. : num_reads(0),
  429. num_writes(0),
  430. compr_data_size(0),
  431. orig_data_size(0),
  432. mem_used_total(0) {
  433. }
  434. // Serializes the platform specific fields to value.
  435. Value ToValue() const;
  436. uint64_t num_reads = 0;
  437. uint64_t num_writes = 0;
  438. uint64_t compr_data_size = 0;
  439. uint64_t orig_data_size = 0;
  440. uint64_t mem_used_total = 0;
  441. };
  442. // Parses a string containing the contents of /sys/block/zram0/mm_stat.
  443. // This should be used for the new ZRAM sysfs interfaces.
  444. // Returns true on success or false for a parsing error.
  445. // Exposed for testing.
  446. BASE_EXPORT bool ParseZramMmStat(StringPiece mm_stat_data, SwapInfo* swap_info);
  447. // Parses a string containing the contents of /sys/block/zram0/stat
  448. // This should be used for the new ZRAM sysfs interfaces.
  449. // Returns true on success or false for a parsing error.
  450. // Exposed for testing.
  451. BASE_EXPORT bool ParseZramStat(StringPiece stat_data, SwapInfo* swap_info);
  452. // In ChromeOS, reads files from /sys/block/zram0 that contain ZRAM usage data.
  453. // Fills in the provided |swap_data| structure.
  454. // Returns true on success or false for a parsing error.
  455. BASE_EXPORT bool GetSwapInfo(SwapInfo* swap_info);
  456. // Data about GPU memory usage. These fields will be -1 if not supported.
  457. struct BASE_EXPORT GraphicsMemoryInfoKB {
  458. // Serializes the platform specific fields to value.
  459. Value ToValue() const;
  460. int gpu_objects = -1;
  461. int64_t gpu_memory_size = -1;
  462. };
  463. // Report on Chrome OS graphics memory. Returns true on success.
  464. // /run/debugfs_gpu is a bind mount into /sys/kernel/debug and synchronously
  465. // reading the in-memory files in /sys is fast in most cases. On platform that
  466. // reading the graphics memory info is slow, this function returns false.
  467. BASE_EXPORT bool GetGraphicsMemoryInfo(GraphicsMemoryInfoKB* gpu_meminfo);
  468. #endif // BUILDFLAG(IS_CHROMEOS)
  469. struct BASE_EXPORT SystemPerformanceInfo {
  470. SystemPerformanceInfo();
  471. SystemPerformanceInfo(const SystemPerformanceInfo& other);
  472. // Serializes the platform specific fields to value.
  473. Value ToValue() const;
  474. // Total idle time of all processes in the system (units of 100 ns).
  475. uint64_t idle_time = 0;
  476. // Number of bytes read.
  477. uint64_t read_transfer_count = 0;
  478. // Number of bytes written.
  479. uint64_t write_transfer_count = 0;
  480. // Number of bytes transferred (e.g. DeviceIoControlFile)
  481. uint64_t other_transfer_count = 0;
  482. // The amount of read operations.
  483. uint64_t read_operation_count = 0;
  484. // The amount of write operations.
  485. uint64_t write_operation_count = 0;
  486. // The amount of other operations.
  487. uint64_t other_operation_count = 0;
  488. // The number of pages written to the system's pagefiles.
  489. uint64_t pagefile_pages_written = 0;
  490. // The number of write operations performed on the system's pagefiles.
  491. uint64_t pagefile_pages_write_ios = 0;
  492. // The number of pages of physical memory available to processes running on
  493. // the system.
  494. uint64_t available_pages = 0;
  495. // The number of pages read from disk to resolve page faults.
  496. uint64_t pages_read = 0;
  497. // The number of read operations initiated to resolve page faults.
  498. uint64_t page_read_ios = 0;
  499. };
  500. // Retrieves performance counters from the operating system.
  501. // Fills in the provided |info| structure. Returns true on success.
  502. BASE_EXPORT bool GetSystemPerformanceInfo(SystemPerformanceInfo* info);
  503. // Collects and holds performance metrics for system memory and disk.
  504. // Provides functionality to retrieve the data on various platforms and
  505. // to serialize the stored data.
  506. class BASE_EXPORT SystemMetrics {
  507. public:
  508. SystemMetrics();
  509. static SystemMetrics Sample();
  510. // Serializes the system metrics to value.
  511. Value ToValue() const;
  512. private:
  513. FRIEND_TEST_ALL_PREFIXES(SystemMetricsTest, SystemMetrics);
  514. size_t committed_memory_;
  515. #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
  516. SystemMemoryInfoKB memory_info_;
  517. VmStatInfo vmstat_info_;
  518. SystemDiskInfo disk_info_;
  519. #endif
  520. #if BUILDFLAG(IS_CHROMEOS)
  521. SwapInfo swap_info_;
  522. GraphicsMemoryInfoKB gpu_memory_info_;
  523. #endif
  524. #if BUILDFLAG(IS_WIN)
  525. SystemPerformanceInfo performance_;
  526. #endif
  527. };
  528. #if BUILDFLAG(IS_MAC)
  529. enum class MachVMRegionResult {
  530. // There were no more memory regions between |address| and the end of the
  531. // virtual address space.
  532. Finished,
  533. // All output parameters are invalid.
  534. Error,
  535. // All output parameters are filled in.
  536. Success
  537. };
  538. // Returns info on the first memory region at or after |address|, including
  539. // resident memory and share mode. On Success, |size| reflects the size of the
  540. // memory region.
  541. // |size| and |info| are output parameters, only valid on Success.
  542. // |address| is an in-out parameter, than represents both the address to start
  543. // looking, and the start address of the memory region.
  544. BASE_EXPORT MachVMRegionResult GetTopInfo(mach_port_t task,
  545. mach_vm_size_t* size,
  546. mach_vm_address_t* address,
  547. vm_region_top_info_data_t* info);
  548. // Returns info on the first memory region at or after |address|, including
  549. // protection values. On Success, |size| reflects the size of the
  550. // memory region.
  551. // Returns info on the first memory region at or after |address|, including
  552. // resident memory and share mode.
  553. // |size| and |info| are output parameters, only valid on Success.
  554. BASE_EXPORT MachVMRegionResult GetBasicInfo(mach_port_t task,
  555. mach_vm_size_t* size,
  556. mach_vm_address_t* address,
  557. vm_region_basic_info_64* info);
  558. #endif // BUILDFLAG(IS_MAC)
  559. } // namespace base
  560. #endif // BASE_PROCESS_PROCESS_METRICS_H_