blob: 18ae9784a6c4342bd9d7dd12567eab833c57223b [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 Patilc6497eb2018-11-20 09:31:36 -0800160 return wss_;
161 }
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
167 return wss_;
168}
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 Patilc6497eb2018-11-20 09:31:36 -0800181const std::vector<uint16_t>& ProcMemInfo::SwapOffsets() {
182 if (get_wss_) {
183 LOG(WARNING) << "Trying to read process swap offsets for " << pid_
184 << " using invalid object";
185 return swap_offsets_;
186 }
187
188 if (maps_.empty() && !ReadMaps(get_wss_)) {
189 LOG(ERROR) << "Failed to get swap offsets for Process " << pid_;
190 }
191
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800192 return swap_offsets_;
193}
194
Sandeep Patil54d87212018-08-29 17:10:47 -0700195bool ProcMemInfo::ReadMaps(bool get_wss) {
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800196 // Each object reads /proc/<pid>/maps only once. This is done to make sure programs that are
197 // running for the lifetime of the system can recycle the objects and don't have to
198 // unnecessarily retain and update this object in memory (which can get significantly large).
199 // E.g. A program that only needs to reset the working set will never all ->Maps(), ->Usage().
200 // E.g. A program that is monitoring smaps_rollup, may never call ->maps(), Usage(), so it
201 // doesn't make sense for us to parse and retain unnecessary memory accounting stats by default.
202 if (!maps_.empty()) return true;
203
Sandeep Patil54d87212018-08-29 17:10:47 -0700204 // parse and read /proc/<pid>/maps
205 std::string maps_file = ::android::base::StringPrintf("/proc/%d/maps", pid_);
206 if (!::android::procinfo::ReadMapFile(
207 maps_file, [&](uint64_t start, uint64_t end, uint16_t flags, uint64_t pgoff,
208 const char* name) {
209 maps_.emplace_back(Vma(start, end, pgoff, flags, name));
210 })) {
211 LOG(ERROR) << "Failed to parse " << maps_file;
212 maps_.clear();
213 return false;
214 }
215
216 std::string pagemap_file = ::android::base::StringPrintf("/proc/%d/pagemap", pid_);
217 ::android::base::unique_fd pagemap_fd(
218 TEMP_FAILURE_RETRY(open(pagemap_file.c_str(), O_RDONLY | O_CLOEXEC)));
219 if (pagemap_fd < 0) {
220 PLOG(ERROR) << "Failed to open " << pagemap_file;
221 return false;
222 }
223
224 for (auto& vma : maps_) {
225 if (!ReadVmaStats(pagemap_fd.get(), vma, get_wss)) {
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800226 LOG(ERROR) << "Failed to read page map for vma " << vma.name << "[" << vma.start << "-"
227 << vma.end << "]";
Sandeep Patil54d87212018-08-29 17:10:47 -0700228 maps_.clear();
229 return false;
230 }
231 if (get_wss) {
232 add_mem_usage(&wss_, vma.wss);
233 } else {
234 add_mem_usage(&usage_, vma.usage);
235 }
236 }
237
238 return true;
239}
240
241bool ProcMemInfo::ReadVmaStats(int pagemap_fd, Vma& vma, bool get_wss) {
242 PageAcct& pinfo = PageAcct::Instance();
243 uint64_t pagesz = getpagesize();
244 uint64_t num_pages = (vma.end - vma.start) / pagesz;
245
246 std::unique_ptr<uint64_t[]> pg_frames(new uint64_t[num_pages]);
247 uint64_t first = vma.start / pagesz;
248 if (pread64(pagemap_fd, pg_frames.get(), num_pages * sizeof(uint64_t),
249 first * sizeof(uint64_t)) < 0) {
250 PLOG(ERROR) << "Failed to read page frames from page map for pid: " << pid_;
251 return false;
252 }
253
254 std::unique_ptr<uint64_t[]> pg_flags(new uint64_t[num_pages]);
255 std::unique_ptr<uint64_t[]> pg_counts(new uint64_t[num_pages]);
256 for (uint64_t i = 0; i < num_pages; ++i) {
257 if (!get_wss) {
258 vma.usage.vss += pagesz;
259 }
260 uint64_t p = pg_frames[i];
261 if (!PAGE_PRESENT(p) && !PAGE_SWAPPED(p)) continue;
262
263 if (PAGE_SWAPPED(p)) {
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800264 vma.usage.swap += pagesz;
265 swap_offsets_.emplace_back(PAGE_SWAP_OFFSET(p));
Sandeep Patil54d87212018-08-29 17:10:47 -0700266 continue;
267 }
268
269 uint64_t page_frame = PAGE_PFN(p);
270 if (!pinfo.PageFlags(page_frame, &pg_flags[i])) {
271 LOG(ERROR) << "Failed to get page flags for " << page_frame << " in process " << pid_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800272 swap_offsets_.clear();
Sandeep Patil54d87212018-08-29 17:10:47 -0700273 return false;
274 }
275
Sandeep Patil549feab2018-11-19 11:38:40 -0800276 // skip unwanted pages from the count
277 if ((pg_flags[i] & pgflags_mask_) != pgflags_) continue;
278
Sandeep Patil54d87212018-08-29 17:10:47 -0700279 if (!pinfo.PageMapCount(page_frame, &pg_counts[i])) {
280 LOG(ERROR) << "Failed to get page count for " << page_frame << " in process " << pid_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800281 swap_offsets_.clear();
Sandeep Patil54d87212018-08-29 17:10:47 -0700282 return false;
283 }
284
285 // Page was unmapped between the presence check at the beginning of the loop and here.
286 if (pg_counts[i] == 0) {
287 pg_frames[i] = 0;
288 pg_flags[i] = 0;
289 continue;
290 }
291
292 bool is_dirty = !!(pg_flags[i] & (1 << KPF_DIRTY));
293 bool is_private = (pg_counts[i] == 1);
294 // Working set
295 if (get_wss) {
296 bool is_referenced = !!(pg_flags[i] & (1 << KPF_REFERENCED));
297 if (!is_referenced) {
298 continue;
299 }
300 // This effectively makes vss = rss for the working set is requested.
301 // The libpagemap implementation returns vss > rss for
302 // working set, which doesn't make sense.
303 vma.wss.vss += pagesz;
304 vma.wss.rss += pagesz;
305 vma.wss.uss += is_private ? pagesz : 0;
306 vma.wss.pss += pagesz / pg_counts[i];
307 if (is_private) {
308 vma.wss.private_dirty += is_dirty ? pagesz : 0;
309 vma.wss.private_clean += is_dirty ? 0 : pagesz;
310 } else {
311 vma.wss.shared_dirty += is_dirty ? pagesz : 0;
312 vma.wss.shared_clean += is_dirty ? 0 : pagesz;
313 }
314 } else {
315 vma.usage.rss += pagesz;
316 vma.usage.uss += is_private ? pagesz : 0;
317 vma.usage.pss += pagesz / pg_counts[i];
318 if (is_private) {
319 vma.usage.private_dirty += is_dirty ? pagesz : 0;
320 vma.usage.private_clean += is_dirty ? 0 : pagesz;
321 } else {
322 vma.usage.shared_dirty += is_dirty ? pagesz : 0;
323 vma.usage.shared_clean += is_dirty ? 0 : pagesz;
324 }
325 }
326 }
327
328 return true;
329}
330
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800331// Public APIs
Sandeep Patil82a48b12019-01-01 16:04:04 -0800332bool ForEachVmaFromFile(const std::string& path, const VmaCallback& callback) {
333 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
334 if (fp == nullptr) {
335 return false;
336 }
337
338 char* line = nullptr;
339 bool parsing_vma = false;
340 ssize_t line_len;
Sandeep Patil002f02e2019-01-13 19:39:46 -0800341 size_t line_alloc = 0;
Sandeep Patil82a48b12019-01-01 16:04:04 -0800342 Vma vma;
Sandeep Patil002f02e2019-01-13 19:39:46 -0800343 while ((line_len = getline(&line, &line_alloc, fp.get())) > 0) {
Sandeep Patil82a48b12019-01-01 16:04:04 -0800344 // Make sure the line buffer terminates like a C string for ReadMapFile
345 line[line_len] = '\0';
346
347 if (parsing_vma) {
348 if (parse_smaps_field(line, &vma.usage)) {
349 // This was a stats field
350 continue;
351 }
352
353 // Done collecting stats, make the call back
354 callback(vma);
355 parsing_vma = false;
356 }
357
358 vma.clear();
359 // If it has, we are looking for the vma stats
360 // 00400000-00409000 r-xp 00000000 fc:00 426998 /usr/lib/gvfs/gvfsd-http
361 if (!::android::procinfo::ReadMapFileContent(
362 line, [&](uint64_t start, uint64_t end, uint16_t flags, uint64_t pgoff,
363 const char* name) {
364 vma.start = start;
365 vma.end = end;
366 vma.flags = flags;
367 vma.offset = pgoff;
368 vma.name = name;
369 })) {
370 LOG(ERROR) << "Failed to parse " << path;
371 return false;
372 }
373 parsing_vma = true;
374 }
375
376 // free getline() managed buffer
377 free(line);
378
379 if (parsing_vma) {
380 callback(vma);
381 }
382
383 return true;
384}
385
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800386bool SmapsOrRollupFromFile(const std::string& path, MemUsage* stats) {
387 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
388 if (fp == nullptr) {
389 return false;
390 }
391
392 char line[1024];
393 stats->clear();
394 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
395 switch (line[0]) {
396 case 'P':
397 if (strncmp(line, "Pss:", 4) == 0) {
398 char* c = line + 4;
399 stats->pss += strtoull(c, nullptr, 10);
400 } else if (strncmp(line, "Private_Clean:", 14) == 0) {
401 char* c = line + 14;
402 uint64_t prcl = strtoull(c, nullptr, 10);
403 stats->private_clean += prcl;
404 stats->uss += prcl;
405 } else if (strncmp(line, "Private_Dirty:", 14) == 0) {
406 char* c = line + 14;
407 uint64_t prdi = strtoull(c, nullptr, 10);
408 stats->private_dirty += prdi;
409 stats->uss += prdi;
410 }
411 break;
412 case 'R':
413 if (strncmp(line, "Rss:", 4) == 0) {
414 char* c = line + 4;
415 stats->rss += strtoull(c, nullptr, 10);
416 }
417 break;
418 case 'S':
419 if (strncmp(line, "SwapPss:", 8) == 0) {
420 char* c = line + 8;
421 stats->swap_pss += strtoull(c, nullptr, 10);
422 }
423 break;
424 }
425 }
426
427 return true;
428}
429
Sandeep Patil54d87212018-08-29 17:10:47 -0700430} // namespace meminfo
431} // namespace android