blob: 1df03b22ef731a692037712abf76706982df3415 [file] [log] [blame]
Sandeep Patil54d87212018-08-29 17:10:47 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <errno.h>
18#include <fcntl.h>
19#include <inttypes.h>
20#include <linux/kernel-page-flags.h>
21#include <stdio.h>
22#include <unistd.h>
23
Sandeep Patildfd34be2019-01-13 17:39:08 -080024#include <atomic>
Sandeep Patil54d87212018-08-29 17:10:47 -070025#include <fstream>
26#include <iostream>
27#include <memory>
28#include <string>
29#include <utility>
30
31#include <android-base/file.h>
32#include <android-base/logging.h>
33#include <android-base/stringprintf.h>
Sandeep Patilfa2d8d52018-12-29 21:05:38 -080034#include <android-base/strings.h>
Sandeep Patil54d87212018-08-29 17:10:47 -070035#include <android-base/unique_fd.h>
36#include <procinfo/process_map.h>
37
38#include "meminfo_private.h"
39
40namespace android {
41namespace meminfo {
42
43static void add_mem_usage(MemUsage* to, const MemUsage& from) {
44 to->vss += from.vss;
45 to->rss += from.rss;
46 to->pss += from.pss;
47 to->uss += from.uss;
48
Sandeep Patil2259fdf2018-11-09 16:42:45 -080049 to->swap += from.swap;
50
Sandeep Patil54d87212018-08-29 17:10:47 -070051 to->private_clean += from.private_clean;
52 to->private_dirty += from.private_dirty;
53
54 to->shared_clean += from.shared_clean;
55 to->shared_dirty += from.shared_dirty;
56}
57
Sandeep Patil82a48b12019-01-01 16:04:04 -080058// Returns true if the line was valid smaps stats line false otherwise.
59static bool parse_smaps_field(const char* line, MemUsage* stats) {
60 char field[64];
61 int len;
62 if (sscanf(line, "%63s %n", field, &len) == 1 && *field && field[strlen(field) - 1] == ':') {
63 const char* c = line + len;
64 switch (field[0]) {
65 case 'P':
66 if (strncmp(field, "Pss:", 4) == 0) {
67 stats->pss = strtoull(c, nullptr, 10);
68 } else if (strncmp(field, "Private_Clean:", 14) == 0) {
69 uint64_t prcl = strtoull(c, nullptr, 10);
70 stats->private_clean = prcl;
71 stats->uss += prcl;
72 } else if (strncmp(field, "Private_Dirty:", 14) == 0) {
73 uint64_t prdi = strtoull(c, nullptr, 10);
74 stats->private_dirty = prdi;
75 stats->uss += prdi;
76 }
77 break;
78 case 'S':
79 if (strncmp(field, "Size:", 5) == 0) {
80 stats->vss = strtoull(c, nullptr, 10);
81 } else if (strncmp(field, "Shared_Clean:", 13) == 0) {
82 stats->shared_clean = strtoull(c, nullptr, 10);
83 } else if (strncmp(field, "Shared_Dirty:", 13) == 0) {
84 stats->shared_dirty = strtoull(c, nullptr, 10);
85 } else if (strncmp(field, "Swap:", 5) == 0) {
86 stats->swap = strtoull(c, nullptr, 10);
87 } else if (strncmp(field, "SwapPss:", 8) == 0) {
88 stats->swap_pss = strtoull(c, nullptr, 10);
89 }
90 break;
91 case 'R':
92 if (strncmp(field, "Rss:", 4) == 0) {
93 stats->rss = strtoull(c, nullptr, 10);
94 }
95 break;
96 }
97 return true;
98 }
99
100 return false;
101}
102
Sandeep Patilf1291992018-11-19 15:25:18 -0800103bool ProcMemInfo::ResetWorkingSet(pid_t pid) {
104 std::string clear_refs_path = ::android::base::StringPrintf("/proc/%d/clear_refs", pid);
105 if (!::android::base::WriteStringToFile("1\n", clear_refs_path)) {
106 PLOG(ERROR) << "Failed to write to " << clear_refs_path;
107 return false;
108 }
109
110 return true;
111}
112
Sandeep Patil549feab2018-11-19 11:38:40 -0800113ProcMemInfo::ProcMemInfo(pid_t pid, bool get_wss, uint64_t pgflags, uint64_t pgflags_mask)
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800114 : pid_(pid), get_wss_(get_wss), pgflags_(pgflags), pgflags_mask_(pgflags_mask) {}
Sandeep Patil54d87212018-08-29 17:10:47 -0700115
116const std::vector<Vma>& ProcMemInfo::Maps() {
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800117 if (maps_.empty() && !ReadMaps(get_wss_)) {
118 LOG(ERROR) << "Failed to read maps for Process " << pid_;
119 }
120
Sandeep Patil54d87212018-08-29 17:10:47 -0700121 return maps_;
122}
123
Sandeep Patil82a48b12019-01-01 16:04:04 -0800124const std::vector<Vma>& ProcMemInfo::Smaps(const std::string& path) {
125 if (!maps_.empty()) {
126 return maps_;
127 }
128
129 auto collect_vmas = [&](const Vma& vma) { maps_.emplace_back(vma); };
130 if (path.empty() && !ForEachVma(collect_vmas)) {
131 LOG(ERROR) << "Failed to read smaps for Process " << pid_;
132 maps_.clear();
133 }
134
135 if (!path.empty() && !ForEachVmaFromFile(path, collect_vmas)) {
136 LOG(ERROR) << "Failed to read smaps from file " << path;
137 maps_.clear();
138 }
139
140 return maps_;
141}
142
Sandeep Patil54d87212018-08-29 17:10:47 -0700143const MemUsage& ProcMemInfo::Usage() {
144 if (get_wss_) {
Sandeep Patilf1291992018-11-19 15:25:18 -0800145 LOG(WARNING) << "Trying to read process memory usage for " << pid_
146 << " using invalid object";
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800147 return usage_;
Sandeep Patil54d87212018-08-29 17:10:47 -0700148 }
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800149
150 if (maps_.empty() && !ReadMaps(get_wss_)) {
151 LOG(ERROR) << "Failed to get memory usage for Process " << pid_;
152 }
153
Sandeep Patil54d87212018-08-29 17:10:47 -0700154 return usage_;
155}
156
157const MemUsage& ProcMemInfo::Wss() {
158 if (!get_wss_) {
Sandeep Patilf1291992018-11-19 15:25:18 -0800159 LOG(WARNING) << "Trying to read process working set for " << pid_
160 << " using invalid object";
Sandeep Patil56c414e2019-01-12 21:29:19 -0800161 return usage_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800162 }
163
164 if (maps_.empty() && !ReadMaps(get_wss_)) {
165 LOG(ERROR) << "Failed to get working set for Process " << pid_;
Sandeep Patil54d87212018-08-29 17:10:47 -0700166 }
167
Sandeep Patil56c414e2019-01-12 21:29:19 -0800168 return usage_;
Sandeep Patil54d87212018-08-29 17:10:47 -0700169}
170
Sandeep Patil82a48b12019-01-01 16:04:04 -0800171bool ProcMemInfo::ForEachVma(const VmaCallback& callback) {
172 std::string path = ::android::base::StringPrintf("/proc/%d/smaps", pid_);
173 return ForEachVmaFromFile(path, callback);
174}
175
Sandeep Patildfd34be2019-01-13 17:39:08 -0800176bool ProcMemInfo::SmapsOrRollup(MemUsage* stats) const {
177 std::string path = ::android::base::StringPrintf(
178 "/proc/%d/%s", pid_, IsSmapsRollupSupported(pid_) ? "smaps_rollup" : "smaps");
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800179 return SmapsOrRollupFromFile(path, stats);
Sandeep Patildfd34be2019-01-13 17:39:08 -0800180}
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800181
Sandeep Patildfd34be2019-01-13 17:39:08 -0800182bool ProcMemInfo::SmapsOrRollupPss(uint64_t* pss) const {
183 std::string path = ::android::base::StringPrintf(
184 "/proc/%d/%s", pid_, IsSmapsRollupSupported(pid_) ? "smaps_rollup" : "smaps");
Sandeep Patil8871e7e2019-01-13 16:47:20 -0800185 return SmapsOrRollupPssFromFile(path, pss);
186}
187
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800188const std::vector<uint16_t>& ProcMemInfo::SwapOffsets() {
189 if (get_wss_) {
190 LOG(WARNING) << "Trying to read process swap offsets for " << pid_
191 << " using invalid object";
192 return swap_offsets_;
193 }
194
195 if (maps_.empty() && !ReadMaps(get_wss_)) {
196 LOG(ERROR) << "Failed to get swap offsets for Process " << pid_;
197 }
198
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800199 return swap_offsets_;
200}
201
Sandeep Patilcbc8f122019-01-21 16:47:24 -0800202bool ProcMemInfo::PageMap(const Vma& vma, std::vector<uint64_t>* pagemap) {
203 pagemap->clear();
204 std::string pagemap_file = ::android::base::StringPrintf("/proc/%d/pagemap", pid_);
205 ::android::base::unique_fd pagemap_fd(
206 TEMP_FAILURE_RETRY(open(pagemap_file.c_str(), O_RDONLY | O_CLOEXEC)));
207 if (pagemap_fd < 0) {
208 PLOG(ERROR) << "Failed to open " << pagemap_file;
209 return false;
210 }
211
212 uint64_t nr_pages = (vma.end - vma.start) / getpagesize();
213 pagemap->reserve(nr_pages);
214
215 uint64_t idx = vma.start / getpagesize();
216 uint64_t last = idx + nr_pages;
217 uint64_t val;
218 for (; idx < last; idx++) {
219 if (pread64(pagemap_fd, &val, sizeof(uint64_t), idx * sizeof(uint64_t)) < 0) {
220 PLOG(ERROR) << "Failed to read page frames from page map for pid: " << pid_;
221 return false;
222 }
223 pagemap->emplace_back(val);
224 }
225
226 return true;
227}
228
Sandeep Patil54d87212018-08-29 17:10:47 -0700229bool ProcMemInfo::ReadMaps(bool get_wss) {
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800230 // Each object reads /proc/<pid>/maps only once. This is done to make sure programs that are
231 // running for the lifetime of the system can recycle the objects and don't have to
232 // unnecessarily retain and update this object in memory (which can get significantly large).
233 // E.g. A program that only needs to reset the working set will never all ->Maps(), ->Usage().
234 // E.g. A program that is monitoring smaps_rollup, may never call ->maps(), Usage(), so it
235 // doesn't make sense for us to parse and retain unnecessary memory accounting stats by default.
236 if (!maps_.empty()) return true;
237
Sandeep Patil54d87212018-08-29 17:10:47 -0700238 // parse and read /proc/<pid>/maps
239 std::string maps_file = ::android::base::StringPrintf("/proc/%d/maps", pid_);
240 if (!::android::procinfo::ReadMapFile(
241 maps_file, [&](uint64_t start, uint64_t end, uint16_t flags, uint64_t pgoff,
242 const char* name) {
243 maps_.emplace_back(Vma(start, end, pgoff, flags, name));
244 })) {
245 LOG(ERROR) << "Failed to parse " << maps_file;
246 maps_.clear();
247 return false;
248 }
249
250 std::string pagemap_file = ::android::base::StringPrintf("/proc/%d/pagemap", pid_);
251 ::android::base::unique_fd pagemap_fd(
252 TEMP_FAILURE_RETRY(open(pagemap_file.c_str(), O_RDONLY | O_CLOEXEC)));
253 if (pagemap_fd < 0) {
254 PLOG(ERROR) << "Failed to open " << pagemap_file;
255 return false;
256 }
257
258 for (auto& vma : maps_) {
259 if (!ReadVmaStats(pagemap_fd.get(), vma, get_wss)) {
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800260 LOG(ERROR) << "Failed to read page map for vma " << vma.name << "[" << vma.start << "-"
261 << vma.end << "]";
Sandeep Patil54d87212018-08-29 17:10:47 -0700262 maps_.clear();
263 return false;
264 }
Sandeep Patil56c414e2019-01-12 21:29:19 -0800265 add_mem_usage(&usage_, vma.usage);
Sandeep Patil54d87212018-08-29 17:10:47 -0700266 }
267
268 return true;
269}
270
271bool ProcMemInfo::ReadVmaStats(int pagemap_fd, Vma& vma, bool get_wss) {
272 PageAcct& pinfo = PageAcct::Instance();
273 uint64_t pagesz = getpagesize();
274 uint64_t num_pages = (vma.end - vma.start) / pagesz;
275
276 std::unique_ptr<uint64_t[]> pg_frames(new uint64_t[num_pages]);
277 uint64_t first = vma.start / pagesz;
278 if (pread64(pagemap_fd, pg_frames.get(), num_pages * sizeof(uint64_t),
279 first * sizeof(uint64_t)) < 0) {
280 PLOG(ERROR) << "Failed to read page frames from page map for pid: " << pid_;
281 return false;
282 }
283
284 std::unique_ptr<uint64_t[]> pg_flags(new uint64_t[num_pages]);
285 std::unique_ptr<uint64_t[]> pg_counts(new uint64_t[num_pages]);
286 for (uint64_t i = 0; i < num_pages; ++i) {
287 if (!get_wss) {
288 vma.usage.vss += pagesz;
289 }
290 uint64_t p = pg_frames[i];
291 if (!PAGE_PRESENT(p) && !PAGE_SWAPPED(p)) continue;
292
293 if (PAGE_SWAPPED(p)) {
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800294 vma.usage.swap += pagesz;
295 swap_offsets_.emplace_back(PAGE_SWAP_OFFSET(p));
Sandeep Patil54d87212018-08-29 17:10:47 -0700296 continue;
297 }
298
299 uint64_t page_frame = PAGE_PFN(p);
300 if (!pinfo.PageFlags(page_frame, &pg_flags[i])) {
301 LOG(ERROR) << "Failed to get page flags for " << page_frame << " in process " << pid_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800302 swap_offsets_.clear();
Sandeep Patil54d87212018-08-29 17:10:47 -0700303 return false;
304 }
305
Sandeep Patil549feab2018-11-19 11:38:40 -0800306 // skip unwanted pages from the count
307 if ((pg_flags[i] & pgflags_mask_) != pgflags_) continue;
308
Sandeep Patil54d87212018-08-29 17:10:47 -0700309 if (!pinfo.PageMapCount(page_frame, &pg_counts[i])) {
310 LOG(ERROR) << "Failed to get page count for " << page_frame << " in process " << pid_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800311 swap_offsets_.clear();
Sandeep Patil54d87212018-08-29 17:10:47 -0700312 return false;
313 }
314
315 // Page was unmapped between the presence check at the beginning of the loop and here.
316 if (pg_counts[i] == 0) {
317 pg_frames[i] = 0;
318 pg_flags[i] = 0;
319 continue;
320 }
321
322 bool is_dirty = !!(pg_flags[i] & (1 << KPF_DIRTY));
323 bool is_private = (pg_counts[i] == 1);
324 // Working set
325 if (get_wss) {
326 bool is_referenced = !!(pg_flags[i] & (1 << KPF_REFERENCED));
327 if (!is_referenced) {
328 continue;
329 }
330 // This effectively makes vss = rss for the working set is requested.
331 // The libpagemap implementation returns vss > rss for
332 // working set, which doesn't make sense.
Sandeep Patil56c414e2019-01-12 21:29:19 -0800333 vma.usage.vss += pagesz;
334 }
335
336 vma.usage.rss += pagesz;
337 vma.usage.uss += is_private ? pagesz : 0;
338 vma.usage.pss += pagesz / pg_counts[i];
339 if (is_private) {
340 vma.usage.private_dirty += is_dirty ? pagesz : 0;
341 vma.usage.private_clean += is_dirty ? 0 : pagesz;
Sandeep Patil54d87212018-08-29 17:10:47 -0700342 } else {
Sandeep Patil56c414e2019-01-12 21:29:19 -0800343 vma.usage.shared_dirty += is_dirty ? pagesz : 0;
344 vma.usage.shared_clean += is_dirty ? 0 : pagesz;
Sandeep Patil54d87212018-08-29 17:10:47 -0700345 }
346 }
Sandeep Patil54d87212018-08-29 17:10:47 -0700347 return true;
348}
349
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800350// Public APIs
Sandeep Patil82a48b12019-01-01 16:04:04 -0800351bool ForEachVmaFromFile(const std::string& path, const VmaCallback& callback) {
352 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
353 if (fp == nullptr) {
354 return false;
355 }
356
357 char* line = nullptr;
358 bool parsing_vma = false;
359 ssize_t line_len;
Sandeep Patil002f02e2019-01-13 19:39:46 -0800360 size_t line_alloc = 0;
Sandeep Patil82a48b12019-01-01 16:04:04 -0800361 Vma vma;
Sandeep Patil002f02e2019-01-13 19:39:46 -0800362 while ((line_len = getline(&line, &line_alloc, fp.get())) > 0) {
Sandeep Patil82a48b12019-01-01 16:04:04 -0800363 // Make sure the line buffer terminates like a C string for ReadMapFile
364 line[line_len] = '\0';
365
366 if (parsing_vma) {
367 if (parse_smaps_field(line, &vma.usage)) {
368 // This was a stats field
369 continue;
370 }
371
372 // Done collecting stats, make the call back
373 callback(vma);
374 parsing_vma = false;
375 }
376
377 vma.clear();
378 // If it has, we are looking for the vma stats
379 // 00400000-00409000 r-xp 00000000 fc:00 426998 /usr/lib/gvfs/gvfsd-http
380 if (!::android::procinfo::ReadMapFileContent(
381 line, [&](uint64_t start, uint64_t end, uint16_t flags, uint64_t pgoff,
382 const char* name) {
383 vma.start = start;
384 vma.end = end;
385 vma.flags = flags;
386 vma.offset = pgoff;
387 vma.name = name;
388 })) {
389 LOG(ERROR) << "Failed to parse " << path;
390 return false;
391 }
392 parsing_vma = true;
393 }
394
395 // free getline() managed buffer
396 free(line);
397
398 if (parsing_vma) {
399 callback(vma);
400 }
401
402 return true;
403}
404
Sandeep Patildfd34be2019-01-13 17:39:08 -0800405enum smaps_rollup_support { UNTRIED, SUPPORTED, UNSUPPORTED };
406
407static std::atomic<smaps_rollup_support> g_rollup_support = UNTRIED;
408
409bool IsSmapsRollupSupported(pid_t pid) {
410 // Similar to OpenSmapsOrRollup checks from android_os_Debug.cpp, except
411 // the method only checks if rollup is supported and returns the status
412 // right away.
413 enum smaps_rollup_support rollup_support = g_rollup_support.load(std::memory_order_relaxed);
414 if (rollup_support != UNTRIED) {
415 return rollup_support == SUPPORTED;
416 }
417 std::string rollup_file = ::android::base::StringPrintf("/proc/%d/smaps_rollup", pid);
418 if (access(rollup_file.c_str(), F_OK | R_OK)) {
419 // No check for errno = ENOENT necessary here. The caller MUST fallback to
420 // using /proc/<pid>/smaps instead anyway.
421 g_rollup_support.store(UNSUPPORTED, std::memory_order_relaxed);
422 return false;
423 }
424
425 g_rollup_support.store(SUPPORTED, std::memory_order_relaxed);
426 LOG(INFO) << "Using smaps_rollup for pss collection";
427 return true;
428}
429
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800430bool SmapsOrRollupFromFile(const std::string& path, MemUsage* stats) {
431 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
432 if (fp == nullptr) {
433 return false;
434 }
435
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800436 char* line = nullptr;
437 size_t line_alloc = 0;
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800438 stats->clear();
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800439 while (getline(&line, &line_alloc, fp.get()) > 0) {
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800440 switch (line[0]) {
441 case 'P':
442 if (strncmp(line, "Pss:", 4) == 0) {
443 char* c = line + 4;
444 stats->pss += strtoull(c, nullptr, 10);
445 } else if (strncmp(line, "Private_Clean:", 14) == 0) {
446 char* c = line + 14;
447 uint64_t prcl = strtoull(c, nullptr, 10);
448 stats->private_clean += prcl;
449 stats->uss += prcl;
450 } else if (strncmp(line, "Private_Dirty:", 14) == 0) {
451 char* c = line + 14;
452 uint64_t prdi = strtoull(c, nullptr, 10);
453 stats->private_dirty += prdi;
454 stats->uss += prdi;
455 }
456 break;
457 case 'R':
458 if (strncmp(line, "Rss:", 4) == 0) {
459 char* c = line + 4;
460 stats->rss += strtoull(c, nullptr, 10);
461 }
462 break;
463 case 'S':
464 if (strncmp(line, "SwapPss:", 8) == 0) {
465 char* c = line + 8;
466 stats->swap_pss += strtoull(c, nullptr, 10);
467 }
468 break;
469 }
470 }
471
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800472 // free getline() managed buffer
473 free(line);
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800474 return true;
475}
476
Sandeep Patil8871e7e2019-01-13 16:47:20 -0800477bool SmapsOrRollupPssFromFile(const std::string& path, uint64_t* pss) {
478 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
479 if (fp == nullptr) {
480 return false;
481 }
482 *pss = 0;
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800483 char* line = nullptr;
484 size_t line_alloc = 0;
485 while (getline(&line, &line_alloc, fp.get()) > 0) {
Sandeep Patil8871e7e2019-01-13 16:47:20 -0800486 uint64_t v;
487 if (sscanf(line, "Pss: %" SCNu64 " kB", &v) == 1) {
488 *pss += v;
489 }
490 }
491
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800492 // free getline() managed buffer
493 free(line);
Sandeep Patil8871e7e2019-01-13 16:47:20 -0800494 return true;
495}
496
Sandeep Patil54d87212018-08-29 17:10:47 -0700497} // namespace meminfo
498} // namespace android