[go: nahoru, domu]

blob: 3d27656d6acccaea911a1a0a8f7294c76f720c79 [file] [log] [blame]
rsesek@chromium.org32f5e9a2013-05-23 12:59:541// 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
5#include "base/process/process_metrics.h"
6
7#include <dirent.h>
davemoore@chromium.org7b9c98872013-05-29 15:42:048#include <fcntl.h>
avibeced7c2015-12-24 06:47:599#include <stddef.h>
10#include <stdint.h>
davemoore@chromium.org7b9c98872013-05-29 15:42:0411#include <sys/stat.h>
rsesek@chromium.org32f5e9a2013-05-23 12:59:5412#include <sys/time.h>
13#include <sys/types.h>
14#include <unistd.h>
danakj0c8d4aa2015-11-25 05:29:5815#include <utility>
rsesek@chromium.org32f5e9a2013-05-23 12:59:5416
thestigcf4c85b2015-12-16 08:33:3017#include "base/files/dir_reader_posix.h"
brettw@chromium.orge3177dd52014-08-13 20:22:1418#include "base/files/file_util.h"
rsesek@chromium.org32f5e9a2013-05-23 12:59:5419#include "base/logging.h"
20#include "base/process/internal_linux.h"
rsesek@chromium.org32f5e9a2013-05-23 12:59:5421#include "base/strings/string_number_conversions.h"
22#include "base/strings/string_split.h"
23#include "base/strings/string_tokenizer.h"
avi@chromium.orgd1a5a2f2013-06-10 21:17:4024#include "base/strings/string_util.h"
rsesek@chromium.org32f5e9a2013-05-23 12:59:5425#include "base/sys_info.h"
26#include "base/threading/thread_restrictions.h"
avibeced7c2015-12-24 06:47:5927#include "build/build_config.h"
rsesek@chromium.org32f5e9a2013-05-23 12:59:5428
29namespace base {
30
31namespace {
32
thestig75844fdb2014-09-09 19:47:1033void TrimKeyValuePairs(StringPairs* pairs) {
34 DCHECK(pairs);
35 StringPairs& p_ref = *pairs;
36 for (size_t i = 0; i < p_ref.size(); ++i) {
37 TrimWhitespaceASCII(p_ref[i].first, TRIM_ALL, &p_ref[i].first);
38 TrimWhitespaceASCII(p_ref[i].second, TRIM_ALL, &p_ref[i].second);
39 }
40}
41
thestiga0d051ed2014-09-08 21:41:1742#if defined(OS_CHROMEOS)
avibeced7c2015-12-24 06:47:5943// Read a file with a single number string and return the number as a uint64_t.
44static uint64_t ReadFileToUint64(const FilePath file) {
nduca@chromium.orgf4134782013-08-29 21:25:2045 std::string file_as_string;
brettw@chromium.org82f84b92013-08-30 18:23:5046 if (!ReadFileToString(file, &file_as_string))
nduca@chromium.orgf4134782013-08-29 21:25:2047 return 0;
thestiga0d051ed2014-09-08 21:41:1748 TrimWhitespaceASCII(file_as_string, TRIM_ALL, &file_as_string);
avibeced7c2015-12-24 06:47:5949 uint64_t file_as_uint64 = 0;
thestiga0d051ed2014-09-08 21:41:1750 if (!StringToUint64(file_as_string, &file_as_uint64))
nduca@chromium.orgf4134782013-08-29 21:25:2051 return 0;
52 return file_as_uint64;
53}
54#endif
55
thestiga0d051ed2014-09-08 21:41:1756// Read /proc/<pid>/status and return the value for |field|, or 0 on failure.
rsesek@chromium.org32f5e9a2013-05-23 12:59:5457// Only works for fields in the form of "Field: value kB".
58size_t ReadProcStatusAndGetFieldAsSizeT(pid_t pid, const std::string& field) {
rsesek@chromium.org32f5e9a2013-05-23 12:59:5459 std::string status;
60 {
thestig75844fdb2014-09-09 19:47:1061 // Synchronously reading files in /proc does not hit the disk.
rsesek@chromium.org32f5e9a2013-05-23 12:59:5462 ThreadRestrictions::ScopedAllowIO allow_io;
thestiga0d051ed2014-09-08 21:41:1763 FilePath stat_file = internal::GetProcPidDir(pid).Append("status");
brettw@chromium.org82f84b92013-08-30 18:23:5064 if (!ReadFileToString(stat_file, &status))
rsesek@chromium.org32f5e9a2013-05-23 12:59:5465 return 0;
66 }
67
thestig75844fdb2014-09-09 19:47:1068 StringPairs pairs;
thestiga0d051ed2014-09-08 21:41:1769 SplitStringIntoKeyValuePairs(status, ':', '\n', &pairs);
thestig75844fdb2014-09-09 19:47:1070 TrimKeyValuePairs(&pairs);
thestiga0d051ed2014-09-08 21:41:1771 for (size_t i = 0; i < pairs.size(); ++i) {
thestig75844fdb2014-09-09 19:47:1072 const std::string& key = pairs[i].first;
73 const std::string& value_str = pairs[i].second;
thestiga0d051ed2014-09-08 21:41:1774 if (key == field) {
brettw26dab8f02015-08-08 00:28:4775 std::vector<StringPiece> split_value_str = SplitStringPiece(
76 value_str, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
thestiga0d051ed2014-09-08 21:41:1777 if (split_value_str.size() != 2 || split_value_str[1] != "kB") {
78 NOTREACHED();
79 return 0;
80 }
81 size_t value;
82 if (!StringToSizeT(split_value_str[0], &value)) {
83 NOTREACHED();
84 return 0;
85 }
86 return value;
rsesek@chromium.org32f5e9a2013-05-23 12:59:5487 }
88 }
sside5fb5cd2016-01-26 12:34:0689 // This can be reached if the process dies when proc is read -- in that case,
90 // the kernel can return missing fields.
rsesek@chromium.org32f5e9a2013-05-23 12:59:5491 return 0;
92}
93
thestig75844fdb2014-09-09 19:47:1094#if defined(OS_LINUX)
95// Read /proc/<pid>/sched and look for |field|. On succes, return true and
96// write the value for |field| into |result|.
97// Only works for fields in the form of "field : uint_value"
98bool ReadProcSchedAndGetFieldAsUint64(pid_t pid,
99 const std::string& field,
avibeced7c2015-12-24 06:47:59100 uint64_t* result) {
thestig75844fdb2014-09-09 19:47:10101 std::string sched_data;
102 {
103 // Synchronously reading files in /proc does not hit the disk.
104 ThreadRestrictions::ScopedAllowIO allow_io;
105 FilePath sched_file = internal::GetProcPidDir(pid).Append("sched");
106 if (!ReadFileToString(sched_file, &sched_data))
107 return false;
108 }
109
110 StringPairs pairs;
111 SplitStringIntoKeyValuePairs(sched_data, ':', '\n', &pairs);
112 TrimKeyValuePairs(&pairs);
113 for (size_t i = 0; i < pairs.size(); ++i) {
114 const std::string& key = pairs[i].first;
115 const std::string& value_str = pairs[i].second;
116 if (key == field) {
avibeced7c2015-12-24 06:47:59117 uint64_t value;
thestig75844fdb2014-09-09 19:47:10118 if (!StringToUint64(value_str, &value))
119 return false;
120 *result = value;
121 return true;
122 }
123 }
124 return false;
125}
126#endif // defined(OS_LINUX)
127
rsesek@chromium.org32f5e9a2013-05-23 12:59:54128// Get the total CPU of a single process. Return value is number of jiffies
129// on success or -1 on error.
130int GetProcessCPU(pid_t pid) {
131 // Use /proc/<pid>/task to find all threads and parse their /stat file.
132 FilePath task_path = internal::GetProcPidDir(pid).Append("task");
133
134 DIR* dir = opendir(task_path.value().c_str());
135 if (!dir) {
136 DPLOG(ERROR) << "opendir(" << task_path.value() << ")";
137 return -1;
138 }
139
140 int total_cpu = 0;
141 while (struct dirent* ent = readdir(dir)) {
142 pid_t tid = internal::ProcDirSlotToPid(ent->d_name);
143 if (!tid)
144 continue;
145
thestig75844fdb2014-09-09 19:47:10146 // Synchronously reading files in /proc does not hit the disk.
rsesek@chromium.org32f5e9a2013-05-23 12:59:54147 ThreadRestrictions::ScopedAllowIO allow_io;
148
149 std::string stat;
150 FilePath stat_path =
151 task_path.Append(ent->d_name).Append(internal::kStatFile);
brettw@chromium.org82f84b92013-08-30 18:23:50152 if (ReadFileToString(stat_path, &stat)) {
rsesek@chromium.org32f5e9a2013-05-23 12:59:54153 int cpu = ParseProcStatCPU(stat);
154 if (cpu > 0)
155 total_cpu += cpu;
156 }
157 }
158 closedir(dir);
159
160 return total_cpu;
161}
162
163} // namespace
164
165// static
166ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
167 return new ProcessMetrics(process);
168}
169
170// On linux, we return vsize.
171size_t ProcessMetrics::GetPagefileUsage() const {
172 return internal::ReadProcStatsAndGetFieldAsSizeT(process_,
173 internal::VM_VSIZE);
174}
175
176// On linux, we return the high water mark of vsize.
177size_t ProcessMetrics::GetPeakPagefileUsage() const {
178 return ReadProcStatusAndGetFieldAsSizeT(process_, "VmPeak") * 1024;
179}
180
181// On linux, we return RSS.
182size_t ProcessMetrics::GetWorkingSetSize() const {
183 return internal::ReadProcStatsAndGetFieldAsSizeT(process_, internal::VM_RSS) *
184 getpagesize();
185}
186
187// On linux, we return the high water mark of RSS.
188size_t ProcessMetrics::GetPeakWorkingSetSize() const {
189 return ReadProcStatusAndGetFieldAsSizeT(process_, "VmHWM") * 1024;
190}
191
192bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes,
193 size_t* shared_bytes) {
194 WorkingSetKBytes ws_usage;
195 if (!GetWorkingSetKBytes(&ws_usage))
196 return false;
197
198 if (private_bytes)
199 *private_bytes = ws_usage.priv * 1024;
200
201 if (shared_bytes)
202 *shared_bytes = ws_usage.shared * 1024;
203
204 return true;
205}
206
rsesek@chromium.org32f5e9a2013-05-23 12:59:54207bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const {
davemoore@chromium.org7b9c98872013-05-29 15:42:04208#if defined(OS_CHROMEOS)
209 if (GetWorkingSetKBytesTotmaps(ws_usage))
210 return true;
211#endif
212 return GetWorkingSetKBytesStatm(ws_usage);
rsesek@chromium.org32f5e9a2013-05-23 12:59:54213}
214
215double ProcessMetrics::GetCPUUsage() {
thakis@chromium.orge21c3322014-04-06 21:25:01216 TimeTicks time = TimeTicks::Now();
rsesek@chromium.org32f5e9a2013-05-23 12:59:54217
thakis@chromium.orge21c3322014-04-06 21:25:01218 if (last_cpu_ == 0) {
rsesek@chromium.org32f5e9a2013-05-23 12:59:54219 // First call, just set the last values.
thakis@chromium.orgac6d0652014-01-14 00:06:37220 last_cpu_time_ = time;
rsesek@chromium.org32f5e9a2013-05-23 12:59:54221 last_cpu_ = GetProcessCPU(process_);
afakhry8c03da072015-12-03 01:26:19222 return 0.0;
rsesek@chromium.org32f5e9a2013-05-23 12:59:54223 }
224
afakhry8c03da072015-12-03 01:26:19225 TimeDelta time_delta = time - last_cpu_time_;
226 if (time_delta.is_zero()) {
227 NOTREACHED();
228 return 0.0;
229 }
rsesek@chromium.org32f5e9a2013-05-23 12:59:54230
231 int cpu = GetProcessCPU(process_);
232
233 // We have the number of jiffies in the time period. Convert to percentage.
234 // Note this means we will go *over* 100 in the case where multiple threads
235 // are together adding to more than one CPU's worth.
simonjam@chromium.org36e8fd42013-08-08 17:24:18236 TimeDelta cpu_time = internal::ClockTicksToTimeDelta(cpu);
237 TimeDelta last_cpu_time = internal::ClockTicksToTimeDelta(last_cpu_);
afakhry8c03da072015-12-03 01:26:19238
239 // If the number of threads running in the process has decreased since the
240 // last time this function was called, |last_cpu_time| will be greater than
241 // |cpu_time| which will result in a negative value in the below percentage
242 // calculation. We prevent this by clamping to 0. crbug.com/546565.
243 // This computation is known to be shaky when threads are destroyed between
244 // "last" and "now", but for our current purposes, it's all right.
245 double percentage = 0.0;
246 if (last_cpu_time < cpu_time) {
247 percentage = 100.0 * (cpu_time - last_cpu_time).InSecondsF() /
248 time_delta.InSecondsF();
249 }
rsesek@chromium.org32f5e9a2013-05-23 12:59:54250
thakis@chromium.orgac6d0652014-01-14 00:06:37251 last_cpu_time_ = time;
rsesek@chromium.org32f5e9a2013-05-23 12:59:54252 last_cpu_ = cpu;
253
254 return percentage;
255}
256
257// To have /proc/self/io file you must enable CONFIG_TASK_IO_ACCOUNTING
258// in your kernel configuration.
259bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
thestig75844fdb2014-09-09 19:47:10260 // Synchronously reading files in /proc does not hit the disk.
rsesek@chromium.org32f5e9a2013-05-23 12:59:54261 ThreadRestrictions::ScopedAllowIO allow_io;
262
263 std::string proc_io_contents;
264 FilePath io_file = internal::GetProcPidDir(process_).Append("io");
brettw@chromium.org82f84b92013-08-30 18:23:50265 if (!ReadFileToString(io_file, &proc_io_contents))
rsesek@chromium.org32f5e9a2013-05-23 12:59:54266 return false;
267
thestiga0d051ed2014-09-08 21:41:17268 io_counters->OtherOperationCount = 0;
269 io_counters->OtherTransferCount = 0;
rsesek@chromium.org32f5e9a2013-05-23 12:59:54270
thestig75844fdb2014-09-09 19:47:10271 StringPairs pairs;
thestiga0d051ed2014-09-08 21:41:17272 SplitStringIntoKeyValuePairs(proc_io_contents, ':', '\n', &pairs);
thestig75844fdb2014-09-09 19:47:10273 TrimKeyValuePairs(&pairs);
thestiga0d051ed2014-09-08 21:41:17274 for (size_t i = 0; i < pairs.size(); ++i) {
thestig75844fdb2014-09-09 19:47:10275 const std::string& key = pairs[i].first;
276 const std::string& value_str = pairs[i].second;
avibeced7c2015-12-24 06:47:59277 uint64_t* target_counter = NULL;
thestiga0d051ed2014-09-08 21:41:17278 if (key == "syscr")
279 target_counter = &io_counters->ReadOperationCount;
280 else if (key == "syscw")
281 target_counter = &io_counters->WriteOperationCount;
282 else if (key == "rchar")
283 target_counter = &io_counters->ReadTransferCount;
284 else if (key == "wchar")
285 target_counter = &io_counters->WriteTransferCount;
286 if (!target_counter)
287 continue;
288 bool converted = StringToUint64(value_str, target_counter);
289 DCHECK(converted);
rsesek@chromium.org32f5e9a2013-05-23 12:59:54290 }
291 return true;
292}
293
afakhry43b3bb72015-12-15 21:57:59294#if defined(OS_LINUX)
295int ProcessMetrics::GetOpenFdCount() const {
296 // Use /proc/<pid>/fd to count the number of entries there.
297 FilePath fd_path = internal::GetProcPidDir(process_).Append("fd");
298
thestigcf4c85b2015-12-16 08:33:30299 DirReaderPosix dir_reader(fd_path.value().c_str());
300 if (!dir_reader.IsValid())
afakhry43b3bb72015-12-15 21:57:59301 return -1;
afakhry43b3bb72015-12-15 21:57:59302
303 int total_count = 0;
thestigcf4c85b2015-12-16 08:33:30304 for (; dir_reader.Next(); ) {
305 const char* name = dir_reader.name();
306 if (strcmp(name, ".") != 0 && strcmp(name, "..") != 0)
307 ++total_count;
308 }
afakhry43b3bb72015-12-15 21:57:59309
310 return total_count;
311}
312#endif // defined(OS_LINUX)
313
rsesek@chromium.org32f5e9a2013-05-23 12:59:54314ProcessMetrics::ProcessMetrics(ProcessHandle process)
315 : process_(process),
rsesek@chromium.org32f5e9a2013-05-23 12:59:54316 last_system_time_(0),
thestig75844fdb2014-09-09 19:47:10317#if defined(OS_LINUX)
318 last_absolute_idle_wakeups_(0),
319#endif
rsesek@chromium.org32f5e9a2013-05-23 12:59:54320 last_cpu_(0) {
thestiga0d051ed2014-09-08 21:41:17321 processor_count_ = SysInfo::NumberOfProcessors();
davemoore@chromium.orgc8db21c2013-05-28 20:16:49322}
323
davemoore@chromium.org7b9c98872013-05-29 15:42:04324#if defined(OS_CHROMEOS)
325// Private, Shared and Proportional working set sizes are obtained from
326// /proc/<pid>/totmaps
327bool ProcessMetrics::GetWorkingSetKBytesTotmaps(WorkingSetKBytes *ws_usage)
328 const {
329 // The format of /proc/<pid>/totmaps is:
330 //
331 // Rss: 6120 kB
332 // Pss: 3335 kB
333 // Shared_Clean: 1008 kB
334 // Shared_Dirty: 4012 kB
335 // Private_Clean: 4 kB
336 // Private_Dirty: 1096 kB
davemoore@chromium.org23deabb72013-07-16 21:55:20337 // Referenced: XXX kB
338 // Anonymous: XXX kB
339 // AnonHugePages: XXX kB
340 // Swap: XXX kB
341 // Locked: XXX kB
342 const size_t kPssIndex = (1 * 3) + 1;
343 const size_t kPrivate_CleanIndex = (4 * 3) + 1;
344 const size_t kPrivate_DirtyIndex = (5 * 3) + 1;
345 const size_t kSwapIndex = (9 * 3) + 1;
davemoore@chromium.org7b9c98872013-05-29 15:42:04346
347 std::string totmaps_data;
348 {
349 FilePath totmaps_file = internal::GetProcPidDir(process_).Append("totmaps");
350 ThreadRestrictions::ScopedAllowIO allow_io;
brettw@chromium.org82f84b92013-08-30 18:23:50351 bool ret = ReadFileToString(totmaps_file, &totmaps_data);
davemoore@chromium.org7b9c98872013-05-29 15:42:04352 if (!ret || totmaps_data.length() == 0)
353 return false;
354 }
355
brettw83dc1612015-08-12 07:31:18356 std::vector<std::string> totmaps_fields = SplitString(
357 totmaps_data, base::kWhitespaceASCII, base::KEEP_WHITESPACE,
358 base::SPLIT_WANT_NONEMPTY);
davemoore@chromium.org7b9c98872013-05-29 15:42:04359
360 DCHECK_EQ("Pss:", totmaps_fields[kPssIndex-1]);
davemoore@chromium.org23deabb72013-07-16 21:55:20361 DCHECK_EQ("Private_Clean:", totmaps_fields[kPrivate_CleanIndex - 1]);
362 DCHECK_EQ("Private_Dirty:", totmaps_fields[kPrivate_DirtyIndex - 1]);
363 DCHECK_EQ("Swap:", totmaps_fields[kSwapIndex-1]);
davemoore@chromium.org7b9c98872013-05-29 15:42:04364
davemoore@chromium.org23deabb72013-07-16 21:55:20365 int pss = 0;
366 int private_clean = 0;
367 int private_dirty = 0;
368 int swap = 0;
davemoore@chromium.org7b9c98872013-05-29 15:42:04369 bool ret = true;
370 ret &= StringToInt(totmaps_fields[kPssIndex], &pss);
371 ret &= StringToInt(totmaps_fields[kPrivate_CleanIndex], &private_clean);
372 ret &= StringToInt(totmaps_fields[kPrivate_DirtyIndex], &private_dirty);
davemoore@chromium.org23deabb72013-07-16 21:55:20373 ret &= StringToInt(totmaps_fields[kSwapIndex], &swap);
davemoore@chromium.org7b9c98872013-05-29 15:42:04374
davemoore@chromium.org23deabb72013-07-16 21:55:20375 // On ChromeOS swap is to zram. We count this as private / shared, as
376 // increased swap decreases available RAM to user processes, which would
377 // otherwise create surprising results.
378 ws_usage->priv = private_clean + private_dirty + swap;
379 ws_usage->shared = pss + swap;
davemoore@chromium.org7b9c98872013-05-29 15:42:04380 ws_usage->shareable = 0;
davemoore@chromium.org23deabb72013-07-16 21:55:20381 ws_usage->swapped = swap;
davemoore@chromium.org7b9c98872013-05-29 15:42:04382 return ret;
383}
384#endif
385
386// Private and Shared working set sizes are obtained from /proc/<pid>/statm.
387bool ProcessMetrics::GetWorkingSetKBytesStatm(WorkingSetKBytes* ws_usage)
388 const {
389 // Use statm instead of smaps because smaps is:
390 // a) Large and slow to parse.
391 // b) Unavailable in the SUID sandbox.
392
393 // First we need to get the page size, since everything is measured in pages.
394 // For details, see: man 5 proc.
395 const int page_size_kb = getpagesize() / 1024;
396 if (page_size_kb <= 0)
397 return false;
398
399 std::string statm;
400 {
401 FilePath statm_file = internal::GetProcPidDir(process_).Append("statm");
thestig75844fdb2014-09-09 19:47:10402 // Synchronously reading files in /proc does not hit the disk.
davemoore@chromium.org7b9c98872013-05-29 15:42:04403 ThreadRestrictions::ScopedAllowIO allow_io;
brettw@chromium.org82f84b92013-08-30 18:23:50404 bool ret = ReadFileToString(statm_file, &statm);
davemoore@chromium.org7b9c98872013-05-29 15:42:04405 if (!ret || statm.length() == 0)
406 return false;
407 }
408
brettw26dab8f02015-08-08 00:28:47409 std::vector<StringPiece> statm_vec = SplitStringPiece(
410 statm, " ", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
davemoore@chromium.org7b9c98872013-05-29 15:42:04411 if (statm_vec.size() != 7)
412 return false; // Not the format we expect.
413
414 int statm_rss, statm_shared;
415 bool ret = true;
416 ret &= StringToInt(statm_vec[1], &statm_rss);
417 ret &= StringToInt(statm_vec[2], &statm_shared);
418
419 ws_usage->priv = (statm_rss - statm_shared) * page_size_kb;
420 ws_usage->shared = statm_shared * page_size_kb;
421
422 // Sharable is not calculated, as it does not provide interesting data.
423 ws_usage->shareable = 0;
424
davemoore@chromium.org23deabb72013-07-16 21:55:20425#if defined(OS_CHROMEOS)
426 // Can't get swapped memory from statm.
427 ws_usage->swapped = 0;
428#endif
429
davemoore@chromium.org7b9c98872013-05-29 15:42:04430 return ret;
431}
432
rsesek@chromium.org32f5e9a2013-05-23 12:59:54433size_t GetSystemCommitCharge() {
434 SystemMemoryInfoKB meminfo;
435 if (!GetSystemMemoryInfo(&meminfo))
436 return 0;
437 return meminfo.total - meminfo.free - meminfo.buffers - meminfo.cached;
438}
439
rsesek@chromium.org32f5e9a2013-05-23 12:59:54440int ParseProcStatCPU(const std::string& input) {
afakhry597a8512015-02-05 00:51:57441 // |input| may be empty if the process disappeared somehow.
442 // e.g. http://crbug.com/145811.
443 if (input.empty())
rsesek@chromium.org32f5e9a2013-05-23 12:59:54444 return -1;
445
afakhry597a8512015-02-05 00:51:57446 size_t start = input.find_last_of(')');
447 if (start == input.npos)
rsesek@chromium.org32f5e9a2013-05-23 12:59:54448 return -1;
afakhry597a8512015-02-05 00:51:57449
450 // Number of spaces remaining until reaching utime's index starting after the
451 // last ')'.
452 int num_spaces_remaining = internal::VM_UTIME - 1;
453
454 size_t i = start;
455 while ((i = input.find(' ', i + 1)) != input.npos) {
456 // Validate the assumption that there aren't any contiguous spaces
457 // in |input| before utime.
458 DCHECK_NE(input[i - 1], ' ');
459 if (--num_spaces_remaining == 0) {
460 int utime = 0;
461 int stime = 0;
462 if (sscanf(&input.data()[i], "%d %d", &utime, &stime) != 2)
463 return -1;
464
465 return utime + stime;
466 }
467 }
468
469 return -1;
rsesek@chromium.org32f5e9a2013-05-23 12:59:54470}
471
jwmak@chromium.org103ff3512013-08-22 07:19:30472const char kProcSelfExe[] = "/proc/self/exe";
473
474int GetNumberOfThreads(ProcessHandle process) {
sheu@chromium.orga98084792014-01-09 01:39:24475 return internal::ReadProcStatsAndGetFieldAsInt64(process,
476 internal::VM_NUMTHREADS);
jwmak@chromium.org103ff3512013-08-22 07:19:30477}
478
rsesek@chromium.org32f5e9a2013-05-23 12:59:54479namespace {
480
nduca@chromium.org669a09332013-08-30 22:59:14481// The format of /proc/diskstats is:
482// Device major number
483// Device minor number
484// Device name
485// Field 1 -- # of reads completed
486// This is the total number of reads completed successfully.
487// Field 2 -- # of reads merged, field 6 -- # of writes merged
488// Reads and writes which are adjacent to each other may be merged for
489// efficiency. Thus two 4K reads may become one 8K read before it is
490// ultimately handed to the disk, and so it will be counted (and queued)
491// as only one I/O. This field lets you know how often this was done.
492// Field 3 -- # of sectors read
493// This is the total number of sectors read successfully.
494// Field 4 -- # of milliseconds spent reading
495// This is the total number of milliseconds spent by all reads (as
496// measured from __make_request() to end_that_request_last()).
497// Field 5 -- # of writes completed
498// This is the total number of writes completed successfully.
499// Field 6 -- # of writes merged
500// See the description of field 2.
501// Field 7 -- # of sectors written
502// This is the total number of sectors written successfully.
503// Field 8 -- # of milliseconds spent writing
504// This is the total number of milliseconds spent by all writes (as
505// measured from __make_request() to end_that_request_last()).
506// Field 9 -- # of I/Os currently in progress
507// The only field that should go to zero. Incremented as requests are
508// given to appropriate struct request_queue and decremented as they
509// finish.
510// Field 10 -- # of milliseconds spent doing I/Os
511// This field increases so long as field 9 is nonzero.
512// Field 11 -- weighted # of milliseconds spent doing I/Os
513// This field is incremented at each I/O start, I/O completion, I/O
514// merge, or read of these stats by the number of I/Os in progress
515// (field 9) times the number of milliseconds spent doing I/O since the
516// last update of this field. This can provide an easy measure of both
517// I/O completion time and the backlog that may be accumulating.
518
519const size_t kDiskDriveName = 2;
520const size_t kDiskReads = 3;
521const size_t kDiskReadsMerged = 4;
522const size_t kDiskSectorsRead = 5;
523const size_t kDiskReadTime = 6;
524const size_t kDiskWrites = 7;
525const size_t kDiskWritesMerged = 8;
526const size_t kDiskSectorsWritten = 9;
527const size_t kDiskWriteTime = 10;
528const size_t kDiskIO = 11;
529const size_t kDiskIOTime = 12;
530const size_t kDiskWeightedIOTime = 13;
531
rsesek@chromium.org32f5e9a2013-05-23 12:59:54532} // namespace
533
jwmak@chromium.org49b0cf82013-09-03 23:46:54534SystemMemoryInfoKB::SystemMemoryInfoKB() {
535 total = 0;
536 free = 0;
halliwellc2eb0f972016-06-17 19:04:52537#if defined(OS_LINUX)
538 available = 0;
539#endif
jwmak@chromium.org49b0cf82013-09-03 23:46:54540 buffers = 0;
541 cached = 0;
542 active_anon = 0;
543 inactive_anon = 0;
544 active_file = 0;
545 inactive_file = 0;
546 swap_total = 0;
547 swap_free = 0;
548 dirty = 0;
549
550 pswpin = 0;
551 pswpout = 0;
552 pgmajfault = 0;
553
554#ifdef OS_CHROMEOS
555 shmem = 0;
556 slab = 0;
557 gem_objects = -1;
558 gem_size = -1;
559#endif
rsesek@chromium.org32f5e9a2013-05-23 12:59:54560}
561
vmpstr7c7877062016-02-18 22:12:24562SystemMemoryInfoKB::SystemMemoryInfoKB(const SystemMemoryInfoKB& other) =
563 default;
564
dcheng093de9b2016-04-04 21:25:51565std::unique_ptr<Value> SystemMemoryInfoKB::ToValue() const {
566 std::unique_ptr<DictionaryValue> res(new DictionaryValue());
jwmak@chromium.orgc2ef94e2013-09-06 13:13:23567
568 res->SetInteger("total", total);
569 res->SetInteger("free", free);
halliwellc2eb0f972016-06-17 19:04:52570#if defined(OS_LINUX)
571 res->SetInteger("available", available);
572#endif
jwmak@chromium.orgc2ef94e2013-09-06 13:13:23573 res->SetInteger("buffers", buffers);
574 res->SetInteger("cached", cached);
575 res->SetInteger("active_anon", active_anon);
576 res->SetInteger("inactive_anon", inactive_anon);
577 res->SetInteger("active_file", active_file);
578 res->SetInteger("inactive_file", inactive_file);
579 res->SetInteger("swap_total", swap_total);
580 res->SetInteger("swap_free", swap_free);
581 res->SetInteger("swap_used", swap_total - swap_free);
582 res->SetInteger("dirty", dirty);
583 res->SetInteger("pswpin", pswpin);
584 res->SetInteger("pswpout", pswpout);
585 res->SetInteger("pgmajfault", pgmajfault);
586#ifdef OS_CHROMEOS
587 res->SetInteger("shmem", shmem);
588 res->SetInteger("slab", slab);
589 res->SetInteger("gem_objects", gem_objects);
590 res->SetInteger("gem_size", gem_size);
591#endif
592
danakj0c8d4aa2015-11-25 05:29:58593 return std::move(res);
jwmak@chromium.orgc2ef94e2013-09-06 13:13:23594}
595
davemoore@chromium.org70baebc2013-11-02 16:58:44596// exposed for testing
597bool ParseProcMeminfo(const std::string& meminfo_data,
598 SystemMemoryInfoKB* meminfo) {
sonnyrao@chromium.orgded8c42b2013-11-05 22:15:03599 // The format of /proc/meminfo is:
600 //
601 // MemTotal: 8235324 kB
602 // MemFree: 1628304 kB
603 // Buffers: 429596 kB
604 // Cached: 4728232 kB
605 // ...
606 // There is no guarantee on the ordering or position
607 // though it doesn't appear to change very often
rsesek@chromium.org32f5e9a2013-05-23 12:59:54608
sonnyrao@chromium.orgded8c42b2013-11-05 22:15:03609 // As a basic sanity check, let's make sure we at least get non-zero
610 // MemTotal value
611 meminfo->total = 0;
rsesek@chromium.org32f5e9a2013-05-23 12:59:54612
brettw37fd9d7d2015-06-24 02:07:16613 for (const StringPiece& line : SplitStringPiece(
614 meminfo_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
615 std::vector<StringPiece> tokens = SplitStringPiece(
616 line, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
sonnyrao@chromium.orgded8c42b2013-11-05 22:15:03617 // HugePages_* only has a number and no suffix so we can't rely on
618 // there being exactly 3 tokens.
thestiga0d051ed2014-09-08 21:41:17619 if (tokens.size() <= 1) {
sonnyrao@chromium.orgded8c42b2013-11-05 22:15:03620 DLOG(WARNING) << "meminfo: tokens: " << tokens.size()
brettw37fd9d7d2015-06-24 02:07:16621 << " malformed line: " << line.as_string();
thestiga0d051ed2014-09-08 21:41:17622 continue;
623 }
624
625 int* target = NULL;
626 if (tokens[0] == "MemTotal:")
627 target = &meminfo->total;
628 else if (tokens[0] == "MemFree:")
629 target = &meminfo->free;
halliwellc2eb0f972016-06-17 19:04:52630#if defined(OS_LINUX)
631 else if (tokens[0] == "MemAvailable:")
632 target = &meminfo->available;
633#endif
thestiga0d051ed2014-09-08 21:41:17634 else if (tokens[0] == "Buffers:")
635 target = &meminfo->buffers;
636 else if (tokens[0] == "Cached:")
637 target = &meminfo->cached;
638 else if (tokens[0] == "Active(anon):")
639 target = &meminfo->active_anon;
640 else if (tokens[0] == "Inactive(anon):")
641 target = &meminfo->inactive_anon;
642 else if (tokens[0] == "Active(file):")
643 target = &meminfo->active_file;
644 else if (tokens[0] == "Inactive(file):")
645 target = &meminfo->inactive_file;
646 else if (tokens[0] == "SwapTotal:")
647 target = &meminfo->swap_total;
648 else if (tokens[0] == "SwapFree:")
649 target = &meminfo->swap_free;
650 else if (tokens[0] == "Dirty:")
651 target = &meminfo->dirty;
652#if defined(OS_CHROMEOS)
653 // Chrome OS has a tweaked kernel that allows us to query Shmem, which is
654 // usually video memory otherwise invisible to the OS.
655 else if (tokens[0] == "Shmem:")
656 target = &meminfo->shmem;
657 else if (tokens[0] == "Slab:")
658 target = &meminfo->slab;
659#endif
660 if (target)
661 StringToInt(tokens[1], target);
sonnyrao@chromium.orgded8c42b2013-11-05 22:15:03662 }
663
664 // Make sure we got a valid MemTotal.
thestiga0d051ed2014-09-08 21:41:17665 return meminfo->total > 0;
davemoore@chromium.org70baebc2013-11-02 16:58:44666}
667
668// exposed for testing
669bool ParseProcVmstat(const std::string& vmstat_data,
670 SystemMemoryInfoKB* meminfo) {
sonnyrao@chromium.orgded8c42b2013-11-05 22:15:03671 // The format of /proc/vmstat is:
672 //
673 // nr_free_pages 299878
674 // nr_inactive_anon 239863
675 // nr_active_anon 1318966
676 // nr_inactive_file 2015629
677 // ...
678 //
679 // We iterate through the whole file because the position of the
680 // fields are dependent on the kernel version and configuration.
681
brettw37fd9d7d2015-06-24 02:07:16682 for (const StringPiece& line : SplitStringPiece(
683 vmstat_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
684 std::vector<StringPiece> tokens = SplitStringPiece(
685 line, " ", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY);
thestiga0d051ed2014-09-08 21:41:17686 if (tokens.size() != 2)
687 continue;
688
689 if (tokens[0] == "pswpin") {
690 StringToInt(tokens[1], &meminfo->pswpin);
691 } else if (tokens[0] == "pswpout") {
692 StringToInt(tokens[1], &meminfo->pswpout);
693 } else if (tokens[0] == "pgmajfault") {
694 StringToInt(tokens[1], &meminfo->pgmajfault);
sonnyrao@chromium.orgded8c42b2013-11-05 22:15:03695 }
696 }
davemoore@chromium.org70baebc2013-11-02 16:58:44697
698 return true;
699}
700
701bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
thestiga0d051ed2014-09-08 21:41:17702 // Synchronously reading files in /proc and /sys are safe.
davemoore@chromium.org70baebc2013-11-02 16:58:44703 ThreadRestrictions::ScopedAllowIO allow_io;
704
705 // Used memory is: total - free - buffers - caches
706 FilePath meminfo_file("/proc/meminfo");
707 std::string meminfo_data;
708 if (!ReadFileToString(meminfo_file, &meminfo_data)) {
709 DLOG(WARNING) << "Failed to open " << meminfo_file.value();
710 return false;
711 }
712
713 if (!ParseProcMeminfo(meminfo_data, meminfo)) {
714 DLOG(WARNING) << "Failed to parse " << meminfo_file.value();
715 return false;
716 }
717
718#if defined(OS_CHROMEOS)
hashimotof3e19a52015-04-17 20:30:35719 // Report on Chrome OS GEM object graphics memory. /run/debugfs_gpu is a
rsesek@chromium.org32f5e9a2013-05-23 12:59:54720 // bind mount into /sys/kernel/debug and synchronously reading the in-memory
721 // files in /sys is fast.
722#if defined(ARCH_CPU_ARM_FAMILY)
hashimotof3e19a52015-04-17 20:30:35723 FilePath geminfo_file("/run/debugfs_gpu/exynos_gem_objects");
rsesek@chromium.org32f5e9a2013-05-23 12:59:54724#else
hashimotof3e19a52015-04-17 20:30:35725 FilePath geminfo_file("/run/debugfs_gpu/i915_gem_objects");
rsesek@chromium.org32f5e9a2013-05-23 12:59:54726#endif
727 std::string geminfo_data;
728 meminfo->gem_objects = -1;
729 meminfo->gem_size = -1;
brettw@chromium.org82f84b92013-08-30 18:23:50730 if (ReadFileToString(geminfo_file, &geminfo_data)) {
rsesek@chromium.org32f5e9a2013-05-23 12:59:54731 int gem_objects = -1;
732 long long gem_size = -1;
733 int num_res = sscanf(geminfo_data.c_str(),
734 "%d objects, %lld bytes",
735 &gem_objects, &gem_size);
736 if (num_res == 2) {
737 meminfo->gem_objects = gem_objects;
738 meminfo->gem_size = gem_size;
739 }
740 }
741
742#if defined(ARCH_CPU_ARM_FAMILY)
743 // Incorporate Mali graphics memory if present.
dbehr@chromium.orgdc5f8fd2013-09-04 04:07:27744 FilePath mali_memory_file("/sys/class/misc/mali0/device/memory");
rsesek@chromium.org32f5e9a2013-05-23 12:59:54745 std::string mali_memory_data;
brettw@chromium.org82f84b92013-08-30 18:23:50746 if (ReadFileToString(mali_memory_file, &mali_memory_data)) {
rsesek@chromium.org32f5e9a2013-05-23 12:59:54747 long long mali_size = -1;
748 int num_res = sscanf(mali_memory_data.c_str(), "%lld bytes", &mali_size);
749 if (num_res == 1)
750 meminfo->gem_size += mali_size;
751 }
752#endif // defined(ARCH_CPU_ARM_FAMILY)
753#endif // defined(OS_CHROMEOS)
754
jwmak@chromium.org49b0cf82013-09-03 23:46:54755 FilePath vmstat_file("/proc/vmstat");
756 std::string vmstat_data;
757 if (!ReadFileToString(vmstat_file, &vmstat_data)) {
758 DLOG(WARNING) << "Failed to open " << vmstat_file.value();
759 return false;
760 }
davemoore@chromium.org70baebc2013-11-02 16:58:44761 if (!ParseProcVmstat(vmstat_data, meminfo)) {
762 DLOG(WARNING) << "Failed to parse " << vmstat_file.value();
763 return false;
764 }
jwmak@chromium.org49b0cf82013-09-03 23:46:54765
rsesek@chromium.org32f5e9a2013-05-23 12:59:54766 return true;
rsesek@chromium.org992a60652013-07-15 18:29:35767}
768
nduca@chromium.org669a09332013-08-30 22:59:14769SystemDiskInfo::SystemDiskInfo() {
770 reads = 0;
771 reads_merged = 0;
772 sectors_read = 0;
773 read_time = 0;
774 writes = 0;
775 writes_merged = 0;
776 sectors_written = 0;
777 write_time = 0;
778 io = 0;
779 io_time = 0;
780 weighted_io_time = 0;
781}
782
vmpstr7c7877062016-02-18 22:12:24783SystemDiskInfo::SystemDiskInfo(const SystemDiskInfo& other) = default;
784
dcheng093de9b2016-04-04 21:25:51785std::unique_ptr<Value> SystemDiskInfo::ToValue() const {
786 std::unique_ptr<DictionaryValue> res(new DictionaryValue());
jwmak@chromium.orgc2ef94e2013-09-06 13:13:23787
avibeced7c2015-12-24 06:47:59788 // Write out uint64_t variables as doubles.
jwmak@chromium.orgc2ef94e2013-09-06 13:13:23789 // Note: this may discard some precision, but for JS there's no other option.
790 res->SetDouble("reads", static_cast<double>(reads));
791 res->SetDouble("reads_merged", static_cast<double>(reads_merged));
792 res->SetDouble("sectors_read", static_cast<double>(sectors_read));
793 res->SetDouble("read_time", static_cast<double>(read_time));
794 res->SetDouble("writes", static_cast<double>(writes));
795 res->SetDouble("writes_merged", static_cast<double>(writes_merged));
796 res->SetDouble("sectors_written", static_cast<double>(sectors_written));
797 res->SetDouble("write_time", static_cast<double>(write_time));
798 res->SetDouble("io", static_cast<double>(io));
799 res->SetDouble("io_time", static_cast<double>(io_time));
800 res->SetDouble("weighted_io_time", static_cast<double>(weighted_io_time));
801
danakj0c8d4aa2015-11-25 05:29:58802 return std::move(res);
jwmak@chromium.orgc2ef94e2013-09-06 13:13:23803}
804
nduca@chromium.org669a09332013-08-30 22:59:14805bool IsValidDiskName(const std::string& candidate) {
806 if (candidate.length() < 3)
807 return false;
thestiga0d051ed2014-09-08 21:41:17808 if (candidate[1] == 'd' &&
809 (candidate[0] == 'h' || candidate[0] == 's' || candidate[0] == 'v')) {
810 // [hsv]d[a-z]+ case
811 for (size_t i = 2; i < candidate.length(); ++i) {
nduca@chromium.org669a09332013-08-30 22:59:14812 if (!islower(candidate[i]))
813 return false;
814 }
thestiga0d051ed2014-09-08 21:41:17815 return true;
nduca@chromium.org669a09332013-08-30 22:59:14816 }
817
thestiga0d051ed2014-09-08 21:41:17818 const char kMMCName[] = "mmcblk";
819 const size_t kMMCNameLen = strlen(kMMCName);
820 if (candidate.length() < kMMCNameLen + 1)
821 return false;
822 if (candidate.compare(0, kMMCNameLen, kMMCName) != 0)
823 return false;
824
825 // mmcblk[0-9]+ case
826 for (size_t i = kMMCNameLen; i < candidate.length(); ++i) {
827 if (!isdigit(candidate[i]))
828 return false;
829 }
nduca@chromium.org669a09332013-08-30 22:59:14830 return true;
831}
832
833bool GetSystemDiskInfo(SystemDiskInfo* diskinfo) {
thestig75844fdb2014-09-09 19:47:10834 // Synchronously reading files in /proc does not hit the disk.
nduca@chromium.org669a09332013-08-30 22:59:14835 ThreadRestrictions::ScopedAllowIO allow_io;
836
837 FilePath diskinfo_file("/proc/diskstats");
838 std::string diskinfo_data;
839 if (!ReadFileToString(diskinfo_file, &diskinfo_data)) {
840 DLOG(WARNING) << "Failed to open " << diskinfo_file.value();
841 return false;
842 }
843
brettw37fd9d7d2015-06-24 02:07:16844 std::vector<StringPiece> diskinfo_lines = SplitStringPiece(
845 diskinfo_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY);
846 if (diskinfo_lines.size() == 0) {
nduca@chromium.org669a09332013-08-30 22:59:14847 DLOG(WARNING) << "No lines found";
848 return false;
849 }
850
851 diskinfo->reads = 0;
852 diskinfo->reads_merged = 0;
853 diskinfo->sectors_read = 0;
854 diskinfo->read_time = 0;
855 diskinfo->writes = 0;
856 diskinfo->writes_merged = 0;
857 diskinfo->sectors_written = 0;
858 diskinfo->write_time = 0;
859 diskinfo->io = 0;
860 diskinfo->io_time = 0;
861 diskinfo->weighted_io_time = 0;
862
avibeced7c2015-12-24 06:47:59863 uint64_t reads = 0;
864 uint64_t reads_merged = 0;
865 uint64_t sectors_read = 0;
866 uint64_t read_time = 0;
867 uint64_t writes = 0;
868 uint64_t writes_merged = 0;
869 uint64_t sectors_written = 0;
870 uint64_t write_time = 0;
871 uint64_t io = 0;
872 uint64_t io_time = 0;
873 uint64_t weighted_io_time = 0;
nduca@chromium.org669a09332013-08-30 22:59:14874
brettw37fd9d7d2015-06-24 02:07:16875 for (const StringPiece& line : diskinfo_lines) {
876 std::vector<StringPiece> disk_fields = SplitStringPiece(
877 line, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
nduca@chromium.org669a09332013-08-30 22:59:14878
879 // Fields may have overflowed and reset to zero.
brettw37fd9d7d2015-06-24 02:07:16880 if (IsValidDiskName(disk_fields[kDiskDriveName].as_string())) {
nduca@chromium.org669a09332013-08-30 22:59:14881 StringToUint64(disk_fields[kDiskReads], &reads);
882 StringToUint64(disk_fields[kDiskReadsMerged], &reads_merged);
883 StringToUint64(disk_fields[kDiskSectorsRead], &sectors_read);
884 StringToUint64(disk_fields[kDiskReadTime], &read_time);
885 StringToUint64(disk_fields[kDiskWrites], &writes);
886 StringToUint64(disk_fields[kDiskWritesMerged], &writes_merged);
887 StringToUint64(disk_fields[kDiskSectorsWritten], &sectors_written);
888 StringToUint64(disk_fields[kDiskWriteTime], &write_time);
889 StringToUint64(disk_fields[kDiskIO], &io);
890 StringToUint64(disk_fields[kDiskIOTime], &io_time);
891 StringToUint64(disk_fields[kDiskWeightedIOTime], &weighted_io_time);
892
893 diskinfo->reads += reads;
894 diskinfo->reads_merged += reads_merged;
895 diskinfo->sectors_read += sectors_read;
896 diskinfo->read_time += read_time;
897 diskinfo->writes += writes;
898 diskinfo->writes_merged += writes_merged;
899 diskinfo->sectors_written += sectors_written;
900 diskinfo->write_time += write_time;
901 diskinfo->io += io;
902 diskinfo->io_time += io_time;
903 diskinfo->weighted_io_time += weighted_io_time;
904 }
905 }
906
907 return true;
908}
909
nduca@chromium.orgf4134782013-08-29 21:25:20910#if defined(OS_CHROMEOS)
dcheng093de9b2016-04-04 21:25:51911std::unique_ptr<Value> SwapInfo::ToValue() const {
912 std::unique_ptr<DictionaryValue> res(new DictionaryValue());
jwmak@chromium.orgc2ef94e2013-09-06 13:13:23913
avibeced7c2015-12-24 06:47:59914 // Write out uint64_t variables as doubles.
jwmak@chromium.orgc2ef94e2013-09-06 13:13:23915 // Note: this may discard some precision, but for JS there's no other option.
916 res->SetDouble("num_reads", static_cast<double>(num_reads));
917 res->SetDouble("num_writes", static_cast<double>(num_writes));
918 res->SetDouble("orig_data_size", static_cast<double>(orig_data_size));
919 res->SetDouble("compr_data_size", static_cast<double>(compr_data_size));
920 res->SetDouble("mem_used_total", static_cast<double>(mem_used_total));
921 if (compr_data_size > 0)
922 res->SetDouble("compression_ratio", static_cast<double>(orig_data_size) /
923 static_cast<double>(compr_data_size));
924 else
925 res->SetDouble("compression_ratio", 0);
926
danakj0c8d4aa2015-11-25 05:29:58927 return std::move(res);
jwmak@chromium.orgc2ef94e2013-09-06 13:13:23928}
929
nduca@chromium.orgf4134782013-08-29 21:25:20930void GetSwapInfo(SwapInfo* swap_info) {
thestig75844fdb2014-09-09 19:47:10931 // Synchronously reading files in /sys/block/zram0 does not hit the disk.
nduca@chromium.orgf4134782013-08-29 21:25:20932 ThreadRestrictions::ScopedAllowIO allow_io;
933
thestiga0d051ed2014-09-08 21:41:17934 FilePath zram_path("/sys/block/zram0");
avibeced7c2015-12-24 06:47:59935 uint64_t orig_data_size =
936 ReadFileToUint64(zram_path.Append("orig_data_size"));
nduca@chromium.orgf4134782013-08-29 21:25:20937 if (orig_data_size <= 4096) {
938 // A single page is compressed at startup, and has a high compression
939 // ratio. We ignore this as it doesn't indicate any real swapping.
940 swap_info->orig_data_size = 0;
941 swap_info->num_reads = 0;
942 swap_info->num_writes = 0;
943 swap_info->compr_data_size = 0;
944 swap_info->mem_used_total = 0;
945 return;
946 }
947 swap_info->orig_data_size = orig_data_size;
948 swap_info->num_reads = ReadFileToUint64(zram_path.Append("num_reads"));
949 swap_info->num_writes = ReadFileToUint64(zram_path.Append("num_writes"));
950 swap_info->compr_data_size =
951 ReadFileToUint64(zram_path.Append("compr_data_size"));
952 swap_info->mem_used_total =
953 ReadFileToUint64(zram_path.Append("mem_used_total"));
954}
955#endif // defined(OS_CHROMEOS)
956
thestig75844fdb2014-09-09 19:47:10957#if defined(OS_LINUX)
958int ProcessMetrics::GetIdleWakeupsPerSecond() {
avibeced7c2015-12-24 06:47:59959 uint64_t wake_ups;
thestig75844fdb2014-09-09 19:47:10960 const char kWakeupStat[] = "se.statistics.nr_wakeups";
961 return ReadProcSchedAndGetFieldAsUint64(process_, kWakeupStat, &wake_ups) ?
962 CalculateIdleWakeupsPerSecond(wake_ups) : 0;
963}
964#endif // defined(OS_LINUX)
965
rsesek@chromium.org32f5e9a2013-05-23 12:59:54966} // namespace base