blob: 1e44ff9bd4ce111575a1667a5d448c887e13cd24 [file] [log] [blame]
Sandeep Patila14119d2018-11-16 09:18:57 -08001/*
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
Sandeep Patilba98e0e2019-04-09 12:31:36 -070017#include <android-base/file.h>
18#include <android-base/parseint.h>
19#include <android-base/stringprintf.h>
20#include <android-base/strings.h>
Sandeep Patila14119d2018-11-16 09:18:57 -080021#include <dirent.h>
22#include <errno.h>
23#include <inttypes.h>
24#include <linux/kernel-page-flags.h>
25#include <linux/oom.h>
Sandeep Patilba98e0e2019-04-09 12:31:36 -070026#include <meminfo/procmeminfo.h>
27#include <meminfo/sysmeminfo.h>
Sandeep Patila14119d2018-11-16 09:18:57 -080028#include <stdio.h>
29#include <stdlib.h>
30#include <sys/types.h>
31#include <unistd.h>
32
33#include <iostream>
34#include <memory>
35#include <sstream>
36#include <vector>
37
Sandeep Patila14119d2018-11-16 09:18:57 -080038using ::android::meminfo::MemUsage;
39using ::android::meminfo::ProcMemInfo;
40
41struct ProcessRecord {
42 public:
43 ProcessRecord(pid_t pid, bool get_wss = false, uint64_t pgflags = 0, uint64_t pgflags_mask = 0)
44 : pid_(-1),
Sandeep Patila14119d2018-11-16 09:18:57 -080045 oomadj_(OOM_SCORE_ADJ_MAX + 1),
46 cmdline_(""),
47 proportional_swap_(0),
48 unique_swap_(0),
49 zswap_(0) {
50 std::unique_ptr<ProcMemInfo> procmem =
51 std::make_unique<ProcMemInfo>(pid, get_wss, pgflags, pgflags_mask);
52 if (procmem == nullptr) {
53 std::cerr << "Failed to create ProcMemInfo for: " << pid << std::endl;
54 return;
55 }
56
57 std::string fname = ::android::base::StringPrintf("/proc/%d/oom_score_adj", pid);
58 auto oomscore_fp =
59 std::unique_ptr<FILE, decltype(&fclose)>{fopen(fname.c_str(), "re"), fclose};
60 if (oomscore_fp == nullptr) {
61 std::cerr << "Failed to open oom_score_adj file: " << fname << std::endl;
62 return;
63 }
64
65 if (fscanf(oomscore_fp.get(), "%d\n", &oomadj_) != 1) {
66 std::cerr << "Failed to read oomadj from: " << fname << std::endl;
67 return;
68 }
69
70 fname = ::android::base::StringPrintf("/proc/%d/cmdline", pid);
71 if (!::android::base::ReadFileToString(fname, &cmdline_)) {
72 std::cerr << "Failed to read cmdline from: " << fname << std::endl;
73 cmdline_ = "<unknown>";
74 }
75 // We deliberately don't read the proc/<pid>cmdline file directly into 'cmdline_'
76 // because of some processes showing up cmdlines that end with "0x00 0x0A 0x00"
77 // e.g. xtra-daemon, lowi-server
78 // The .c_str() assignment below then takes care of trimming the cmdline at the first
79 // 0x00. This is how original procrank worked (luckily)
80 cmdline_.resize(strlen(cmdline_.c_str()));
Sandeep Patila42207e2019-04-17 11:38:15 -070081 usage_or_wss_ = get_wss ? procmem->Wss() : procmem->Usage();
82 swap_offsets_ = procmem->SwapOffsets();
Sandeep Patila14119d2018-11-16 09:18:57 -080083 pid_ = pid;
84 }
85
86 bool valid() const { return pid_ != -1; }
87
88 void CalculateSwap(const uint16_t* swap_offset_array, float zram_compression_ratio) {
Sandeep Patila42207e2019-04-17 11:38:15 -070089 for (auto& off : swap_offsets_) {
Sandeep Patila14119d2018-11-16 09:18:57 -080090 proportional_swap_ += getpagesize() / swap_offset_array[off];
91 unique_swap_ += swap_offset_array[off] == 1 ? getpagesize() : 0;
92 zswap_ = proportional_swap_ * zram_compression_ratio;
93 }
94 }
95
96 // Getters
97 pid_t pid() const { return pid_; }
98 const std::string& cmdline() const { return cmdline_; }
99 int32_t oomadj() const { return oomadj_; }
100 uint64_t proportional_swap() const { return proportional_swap_; }
101 uint64_t unique_swap() const { return unique_swap_; }
102 uint64_t zswap() const { return zswap_; }
103
104 // Wrappers to ProcMemInfo
Sandeep Patila42207e2019-04-17 11:38:15 -0700105 const std::vector<uint16_t>& SwapOffsets() const { return swap_offsets_; }
106 const MemUsage& Usage() const { return usage_or_wss_; }
107 const MemUsage& Wss() const { return usage_or_wss_; }
Sandeep Patila14119d2018-11-16 09:18:57 -0800108
109 private:
110 pid_t pid_;
Sandeep Patila14119d2018-11-16 09:18:57 -0800111 int32_t oomadj_;
112 std::string cmdline_;
113 uint64_t proportional_swap_;
114 uint64_t unique_swap_;
115 uint64_t zswap_;
Sandeep Patila42207e2019-04-17 11:38:15 -0700116 MemUsage usage_or_wss_;
117 std::vector<uint16_t> swap_offsets_;
Sandeep Patila14119d2018-11-16 09:18:57 -0800118};
119
120// Show working set instead of memory consumption
121bool show_wss = false;
122// Reset working set of each process
123bool reset_wss = false;
124// Show per-process oom_score_adj column
125bool show_oomadj = false;
126// True if the device has swap enabled
127bool has_swap = false;
128// True, if device has zram enabled
129bool has_zram = false;
130// If zram is enabled, the compression ratio is zram used / swap used.
131float zram_compression_ratio = 0.0;
132// Sort process in reverse, default is descending
133bool reverse_sort = false;
134
135// Calculated total memory usage across all processes in the system
136uint64_t total_pss = 0;
137uint64_t total_uss = 0;
138uint64_t total_swap = 0;
139uint64_t total_pswap = 0;
140uint64_t total_uswap = 0;
141uint64_t total_zswap = 0;
142
Sandeep Patil7b20fb62018-12-30 13:28:55 -0800143[[noreturn]] static void usage(int exit_status) {
144 std::cerr << "Usage: " << getprogname() << " [ -W ] [ -v | -r | -p | -u | -s | -h ]"
145 << std::endl
Sandeep Patila14119d2018-11-16 09:18:57 -0800146 << " -v Sort by VSS." << std::endl
147 << " -r Sort by RSS." << std::endl
148 << " -p Sort by PSS." << std::endl
149 << " -u Sort by USS." << std::endl
150 << " -s Sort by swap." << std::endl
151 << " (Default sort order is PSS.)" << std::endl
152 << " -R Reverse sort order (default is descending)." << std::endl
153 << " -c Only show cached (storage backed) pages" << std::endl
154 << " -C Only show non-cached (ram/swap backed) pages" << std::endl
155 << " -k Only show pages collapsed by KSM" << std::endl
156 << " -w Display statistics for working set only." << std::endl
157 << " -W Reset working set of all processes." << std::endl
158 << " -o Show and sort by oom score against lowmemorykiller thresholds."
159 << std::endl
160 << " -h Display this help screen." << std::endl;
Sandeep Patil7b20fb62018-12-30 13:28:55 -0800161 exit(exit_status);
Sandeep Patila14119d2018-11-16 09:18:57 -0800162}
163
164static bool read_all_pids(std::vector<pid_t>* pids, std::function<bool(pid_t pid)> for_each_pid) {
165 pids->clear();
166 std::unique_ptr<DIR, int (*)(DIR*)> procdir(opendir("/proc"), closedir);
167 if (!procdir) return false;
168
169 struct dirent* dir;
170 pid_t pid;
171 while ((dir = readdir(procdir.get()))) {
172 if (!::android::base::ParseInt(dir->d_name, &pid)) continue;
173 if (!for_each_pid(pid)) return false;
Sandeep Patila42207e2019-04-17 11:38:15 -0700174 pids->emplace_back(pid);
Sandeep Patila14119d2018-11-16 09:18:57 -0800175 }
176
177 return true;
178}
179
180static bool count_swap_offsets(const ProcessRecord& proc, uint16_t* swap_offset_array,
181 uint32_t size) {
182 const std::vector<uint16_t>& swp_offs = proc.SwapOffsets();
183 for (auto& off : swp_offs) {
184 if (off >= size) {
185 std::cerr << "swap offset " << off << " is out of bounds for process: " << proc.pid()
186 << std::endl;
187 return false;
188 }
189
190 if (swap_offset_array[off] == USHRT_MAX) {
191 std::cerr << "swap offset " << off << " ref count overflow in process: " << proc.pid()
192 << std::endl;
193 return false;
194 }
195
196 swap_offset_array[off]++;
197 }
198
199 return true;
200}
201
202static void print_header(std::stringstream& ss) {
203 ss.str("");
204 ss << ::android::base::StringPrintf("%5s ", "PID");
205 if (show_oomadj) {
206 ss << ::android::base::StringPrintf("%5s ", "oom");
207 }
208
209 if (show_wss) {
210 ss << ::android::base::StringPrintf("%7s %7s %7s ", "WRss", "WPss", "WUss");
211 // now swap statistics here, working set pages by definition shouldn't end up in swap.
212 } else {
213 ss << ::android::base::StringPrintf("%8s %7s %7s %7s ", "Vss", "Rss", "Pss", "Uss");
214 if (has_swap) {
215 ss << ::android::base::StringPrintf("%7s %7s %7s ", "Swap", "PSwap", "USwap");
216 if (has_zram) {
217 ss << ::android::base::StringPrintf("%7s ", "ZSwap");
218 }
219 }
220 }
221
222 ss << "cmdline";
223}
224
225static void print_process_record(std::stringstream& ss, ProcessRecord& proc) {
226 ss << ::android::base::StringPrintf("%5d ", proc.pid());
227 if (show_oomadj) {
228 ss << ::android::base::StringPrintf("%5d ", proc.oomadj());
229 }
230
231 if (show_wss) {
232 ss << ::android::base::StringPrintf("%6" PRIu64 "K %6" PRIu64 "K %6" PRIu64 "K ",
233 proc.Wss().rss / 1024, proc.Wss().pss / 1024,
234 proc.Wss().uss / 1024);
235 } else {
236 ss << ::android::base::StringPrintf("%7" PRIu64 "K %6" PRIu64 "K %6" PRIu64 "K %6" PRIu64
237 "K ",
238 proc.Usage().vss / 1024, proc.Usage().rss / 1024,
239 proc.Usage().pss / 1024, proc.Usage().uss / 1024);
240 if (has_swap) {
241 ss << ::android::base::StringPrintf("%6" PRIu64 "K ", proc.Usage().swap / 1024);
242 ss << ::android::base::StringPrintf("%6" PRIu64 "K ", proc.proportional_swap() / 1024);
243 ss << ::android::base::StringPrintf("%6" PRIu64 "K ", proc.unique_swap() / 1024);
244 if (has_zram) {
245 ss << ::android::base::StringPrintf("%6" PRIu64 "K ", (proc.zswap() / 1024));
246 }
247 }
248 }
249}
250
251static void print_processes(std::stringstream& ss, std::vector<ProcessRecord>& procs,
252 uint16_t* swap_offset_array) {
253 for (auto& proc : procs) {
254 total_pss += show_wss ? proc.Wss().pss : proc.Usage().pss;
255 total_uss += show_wss ? proc.Wss().uss : proc.Usage().uss;
256 if (!show_wss && has_swap) {
257 proc.CalculateSwap(swap_offset_array, zram_compression_ratio);
258 total_swap += proc.Usage().swap;
259 total_pswap += proc.proportional_swap();
260 total_uswap += proc.unique_swap();
261 if (has_zram) {
262 total_zswap += proc.zswap();
263 }
264 }
265
266 print_process_record(ss, proc);
267 ss << proc.cmdline() << std::endl;
268 }
269}
270
271static void print_separator(std::stringstream& ss) {
272 ss << ::android::base::StringPrintf("%5s ", "");
273 if (show_oomadj) {
274 ss << ::android::base::StringPrintf("%5s ", "");
275 }
276
277 if (show_wss) {
278 ss << ::android::base::StringPrintf("%7s %7s %7s ", "", "------", "------");
279 } else {
280 ss << ::android::base::StringPrintf("%8s %7s %7s %7s ", "", "", "------", "------");
281 if (has_swap) {
282 ss << ::android::base::StringPrintf("%7s %7s %7s ", "------", "------", "------");
283 if (has_zram) {
284 ss << ::android::base::StringPrintf("%7s ", "------");
285 }
286 }
287 }
288
289 ss << ::android::base::StringPrintf("%s", "------");
290}
291
292static void print_totals(std::stringstream& ss) {
293 ss << ::android::base::StringPrintf("%5s ", "");
294 if (show_oomadj) {
295 ss << ::android::base::StringPrintf("%5s ", "");
296 }
297
298 if (show_wss) {
299 ss << ::android::base::StringPrintf("%7s %6" PRIu64 "K %6" PRIu64 "K ", "",
300 total_pss / 1024, total_uss / 1024);
301 } else {
302 ss << ::android::base::StringPrintf("%8s %7s %6" PRIu64 "K %6" PRIu64 "K ", "", "",
303 total_pss / 1024, total_uss / 1024);
304 if (has_swap) {
305 ss << ::android::base::StringPrintf("%6" PRIu64 "K ", total_swap / 1024);
306 ss << ::android::base::StringPrintf("%6" PRIu64 "K ", total_pswap / 1024);
307 ss << ::android::base::StringPrintf("%6" PRIu64 "K ", total_uswap / 1024);
308 if (has_zram) {
309 ss << ::android::base::StringPrintf("%6" PRIu64 "K ", total_zswap / 1024);
310 }
311 }
312 }
313 ss << "TOTAL";
314}
315
316static void print_sysmeminfo(std::stringstream& ss, ::android::meminfo::SysMemInfo& smi) {
317 if (has_swap) {
318 ss << ::android::base::StringPrintf("ZRAM: %" PRIu64 "K physical used for %" PRIu64
319 "K in swap "
320 "(%" PRIu64 "K total swap)",
321 smi.mem_zram_kb(),
322 (smi.mem_swap_kb() - smi.mem_swap_free_kb()),
323 smi.mem_swap_kb())
324 << std::endl;
325 }
326
327 ss << ::android::base::StringPrintf(" RAM: %" PRIu64 "K total, %" PRIu64 "K free, %" PRIu64
328 "K buffers, "
329 "%" PRIu64 "K cached, %" PRIu64 "K shmem, %" PRIu64
330 "K slab",
331 smi.mem_total_kb(), smi.mem_free_kb(), smi.mem_buffers_kb(),
332 smi.mem_cached_kb(), smi.mem_shmem_kb(), smi.mem_slab_kb());
333}
334
335int main(int argc, char* argv[]) {
336 auto pss_sort = [](ProcessRecord& a, ProcessRecord& b) {
337 MemUsage stats_a = show_wss ? a.Wss() : a.Usage();
338 MemUsage stats_b = show_wss ? b.Wss() : b.Usage();
339 return reverse_sort ? stats_a.pss < stats_b.pss : stats_a.pss > stats_b.pss;
340 };
341
342 auto uss_sort = [](ProcessRecord& a, ProcessRecord& b) {
343 MemUsage stats_a = show_wss ? a.Wss() : a.Usage();
344 MemUsage stats_b = show_wss ? b.Wss() : b.Usage();
345 return reverse_sort ? stats_a.uss < stats_b.uss : stats_a.uss > stats_b.uss;
346 };
347
348 auto rss_sort = [](ProcessRecord& a, ProcessRecord& b) {
349 MemUsage stats_a = show_wss ? a.Wss() : a.Usage();
350 MemUsage stats_b = show_wss ? b.Wss() : b.Usage();
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700351 return reverse_sort ? stats_a.rss < stats_b.rss : stats_a.rss > stats_b.rss;
Sandeep Patila14119d2018-11-16 09:18:57 -0800352 };
353
354 auto vss_sort = [](ProcessRecord& a, ProcessRecord& b) {
355 MemUsage stats_a = show_wss ? a.Wss() : a.Usage();
356 MemUsage stats_b = show_wss ? b.Wss() : b.Usage();
357 return reverse_sort ? stats_a.vss < stats_b.vss : stats_a.vss > stats_b.vss;
358 };
359
360 auto swap_sort = [](ProcessRecord& a, ProcessRecord& b) {
361 MemUsage stats_a = show_wss ? a.Wss() : a.Usage();
362 MemUsage stats_b = show_wss ? b.Wss() : b.Usage();
363 return reverse_sort ? stats_a.swap < stats_b.swap : stats_a.swap > stats_b.swap;
364 };
365
366 auto oomadj_sort = [](ProcessRecord& a, ProcessRecord& b) {
367 return reverse_sort ? a.oomadj() < b.oomadj() : a.oomadj() > b.oomadj();
368 };
369
370 // default PSS sort
371 std::function<bool(ProcessRecord & a, ProcessRecord & b)> proc_sort = pss_sort;
372
373 // count all pages by default
374 uint64_t pgflags = 0;
375 uint64_t pgflags_mask = 0;
376
377 int opt;
378 while ((opt = getopt(argc, argv, "cChkoprRsuvwW")) != -1) {
379 switch (opt) {
380 case 'c':
381 pgflags = 0;
382 pgflags_mask = (1 << KPF_SWAPBACKED);
383 break;
384 case 'C':
385 pgflags = (1 << KPF_SWAPBACKED);
386 pgflags_mask = (1 << KPF_SWAPBACKED);
387 break;
388 case 'h':
Sandeep Patil7b20fb62018-12-30 13:28:55 -0800389 usage(EXIT_SUCCESS);
Sandeep Patila14119d2018-11-16 09:18:57 -0800390 case 'k':
391 pgflags = (1 << KPF_KSM);
392 pgflags_mask = (1 << KPF_KSM);
393 break;
394 case 'o':
395 proc_sort = oomadj_sort;
396 show_oomadj = true;
397 break;
398 case 'p':
399 proc_sort = pss_sort;
400 break;
401 case 'r':
402 proc_sort = rss_sort;
403 break;
404 case 'R':
405 reverse_sort = true;
406 break;
407 case 's':
408 proc_sort = swap_sort;
409 break;
410 case 'u':
411 proc_sort = uss_sort;
412 break;
413 case 'v':
414 proc_sort = vss_sort;
415 break;
416 case 'w':
417 show_wss = true;
418 break;
419 case 'W':
420 reset_wss = true;
421 break;
422 default:
Sandeep Patil7b20fb62018-12-30 13:28:55 -0800423 usage(EXIT_FAILURE);
Sandeep Patila14119d2018-11-16 09:18:57 -0800424 }
425 }
426
427 std::vector<pid_t> pids;
428 std::vector<ProcessRecord> procs;
429 if (reset_wss) {
430 if (!read_all_pids(&pids,
431 [&](pid_t pid) -> bool { return ProcMemInfo::ResetWorkingSet(pid); })) {
432 std::cerr << "Failed to reset working set of all processes" << std::endl;
433 exit(EXIT_FAILURE);
434 }
435 // we are done, all other options passed to procrank are ignored in the presence of '-W'
436 return 0;
437 }
438
439 ::android::meminfo::SysMemInfo smi;
440 if (!smi.ReadMemInfo()) {
441 std::cerr << "Failed to get system memory info" << std::endl;
442 exit(EXIT_FAILURE);
443 }
444
445 // Figure out swap and zram
446 uint64_t swap_total = smi.mem_swap_kb() * 1024;
447 has_swap = swap_total > 0;
448 // Allocate the swap array
449 auto swap_offset_array = std::make_unique<uint16_t[]>(swap_total / getpagesize());
450 if (has_swap) {
451 has_zram = smi.mem_zram_kb() > 0;
452 if (has_zram) {
453 zram_compression_ratio = static_cast<float>(smi.mem_zram_kb()) /
454 (smi.mem_swap_kb() - smi.mem_swap_free_kb());
455 }
456 }
457
458 auto mark_swap_usage = [&](pid_t pid) -> bool {
459 ProcessRecord proc(pid, show_wss, pgflags, pgflags_mask);
460 if (!proc.valid()) {
Sandeep Patilba98e0e2019-04-09 12:31:36 -0700461 // Check to see if the process is still around, skip the process if the proc
462 // directory is inaccessible. It was most likely killed while creating the process
463 // record
464 std::string procdir = ::android::base::StringPrintf("/proc/%d", pid);
465 if (access(procdir.c_str(), F_OK | R_OK)) return true;
466
467 // Warn if we failed to gather process stats even while it is still alive.
468 // Return success here, so we continue to print stats for other processes.
469 std::cerr << "warning: failed to create process record for: " << pid << std::endl;
470 return true;
Sandeep Patila14119d2018-11-16 09:18:57 -0800471 }
472
473 // Skip processes with no memory mappings
Sandeep Patila42207e2019-04-17 11:38:15 -0700474 uint64_t vss = show_wss ? proc.Wss().vss : proc.Usage().vss;
Sandeep Patila14119d2018-11-16 09:18:57 -0800475 if (vss == 0) return true;
476
477 // collect swap_offset counts from all processes in 1st pass
478 if (!show_wss && has_swap &&
479 !count_swap_offsets(proc, swap_offset_array.get(), swap_total / getpagesize())) {
480 std::cerr << "Failed to count swap offsets for process: " << pid << std::endl;
481 return false;
482 }
483
Sandeep Patila42207e2019-04-17 11:38:15 -0700484 procs.emplace_back(std::move(proc));
Sandeep Patila14119d2018-11-16 09:18:57 -0800485 return true;
486 };
487
Sandeep Patilba98e0e2019-04-09 12:31:36 -0700488 // Get a list of all pids currently running in the system in 1st pass through all processes.
489 // Mark each swap offset used by the process as we find them for calculating proportional
490 // swap usage later.
Sandeep Patila14119d2018-11-16 09:18:57 -0800491 if (!read_all_pids(&pids, mark_swap_usage)) {
492 std::cerr << "Failed to read all pids from the system" << std::endl;
493 exit(EXIT_FAILURE);
494 }
495
496 std::stringstream ss;
497 if (procs.empty()) {
498 // This would happen in corner cases where procrank is being run to find KSM usage on a
499 // system with no KSM and combined with working set determination as follows
500 // procrank -w -u -k
501 // procrank -w -s -k
502 // procrank -w -o -k
503 ss << "<empty>" << std::endl << std::endl;
504 print_sysmeminfo(ss, smi);
505 ss << std::endl;
506 std::cout << ss.str();
507 return 0;
508 }
509
510 // Sort all process records, default is PSS descending
511 std::sort(procs.begin(), procs.end(), proc_sort);
512
513 // start dumping output in string stream
514 print_header(ss);
515 ss << std::endl;
516
517 // 2nd pass to calculate and get per process stats to add them up
518 print_processes(ss, procs, swap_offset_array.get());
519
520 // Add separator to output
521 print_separator(ss);
522 ss << std::endl;
523
524 // Add totals to output
525 print_totals(ss);
526 ss << std::endl << std::endl;
527
528 // Add system information at the end
529 print_sysmeminfo(ss, smi);
530 ss << std::endl;
531
532 // dump on the screen
533 std::cout << ss.str();
534
535 return 0;
536}