• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
5 #include "base/process/process_metrics.h"
6 
7 #include <dirent.h>
8 #include <fcntl.h>
9 #include <sys/stat.h>
10 #include <sys/time.h>
11 #include <sys/types.h>
12 #include <unistd.h>
13 
14 #include "base/file_util.h"
15 #include "base/logging.h"
16 #include "base/process/internal_linux.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_split.h"
19 #include "base/strings/string_tokenizer.h"
20 #include "base/strings/string_util.h"
21 #include "base/sys_info.h"
22 #include "base/threading/thread_restrictions.h"
23 
24 namespace base {
25 
26 namespace {
27 
28 enum ParsingState {
29   KEY_NAME,
30   KEY_VALUE
31 };
32 
33 #ifdef OS_CHROMEOS
34 // Read a file with a single number string and return the number as a uint64.
ReadFileToUint64(const base::FilePath file)35 static uint64 ReadFileToUint64(const base::FilePath file) {
36   std::string file_as_string;
37   if (!ReadFileToString(file, &file_as_string))
38     return 0;
39   TrimWhitespaceASCII(file_as_string, TRIM_ALL, &file_as_string);
40   uint64 file_as_uint64 = 0;
41   if (!base::StringToUint64(file_as_string, &file_as_uint64))
42     return 0;
43   return file_as_uint64;
44 }
45 #endif
46 
47 // Read /proc/<pid>/status and returns the value for |field|, or 0 on failure.
48 // Only works for fields in the form of "Field: value kB".
ReadProcStatusAndGetFieldAsSizeT(pid_t pid,const std::string & field)49 size_t ReadProcStatusAndGetFieldAsSizeT(pid_t pid, const std::string& field) {
50   FilePath stat_file = internal::GetProcPidDir(pid).Append("status");
51   std::string status;
52   {
53     // Synchronously reading files in /proc is safe.
54     ThreadRestrictions::ScopedAllowIO allow_io;
55     if (!ReadFileToString(stat_file, &status))
56       return 0;
57   }
58 
59   StringTokenizer tokenizer(status, ":\n");
60   ParsingState state = KEY_NAME;
61   StringPiece last_key_name;
62   while (tokenizer.GetNext()) {
63     switch (state) {
64       case KEY_NAME:
65         last_key_name = tokenizer.token_piece();
66         state = KEY_VALUE;
67         break;
68       case KEY_VALUE:
69         DCHECK(!last_key_name.empty());
70         if (last_key_name == field) {
71           std::string value_str;
72           tokenizer.token_piece().CopyToString(&value_str);
73           std::string value_str_trimmed;
74           TrimWhitespaceASCII(value_str, TRIM_ALL, &value_str_trimmed);
75           std::vector<std::string> split_value_str;
76           SplitString(value_str_trimmed, ' ', &split_value_str);
77           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;
87         }
88         state = KEY_NAME;
89         break;
90     }
91   }
92   NOTREACHED();
93   return 0;
94 }
95 
96 // Get the total CPU of a single process.  Return value is number of jiffies
97 // on success or -1 on error.
GetProcessCPU(pid_t pid)98 int GetProcessCPU(pid_t pid) {
99   // Use /proc/<pid>/task to find all threads and parse their /stat file.
100   FilePath task_path = internal::GetProcPidDir(pid).Append("task");
101 
102   DIR* dir = opendir(task_path.value().c_str());
103   if (!dir) {
104     DPLOG(ERROR) << "opendir(" << task_path.value() << ")";
105     return -1;
106   }
107 
108   int total_cpu = 0;
109   while (struct dirent* ent = readdir(dir)) {
110     pid_t tid = internal::ProcDirSlotToPid(ent->d_name);
111     if (!tid)
112       continue;
113 
114     // Synchronously reading files in /proc is safe.
115     ThreadRestrictions::ScopedAllowIO allow_io;
116 
117     std::string stat;
118     FilePath stat_path =
119         task_path.Append(ent->d_name).Append(internal::kStatFile);
120     if (ReadFileToString(stat_path, &stat)) {
121       int cpu = ParseProcStatCPU(stat);
122       if (cpu > 0)
123         total_cpu += cpu;
124     }
125   }
126   closedir(dir);
127 
128   return total_cpu;
129 }
130 
131 }  // namespace
132 
133 // static
CreateProcessMetrics(ProcessHandle process)134 ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
135   return new ProcessMetrics(process);
136 }
137 
138 // On linux, we return vsize.
GetPagefileUsage() const139 size_t ProcessMetrics::GetPagefileUsage() const {
140   return internal::ReadProcStatsAndGetFieldAsSizeT(process_,
141                                                    internal::VM_VSIZE);
142 }
143 
144 // On linux, we return the high water mark of vsize.
GetPeakPagefileUsage() const145 size_t ProcessMetrics::GetPeakPagefileUsage() const {
146   return ReadProcStatusAndGetFieldAsSizeT(process_, "VmPeak") * 1024;
147 }
148 
149 // On linux, we return RSS.
GetWorkingSetSize() const150 size_t ProcessMetrics::GetWorkingSetSize() const {
151   return internal::ReadProcStatsAndGetFieldAsSizeT(process_, internal::VM_RSS) *
152       getpagesize();
153 }
154 
155 // On linux, we return the high water mark of RSS.
GetPeakWorkingSetSize() const156 size_t ProcessMetrics::GetPeakWorkingSetSize() const {
157   return ReadProcStatusAndGetFieldAsSizeT(process_, "VmHWM") * 1024;
158 }
159 
GetMemoryBytes(size_t * private_bytes,size_t * shared_bytes)160 bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes,
161                                     size_t* shared_bytes) {
162   WorkingSetKBytes ws_usage;
163   if (!GetWorkingSetKBytes(&ws_usage))
164     return false;
165 
166   if (private_bytes)
167     *private_bytes = ws_usage.priv * 1024;
168 
169   if (shared_bytes)
170     *shared_bytes = ws_usage.shared * 1024;
171 
172   return true;
173 }
174 
GetWorkingSetKBytes(WorkingSetKBytes * ws_usage) const175 bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const {
176 #if defined(OS_CHROMEOS)
177   if (GetWorkingSetKBytesTotmaps(ws_usage))
178     return true;
179 #endif
180   return GetWorkingSetKBytesStatm(ws_usage);
181 }
182 
GetCPUUsage()183 double ProcessMetrics::GetCPUUsage() {
184   struct timeval now;
185   int retval = gettimeofday(&now, NULL);
186   if (retval)
187     return 0;
188   int64 time = TimeValToMicroseconds(now);
189 
190   if (last_time_ == 0) {
191     // First call, just set the last values.
192     last_time_ = time;
193     last_cpu_ = GetProcessCPU(process_);
194     return 0;
195   }
196 
197   int64 time_delta = time - last_time_;
198   DCHECK_NE(time_delta, 0);
199   if (time_delta == 0)
200     return 0;
201 
202   int cpu = GetProcessCPU(process_);
203 
204   // We have the number of jiffies in the time period.  Convert to percentage.
205   // Note this means we will go *over* 100 in the case where multiple threads
206   // are together adding to more than one CPU's worth.
207   TimeDelta cpu_time = internal::ClockTicksToTimeDelta(cpu);
208   TimeDelta last_cpu_time = internal::ClockTicksToTimeDelta(last_cpu_);
209   int percentage = 100 * (cpu_time - last_cpu_time).InSecondsF() /
210       TimeDelta::FromMicroseconds(time_delta).InSecondsF();
211 
212   last_time_ = time;
213   last_cpu_ = cpu;
214 
215   return percentage;
216 }
217 
218 // To have /proc/self/io file you must enable CONFIG_TASK_IO_ACCOUNTING
219 // in your kernel configuration.
GetIOCounters(IoCounters * io_counters) const220 bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
221   // Synchronously reading files in /proc is safe.
222   ThreadRestrictions::ScopedAllowIO allow_io;
223 
224   std::string proc_io_contents;
225   FilePath io_file = internal::GetProcPidDir(process_).Append("io");
226   if (!ReadFileToString(io_file, &proc_io_contents))
227     return false;
228 
229   (*io_counters).OtherOperationCount = 0;
230   (*io_counters).OtherTransferCount = 0;
231 
232   StringTokenizer tokenizer(proc_io_contents, ": \n");
233   ParsingState state = KEY_NAME;
234   StringPiece last_key_name;
235   while (tokenizer.GetNext()) {
236     switch (state) {
237       case KEY_NAME:
238         last_key_name = tokenizer.token_piece();
239         state = KEY_VALUE;
240         break;
241       case KEY_VALUE:
242         DCHECK(!last_key_name.empty());
243         if (last_key_name == "syscr") {
244           StringToInt64(tokenizer.token_piece(),
245               reinterpret_cast<int64*>(&(*io_counters).ReadOperationCount));
246         } else if (last_key_name == "syscw") {
247           StringToInt64(tokenizer.token_piece(),
248               reinterpret_cast<int64*>(&(*io_counters).WriteOperationCount));
249         } else if (last_key_name == "rchar") {
250           StringToInt64(tokenizer.token_piece(),
251               reinterpret_cast<int64*>(&(*io_counters).ReadTransferCount));
252         } else if (last_key_name == "wchar") {
253           StringToInt64(tokenizer.token_piece(),
254               reinterpret_cast<int64*>(&(*io_counters).WriteTransferCount));
255         }
256         state = KEY_NAME;
257         break;
258     }
259   }
260   return true;
261 }
262 
ProcessMetrics(ProcessHandle process)263 ProcessMetrics::ProcessMetrics(ProcessHandle process)
264     : process_(process),
265       last_time_(0),
266       last_system_time_(0),
267       last_cpu_(0) {
268   processor_count_ = base::SysInfo::NumberOfProcessors();
269 }
270 
271 #if defined(OS_CHROMEOS)
272 // Private, Shared and Proportional working set sizes are obtained from
273 // /proc/<pid>/totmaps
GetWorkingSetKBytesTotmaps(WorkingSetKBytes * ws_usage) const274 bool ProcessMetrics::GetWorkingSetKBytesTotmaps(WorkingSetKBytes *ws_usage)
275   const {
276   // The format of /proc/<pid>/totmaps is:
277   //
278   // Rss:                6120 kB
279   // Pss:                3335 kB
280   // Shared_Clean:       1008 kB
281   // Shared_Dirty:       4012 kB
282   // Private_Clean:         4 kB
283   // Private_Dirty:      1096 kB
284   // Referenced:          XXX kB
285   // Anonymous:           XXX kB
286   // AnonHugePages:       XXX kB
287   // Swap:                XXX kB
288   // Locked:              XXX kB
289   const size_t kPssIndex = (1 * 3) + 1;
290   const size_t kPrivate_CleanIndex = (4 * 3) + 1;
291   const size_t kPrivate_DirtyIndex = (5 * 3) + 1;
292   const size_t kSwapIndex = (9 * 3) + 1;
293 
294   std::string totmaps_data;
295   {
296     FilePath totmaps_file = internal::GetProcPidDir(process_).Append("totmaps");
297     ThreadRestrictions::ScopedAllowIO allow_io;
298     bool ret = ReadFileToString(totmaps_file, &totmaps_data);
299     if (!ret || totmaps_data.length() == 0)
300       return false;
301   }
302 
303   std::vector<std::string> totmaps_fields;
304   SplitStringAlongWhitespace(totmaps_data, &totmaps_fields);
305 
306   DCHECK_EQ("Pss:", totmaps_fields[kPssIndex-1]);
307   DCHECK_EQ("Private_Clean:", totmaps_fields[kPrivate_CleanIndex - 1]);
308   DCHECK_EQ("Private_Dirty:", totmaps_fields[kPrivate_DirtyIndex - 1]);
309   DCHECK_EQ("Swap:", totmaps_fields[kSwapIndex-1]);
310 
311   int pss = 0;
312   int private_clean = 0;
313   int private_dirty = 0;
314   int swap = 0;
315   bool ret = true;
316   ret &= StringToInt(totmaps_fields[kPssIndex], &pss);
317   ret &= StringToInt(totmaps_fields[kPrivate_CleanIndex], &private_clean);
318   ret &= StringToInt(totmaps_fields[kPrivate_DirtyIndex], &private_dirty);
319   ret &= StringToInt(totmaps_fields[kSwapIndex], &swap);
320 
321   // On ChromeOS swap is to zram. We count this as private / shared, as
322   // increased swap decreases available RAM to user processes, which would
323   // otherwise create surprising results.
324   ws_usage->priv = private_clean + private_dirty + swap;
325   ws_usage->shared = pss + swap;
326   ws_usage->shareable = 0;
327   ws_usage->swapped = swap;
328   return ret;
329 }
330 #endif
331 
332 // Private and Shared working set sizes are obtained from /proc/<pid>/statm.
GetWorkingSetKBytesStatm(WorkingSetKBytes * ws_usage) const333 bool ProcessMetrics::GetWorkingSetKBytesStatm(WorkingSetKBytes* ws_usage)
334     const {
335   // Use statm instead of smaps because smaps is:
336   // a) Large and slow to parse.
337   // b) Unavailable in the SUID sandbox.
338 
339   // First we need to get the page size, since everything is measured in pages.
340   // For details, see: man 5 proc.
341   const int page_size_kb = getpagesize() / 1024;
342   if (page_size_kb <= 0)
343     return false;
344 
345   std::string statm;
346   {
347     FilePath statm_file = internal::GetProcPidDir(process_).Append("statm");
348     // Synchronously reading files in /proc is safe.
349     ThreadRestrictions::ScopedAllowIO allow_io;
350     bool ret = ReadFileToString(statm_file, &statm);
351     if (!ret || statm.length() == 0)
352       return false;
353   }
354 
355   std::vector<std::string> statm_vec;
356   SplitString(statm, ' ', &statm_vec);
357   if (statm_vec.size() != 7)
358     return false;  // Not the format we expect.
359 
360   int statm_rss, statm_shared;
361   bool ret = true;
362   ret &= StringToInt(statm_vec[1], &statm_rss);
363   ret &= StringToInt(statm_vec[2], &statm_shared);
364 
365   ws_usage->priv = (statm_rss - statm_shared) * page_size_kb;
366   ws_usage->shared = statm_shared * page_size_kb;
367 
368   // Sharable is not calculated, as it does not provide interesting data.
369   ws_usage->shareable = 0;
370 
371 #if defined(OS_CHROMEOS)
372   // Can't get swapped memory from statm.
373   ws_usage->swapped = 0;
374 #endif
375 
376   return ret;
377 }
378 
GetSystemCommitCharge()379 size_t GetSystemCommitCharge() {
380   SystemMemoryInfoKB meminfo;
381   if (!GetSystemMemoryInfo(&meminfo))
382     return 0;
383   return meminfo.total - meminfo.free - meminfo.buffers - meminfo.cached;
384 }
385 
386 // Exposed for testing.
ParseProcStatCPU(const std::string & input)387 int ParseProcStatCPU(const std::string& input) {
388   std::vector<std::string> proc_stats;
389   if (!internal::ParseProcStats(input, &proc_stats))
390     return -1;
391 
392   if (proc_stats.size() <= internal::VM_STIME)
393     return -1;
394   int utime = GetProcStatsFieldAsInt(proc_stats, internal::VM_UTIME);
395   int stime = GetProcStatsFieldAsInt(proc_stats, internal::VM_STIME);
396   return utime + stime;
397 }
398 
399 const char kProcSelfExe[] = "/proc/self/exe";
400 
GetNumberOfThreads(ProcessHandle process)401 int GetNumberOfThreads(ProcessHandle process) {
402   return internal::ReadProcStatsAndGetFieldAsInt(process,
403                                                  internal::VM_NUMTHREADS);
404 }
405 
406 namespace {
407 
408 // The format of /proc/diskstats is:
409 //  Device major number
410 //  Device minor number
411 //  Device name
412 //  Field  1 -- # of reads completed
413 //      This is the total number of reads completed successfully.
414 //  Field  2 -- # of reads merged, field 6 -- # of writes merged
415 //      Reads and writes which are adjacent to each other may be merged for
416 //      efficiency.  Thus two 4K reads may become one 8K read before it is
417 //      ultimately handed to the disk, and so it will be counted (and queued)
418 //      as only one I/O.  This field lets you know how often this was done.
419 //  Field  3 -- # of sectors read
420 //      This is the total number of sectors read successfully.
421 //  Field  4 -- # of milliseconds spent reading
422 //      This is the total number of milliseconds spent by all reads (as
423 //      measured from __make_request() to end_that_request_last()).
424 //  Field  5 -- # of writes completed
425 //      This is the total number of writes completed successfully.
426 //  Field  6 -- # of writes merged
427 //      See the description of field 2.
428 //  Field  7 -- # of sectors written
429 //      This is the total number of sectors written successfully.
430 //  Field  8 -- # of milliseconds spent writing
431 //      This is the total number of milliseconds spent by all writes (as
432 //      measured from __make_request() to end_that_request_last()).
433 //  Field  9 -- # of I/Os currently in progress
434 //      The only field that should go to zero. Incremented as requests are
435 //      given to appropriate struct request_queue and decremented as they
436 //      finish.
437 //  Field 10 -- # of milliseconds spent doing I/Os
438 //      This field increases so long as field 9 is nonzero.
439 //  Field 11 -- weighted # of milliseconds spent doing I/Os
440 //      This field is incremented at each I/O start, I/O completion, I/O
441 //      merge, or read of these stats by the number of I/Os in progress
442 //      (field 9) times the number of milliseconds spent doing I/O since the
443 //      last update of this field.  This can provide an easy measure of both
444 //      I/O completion time and the backlog that may be accumulating.
445 
446 const size_t kDiskDriveName = 2;
447 const size_t kDiskReads = 3;
448 const size_t kDiskReadsMerged = 4;
449 const size_t kDiskSectorsRead = 5;
450 const size_t kDiskReadTime = 6;
451 const size_t kDiskWrites = 7;
452 const size_t kDiskWritesMerged = 8;
453 const size_t kDiskSectorsWritten = 9;
454 const size_t kDiskWriteTime = 10;
455 const size_t kDiskIO = 11;
456 const size_t kDiskIOTime = 12;
457 const size_t kDiskWeightedIOTime = 13;
458 
459 }  // namespace
460 
SystemMemoryInfoKB()461 SystemMemoryInfoKB::SystemMemoryInfoKB() {
462   total = 0;
463   free = 0;
464   buffers = 0;
465   cached = 0;
466   active_anon = 0;
467   inactive_anon = 0;
468   active_file = 0;
469   inactive_file = 0;
470   swap_total = 0;
471   swap_free = 0;
472   dirty = 0;
473 
474   pswpin = 0;
475   pswpout = 0;
476   pgmajfault = 0;
477 
478 #ifdef OS_CHROMEOS
479   shmem = 0;
480   slab = 0;
481   gem_objects = -1;
482   gem_size = -1;
483 #endif
484 }
485 
ToValue() const486 scoped_ptr<Value> SystemMemoryInfoKB::ToValue() const {
487   scoped_ptr<DictionaryValue> res(new base::DictionaryValue());
488 
489   res->SetInteger("total", total);
490   res->SetInteger("free", free);
491   res->SetInteger("buffers", buffers);
492   res->SetInteger("cached", cached);
493   res->SetInteger("active_anon", active_anon);
494   res->SetInteger("inactive_anon", inactive_anon);
495   res->SetInteger("active_file", active_file);
496   res->SetInteger("inactive_file", inactive_file);
497   res->SetInteger("swap_total", swap_total);
498   res->SetInteger("swap_free", swap_free);
499   res->SetInteger("swap_used", swap_total - swap_free);
500   res->SetInteger("dirty", dirty);
501   res->SetInteger("pswpin", pswpin);
502   res->SetInteger("pswpout", pswpout);
503   res->SetInteger("pgmajfault", pgmajfault);
504 #ifdef OS_CHROMEOS
505   res->SetInteger("shmem", shmem);
506   res->SetInteger("slab", slab);
507   res->SetInteger("gem_objects", gem_objects);
508   res->SetInteger("gem_size", gem_size);
509 #endif
510 
511   return res.PassAs<Value>();
512 }
513 
514 // exposed for testing
ParseProcMeminfo(const std::string & meminfo_data,SystemMemoryInfoKB * meminfo)515 bool ParseProcMeminfo(const std::string& meminfo_data,
516                       SystemMemoryInfoKB* meminfo) {
517   // The format of /proc/meminfo is:
518   //
519   // MemTotal:      8235324 kB
520   // MemFree:       1628304 kB
521   // Buffers:        429596 kB
522   // Cached:        4728232 kB
523   // ...
524   // There is no guarantee on the ordering or position
525   // though it doesn't appear to change very often
526 
527   // As a basic sanity check, let's make sure we at least get non-zero
528   // MemTotal value
529   meminfo->total = 0;
530 
531   std::vector<std::string> meminfo_lines;
532   Tokenize(meminfo_data, "\n", &meminfo_lines);
533   for (std::vector<std::string>::iterator it = meminfo_lines.begin();
534        it != meminfo_lines.end(); ++it) {
535     std::vector<std::string> tokens;
536     SplitStringAlongWhitespace(*it, &tokens);
537     // HugePages_* only has a number and no suffix so we can't rely on
538     // there being exactly 3 tokens.
539     if (tokens.size() > 1) {
540       if (tokens[0] == "MemTotal:") {
541         StringToInt(tokens[1], &meminfo->total);
542         continue;
543       } if (tokens[0] == "MemFree:") {
544         StringToInt(tokens[1], &meminfo->free);
545         continue;
546       } if (tokens[0] == "Buffers:") {
547         StringToInt(tokens[1], &meminfo->buffers);
548         continue;
549       } if (tokens[0] == "Cached:") {
550         StringToInt(tokens[1], &meminfo->cached);
551         continue;
552       } if (tokens[0] == "Active(anon):") {
553         StringToInt(tokens[1], &meminfo->active_anon);
554         continue;
555       } if (tokens[0] == "Inactive(anon):") {
556         StringToInt(tokens[1], &meminfo->inactive_anon);
557         continue;
558       } if (tokens[0] == "Active(file):") {
559         StringToInt(tokens[1], &meminfo->active_file);
560         continue;
561       } if (tokens[0] == "Inactive(file):") {
562         StringToInt(tokens[1], &meminfo->inactive_file);
563         continue;
564       } if (tokens[0] == "SwapTotal:") {
565         StringToInt(tokens[1], &meminfo->swap_total);
566         continue;
567       } if (tokens[0] == "SwapFree:") {
568         StringToInt(tokens[1], &meminfo->swap_free);
569         continue;
570       } if (tokens[0] == "Dirty:") {
571         StringToInt(tokens[1], &meminfo->dirty);
572         continue;
573 #if defined(OS_CHROMEOS)
574       // Chrome OS has a tweaked kernel that allows us to query Shmem, which is
575       // usually video memory otherwise invisible to the OS.
576       } if (tokens[0] == "Shmem:") {
577         StringToInt(tokens[1], &meminfo->shmem);
578         continue;
579       } if (tokens[0] == "Slab:") {
580         StringToInt(tokens[1], &meminfo->slab);
581         continue;
582 #endif
583       }
584     } else
585       DLOG(WARNING) << "meminfo: tokens: " << tokens.size()
586                     << " malformed line: " << *it;
587   }
588 
589   // Make sure we got a valid MemTotal.
590   if (!meminfo->total)
591     return false;
592 
593   return true;
594 }
595 
596 // exposed for testing
ParseProcVmstat(const std::string & vmstat_data,SystemMemoryInfoKB * meminfo)597 bool ParseProcVmstat(const std::string& vmstat_data,
598                      SystemMemoryInfoKB* meminfo) {
599   // The format of /proc/vmstat is:
600   //
601   // nr_free_pages 299878
602   // nr_inactive_anon 239863
603   // nr_active_anon 1318966
604   // nr_inactive_file 2015629
605   // ...
606   //
607   // We iterate through the whole file because the position of the
608   // fields are dependent on the kernel version and configuration.
609 
610   std::vector<std::string> vmstat_lines;
611   Tokenize(vmstat_data, "\n", &vmstat_lines);
612   for (std::vector<std::string>::iterator it = vmstat_lines.begin();
613        it != vmstat_lines.end(); ++it) {
614     std::vector<std::string> tokens;
615     SplitString(*it, ' ', &tokens);
616     if (tokens.size() == 2) {
617       if (tokens[0] == "pswpin") {
618         StringToInt(tokens[1], &meminfo->pswpin);
619         continue;
620       } if (tokens[0] == "pswpout") {
621         StringToInt(tokens[1], &meminfo->pswpout);
622         continue;
623       } if (tokens[0] == "pgmajfault")
624         StringToInt(tokens[1], &meminfo->pgmajfault);
625     }
626   }
627 
628   return true;
629 }
630 
GetSystemMemoryInfo(SystemMemoryInfoKB * meminfo)631 bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
632   // Synchronously reading files in /proc is safe.
633   ThreadRestrictions::ScopedAllowIO allow_io;
634 
635   // Used memory is: total - free - buffers - caches
636   FilePath meminfo_file("/proc/meminfo");
637   std::string meminfo_data;
638   if (!ReadFileToString(meminfo_file, &meminfo_data)) {
639     DLOG(WARNING) << "Failed to open " << meminfo_file.value();
640     return false;
641   }
642 
643   if (!ParseProcMeminfo(meminfo_data, meminfo)) {
644     DLOG(WARNING) << "Failed to parse " << meminfo_file.value();
645     return false;
646   }
647 
648 #if defined(OS_CHROMEOS)
649   // Report on Chrome OS GEM object graphics memory. /var/run/debugfs_gpu is a
650   // bind mount into /sys/kernel/debug and synchronously reading the in-memory
651   // files in /sys is fast.
652 #if defined(ARCH_CPU_ARM_FAMILY)
653   FilePath geminfo_file("/var/run/debugfs_gpu/exynos_gem_objects");
654 #else
655   FilePath geminfo_file("/var/run/debugfs_gpu/i915_gem_objects");
656 #endif
657   std::string geminfo_data;
658   meminfo->gem_objects = -1;
659   meminfo->gem_size = -1;
660   if (ReadFileToString(geminfo_file, &geminfo_data)) {
661     int gem_objects = -1;
662     long long gem_size = -1;
663     int num_res = sscanf(geminfo_data.c_str(),
664                          "%d objects, %lld bytes",
665                          &gem_objects, &gem_size);
666     if (num_res == 2) {
667       meminfo->gem_objects = gem_objects;
668       meminfo->gem_size = gem_size;
669     }
670   }
671 
672 #if defined(ARCH_CPU_ARM_FAMILY)
673   // Incorporate Mali graphics memory if present.
674   FilePath mali_memory_file("/sys/class/misc/mali0/device/memory");
675   std::string mali_memory_data;
676   if (ReadFileToString(mali_memory_file, &mali_memory_data)) {
677     long long mali_size = -1;
678     int num_res = sscanf(mali_memory_data.c_str(), "%lld bytes", &mali_size);
679     if (num_res == 1)
680       meminfo->gem_size += mali_size;
681   }
682 #endif  // defined(ARCH_CPU_ARM_FAMILY)
683 #endif  // defined(OS_CHROMEOS)
684 
685   FilePath vmstat_file("/proc/vmstat");
686   std::string vmstat_data;
687   if (!ReadFileToString(vmstat_file, &vmstat_data)) {
688     DLOG(WARNING) << "Failed to open " << vmstat_file.value();
689     return false;
690   }
691   if (!ParseProcVmstat(vmstat_data, meminfo)) {
692     DLOG(WARNING) << "Failed to parse " << vmstat_file.value();
693     return false;
694   }
695 
696   return true;
697 }
698 
SystemDiskInfo()699 SystemDiskInfo::SystemDiskInfo() {
700   reads = 0;
701   reads_merged = 0;
702   sectors_read = 0;
703   read_time = 0;
704   writes = 0;
705   writes_merged = 0;
706   sectors_written = 0;
707   write_time = 0;
708   io = 0;
709   io_time = 0;
710   weighted_io_time = 0;
711 }
712 
ToValue() const713 scoped_ptr<Value> SystemDiskInfo::ToValue() const {
714   scoped_ptr<DictionaryValue> res(new base::DictionaryValue());
715 
716   // Write out uint64 variables as doubles.
717   // Note: this may discard some precision, but for JS there's no other option.
718   res->SetDouble("reads", static_cast<double>(reads));
719   res->SetDouble("reads_merged", static_cast<double>(reads_merged));
720   res->SetDouble("sectors_read", static_cast<double>(sectors_read));
721   res->SetDouble("read_time", static_cast<double>(read_time));
722   res->SetDouble("writes", static_cast<double>(writes));
723   res->SetDouble("writes_merged", static_cast<double>(writes_merged));
724   res->SetDouble("sectors_written", static_cast<double>(sectors_written));
725   res->SetDouble("write_time", static_cast<double>(write_time));
726   res->SetDouble("io", static_cast<double>(io));
727   res->SetDouble("io_time", static_cast<double>(io_time));
728   res->SetDouble("weighted_io_time", static_cast<double>(weighted_io_time));
729 
730   return res.PassAs<Value>();
731 }
732 
IsValidDiskName(const std::string & candidate)733 bool IsValidDiskName(const std::string& candidate) {
734   if (candidate.length() < 3)
735     return false;
736   if (candidate.substr(0,2) == "sd" || candidate.substr(0,2) == "hd") {
737     // [sh]d[a-z]+ case
738     for (size_t i = 2; i < candidate.length(); i++) {
739       if (!islower(candidate[i]))
740         return false;
741     }
742   } else {
743     if (candidate.length() < 7) {
744       return false;
745     }
746     if (candidate.substr(0,6) == "mmcblk") {
747       // mmcblk[0-9]+ case
748       for (size_t i = 6; i < candidate.length(); i++) {
749         if (!isdigit(candidate[i]))
750           return false;
751       }
752     } else {
753       return false;
754     }
755   }
756 
757   return true;
758 }
759 
GetSystemDiskInfo(SystemDiskInfo * diskinfo)760 bool GetSystemDiskInfo(SystemDiskInfo* diskinfo) {
761   // Synchronously reading files in /proc is safe.
762   ThreadRestrictions::ScopedAllowIO allow_io;
763 
764   FilePath diskinfo_file("/proc/diskstats");
765   std::string diskinfo_data;
766   if (!ReadFileToString(diskinfo_file, &diskinfo_data)) {
767     DLOG(WARNING) << "Failed to open " << diskinfo_file.value();
768     return false;
769   }
770 
771   std::vector<std::string> diskinfo_lines;
772   size_t line_count = Tokenize(diskinfo_data, "\n", &diskinfo_lines);
773   if (line_count == 0) {
774     DLOG(WARNING) << "No lines found";
775     return false;
776   }
777 
778   diskinfo->reads = 0;
779   diskinfo->reads_merged = 0;
780   diskinfo->sectors_read = 0;
781   diskinfo->read_time = 0;
782   diskinfo->writes = 0;
783   diskinfo->writes_merged = 0;
784   diskinfo->sectors_written = 0;
785   diskinfo->write_time = 0;
786   diskinfo->io = 0;
787   diskinfo->io_time = 0;
788   diskinfo->weighted_io_time = 0;
789 
790   uint64 reads = 0;
791   uint64 reads_merged = 0;
792   uint64 sectors_read = 0;
793   uint64 read_time = 0;
794   uint64 writes = 0;
795   uint64 writes_merged = 0;
796   uint64 sectors_written = 0;
797   uint64 write_time = 0;
798   uint64 io = 0;
799   uint64 io_time = 0;
800   uint64 weighted_io_time = 0;
801 
802   for (size_t i = 0; i < line_count; i++) {
803     std::vector<std::string> disk_fields;
804     SplitStringAlongWhitespace(diskinfo_lines[i], &disk_fields);
805 
806     // Fields may have overflowed and reset to zero.
807     if (IsValidDiskName(disk_fields[kDiskDriveName])) {
808       StringToUint64(disk_fields[kDiskReads], &reads);
809       StringToUint64(disk_fields[kDiskReadsMerged], &reads_merged);
810       StringToUint64(disk_fields[kDiskSectorsRead], &sectors_read);
811       StringToUint64(disk_fields[kDiskReadTime], &read_time);
812       StringToUint64(disk_fields[kDiskWrites], &writes);
813       StringToUint64(disk_fields[kDiskWritesMerged], &writes_merged);
814       StringToUint64(disk_fields[kDiskSectorsWritten], &sectors_written);
815       StringToUint64(disk_fields[kDiskWriteTime], &write_time);
816       StringToUint64(disk_fields[kDiskIO], &io);
817       StringToUint64(disk_fields[kDiskIOTime], &io_time);
818       StringToUint64(disk_fields[kDiskWeightedIOTime], &weighted_io_time);
819 
820       diskinfo->reads += reads;
821       diskinfo->reads_merged += reads_merged;
822       diskinfo->sectors_read += sectors_read;
823       diskinfo->read_time += read_time;
824       diskinfo->writes += writes;
825       diskinfo->writes_merged += writes_merged;
826       diskinfo->sectors_written += sectors_written;
827       diskinfo->write_time += write_time;
828       diskinfo->io += io;
829       diskinfo->io_time += io_time;
830       diskinfo->weighted_io_time += weighted_io_time;
831     }
832   }
833 
834   return true;
835 }
836 
837 #if defined(OS_CHROMEOS)
ToValue() const838 scoped_ptr<Value> SwapInfo::ToValue() const {
839   scoped_ptr<DictionaryValue> res(new DictionaryValue());
840 
841   // Write out uint64 variables as doubles.
842   // Note: this may discard some precision, but for JS there's no other option.
843   res->SetDouble("num_reads", static_cast<double>(num_reads));
844   res->SetDouble("num_writes", static_cast<double>(num_writes));
845   res->SetDouble("orig_data_size", static_cast<double>(orig_data_size));
846   res->SetDouble("compr_data_size", static_cast<double>(compr_data_size));
847   res->SetDouble("mem_used_total", static_cast<double>(mem_used_total));
848   if (compr_data_size > 0)
849     res->SetDouble("compression_ratio", static_cast<double>(orig_data_size) /
850                                         static_cast<double>(compr_data_size));
851   else
852     res->SetDouble("compression_ratio", 0);
853 
854   return res.PassAs<Value>();
855 }
856 
GetSwapInfo(SwapInfo * swap_info)857 void GetSwapInfo(SwapInfo* swap_info) {
858   // Synchronously reading files in /sys/block/zram0 is safe.
859   ThreadRestrictions::ScopedAllowIO allow_io;
860 
861   base::FilePath zram_path("/sys/block/zram0");
862   uint64 orig_data_size = ReadFileToUint64(zram_path.Append("orig_data_size"));
863   if (orig_data_size <= 4096) {
864     // A single page is compressed at startup, and has a high compression
865     // ratio. We ignore this as it doesn't indicate any real swapping.
866     swap_info->orig_data_size = 0;
867     swap_info->num_reads = 0;
868     swap_info->num_writes = 0;
869     swap_info->compr_data_size = 0;
870     swap_info->mem_used_total = 0;
871     return;
872   }
873   swap_info->orig_data_size = orig_data_size;
874   swap_info->num_reads = ReadFileToUint64(zram_path.Append("num_reads"));
875   swap_info->num_writes = ReadFileToUint64(zram_path.Append("num_writes"));
876   swap_info->compr_data_size =
877       ReadFileToUint64(zram_path.Append("compr_data_size"));
878   swap_info->mem_used_total =
879       ReadFileToUint64(zram_path.Append("mem_used_total"));
880 }
881 #endif  // defined(OS_CHROMEOS)
882 
883 }  // namespace base
884