blob: 1daff1ef2e9d92f8ac36f8649162256fc4d4f499 [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 Patilf1291992018-11-19 15:25:18 -080057bool ProcMemInfo::ResetWorkingSet(pid_t pid) {
58 std::string clear_refs_path = ::android::base::StringPrintf("/proc/%d/clear_refs", pid);
59 if (!::android::base::WriteStringToFile("1\n", clear_refs_path)) {
60 PLOG(ERROR) << "Failed to write to " << clear_refs_path;
61 return false;
62 }
63
64 return true;
65}
66
Sandeep Patil549feab2018-11-19 11:38:40 -080067ProcMemInfo::ProcMemInfo(pid_t pid, bool get_wss, uint64_t pgflags, uint64_t pgflags_mask)
Sandeep Patilc6497eb2018-11-20 09:31:36 -080068 : pid_(pid), get_wss_(get_wss), pgflags_(pgflags), pgflags_mask_(pgflags_mask) {}
Sandeep Patil54d87212018-08-29 17:10:47 -070069
70const std::vector<Vma>& ProcMemInfo::Maps() {
Sandeep Patilc6497eb2018-11-20 09:31:36 -080071 if (maps_.empty() && !ReadMaps(get_wss_)) {
72 LOG(ERROR) << "Failed to read maps for Process " << pid_;
73 }
74
Sandeep Patil54d87212018-08-29 17:10:47 -070075 return maps_;
76}
77
78const MemUsage& ProcMemInfo::Usage() {
79 if (get_wss_) {
Sandeep Patilf1291992018-11-19 15:25:18 -080080 LOG(WARNING) << "Trying to read process memory usage for " << pid_
81 << " using invalid object";
Sandeep Patilc6497eb2018-11-20 09:31:36 -080082 return usage_;
Sandeep Patil54d87212018-08-29 17:10:47 -070083 }
Sandeep Patilc6497eb2018-11-20 09:31:36 -080084
85 if (maps_.empty() && !ReadMaps(get_wss_)) {
86 LOG(ERROR) << "Failed to get memory usage for Process " << pid_;
87 }
88
Sandeep Patil54d87212018-08-29 17:10:47 -070089 return usage_;
90}
91
92const MemUsage& ProcMemInfo::Wss() {
93 if (!get_wss_) {
Sandeep Patilf1291992018-11-19 15:25:18 -080094 LOG(WARNING) << "Trying to read process working set for " << pid_
95 << " using invalid object";
Sandeep Patilc6497eb2018-11-20 09:31:36 -080096 return wss_;
97 }
98
99 if (maps_.empty() && !ReadMaps(get_wss_)) {
100 LOG(ERROR) << "Failed to get working set for Process " << pid_;
Sandeep Patil54d87212018-08-29 17:10:47 -0700101 }
102
103 return wss_;
104}
105
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800106bool ProcMemInfo::SmapsOrRollup(bool use_rollup, MemUsage* stats) const {
107 std::string path = ::android::base::StringPrintf("/proc/%d/%s", pid_,
108 use_rollup ? "smaps_rollup" : "smaps");
109 return SmapsOrRollupFromFile(path, stats);
110};
111
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800112const std::vector<uint16_t>& ProcMemInfo::SwapOffsets() {
113 if (get_wss_) {
114 LOG(WARNING) << "Trying to read process swap offsets for " << pid_
115 << " using invalid object";
116 return swap_offsets_;
117 }
118
119 if (maps_.empty() && !ReadMaps(get_wss_)) {
120 LOG(ERROR) << "Failed to get swap offsets for Process " << pid_;
121 }
122
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800123 return swap_offsets_;
124}
125
Sandeep Patil54d87212018-08-29 17:10:47 -0700126bool ProcMemInfo::ReadMaps(bool get_wss) {
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800127 // Each object reads /proc/<pid>/maps only once. This is done to make sure programs that are
128 // running for the lifetime of the system can recycle the objects and don't have to
129 // unnecessarily retain and update this object in memory (which can get significantly large).
130 // E.g. A program that only needs to reset the working set will never all ->Maps(), ->Usage().
131 // E.g. A program that is monitoring smaps_rollup, may never call ->maps(), Usage(), so it
132 // doesn't make sense for us to parse and retain unnecessary memory accounting stats by default.
133 if (!maps_.empty()) return true;
134
Sandeep Patil54d87212018-08-29 17:10:47 -0700135 // parse and read /proc/<pid>/maps
136 std::string maps_file = ::android::base::StringPrintf("/proc/%d/maps", pid_);
137 if (!::android::procinfo::ReadMapFile(
138 maps_file, [&](uint64_t start, uint64_t end, uint16_t flags, uint64_t pgoff,
139 const char* name) {
140 maps_.emplace_back(Vma(start, end, pgoff, flags, name));
141 })) {
142 LOG(ERROR) << "Failed to parse " << maps_file;
143 maps_.clear();
144 return false;
145 }
146
147 std::string pagemap_file = ::android::base::StringPrintf("/proc/%d/pagemap", pid_);
148 ::android::base::unique_fd pagemap_fd(
149 TEMP_FAILURE_RETRY(open(pagemap_file.c_str(), O_RDONLY | O_CLOEXEC)));
150 if (pagemap_fd < 0) {
151 PLOG(ERROR) << "Failed to open " << pagemap_file;
152 return false;
153 }
154
155 for (auto& vma : maps_) {
156 if (!ReadVmaStats(pagemap_fd.get(), vma, get_wss)) {
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800157 LOG(ERROR) << "Failed to read page map for vma " << vma.name << "[" << vma.start << "-"
158 << vma.end << "]";
Sandeep Patil54d87212018-08-29 17:10:47 -0700159 maps_.clear();
160 return false;
161 }
162 if (get_wss) {
163 add_mem_usage(&wss_, vma.wss);
164 } else {
165 add_mem_usage(&usage_, vma.usage);
166 }
167 }
168
169 return true;
170}
171
172bool ProcMemInfo::ReadVmaStats(int pagemap_fd, Vma& vma, bool get_wss) {
173 PageAcct& pinfo = PageAcct::Instance();
174 uint64_t pagesz = getpagesize();
175 uint64_t num_pages = (vma.end - vma.start) / pagesz;
176
177 std::unique_ptr<uint64_t[]> pg_frames(new uint64_t[num_pages]);
178 uint64_t first = vma.start / pagesz;
179 if (pread64(pagemap_fd, pg_frames.get(), num_pages * sizeof(uint64_t),
180 first * sizeof(uint64_t)) < 0) {
181 PLOG(ERROR) << "Failed to read page frames from page map for pid: " << pid_;
182 return false;
183 }
184
185 std::unique_ptr<uint64_t[]> pg_flags(new uint64_t[num_pages]);
186 std::unique_ptr<uint64_t[]> pg_counts(new uint64_t[num_pages]);
187 for (uint64_t i = 0; i < num_pages; ++i) {
188 if (!get_wss) {
189 vma.usage.vss += pagesz;
190 }
191 uint64_t p = pg_frames[i];
192 if (!PAGE_PRESENT(p) && !PAGE_SWAPPED(p)) continue;
193
194 if (PAGE_SWAPPED(p)) {
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800195 vma.usage.swap += pagesz;
196 swap_offsets_.emplace_back(PAGE_SWAP_OFFSET(p));
Sandeep Patil54d87212018-08-29 17:10:47 -0700197 continue;
198 }
199
200 uint64_t page_frame = PAGE_PFN(p);
201 if (!pinfo.PageFlags(page_frame, &pg_flags[i])) {
202 LOG(ERROR) << "Failed to get page flags for " << page_frame << " in process " << pid_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800203 swap_offsets_.clear();
Sandeep Patil54d87212018-08-29 17:10:47 -0700204 return false;
205 }
206
Sandeep Patil549feab2018-11-19 11:38:40 -0800207 // skip unwanted pages from the count
208 if ((pg_flags[i] & pgflags_mask_) != pgflags_) continue;
209
Sandeep Patil54d87212018-08-29 17:10:47 -0700210 if (!pinfo.PageMapCount(page_frame, &pg_counts[i])) {
211 LOG(ERROR) << "Failed to get page count for " << page_frame << " in process " << pid_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800212 swap_offsets_.clear();
Sandeep Patil54d87212018-08-29 17:10:47 -0700213 return false;
214 }
215
216 // Page was unmapped between the presence check at the beginning of the loop and here.
217 if (pg_counts[i] == 0) {
218 pg_frames[i] = 0;
219 pg_flags[i] = 0;
220 continue;
221 }
222
223 bool is_dirty = !!(pg_flags[i] & (1 << KPF_DIRTY));
224 bool is_private = (pg_counts[i] == 1);
225 // Working set
226 if (get_wss) {
227 bool is_referenced = !!(pg_flags[i] & (1 << KPF_REFERENCED));
228 if (!is_referenced) {
229 continue;
230 }
231 // This effectively makes vss = rss for the working set is requested.
232 // The libpagemap implementation returns vss > rss for
233 // working set, which doesn't make sense.
234 vma.wss.vss += pagesz;
235 vma.wss.rss += pagesz;
236 vma.wss.uss += is_private ? pagesz : 0;
237 vma.wss.pss += pagesz / pg_counts[i];
238 if (is_private) {
239 vma.wss.private_dirty += is_dirty ? pagesz : 0;
240 vma.wss.private_clean += is_dirty ? 0 : pagesz;
241 } else {
242 vma.wss.shared_dirty += is_dirty ? pagesz : 0;
243 vma.wss.shared_clean += is_dirty ? 0 : pagesz;
244 }
245 } else {
246 vma.usage.rss += pagesz;
247 vma.usage.uss += is_private ? pagesz : 0;
248 vma.usage.pss += pagesz / pg_counts[i];
249 if (is_private) {
250 vma.usage.private_dirty += is_dirty ? pagesz : 0;
251 vma.usage.private_clean += is_dirty ? 0 : pagesz;
252 } else {
253 vma.usage.shared_dirty += is_dirty ? pagesz : 0;
254 vma.usage.shared_clean += is_dirty ? 0 : pagesz;
255 }
256 }
257 }
258
259 return true;
260}
261
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800262// Public APIs
263bool SmapsOrRollupFromFile(const std::string& path, MemUsage* stats) {
264 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
265 if (fp == nullptr) {
266 return false;
267 }
268
269 char line[1024];
270 stats->clear();
271 while (fgets(line, sizeof(line), fp.get()) != nullptr) {
272 switch (line[0]) {
273 case 'P':
274 if (strncmp(line, "Pss:", 4) == 0) {
275 char* c = line + 4;
276 stats->pss += strtoull(c, nullptr, 10);
277 } else if (strncmp(line, "Private_Clean:", 14) == 0) {
278 char* c = line + 14;
279 uint64_t prcl = strtoull(c, nullptr, 10);
280 stats->private_clean += prcl;
281 stats->uss += prcl;
282 } else if (strncmp(line, "Private_Dirty:", 14) == 0) {
283 char* c = line + 14;
284 uint64_t prdi = strtoull(c, nullptr, 10);
285 stats->private_dirty += prdi;
286 stats->uss += prdi;
287 }
288 break;
289 case 'R':
290 if (strncmp(line, "Rss:", 4) == 0) {
291 char* c = line + 4;
292 stats->rss += strtoull(c, nullptr, 10);
293 }
294 break;
295 case 'S':
296 if (strncmp(line, "SwapPss:", 8) == 0) {
297 char* c = line + 8;
298 stats->swap_pss += strtoull(c, nullptr, 10);
299 }
300 break;
301 }
302 }
303
304 return true;
305}
306
Sandeep Patil54d87212018-08-29 17:10:47 -0700307} // namespace meminfo
308} // namespace android