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