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