Revert "Fix broken channel icon in chrome://help on CrOS" and try again
[chromium-blink-merge.git] / base / process / process_metrics.h
blob54b10aaacfa2f5cfb0ab3ffc702fbc226435c325
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.
5 // This file contains routines for gathering resource statistics for processes
6 // running on the system.
8 #ifndef BASE_PROCESS_PROCESS_METRICS_H_
9 #define BASE_PROCESS_PROCESS_METRICS_H_
11 #include <string>
13 #include "base/base_export.h"
14 #include "base/basictypes.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/process/process_handle.h"
17 #include "base/time/time.h"
18 #include "base/values.h"
20 #if defined(OS_MACOSX)
21 #include <mach/mach.h>
22 #endif
24 namespace base {
26 #if defined(OS_WIN)
27 struct IoCounters : public IO_COUNTERS {
29 #elif defined(OS_POSIX)
30 struct IoCounters {
31 uint64_t ReadOperationCount;
32 uint64_t WriteOperationCount;
33 uint64_t OtherOperationCount;
34 uint64_t ReadTransferCount;
35 uint64_t WriteTransferCount;
36 uint64_t OtherTransferCount;
38 #endif
40 // Working Set (resident) memory usage broken down by
42 // On Windows:
43 // priv (private): These pages (kbytes) cannot be shared with any other process.
44 // shareable: These pages (kbytes) can be shared with other processes under
45 // the right circumstances.
46 // shared : These pages (kbytes) are currently shared with at least one
47 // other process.
49 // On Linux:
50 // priv: Pages mapped only by this process.
51 // shared: PSS or 0 if the kernel doesn't support this.
52 // shareable: 0
54 // On ChromeOS:
55 // priv: Pages mapped only by this process.
56 // shared: PSS or 0 if the kernel doesn't support this.
57 // shareable: 0
58 // swapped Pages swapped out to zram.
60 // On OS X: TODO(thakis): Revise.
61 // priv: Memory.
62 // shared: 0
63 // shareable: 0
65 struct WorkingSetKBytes {
66 WorkingSetKBytes() : priv(0), shareable(0), shared(0) {}
67 size_t priv;
68 size_t shareable;
69 size_t shared;
70 #if defined(OS_CHROMEOS)
71 size_t swapped;
72 #endif
75 // Committed (resident + paged) memory usage broken down by
76 // private: These pages cannot be shared with any other process.
77 // mapped: These pages are mapped into the view of a section (backed by
78 // pagefile.sys)
79 // image: These pages are mapped into the view of an image section (backed by
80 // file system)
81 struct CommittedKBytes {
82 CommittedKBytes() : priv(0), mapped(0), image(0) {}
83 size_t priv;
84 size_t mapped;
85 size_t image;
88 // Convert a POSIX timeval to microseconds.
89 BASE_EXPORT int64 TimeValToMicroseconds(const struct timeval& tv);
91 // Provides performance metrics for a specified process (CPU usage, memory and
92 // IO counters). To use it, invoke CreateProcessMetrics() to get an instance
93 // for a specific process, then access the information with the different get
94 // methods.
95 class BASE_EXPORT ProcessMetrics {
96 public:
97 ~ProcessMetrics();
99 // Creates a ProcessMetrics for the specified process.
100 // The caller owns the returned object.
101 #if !defined(OS_MACOSX) || defined(OS_IOS)
102 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process);
103 #else
104 class PortProvider {
105 public:
106 virtual ~PortProvider() {}
108 // Should return the mach task for |process| if possible, or else
109 // |MACH_PORT_NULL|. Only processes that this returns tasks for will have
110 // metrics on OS X (except for the current process, which always gets
111 // metrics).
112 virtual mach_port_t TaskForPid(ProcessHandle process) const = 0;
115 // The port provider needs to outlive the ProcessMetrics object returned by
116 // this function. If NULL is passed as provider, the returned object
117 // only returns valid metrics if |process| is the current process.
118 static ProcessMetrics* CreateProcessMetrics(ProcessHandle process,
119 PortProvider* port_provider);
120 #endif // !defined(OS_MACOSX) || defined(OS_IOS)
122 // Returns the current space allocated for the pagefile, in bytes (these pages
123 // may or may not be in memory). On Linux, this returns the total virtual
124 // memory size.
125 size_t GetPagefileUsage() const;
126 // Returns the peak space allocated for the pagefile, in bytes.
127 size_t GetPeakPagefileUsage() const;
128 // Returns the current working set size, in bytes. On Linux, this returns
129 // the resident set size.
130 size_t GetWorkingSetSize() const;
131 // Returns the peak working set size, in bytes.
132 size_t GetPeakWorkingSetSize() const;
133 // Returns private and sharedusage, in bytes. Private bytes is the amount of
134 // memory currently allocated to a process that cannot be shared. Returns
135 // false on platform specific error conditions. Note: |private_bytes|
136 // returns 0 on unsupported OSes: prior to XP SP2.
137 bool GetMemoryBytes(size_t* private_bytes,
138 size_t* shared_bytes);
139 // Fills a CommittedKBytes with both resident and paged
140 // memory usage as per definition of CommittedBytes.
141 void GetCommittedKBytes(CommittedKBytes* usage) const;
142 // Fills a WorkingSetKBytes containing resident private and shared memory
143 // usage in bytes, as per definition of WorkingSetBytes. Note that this
144 // function is somewhat expensive on Windows (a few ms per process).
145 bool GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const;
147 #if defined(OS_MACOSX)
148 // Fills both CommitedKBytes and WorkingSetKBytes in a single operation. This
149 // is more efficient on Mac OS X, as the two can be retrieved with a single
150 // system call.
151 bool GetCommittedAndWorkingSetKBytes(CommittedKBytes* usage,
152 WorkingSetKBytes* ws_usage) const;
153 #endif
155 // Returns the CPU usage in percent since the last time this method or
156 // GetPlatformIndependentCPUUsage() was called. The first time this method
157 // is called it returns 0 and will return the actual CPU info on subsequent
158 // calls. On Windows, the CPU usage value is for all CPUs. So if you have
159 // 2 CPUs and your process is using all the cycles of 1 CPU and not the other
160 // CPU, this method returns 50.
161 double GetCPUUsage();
163 // Returns the number of average idle cpu wakeups per second since the last
164 // call.
165 int GetIdleWakeupsPerSecond();
167 // Same as GetCPUUsage(), but will return consistent values on all platforms
168 // (cancelling the Windows exception mentioned above) by returning a value in
169 // the range of 0 to (100 * numCPUCores) everywhere.
170 double GetPlatformIndependentCPUUsage();
172 // Retrieves accounting information for all I/O operations performed by the
173 // process.
174 // If IO information is retrieved successfully, the function returns true
175 // and fills in the IO_COUNTERS passed in. The function returns false
176 // otherwise.
177 bool GetIOCounters(IoCounters* io_counters) const;
179 private:
180 #if !defined(OS_MACOSX) || defined(OS_IOS)
181 explicit ProcessMetrics(ProcessHandle process);
182 #else
183 ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
184 #endif // !defined(OS_MACOSX) || defined(OS_IOS)
186 #if defined(OS_LINUX) || defined(OS_ANDROID)
187 bool GetWorkingSetKBytesStatm(WorkingSetKBytes* ws_usage) const;
188 #endif
190 #if defined(OS_CHROMEOS)
191 bool GetWorkingSetKBytesTotmaps(WorkingSetKBytes *ws_usage) const;
192 #endif
194 #if defined(OS_MACOSX) || defined(OS_LINUX)
195 int CalculateIdleWakeupsPerSecond(uint64 absolute_idle_wakeups);
196 #endif
198 ProcessHandle process_;
200 int processor_count_;
202 // Used to store the previous times and CPU usage counts so we can
203 // compute the CPU usage between calls.
204 TimeTicks last_cpu_time_;
205 int64 last_system_time_;
207 #if defined(OS_MACOSX) || defined(OS_LINUX)
208 // Same thing for idle wakeups.
209 TimeTicks last_idle_wakeups_time_;
210 uint64 last_absolute_idle_wakeups_;
211 #endif
213 #if !defined(OS_IOS)
214 #if defined(OS_MACOSX)
215 // Queries the port provider if it's set.
216 mach_port_t TaskForPid(ProcessHandle process) const;
218 PortProvider* port_provider_;
219 #elif defined(OS_POSIX)
220 // Jiffie count at the last_cpu_time_ we updated.
221 int last_cpu_;
222 #endif // defined(OS_POSIX)
223 #endif // !defined(OS_IOS)
225 DISALLOW_COPY_AND_ASSIGN(ProcessMetrics);
228 // Returns the memory committed by the system in KBytes.
229 // Returns 0 if it can't compute the commit charge.
230 BASE_EXPORT size_t GetSystemCommitCharge();
232 // Returns the number of bytes in a memory page.
233 BASE_EXPORT size_t GetPageSize();
235 #if defined(OS_POSIX)
236 // Returns the maximum number of file descriptors that can be open by a process
237 // at once. If the number is unavailable, a conservative best guess is returned.
238 BASE_EXPORT size_t GetMaxFds();
240 // Sets the file descriptor soft limit to |max_descriptors| or the OS hard
241 // limit, whichever is lower.
242 BASE_EXPORT void SetFdLimit(unsigned int max_descriptors);
243 #endif // defined(OS_POSIX)
245 #if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) || \
246 defined(OS_ANDROID)
247 // Data about system-wide memory consumption. Values are in KB. Available on
248 // Windows, Mac, Linux, Android and Chrome OS.
250 // Total/free memory are available on all platforms that implement
251 // GetSystemMemoryInfo(). Total/free swap memory are available on all platforms
252 // except on Mac. Buffers/cached/active_anon/inactive_anon/active_file/
253 // inactive_file/dirty/pswpin/pswpout/pgmajfault are available on
254 // Linux/Android/Chrome OS. Shmem/slab/gem_objects/gem_size are Chrome OS only.
255 struct BASE_EXPORT SystemMemoryInfoKB {
256 SystemMemoryInfoKB();
258 // Serializes the platform specific fields to value.
259 scoped_ptr<Value> ToValue() const;
261 int total;
262 int free;
264 #if !defined(OS_MACOSX)
265 int swap_total;
266 int swap_free;
267 #endif
269 #if defined(OS_ANDROID) || defined(OS_LINUX)
270 int buffers;
271 int cached;
272 int active_anon;
273 int inactive_anon;
274 int active_file;
275 int inactive_file;
276 int dirty;
278 // vmstats data.
279 int pswpin;
280 int pswpout;
281 int pgmajfault;
282 #endif // defined(OS_ANDROID) || defined(OS_LINUX)
284 #if defined(OS_CHROMEOS)
285 int shmem;
286 int slab;
287 // Gem data will be -1 if not supported.
288 int gem_objects;
289 long long gem_size;
290 #endif // defined(OS_CHROMEOS)
293 // On Linux/Android/Chrome OS, system-wide memory consumption data is parsed
294 // from /proc/meminfo and /proc/vmstat. On Windows/Mac, it is obtained using
295 // system API calls.
297 // Fills in the provided |meminfo| structure. Returns true on success.
298 // Exposed for memory debugging widget.
299 BASE_EXPORT bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo);
301 #endif // defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX) ||
302 // defined(OS_ANDROID)
304 #if defined(OS_LINUX) || defined(OS_ANDROID)
305 // Parse the data found in /proc/<pid>/stat and return the sum of the
306 // CPU-related ticks. Returns -1 on parse error.
307 // Exposed for testing.
308 BASE_EXPORT int ParseProcStatCPU(const std::string& input);
310 // Get the number of threads of |process| as available in /proc/<pid>/stat.
311 // This should be used with care as no synchronization with running threads is
312 // done. This is mostly useful to guarantee being single-threaded.
313 // Returns 0 on failure.
314 BASE_EXPORT int GetNumberOfThreads(ProcessHandle process);
316 // /proc/self/exe refers to the current executable.
317 BASE_EXPORT extern const char kProcSelfExe[];
319 // Parses a string containing the contents of /proc/meminfo
320 // returns true on success or false for a parsing error
321 BASE_EXPORT bool ParseProcMeminfo(const std::string& input,
322 SystemMemoryInfoKB* meminfo);
324 // Parses a string containing the contents of /proc/vmstat
325 // returns true on success or false for a parsing error
326 BASE_EXPORT bool ParseProcVmstat(const std::string& input,
327 SystemMemoryInfoKB* meminfo);
329 // Data from /proc/diskstats about system-wide disk I/O.
330 struct BASE_EXPORT SystemDiskInfo {
331 SystemDiskInfo();
333 // Serializes the platform specific fields to value.
334 scoped_ptr<Value> ToValue() const;
336 uint64 reads;
337 uint64 reads_merged;
338 uint64 sectors_read;
339 uint64 read_time;
340 uint64 writes;
341 uint64 writes_merged;
342 uint64 sectors_written;
343 uint64 write_time;
344 uint64 io;
345 uint64 io_time;
346 uint64 weighted_io_time;
349 // Checks whether the candidate string is a valid disk name, [hsv]d[a-z]+
350 // for a generic disk or mmcblk[0-9]+ for the MMC case.
351 // Names of disk partitions (e.g. sda1) are not valid.
352 BASE_EXPORT bool IsValidDiskName(const std::string& candidate);
354 // Retrieves data from /proc/diskstats about system-wide disk I/O.
355 // Fills in the provided |diskinfo| structure. Returns true on success.
356 BASE_EXPORT bool GetSystemDiskInfo(SystemDiskInfo* diskinfo);
357 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
359 #if defined(OS_CHROMEOS)
360 // Data from files in directory /sys/block/zram0 about ZRAM usage.
361 struct BASE_EXPORT SwapInfo {
362 SwapInfo()
363 : num_reads(0),
364 num_writes(0),
365 compr_data_size(0),
366 orig_data_size(0),
367 mem_used_total(0) {
370 // Serializes the platform specific fields to value.
371 scoped_ptr<Value> ToValue() const;
373 uint64 num_reads;
374 uint64 num_writes;
375 uint64 compr_data_size;
376 uint64 orig_data_size;
377 uint64 mem_used_total;
380 // In ChromeOS, reads files from /sys/block/zram0 that contain ZRAM usage data.
381 // Fills in the provided |swap_data| structure.
382 BASE_EXPORT void GetSwapInfo(SwapInfo* swap_info);
383 #endif // defined(OS_CHROMEOS)
385 // Collects and holds performance metrics for system memory and disk.
386 // Provides functionality to retrieve the data on various platforms and
387 // to serialize the stored data.
388 class SystemMetrics {
389 public:
390 SystemMetrics();
392 static SystemMetrics Sample();
394 // Serializes the system metrics to value.
395 scoped_ptr<Value> ToValue() const;
397 private:
398 FRIEND_TEST_ALL_PREFIXES(SystemMetricsTest, SystemMetrics);
400 size_t committed_memory_;
401 #if defined(OS_LINUX) || defined(OS_ANDROID)
402 SystemMemoryInfoKB memory_info_;
403 SystemDiskInfo disk_info_;
404 #endif
405 #if defined(OS_CHROMEOS)
406 SwapInfo swap_info_;
407 #endif
410 } // namespace base
412 #endif // BASE_PROCESS_PROCESS_METRICS_H_