blob: 19fb4891259824ea254251c7c42004973f89d6eb [file] [log] [blame]
Yabin Cui323e9452015-04-20 18:07:17 -07001/*
2 * Copyright (C) 2015 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 <inttypes.h>
Yabin Cui621a5332015-06-15 16:17:20 -070018#include <signal.h>
Yabin Cui323e9452015-04-20 18:07:17 -070019#include <stdio.h>
Yabin Cui04d08a32015-08-19 15:01:12 -070020#include <string.h>
Yabin Cui987d9ab2016-07-15 14:08:48 -070021#include <sys/prctl.h>
Yabin Cui04d08a32015-08-19 15:01:12 -070022
23#include <algorithm>
Yabin Cui323e9452015-04-20 18:07:17 -070024#include <chrono>
Yabin Cuif53f7162020-06-19 15:16:31 -070025#include <optional>
Yabin Cuib032de72015-06-17 21:15:09 -070026#include <set>
Yabin Cui323e9452015-04-20 18:07:17 -070027#include <string>
Yabin Cui117caa42019-07-15 10:39:15 -070028#include <string_view>
Yabin Cui323e9452015-04-20 18:07:17 -070029#include <vector>
30
Yabin Cuia80f8f72017-07-12 15:50:20 -070031#include <android-base/file.h>
Elliott Hughes66dd09e2015-12-04 14:00:57 -080032#include <android-base/logging.h>
33#include <android-base/strings.h>
Yabin Cui1a30a582019-01-10 15:35:39 -080034#include <android-base/unique_fd.h>
Yabin Cui323e9452015-04-20 18:07:17 -070035
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +020036#include "IOEventLoop.h"
Yabin Cui61b4dac2023-11-03 15:19:14 -070037#include "ProbeEvents.h"
Yabin Cuib3ed39b2020-03-26 14:00:49 -070038#include "cmd_stat_impl.h"
Yabin Cui323e9452015-04-20 18:07:17 -070039#include "command.h"
40#include "environment.h"
Yabin Cui9fd3cc12015-06-25 17:42:23 -070041#include "event_attr.h"
42#include "event_fd.h"
Yabin Cui9759e1b2015-04-28 15:54:13 -070043#include "event_selection_set.h"
Yabin Cui323e9452015-04-20 18:07:17 -070044#include "event_type.h"
Yabin Cui621a5332015-06-15 16:17:20 -070045#include "utils.h"
Yabin Cui323e9452015-04-20 18:07:17 -070046#include "workload.h"
47
Yabin Cui5271aa72020-03-31 16:59:33 -070048namespace simpleperf {
Yabin Cui877751b2016-06-13 18:03:47 -070049
Yabin Cuifaa7b922021-01-11 17:35:57 -080050using android::base::Split;
51
Yabin Cui323e9452015-04-20 18:07:17 -070052static std::vector<std::string> default_measured_event_types{
Yabin Cuif569b472015-04-30 09:43:26 -070053 "cpu-cycles", "stalled-cycles-frontend", "stalled-cycles-backend",
54 "instructions", "branch-instructions", "branch-misses",
55 "task-clock", "context-switches", "page-faults",
Yabin Cui323e9452015-04-20 18:07:17 -070056};
57
Yabin Cui117caa42019-07-15 10:39:15 -070058static const std::unordered_map<std::string_view, std::pair<std::string_view, std::string_view>>
59 COMMON_EVENT_RATE_MAP = {
60 {"cache-misses", {"cache-references", "miss rate"}},
61 {"branch-misses", {"branch-instructions", "miss rate"}},
62};
63
64static const std::unordered_map<std::string_view, std::pair<std::string_view, std::string_view>>
65 ARM_EVENT_RATE_MAP = {
66 // Refer to "D6.10.5 Meaningful ratios between common microarchitectural events" in ARMv8
67 // specification.
68 {"raw-l1i-cache-refill", {"raw-l1i-cache", "level 1 instruction cache refill rate"}},
69 {"raw-l1i-tlb-refill", {"raw-l1i-tlb", "level 1 instruction TLB refill rate"}},
70 {"raw-l1d-cache-refill", {"raw-l1d-cache", "level 1 data or unified cache refill rate"}},
71 {"raw-l1d-tlb-refill", {"raw-l1d-tlb", "level 1 data or unified TLB refill rate"}},
72 {"raw-l2d-cache-refill", {"raw-l2d-cache", "level 2 data or unified cache refill rate"}},
73 {"raw-l2i-cache-refill", {"raw-l2i-cache", "level 2 instruction cache refill rate"}},
74 {"raw-l3d-cache-refill", {"raw-l3d-cache", "level 3 data or unified cache refill rate"}},
75 {"raw-l2d-tlb-refill", {"raw-l2d-tlb", "level 2 data or unified TLB refill rate"}},
76 {"raw-l2i-tlb-refill", {"raw-l2i-tlb", "level 2 instruction TLB refill rate"}},
77 {"raw-bus-access", {"raw-bus-cycles", "bus accesses per cycle"}},
78 {"raw-ll-cache-miss", {"raw-ll-cache", "last level data or unified cache refill rate"}},
79 {"raw-dtlb-walk", {"raw-l1d-tlb", "data TLB miss rate"}},
80 {"raw-itlb-walk", {"raw-l1i-tlb", "instruction TLB miss rate"}},
81 {"raw-ll-cache-miss-rd", {"raw-ll-cache-rd", "memory read operation miss rate"}},
82 {"raw-remote-access-rd",
83 {"raw-remote-access", "read accesses to another socket in a multi-socket system"}},
84 // Refer to "Table K3-2 Relationship between REFILL events and associated access events" in
85 // ARMv8 specification.
86 {"raw-l1d-cache-refill-rd", {"raw-l1d-cache-rd", "level 1 cache refill rate, read"}},
87 {"raw-l1d-cache-refill-wr", {"raw-l1d-cache-wr", "level 1 cache refill rate, write"}},
88 {"raw-l1d-tlb-refill-rd", {"raw-l1d-tlb-rd", "level 1 TLB refill rate, read"}},
89 {"raw-l1d-tlb-refill-wr", {"raw-l1d-tlb-wr", "level 1 TLB refill rate, write"}},
90 {"raw-l2d-cache-refill-rd", {"raw-l2d-cache-rd", "level 2 data cache refill rate, read"}},
91 {"raw-l2d-cache-refill-wr", {"raw-l2d-cache-wr", "level 2 data cache refill rate, write"}},
92 {"raw-l2d-tlb-refill-rd", {"raw-l2d-tlb-rd", "level 2 data TLB refill rate, read"}},
93};
94
Yabin Cuibb9a0d12023-08-31 15:53:31 -070095std::string CounterSummary::ReadableCountValue(bool csv) {
96 if (type_name == "cpu-clock" || type_name == "task-clock") {
97 // Convert nanoseconds to milliseconds.
98 double value = count / 1e6;
99 return android::base::StringPrintf("%lf(ms)", value);
100 }
101 if (csv) {
102 return android::base::StringPrintf("%" PRIu64, count);
103 }
104 return ReadableCount(count);
105}
106
Yabin Cui5271aa72020-03-31 16:59:33 -0700107const CounterSummary* CounterSummaries::FindSummary(const std::string& type_name,
108 const std::string& modifier,
109 const ThreadInfo* thread, int cpu) {
110 for (const auto& s : summaries_) {
111 if (s.type_name == type_name && s.modifier == modifier && s.thread == thread && s.cpu == cpu) {
112 return &s;
Yabin Cui0a45adf2016-06-22 20:58:52 -0700113 }
Yabin Cui0a45adf2016-06-22 20:58:52 -0700114 }
Yabin Cui5271aa72020-03-31 16:59:33 -0700115 return nullptr;
116}
Yabin Cui0a45adf2016-06-22 20:58:52 -0700117
Yabin Cui5271aa72020-03-31 16:59:33 -0700118void CounterSummaries::AutoGenerateSummaries() {
119 for (size_t i = 0; i < summaries_.size(); ++i) {
120 const CounterSummary& s = summaries_[i];
121 if (s.modifier == "u") {
122 const CounterSummary* other = FindSummary(s.type_name, "k", s.thread, s.cpu);
123 if (other != nullptr && other->IsMonitoredAtTheSameTime(s)) {
124 if (FindSummary(s.type_name, "", s.thread, s.cpu) == nullptr) {
125 summaries_.emplace_back(s.type_name, "", s.group_id, s.thread, s.cpu,
Yabin Cui6922c072020-03-31 18:04:59 -0700126 s.count + other->count, s.runtime_in_ns, s.scale, true, csv_);
Yabin Cui0a45adf2016-06-22 20:58:52 -0700127 }
128 }
129 }
130 }
Yabin Cui5271aa72020-03-31 16:59:33 -0700131}
Yabin Cui0a45adf2016-06-22 20:58:52 -0700132
Yabin Cui5271aa72020-03-31 16:59:33 -0700133void CounterSummaries::GenerateComments(double duration_in_sec) {
134 for (auto& s : summaries_) {
135 s.comment = GetCommentForSummary(s, duration_in_sec);
136 }
137}
138
139void CounterSummaries::Show(FILE* fp) {
Yabin Cuif53f7162020-06-19 15:16:31 -0700140 bool show_thread = !summaries_.empty() && summaries_[0].thread != nullptr;
141 bool show_cpu = !summaries_.empty() && summaries_[0].cpu != -1;
Yabin Cui5271aa72020-03-31 16:59:33 -0700142 if (csv_) {
Yabin Cuif53f7162020-06-19 15:16:31 -0700143 ShowCSV(fp, show_thread, show_cpu);
Yabin Cui5271aa72020-03-31 16:59:33 -0700144 } else {
Yabin Cuif53f7162020-06-19 15:16:31 -0700145 ShowText(fp, show_thread, show_cpu);
Yabin Cui5271aa72020-03-31 16:59:33 -0700146 }
147}
148
Yabin Cuif53f7162020-06-19 15:16:31 -0700149void CounterSummaries::ShowCSV(FILE* fp, bool show_thread, bool show_cpu) {
Yabin Cui5271aa72020-03-31 16:59:33 -0700150 for (auto& s : summaries_) {
Yabin Cuif53f7162020-06-19 15:16:31 -0700151 if (show_thread) {
Yabin Cui5271aa72020-03-31 16:59:33 -0700152 fprintf(fp, "%s,%d,%d,", s.thread->name.c_str(), s.thread->pid, s.thread->tid);
Yabin Cui0a45adf2016-06-22 20:58:52 -0700153 }
Yabin Cuif53f7162020-06-19 15:16:31 -0700154 if (show_cpu) {
155 fprintf(fp, "%d,", s.cpu);
156 }
Yabin Cuiabc8ee22022-08-25 11:06:39 -0700157 fprintf(fp, "%s,%s,%s,%s\n", s.readable_count.c_str(), s.Name().c_str(), s.comment.c_str(),
158 (s.auto_generated ? "(generated)," : ""));
Yabin Cui5271aa72020-03-31 16:59:33 -0700159 }
160}
161
Yabin Cuif53f7162020-06-19 15:16:31 -0700162void CounterSummaries::ShowText(FILE* fp, bool show_thread, bool show_cpu) {
Yabin Cui5271aa72020-03-31 16:59:33 -0700163 std::vector<std::string> titles;
164
165 if (show_thread) {
166 titles = {"thread_name", "pid", "tid"};
167 }
168 if (show_cpu) {
169 titles.emplace_back("cpu");
170 }
171 titles.emplace_back("count");
172 titles.emplace_back("event_name");
Yabin4ed8e112022-08-23 11:43:01 -0700173 titles.emplace_back(" # count / runtime");
Yabin Cui5271aa72020-03-31 16:59:33 -0700174
175 std::vector<size_t> width(titles.size(), 0);
176
177 auto adjust_width = [](size_t& w, size_t size) { w = std::max(w, size); };
178
179 // The last title is too long. Don't include it for width adjustment.
180 for (size_t i = 0; i + 1 < titles.size(); i++) {
181 adjust_width(width[i], titles[i].size());
Yabin Cui0a45adf2016-06-22 20:58:52 -0700182 }
183
Yabin Cui5271aa72020-03-31 16:59:33 -0700184 for (auto& s : summaries_) {
185 size_t i = 0;
Yabin Cuidc2708c2020-01-10 15:33:11 -0800186 if (show_thread) {
Yabin Cui5271aa72020-03-31 16:59:33 -0700187 adjust_width(width[i++], s.thread->name.size());
188 adjust_width(width[i++], std::to_string(s.thread->pid).size());
189 adjust_width(width[i++], std::to_string(s.thread->tid).size());
Yabin Cui8ab56212020-01-27 15:23:46 -0800190 }
191 if (show_cpu) {
Yabin Cui5271aa72020-03-31 16:59:33 -0700192 adjust_width(width[i++], std::to_string(s.cpu).size());
Yabin Cui8ab56212020-01-27 15:23:46 -0800193 }
Yabin Cui5271aa72020-03-31 16:59:33 -0700194 adjust_width(width[i++], s.readable_count.size());
195 adjust_width(width[i++], s.Name().size());
196 adjust_width(width[i++], s.comment.size());
Yabin Cui0a45adf2016-06-22 20:58:52 -0700197 }
198
Yabin Cui5271aa72020-03-31 16:59:33 -0700199 fprintf(fp, "# ");
200 for (size_t i = 0; i < titles.size(); i++) {
201 if (titles[i] == "count") {
202 fprintf(fp, "%*s", static_cast<int>(width[i]), titles[i].c_str());
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700203 } else {
Yabin Cui5271aa72020-03-31 16:59:33 -0700204 fprintf(fp, "%-*s", static_cast<int>(width[i]), titles[i].c_str());
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700205 }
Yabin Cui5271aa72020-03-31 16:59:33 -0700206 if (i + 1 < titles.size()) {
207 fprintf(fp, " ");
Yabin Cui0a45adf2016-06-22 20:58:52 -0700208 }
Yabin Cui5271aa72020-03-31 16:59:33 -0700209 }
210 fprintf(fp, "\n");
211
212 for (auto& s : summaries_) {
213 size_t i = 0;
214 if (show_thread) {
215 fprintf(fp, " %-*s", static_cast<int>(width[i++]), s.thread->name.c_str());
216 fprintf(fp, " %-*d", static_cast<int>(width[i++]), s.thread->pid);
217 fprintf(fp, " %-*d", static_cast<int>(width[i++]), s.thread->tid);
Yabin Cui0a45adf2016-06-22 20:58:52 -0700218 }
Yabin Cui5271aa72020-03-31 16:59:33 -0700219 if (show_cpu) {
220 fprintf(fp, " %-*d", static_cast<int>(width[i++]), s.cpu);
Yabin Cui0a45adf2016-06-22 20:58:52 -0700221 }
Yabin4ed8e112022-08-23 11:43:01 -0700222 fprintf(fp, " %*s %-*s # %-*s%s\n", static_cast<int>(width[i]), s.readable_count.c_str(),
223 static_cast<int>(width[i + 1]), s.Name().c_str(), static_cast<int>(width[i + 2]),
224 s.comment.c_str(), (s.auto_generated ? " (generated)" : ""));
Yabin Cui5271aa72020-03-31 16:59:33 -0700225 }
226}
227
228std::string CounterSummaries::GetCommentForSummary(const CounterSummary& s,
229 double duration_in_sec) {
230 char sap_mid;
231 if (csv_) {
232 sap_mid = ',';
233 } else {
234 sap_mid = ' ';
235 }
236 if (s.type_name == "task-clock") {
237 double run_sec = s.count / 1e9;
Yabin Cui6922c072020-03-31 18:04:59 -0700238 double used_cpus = run_sec / duration_in_sec;
239 return android::base::StringPrintf("%f%ccpus used", used_cpus, sap_mid);
Yabin Cui5271aa72020-03-31 16:59:33 -0700240 }
241 if (s.type_name == "cpu-clock") {
242 return "";
243 }
244 if (s.type_name == "cpu-cycles") {
Yabin Cui6922c072020-03-31 18:04:59 -0700245 if (s.runtime_in_ns == 0) {
Yabin Cui900ea072018-03-06 11:35:22 -0800246 return "";
247 }
Yabin Cui6922c072020-03-31 18:04:59 -0700248 double ghz = static_cast<double>(s.count) / s.runtime_in_ns;
249 return android::base::StringPrintf("%f%cGHz", ghz, sap_mid);
Yabin Cui0a45adf2016-06-22 20:58:52 -0700250 }
Yabin Cui5271aa72020-03-31 16:59:33 -0700251 if (s.type_name == "instructions" && s.count != 0) {
252 const CounterSummary* other = FindSummary("cpu-cycles", s.modifier, s.thread, s.cpu);
253 if (other != nullptr && other->IsMonitoredAtTheSameTime(s)) {
254 double cpi = static_cast<double>(other->count) / s.count;
Yabin Cui6922c072020-03-31 18:04:59 -0700255 return android::base::StringPrintf("%f%ccycles per instruction", cpi, sap_mid);
Yabin Cui5271aa72020-03-31 16:59:33 -0700256 }
257 }
258 std::string rate_comment = GetRateComment(s, sap_mid);
259 if (!rate_comment.empty()) {
260 return rate_comment;
261 }
Yabin Cui6922c072020-03-31 18:04:59 -0700262 if (s.runtime_in_ns == 0) {
Yabin Cui5271aa72020-03-31 16:59:33 -0700263 return "";
264 }
Yabin Cui6922c072020-03-31 18:04:59 -0700265 double runtime_in_sec = static_cast<double>(s.runtime_in_ns) / 1e9;
266 double rate = s.count / runtime_in_sec;
267 if (rate >= 1e9 - 1e5) {
268 return android::base::StringPrintf("%.3f%cG/sec", rate / 1e9, sap_mid);
Yabin Cui5271aa72020-03-31 16:59:33 -0700269 }
Yabin Cui6922c072020-03-31 18:04:59 -0700270 if (rate >= 1e6 - 1e2) {
271 return android::base::StringPrintf("%.3f%cM/sec", rate / 1e6, sap_mid);
Yabin Cui5271aa72020-03-31 16:59:33 -0700272 }
Yabin Cui6922c072020-03-31 18:04:59 -0700273 if (rate >= 1e3) {
274 return android::base::StringPrintf("%.3f%cK/sec", rate / 1e3, sap_mid);
Yabin Cui5271aa72020-03-31 16:59:33 -0700275 }
Yabin Cui6922c072020-03-31 18:04:59 -0700276 return android::base::StringPrintf("%.3f%c/sec", rate, sap_mid);
Yabin Cui5271aa72020-03-31 16:59:33 -0700277}
Yabin Cui0a45adf2016-06-22 20:58:52 -0700278
Yabin Cui5271aa72020-03-31 16:59:33 -0700279std::string CounterSummaries::GetRateComment(const CounterSummary& s, char sep) {
280 std::string_view miss_event_name = s.type_name;
281 std::string event_name;
282 std::string rate_desc;
283 if (auto it = COMMON_EVENT_RATE_MAP.find(miss_event_name); it != COMMON_EVENT_RATE_MAP.end()) {
284 event_name = it->second.first;
285 rate_desc = it->second.second;
286 }
Yabin Cui38076912021-08-16 16:59:09 -0700287 if (event_name.empty() && (GetTargetArch() == ARCH_ARM || GetTargetArch() == ARCH_ARM64)) {
Yabin Cui5271aa72020-03-31 16:59:33 -0700288 if (auto it = ARM_EVENT_RATE_MAP.find(miss_event_name); it != ARM_EVENT_RATE_MAP.end()) {
Yabin Cui117caa42019-07-15 10:39:15 -0700289 event_name = it->second.first;
290 rate_desc = it->second.second;
291 }
Yabin Cui117caa42019-07-15 10:39:15 -0700292 }
Yabin Cui5271aa72020-03-31 16:59:33 -0700293 if (event_name.empty() && android::base::ConsumeSuffix(&miss_event_name, "-misses")) {
294 event_name = std::string(miss_event_name) + "s";
295 rate_desc = "miss rate";
Yabin Cui900ea072018-03-06 11:35:22 -0800296 }
Yabin Cui5271aa72020-03-31 16:59:33 -0700297 if (!event_name.empty()) {
298 const CounterSummary* other = FindSummary(event_name, s.modifier, s.thread, s.cpu);
299 if (other != nullptr && other->IsMonitoredAtTheSameTime(s) && other->count != 0) {
300 double miss_rate = static_cast<double>(s.count) / other->count;
301 return android::base::StringPrintf("%f%%%c%s", miss_rate * 100, sep, rate_desc.c_str());
302 }
303 }
304 return "";
305}
Yabin Cui900ea072018-03-06 11:35:22 -0800306
Yabin Cui5271aa72020-03-31 16:59:33 -0700307namespace {
Yabin Cui0a45adf2016-06-22 20:58:52 -0700308
Yabin Cui52f32a42019-08-12 16:53:46 -0700309// devfreq may use performance counters to calculate memory latency (as in
310// drivers/devfreq/arm-memlat-mon.c). Hopefully we can get more available counters by asking devfreq
311// to not use the memory latency governor temporarily.
312class DevfreqCounters {
313 public:
314 bool Use() {
315 if (!IsRoot()) {
316 LOG(ERROR) << "--use-devfreq-counters needs root permission to set devfreq governors";
317 return false;
318 }
319 std::string devfreq_dir = "/sys/class/devfreq/";
320 for (auto& name : GetSubDirs(devfreq_dir)) {
321 std::string governor_path = devfreq_dir + name + "/governor";
322 if (IsRegularFile(governor_path)) {
323 std::string governor;
324 if (!android::base::ReadFileToString(governor_path, &governor)) {
325 LOG(ERROR) << "failed to read " << governor_path;
326 return false;
327 }
328 governor = android::base::Trim(governor);
329 if (governor == "mem_latency") {
330 if (!android::base::WriteStringToFile("performance", governor_path)) {
331 PLOG(ERROR) << "failed to write " << governor_path;
332 return false;
333 }
334 mem_latency_governor_paths_.emplace_back(std::move(governor_path));
335 }
336 }
337 }
338 return true;
339 }
340
341 ~DevfreqCounters() {
342 for (auto& path : mem_latency_governor_paths_) {
343 android::base::WriteStringToFile("mem_latency", path);
344 }
345 }
346
347 private:
348 std::vector<std::string> mem_latency_governor_paths_;
349};
350
Yabin Cuif79f07e2015-06-01 11:21:37 -0700351class StatCommand : public Command {
Yabin Cui323e9452015-04-20 18:07:17 -0700352 public:
Yabin Cuif79f07e2015-06-01 11:21:37 -0700353 StatCommand()
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200354 : Command(
355 "stat", "gather performance counter information",
356 // clang-format off
Yabin Cui877751b2016-06-13 18:03:47 -0700357"Usage: simpleperf stat [options] [command [command-args]]\n"
Yabin Cui8a599d72016-07-21 18:32:53 -0700358" Gather performance counter information of running [command].\n"
359" And -a/-p/-t option can be used to change target of counter information.\n"
Yabin Cui877751b2016-06-13 18:03:47 -0700360"-a Collect system-wide information.\n"
Yabin Cuia80f8f72017-07-12 15:50:20 -0700361#if defined(__ANDROID__)
362"--app package_name Profile the process of an Android application.\n"
363" On non-rooted devices, the app must be debuggable,\n"
364" because we use run-as to switch to the app's context.\n"
365#endif
Yabin Cuidbf82802023-10-19 13:28:42 -0700366"--cpu cpu_item1,cpu_item2,... Monitor events on selected cpus. cpu_item can be a number like\n"
367" 1, or a range like 0-3. A --cpu option affects all event types\n"
368" following it until meeting another --cpu option.\n"
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700369"--csv Write report in comma separate form.\n"
Yabin Cui8a599d72016-07-21 18:32:53 -0700370"--duration time_in_sec Monitor for time_in_sec seconds instead of running\n"
371" [command]. Here time_in_sec may be any positive\n"
372" floating point number.\n"
Wei Wang539fb882016-09-28 14:42:02 -0700373"--interval time_in_ms Print stat for every time_in_ms milliseconds.\n"
374" Here time_in_ms may be any positive floating point\n"
Yabin Cui9267db22018-04-18 11:17:19 -0700375" number. Simpleperf prints total values from the\n"
376" starting point. But this can be changed by\n"
377" --interval-only-values.\n"
378"--interval-only-values Print numbers of events happened in each interval.\n"
Yabin Cui877751b2016-06-13 18:03:47 -0700379"-e event1[:modifier1],event2[:modifier2],...\n"
Yabin Cui5e8ee332018-05-10 15:38:00 -0700380" Select a list of events to count. An event can be:\n"
381" 1) an event name listed in `simpleperf list`;\n"
382" 2) a raw PMU event in rN format. N is a hex number.\n"
383" For example, r1b selects event number 0x1b.\n"
384" Modifiers can be added to define how the event should be\n"
385" monitored. Possible modifiers are:\n"
Yabin Cui877751b2016-06-13 18:03:47 -0700386" u - monitor user space events only\n"
387" k - monitor kernel space events only\n"
388"--group event1[:modifier],event2[:modifier2],...\n"
389" Similar to -e option. But events specified in the same --group\n"
390" option are monitored as a group, and scheduled in and out at the\n"
391" same time.\n"
Yabin Cui61b4dac2023-11-03 15:19:14 -0700392"--kprobe kprobe_event1,kprobe_event2,...\n"
393" Add kprobe events during stating. The kprobe_event format is in\n"
394" Documentation/trace/kprobetrace.rst in the kernel. Examples:\n"
395" 'p:myprobe do_sys_openat2 $arg2:string' - add event kprobes:myprobe\n"
396" 'r:myretprobe do_sys_openat2 $retval:s64' - add event kprobes:myretprobe\n"
Yabin Cui877751b2016-06-13 18:03:47 -0700397"--no-inherit Don't stat created child threads/processes.\n"
Yabin Cui0a45adf2016-06-22 20:58:52 -0700398"-o output_filename Write report to output_filename instead of standard output.\n"
Yabin Cui8ab56212020-01-27 15:23:46 -0800399"--per-core Print counters for each cpu core.\n"
Yabin Cuidc2708c2020-01-10 15:33:11 -0800400"--per-thread Print counters for each thread.\n"
Yabin Cui1c6be752023-02-28 11:46:37 -0800401"-p pid_or_process_name_regex1,pid_or_process_name_regex2,...\n"
402" Stat events on existing processes. Processes are searched either by pid\n"
403" or process name regex. Mutually exclusive with -a.\n"
404"-t tid1,tid2,... Stat events on existing threads. Mutually exclusive with -a.\n"
Yabin Cui6de79a02023-11-03 16:36:56 -0700405"--tp-filter filter_string Set filter_string for the previous tracepoint event.\n"
406" Format is in Documentation/trace/events.rst in the kernel.\n"
407" An example: 'prev_comm != \"simpleperf\" && (prev_pid > 1)'.\n"
Yabin Cuif1a1e482021-12-22 14:54:20 -0800408"--print-hw-counter Test and print CPU PMU hardware counters available on the device.\n"
Yabin Cuif53f7162020-06-19 15:16:31 -0700409"--sort key1,key2,... Select keys used to sort the report, used when --per-thread\n"
410" or --per-core appears. The appearance order of keys decides\n"
411" the order of keys used to sort the report.\n"
412" Possible keys include:\n"
413" count -- event count for each entry\n"
414" count_per_thread -- event count for a thread on all cpus\n"
415" cpu -- cpu id\n"
416" pid -- process id\n"
417" tid -- thread id\n"
418" comm -- thread name\n"
419" The default sort keys are:\n"
420" count_per_thread,tid,cpu,count\n"
Yabin Cui52f32a42019-08-12 16:53:46 -0700421#if defined(__ANDROID__)
422"--use-devfreq-counters On devices with Qualcomm SOCs, some hardware counters may be used\n"
423" to monitor memory latency (in drivers/devfreq/arm-memlat-mon.c),\n"
424" making fewer counters available to users. This option asks devfreq\n"
425" to temporarily release counters by replacing memory-latency governor\n"
426" with performance governor. It affects memory latency during profiling,\n"
427" and may cause wedged power if simpleperf is killed in between.\n"
428#endif
Yabin Cui877751b2016-06-13 18:03:47 -0700429"--verbose Show result in verbose mode.\n"
Yabin Cuia80f8f72017-07-12 15:50:20 -0700430#if 0
431// Below options are only used internally and shouldn't be visible to the public.
432"--in-app We are already running in the app's context.\n"
Yabin Cuif8974522017-07-17 14:36:37 -0700433"--tracepoint-events file_name Read tracepoint events from [file_name] instead of tracefs.\n"
Yabin Cui1a30a582019-01-10 15:35:39 -0800434"--out-fd <fd> Write output to a file descriptor.\n"
435"--stop-signal-fd <fd> Stop stating when fd is readable.\n"
Yabin Cuia80f8f72017-07-12 15:50:20 -0700436#endif
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200437 // clang-format on
438 ),
Yabin Cuif79f07e2015-06-01 11:21:37 -0700439 verbose_mode_(false),
Yabin Cui4be41262015-06-22 14:23:01 -0700440 system_wide_collection_(false),
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700441 child_inherit_(true),
Yabin Cui3e4c5952016-07-26 15:03:27 -0700442 duration_in_sec_(0),
Wei Wang539fb882016-09-28 14:42:02 -0700443 interval_in_ms_(0),
Yabin Cui9267db22018-04-18 11:17:19 -0700444 interval_only_values_(false),
Yabin Cui4cf37d12016-08-19 15:42:39 -0700445 event_selection_set_(true),
Yabin Cuia80f8f72017-07-12 15:50:20 -0700446 csv_(false),
447 in_app_context_(false) {
Yabin Cui987d9ab2016-07-15 14:08:48 -0700448 // Die if parent exits.
449 prctl(PR_SET_PDEATHSIG, SIGHUP, 0, 0, 0);
Yabin Cuif53f7162020-06-19 15:16:31 -0700450 // Set default sort keys. Full key list is in BuildSummaryComparator().
451 sort_keys_ = {"count_per_thread", "tid", "cpu", "count"};
Yabin Cui323e9452015-04-20 18:07:17 -0700452 }
453
454 bool Run(const std::vector<std::string>& args);
455
456 private:
Yabin Cui61b4dac2023-11-03 15:19:14 -0700457 bool ParseOptions(const std::vector<std::string>& args, std::vector<std::string>* non_option_args,
458 ProbeEvents& probe_events);
Yabin Cui5aded992022-08-25 10:51:11 -0700459 void PrintHardwareCounters();
Yabin Cui323e9452015-04-20 18:07:17 -0700460 bool AddDefaultMeasuredEventTypes();
Yabin Cui877751b2016-06-13 18:03:47 -0700461 void SetEventSelectionFlags();
Yabin Cuidc2708c2020-01-10 15:33:11 -0800462 void MonitorEachThread();
Yabin Cui8ab56212020-01-27 15:23:46 -0800463 void AdjustToIntervalOnlyValues(std::vector<CountersInfo>& counters);
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200464 bool ShowCounters(const std::vector<CountersInfo>& counters, double duration_in_sec, FILE* fp);
Yabin4ed8e112022-08-23 11:43:01 -0700465 void CheckHardwareCounterMultiplexing();
Yabin Cui6a2fda42022-09-01 11:52:51 -0700466 void PrintWarningForInaccurateEvents();
Yabin Cui323e9452015-04-20 18:07:17 -0700467
Yabin Cui323e9452015-04-20 18:07:17 -0700468 bool verbose_mode_;
469 bool system_wide_collection_;
Yabin Cui4be41262015-06-22 14:23:01 -0700470 bool child_inherit_;
Yabin Cui3e4c5952016-07-26 15:03:27 -0700471 double duration_in_sec_;
Wei Wang539fb882016-09-28 14:42:02 -0700472 double interval_in_ms_;
Yabin Cui9267db22018-04-18 11:17:19 -0700473 bool interval_only_values_;
Yabin Cui8ab56212020-01-27 15:23:46 -0800474 std::vector<std::vector<CounterSum>> last_sum_values_;
Yabin Cui4be41262015-06-22 14:23:01 -0700475 EventSelectionSet event_selection_set_;
Yabin Cui0a45adf2016-06-22 20:58:52 -0700476 std::string output_filename_;
Yabin Cui1a30a582019-01-10 15:35:39 -0800477 android::base::unique_fd out_fd_;
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700478 bool csv_;
Yabin Cuia80f8f72017-07-12 15:50:20 -0700479 std::string app_package_name_;
480 bool in_app_context_;
Yabin Cui1a30a582019-01-10 15:35:39 -0800481 android::base::unique_fd stop_signal_fd_;
Yabin Cui52f32a42019-08-12 16:53:46 -0700482 bool use_devfreq_counters_ = false;
Yabin Cuidc2708c2020-01-10 15:33:11 -0800483
Yabin Cui8ab56212020-01-27 15:23:46 -0800484 bool report_per_core_ = false;
Yabin Cuidc2708c2020-01-10 15:33:11 -0800485 bool report_per_thread_ = false;
Yabin Cui8ab56212020-01-27 15:23:46 -0800486 // used to report event count for each thread
Yabin Cuidc2708c2020-01-10 15:33:11 -0800487 std::unordered_map<pid_t, ThreadInfo> thread_info_;
Yabin Cuif53f7162020-06-19 15:16:31 -0700488 // used to sort report
489 std::vector<std::string> sort_keys_;
490 std::optional<SummaryComparator> summary_comparator_;
Yabin Cuif1a1e482021-12-22 14:54:20 -0800491 bool print_hw_counter_ = false;
Yabin Cui323e9452015-04-20 18:07:17 -0700492};
493
Yabin Cuif79f07e2015-06-01 11:21:37 -0700494bool StatCommand::Run(const std::vector<std::string>& args) {
Yabin Cuiebf79f32016-06-01 15:39:39 -0700495 if (!CheckPerfEventLimit()) {
496 return false;
497 }
Yabin Cuidc2708c2020-01-10 15:33:11 -0800498 AllowMoreOpenedFiles();
Yabin Cuiebf79f32016-06-01 15:39:39 -0700499
Yabin Cui4be41262015-06-22 14:23:01 -0700500 // 1. Parse options, and use default measured event types if not given.
Yabin Cui323e9452015-04-20 18:07:17 -0700501 std::vector<std::string> workload_args;
Yabin Cui61b4dac2023-11-03 15:19:14 -0700502 ProbeEvents probe_events(event_selection_set_);
503 if (!ParseOptions(args, &workload_args, probe_events)) {
Yabin Cui323e9452015-04-20 18:07:17 -0700504 return false;
505 }
Yabin Cuif1a1e482021-12-22 14:54:20 -0800506 if (print_hw_counter_) {
Yabin Cui5aded992022-08-25 10:51:11 -0700507 PrintHardwareCounters();
508 return true;
Yabin Cuif1a1e482021-12-22 14:54:20 -0800509 }
Yabin Cuia80f8f72017-07-12 15:50:20 -0700510 if (!app_package_name_.empty() && !in_app_context_) {
511 if (!IsRoot()) {
512 return RunInAppContext(app_package_name_, "stat", args, workload_args.size(),
Yabin Cuif8974522017-07-17 14:36:37 -0700513 output_filename_, !event_selection_set_.GetTracepointEvents().empty());
Yabin Cuia80f8f72017-07-12 15:50:20 -0700514 }
515 }
Yabin Cui52f32a42019-08-12 16:53:46 -0700516 DevfreqCounters devfreq_counters;
517 if (use_devfreq_counters_) {
518 if (!devfreq_counters.Use()) {
519 return false;
520 }
521 }
Yabin Cui877751b2016-06-13 18:03:47 -0700522 if (event_selection_set_.empty()) {
Yabin Cui323e9452015-04-20 18:07:17 -0700523 if (!AddDefaultMeasuredEventTypes()) {
524 return false;
525 }
526 }
Yabin Cui877751b2016-06-13 18:03:47 -0700527 SetEventSelectionFlags();
Yabin Cui323e9452015-04-20 18:07:17 -0700528
Yabin Cui4be41262015-06-22 14:23:01 -0700529 // 2. Create workload.
Yabin Cuib032de72015-06-17 21:15:09 -0700530 std::unique_ptr<Workload> workload;
531 if (!workload_args.empty()) {
532 workload = Workload::CreateWorkload(workload_args);
533 if (workload == nullptr) {
534 return false;
535 }
Yabin Cui323e9452015-04-20 18:07:17 -0700536 }
Yabin Cui5f43fc42016-12-13 13:47:49 -0800537 bool need_to_check_targets = false;
Yabin Cuibc2a1022016-08-29 12:33:17 -0700538 if (system_wide_collection_) {
Yabin Cuidc2708c2020-01-10 15:33:11 -0800539 if (report_per_thread_) {
540 event_selection_set_.AddMonitoredProcesses(GetAllProcesses());
541 } else {
542 event_selection_set_.AddMonitoredThreads({-1});
543 }
Yabin Cuibc2a1022016-08-29 12:33:17 -0700544 } else if (!event_selection_set_.HasMonitoredTarget()) {
Yabin Cuib032de72015-06-17 21:15:09 -0700545 if (workload != nullptr) {
Yabin Cuibc2a1022016-08-29 12:33:17 -0700546 event_selection_set_.AddMonitoredProcesses({workload->GetPid()});
Yabin Cuie964a022023-11-22 14:26:49 -0800547 event_selection_set_.SetEnableCondition(false, true);
Yabin Cuia80f8f72017-07-12 15:50:20 -0700548 } else if (!app_package_name_.empty()) {
Yabin Cui7cb6f292017-08-28 14:49:04 -0700549 std::set<pid_t> pids = WaitForAppProcesses(app_package_name_);
550 event_selection_set_.AddMonitoredProcesses(pids);
Yabin Cuib032de72015-06-17 21:15:09 -0700551 } else {
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200552 LOG(ERROR) << "No threads to monitor. Try `simpleperf help stat` for help\n";
Yabin Cuib032de72015-06-17 21:15:09 -0700553 return false;
554 }
Yabin Cui5f43fc42016-12-13 13:47:49 -0800555 } else {
556 need_to_check_targets = true;
Yabin Cui323e9452015-04-20 18:07:17 -0700557 }
558
Yabin Cuidc2708c2020-01-10 15:33:11 -0800559 if (report_per_thread_) {
560 MonitorEachThread();
561 }
562
Wei Wang539fb882016-09-28 14:42:02 -0700563 // 3. Open perf_event_files and output file if defined.
Yabin Cuidbf82802023-10-19 13:28:42 -0700564 if (!event_selection_set_.OpenEventFiles()) {
Yabin Cuibc2a1022016-08-29 12:33:17 -0700565 return false;
Yabin Cui323e9452015-04-20 18:07:17 -0700566 }
Wei Wang539fb882016-09-28 14:42:02 -0700567 std::unique_ptr<FILE, decltype(&fclose)> fp_holder(nullptr, fclose);
Wei Wang539fb882016-09-28 14:42:02 -0700568 if (!output_filename_.empty()) {
Yabin Cui1a30a582019-01-10 15:35:39 -0800569 fp_holder.reset(fopen(output_filename_.c_str(), "we"));
Wei Wang539fb882016-09-28 14:42:02 -0700570 if (fp_holder == nullptr) {
571 PLOG(ERROR) << "failed to open " << output_filename_;
572 return false;
573 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800574 } else if (out_fd_ != -1) {
575 fp_holder.reset(fdopen(out_fd_.release(), "we"));
576 if (fp_holder == nullptr) {
577 PLOG(ERROR) << "failed to write output.";
578 return false;
579 }
Wei Wang539fb882016-09-28 14:42:02 -0700580 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800581 FILE* fp = fp_holder ? fp_holder.get() : stdout;
Yabin Cui323e9452015-04-20 18:07:17 -0700582
Yabin Cui26968e62017-01-30 11:34:24 -0800583 // 4. Add signal/periodic Events.
Yabin Cuic29e1722018-02-14 13:41:03 -0800584 IOEventLoop* loop = event_selection_set_.GetIOEventLoop();
Wei Wang539fb882016-09-28 14:42:02 -0700585 std::chrono::time_point<std::chrono::steady_clock> start_time;
586 std::vector<CountersInfo> counters;
Yabin Cui5f43fc42016-12-13 13:47:49 -0800587 if (need_to_check_targets && !event_selection_set_.StopWhenNoMoreTargets()) {
588 return false;
589 }
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200590 auto exit_loop_callback = [loop]() { return loop->ExitLoop(); };
Yabin Cui1a30a582019-01-10 15:35:39 -0800591 if (!loop->AddSignalEvents({SIGCHLD, SIGINT, SIGTERM, SIGHUP}, exit_loop_callback)) {
Yabin Cui3e4c5952016-07-26 15:03:27 -0700592 return false;
593 }
Yabin Cui1a30a582019-01-10 15:35:39 -0800594 if (stop_signal_fd_ != -1) {
595 if (!loop->AddReadEvent(stop_signal_fd_, exit_loop_callback)) {
596 return false;
597 }
598 }
Yabin Cui3e4c5952016-07-26 15:03:27 -0700599 if (duration_in_sec_ != 0) {
Yabin Cui1a30a582019-01-10 15:35:39 -0800600 if (!loop->AddPeriodicEvent(SecondToTimeval(duration_in_sec_), exit_loop_callback)) {
Yabin Cui3e4c5952016-07-26 15:03:27 -0700601 return false;
602 }
603 }
Wei Wang539fb882016-09-28 14:42:02 -0700604 auto print_counters = [&]() {
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200605 auto end_time = std::chrono::steady_clock::now();
606 if (!event_selection_set_.ReadCounters(&counters)) {
607 return false;
608 }
609 double duration_in_sec =
610 std::chrono::duration_cast<std::chrono::duration<double>>(end_time - start_time).count();
611 if (interval_only_values_) {
612 AdjustToIntervalOnlyValues(counters);
613 }
614 if (!ShowCounters(counters, duration_in_sec, fp)) {
615 return false;
616 }
617 return true;
Wei Wang539fb882016-09-28 14:42:02 -0700618 };
619
620 if (interval_in_ms_ != 0) {
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200621 if (!loop->AddPeriodicEvent(SecondToTimeval(interval_in_ms_ / 1000.0), print_counters)) {
Wei Wang539fb882016-09-28 14:42:02 -0700622 return false;
623 }
624 }
Yabin Cui3e4c5952016-07-26 15:03:27 -0700625
626 // 5. Count events while workload running.
Wei Wang539fb882016-09-28 14:42:02 -0700627 start_time = std::chrono::steady_clock::now();
Yabin Cuib032de72015-06-17 21:15:09 -0700628 if (workload != nullptr && !workload->Start()) {
Yabin Cui323e9452015-04-20 18:07:17 -0700629 return false;
630 }
Yabin Cui26968e62017-01-30 11:34:24 -0800631 if (!loop->RunLoop()) {
Yabin Cui3e4c5952016-07-26 15:03:27 -0700632 return false;
Yabin Cui621a5332015-06-15 16:17:20 -0700633 }
Yabin Cui323e9452015-04-20 18:07:17 -0700634
Yabin Cui3e4c5952016-07-26 15:03:27 -0700635 // 6. Read and print counters.
Yabin Cui9267db22018-04-18 11:17:19 -0700636 if (interval_in_ms_ == 0) {
Yabin4ed8e112022-08-23 11:43:01 -0700637 if (!print_counters()) {
638 return false;
639 }
Yabin Cui9267db22018-04-18 11:17:19 -0700640 }
Yabin4ed8e112022-08-23 11:43:01 -0700641
Yabin Cui6a2fda42022-09-01 11:52:51 -0700642 // 7. Print warnings when needed.
Yabin4ed8e112022-08-23 11:43:01 -0700643 event_selection_set_.CloseEventFiles();
644 CheckHardwareCounterMultiplexing();
Yabin Cui6a2fda42022-09-01 11:52:51 -0700645 PrintWarningForInaccurateEvents();
Yabin4ed8e112022-08-23 11:43:01 -0700646
Yabin Cui9267db22018-04-18 11:17:19 -0700647 return true;
Yabin Cui323e9452015-04-20 18:07:17 -0700648}
649
Yabin Cuif79f07e2015-06-01 11:21:37 -0700650bool StatCommand::ParseOptions(const std::vector<std::string>& args,
Yabin Cui61b4dac2023-11-03 15:19:14 -0700651 std::vector<std::string>* non_option_args,
652 ProbeEvents& probe_events) {
Yabin Cui6f094672020-07-22 14:50:35 -0700653 OptionValueMap options;
654 std::vector<std::pair<OptionName, OptionValue>> ordered_options;
655
656 if (!PreprocessOptions(args, GetStatCmdOptionFormats(), &options, &ordered_options,
657 non_option_args)) {
658 return false;
659 }
660
661 // Process options.
662 system_wide_collection_ = options.PullBoolValue("-a");
663
664 if (auto value = options.PullValue("--app"); value) {
665 app_package_name_ = *value->str_value;
666 }
Yabin Cui6f094672020-07-22 14:50:35 -0700667 csv_ = options.PullBoolValue("--csv");
668
669 if (!options.PullDoubleValue("--duration", &duration_in_sec_, 1e-9)) {
670 return false;
671 }
672 if (!options.PullDoubleValue("--interval", &interval_in_ms_, 1e-9)) {
673 return false;
674 }
675 interval_only_values_ = options.PullBoolValue("--interval-only-values");
676
Yabin Cui6f094672020-07-22 14:50:35 -0700677 in_app_context_ = options.PullBoolValue("--in-app");
Yabin Cui61b4dac2023-11-03 15:19:14 -0700678 for (const OptionValue& value : options.PullValues("--kprobe")) {
679 for (const auto& cmd : Split(*value.str_value, ",")) {
680 if (!probe_events.AddKprobe(cmd)) {
681 return false;
682 }
683 }
684 }
Yabin Cui6f094672020-07-22 14:50:35 -0700685 child_inherit_ = !options.PullBoolValue("--no-inherit");
686
687 if (auto value = options.PullValue("-o"); value) {
688 output_filename_ = *value->str_value;
689 }
690 if (auto value = options.PullValue("--out-fd"); value) {
691 out_fd_.reset(static_cast<int>(value->uint_value));
692 }
693
694 report_per_core_ = options.PullBoolValue("--per-core");
695 report_per_thread_ = options.PullBoolValue("--per-thread");
696
Yabin Cui1c6be752023-02-28 11:46:37 -0800697 if (auto strs = options.PullStringValues("-p"); !strs.empty()) {
698 if (auto pids = GetPidsFromStrings(strs, true, true); pids) {
Yabin Cuie3ca9982020-10-16 13:16:26 -0700699 event_selection_set_.AddMonitoredProcesses(pids.value());
700 } else {
701 return false;
Yabin Cui6f094672020-07-22 14:50:35 -0700702 }
703 }
Yabin Cuif1a1e482021-12-22 14:54:20 -0800704 print_hw_counter_ = options.PullBoolValue("--print-hw-counter");
Yabin Cuif53f7162020-06-19 15:16:31 -0700705
Yabin Cui6f094672020-07-22 14:50:35 -0700706 if (auto value = options.PullValue("--sort"); value) {
707 sort_keys_ = Split(*value->str_value, ",");
708 }
709
710 if (auto value = options.PullValue("--stop-signal-fd"); value) {
711 stop_signal_fd_.reset(static_cast<int>(value->uint_value));
712 }
713
Yabin Cuie3ca9982020-10-16 13:16:26 -0700714 for (const OptionValue& value : options.PullValues("-t")) {
715 if (auto tids = GetTidsFromString(*value.str_value, true); tids) {
716 event_selection_set_.AddMonitoredThreads(tids.value());
717 } else {
718 return false;
Yabin Cui6f094672020-07-22 14:50:35 -0700719 }
720 }
721
722 if (auto value = options.PullValue("--tracepoint-events"); value) {
Yabin Cui16a6ace2020-10-01 14:56:32 -0700723 if (!EventTypeManager::Instance().ReadTracepointsFromFile(*value->str_value)) {
Yabin Cui323e9452015-04-20 18:07:17 -0700724 return false;
725 }
726 }
727
Yabin Cui6f094672020-07-22 14:50:35 -0700728 use_devfreq_counters_ = options.PullBoolValue("--use-devfreq-counters");
729 verbose_mode_ = options.PullBoolValue("--verbose");
730
731 CHECK(options.values.empty());
Yabin Cuidbf82802023-10-19 13:28:42 -0700732
733 // Process ordered options.
734 for (const auto& pair : ordered_options) {
735 const OptionName& name = pair.first;
736 const OptionValue& value = pair.second;
737
738 if (name == "--cpu") {
739 if (auto v = GetCpusFromString(*value.str_value); v) {
740 std::set<int>& cpus = v.value();
741 event_selection_set_.SetCpusForNewEvents(std::vector<int>(cpus.begin(), cpus.end()));
742 } else {
743 return false;
744 }
745 } else if (name == "-e") {
746 for (const auto& event_type : Split(*value.str_value, ",")) {
Yabin Cui61b4dac2023-11-03 15:19:14 -0700747 if (!probe_events.CreateProbeEventIfNotExist(event_type)) {
748 return false;
749 }
Yabin Cuidbf82802023-10-19 13:28:42 -0700750 if (!event_selection_set_.AddEventType(event_type)) {
751 return false;
752 }
753 }
754 } else if (name == "--group") {
Yabin Cui61b4dac2023-11-03 15:19:14 -0700755 std::vector<std::string> event_types = Split(*value.str_value, ",");
756 for (const auto& event_type : event_types) {
757 if (!probe_events.CreateProbeEventIfNotExist(event_type)) {
758 return false;
759 }
760 }
761 if (!event_selection_set_.AddEventGroup(event_types)) {
Yabin Cuidbf82802023-10-19 13:28:42 -0700762 return false;
763 }
Yabin Cui6de79a02023-11-03 16:36:56 -0700764 } else if (name == "--tp-filter") {
765 if (!event_selection_set_.SetTracepointFilter(*value.str_value)) {
766 return false;
767 }
768 } else {
769 LOG(ERROR) << "unprocessed option: " << name;
770 return false;
Yabin Cuidbf82802023-10-19 13:28:42 -0700771 }
772 }
Yabin Cui6f094672020-07-22 14:50:35 -0700773
Yabin Cuibc2a1022016-08-29 12:33:17 -0700774 if (system_wide_collection_ && event_selection_set_.HasMonitoredTarget()) {
Yabin Cui877751b2016-06-13 18:03:47 -0700775 LOG(ERROR) << "Stat system wide and existing processes/threads can't be "
776 "used at the same time.";
Yabin Cuib032de72015-06-17 21:15:09 -0700777 return false;
778 }
Yabin Cui8a599d72016-07-21 18:32:53 -0700779 if (system_wide_collection_ && !IsRoot()) {
780 LOG(ERROR) << "System wide profiling needs root privilege.";
781 return false;
782 }
Yabin Cuib032de72015-06-17 21:15:09 -0700783
Yabin Cuif53f7162020-06-19 15:16:31 -0700784 if (report_per_core_ || report_per_thread_) {
785 summary_comparator_ = BuildSummaryComparator(sort_keys_, report_per_thread_, report_per_core_);
786 if (!summary_comparator_) {
787 return false;
788 }
789 }
Yabin Cui323e9452015-04-20 18:07:17 -0700790 return true;
791}
792
Yabin4ed8e112022-08-23 11:43:01 -0700793std::optional<bool> CheckHardwareCountersOnCpu(int cpu, size_t counters) {
Yabin Cuidbf82802023-10-19 13:28:42 -0700794 if (counters == 0) {
795 return true;
796 }
Yabin Cuif1a1e482021-12-22 14:54:20 -0800797 const EventType* event = FindEventTypeByName("cpu-cycles", true);
798 if (event == nullptr) {
Yabin6b771a22022-08-18 17:01:54 -0700799 return std::nullopt;
Yabin Cuif1a1e482021-12-22 14:54:20 -0800800 }
801 perf_event_attr attr = CreateDefaultPerfEventAttr(*event);
Yabin4ed8e112022-08-23 11:43:01 -0700802 auto workload = Workload::CreateWorkload({"sleep", "0.1"});
803 if (!workload || !workload->SetCpuAffinity(cpu)) {
804 return std::nullopt;
805 }
806 std::vector<std::unique_ptr<EventFd>> event_fds;
807 for (size_t i = 0; i < counters; i++) {
808 EventFd* group_event_fd = event_fds.empty() ? nullptr : event_fds[0].get();
809 auto event_fd =
810 EventFd::OpenEventFile(attr, workload->GetPid(), cpu, group_event_fd, "cpu-cycles", false);
811 if (!event_fd) {
Yabin Cuif1a1e482021-12-22 14:54:20 -0800812 return false;
813 }
Yabin4ed8e112022-08-23 11:43:01 -0700814 event_fds.emplace_back(std::move(event_fd));
815 }
816 if (!workload->Start() || !workload->WaitChildProcess(true, nullptr)) {
817 return std::nullopt;
818 }
819 for (auto& event_fd : event_fds) {
820 PerfCounter counter;
821 if (!event_fd->ReadCounter(&counter)) {
822 return std::nullopt;
Yabin Cuif1a1e482021-12-22 14:54:20 -0800823 }
Yabin4ed8e112022-08-23 11:43:01 -0700824 if (counter.time_enabled == 0 || counter.time_enabled > counter.time_running) {
825 return false;
826 }
827 }
828 return true;
829}
830
831std::optional<size_t> GetHardwareCountersOnCpu(int cpu) {
832 size_t available_counters = 0;
833 while (true) {
834 std::optional<bool> result = CheckHardwareCountersOnCpu(cpu, available_counters + 1);
835 if (!result.has_value()) {
836 return std::nullopt;
837 }
838 if (!result.value()) {
Yabin Cuif1a1e482021-12-22 14:54:20 -0800839 break;
840 }
841 available_counters++;
842 }
Yabin6b771a22022-08-18 17:01:54 -0700843 return available_counters;
844}
845
Yabin Cui5aded992022-08-25 10:51:11 -0700846void StatCommand::PrintHardwareCounters() {
Yabin6b771a22022-08-18 17:01:54 -0700847 for (int cpu : GetOnlineCpus()) {
848 std::optional<size_t> counters = GetHardwareCountersOnCpu(cpu);
849 if (!counters) {
Yabin Cui5aded992022-08-25 10:51:11 -0700850 // When built as a 32-bit program, we can't set sched_affinity to a 64-bit only CPU. So we
851 // may not be able to get hardware counters on that CPU.
852 LOG(WARNING) << "Failed to get CPU PMU hardware counters on cpu " << cpu;
853 continue;
Yabin6b771a22022-08-18 17:01:54 -0700854 }
855 printf("There are %zu CPU PMU hardware counters available on cpu %d.\n", counters.value(), cpu);
856 }
Yabin Cuif1a1e482021-12-22 14:54:20 -0800857}
858
Yabin Cuif79f07e2015-06-01 11:21:37 -0700859bool StatCommand::AddDefaultMeasuredEventTypes() {
Yabin Cui323e9452015-04-20 18:07:17 -0700860 for (auto& name : default_measured_event_types) {
Yabin Cui877751b2016-06-13 18:03:47 -0700861 // It is not an error when some event types in the default list are not
862 // supported by the kernel.
Yabin Cui9fd3cc12015-06-25 17:42:23 -0700863 const EventType* type = FindEventTypeByName(name);
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200864 if (type != nullptr && IsEventAttrSupported(CreateDefaultPerfEventAttr(*type), name)) {
Yabin Cui877751b2016-06-13 18:03:47 -0700865 if (!event_selection_set_.AddEventType(name)) {
866 return false;
867 }
Yabin Cui9fd3cc12015-06-25 17:42:23 -0700868 }
Yabin Cui323e9452015-04-20 18:07:17 -0700869 }
Yabin Cui877751b2016-06-13 18:03:47 -0700870 if (event_selection_set_.empty()) {
Yabin Cui323e9452015-04-20 18:07:17 -0700871 LOG(ERROR) << "Failed to add any supported default measured types";
872 return false;
873 }
874 return true;
875}
876
Yabin Cui877751b2016-06-13 18:03:47 -0700877void StatCommand::SetEventSelectionFlags() {
Yabin Cui4be41262015-06-22 14:23:01 -0700878 event_selection_set_.SetInherit(child_inherit_);
879}
880
Yabin Cuidc2708c2020-01-10 15:33:11 -0800881void StatCommand::MonitorEachThread() {
882 std::vector<pid_t> threads;
883 for (auto pid : event_selection_set_.GetMonitoredProcesses()) {
884 for (auto tid : GetThreadsInProcess(pid)) {
885 ThreadInfo info;
886 if (GetThreadName(tid, &info.name)) {
887 info.tid = tid;
888 info.pid = pid;
889 thread_info_[tid] = std::move(info);
890 threads.push_back(tid);
891 }
892 }
893 }
894 for (auto tid : event_selection_set_.GetMonitoredThreads()) {
895 ThreadInfo info;
896 if (ReadThreadNameAndPid(tid, &info.name, &info.pid)) {
897 info.tid = tid;
898 thread_info_[tid] = std::move(info);
899 threads.push_back(tid);
900 }
901 }
902 event_selection_set_.ClearMonitoredTargets();
903 event_selection_set_.AddMonitoredThreads(threads);
904}
905
Yabin Cui8ab56212020-01-27 15:23:46 -0800906void StatCommand::AdjustToIntervalOnlyValues(std::vector<CountersInfo>& counters) {
907 if (last_sum_values_.size() < counters.size()) {
908 last_sum_values_.resize(counters.size());
909 }
910 for (size_t i = 0; i < counters.size(); i++) {
911 std::vector<CounterInfo>& counters_per_event = counters[i].counters;
912 std::vector<CounterSum>& last_sum = last_sum_values_[i];
913
914 if (last_sum.size() < counters_per_event.size()) {
915 last_sum.resize(counters_per_event.size());
916 }
917 for (size_t j = 0; j < counters_per_event.size(); j++) {
918 PerfCounter& counter = counters_per_event[j].counter;
Yabin Cuib3ed39b2020-03-26 14:00:49 -0700919 CounterSum new_sum;
920 new_sum.FromCounter(counter);
921 CounterSum delta = new_sum - last_sum[j];
922 delta.ToCounter(counter);
923 last_sum[j] = new_sum;
Yabin Cui8ab56212020-01-27 15:23:46 -0800924 }
925 }
926}
927
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200928bool StatCommand::ShowCounters(const std::vector<CountersInfo>& counters, double duration_in_sec,
929 FILE* fp) {
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700930 if (csv_) {
931 fprintf(fp, "Performance counter statistics,\n");
932 } else {
933 fprintf(fp, "Performance counter statistics:\n\n");
934 }
Yabin Cui323e9452015-04-20 18:07:17 -0700935
Yabin Cui04d08a32015-08-19 15:01:12 -0700936 if (verbose_mode_) {
937 for (auto& counters_info : counters) {
Yabin Cui04d08a32015-08-19 15:01:12 -0700938 for (auto& counter_info : counters_info.counters) {
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700939 if (csv_) {
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200940 fprintf(fp,
941 "%s,tid,%d,cpu,%d,count,%" PRIu64 ",time_enabled,%" PRIu64
942 ",time running,%" PRIu64 ",id,%" PRIu64 ",\n",
943 counters_info.event_name.c_str(), counter_info.tid, counter_info.cpu,
944 counter_info.counter.value, counter_info.counter.time_enabled,
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700945 counter_info.counter.time_running, counter_info.counter.id);
946 } else {
947 fprintf(fp,
948 "%s(tid %d, cpu %d): count %" PRIu64 ", time_enabled %" PRIu64
949 ", time running %" PRIu64 ", id %" PRIu64 "\n",
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200950 counters_info.event_name.c_str(), counter_info.tid, counter_info.cpu,
951 counter_info.counter.value, counter_info.counter.time_enabled,
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700952 counter_info.counter.time_running, counter_info.counter.id);
953 }
Yabin Cui323e9452015-04-20 18:07:17 -0700954 }
955 }
Yabin Cui04d08a32015-08-19 15:01:12 -0700956 }
Yabin Cui323e9452015-04-20 18:07:17 -0700957
Yabin Cuif53f7162020-06-19 15:16:31 -0700958 CounterSummaryBuilder builder(report_per_thread_, report_per_core_, csv_, thread_info_,
959 summary_comparator_);
Yabin Cui8ab56212020-01-27 15:23:46 -0800960 for (const auto& info : counters) {
Yabin Cuib3ed39b2020-03-26 14:00:49 -0700961 builder.AddCountersForOneEventType(info);
Yabin Cui323e9452015-04-20 18:07:17 -0700962 }
Yabin Cuib3ed39b2020-03-26 14:00:49 -0700963 CounterSummaries summaries(builder.Build(), csv_);
Yabin Cui0a45adf2016-06-22 20:58:52 -0700964 summaries.AutoGenerateSummaries();
965 summaries.GenerateComments(duration_in_sec);
966 summaries.Show(fp);
Yabin Cui04d08a32015-08-19 15:01:12 -0700967
Yabin4ed8e112022-08-23 11:43:01 -0700968 if (csv_) {
Zhiting Zhu0979ba82016-07-09 19:38:08 -0700969 fprintf(fp, "Total test time,%lf,seconds,\n", duration_in_sec);
Yabin Cui8ab56212020-01-27 15:23:46 -0800970 } else {
Yabin4ed8e112022-08-23 11:43:01 -0700971 fprintf(fp, "\nTotal test time: %lf seconds.\n", duration_in_sec);
Yabin Cui52f32a42019-08-12 16:53:46 -0700972 }
Yabin Cui323e9452015-04-20 18:07:17 -0700973 return true;
974}
975
Yabin4ed8e112022-08-23 11:43:01 -0700976void StatCommand::CheckHardwareCounterMultiplexing() {
Yabin Cuidbf82802023-10-19 13:28:42 -0700977 for (const auto& [cpu, hardware_events] : event_selection_set_.GetHardwareCountersForCpus()) {
Yabin4ed8e112022-08-23 11:43:01 -0700978 std::optional<bool> result = CheckHardwareCountersOnCpu(cpu, hardware_events);
979 if (result.has_value() && !result.value()) {
980 LOG(WARNING) << "It seems the number of hardware events are more than the number of\n"
981 << "available CPU PMU hardware counters. That will trigger hardware counter\n"
982 << "multiplexing. As a result, events are not counted all the time processes\n"
983 << "running, and event counts are smaller than what really happen.\n"
984 << "Use --print-hw-counter to show available hardware counters.\n"
985#if defined(__ANDROID__)
986 << "If on a rooted device, try --use-devfreq-counters to get more counters.\n"
987#endif
988 ;
989 break;
990 }
991 }
992}
993
Yabin Cui6a2fda42022-09-01 11:52:51 -0700994void StatCommand::PrintWarningForInaccurateEvents() {
995 for (const EventType* event : event_selection_set_.GetEvents()) {
996 if (event->name == "raw-l3d-cache-lmiss-rd") {
997 LOG(WARNING) << "PMU event L3D_CACHE_LMISS_RD might undercount on A510. Please use "
998 "L3D_CACHE_REFILL_RD instead.";
999 break;
1000 }
1001 }
1002}
1003
Yabin Cui877751b2016-06-13 18:03:47 -07001004} // namespace
1005
Yabin Cuiff7465c2016-02-25 11:02:30 -08001006void RegisterStatCommand() {
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +02001007 RegisterCommand("stat", [] { return std::unique_ptr<Command>(new StatCommand); });
Yabin Cuif79f07e2015-06-01 11:21:37 -07001008}
Yabin Cuiacbdb242020-07-07 15:56:34 -07001009
1010} // namespace simpleperf