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