blob: f72d46964f9adf704f60125d769a8e62fdc36746 [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
24#include <fstream>
25#include <iostream>
26#include <memory>
27#include <string>
28#include <utility>
29
30#include <android-base/file.h>
31#include <android-base/logging.h>
32#include <android-base/stringprintf.h>
Sandeep Patilfa2d8d52018-12-29 21:05:38 -080033#include <android-base/strings.h>
Sandeep Patil54d87212018-08-29 17:10:47 -070034#include <android-base/unique_fd.h>
35#include <procinfo/process_map.h>
36
37#include "meminfo_private.h"
38
39namespace android {
40namespace meminfo {
41
42static void add_mem_usage(MemUsage* to, const MemUsage& from) {
43 to->vss += from.vss;
44 to->rss += from.rss;
45 to->pss += from.pss;
46 to->uss += from.uss;
47
Sandeep Patil2259fdf2018-11-09 16:42:45 -080048 to->swap += from.swap;
49
Sandeep Patil54d87212018-08-29 17:10:47 -070050 to->private_clean += from.private_clean;
51 to->private_dirty += from.private_dirty;
52
53 to->shared_clean += from.shared_clean;
54 to->shared_dirty += from.shared_dirty;
55}
56
Sandeep Patil82a48b12019-01-01 16:04:04 -080057// Returns true if the line was valid smaps stats line false otherwise.
58static bool parse_smaps_field(const char* line, MemUsage* stats) {
59 char field[64];
60 int len;
61 if (sscanf(line, "%63s %n", field, &len) == 1 && *field && field[strlen(field) - 1] == ':') {
62 const char* c = line + len;
63 switch (field[0]) {
64 case 'P':
65 if (strncmp(field, "Pss:", 4) == 0) {
66 stats->pss = strtoull(c, nullptr, 10);
67 } else if (strncmp(field, "Private_Clean:", 14) == 0) {
68 uint64_t prcl = strtoull(c, nullptr, 10);
69 stats->private_clean = prcl;
70 stats->uss += prcl;
71 } else if (strncmp(field, "Private_Dirty:", 14) == 0) {
72 uint64_t prdi = strtoull(c, nullptr, 10);
73 stats->private_dirty = prdi;
74 stats->uss += prdi;
75 }
76 break;
77 case 'S':
78 if (strncmp(field, "Size:", 5) == 0) {
79 stats->vss = strtoull(c, nullptr, 10);
80 } else if (strncmp(field, "Shared_Clean:", 13) == 0) {
81 stats->shared_clean = strtoull(c, nullptr, 10);
82 } else if (strncmp(field, "Shared_Dirty:", 13) == 0) {
83 stats->shared_dirty = strtoull(c, nullptr, 10);
84 } else if (strncmp(field, "Swap:", 5) == 0) {
85 stats->swap = strtoull(c, nullptr, 10);
86 } else if (strncmp(field, "SwapPss:", 8) == 0) {
87 stats->swap_pss = strtoull(c, nullptr, 10);
88 }
89 break;
90 case 'R':
91 if (strncmp(field, "Rss:", 4) == 0) {
92 stats->rss = strtoull(c, nullptr, 10);
93 }
94 break;
95 }
96 return true;
97 }
98
99 return false;
100}
101
Sandeep Patilf1291992018-11-19 15:25:18 -0800102bool ProcMemInfo::ResetWorkingSet(pid_t pid) {
103 std::string clear_refs_path = ::android::base::StringPrintf("/proc/%d/clear_refs", pid);
104 if (!::android::base::WriteStringToFile("1\n", clear_refs_path)) {
105 PLOG(ERROR) << "Failed to write to " << clear_refs_path;
106 return false;
107 }
108
109 return true;
110}
111
Sandeep Patil549feab2018-11-19 11:38:40 -0800112ProcMemInfo::ProcMemInfo(pid_t pid, bool get_wss, uint64_t pgflags, uint64_t pgflags_mask)
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800113 : pid_(pid), get_wss_(get_wss), pgflags_(pgflags), pgflags_mask_(pgflags_mask) {}
Sandeep Patil54d87212018-08-29 17:10:47 -0700114
115const std::vector<Vma>& ProcMemInfo::Maps() {
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800116 if (maps_.empty() && !ReadMaps(get_wss_)) {
117 LOG(ERROR) << "Failed to read maps for Process " << pid_;
118 }
119
Sandeep Patil54d87212018-08-29 17:10:47 -0700120 return maps_;
121}
122
Sandeep Patil82a48b12019-01-01 16:04:04 -0800123const std::vector<Vma>& ProcMemInfo::Smaps(const std::string& path) {
124 if (!maps_.empty()) {
125 return maps_;
126 }
127
128 auto collect_vmas = [&](const Vma& vma) { maps_.emplace_back(vma); };
129 if (path.empty() && !ForEachVma(collect_vmas)) {
130 LOG(ERROR) << "Failed to read smaps for Process " << pid_;
131 maps_.clear();
132 }
133
134 if (!path.empty() && !ForEachVmaFromFile(path, collect_vmas)) {
135 LOG(ERROR) << "Failed to read smaps from file " << path;
136 maps_.clear();
137 }
138
139 return maps_;
140}
141
Sandeep Patil54d87212018-08-29 17:10:47 -0700142const MemUsage& ProcMemInfo::Usage() {
143 if (get_wss_) {
Sandeep Patilf1291992018-11-19 15:25:18 -0800144 LOG(WARNING) << "Trying to read process memory usage for " << pid_
145 << " using invalid object";
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800146 return usage_;
Sandeep Patil54d87212018-08-29 17:10:47 -0700147 }
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800148
149 if (maps_.empty() && !ReadMaps(get_wss_)) {
150 LOG(ERROR) << "Failed to get memory usage for Process " << pid_;
151 }
152
Sandeep Patil54d87212018-08-29 17:10:47 -0700153 return usage_;
154}
155
156const MemUsage& ProcMemInfo::Wss() {
157 if (!get_wss_) {
Sandeep Patilf1291992018-11-19 15:25:18 -0800158 LOG(WARNING) << "Trying to read process working set for " << pid_
159 << " using invalid object";
Sandeep Patil56c414e2019-01-12 21:29:19 -0800160 return usage_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800161 }
162
163 if (maps_.empty() && !ReadMaps(get_wss_)) {
164 LOG(ERROR) << "Failed to get working set for Process " << pid_;
Sandeep Patil54d87212018-08-29 17:10:47 -0700165 }
166
Sandeep Patil56c414e2019-01-12 21:29:19 -0800167 return usage_;
Sandeep Patil54d87212018-08-29 17:10:47 -0700168}
169
Sandeep Patil82a48b12019-01-01 16:04:04 -0800170bool ProcMemInfo::ForEachVma(const VmaCallback& callback) {
171 std::string path = ::android::base::StringPrintf("/proc/%d/smaps", pid_);
172 return ForEachVmaFromFile(path, callback);
173}
174
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800175bool ProcMemInfo::SmapsOrRollup(bool use_rollup, MemUsage* stats) const {
176 std::string path = ::android::base::StringPrintf("/proc/%d/%s", pid_,
177 use_rollup ? "smaps_rollup" : "smaps");
178 return SmapsOrRollupFromFile(path, stats);
179};
180
Sandeep Patil8871e7e2019-01-13 16:47:20 -0800181bool ProcMemInfo::SmapsOrRollupPss(bool use_rollup, uint64_t* pss) const {
182 std::string path = ::android::base::StringPrintf("/proc/%d/%s", pid_,
183 use_rollup ? "smaps_rollup" : "smaps");
184 return SmapsOrRollupPssFromFile(path, pss);
185}
186
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800187const std::vector<uint16_t>& ProcMemInfo::SwapOffsets() {
188 if (get_wss_) {
189 LOG(WARNING) << "Trying to read process swap offsets for " << pid_
190 << " using invalid object";
191 return swap_offsets_;
192 }
193
194 if (maps_.empty() && !ReadMaps(get_wss_)) {
195 LOG(ERROR) << "Failed to get swap offsets for Process " << pid_;
196 }
197
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800198 return swap_offsets_;
199}
200
Sandeep Patil54d87212018-08-29 17:10:47 -0700201bool ProcMemInfo::ReadMaps(bool get_wss) {
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800202 // Each object reads /proc/<pid>/maps only once. This is done to make sure programs that are
203 // running for the lifetime of the system can recycle the objects and don't have to
204 // unnecessarily retain and update this object in memory (which can get significantly large).
205 // E.g. A program that only needs to reset the working set will never all ->Maps(), ->Usage().
206 // E.g. A program that is monitoring smaps_rollup, may never call ->maps(), Usage(), so it
207 // doesn't make sense for us to parse and retain unnecessary memory accounting stats by default.
208 if (!maps_.empty()) return true;
209
Sandeep Patil54d87212018-08-29 17:10:47 -0700210 // parse and read /proc/<pid>/maps
211 std::string maps_file = ::android::base::StringPrintf("/proc/%d/maps", pid_);
212 if (!::android::procinfo::ReadMapFile(
213 maps_file, [&](uint64_t start, uint64_t end, uint16_t flags, uint64_t pgoff,
214 const char* name) {
215 maps_.emplace_back(Vma(start, end, pgoff, flags, name));
216 })) {
217 LOG(ERROR) << "Failed to parse " << maps_file;
218 maps_.clear();
219 return false;
220 }
221
222 std::string pagemap_file = ::android::base::StringPrintf("/proc/%d/pagemap", pid_);
223 ::android::base::unique_fd pagemap_fd(
224 TEMP_FAILURE_RETRY(open(pagemap_file.c_str(), O_RDONLY | O_CLOEXEC)));
225 if (pagemap_fd < 0) {
226 PLOG(ERROR) << "Failed to open " << pagemap_file;
227 return false;
228 }
229
230 for (auto& vma : maps_) {
231 if (!ReadVmaStats(pagemap_fd.get(), vma, get_wss)) {
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800232 LOG(ERROR) << "Failed to read page map for vma " << vma.name << "[" << vma.start << "-"
233 << vma.end << "]";
Sandeep Patil54d87212018-08-29 17:10:47 -0700234 maps_.clear();
235 return false;
236 }
Sandeep Patil56c414e2019-01-12 21:29:19 -0800237 add_mem_usage(&usage_, vma.usage);
Sandeep Patil54d87212018-08-29 17:10:47 -0700238 }
239
240 return true;
241}
242
243bool ProcMemInfo::ReadVmaStats(int pagemap_fd, Vma& vma, bool get_wss) {
244 PageAcct& pinfo = PageAcct::Instance();
245 uint64_t pagesz = getpagesize();
246 uint64_t num_pages = (vma.end - vma.start) / pagesz;
247
248 std::unique_ptr<uint64_t[]> pg_frames(new uint64_t[num_pages]);
249 uint64_t first = vma.start / pagesz;
250 if (pread64(pagemap_fd, pg_frames.get(), num_pages * sizeof(uint64_t),
251 first * sizeof(uint64_t)) < 0) {
252 PLOG(ERROR) << "Failed to read page frames from page map for pid: " << pid_;
253 return false;
254 }
255
256 std::unique_ptr<uint64_t[]> pg_flags(new uint64_t[num_pages]);
257 std::unique_ptr<uint64_t[]> pg_counts(new uint64_t[num_pages]);
258 for (uint64_t i = 0; i < num_pages; ++i) {
259 if (!get_wss) {
260 vma.usage.vss += pagesz;
261 }
262 uint64_t p = pg_frames[i];
263 if (!PAGE_PRESENT(p) && !PAGE_SWAPPED(p)) continue;
264
265 if (PAGE_SWAPPED(p)) {
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800266 vma.usage.swap += pagesz;
267 swap_offsets_.emplace_back(PAGE_SWAP_OFFSET(p));
Sandeep Patil54d87212018-08-29 17:10:47 -0700268 continue;
269 }
270
271 uint64_t page_frame = PAGE_PFN(p);
272 if (!pinfo.PageFlags(page_frame, &pg_flags[i])) {
273 LOG(ERROR) << "Failed to get page flags for " << page_frame << " in process " << pid_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800274 swap_offsets_.clear();
Sandeep Patil54d87212018-08-29 17:10:47 -0700275 return false;
276 }
277
Sandeep Patil549feab2018-11-19 11:38:40 -0800278 // skip unwanted pages from the count
279 if ((pg_flags[i] & pgflags_mask_) != pgflags_) continue;
280
Sandeep Patil54d87212018-08-29 17:10:47 -0700281 if (!pinfo.PageMapCount(page_frame, &pg_counts[i])) {
282 LOG(ERROR) << "Failed to get page count for " << page_frame << " in process " << pid_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800283 swap_offsets_.clear();
Sandeep Patil54d87212018-08-29 17:10:47 -0700284 return false;
285 }
286
287 // Page was unmapped between the presence check at the beginning of the loop and here.
288 if (pg_counts[i] == 0) {
289 pg_frames[i] = 0;
290 pg_flags[i] = 0;
291 continue;
292 }
293
294 bool is_dirty = !!(pg_flags[i] & (1 << KPF_DIRTY));
295 bool is_private = (pg_counts[i] == 1);
296 // Working set
297 if (get_wss) {
298 bool is_referenced = !!(pg_flags[i] & (1 << KPF_REFERENCED));
299 if (!is_referenced) {
300 continue;
301 }
302 // This effectively makes vss = rss for the working set is requested.
303 // The libpagemap implementation returns vss > rss for
304 // working set, which doesn't make sense.
Sandeep Patil56c414e2019-01-12 21:29:19 -0800305 vma.usage.vss += pagesz;
306 }
307
308 vma.usage.rss += pagesz;
309 vma.usage.uss += is_private ? pagesz : 0;
310 vma.usage.pss += pagesz / pg_counts[i];
311 if (is_private) {
312 vma.usage.private_dirty += is_dirty ? pagesz : 0;
313 vma.usage.private_clean += is_dirty ? 0 : pagesz;
Sandeep Patil54d87212018-08-29 17:10:47 -0700314 } else {
Sandeep Patil56c414e2019-01-12 21:29:19 -0800315 vma.usage.shared_dirty += is_dirty ? pagesz : 0;
316 vma.usage.shared_clean += is_dirty ? 0 : pagesz;
Sandeep Patil54d87212018-08-29 17:10:47 -0700317 }
318 }
Sandeep Patil54d87212018-08-29 17:10:47 -0700319 return true;
320}
321
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800322// Public APIs
Sandeep Patil82a48b12019-01-01 16:04:04 -0800323bool ForEachVmaFromFile(const std::string& path, const VmaCallback& callback) {
324 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
325 if (fp == nullptr) {
326 return false;
327 }
328
329 char* line = nullptr;
330 bool parsing_vma = false;
331 ssize_t line_len;
Sandeep Patil002f02e2019-01-13 19:39:46 -0800332 size_t line_alloc = 0;
Sandeep Patil82a48b12019-01-01 16:04:04 -0800333 Vma vma;
Sandeep Patil002f02e2019-01-13 19:39:46 -0800334 while ((line_len = getline(&line, &line_alloc, fp.get())) > 0) {
Sandeep Patil82a48b12019-01-01 16:04:04 -0800335 // Make sure the line buffer terminates like a C string for ReadMapFile
336 line[line_len] = '\0';
337
338 if (parsing_vma) {
339 if (parse_smaps_field(line, &vma.usage)) {
340 // This was a stats field
341 continue;
342 }
343
344 // Done collecting stats, make the call back
345 callback(vma);
346 parsing_vma = false;
347 }
348
349 vma.clear();
350 // If it has, we are looking for the vma stats
351 // 00400000-00409000 r-xp 00000000 fc:00 426998 /usr/lib/gvfs/gvfsd-http
352 if (!::android::procinfo::ReadMapFileContent(
353 line, [&](uint64_t start, uint64_t end, uint16_t flags, uint64_t pgoff,
354 const char* name) {
355 vma.start = start;
356 vma.end = end;
357 vma.flags = flags;
358 vma.offset = pgoff;
359 vma.name = name;
360 })) {
361 LOG(ERROR) << "Failed to parse " << path;
362 return false;
363 }
364 parsing_vma = true;
365 }
366
367 // free getline() managed buffer
368 free(line);
369
370 if (parsing_vma) {
371 callback(vma);
372 }
373
374 return true;
375}
376
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800377bool SmapsOrRollupFromFile(const std::string& path, MemUsage* stats) {
378 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
379 if (fp == nullptr) {
380 return false;
381 }
382
383 char line[1024];
384 stats->clear();
385 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
386 switch (line[0]) {
387 case 'P':
388 if (strncmp(line, "Pss:", 4) == 0) {
389 char* c = line + 4;
390 stats->pss += strtoull(c, nullptr, 10);
391 } else if (strncmp(line, "Private_Clean:", 14) == 0) {
392 char* c = line + 14;
393 uint64_t prcl = strtoull(c, nullptr, 10);
394 stats->private_clean += prcl;
395 stats->uss += prcl;
396 } else if (strncmp(line, "Private_Dirty:", 14) == 0) {
397 char* c = line + 14;
398 uint64_t prdi = strtoull(c, nullptr, 10);
399 stats->private_dirty += prdi;
400 stats->uss += prdi;
401 }
402 break;
403 case 'R':
404 if (strncmp(line, "Rss:", 4) == 0) {
405 char* c = line + 4;
406 stats->rss += strtoull(c, nullptr, 10);
407 }
408 break;
409 case 'S':
410 if (strncmp(line, "SwapPss:", 8) == 0) {
411 char* c = line + 8;
412 stats->swap_pss += strtoull(c, nullptr, 10);
413 }
414 break;
415 }
416 }
417
418 return true;
419}
420
Sandeep Patil8871e7e2019-01-13 16:47:20 -0800421bool SmapsOrRollupPssFromFile(const std::string& path, uint64_t* pss) {
422 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
423 if (fp == nullptr) {
424 return false;
425 }
426 *pss = 0;
427 char line[1024];
428 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
429 uint64_t v;
430 if (sscanf(line, "Pss: %" SCNu64 " kB", &v) == 1) {
431 *pss += v;
432 }
433 }
434
435 return true;
436}
437
Sandeep Patil54d87212018-08-29 17:10:47 -0700438} // namespace meminfo
439} // namespace android