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