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