1*288bf522SAndroid Build Coastguard Worker /*
2*288bf522SAndroid Build Coastguard Worker * Copyright (C) 2015 The Android Open Source Project
3*288bf522SAndroid Build Coastguard Worker *
4*288bf522SAndroid Build Coastguard Worker * Licensed under the Apache License, Version 2.0 (the "License");
5*288bf522SAndroid Build Coastguard Worker * you may not use this file except in compliance with the License.
6*288bf522SAndroid Build Coastguard Worker * You may obtain a copy of the License at
7*288bf522SAndroid Build Coastguard Worker *
8*288bf522SAndroid Build Coastguard Worker * http://www.apache.org/licenses/LICENSE-2.0
9*288bf522SAndroid Build Coastguard Worker *
10*288bf522SAndroid Build Coastguard Worker * Unless required by applicable law or agreed to in writing, software
11*288bf522SAndroid Build Coastguard Worker * distributed under the License is distributed on an "AS IS" BASIS,
12*288bf522SAndroid Build Coastguard Worker * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13*288bf522SAndroid Build Coastguard Worker * See the License for the specific language governing permissions and
14*288bf522SAndroid Build Coastguard Worker * limitations under the License.
15*288bf522SAndroid Build Coastguard Worker */
16*288bf522SAndroid Build Coastguard Worker
17*288bf522SAndroid Build Coastguard Worker #include <inttypes.h>
18*288bf522SAndroid Build Coastguard Worker #include <signal.h>
19*288bf522SAndroid Build Coastguard Worker #include <stdio.h>
20*288bf522SAndroid Build Coastguard Worker #include <string.h>
21*288bf522SAndroid Build Coastguard Worker #include <sys/prctl.h>
22*288bf522SAndroid Build Coastguard Worker
23*288bf522SAndroid Build Coastguard Worker #include <algorithm>
24*288bf522SAndroid Build Coastguard Worker #include <chrono>
25*288bf522SAndroid Build Coastguard Worker #include <optional>
26*288bf522SAndroid Build Coastguard Worker #include <set>
27*288bf522SAndroid Build Coastguard Worker #include <string>
28*288bf522SAndroid Build Coastguard Worker #include <string_view>
29*288bf522SAndroid Build Coastguard Worker #include <vector>
30*288bf522SAndroid Build Coastguard Worker
31*288bf522SAndroid Build Coastguard Worker #include <android-base/file.h>
32*288bf522SAndroid Build Coastguard Worker #include <android-base/logging.h>
33*288bf522SAndroid Build Coastguard Worker #include <android-base/strings.h>
34*288bf522SAndroid Build Coastguard Worker #include <android-base/unique_fd.h>
35*288bf522SAndroid Build Coastguard Worker
36*288bf522SAndroid Build Coastguard Worker #include "IOEventLoop.h"
37*288bf522SAndroid Build Coastguard Worker #include "ProbeEvents.h"
38*288bf522SAndroid Build Coastguard Worker #include "cmd_stat_impl.h"
39*288bf522SAndroid Build Coastguard Worker #include "command.h"
40*288bf522SAndroid Build Coastguard Worker #include "environment.h"
41*288bf522SAndroid Build Coastguard Worker #include "event_attr.h"
42*288bf522SAndroid Build Coastguard Worker #include "event_fd.h"
43*288bf522SAndroid Build Coastguard Worker #include "event_selection_set.h"
44*288bf522SAndroid Build Coastguard Worker #include "event_type.h"
45*288bf522SAndroid Build Coastguard Worker #include "utils.h"
46*288bf522SAndroid Build Coastguard Worker #include "workload.h"
47*288bf522SAndroid Build Coastguard Worker
48*288bf522SAndroid Build Coastguard Worker namespace simpleperf {
49*288bf522SAndroid Build Coastguard Worker
50*288bf522SAndroid Build Coastguard Worker using android::base::Split;
51*288bf522SAndroid Build Coastguard Worker
52*288bf522SAndroid Build Coastguard Worker static std::vector<std::string> default_measured_event_types{
53*288bf522SAndroid Build Coastguard Worker "cpu-cycles", "stalled-cycles-frontend", "stalled-cycles-backend",
54*288bf522SAndroid Build Coastguard Worker "instructions", "branch-instructions", "branch-misses",
55*288bf522SAndroid Build Coastguard Worker "task-clock", "context-switches", "page-faults",
56*288bf522SAndroid Build Coastguard Worker };
57*288bf522SAndroid Build Coastguard Worker
58*288bf522SAndroid Build Coastguard Worker static const std::unordered_map<std::string_view, std::pair<std::string_view, std::string_view>>
59*288bf522SAndroid Build Coastguard Worker COMMON_EVENT_RATE_MAP = {
60*288bf522SAndroid Build Coastguard Worker {"cache-misses", {"cache-references", "miss rate"}},
61*288bf522SAndroid Build Coastguard Worker {"branch-misses", {"branch-instructions", "miss rate"}},
62*288bf522SAndroid Build Coastguard Worker };
63*288bf522SAndroid Build Coastguard Worker
64*288bf522SAndroid Build Coastguard Worker static const std::unordered_map<std::string_view, std::pair<std::string_view, std::string_view>>
65*288bf522SAndroid Build Coastguard Worker ARM_EVENT_RATE_MAP = {
66*288bf522SAndroid Build Coastguard Worker // Refer to "D6.10.5 Meaningful ratios between common microarchitectural events" in ARMv8
67*288bf522SAndroid Build Coastguard Worker // specification.
68*288bf522SAndroid Build Coastguard Worker {"raw-l1i-cache-refill", {"raw-l1i-cache", "level 1 instruction cache refill rate"}},
69*288bf522SAndroid Build Coastguard Worker {"raw-l1i-tlb-refill", {"raw-l1i-tlb", "level 1 instruction TLB refill rate"}},
70*288bf522SAndroid Build Coastguard Worker {"raw-l1d-cache-refill", {"raw-l1d-cache", "level 1 data or unified cache refill rate"}},
71*288bf522SAndroid Build Coastguard Worker {"raw-l1d-tlb-refill", {"raw-l1d-tlb", "level 1 data or unified TLB refill rate"}},
72*288bf522SAndroid Build Coastguard Worker {"raw-l2d-cache-refill", {"raw-l2d-cache", "level 2 data or unified cache refill rate"}},
73*288bf522SAndroid Build Coastguard Worker {"raw-l2i-cache-refill", {"raw-l2i-cache", "level 2 instruction cache refill rate"}},
74*288bf522SAndroid Build Coastguard Worker {"raw-l3d-cache-refill", {"raw-l3d-cache", "level 3 data or unified cache refill rate"}},
75*288bf522SAndroid Build Coastguard Worker {"raw-l2d-tlb-refill", {"raw-l2d-tlb", "level 2 data or unified TLB refill rate"}},
76*288bf522SAndroid Build Coastguard Worker {"raw-l2i-tlb-refill", {"raw-l2i-tlb", "level 2 instruction TLB refill rate"}},
77*288bf522SAndroid Build Coastguard Worker {"raw-bus-access", {"raw-bus-cycles", "bus accesses per cycle"}},
78*288bf522SAndroid Build Coastguard Worker {"raw-ll-cache-miss", {"raw-ll-cache", "last level data or unified cache refill rate"}},
79*288bf522SAndroid Build Coastguard Worker {"raw-dtlb-walk", {"raw-l1d-tlb", "data TLB miss rate"}},
80*288bf522SAndroid Build Coastguard Worker {"raw-itlb-walk", {"raw-l1i-tlb", "instruction TLB miss rate"}},
81*288bf522SAndroid Build Coastguard Worker {"raw-ll-cache-miss-rd", {"raw-ll-cache-rd", "memory read operation miss rate"}},
82*288bf522SAndroid Build Coastguard Worker {"raw-remote-access-rd",
83*288bf522SAndroid Build Coastguard Worker {"raw-remote-access", "read accesses to another socket in a multi-socket system"}},
84*288bf522SAndroid Build Coastguard Worker // Refer to "Table K3-2 Relationship between REFILL events and associated access events" in
85*288bf522SAndroid Build Coastguard Worker // ARMv8 specification.
86*288bf522SAndroid Build Coastguard Worker {"raw-l1d-cache-refill-rd", {"raw-l1d-cache-rd", "level 1 cache refill rate, read"}},
87*288bf522SAndroid Build Coastguard Worker {"raw-l1d-cache-refill-wr", {"raw-l1d-cache-wr", "level 1 cache refill rate, write"}},
88*288bf522SAndroid Build Coastguard Worker {"raw-l1d-tlb-refill-rd", {"raw-l1d-tlb-rd", "level 1 TLB refill rate, read"}},
89*288bf522SAndroid Build Coastguard Worker {"raw-l1d-tlb-refill-wr", {"raw-l1d-tlb-wr", "level 1 TLB refill rate, write"}},
90*288bf522SAndroid Build Coastguard Worker {"raw-l2d-cache-refill-rd", {"raw-l2d-cache-rd", "level 2 data cache refill rate, read"}},
91*288bf522SAndroid Build Coastguard Worker {"raw-l2d-cache-refill-wr", {"raw-l2d-cache-wr", "level 2 data cache refill rate, write"}},
92*288bf522SAndroid Build Coastguard Worker {"raw-l2d-tlb-refill-rd", {"raw-l2d-tlb-rd", "level 2 data TLB refill rate, read"}},
93*288bf522SAndroid Build Coastguard Worker };
94*288bf522SAndroid Build Coastguard Worker
ReadableCountValue(bool csv)95*288bf522SAndroid Build Coastguard Worker std::string CounterSummary::ReadableCountValue(bool csv) {
96*288bf522SAndroid Build Coastguard Worker if (type_name == "cpu-clock" || type_name == "task-clock") {
97*288bf522SAndroid Build Coastguard Worker // Convert nanoseconds to milliseconds.
98*288bf522SAndroid Build Coastguard Worker double value = count / 1e6;
99*288bf522SAndroid Build Coastguard Worker return android::base::StringPrintf("%lf(ms)", value);
100*288bf522SAndroid Build Coastguard Worker }
101*288bf522SAndroid Build Coastguard Worker if (csv) {
102*288bf522SAndroid Build Coastguard Worker return android::base::StringPrintf("%" PRIu64, count);
103*288bf522SAndroid Build Coastguard Worker }
104*288bf522SAndroid Build Coastguard Worker return ReadableCount(count);
105*288bf522SAndroid Build Coastguard Worker }
106*288bf522SAndroid Build Coastguard Worker
FindSummary(const std::string & type_name,const std::string & modifier,const ThreadInfo * thread,int cpu)107*288bf522SAndroid Build Coastguard Worker const CounterSummary* CounterSummaries::FindSummary(const std::string& type_name,
108*288bf522SAndroid Build Coastguard Worker const std::string& modifier,
109*288bf522SAndroid Build Coastguard Worker const ThreadInfo* thread, int cpu) {
110*288bf522SAndroid Build Coastguard Worker for (const auto& s : summaries_) {
111*288bf522SAndroid Build Coastguard Worker if (s.type_name == type_name && s.modifier == modifier && s.thread == thread && s.cpu == cpu) {
112*288bf522SAndroid Build Coastguard Worker return &s;
113*288bf522SAndroid Build Coastguard Worker }
114*288bf522SAndroid Build Coastguard Worker }
115*288bf522SAndroid Build Coastguard Worker return nullptr;
116*288bf522SAndroid Build Coastguard Worker }
117*288bf522SAndroid Build Coastguard Worker
AutoGenerateSummaries()118*288bf522SAndroid Build Coastguard Worker void CounterSummaries::AutoGenerateSummaries() {
119*288bf522SAndroid Build Coastguard Worker for (size_t i = 0; i < summaries_.size(); ++i) {
120*288bf522SAndroid Build Coastguard Worker const CounterSummary& s = summaries_[i];
121*288bf522SAndroid Build Coastguard Worker if (s.modifier == "u") {
122*288bf522SAndroid Build Coastguard Worker const CounterSummary* other = FindSummary(s.type_name, "k", s.thread, s.cpu);
123*288bf522SAndroid Build Coastguard Worker if (other != nullptr && other->IsMonitoredAtTheSameTime(s)) {
124*288bf522SAndroid Build Coastguard Worker if (FindSummary(s.type_name, "", s.thread, s.cpu) == nullptr) {
125*288bf522SAndroid Build Coastguard Worker summaries_.emplace_back(s.type_name, "", s.group_id, s.thread, s.cpu,
126*288bf522SAndroid Build Coastguard Worker s.count + other->count, s.runtime_in_ns, s.scale, true, csv_);
127*288bf522SAndroid Build Coastguard Worker }
128*288bf522SAndroid Build Coastguard Worker }
129*288bf522SAndroid Build Coastguard Worker }
130*288bf522SAndroid Build Coastguard Worker }
131*288bf522SAndroid Build Coastguard Worker }
132*288bf522SAndroid Build Coastguard Worker
GenerateComments(double duration_in_sec)133*288bf522SAndroid Build Coastguard Worker void CounterSummaries::GenerateComments(double duration_in_sec) {
134*288bf522SAndroid Build Coastguard Worker for (auto& s : summaries_) {
135*288bf522SAndroid Build Coastguard Worker s.comment = GetCommentForSummary(s, duration_in_sec);
136*288bf522SAndroid Build Coastguard Worker }
137*288bf522SAndroid Build Coastguard Worker }
138*288bf522SAndroid Build Coastguard Worker
Show(FILE * fp)139*288bf522SAndroid Build Coastguard Worker void CounterSummaries::Show(FILE* fp) {
140*288bf522SAndroid Build Coastguard Worker bool show_thread = !summaries_.empty() && summaries_[0].thread != nullptr;
141*288bf522SAndroid Build Coastguard Worker bool show_cpu = !summaries_.empty() && summaries_[0].cpu != -1;
142*288bf522SAndroid Build Coastguard Worker if (csv_) {
143*288bf522SAndroid Build Coastguard Worker ShowCSV(fp, show_thread, show_cpu);
144*288bf522SAndroid Build Coastguard Worker } else {
145*288bf522SAndroid Build Coastguard Worker ShowText(fp, show_thread, show_cpu);
146*288bf522SAndroid Build Coastguard Worker }
147*288bf522SAndroid Build Coastguard Worker }
148*288bf522SAndroid Build Coastguard Worker
ShowCSV(FILE * fp,bool show_thread,bool show_cpu)149*288bf522SAndroid Build Coastguard Worker void CounterSummaries::ShowCSV(FILE* fp, bool show_thread, bool show_cpu) {
150*288bf522SAndroid Build Coastguard Worker for (auto& s : summaries_) {
151*288bf522SAndroid Build Coastguard Worker if (show_thread) {
152*288bf522SAndroid Build Coastguard Worker fprintf(fp, "%s,%d,%d,", s.thread->name.c_str(), s.thread->pid, s.thread->tid);
153*288bf522SAndroid Build Coastguard Worker }
154*288bf522SAndroid Build Coastguard Worker if (show_cpu) {
155*288bf522SAndroid Build Coastguard Worker fprintf(fp, "%d,", s.cpu);
156*288bf522SAndroid Build Coastguard Worker }
157*288bf522SAndroid Build Coastguard Worker fprintf(fp, "%s,%s,%s,%s\n", s.readable_count.c_str(), s.Name().c_str(), s.comment.c_str(),
158*288bf522SAndroid Build Coastguard Worker (s.auto_generated ? "(generated)," : ""));
159*288bf522SAndroid Build Coastguard Worker }
160*288bf522SAndroid Build Coastguard Worker }
161*288bf522SAndroid Build Coastguard Worker
ShowText(FILE * fp,bool show_thread,bool show_cpu)162*288bf522SAndroid Build Coastguard Worker void CounterSummaries::ShowText(FILE* fp, bool show_thread, bool show_cpu) {
163*288bf522SAndroid Build Coastguard Worker std::vector<std::string> titles;
164*288bf522SAndroid Build Coastguard Worker
165*288bf522SAndroid Build Coastguard Worker if (show_thread) {
166*288bf522SAndroid Build Coastguard Worker titles = {"thread_name", "pid", "tid"};
167*288bf522SAndroid Build Coastguard Worker }
168*288bf522SAndroid Build Coastguard Worker if (show_cpu) {
169*288bf522SAndroid Build Coastguard Worker titles.emplace_back("cpu");
170*288bf522SAndroid Build Coastguard Worker }
171*288bf522SAndroid Build Coastguard Worker titles.emplace_back("count");
172*288bf522SAndroid Build Coastguard Worker titles.emplace_back("event_name");
173*288bf522SAndroid Build Coastguard Worker titles.emplace_back(" # count / runtime");
174*288bf522SAndroid Build Coastguard Worker
175*288bf522SAndroid Build Coastguard Worker std::vector<size_t> width(titles.size(), 0);
176*288bf522SAndroid Build Coastguard Worker
177*288bf522SAndroid Build Coastguard Worker auto adjust_width = [](size_t& w, size_t size) { w = std::max(w, size); };
178*288bf522SAndroid Build Coastguard Worker
179*288bf522SAndroid Build Coastguard Worker // The last title is too long. Don't include it for width adjustment.
180*288bf522SAndroid Build Coastguard Worker for (size_t i = 0; i + 1 < titles.size(); i++) {
181*288bf522SAndroid Build Coastguard Worker adjust_width(width[i], titles[i].size());
182*288bf522SAndroid Build Coastguard Worker }
183*288bf522SAndroid Build Coastguard Worker
184*288bf522SAndroid Build Coastguard Worker for (auto& s : summaries_) {
185*288bf522SAndroid Build Coastguard Worker size_t i = 0;
186*288bf522SAndroid Build Coastguard Worker if (show_thread) {
187*288bf522SAndroid Build Coastguard Worker adjust_width(width[i++], s.thread->name.size());
188*288bf522SAndroid Build Coastguard Worker adjust_width(width[i++], std::to_string(s.thread->pid).size());
189*288bf522SAndroid Build Coastguard Worker adjust_width(width[i++], std::to_string(s.thread->tid).size());
190*288bf522SAndroid Build Coastguard Worker }
191*288bf522SAndroid Build Coastguard Worker if (show_cpu) {
192*288bf522SAndroid Build Coastguard Worker adjust_width(width[i++], std::to_string(s.cpu).size());
193*288bf522SAndroid Build Coastguard Worker }
194*288bf522SAndroid Build Coastguard Worker adjust_width(width[i++], s.readable_count.size());
195*288bf522SAndroid Build Coastguard Worker adjust_width(width[i++], s.Name().size());
196*288bf522SAndroid Build Coastguard Worker adjust_width(width[i++], s.comment.size());
197*288bf522SAndroid Build Coastguard Worker }
198*288bf522SAndroid Build Coastguard Worker
199*288bf522SAndroid Build Coastguard Worker fprintf(fp, "# ");
200*288bf522SAndroid Build Coastguard Worker for (size_t i = 0; i < titles.size(); i++) {
201*288bf522SAndroid Build Coastguard Worker if (titles[i] == "count") {
202*288bf522SAndroid Build Coastguard Worker fprintf(fp, "%*s", static_cast<int>(width[i]), titles[i].c_str());
203*288bf522SAndroid Build Coastguard Worker } else {
204*288bf522SAndroid Build Coastguard Worker fprintf(fp, "%-*s", static_cast<int>(width[i]), titles[i].c_str());
205*288bf522SAndroid Build Coastguard Worker }
206*288bf522SAndroid Build Coastguard Worker if (i + 1 < titles.size()) {
207*288bf522SAndroid Build Coastguard Worker fprintf(fp, " ");
208*288bf522SAndroid Build Coastguard Worker }
209*288bf522SAndroid Build Coastguard Worker }
210*288bf522SAndroid Build Coastguard Worker fprintf(fp, "\n");
211*288bf522SAndroid Build Coastguard Worker
212*288bf522SAndroid Build Coastguard Worker for (auto& s : summaries_) {
213*288bf522SAndroid Build Coastguard Worker size_t i = 0;
214*288bf522SAndroid Build Coastguard Worker if (show_thread) {
215*288bf522SAndroid Build Coastguard Worker fprintf(fp, " %-*s", static_cast<int>(width[i++]), s.thread->name.c_str());
216*288bf522SAndroid Build Coastguard Worker fprintf(fp, " %-*d", static_cast<int>(width[i++]), s.thread->pid);
217*288bf522SAndroid Build Coastguard Worker fprintf(fp, " %-*d", static_cast<int>(width[i++]), s.thread->tid);
218*288bf522SAndroid Build Coastguard Worker }
219*288bf522SAndroid Build Coastguard Worker if (show_cpu) {
220*288bf522SAndroid Build Coastguard Worker fprintf(fp, " %-*d", static_cast<int>(width[i++]), s.cpu);
221*288bf522SAndroid Build Coastguard Worker }
222*288bf522SAndroid Build Coastguard Worker fprintf(fp, " %*s %-*s # %-*s%s\n", static_cast<int>(width[i]), s.readable_count.c_str(),
223*288bf522SAndroid Build Coastguard Worker static_cast<int>(width[i + 1]), s.Name().c_str(), static_cast<int>(width[i + 2]),
224*288bf522SAndroid Build Coastguard Worker s.comment.c_str(), (s.auto_generated ? " (generated)" : ""));
225*288bf522SAndroid Build Coastguard Worker }
226*288bf522SAndroid Build Coastguard Worker }
227*288bf522SAndroid Build Coastguard Worker
GetCommentForSummary(const CounterSummary & s,double duration_in_sec)228*288bf522SAndroid Build Coastguard Worker std::string CounterSummaries::GetCommentForSummary(const CounterSummary& s,
229*288bf522SAndroid Build Coastguard Worker double duration_in_sec) {
230*288bf522SAndroid Build Coastguard Worker char sap_mid;
231*288bf522SAndroid Build Coastguard Worker if (csv_) {
232*288bf522SAndroid Build Coastguard Worker sap_mid = ',';
233*288bf522SAndroid Build Coastguard Worker } else {
234*288bf522SAndroid Build Coastguard Worker sap_mid = ' ';
235*288bf522SAndroid Build Coastguard Worker }
236*288bf522SAndroid Build Coastguard Worker if (s.type_name == "task-clock") {
237*288bf522SAndroid Build Coastguard Worker double run_sec = s.count / 1e9;
238*288bf522SAndroid Build Coastguard Worker double used_cpus = run_sec / duration_in_sec;
239*288bf522SAndroid Build Coastguard Worker return android::base::StringPrintf("%f%ccpus used", used_cpus, sap_mid);
240*288bf522SAndroid Build Coastguard Worker }
241*288bf522SAndroid Build Coastguard Worker if (s.type_name == "cpu-clock") {
242*288bf522SAndroid Build Coastguard Worker return "";
243*288bf522SAndroid Build Coastguard Worker }
244*288bf522SAndroid Build Coastguard Worker if (s.type_name == "cpu-cycles") {
245*288bf522SAndroid Build Coastguard Worker if (s.runtime_in_ns == 0) {
246*288bf522SAndroid Build Coastguard Worker return "";
247*288bf522SAndroid Build Coastguard Worker }
248*288bf522SAndroid Build Coastguard Worker double ghz = static_cast<double>(s.count) / s.runtime_in_ns;
249*288bf522SAndroid Build Coastguard Worker return android::base::StringPrintf("%f%cGHz", ghz, sap_mid);
250*288bf522SAndroid Build Coastguard Worker }
251*288bf522SAndroid Build Coastguard Worker if (s.type_name == "instructions" && s.count != 0) {
252*288bf522SAndroid Build Coastguard Worker const CounterSummary* other = FindSummary("cpu-cycles", s.modifier, s.thread, s.cpu);
253*288bf522SAndroid Build Coastguard Worker if (other != nullptr && other->IsMonitoredAtTheSameTime(s)) {
254*288bf522SAndroid Build Coastguard Worker double cpi = static_cast<double>(other->count) / s.count;
255*288bf522SAndroid Build Coastguard Worker return android::base::StringPrintf("%f%ccycles per instruction", cpi, sap_mid);
256*288bf522SAndroid Build Coastguard Worker }
257*288bf522SAndroid Build Coastguard Worker }
258*288bf522SAndroid Build Coastguard Worker std::string rate_comment = GetRateComment(s, sap_mid);
259*288bf522SAndroid Build Coastguard Worker if (!rate_comment.empty()) {
260*288bf522SAndroid Build Coastguard Worker return rate_comment;
261*288bf522SAndroid Build Coastguard Worker }
262*288bf522SAndroid Build Coastguard Worker if (s.runtime_in_ns == 0) {
263*288bf522SAndroid Build Coastguard Worker return "";
264*288bf522SAndroid Build Coastguard Worker }
265*288bf522SAndroid Build Coastguard Worker double runtime_in_sec = static_cast<double>(s.runtime_in_ns) / 1e9;
266*288bf522SAndroid Build Coastguard Worker double rate = s.count / runtime_in_sec;
267*288bf522SAndroid Build Coastguard Worker if (rate >= 1e9 - 1e5) {
268*288bf522SAndroid Build Coastguard Worker return android::base::StringPrintf("%.3f%cG/sec", rate / 1e9, sap_mid);
269*288bf522SAndroid Build Coastguard Worker }
270*288bf522SAndroid Build Coastguard Worker if (rate >= 1e6 - 1e2) {
271*288bf522SAndroid Build Coastguard Worker return android::base::StringPrintf("%.3f%cM/sec", rate / 1e6, sap_mid);
272*288bf522SAndroid Build Coastguard Worker }
273*288bf522SAndroid Build Coastguard Worker if (rate >= 1e3) {
274*288bf522SAndroid Build Coastguard Worker return android::base::StringPrintf("%.3f%cK/sec", rate / 1e3, sap_mid);
275*288bf522SAndroid Build Coastguard Worker }
276*288bf522SAndroid Build Coastguard Worker return android::base::StringPrintf("%.3f%c/sec", rate, sap_mid);
277*288bf522SAndroid Build Coastguard Worker }
278*288bf522SAndroid Build Coastguard Worker
GetRateComment(const CounterSummary & s,char sep)279*288bf522SAndroid Build Coastguard Worker std::string CounterSummaries::GetRateComment(const CounterSummary& s, char sep) {
280*288bf522SAndroid Build Coastguard Worker std::string_view miss_event_name = s.type_name;
281*288bf522SAndroid Build Coastguard Worker std::string event_name;
282*288bf522SAndroid Build Coastguard Worker std::string rate_desc;
283*288bf522SAndroid Build Coastguard Worker if (auto it = COMMON_EVENT_RATE_MAP.find(miss_event_name); it != COMMON_EVENT_RATE_MAP.end()) {
284*288bf522SAndroid Build Coastguard Worker event_name = it->second.first;
285*288bf522SAndroid Build Coastguard Worker rate_desc = it->second.second;
286*288bf522SAndroid Build Coastguard Worker }
287*288bf522SAndroid Build Coastguard Worker if (event_name.empty() && (GetTargetArch() == ARCH_ARM || GetTargetArch() == ARCH_ARM64)) {
288*288bf522SAndroid Build Coastguard Worker if (auto it = ARM_EVENT_RATE_MAP.find(miss_event_name); it != ARM_EVENT_RATE_MAP.end()) {
289*288bf522SAndroid Build Coastguard Worker event_name = it->second.first;
290*288bf522SAndroid Build Coastguard Worker rate_desc = it->second.second;
291*288bf522SAndroid Build Coastguard Worker }
292*288bf522SAndroid Build Coastguard Worker }
293*288bf522SAndroid Build Coastguard Worker if (event_name.empty() && android::base::ConsumeSuffix(&miss_event_name, "-misses")) {
294*288bf522SAndroid Build Coastguard Worker event_name = std::string(miss_event_name) + "s";
295*288bf522SAndroid Build Coastguard Worker rate_desc = "miss rate";
296*288bf522SAndroid Build Coastguard Worker }
297*288bf522SAndroid Build Coastguard Worker if (!event_name.empty()) {
298*288bf522SAndroid Build Coastguard Worker const CounterSummary* other = FindSummary(event_name, s.modifier, s.thread, s.cpu);
299*288bf522SAndroid Build Coastguard Worker if (other != nullptr && other->IsMonitoredAtTheSameTime(s) && other->count != 0) {
300*288bf522SAndroid Build Coastguard Worker double miss_rate = static_cast<double>(s.count) / other->count;
301*288bf522SAndroid Build Coastguard Worker return android::base::StringPrintf("%f%%%c%s", miss_rate * 100, sep, rate_desc.c_str());
302*288bf522SAndroid Build Coastguard Worker }
303*288bf522SAndroid Build Coastguard Worker }
304*288bf522SAndroid Build Coastguard Worker return "";
305*288bf522SAndroid Build Coastguard Worker }
306*288bf522SAndroid Build Coastguard Worker
307*288bf522SAndroid Build Coastguard Worker namespace {
308*288bf522SAndroid Build Coastguard Worker
309*288bf522SAndroid Build Coastguard Worker // devfreq may use performance counters to calculate memory latency (as in
310*288bf522SAndroid Build Coastguard Worker // drivers/devfreq/arm-memlat-mon.c). Hopefully we can get more available counters by asking devfreq
311*288bf522SAndroid Build Coastguard Worker // to not use the memory latency governor temporarily.
312*288bf522SAndroid Build Coastguard Worker class DevfreqCounters {
313*288bf522SAndroid Build Coastguard Worker public:
Use()314*288bf522SAndroid Build Coastguard Worker bool Use() {
315*288bf522SAndroid Build Coastguard Worker if (!IsRoot()) {
316*288bf522SAndroid Build Coastguard Worker LOG(ERROR) << "--use-devfreq-counters needs root permission to set devfreq governors";
317*288bf522SAndroid Build Coastguard Worker return false;
318*288bf522SAndroid Build Coastguard Worker }
319*288bf522SAndroid Build Coastguard Worker std::string devfreq_dir = "/sys/class/devfreq/";
320*288bf522SAndroid Build Coastguard Worker for (auto& name : GetSubDirs(devfreq_dir)) {
321*288bf522SAndroid Build Coastguard Worker std::string governor_path = devfreq_dir + name + "/governor";
322*288bf522SAndroid Build Coastguard Worker if (IsRegularFile(governor_path)) {
323*288bf522SAndroid Build Coastguard Worker std::string governor;
324*288bf522SAndroid Build Coastguard Worker if (!android::base::ReadFileToString(governor_path, &governor)) {
325*288bf522SAndroid Build Coastguard Worker LOG(ERROR) << "failed to read " << governor_path;
326*288bf522SAndroid Build Coastguard Worker return false;
327*288bf522SAndroid Build Coastguard Worker }
328*288bf522SAndroid Build Coastguard Worker governor = android::base::Trim(governor);
329*288bf522SAndroid Build Coastguard Worker if (governor == "mem_latency") {
330*288bf522SAndroid Build Coastguard Worker if (!android::base::WriteStringToFile("performance", governor_path)) {
331*288bf522SAndroid Build Coastguard Worker PLOG(ERROR) << "failed to write " << governor_path;
332*288bf522SAndroid Build Coastguard Worker return false;
333*288bf522SAndroid Build Coastguard Worker }
334*288bf522SAndroid Build Coastguard Worker mem_latency_governor_paths_.emplace_back(std::move(governor_path));
335*288bf522SAndroid Build Coastguard Worker }
336*288bf522SAndroid Build Coastguard Worker }
337*288bf522SAndroid Build Coastguard Worker }
338*288bf522SAndroid Build Coastguard Worker return true;
339*288bf522SAndroid Build Coastguard Worker }
340*288bf522SAndroid Build Coastguard Worker
~DevfreqCounters()341*288bf522SAndroid Build Coastguard Worker ~DevfreqCounters() {
342*288bf522SAndroid Build Coastguard Worker for (auto& path : mem_latency_governor_paths_) {
343*288bf522SAndroid Build Coastguard Worker android::base::WriteStringToFile("mem_latency", path);
344*288bf522SAndroid Build Coastguard Worker }
345*288bf522SAndroid Build Coastguard Worker }
346*288bf522SAndroid Build Coastguard Worker
347*288bf522SAndroid Build Coastguard Worker private:
348*288bf522SAndroid Build Coastguard Worker std::vector<std::string> mem_latency_governor_paths_;
349*288bf522SAndroid Build Coastguard Worker };
350*288bf522SAndroid Build Coastguard Worker
351*288bf522SAndroid Build Coastguard Worker class StatCommand : public Command {
352*288bf522SAndroid Build Coastguard Worker public:
StatCommand()353*288bf522SAndroid Build Coastguard Worker StatCommand()
354*288bf522SAndroid Build Coastguard Worker : Command(
355*288bf522SAndroid Build Coastguard Worker "stat", "gather performance counter information",
356*288bf522SAndroid Build Coastguard Worker // clang-format off
357*288bf522SAndroid Build Coastguard Worker "Usage: simpleperf stat [options] [command [command-args]]\n"
358*288bf522SAndroid Build Coastguard Worker " Gather performance counter information of running [command].\n"
359*288bf522SAndroid Build Coastguard Worker " And -a/-p/-t option can be used to change target of counter information.\n"
360*288bf522SAndroid Build Coastguard Worker "-a Collect system-wide information.\n"
361*288bf522SAndroid Build Coastguard Worker #if defined(__ANDROID__)
362*288bf522SAndroid Build Coastguard Worker "--app package_name Profile the process of an Android application.\n"
363*288bf522SAndroid Build Coastguard Worker " On non-rooted devices, the app must be debuggable,\n"
364*288bf522SAndroid Build Coastguard Worker " because we use run-as to switch to the app's context.\n"
365*288bf522SAndroid Build Coastguard Worker #endif
366*288bf522SAndroid Build Coastguard Worker "--cpu cpu_item1,cpu_item2,... Monitor events on selected cpus. cpu_item can be a number like\n"
367*288bf522SAndroid Build Coastguard Worker " 1, or a range like 0-3. A --cpu option affects all event types\n"
368*288bf522SAndroid Build Coastguard Worker " following it until meeting another --cpu option.\n"
369*288bf522SAndroid Build Coastguard Worker "--csv Write report in comma separate form.\n"
370*288bf522SAndroid Build Coastguard Worker "--duration time_in_sec Monitor for time_in_sec seconds instead of running\n"
371*288bf522SAndroid Build Coastguard Worker " [command]. Here time_in_sec may be any positive\n"
372*288bf522SAndroid Build Coastguard Worker " floating point number.\n"
373*288bf522SAndroid Build Coastguard Worker "--interval time_in_ms Print stat for every time_in_ms milliseconds.\n"
374*288bf522SAndroid Build Coastguard Worker " Here time_in_ms may be any positive floating point\n"
375*288bf522SAndroid Build Coastguard Worker " number. Simpleperf prints total values from the\n"
376*288bf522SAndroid Build Coastguard Worker " starting point. But this can be changed by\n"
377*288bf522SAndroid Build Coastguard Worker " --interval-only-values.\n"
378*288bf522SAndroid Build Coastguard Worker "--interval-only-values Print numbers of events happened in each interval.\n"
379*288bf522SAndroid Build Coastguard Worker "-e event1[:modifier1],event2[:modifier2],...\n"
380*288bf522SAndroid Build Coastguard Worker " Select a list of events to count. An event can be:\n"
381*288bf522SAndroid Build Coastguard Worker " 1) an event name listed in `simpleperf list`;\n"
382*288bf522SAndroid Build Coastguard Worker " 2) a raw PMU event in rN format. N is a hex number.\n"
383*288bf522SAndroid Build Coastguard Worker " For example, r1b selects event number 0x1b.\n"
384*288bf522SAndroid Build Coastguard Worker " Modifiers can be added to define how the event should be\n"
385*288bf522SAndroid Build Coastguard Worker " monitored. Possible modifiers are:\n"
386*288bf522SAndroid Build Coastguard Worker " u - monitor user space events only\n"
387*288bf522SAndroid Build Coastguard Worker " k - monitor kernel space events only\n"
388*288bf522SAndroid Build Coastguard Worker "--group event1[:modifier],event2[:modifier2],...\n"
389*288bf522SAndroid Build Coastguard Worker " Similar to -e option. But events specified in the same --group\n"
390*288bf522SAndroid Build Coastguard Worker " option are monitored as a group, and scheduled in and out at the\n"
391*288bf522SAndroid Build Coastguard Worker " same time.\n"
392*288bf522SAndroid Build Coastguard Worker "--kprobe kprobe_event1,kprobe_event2,...\n"
393*288bf522SAndroid Build Coastguard Worker " Add kprobe events during stating. The kprobe_event format is in\n"
394*288bf522SAndroid Build Coastguard Worker " Documentation/trace/kprobetrace.rst in the kernel. Examples:\n"
395*288bf522SAndroid Build Coastguard Worker " 'p:myprobe do_sys_openat2 $arg2:string' - add event kprobes:myprobe\n"
396*288bf522SAndroid Build Coastguard Worker " 'r:myretprobe do_sys_openat2 $retval:s64' - add event kprobes:myretprobe\n"
397*288bf522SAndroid Build Coastguard Worker "--no-inherit Don't stat created child threads/processes.\n"
398*288bf522SAndroid Build Coastguard Worker "-o output_filename Write report to output_filename instead of standard output.\n"
399*288bf522SAndroid Build Coastguard Worker "--per-core Print counters for each cpu core.\n"
400*288bf522SAndroid Build Coastguard Worker "--per-thread Print counters for each thread.\n"
401*288bf522SAndroid Build Coastguard Worker "-p pid_or_process_name_regex1,pid_or_process_name_regex2,...\n"
402*288bf522SAndroid Build Coastguard Worker " Stat events on existing processes. Processes are searched either by pid\n"
403*288bf522SAndroid Build Coastguard Worker " or process name regex. Mutually exclusive with -a.\n"
404*288bf522SAndroid Build Coastguard Worker "-t tid1,tid2,... Stat events on existing threads. Mutually exclusive with -a.\n"
405*288bf522SAndroid Build Coastguard Worker "--tp-filter filter_string Set filter_string for the previous tracepoint event.\n"
406*288bf522SAndroid Build Coastguard Worker " Format is in Documentation/trace/events.rst in the kernel.\n"
407*288bf522SAndroid Build Coastguard Worker " An example: 'prev_comm != \"simpleperf\" && (prev_pid > 1)'.\n"
408*288bf522SAndroid Build Coastguard Worker "--print-hw-counter Test and print CPU PMU hardware counters available on the device.\n"
409*288bf522SAndroid Build Coastguard Worker "--sort key1,key2,... Select keys used to sort the report, used when --per-thread\n"
410*288bf522SAndroid Build Coastguard Worker " or --per-core appears. The appearance order of keys decides\n"
411*288bf522SAndroid Build Coastguard Worker " the order of keys used to sort the report.\n"
412*288bf522SAndroid Build Coastguard Worker " Possible keys include:\n"
413*288bf522SAndroid Build Coastguard Worker " count -- event count for each entry\n"
414*288bf522SAndroid Build Coastguard Worker " count_per_thread -- event count for a thread on all cpus\n"
415*288bf522SAndroid Build Coastguard Worker " cpu -- cpu id\n"
416*288bf522SAndroid Build Coastguard Worker " pid -- process id\n"
417*288bf522SAndroid Build Coastguard Worker " tid -- thread id\n"
418*288bf522SAndroid Build Coastguard Worker " comm -- thread name\n"
419*288bf522SAndroid Build Coastguard Worker " The default sort keys are:\n"
420*288bf522SAndroid Build Coastguard Worker " count_per_thread,tid,cpu,count\n"
421*288bf522SAndroid Build Coastguard Worker #if defined(__ANDROID__)
422*288bf522SAndroid Build Coastguard Worker "--use-devfreq-counters On devices with Qualcomm SOCs, some hardware counters may be used\n"
423*288bf522SAndroid Build Coastguard Worker " to monitor memory latency (in drivers/devfreq/arm-memlat-mon.c),\n"
424*288bf522SAndroid Build Coastguard Worker " making fewer counters available to users. This option asks devfreq\n"
425*288bf522SAndroid Build Coastguard Worker " to temporarily release counters by replacing memory-latency governor\n"
426*288bf522SAndroid Build Coastguard Worker " with performance governor. It affects memory latency during profiling,\n"
427*288bf522SAndroid Build Coastguard Worker " and may cause wedged power if simpleperf is killed in between.\n"
428*288bf522SAndroid Build Coastguard Worker #endif
429*288bf522SAndroid Build Coastguard Worker "--verbose Show result in verbose mode.\n"
430*288bf522SAndroid Build Coastguard Worker #if 0
431*288bf522SAndroid Build Coastguard Worker // Below options are only used internally and shouldn't be visible to the public.
432*288bf522SAndroid Build Coastguard Worker "--in-app We are already running in the app's context.\n"
433*288bf522SAndroid Build Coastguard Worker "--tracepoint-events file_name Read tracepoint events from [file_name] instead of tracefs.\n"
434*288bf522SAndroid Build Coastguard Worker "--out-fd <fd> Write output to a file descriptor.\n"
435*288bf522SAndroid Build Coastguard Worker "--stop-signal-fd <fd> Stop stating when fd is readable.\n"
436*288bf522SAndroid Build Coastguard Worker #endif
437*288bf522SAndroid Build Coastguard Worker // clang-format on
438*288bf522SAndroid Build Coastguard Worker ),
439*288bf522SAndroid Build Coastguard Worker verbose_mode_(false),
440*288bf522SAndroid Build Coastguard Worker system_wide_collection_(false),
441*288bf522SAndroid Build Coastguard Worker child_inherit_(true),
442*288bf522SAndroid Build Coastguard Worker duration_in_sec_(0),
443*288bf522SAndroid Build Coastguard Worker interval_in_ms_(0),
444*288bf522SAndroid Build Coastguard Worker interval_only_values_(false),
445*288bf522SAndroid Build Coastguard Worker event_selection_set_(true),
446*288bf522SAndroid Build Coastguard Worker csv_(false),
447*288bf522SAndroid Build Coastguard Worker in_app_context_(false) {
448*288bf522SAndroid Build Coastguard Worker // Die if parent exits.
449*288bf522SAndroid Build Coastguard Worker prctl(PR_SET_PDEATHSIG, SIGHUP, 0, 0, 0);
450*288bf522SAndroid Build Coastguard Worker // Set default sort keys. Full key list is in BuildSummaryComparator().
451*288bf522SAndroid Build Coastguard Worker sort_keys_ = {"count_per_thread", "tid", "cpu", "count"};
452*288bf522SAndroid Build Coastguard Worker }
453*288bf522SAndroid Build Coastguard Worker
454*288bf522SAndroid Build Coastguard Worker bool Run(const std::vector<std::string>& args);
455*288bf522SAndroid Build Coastguard Worker
456*288bf522SAndroid Build Coastguard Worker private:
457*288bf522SAndroid Build Coastguard Worker bool ParseOptions(const std::vector<std::string>& args, std::vector<std::string>* non_option_args,
458*288bf522SAndroid Build Coastguard Worker ProbeEvents& probe_events);
459*288bf522SAndroid Build Coastguard Worker void PrintHardwareCounters();
460*288bf522SAndroid Build Coastguard Worker bool AddDefaultMeasuredEventTypes();
461*288bf522SAndroid Build Coastguard Worker void SetEventSelectionFlags();
462*288bf522SAndroid Build Coastguard Worker void MonitorEachThread();
463*288bf522SAndroid Build Coastguard Worker void AdjustToIntervalOnlyValues(std::vector<CountersInfo>& counters);
464*288bf522SAndroid Build Coastguard Worker bool ShowCounters(const std::vector<CountersInfo>& counters, double duration_in_sec, FILE* fp);
465*288bf522SAndroid Build Coastguard Worker void CheckHardwareCounterMultiplexing();
466*288bf522SAndroid Build Coastguard Worker void PrintWarningForInaccurateEvents();
467*288bf522SAndroid Build Coastguard Worker
468*288bf522SAndroid Build Coastguard Worker bool verbose_mode_;
469*288bf522SAndroid Build Coastguard Worker bool system_wide_collection_;
470*288bf522SAndroid Build Coastguard Worker bool child_inherit_;
471*288bf522SAndroid Build Coastguard Worker double duration_in_sec_;
472*288bf522SAndroid Build Coastguard Worker double interval_in_ms_;
473*288bf522SAndroid Build Coastguard Worker bool interval_only_values_;
474*288bf522SAndroid Build Coastguard Worker std::vector<std::vector<CounterSum>> last_sum_values_;
475*288bf522SAndroid Build Coastguard Worker EventSelectionSet event_selection_set_;
476*288bf522SAndroid Build Coastguard Worker std::string output_filename_;
477*288bf522SAndroid Build Coastguard Worker android::base::unique_fd out_fd_;
478*288bf522SAndroid Build Coastguard Worker bool csv_;
479*288bf522SAndroid Build Coastguard Worker std::string app_package_name_;
480*288bf522SAndroid Build Coastguard Worker bool in_app_context_;
481*288bf522SAndroid Build Coastguard Worker android::base::unique_fd stop_signal_fd_;
482*288bf522SAndroid Build Coastguard Worker bool use_devfreq_counters_ = false;
483*288bf522SAndroid Build Coastguard Worker
484*288bf522SAndroid Build Coastguard Worker bool report_per_core_ = false;
485*288bf522SAndroid Build Coastguard Worker bool report_per_thread_ = false;
486*288bf522SAndroid Build Coastguard Worker // used to report event count for each thread
487*288bf522SAndroid Build Coastguard Worker std::unordered_map<pid_t, ThreadInfo> thread_info_;
488*288bf522SAndroid Build Coastguard Worker // used to sort report
489*288bf522SAndroid Build Coastguard Worker std::vector<std::string> sort_keys_;
490*288bf522SAndroid Build Coastguard Worker std::optional<SummaryComparator> summary_comparator_;
491*288bf522SAndroid Build Coastguard Worker bool print_hw_counter_ = false;
492*288bf522SAndroid Build Coastguard Worker };
493*288bf522SAndroid Build Coastguard Worker
Run(const std::vector<std::string> & args)494*288bf522SAndroid Build Coastguard Worker bool StatCommand::Run(const std::vector<std::string>& args) {
495*288bf522SAndroid Build Coastguard Worker if (!CheckPerfEventLimit()) {
496*288bf522SAndroid Build Coastguard Worker return false;
497*288bf522SAndroid Build Coastguard Worker }
498*288bf522SAndroid Build Coastguard Worker AllowMoreOpenedFiles();
499*288bf522SAndroid Build Coastguard Worker
500*288bf522SAndroid Build Coastguard Worker // 1. Parse options, and use default measured event types if not given.
501*288bf522SAndroid Build Coastguard Worker std::vector<std::string> workload_args;
502*288bf522SAndroid Build Coastguard Worker ProbeEvents probe_events(event_selection_set_);
503*288bf522SAndroid Build Coastguard Worker if (!ParseOptions(args, &workload_args, probe_events)) {
504*288bf522SAndroid Build Coastguard Worker return false;
505*288bf522SAndroid Build Coastguard Worker }
506*288bf522SAndroid Build Coastguard Worker if (print_hw_counter_) {
507*288bf522SAndroid Build Coastguard Worker PrintHardwareCounters();
508*288bf522SAndroid Build Coastguard Worker return true;
509*288bf522SAndroid Build Coastguard Worker }
510*288bf522SAndroid Build Coastguard Worker if (!app_package_name_.empty() && !in_app_context_) {
511*288bf522SAndroid Build Coastguard Worker if (!IsRoot()) {
512*288bf522SAndroid Build Coastguard Worker return RunInAppContext(app_package_name_, "stat", args, workload_args.size(),
513*288bf522SAndroid Build Coastguard Worker output_filename_, !event_selection_set_.GetTracepointEvents().empty());
514*288bf522SAndroid Build Coastguard Worker }
515*288bf522SAndroid Build Coastguard Worker }
516*288bf522SAndroid Build Coastguard Worker DevfreqCounters devfreq_counters;
517*288bf522SAndroid Build Coastguard Worker if (use_devfreq_counters_) {
518*288bf522SAndroid Build Coastguard Worker if (!devfreq_counters.Use()) {
519*288bf522SAndroid Build Coastguard Worker return false;
520*288bf522SAndroid Build Coastguard Worker }
521*288bf522SAndroid Build Coastguard Worker }
522*288bf522SAndroid Build Coastguard Worker if (event_selection_set_.empty()) {
523*288bf522SAndroid Build Coastguard Worker if (!AddDefaultMeasuredEventTypes()) {
524*288bf522SAndroid Build Coastguard Worker return false;
525*288bf522SAndroid Build Coastguard Worker }
526*288bf522SAndroid Build Coastguard Worker }
527*288bf522SAndroid Build Coastguard Worker SetEventSelectionFlags();
528*288bf522SAndroid Build Coastguard Worker
529*288bf522SAndroid Build Coastguard Worker // 2. Create workload.
530*288bf522SAndroid Build Coastguard Worker std::unique_ptr<Workload> workload;
531*288bf522SAndroid Build Coastguard Worker if (!workload_args.empty()) {
532*288bf522SAndroid Build Coastguard Worker workload = Workload::CreateWorkload(workload_args);
533*288bf522SAndroid Build Coastguard Worker if (workload == nullptr) {
534*288bf522SAndroid Build Coastguard Worker return false;
535*288bf522SAndroid Build Coastguard Worker }
536*288bf522SAndroid Build Coastguard Worker }
537*288bf522SAndroid Build Coastguard Worker bool need_to_check_targets = false;
538*288bf522SAndroid Build Coastguard Worker if (system_wide_collection_) {
539*288bf522SAndroid Build Coastguard Worker if (report_per_thread_) {
540*288bf522SAndroid Build Coastguard Worker event_selection_set_.AddMonitoredProcesses(GetAllProcesses());
541*288bf522SAndroid Build Coastguard Worker } else {
542*288bf522SAndroid Build Coastguard Worker event_selection_set_.AddMonitoredThreads({-1});
543*288bf522SAndroid Build Coastguard Worker }
544*288bf522SAndroid Build Coastguard Worker } else if (!event_selection_set_.HasMonitoredTarget()) {
545*288bf522SAndroid Build Coastguard Worker if (workload != nullptr) {
546*288bf522SAndroid Build Coastguard Worker event_selection_set_.AddMonitoredProcesses({workload->GetPid()});
547*288bf522SAndroid Build Coastguard Worker event_selection_set_.SetEnableCondition(false, true);
548*288bf522SAndroid Build Coastguard Worker } else if (!app_package_name_.empty()) {
549*288bf522SAndroid Build Coastguard Worker std::set<pid_t> pids = WaitForAppProcesses(app_package_name_);
550*288bf522SAndroid Build Coastguard Worker event_selection_set_.AddMonitoredProcesses(pids);
551*288bf522SAndroid Build Coastguard Worker } else {
552*288bf522SAndroid Build Coastguard Worker LOG(ERROR) << "No threads to monitor. Try `simpleperf help stat` for help\n";
553*288bf522SAndroid Build Coastguard Worker return false;
554*288bf522SAndroid Build Coastguard Worker }
555*288bf522SAndroid Build Coastguard Worker } else {
556*288bf522SAndroid Build Coastguard Worker need_to_check_targets = true;
557*288bf522SAndroid Build Coastguard Worker }
558*288bf522SAndroid Build Coastguard Worker
559*288bf522SAndroid Build Coastguard Worker if (report_per_thread_) {
560*288bf522SAndroid Build Coastguard Worker MonitorEachThread();
561*288bf522SAndroid Build Coastguard Worker }
562*288bf522SAndroid Build Coastguard Worker
563*288bf522SAndroid Build Coastguard Worker // 3. Open perf_event_files and output file if defined.
564*288bf522SAndroid Build Coastguard Worker if (!event_selection_set_.OpenEventFiles()) {
565*288bf522SAndroid Build Coastguard Worker return false;
566*288bf522SAndroid Build Coastguard Worker }
567*288bf522SAndroid Build Coastguard Worker std::unique_ptr<FILE, decltype(&fclose)> fp_holder(nullptr, fclose);
568*288bf522SAndroid Build Coastguard Worker if (!output_filename_.empty()) {
569*288bf522SAndroid Build Coastguard Worker fp_holder.reset(fopen(output_filename_.c_str(), "we"));
570*288bf522SAndroid Build Coastguard Worker if (fp_holder == nullptr) {
571*288bf522SAndroid Build Coastguard Worker PLOG(ERROR) << "failed to open " << output_filename_;
572*288bf522SAndroid Build Coastguard Worker return false;
573*288bf522SAndroid Build Coastguard Worker }
574*288bf522SAndroid Build Coastguard Worker } else if (out_fd_ != -1) {
575*288bf522SAndroid Build Coastguard Worker fp_holder.reset(fdopen(out_fd_.release(), "we"));
576*288bf522SAndroid Build Coastguard Worker if (fp_holder == nullptr) {
577*288bf522SAndroid Build Coastguard Worker PLOG(ERROR) << "failed to write output.";
578*288bf522SAndroid Build Coastguard Worker return false;
579*288bf522SAndroid Build Coastguard Worker }
580*288bf522SAndroid Build Coastguard Worker }
581*288bf522SAndroid Build Coastguard Worker FILE* fp = fp_holder ? fp_holder.get() : stdout;
582*288bf522SAndroid Build Coastguard Worker
583*288bf522SAndroid Build Coastguard Worker // 4. Add signal/periodic Events.
584*288bf522SAndroid Build Coastguard Worker IOEventLoop* loop = event_selection_set_.GetIOEventLoop();
585*288bf522SAndroid Build Coastguard Worker std::chrono::time_point<std::chrono::steady_clock> start_time;
586*288bf522SAndroid Build Coastguard Worker std::vector<CountersInfo> counters;
587*288bf522SAndroid Build Coastguard Worker if (need_to_check_targets && !event_selection_set_.StopWhenNoMoreTargets()) {
588*288bf522SAndroid Build Coastguard Worker return false;
589*288bf522SAndroid Build Coastguard Worker }
590*288bf522SAndroid Build Coastguard Worker auto exit_loop_callback = [loop]() { return loop->ExitLoop(); };
591*288bf522SAndroid Build Coastguard Worker if (!loop->AddSignalEvents({SIGCHLD, SIGINT, SIGTERM, SIGHUP}, exit_loop_callback)) {
592*288bf522SAndroid Build Coastguard Worker return false;
593*288bf522SAndroid Build Coastguard Worker }
594*288bf522SAndroid Build Coastguard Worker if (stop_signal_fd_ != -1) {
595*288bf522SAndroid Build Coastguard Worker if (!loop->AddReadEvent(stop_signal_fd_, exit_loop_callback)) {
596*288bf522SAndroid Build Coastguard Worker return false;
597*288bf522SAndroid Build Coastguard Worker }
598*288bf522SAndroid Build Coastguard Worker }
599*288bf522SAndroid Build Coastguard Worker if (duration_in_sec_ != 0) {
600*288bf522SAndroid Build Coastguard Worker if (!loop->AddPeriodicEvent(SecondToTimeval(duration_in_sec_), exit_loop_callback)) {
601*288bf522SAndroid Build Coastguard Worker return false;
602*288bf522SAndroid Build Coastguard Worker }
603*288bf522SAndroid Build Coastguard Worker }
604*288bf522SAndroid Build Coastguard Worker auto print_counters = [&]() {
605*288bf522SAndroid Build Coastguard Worker auto end_time = std::chrono::steady_clock::now();
606*288bf522SAndroid Build Coastguard Worker if (!event_selection_set_.ReadCounters(&counters)) {
607*288bf522SAndroid Build Coastguard Worker return false;
608*288bf522SAndroid Build Coastguard Worker }
609*288bf522SAndroid Build Coastguard Worker double duration_in_sec =
610*288bf522SAndroid Build Coastguard Worker std::chrono::duration_cast<std::chrono::duration<double>>(end_time - start_time).count();
611*288bf522SAndroid Build Coastguard Worker if (interval_only_values_) {
612*288bf522SAndroid Build Coastguard Worker AdjustToIntervalOnlyValues(counters);
613*288bf522SAndroid Build Coastguard Worker }
614*288bf522SAndroid Build Coastguard Worker if (!ShowCounters(counters, duration_in_sec, fp)) {
615*288bf522SAndroid Build Coastguard Worker return false;
616*288bf522SAndroid Build Coastguard Worker }
617*288bf522SAndroid Build Coastguard Worker return true;
618*288bf522SAndroid Build Coastguard Worker };
619*288bf522SAndroid Build Coastguard Worker
620*288bf522SAndroid Build Coastguard Worker if (interval_in_ms_ != 0) {
621*288bf522SAndroid Build Coastguard Worker if (!loop->AddPeriodicEvent(SecondToTimeval(interval_in_ms_ / 1000.0), print_counters)) {
622*288bf522SAndroid Build Coastguard Worker return false;
623*288bf522SAndroid Build Coastguard Worker }
624*288bf522SAndroid Build Coastguard Worker }
625*288bf522SAndroid Build Coastguard Worker
626*288bf522SAndroid Build Coastguard Worker // 5. Count events while workload running.
627*288bf522SAndroid Build Coastguard Worker start_time = std::chrono::steady_clock::now();
628*288bf522SAndroid Build Coastguard Worker if (workload != nullptr && !workload->Start()) {
629*288bf522SAndroid Build Coastguard Worker return false;
630*288bf522SAndroid Build Coastguard Worker }
631*288bf522SAndroid Build Coastguard Worker if (!loop->RunLoop()) {
632*288bf522SAndroid Build Coastguard Worker return false;
633*288bf522SAndroid Build Coastguard Worker }
634*288bf522SAndroid Build Coastguard Worker
635*288bf522SAndroid Build Coastguard Worker // 6. Read and print counters.
636*288bf522SAndroid Build Coastguard Worker if (interval_in_ms_ == 0) {
637*288bf522SAndroid Build Coastguard Worker if (!print_counters()) {
638*288bf522SAndroid Build Coastguard Worker return false;
639*288bf522SAndroid Build Coastguard Worker }
640*288bf522SAndroid Build Coastguard Worker }
641*288bf522SAndroid Build Coastguard Worker
642*288bf522SAndroid Build Coastguard Worker // 7. Print warnings when needed.
643*288bf522SAndroid Build Coastguard Worker event_selection_set_.CloseEventFiles();
644*288bf522SAndroid Build Coastguard Worker CheckHardwareCounterMultiplexing();
645*288bf522SAndroid Build Coastguard Worker PrintWarningForInaccurateEvents();
646*288bf522SAndroid Build Coastguard Worker
647*288bf522SAndroid Build Coastguard Worker return true;
648*288bf522SAndroid Build Coastguard Worker }
649*288bf522SAndroid Build Coastguard Worker
ParseOptions(const std::vector<std::string> & args,std::vector<std::string> * non_option_args,ProbeEvents & probe_events)650*288bf522SAndroid Build Coastguard Worker bool StatCommand::ParseOptions(const std::vector<std::string>& args,
651*288bf522SAndroid Build Coastguard Worker std::vector<std::string>* non_option_args,
652*288bf522SAndroid Build Coastguard Worker ProbeEvents& probe_events) {
653*288bf522SAndroid Build Coastguard Worker OptionValueMap options;
654*288bf522SAndroid Build Coastguard Worker std::vector<std::pair<OptionName, OptionValue>> ordered_options;
655*288bf522SAndroid Build Coastguard Worker
656*288bf522SAndroid Build Coastguard Worker if (!PreprocessOptions(args, GetStatCmdOptionFormats(), &options, &ordered_options,
657*288bf522SAndroid Build Coastguard Worker non_option_args)) {
658*288bf522SAndroid Build Coastguard Worker return false;
659*288bf522SAndroid Build Coastguard Worker }
660*288bf522SAndroid Build Coastguard Worker
661*288bf522SAndroid Build Coastguard Worker // Process options.
662*288bf522SAndroid Build Coastguard Worker system_wide_collection_ = options.PullBoolValue("-a");
663*288bf522SAndroid Build Coastguard Worker
664*288bf522SAndroid Build Coastguard Worker if (auto value = options.PullValue("--app"); value) {
665*288bf522SAndroid Build Coastguard Worker app_package_name_ = value->str_value;
666*288bf522SAndroid Build Coastguard Worker }
667*288bf522SAndroid Build Coastguard Worker csv_ = options.PullBoolValue("--csv");
668*288bf522SAndroid Build Coastguard Worker
669*288bf522SAndroid Build Coastguard Worker if (!options.PullDoubleValue("--duration", &duration_in_sec_, 1e-9)) {
670*288bf522SAndroid Build Coastguard Worker return false;
671*288bf522SAndroid Build Coastguard Worker }
672*288bf522SAndroid Build Coastguard Worker if (!options.PullDoubleValue("--interval", &interval_in_ms_, 1e-9)) {
673*288bf522SAndroid Build Coastguard Worker return false;
674*288bf522SAndroid Build Coastguard Worker }
675*288bf522SAndroid Build Coastguard Worker interval_only_values_ = options.PullBoolValue("--interval-only-values");
676*288bf522SAndroid Build Coastguard Worker
677*288bf522SAndroid Build Coastguard Worker in_app_context_ = options.PullBoolValue("--in-app");
678*288bf522SAndroid Build Coastguard Worker for (const OptionValue& value : options.PullValues("--kprobe")) {
679*288bf522SAndroid Build Coastguard Worker for (const auto& cmd : Split(value.str_value, ",")) {
680*288bf522SAndroid Build Coastguard Worker if (!probe_events.AddKprobe(cmd)) {
681*288bf522SAndroid Build Coastguard Worker return false;
682*288bf522SAndroid Build Coastguard Worker }
683*288bf522SAndroid Build Coastguard Worker }
684*288bf522SAndroid Build Coastguard Worker }
685*288bf522SAndroid Build Coastguard Worker child_inherit_ = !options.PullBoolValue("--no-inherit");
686*288bf522SAndroid Build Coastguard Worker
687*288bf522SAndroid Build Coastguard Worker if (auto value = options.PullValue("-o"); value) {
688*288bf522SAndroid Build Coastguard Worker output_filename_ = value->str_value;
689*288bf522SAndroid Build Coastguard Worker }
690*288bf522SAndroid Build Coastguard Worker if (auto value = options.PullValue("--out-fd"); value) {
691*288bf522SAndroid Build Coastguard Worker out_fd_.reset(static_cast<int>(value->uint_value));
692*288bf522SAndroid Build Coastguard Worker }
693*288bf522SAndroid Build Coastguard Worker
694*288bf522SAndroid Build Coastguard Worker report_per_core_ = options.PullBoolValue("--per-core");
695*288bf522SAndroid Build Coastguard Worker report_per_thread_ = options.PullBoolValue("--per-thread");
696*288bf522SAndroid Build Coastguard Worker
697*288bf522SAndroid Build Coastguard Worker if (auto strs = options.PullStringValues("-p"); !strs.empty()) {
698*288bf522SAndroid Build Coastguard Worker if (auto pids = GetPidsFromStrings(strs, true, true); pids) {
699*288bf522SAndroid Build Coastguard Worker event_selection_set_.AddMonitoredProcesses(pids.value());
700*288bf522SAndroid Build Coastguard Worker } else {
701*288bf522SAndroid Build Coastguard Worker return false;
702*288bf522SAndroid Build Coastguard Worker }
703*288bf522SAndroid Build Coastguard Worker }
704*288bf522SAndroid Build Coastguard Worker print_hw_counter_ = options.PullBoolValue("--print-hw-counter");
705*288bf522SAndroid Build Coastguard Worker
706*288bf522SAndroid Build Coastguard Worker if (auto value = options.PullValue("--sort"); value) {
707*288bf522SAndroid Build Coastguard Worker sort_keys_ = Split(value->str_value, ",");
708*288bf522SAndroid Build Coastguard Worker }
709*288bf522SAndroid Build Coastguard Worker
710*288bf522SAndroid Build Coastguard Worker if (auto value = options.PullValue("--stop-signal-fd"); value) {
711*288bf522SAndroid Build Coastguard Worker stop_signal_fd_.reset(static_cast<int>(value->uint_value));
712*288bf522SAndroid Build Coastguard Worker }
713*288bf522SAndroid Build Coastguard Worker
714*288bf522SAndroid Build Coastguard Worker for (const OptionValue& value : options.PullValues("-t")) {
715*288bf522SAndroid Build Coastguard Worker if (auto tids = GetTidsFromString(value.str_value, true); tids) {
716*288bf522SAndroid Build Coastguard Worker event_selection_set_.AddMonitoredThreads(tids.value());
717*288bf522SAndroid Build Coastguard Worker } else {
718*288bf522SAndroid Build Coastguard Worker return false;
719*288bf522SAndroid Build Coastguard Worker }
720*288bf522SAndroid Build Coastguard Worker }
721*288bf522SAndroid Build Coastguard Worker
722*288bf522SAndroid Build Coastguard Worker if (auto value = options.PullValue("--tracepoint-events"); value) {
723*288bf522SAndroid Build Coastguard Worker if (!EventTypeManager::Instance().ReadTracepointsFromFile(value->str_value)) {
724*288bf522SAndroid Build Coastguard Worker return false;
725*288bf522SAndroid Build Coastguard Worker }
726*288bf522SAndroid Build Coastguard Worker }
727*288bf522SAndroid Build Coastguard Worker
728*288bf522SAndroid Build Coastguard Worker use_devfreq_counters_ = options.PullBoolValue("--use-devfreq-counters");
729*288bf522SAndroid Build Coastguard Worker verbose_mode_ = options.PullBoolValue("--verbose");
730*288bf522SAndroid Build Coastguard Worker
731*288bf522SAndroid Build Coastguard Worker CHECK(options.values.empty());
732*288bf522SAndroid Build Coastguard Worker
733*288bf522SAndroid Build Coastguard Worker // Process ordered options.
734*288bf522SAndroid Build Coastguard Worker for (const auto& pair : ordered_options) {
735*288bf522SAndroid Build Coastguard Worker const OptionName& name = pair.first;
736*288bf522SAndroid Build Coastguard Worker const OptionValue& value = pair.second;
737*288bf522SAndroid Build Coastguard Worker
738*288bf522SAndroid Build Coastguard Worker if (name == "--cpu") {
739*288bf522SAndroid Build Coastguard Worker if (auto v = GetCpusFromString(value.str_value); v) {
740*288bf522SAndroid Build Coastguard Worker std::set<int>& cpus = v.value();
741*288bf522SAndroid Build Coastguard Worker event_selection_set_.SetCpusForNewEvents(std::vector<int>(cpus.begin(), cpus.end()));
742*288bf522SAndroid Build Coastguard Worker } else {
743*288bf522SAndroid Build Coastguard Worker return false;
744*288bf522SAndroid Build Coastguard Worker }
745*288bf522SAndroid Build Coastguard Worker } else if (name == "-e") {
746*288bf522SAndroid Build Coastguard Worker for (const auto& event_type : Split(value.str_value, ",")) {
747*288bf522SAndroid Build Coastguard Worker if (!probe_events.CreateProbeEventIfNotExist(event_type)) {
748*288bf522SAndroid Build Coastguard Worker return false;
749*288bf522SAndroid Build Coastguard Worker }
750*288bf522SAndroid Build Coastguard Worker if (!event_selection_set_.AddEventType(event_type)) {
751*288bf522SAndroid Build Coastguard Worker return false;
752*288bf522SAndroid Build Coastguard Worker }
753*288bf522SAndroid Build Coastguard Worker }
754*288bf522SAndroid Build Coastguard Worker } else if (name == "--group") {
755*288bf522SAndroid Build Coastguard Worker std::vector<std::string> event_types = Split(value.str_value, ",");
756*288bf522SAndroid Build Coastguard Worker for (const auto& event_type : event_types) {
757*288bf522SAndroid Build Coastguard Worker if (!probe_events.CreateProbeEventIfNotExist(event_type)) {
758*288bf522SAndroid Build Coastguard Worker return false;
759*288bf522SAndroid Build Coastguard Worker }
760*288bf522SAndroid Build Coastguard Worker }
761*288bf522SAndroid Build Coastguard Worker if (!event_selection_set_.AddEventGroup(event_types)) {
762*288bf522SAndroid Build Coastguard Worker return false;
763*288bf522SAndroid Build Coastguard Worker }
764*288bf522SAndroid Build Coastguard Worker } else if (name == "--tp-filter") {
765*288bf522SAndroid Build Coastguard Worker if (!event_selection_set_.SetTracepointFilter(value.str_value)) {
766*288bf522SAndroid Build Coastguard Worker return false;
767*288bf522SAndroid Build Coastguard Worker }
768*288bf522SAndroid Build Coastguard Worker } else {
769*288bf522SAndroid Build Coastguard Worker LOG(ERROR) << "unprocessed option: " << name;
770*288bf522SAndroid Build Coastguard Worker return false;
771*288bf522SAndroid Build Coastguard Worker }
772*288bf522SAndroid Build Coastguard Worker }
773*288bf522SAndroid Build Coastguard Worker
774*288bf522SAndroid Build Coastguard Worker if (system_wide_collection_ && event_selection_set_.HasMonitoredTarget()) {
775*288bf522SAndroid Build Coastguard Worker LOG(ERROR) << "Stat system wide and existing processes/threads can't be "
776*288bf522SAndroid Build Coastguard Worker "used at the same time.";
777*288bf522SAndroid Build Coastguard Worker return false;
778*288bf522SAndroid Build Coastguard Worker }
779*288bf522SAndroid Build Coastguard Worker if (system_wide_collection_ && !IsRoot()) {
780*288bf522SAndroid Build Coastguard Worker LOG(ERROR) << "System wide profiling needs root privilege.";
781*288bf522SAndroid Build Coastguard Worker return false;
782*288bf522SAndroid Build Coastguard Worker }
783*288bf522SAndroid Build Coastguard Worker
784*288bf522SAndroid Build Coastguard Worker if (report_per_core_ || report_per_thread_) {
785*288bf522SAndroid Build Coastguard Worker summary_comparator_ = BuildSummaryComparator(sort_keys_, report_per_thread_, report_per_core_);
786*288bf522SAndroid Build Coastguard Worker if (!summary_comparator_) {
787*288bf522SAndroid Build Coastguard Worker return false;
788*288bf522SAndroid Build Coastguard Worker }
789*288bf522SAndroid Build Coastguard Worker }
790*288bf522SAndroid Build Coastguard Worker return true;
791*288bf522SAndroid Build Coastguard Worker }
792*288bf522SAndroid Build Coastguard Worker
CheckHardwareCountersOnCpu(int cpu,size_t counters)793*288bf522SAndroid Build Coastguard Worker std::optional<bool> CheckHardwareCountersOnCpu(int cpu, size_t counters) {
794*288bf522SAndroid Build Coastguard Worker if (counters == 0) {
795*288bf522SAndroid Build Coastguard Worker return true;
796*288bf522SAndroid Build Coastguard Worker }
797*288bf522SAndroid Build Coastguard Worker const EventType* event = FindEventTypeByName("cpu-cycles", true);
798*288bf522SAndroid Build Coastguard Worker if (event == nullptr) {
799*288bf522SAndroid Build Coastguard Worker return std::nullopt;
800*288bf522SAndroid Build Coastguard Worker }
801*288bf522SAndroid Build Coastguard Worker perf_event_attr attr = CreateDefaultPerfEventAttr(*event);
802*288bf522SAndroid Build Coastguard Worker auto workload = Workload::CreateWorkload({"sleep", "0.1"});
803*288bf522SAndroid Build Coastguard Worker if (!workload || !workload->SetCpuAffinity(cpu)) {
804*288bf522SAndroid Build Coastguard Worker return std::nullopt;
805*288bf522SAndroid Build Coastguard Worker }
806*288bf522SAndroid Build Coastguard Worker std::vector<std::unique_ptr<EventFd>> event_fds;
807*288bf522SAndroid Build Coastguard Worker for (size_t i = 0; i < counters; i++) {
808*288bf522SAndroid Build Coastguard Worker EventFd* group_event_fd = event_fds.empty() ? nullptr : event_fds[0].get();
809*288bf522SAndroid Build Coastguard Worker auto event_fd =
810*288bf522SAndroid Build Coastguard Worker EventFd::OpenEventFile(attr, workload->GetPid(), cpu, group_event_fd, "cpu-cycles", false);
811*288bf522SAndroid Build Coastguard Worker if (!event_fd) {
812*288bf522SAndroid Build Coastguard Worker return false;
813*288bf522SAndroid Build Coastguard Worker }
814*288bf522SAndroid Build Coastguard Worker event_fds.emplace_back(std::move(event_fd));
815*288bf522SAndroid Build Coastguard Worker }
816*288bf522SAndroid Build Coastguard Worker if (!workload->Start() || !workload->WaitChildProcess(true, nullptr)) {
817*288bf522SAndroid Build Coastguard Worker return std::nullopt;
818*288bf522SAndroid Build Coastguard Worker }
819*288bf522SAndroid Build Coastguard Worker for (auto& event_fd : event_fds) {
820*288bf522SAndroid Build Coastguard Worker PerfCounter counter;
821*288bf522SAndroid Build Coastguard Worker if (!event_fd->ReadCounter(&counter)) {
822*288bf522SAndroid Build Coastguard Worker return std::nullopt;
823*288bf522SAndroid Build Coastguard Worker }
824*288bf522SAndroid Build Coastguard Worker if (counter.time_enabled == 0 || counter.time_enabled > counter.time_running) {
825*288bf522SAndroid Build Coastguard Worker return false;
826*288bf522SAndroid Build Coastguard Worker }
827*288bf522SAndroid Build Coastguard Worker }
828*288bf522SAndroid Build Coastguard Worker return true;
829*288bf522SAndroid Build Coastguard Worker }
830*288bf522SAndroid Build Coastguard Worker
GetHardwareCountersOnCpu(int cpu)831*288bf522SAndroid Build Coastguard Worker std::optional<size_t> GetHardwareCountersOnCpu(int cpu) {
832*288bf522SAndroid Build Coastguard Worker size_t available_counters = 0;
833*288bf522SAndroid Build Coastguard Worker while (true) {
834*288bf522SAndroid Build Coastguard Worker std::optional<bool> result = CheckHardwareCountersOnCpu(cpu, available_counters + 1);
835*288bf522SAndroid Build Coastguard Worker if (!result.has_value()) {
836*288bf522SAndroid Build Coastguard Worker return std::nullopt;
837*288bf522SAndroid Build Coastguard Worker }
838*288bf522SAndroid Build Coastguard Worker if (!result.value()) {
839*288bf522SAndroid Build Coastguard Worker break;
840*288bf522SAndroid Build Coastguard Worker }
841*288bf522SAndroid Build Coastguard Worker available_counters++;
842*288bf522SAndroid Build Coastguard Worker }
843*288bf522SAndroid Build Coastguard Worker return available_counters;
844*288bf522SAndroid Build Coastguard Worker }
845*288bf522SAndroid Build Coastguard Worker
PrintHardwareCounters()846*288bf522SAndroid Build Coastguard Worker void StatCommand::PrintHardwareCounters() {
847*288bf522SAndroid Build Coastguard Worker for (int cpu : GetOnlineCpus()) {
848*288bf522SAndroid Build Coastguard Worker std::optional<size_t> counters = GetHardwareCountersOnCpu(cpu);
849*288bf522SAndroid Build Coastguard Worker if (!counters) {
850*288bf522SAndroid Build Coastguard Worker // When built as a 32-bit program, we can't set sched_affinity to a 64-bit only CPU. So we
851*288bf522SAndroid Build Coastguard Worker // may not be able to get hardware counters on that CPU.
852*288bf522SAndroid Build Coastguard Worker LOG(WARNING) << "Failed to get CPU PMU hardware counters on cpu " << cpu;
853*288bf522SAndroid Build Coastguard Worker continue;
854*288bf522SAndroid Build Coastguard Worker }
855*288bf522SAndroid Build Coastguard Worker printf("There are %zu CPU PMU hardware counters available on cpu %d.\n", counters.value(), cpu);
856*288bf522SAndroid Build Coastguard Worker }
857*288bf522SAndroid Build Coastguard Worker }
858*288bf522SAndroid Build Coastguard Worker
AddDefaultMeasuredEventTypes()859*288bf522SAndroid Build Coastguard Worker bool StatCommand::AddDefaultMeasuredEventTypes() {
860*288bf522SAndroid Build Coastguard Worker for (auto& name : default_measured_event_types) {
861*288bf522SAndroid Build Coastguard Worker // It is not an error when some event types in the default list are not
862*288bf522SAndroid Build Coastguard Worker // supported by the kernel.
863*288bf522SAndroid Build Coastguard Worker const EventType* type = FindEventTypeByName(name);
864*288bf522SAndroid Build Coastguard Worker if (type != nullptr && IsEventAttrSupported(CreateDefaultPerfEventAttr(*type), name)) {
865*288bf522SAndroid Build Coastguard Worker if (!event_selection_set_.AddEventType(name)) {
866*288bf522SAndroid Build Coastguard Worker return false;
867*288bf522SAndroid Build Coastguard Worker }
868*288bf522SAndroid Build Coastguard Worker }
869*288bf522SAndroid Build Coastguard Worker }
870*288bf522SAndroid Build Coastguard Worker if (event_selection_set_.empty()) {
871*288bf522SAndroid Build Coastguard Worker LOG(ERROR) << "Failed to add any supported default measured types";
872*288bf522SAndroid Build Coastguard Worker return false;
873*288bf522SAndroid Build Coastguard Worker }
874*288bf522SAndroid Build Coastguard Worker return true;
875*288bf522SAndroid Build Coastguard Worker }
876*288bf522SAndroid Build Coastguard Worker
SetEventSelectionFlags()877*288bf522SAndroid Build Coastguard Worker void StatCommand::SetEventSelectionFlags() {
878*288bf522SAndroid Build Coastguard Worker event_selection_set_.SetInherit(child_inherit_);
879*288bf522SAndroid Build Coastguard Worker }
880*288bf522SAndroid Build Coastguard Worker
MonitorEachThread()881*288bf522SAndroid Build Coastguard Worker void StatCommand::MonitorEachThread() {
882*288bf522SAndroid Build Coastguard Worker std::vector<pid_t> threads;
883*288bf522SAndroid Build Coastguard Worker for (auto pid : event_selection_set_.GetMonitoredProcesses()) {
884*288bf522SAndroid Build Coastguard Worker for (auto tid : GetThreadsInProcess(pid)) {
885*288bf522SAndroid Build Coastguard Worker ThreadInfo info;
886*288bf522SAndroid Build Coastguard Worker if (GetThreadName(tid, &info.name)) {
887*288bf522SAndroid Build Coastguard Worker info.tid = tid;
888*288bf522SAndroid Build Coastguard Worker info.pid = pid;
889*288bf522SAndroid Build Coastguard Worker thread_info_[tid] = std::move(info);
890*288bf522SAndroid Build Coastguard Worker threads.push_back(tid);
891*288bf522SAndroid Build Coastguard Worker }
892*288bf522SAndroid Build Coastguard Worker }
893*288bf522SAndroid Build Coastguard Worker }
894*288bf522SAndroid Build Coastguard Worker for (auto tid : event_selection_set_.GetMonitoredThreads()) {
895*288bf522SAndroid Build Coastguard Worker ThreadInfo info;
896*288bf522SAndroid Build Coastguard Worker if (ReadThreadNameAndPid(tid, &info.name, &info.pid)) {
897*288bf522SAndroid Build Coastguard Worker info.tid = tid;
898*288bf522SAndroid Build Coastguard Worker thread_info_[tid] = std::move(info);
899*288bf522SAndroid Build Coastguard Worker threads.push_back(tid);
900*288bf522SAndroid Build Coastguard Worker }
901*288bf522SAndroid Build Coastguard Worker }
902*288bf522SAndroid Build Coastguard Worker event_selection_set_.ClearMonitoredTargets();
903*288bf522SAndroid Build Coastguard Worker event_selection_set_.AddMonitoredThreads(threads);
904*288bf522SAndroid Build Coastguard Worker }
905*288bf522SAndroid Build Coastguard Worker
AdjustToIntervalOnlyValues(std::vector<CountersInfo> & counters)906*288bf522SAndroid Build Coastguard Worker void StatCommand::AdjustToIntervalOnlyValues(std::vector<CountersInfo>& counters) {
907*288bf522SAndroid Build Coastguard Worker if (last_sum_values_.size() < counters.size()) {
908*288bf522SAndroid Build Coastguard Worker last_sum_values_.resize(counters.size());
909*288bf522SAndroid Build Coastguard Worker }
910*288bf522SAndroid Build Coastguard Worker for (size_t i = 0; i < counters.size(); i++) {
911*288bf522SAndroid Build Coastguard Worker std::vector<CounterInfo>& counters_per_event = counters[i].counters;
912*288bf522SAndroid Build Coastguard Worker std::vector<CounterSum>& last_sum = last_sum_values_[i];
913*288bf522SAndroid Build Coastguard Worker
914*288bf522SAndroid Build Coastguard Worker if (last_sum.size() < counters_per_event.size()) {
915*288bf522SAndroid Build Coastguard Worker last_sum.resize(counters_per_event.size());
916*288bf522SAndroid Build Coastguard Worker }
917*288bf522SAndroid Build Coastguard Worker for (size_t j = 0; j < counters_per_event.size(); j++) {
918*288bf522SAndroid Build Coastguard Worker PerfCounter& counter = counters_per_event[j].counter;
919*288bf522SAndroid Build Coastguard Worker CounterSum new_sum;
920*288bf522SAndroid Build Coastguard Worker new_sum.FromCounter(counter);
921*288bf522SAndroid Build Coastguard Worker CounterSum delta = new_sum - last_sum[j];
922*288bf522SAndroid Build Coastguard Worker delta.ToCounter(counter);
923*288bf522SAndroid Build Coastguard Worker last_sum[j] = new_sum;
924*288bf522SAndroid Build Coastguard Worker }
925*288bf522SAndroid Build Coastguard Worker }
926*288bf522SAndroid Build Coastguard Worker }
927*288bf522SAndroid Build Coastguard Worker
ShowCounters(const std::vector<CountersInfo> & counters,double duration_in_sec,FILE * fp)928*288bf522SAndroid Build Coastguard Worker bool StatCommand::ShowCounters(const std::vector<CountersInfo>& counters, double duration_in_sec,
929*288bf522SAndroid Build Coastguard Worker FILE* fp) {
930*288bf522SAndroid Build Coastguard Worker if (csv_) {
931*288bf522SAndroid Build Coastguard Worker fprintf(fp, "Performance counter statistics,\n");
932*288bf522SAndroid Build Coastguard Worker } else {
933*288bf522SAndroid Build Coastguard Worker fprintf(fp, "Performance counter statistics:\n\n");
934*288bf522SAndroid Build Coastguard Worker }
935*288bf522SAndroid Build Coastguard Worker
936*288bf522SAndroid Build Coastguard Worker if (verbose_mode_) {
937*288bf522SAndroid Build Coastguard Worker for (auto& counters_info : counters) {
938*288bf522SAndroid Build Coastguard Worker for (auto& counter_info : counters_info.counters) {
939*288bf522SAndroid Build Coastguard Worker if (csv_) {
940*288bf522SAndroid Build Coastguard Worker fprintf(fp,
941*288bf522SAndroid Build Coastguard Worker "%s,tid,%d,cpu,%d,count,%" PRIu64 ",time_enabled,%" PRIu64
942*288bf522SAndroid Build Coastguard Worker ",time running,%" PRIu64 ",id,%" PRIu64 ",\n",
943*288bf522SAndroid Build Coastguard Worker counters_info.event_name.c_str(), counter_info.tid, counter_info.cpu,
944*288bf522SAndroid Build Coastguard Worker counter_info.counter.value, counter_info.counter.time_enabled,
945*288bf522SAndroid Build Coastguard Worker counter_info.counter.time_running, counter_info.counter.id);
946*288bf522SAndroid Build Coastguard Worker } else {
947*288bf522SAndroid Build Coastguard Worker fprintf(fp,
948*288bf522SAndroid Build Coastguard Worker "%s(tid %d, cpu %d): count %" PRIu64 ", time_enabled %" PRIu64
949*288bf522SAndroid Build Coastguard Worker ", time running %" PRIu64 ", id %" PRIu64 "\n",
950*288bf522SAndroid Build Coastguard Worker counters_info.event_name.c_str(), counter_info.tid, counter_info.cpu,
951*288bf522SAndroid Build Coastguard Worker counter_info.counter.value, counter_info.counter.time_enabled,
952*288bf522SAndroid Build Coastguard Worker counter_info.counter.time_running, counter_info.counter.id);
953*288bf522SAndroid Build Coastguard Worker }
954*288bf522SAndroid Build Coastguard Worker }
955*288bf522SAndroid Build Coastguard Worker }
956*288bf522SAndroid Build Coastguard Worker }
957*288bf522SAndroid Build Coastguard Worker
958*288bf522SAndroid Build Coastguard Worker CounterSummaryBuilder builder(report_per_thread_, report_per_core_, csv_, thread_info_,
959*288bf522SAndroid Build Coastguard Worker summary_comparator_);
960*288bf522SAndroid Build Coastguard Worker for (const auto& info : counters) {
961*288bf522SAndroid Build Coastguard Worker builder.AddCountersForOneEventType(info);
962*288bf522SAndroid Build Coastguard Worker }
963*288bf522SAndroid Build Coastguard Worker CounterSummaries summaries(builder.Build(), csv_);
964*288bf522SAndroid Build Coastguard Worker summaries.AutoGenerateSummaries();
965*288bf522SAndroid Build Coastguard Worker summaries.GenerateComments(duration_in_sec);
966*288bf522SAndroid Build Coastguard Worker summaries.Show(fp);
967*288bf522SAndroid Build Coastguard Worker
968*288bf522SAndroid Build Coastguard Worker if (csv_) {
969*288bf522SAndroid Build Coastguard Worker fprintf(fp, "Total test time,%lf,seconds,\n", duration_in_sec);
970*288bf522SAndroid Build Coastguard Worker } else {
971*288bf522SAndroid Build Coastguard Worker fprintf(fp, "\nTotal test time: %lf seconds.\n", duration_in_sec);
972*288bf522SAndroid Build Coastguard Worker }
973*288bf522SAndroid Build Coastguard Worker return true;
974*288bf522SAndroid Build Coastguard Worker }
975*288bf522SAndroid Build Coastguard Worker
CheckHardwareCounterMultiplexing()976*288bf522SAndroid Build Coastguard Worker void StatCommand::CheckHardwareCounterMultiplexing() {
977*288bf522SAndroid Build Coastguard Worker for (const auto& [cpu, hardware_events] : event_selection_set_.GetHardwareCountersForCpus()) {
978*288bf522SAndroid Build Coastguard Worker std::optional<bool> result = CheckHardwareCountersOnCpu(cpu, hardware_events);
979*288bf522SAndroid Build Coastguard Worker if (result.has_value() && !result.value()) {
980*288bf522SAndroid Build Coastguard Worker LOG(WARNING) << "It seems the number of hardware events are more than the number of\n"
981*288bf522SAndroid Build Coastguard Worker << "available CPU PMU hardware counters. That will trigger hardware counter\n"
982*288bf522SAndroid Build Coastguard Worker << "multiplexing. As a result, events are not counted all the time processes\n"
983*288bf522SAndroid Build Coastguard Worker << "running, and event counts are smaller than what really happen.\n"
984*288bf522SAndroid Build Coastguard Worker << "Use --print-hw-counter to show available hardware counters.\n"
985*288bf522SAndroid Build Coastguard Worker #if defined(__ANDROID__)
986*288bf522SAndroid Build Coastguard Worker << "If on a rooted device, try --use-devfreq-counters to get more counters.\n"
987*288bf522SAndroid Build Coastguard Worker #endif
988*288bf522SAndroid Build Coastguard Worker ;
989*288bf522SAndroid Build Coastguard Worker break;
990*288bf522SAndroid Build Coastguard Worker }
991*288bf522SAndroid Build Coastguard Worker }
992*288bf522SAndroid Build Coastguard Worker }
993*288bf522SAndroid Build Coastguard Worker
PrintWarningForInaccurateEvents()994*288bf522SAndroid Build Coastguard Worker void StatCommand::PrintWarningForInaccurateEvents() {
995*288bf522SAndroid Build Coastguard Worker for (const EventType* event : event_selection_set_.GetEvents()) {
996*288bf522SAndroid Build Coastguard Worker if (event->name == "raw-l3d-cache-lmiss-rd") {
997*288bf522SAndroid Build Coastguard Worker LOG(WARNING) << "PMU event L3D_CACHE_LMISS_RD might undercount on A510. Please use "
998*288bf522SAndroid Build Coastguard Worker "L3D_CACHE_REFILL_RD instead.";
999*288bf522SAndroid Build Coastguard Worker break;
1000*288bf522SAndroid Build Coastguard Worker }
1001*288bf522SAndroid Build Coastguard Worker }
1002*288bf522SAndroid Build Coastguard Worker }
1003*288bf522SAndroid Build Coastguard Worker
1004*288bf522SAndroid Build Coastguard Worker } // namespace
1005*288bf522SAndroid Build Coastguard Worker
RegisterStatCommand()1006*288bf522SAndroid Build Coastguard Worker void RegisterStatCommand() {
1007*288bf522SAndroid Build Coastguard Worker RegisterCommand("stat", [] { return std::unique_ptr<Command>(new StatCommand); });
1008*288bf522SAndroid Build Coastguard Worker }
1009*288bf522SAndroid Build Coastguard Worker
1010*288bf522SAndroid Build Coastguard Worker } // namespace simpleperf
1011