• 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 #include "base/process/process_metrics.h"
6 
7 #include <dirent.h>
8 #include <fcntl.h>
9 #include <inttypes.h>
10 #include <stddef.h>
11 #include <stdint.h>
12 #include <sys/stat.h>
13 #include <sys/time.h>
14 #include <sys/types.h>
15 #include <unistd.h>
16 
17 #include <utility>
18 
19 #include "base/cpu.h"
20 #include "base/files/dir_reader_posix.h"
21 #include "base/files/file_util.h"
22 #include "base/logging.h"
23 #include "base/memory/ptr_util.h"
24 #include "base/notreached.h"
25 #include "base/numerics/safe_conversions.h"
26 #include "base/process/internal_linux.h"
27 #include "base/process/process_metrics_iocounters.h"
28 #include "base/strings/string_number_conversions.h"
29 #include "base/strings/string_piece.h"
30 #include "base/strings/string_split.h"
31 #include "base/strings/string_tokenizer.h"
32 #include "base/strings/string_util.h"
33 #include "base/system/sys_info.h"
34 #include "base/threading/thread_restrictions.h"
35 #include "base/values.h"
36 #include "build/build_config.h"
37 #include "third_party/abseil-cpp/absl/strings/ascii.h"
38 #include "third_party/abseil-cpp/absl/types/optional.h"
39 
40 namespace base {
41 
42 class ScopedAllowBlockingForProcessMetrics : public ScopedAllowBlocking {};
43 
44 namespace {
45 
46 #if BUILDFLAG(IS_CHROMEOS)
47 // Read a file with a single number string and return the number as a uint64_t.
ReadFileToUint64(const FilePath & file)48 uint64_t ReadFileToUint64(const FilePath& file) {
49   std::string file_contents;
50   if (!ReadFileToString(file, &file_contents))
51     return 0;
52   TrimWhitespaceASCII(file_contents, TRIM_ALL, &file_contents);
53   uint64_t file_contents_uint64 = 0;
54   if (!StringToUint64(file_contents, &file_contents_uint64))
55     return 0;
56   return file_contents_uint64;
57 }
58 #endif
59 
60 // Get the total CPU from a proc stat buffer.  Return value is number of jiffies
61 // on success or 0 if parsing failed.
ParseTotalCPUTimeFromStats(const std::vector<std::string> & proc_stats)62 int64_t ParseTotalCPUTimeFromStats(const std::vector<std::string>& proc_stats) {
63   return internal::GetProcStatsFieldAsInt64(proc_stats, internal::VM_UTIME) +
64          internal::GetProcStatsFieldAsInt64(proc_stats, internal::VM_STIME);
65 }
66 
67 // Get the total CPU of a single process.  Return value is number of jiffies
68 // on success or -1 on error.
GetProcessCPU(pid_t pid)69 int64_t GetProcessCPU(pid_t pid) {
70   std::string buffer;
71   std::vector<std::string> proc_stats;
72   if (!internal::ReadProcStats(pid, &buffer) ||
73       !internal::ParseProcStats(buffer, &proc_stats)) {
74     return -1;
75   }
76 
77   return ParseTotalCPUTimeFromStats(proc_stats);
78 }
79 
80 }  // namespace
81 
82 // static
CreateProcessMetrics(ProcessHandle process)83 std::unique_ptr<ProcessMetrics> ProcessMetrics::CreateProcessMetrics(
84     ProcessHandle process) {
85   return WrapUnique(new ProcessMetrics(process));
86 }
87 
GetResidentSetSize() const88 size_t ProcessMetrics::GetResidentSetSize() const {
89   return internal::ReadProcStatsAndGetFieldAsSizeT(process_, internal::VM_RSS) *
90          checked_cast<size_t>(getpagesize());
91 }
92 
GetCumulativeCPUUsage()93 TimeDelta ProcessMetrics::GetCumulativeCPUUsage() {
94   return internal::ClockTicksToTimeDelta(GetProcessCPU(process_));
95 }
96 
GetCumulativeCPUUsagePerThread(CPUUsagePerThread & cpu_per_thread)97 bool ProcessMetrics::GetCumulativeCPUUsagePerThread(
98     CPUUsagePerThread& cpu_per_thread) {
99   cpu_per_thread.clear();
100 
101   internal::ForEachProcessTask(
102       process_,
103       [&cpu_per_thread](PlatformThreadId tid, const FilePath& task_path) {
104         FilePath thread_stat_path = task_path.Append("stat");
105 
106         std::string buffer;
107         std::vector<std::string> proc_stats;
108         if (!internal::ReadProcFile(thread_stat_path, &buffer) ||
109             !internal::ParseProcStats(buffer, &proc_stats)) {
110           return;
111         }
112 
113         TimeDelta thread_time = internal::ClockTicksToTimeDelta(
114             ParseTotalCPUTimeFromStats(proc_stats));
115         cpu_per_thread.emplace_back(tid, thread_time);
116       });
117 
118   return !cpu_per_thread.empty();
119 }
120 
121 // For the /proc/self/io file to exist, the Linux kernel must have
122 // CONFIG_TASK_IO_ACCOUNTING enabled.
GetIOCounters(IoCounters * io_counters) const123 bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
124   StringPairs pairs;
125   if (!internal::ReadProcFileToTrimmedStringPairs(process_, "io", &pairs)) {
126     return false;
127   }
128 
129   io_counters->OtherOperationCount = 0;
130   io_counters->OtherTransferCount = 0;
131 
132   for (const auto& pair : pairs) {
133     const std::string& key = pair.first;
134     const std::string& value_str = pair.second;
135     uint64_t* target_counter = nullptr;
136     if (key == "syscr")
137       target_counter = &io_counters->ReadOperationCount;
138     else if (key == "syscw")
139       target_counter = &io_counters->WriteOperationCount;
140     else if (key == "rchar")
141       target_counter = &io_counters->ReadTransferCount;
142     else if (key == "wchar")
143       target_counter = &io_counters->WriteTransferCount;
144     if (!target_counter)
145       continue;
146     bool converted = StringToUint64(value_str, target_counter);
147     DCHECK(converted);
148   }
149   return true;
150 }
151 
152 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_ANDROID)
GetVmSwapBytes() const153 uint64_t ProcessMetrics::GetVmSwapBytes() const {
154   return internal::ReadProcStatusAndGetKbFieldAsSizeT(process_, "VmSwap") *
155          1024;
156 }
157 
GetPageFaultCounts(PageFaultCounts * counts) const158 bool ProcessMetrics::GetPageFaultCounts(PageFaultCounts* counts) const {
159   // We are not using internal::ReadStatsFileAndGetFieldAsInt64(), since it
160   // would read the file twice, and return inconsistent numbers.
161   std::string stats_data;
162   if (!internal::ReadProcStats(process_, &stats_data))
163     return false;
164   std::vector<std::string> proc_stats;
165   if (!internal::ParseProcStats(stats_data, &proc_stats))
166     return false;
167 
168   counts->minor =
169       internal::GetProcStatsFieldAsInt64(proc_stats, internal::VM_MINFLT);
170   counts->major =
171       internal::GetProcStatsFieldAsInt64(proc_stats, internal::VM_MAJFLT);
172   return true;
173 }
174 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
175         // BUILDFLAG(IS_ANDROID)
176 
GetOpenFdCount() const177 int ProcessMetrics::GetOpenFdCount() const {
178   // Use /proc/<pid>/fd to count the number of entries there.
179   FilePath fd_path = internal::GetProcPidDir(process_).Append("fd");
180 
181   DirReaderPosix dir_reader(fd_path.value().c_str());
182   if (!dir_reader.IsValid())
183     return -1;
184 
185   int total_count = 0;
186   for (; dir_reader.Next(); ) {
187     const char* name = dir_reader.name();
188     if (strcmp(name, ".") != 0 && strcmp(name, "..") != 0)
189       ++total_count;
190   }
191 
192   return total_count;
193 }
194 
GetOpenFdSoftLimit() const195 int ProcessMetrics::GetOpenFdSoftLimit() const {
196   // Use /proc/<pid>/limits to read the open fd limit.
197   FilePath fd_path = internal::GetProcPidDir(process_).Append("limits");
198 
199   std::string limits_contents;
200   if (!ReadFileToStringNonBlocking(fd_path, &limits_contents))
201     return -1;
202 
203   for (const auto& line : SplitStringPiece(
204            limits_contents, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
205     if (!StartsWith(line, "Max open files"))
206       continue;
207 
208     auto tokens =
209         SplitStringPiece(line, " ", TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
210     if (tokens.size() > 3) {
211       int limit = -1;
212       if (!StringToInt(tokens[3], &limit))
213         return -1;
214       return limit;
215     }
216   }
217   return -1;
218 }
219 
220 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_AIX)
ProcessMetrics(ProcessHandle process)221 ProcessMetrics::ProcessMetrics(ProcessHandle process)
222     : process_(process), last_absolute_idle_wakeups_(0) {}
223 #else
ProcessMetrics(ProcessHandle process)224 ProcessMetrics::ProcessMetrics(ProcessHandle process) : process_(process) {}
225 #endif
226 
GetSystemCommitCharge()227 size_t GetSystemCommitCharge() {
228   SystemMemoryInfoKB meminfo;
229   if (!GetSystemMemoryInfo(&meminfo))
230     return 0;
231   return checked_cast<size_t>(meminfo.total - meminfo.free - meminfo.buffers -
232                               meminfo.cached);
233 }
234 
ParseProcStatCPU(StringPiece input)235 int ParseProcStatCPU(StringPiece input) {
236   // |input| may be empty if the process disappeared somehow.
237   // e.g. http://crbug.com/145811.
238   if (input.empty())
239     return -1;
240 
241   size_t start = input.find_last_of(')');
242   if (start == input.npos)
243     return -1;
244 
245   // Number of spaces remaining until reaching utime's index starting after the
246   // last ')'.
247   int num_spaces_remaining = internal::VM_UTIME - 1;
248 
249   size_t i = start;
250   while ((i = input.find(' ', i + 1)) != input.npos) {
251     // Validate the assumption that there aren't any contiguous spaces
252     // in |input| before utime.
253     DCHECK_NE(input[i - 1], ' ');
254     if (--num_spaces_remaining == 0) {
255       int utime = 0;
256       int stime = 0;
257       if (sscanf(&input.data()[i], "%d %d", &utime, &stime) != 2)
258         return -1;
259 
260       return utime + stime;
261     }
262   }
263 
264   return -1;
265 }
266 
GetNumberOfThreads(ProcessHandle process)267 int64_t GetNumberOfThreads(ProcessHandle process) {
268   return internal::ReadProcStatsAndGetFieldAsInt64(process,
269                                                    internal::VM_NUMTHREADS);
270 }
271 
272 const char kProcSelfExe[] = "/proc/self/exe";
273 
274 namespace {
275 
276 // The format of /proc/diskstats is:
277 //  Device major number
278 //  Device minor number
279 //  Device name
280 //  Field  1 -- # of reads completed
281 //      This is the total number of reads completed successfully.
282 //  Field  2 -- # of reads merged, field 6 -- # of writes merged
283 //      Reads and writes which are adjacent to each other may be merged for
284 //      efficiency.  Thus two 4K reads may become one 8K read before it is
285 //      ultimately handed to the disk, and so it will be counted (and queued)
286 //      as only one I/O.  This field lets you know how often this was done.
287 //  Field  3 -- # of sectors read
288 //      This is the total number of sectors read successfully.
289 //  Field  4 -- # of milliseconds spent reading
290 //      This is the total number of milliseconds spent by all reads (as
291 //      measured from __make_request() to end_that_request_last()).
292 //  Field  5 -- # of writes completed
293 //      This is the total number of writes completed successfully.
294 //  Field  6 -- # of writes merged
295 //      See the description of field 2.
296 //  Field  7 -- # of sectors written
297 //      This is the total number of sectors written successfully.
298 //  Field  8 -- # of milliseconds spent writing
299 //      This is the total number of milliseconds spent by all writes (as
300 //      measured from __make_request() to end_that_request_last()).
301 //  Field  9 -- # of I/Os currently in progress
302 //      The only field that should go to zero. Incremented as requests are
303 //      given to appropriate struct request_queue and decremented as they
304 //      finish.
305 //  Field 10 -- # of milliseconds spent doing I/Os
306 //      This field increases so long as field 9 is nonzero.
307 //  Field 11 -- weighted # of milliseconds spent doing I/Os
308 //      This field is incremented at each I/O start, I/O completion, I/O
309 //      merge, or read of these stats by the number of I/Os in progress
310 //      (field 9) times the number of milliseconds spent doing I/O since the
311 //      last update of this field.  This can provide an easy measure of both
312 //      I/O completion time and the backlog that may be accumulating.
313 
314 const size_t kDiskDriveName = 2;
315 const size_t kDiskReads = 3;
316 const size_t kDiskReadsMerged = 4;
317 const size_t kDiskSectorsRead = 5;
318 const size_t kDiskReadTime = 6;
319 const size_t kDiskWrites = 7;
320 const size_t kDiskWritesMerged = 8;
321 const size_t kDiskSectorsWritten = 9;
322 const size_t kDiskWriteTime = 10;
323 const size_t kDiskIO = 11;
324 const size_t kDiskIOTime = 12;
325 const size_t kDiskWeightedIOTime = 13;
326 
327 }  // namespace
328 
ToDict() const329 Value::Dict SystemMemoryInfoKB::ToDict() const {
330   Value::Dict res;
331   res.Set("total", total);
332   res.Set("free", free);
333   res.Set("available", available);
334   res.Set("buffers", buffers);
335   res.Set("cached", cached);
336   res.Set("active_anon", active_anon);
337   res.Set("inactive_anon", inactive_anon);
338   res.Set("active_file", active_file);
339   res.Set("inactive_file", inactive_file);
340   res.Set("swap_total", swap_total);
341   res.Set("swap_free", swap_free);
342   res.Set("swap_used", swap_total - swap_free);
343   res.Set("dirty", dirty);
344   res.Set("reclaimable", reclaimable);
345 #if BUILDFLAG(IS_CHROMEOS)
346   res.Set("shmem", shmem);
347   res.Set("slab", slab);
348 #endif
349 
350   return res;
351 }
352 
ParseProcMeminfo(StringPiece meminfo_data,SystemMemoryInfoKB * meminfo)353 bool ParseProcMeminfo(StringPiece meminfo_data, SystemMemoryInfoKB* meminfo) {
354   // The format of /proc/meminfo is:
355   //
356   // MemTotal:      8235324 kB
357   // MemFree:       1628304 kB
358   // Buffers:        429596 kB
359   // Cached:        4728232 kB
360   // ...
361   // There is no guarantee on the ordering or position
362   // though it doesn't appear to change very often
363 
364   // As a basic sanity check at the end, make sure the MemTotal value will be at
365   // least non-zero. So start off with a zero total.
366   meminfo->total = 0;
367 
368   for (const StringPiece& line : SplitStringPiece(
369            meminfo_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
370     std::vector<StringPiece> tokens = SplitStringPiece(
371         line, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
372     // HugePages_* only has a number and no suffix so there may not be exactly 3
373     // tokens.
374     if (tokens.size() <= 1) {
375       DLOG(WARNING) << "meminfo: tokens: " << tokens.size()
376                     << " malformed line: " << line;
377       continue;
378     }
379 
380     int* target = nullptr;
381     if (tokens[0] == "MemTotal:")
382       target = &meminfo->total;
383     else if (tokens[0] == "MemFree:")
384       target = &meminfo->free;
385     else if (tokens[0] == "MemAvailable:")
386       target = &meminfo->available;
387     else if (tokens[0] == "Buffers:")
388       target = &meminfo->buffers;
389     else if (tokens[0] == "Cached:")
390       target = &meminfo->cached;
391     else if (tokens[0] == "Active(anon):")
392       target = &meminfo->active_anon;
393     else if (tokens[0] == "Inactive(anon):")
394       target = &meminfo->inactive_anon;
395     else if (tokens[0] == "Active(file):")
396       target = &meminfo->active_file;
397     else if (tokens[0] == "Inactive(file):")
398       target = &meminfo->inactive_file;
399     else if (tokens[0] == "SwapTotal:")
400       target = &meminfo->swap_total;
401     else if (tokens[0] == "SwapFree:")
402       target = &meminfo->swap_free;
403     else if (tokens[0] == "Dirty:")
404       target = &meminfo->dirty;
405     else if (tokens[0] == "SReclaimable:")
406       target = &meminfo->reclaimable;
407 #if BUILDFLAG(IS_CHROMEOS)
408     // Chrome OS has a tweaked kernel that allows querying Shmem, which is
409     // usually video memory otherwise invisible to the OS.
410     else if (tokens[0] == "Shmem:")
411       target = &meminfo->shmem;
412     else if (tokens[0] == "Slab:")
413       target = &meminfo->slab;
414 #endif
415     if (target)
416       StringToInt(tokens[1], target);
417   }
418 
419   // Make sure the MemTotal is valid.
420   return meminfo->total > 0;
421 }
422 
ParseProcVmstat(StringPiece vmstat_data,VmStatInfo * vmstat)423 bool ParseProcVmstat(StringPiece vmstat_data, VmStatInfo* vmstat) {
424   // The format of /proc/vmstat is:
425   //
426   // nr_free_pages 299878
427   // nr_inactive_anon 239863
428   // nr_active_anon 1318966
429   // nr_inactive_file 2015629
430   // ...
431   //
432   // Iterate through the whole file because the position of the
433   // fields are dependent on the kernel version and configuration.
434 
435   // Returns true if all of these 3 fields are present.
436   bool has_pswpin = false;
437   bool has_pswpout = false;
438   bool has_pgmajfault = false;
439 
440   // The oom_kill field is optional. The vmstat oom_kill field is available on
441   // upstream kernel 4.13. It's backported to Chrome OS kernel 3.10.
442   bool has_oom_kill = false;
443   vmstat->oom_kill = 0;
444 
445   for (const StringPiece& line : SplitStringPiece(
446            vmstat_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
447     std::vector<StringPiece> tokens = SplitStringPiece(
448         line, " ", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY);
449     if (tokens.size() != 2)
450       continue;
451 
452     uint64_t val;
453     if (!StringToUint64(tokens[1], &val))
454       continue;
455 
456     if (tokens[0] == "pswpin") {
457       vmstat->pswpin = val;
458       DCHECK(!has_pswpin);
459       has_pswpin = true;
460     } else if (tokens[0] == "pswpout") {
461       vmstat->pswpout = val;
462       DCHECK(!has_pswpout);
463       has_pswpout = true;
464     } else if (tokens[0] == "pgmajfault") {
465       vmstat->pgmajfault = val;
466       DCHECK(!has_pgmajfault);
467       has_pgmajfault = true;
468     } else if (tokens[0] == "oom_kill") {
469       vmstat->oom_kill = val;
470       DCHECK(!has_oom_kill);
471       has_oom_kill = true;
472     }
473   }
474 
475   return has_pswpin && has_pswpout && has_pgmajfault;
476 }
477 
GetSystemMemoryInfo(SystemMemoryInfoKB * meminfo)478 bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
479   // Used memory is: total - free - buffers - caches
480   // ReadFileToStringNonBlocking doesn't require ScopedAllowIO, and reading
481   // /proc/meminfo is fast. See crbug.com/1160988 for details.
482   FilePath meminfo_file("/proc/meminfo");
483   std::string meminfo_data;
484   if (!ReadFileToStringNonBlocking(meminfo_file, &meminfo_data)) {
485     DLOG(WARNING) << "Failed to open " << meminfo_file.value();
486     return false;
487   }
488 
489   if (!ParseProcMeminfo(meminfo_data, meminfo)) {
490     DLOG(WARNING) << "Failed to parse " << meminfo_file.value();
491     return false;
492   }
493 
494   return true;
495 }
496 
ToDict() const497 Value::Dict VmStatInfo::ToDict() const {
498   Value::Dict res;
499   // TODO(crbug.com/1334256): Make base::Value able to hold uint64_t and remove
500   // casts below.
501   res.Set("pswpin", static_cast<int>(pswpin));
502   res.Set("pswpout", static_cast<int>(pswpout));
503   res.Set("pgmajfault", static_cast<int>(pgmajfault));
504   return res;
505 }
506 
GetVmStatInfo(VmStatInfo * vmstat)507 bool GetVmStatInfo(VmStatInfo* vmstat) {
508   // Synchronously reading files in /proc is safe.
509   ScopedAllowBlockingForProcessMetrics allow_blocking;
510 
511   FilePath vmstat_file("/proc/vmstat");
512   std::string vmstat_data;
513   if (!ReadFileToStringNonBlocking(vmstat_file, &vmstat_data)) {
514     DLOG(WARNING) << "Failed to open " << vmstat_file.value();
515     return false;
516   }
517   if (!ParseProcVmstat(vmstat_data, vmstat)) {
518     DLOG(WARNING) << "Failed to parse " << vmstat_file.value();
519     return false;
520   }
521   return true;
522 }
523 
SystemDiskInfo()524 SystemDiskInfo::SystemDiskInfo() {
525   reads = 0;
526   reads_merged = 0;
527   sectors_read = 0;
528   read_time = 0;
529   writes = 0;
530   writes_merged = 0;
531   sectors_written = 0;
532   write_time = 0;
533   io = 0;
534   io_time = 0;
535   weighted_io_time = 0;
536 }
537 
538 SystemDiskInfo::SystemDiskInfo(const SystemDiskInfo&) = default;
539 
540 SystemDiskInfo& SystemDiskInfo::operator=(const SystemDiskInfo&) = default;
541 
ToDict() const542 Value::Dict SystemDiskInfo::ToDict() const {
543   Value::Dict res;
544 
545   // Write out uint64_t variables as doubles.
546   // Note: this may discard some precision, but for JS there's no other option.
547   res.Set("reads", static_cast<double>(reads));
548   res.Set("reads_merged", static_cast<double>(reads_merged));
549   res.Set("sectors_read", static_cast<double>(sectors_read));
550   res.Set("read_time", static_cast<double>(read_time));
551   res.Set("writes", static_cast<double>(writes));
552   res.Set("writes_merged", static_cast<double>(writes_merged));
553   res.Set("sectors_written", static_cast<double>(sectors_written));
554   res.Set("write_time", static_cast<double>(write_time));
555   res.Set("io", static_cast<double>(io));
556   res.Set("io_time", static_cast<double>(io_time));
557   res.Set("weighted_io_time", static_cast<double>(weighted_io_time));
558 
559   return res;
560 }
561 
IsValidDiskName(StringPiece candidate)562 bool IsValidDiskName(StringPiece candidate) {
563   if (candidate.length() < 3)
564     return false;
565 
566   if (candidate[1] == 'd' &&
567       (candidate[0] == 'h' || candidate[0] == 's' || candidate[0] == 'v')) {
568     // [hsv]d[a-z]+ case
569     for (size_t i = 2; i < candidate.length(); ++i) {
570       if (!absl::ascii_islower(static_cast<unsigned char>(candidate[i]))) {
571         return false;
572       }
573     }
574     return true;
575   }
576 
577   const char kMMCName[] = "mmcblk";
578   if (!StartsWith(candidate, kMMCName))
579     return false;
580 
581   // mmcblk[0-9]+ case
582   for (size_t i = strlen(kMMCName); i < candidate.length(); ++i) {
583     if (!absl::ascii_isdigit(static_cast<unsigned char>(candidate[i]))) {
584       return false;
585     }
586   }
587   return true;
588 }
589 
GetSystemDiskInfo(SystemDiskInfo * diskinfo)590 bool GetSystemDiskInfo(SystemDiskInfo* diskinfo) {
591   // Synchronously reading files in /proc does not hit the disk.
592   ScopedAllowBlockingForProcessMetrics allow_blocking;
593 
594   FilePath diskinfo_file("/proc/diskstats");
595   std::string diskinfo_data;
596   if (!ReadFileToStringNonBlocking(diskinfo_file, &diskinfo_data)) {
597     DLOG(WARNING) << "Failed to open " << diskinfo_file.value();
598     return false;
599   }
600 
601   std::vector<StringPiece> diskinfo_lines = SplitStringPiece(
602       diskinfo_data, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY);
603   if (diskinfo_lines.empty()) {
604     DLOG(WARNING) << "No lines found";
605     return false;
606   }
607 
608   diskinfo->reads = 0;
609   diskinfo->reads_merged = 0;
610   diskinfo->sectors_read = 0;
611   diskinfo->read_time = 0;
612   diskinfo->writes = 0;
613   diskinfo->writes_merged = 0;
614   diskinfo->sectors_written = 0;
615   diskinfo->write_time = 0;
616   diskinfo->io = 0;
617   diskinfo->io_time = 0;
618   diskinfo->weighted_io_time = 0;
619 
620   uint64_t reads = 0;
621   uint64_t reads_merged = 0;
622   uint64_t sectors_read = 0;
623   uint64_t read_time = 0;
624   uint64_t writes = 0;
625   uint64_t writes_merged = 0;
626   uint64_t sectors_written = 0;
627   uint64_t write_time = 0;
628   uint64_t io = 0;
629   uint64_t io_time = 0;
630   uint64_t weighted_io_time = 0;
631 
632   for (const StringPiece& line : diskinfo_lines) {
633     std::vector<StringPiece> disk_fields = SplitStringPiece(
634         line, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
635 
636     // Fields may have overflowed and reset to zero.
637     if (!IsValidDiskName(disk_fields[kDiskDriveName]))
638       continue;
639 
640     StringToUint64(disk_fields[kDiskReads], &reads);
641     StringToUint64(disk_fields[kDiskReadsMerged], &reads_merged);
642     StringToUint64(disk_fields[kDiskSectorsRead], &sectors_read);
643     StringToUint64(disk_fields[kDiskReadTime], &read_time);
644     StringToUint64(disk_fields[kDiskWrites], &writes);
645     StringToUint64(disk_fields[kDiskWritesMerged], &writes_merged);
646     StringToUint64(disk_fields[kDiskSectorsWritten], &sectors_written);
647     StringToUint64(disk_fields[kDiskWriteTime], &write_time);
648     StringToUint64(disk_fields[kDiskIO], &io);
649     StringToUint64(disk_fields[kDiskIOTime], &io_time);
650     StringToUint64(disk_fields[kDiskWeightedIOTime], &weighted_io_time);
651 
652     diskinfo->reads += reads;
653     diskinfo->reads_merged += reads_merged;
654     diskinfo->sectors_read += sectors_read;
655     diskinfo->read_time += read_time;
656     diskinfo->writes += writes;
657     diskinfo->writes_merged += writes_merged;
658     diskinfo->sectors_written += sectors_written;
659     diskinfo->write_time += write_time;
660     diskinfo->io += io;
661     diskinfo->io_time += io_time;
662     diskinfo->weighted_io_time += weighted_io_time;
663   }
664 
665   return true;
666 }
667 
GetUserCpuTimeSinceBoot()668 TimeDelta GetUserCpuTimeSinceBoot() {
669   return internal::GetUserCpuTimeSinceBoot();
670 }
671 
672 #if BUILDFLAG(IS_CHROMEOS)
ToDict() const673 Value::Dict SwapInfo::ToDict() const {
674   Value::Dict res;
675 
676   // Write out uint64_t variables as doubles.
677   // Note: this may discard some precision, but for JS there's no other option.
678   res.Set("num_reads", static_cast<double>(num_reads));
679   res.Set("num_writes", static_cast<double>(num_writes));
680   res.Set("orig_data_size", static_cast<double>(orig_data_size));
681   res.Set("compr_data_size", static_cast<double>(compr_data_size));
682   res.Set("mem_used_total", static_cast<double>(mem_used_total));
683   double ratio = compr_data_size ? static_cast<double>(orig_data_size) /
684                                        static_cast<double>(compr_data_size)
685                                  : 0;
686   res.Set("compression_ratio", ratio);
687 
688   return res;
689 }
690 
ToDict() const691 Value::Dict GraphicsMemoryInfoKB::ToDict() const {
692   Value::Dict res;
693 
694   res.Set("gpu_objects", gpu_objects);
695   res.Set("gpu_memory_size", static_cast<double>(gpu_memory_size));
696 
697   return res;
698 }
699 
ParseZramMmStat(StringPiece mm_stat_data,SwapInfo * swap_info)700 bool ParseZramMmStat(StringPiece mm_stat_data, SwapInfo* swap_info) {
701   // There are 7 columns in /sys/block/zram0/mm_stat,
702   // split by several spaces. The first three columns
703   // are orig_data_size, compr_data_size and mem_used_total.
704   // Example:
705   // 17715200 5008166 566062  0 1225715712  127 183842
706   //
707   // For more details:
708   // https://www.kernel.org/doc/Documentation/blockdev/zram.txt
709 
710   std::vector<StringPiece> tokens = SplitStringPiece(
711       mm_stat_data, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
712   if (tokens.size() < 7) {
713     DLOG(WARNING) << "zram mm_stat: tokens: " << tokens.size()
714                   << " malformed line: " << mm_stat_data;
715     return false;
716   }
717 
718   if (!StringToUint64(tokens[0], &swap_info->orig_data_size))
719     return false;
720   if (!StringToUint64(tokens[1], &swap_info->compr_data_size))
721     return false;
722   if (!StringToUint64(tokens[2], &swap_info->mem_used_total))
723     return false;
724 
725   return true;
726 }
727 
ParseZramStat(StringPiece stat_data,SwapInfo * swap_info)728 bool ParseZramStat(StringPiece stat_data, SwapInfo* swap_info) {
729   // There are 11 columns in /sys/block/zram0/stat,
730   // split by several spaces. The first column is read I/Os
731   // and fifth column is write I/Os.
732   // Example:
733   // 299    0    2392    0    1    0    8    0    0    0    0
734   //
735   // For more details:
736   // https://www.kernel.org/doc/Documentation/blockdev/zram.txt
737 
738   std::vector<StringPiece> tokens = SplitStringPiece(
739       stat_data, kWhitespaceASCII, TRIM_WHITESPACE, SPLIT_WANT_NONEMPTY);
740   if (tokens.size() < 11) {
741     DLOG(WARNING) << "zram stat: tokens: " << tokens.size()
742                   << " malformed line: " << stat_data;
743     return false;
744   }
745 
746   if (!StringToUint64(tokens[0], &swap_info->num_reads))
747     return false;
748   if (!StringToUint64(tokens[4], &swap_info->num_writes))
749     return false;
750 
751   return true;
752 }
753 
754 namespace {
755 
IgnoreZramFirstPage(uint64_t orig_data_size,SwapInfo * swap_info)756 bool IgnoreZramFirstPage(uint64_t orig_data_size, SwapInfo* swap_info) {
757   if (orig_data_size <= 4096) {
758     // A single page is compressed at startup, and has a high compression
759     // ratio. Ignore this as it doesn't indicate any real swapping.
760     swap_info->orig_data_size = 0;
761     swap_info->num_reads = 0;
762     swap_info->num_writes = 0;
763     swap_info->compr_data_size = 0;
764     swap_info->mem_used_total = 0;
765     return true;
766   }
767   return false;
768 }
769 
ParseZramPath(SwapInfo * swap_info)770 void ParseZramPath(SwapInfo* swap_info) {
771   FilePath zram_path("/sys/block/zram0");
772   uint64_t orig_data_size =
773       ReadFileToUint64(zram_path.Append("orig_data_size"));
774   if (IgnoreZramFirstPage(orig_data_size, swap_info))
775     return;
776 
777   swap_info->orig_data_size = orig_data_size;
778   swap_info->num_reads = ReadFileToUint64(zram_path.Append("num_reads"));
779   swap_info->num_writes = ReadFileToUint64(zram_path.Append("num_writes"));
780   swap_info->compr_data_size =
781       ReadFileToUint64(zram_path.Append("compr_data_size"));
782   swap_info->mem_used_total =
783       ReadFileToUint64(zram_path.Append("mem_used_total"));
784 }
785 
GetSwapInfoImpl(SwapInfo * swap_info)786 bool GetSwapInfoImpl(SwapInfo* swap_info) {
787   // Synchronously reading files in /sys/block/zram0 does not hit the disk.
788   ScopedAllowBlockingForProcessMetrics allow_blocking;
789 
790   // Since ZRAM update, it shows the usage data in different places.
791   // If file "/sys/block/zram0/mm_stat" exists, use the new way, otherwise,
792   // use the old way.
793   static absl::optional<bool> use_new_zram_interface;
794   FilePath zram_mm_stat_file("/sys/block/zram0/mm_stat");
795   if (!use_new_zram_interface.has_value()) {
796     use_new_zram_interface = PathExists(zram_mm_stat_file);
797   }
798 
799   if (!use_new_zram_interface.value()) {
800     ParseZramPath(swap_info);
801     return true;
802   }
803 
804   std::string mm_stat_data;
805   if (!ReadFileToStringNonBlocking(zram_mm_stat_file, &mm_stat_data)) {
806     DLOG(WARNING) << "Failed to open " << zram_mm_stat_file.value();
807     return false;
808   }
809   if (!ParseZramMmStat(mm_stat_data, swap_info)) {
810     DLOG(WARNING) << "Failed to parse " << zram_mm_stat_file.value();
811     return false;
812   }
813   if (IgnoreZramFirstPage(swap_info->orig_data_size, swap_info))
814     return true;
815 
816   FilePath zram_stat_file("/sys/block/zram0/stat");
817   std::string stat_data;
818   if (!ReadFileToStringNonBlocking(zram_stat_file, &stat_data)) {
819     DLOG(WARNING) << "Failed to open " << zram_stat_file.value();
820     return false;
821   }
822   if (!ParseZramStat(stat_data, swap_info)) {
823     DLOG(WARNING) << "Failed to parse " << zram_stat_file.value();
824     return false;
825   }
826 
827   return true;
828 }
829 
830 }  // namespace
831 
GetSwapInfo(SwapInfo * swap_info)832 bool GetSwapInfo(SwapInfo* swap_info) {
833   if (!GetSwapInfoImpl(swap_info)) {
834     *swap_info = SwapInfo();
835     return false;
836   }
837   return true;
838 }
839 
GetGraphicsMemoryInfo(GraphicsMemoryInfoKB * gpu_meminfo)840 bool GetGraphicsMemoryInfo(GraphicsMemoryInfoKB* gpu_meminfo) {
841 #if defined(ARCH_CPU_X86_FAMILY)
842   // Reading i915_gem_objects on intel platform with kernel 5.4 is slow and is
843   // prohibited.
844   // TODO(b/170397975): Update if i915_gem_objects reading time is improved.
845   static bool is_newer_kernel =
846       base::StartsWith(base::SysInfo::KernelVersion(), "5.");
847   static bool is_intel_cpu = base::CPU().vendor_name() == "GenuineIntel";
848   if (is_newer_kernel && is_intel_cpu)
849     return false;
850 #endif
851 
852 #if defined(ARCH_CPU_ARM_FAMILY)
853   const FilePath geminfo_path("/run/debugfs_gpu/exynos_gem_objects");
854 #else
855   const FilePath geminfo_path("/run/debugfs_gpu/i915_gem_objects");
856 #endif
857   std::string geminfo_data;
858   gpu_meminfo->gpu_objects = -1;
859   gpu_meminfo->gpu_memory_size = -1;
860   if (ReadFileToStringNonBlocking(geminfo_path, &geminfo_data)) {
861     int gpu_objects = -1;
862     int64_t gpu_memory_size = -1;
863     int num_res = sscanf(geminfo_data.c_str(), "%d objects, %" SCNd64 " bytes",
864                          &gpu_objects, &gpu_memory_size);
865     if (num_res == 2) {
866       gpu_meminfo->gpu_objects = gpu_objects;
867       gpu_meminfo->gpu_memory_size = gpu_memory_size;
868     }
869   }
870 
871 #if defined(ARCH_CPU_ARM_FAMILY)
872   // Incorporate Mali graphics memory if present.
873   FilePath mali_memory_file("/sys/class/misc/mali0/device/memory");
874   std::string mali_memory_data;
875   if (ReadFileToStringNonBlocking(mali_memory_file, &mali_memory_data)) {
876     int64_t mali_size = -1;
877     int num_res =
878         sscanf(mali_memory_data.c_str(), "%" SCNd64 " bytes", &mali_size);
879     if (num_res == 1)
880       gpu_meminfo->gpu_memory_size += mali_size;
881   }
882 #endif  // defined(ARCH_CPU_ARM_FAMILY)
883 
884   return gpu_meminfo->gpu_memory_size != -1;
885 }
886 
887 #endif  // BUILDFLAG(IS_CHROMEOS)
888 
889 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_AIX)
GetIdleWakeupsPerSecond()890 int ProcessMetrics::GetIdleWakeupsPerSecond() {
891   uint64_t num_switches;
892   static const char kSwitchStat[] = "voluntary_ctxt_switches";
893   return internal::ReadProcStatusAndGetFieldAsUint64(process_, kSwitchStat,
894                                                      &num_switches)
895              ? CalculateIdleWakeupsPerSecond(num_switches)
896              : 0;
897 }
898 #endif  // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_AIX)
899 
900 }  // namespace base
901