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 "event_selection_set.h"
18 
19 #include <algorithm>
20 #include <atomic>
21 #include <thread>
22 #include <unordered_map>
23 
24 #include <android-base/logging.h>
25 #include <android-base/stringprintf.h>
26 #include <android-base/strings.h>
27 
28 #include "ETMRecorder.h"
29 #include "IOEventLoop.h"
30 #include "RecordReadThread.h"
31 #include "environment.h"
32 #include "event_attr.h"
33 #include "event_type.h"
34 #include "perf_regs.h"
35 #include "tracing.h"
36 #include "utils.h"
37 
38 namespace simpleperf {
39 
40 using android::base::StringPrintf;
41 
IsBranchSamplingSupported()42 bool IsBranchSamplingSupported() {
43   const EventType* type = FindEventTypeByName("cpu-cycles");
44   if (type == nullptr) {
45     return false;
46   }
47   perf_event_attr attr = CreateDefaultPerfEventAttr(*type);
48   attr.sample_type |= PERF_SAMPLE_BRANCH_STACK;
49   attr.branch_sample_type = PERF_SAMPLE_BRANCH_ANY;
50   return IsEventAttrSupported(attr, type->name);
51 }
52 
IsDwarfCallChainSamplingSupported()53 bool IsDwarfCallChainSamplingSupported() {
54   if (auto version = GetKernelVersion(); version && version.value() >= std::make_pair(3, 18)) {
55     // Skip test on kernel >= 3.18, which has all patches needed to support dwarf callchain.
56     return true;
57   }
58   const EventType* type = FindEventTypeByName("cpu-clock");
59   if (type == nullptr) {
60     return false;
61   }
62   perf_event_attr attr = CreateDefaultPerfEventAttr(*type);
63   attr.sample_type |= PERF_SAMPLE_CALLCHAIN | PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER;
64   attr.exclude_callchain_user = 1;
65   attr.sample_regs_user = GetSupportedRegMask(GetTargetArch());
66   attr.sample_stack_user = 8192;
67   return IsEventAttrSupported(attr, type->name);
68 }
69 
IsDumpingRegsForTracepointEventsSupported()70 bool IsDumpingRegsForTracepointEventsSupported() {
71   if (auto version = GetKernelVersion(); version && version.value() >= std::make_pair(4, 2)) {
72     // Kernel >= 4.2 has patch "5b09a094f2 arm64: perf: Fix callchain parse error with kernel
73     // tracepoint events". So no need to test.
74     return true;
75   }
76   const EventType* event_type = FindEventTypeByName("sched:sched_switch", false);
77   if (event_type == nullptr) {
78     return false;
79   }
80   std::atomic<bool> done(false);
81   std::atomic<pid_t> thread_id(0);
82   std::thread thread([&]() {
83     thread_id = gettid();
84     while (!done) {
85       usleep(1);
86     }
87     usleep(1);  // Make a sched out to generate one sample.
88   });
89   while (thread_id == 0) {
90     usleep(1);
91   }
92   perf_event_attr attr = CreateDefaultPerfEventAttr(*event_type);
93   attr.freq = 0;
94   attr.sample_period = 1;
95   std::unique_ptr<EventFd> event_fd =
96       EventFd::OpenEventFile(attr, thread_id, -1, nullptr, event_type->name);
97   if (event_fd == nullptr || !event_fd->CreateMappedBuffer(4, true)) {
98     done = true;
99     thread.join();
100     return false;
101   }
102   done = true;
103   thread.join();
104 
105   // There are small chances that we don't see samples immediately after joining the thread on
106   // cuttlefish, probably due to data synchronization between cpus. To avoid flaky tests, use a
107   // loop to wait for samples.
108   for (int timeout = 0; timeout < 1000; timeout++) {
109     std::vector<char> buffer = event_fd->GetAvailableMmapData();
110     std::vector<std::unique_ptr<Record>> records =
111         ReadRecordsFromBuffer(attr, buffer.data(), buffer.size());
112     for (auto& r : records) {
113       if (r->type() == PERF_RECORD_SAMPLE) {
114         auto& record = *static_cast<SampleRecord*>(r.get());
115         return record.ip_data.ip != 0;
116       }
117     }
118     usleep(1);
119   }
120   return false;
121 }
122 
IsSettingClockIdSupported()123 bool IsSettingClockIdSupported() {
124   // Do the real check only once and keep the result in a static variable.
125   static int is_supported = -1;
126   if (is_supported == -1) {
127     is_supported = 0;
128     if (auto version = GetKernelVersion(); version && version.value() >= std::make_pair(4, 1)) {
129       // Kernel >= 4.1 has patch "34f43927 perf: Add per event clockid support". So no need to test.
130       is_supported = 1;
131     } else if (const EventType* type = FindEventTypeByName("cpu-clock"); type != nullptr) {
132       // Check if the kernel supports setting clockid, which was added in kernel 4.0. Just check
133       // with one clockid is enough. Because all needed clockids were supported before kernel 4.0.
134       perf_event_attr attr = CreateDefaultPerfEventAttr(*type);
135       attr.use_clockid = 1;
136       attr.clockid = CLOCK_MONOTONIC;
137       is_supported = IsEventAttrSupported(attr, type->name) ? 1 : 0;
138     }
139   }
140   return is_supported;
141 }
142 
IsMmap2Supported()143 bool IsMmap2Supported() {
144   if (auto version = GetKernelVersion(); version && version.value() >= std::make_pair(3, 12)) {
145     // Kernel >= 3.12 has patch "13d7a2410 perf: Add attr->mmap2 attribute to an event". So no need
146     // to test.
147     return true;
148   }
149   const EventType* type = FindEventTypeByName("cpu-clock");
150   if (type == nullptr) {
151     return false;
152   }
153   perf_event_attr attr = CreateDefaultPerfEventAttr(*type);
154   attr.mmap2 = 1;
155   return IsEventAttrSupported(attr, type->name);
156 }
157 
IsHardwareEventSupported()158 bool IsHardwareEventSupported() {
159   const EventType* type = FindEventTypeByName("cpu-cycles");
160   if (type == nullptr) {
161     return false;
162   }
163   perf_event_attr attr = CreateDefaultPerfEventAttr(*type);
164   return IsEventAttrSupported(attr, type->name);
165 }
166 
IsSwitchRecordSupported()167 bool IsSwitchRecordSupported() {
168   // Kernel >= 4.3 has patch "45ac1403f perf: Add PERF_RECORD_SWITCH to indicate context switches".
169   auto version = GetKernelVersion();
170   return version && version.value() >= std::make_pair(4, 3);
171 }
172 
ToString() const173 std::string AddrFilter::ToString() const {
174   switch (type) {
175     case FILE_RANGE:
176       return StringPrintf("filter 0x%" PRIx64 "/0x%" PRIx64 "@%s", addr, size, file_path.c_str());
177     case AddrFilter::FILE_START:
178       return StringPrintf("start 0x%" PRIx64 "@%s", addr, file_path.c_str());
179     case AddrFilter::FILE_STOP:
180       return StringPrintf("stop 0x%" PRIx64 "@%s", addr, file_path.c_str());
181     case AddrFilter::KERNEL_RANGE:
182       return StringPrintf("filter 0x%" PRIx64 "/0x%" PRIx64, addr, size);
183     case AddrFilter::KERNEL_START:
184       return StringPrintf("start 0x%" PRIx64, addr);
185     case AddrFilter::KERNEL_STOP:
186       return StringPrintf("stop 0x%" PRIx64, addr);
187   }
188 }
189 
EventSelectionSet(bool for_stat_cmd)190 EventSelectionSet::EventSelectionSet(bool for_stat_cmd)
191     : for_stat_cmd_(for_stat_cmd), loop_(new IOEventLoop) {}
192 
~EventSelectionSet()193 EventSelectionSet::~EventSelectionSet() {}
194 
BuildAndCheckEventSelection(const std::string & event_name,bool first_event,EventSelection * selection)195 bool EventSelectionSet::BuildAndCheckEventSelection(const std::string& event_name, bool first_event,
196                                                     EventSelection* selection) {
197   std::unique_ptr<EventTypeAndModifier> event_type = ParseEventType(event_name);
198   if (event_type == nullptr) {
199     return false;
200   }
201   if (for_stat_cmd_) {
202     if (event_type->event_type.name == "cpu-clock" || event_type->event_type.name == "task-clock") {
203       if (event_type->exclude_user || event_type->exclude_kernel) {
204         LOG(ERROR) << "Modifier u and modifier k used in event type " << event_type->event_type.name
205                    << " are not supported by the kernel.";
206         return false;
207       }
208     }
209   }
210   selection->event_type_modifier = *event_type;
211   selection->event_attr = CreateDefaultPerfEventAttr(event_type->event_type);
212   selection->event_attr.exclude_user = event_type->exclude_user;
213   selection->event_attr.exclude_kernel = event_type->exclude_kernel;
214   selection->event_attr.exclude_hv = event_type->exclude_hv;
215   selection->event_attr.exclude_host = event_type->exclude_host;
216   selection->event_attr.exclude_guest = event_type->exclude_guest;
217   selection->event_attr.precise_ip = event_type->precise_ip;
218   if (IsEtmEventType(event_type->event_type.type)) {
219     auto& etm_recorder = ETMRecorder::GetInstance();
220     if (auto result = etm_recorder.CheckEtmSupport(); !result.ok()) {
221       LOG(ERROR) << result.error();
222       return false;
223     }
224     ETMRecorder::GetInstance().SetEtmPerfEventAttr(&selection->event_attr);
225   }
226   bool set_default_sample_freq = false;
227   if (!for_stat_cmd_) {
228     if (event_type->event_type.type == PERF_TYPE_TRACEPOINT) {
229       selection->event_attr.freq = 0;
230       selection->event_attr.sample_period = DEFAULT_SAMPLE_PERIOD_FOR_TRACEPOINT_EVENT;
231     } else if (IsEtmEventType(event_type->event_type.type)) {
232       // ETM recording has no sample frequency to adjust. Using sample frequency only wastes time
233       // enabling/disabling etm devices. So don't adjust frequency by default.
234       selection->event_attr.freq = 0;
235       selection->event_attr.sample_period = 1;
236       // An ETM event can't be enabled without mmap aux buffer. So disable it by default.
237       selection->event_attr.disabled = 1;
238     } else {
239       selection->event_attr.freq = 1;
240       // Set default sample freq here may print msg "Adjust sample freq to max allowed sample
241       // freq". But this is misleading. Because default sample freq may not be the final sample
242       // freq we use. So use minimum sample freq (1) here.
243       selection->event_attr.sample_freq = 1;
244       set_default_sample_freq = true;
245     }
246     // We only need to dump mmap and comm records for the first event type. Because all event types
247     // are monitoring the same processes.
248     if (first_event) {
249       selection->event_attr.mmap = 1;
250       selection->event_attr.comm = 1;
251       if (IsMmap2Supported()) {
252         selection->event_attr.mmap2 = 1;
253       }
254     }
255   }
256   // PMU events are provided by kernel, so they should be supported
257   if (!event_type->event_type.IsPmuEvent() &&
258       !IsEventAttrSupported(selection->event_attr, selection->event_type_modifier.name)) {
259     LOG(ERROR) << "Event type '" << event_type->name << "' is not supported on the device";
260     return false;
261   }
262   if (set_default_sample_freq) {
263     selection->event_attr.sample_freq = DEFAULT_SAMPLE_FREQ_FOR_NONTRACEPOINT_EVENT;
264   }
265 
266   selection->event_fds.clear();
267 
268   for (const auto& group : groups_) {
269     for (const auto& sel : group.selections) {
270       if (sel.event_type_modifier.name == selection->event_type_modifier.name) {
271         LOG(ERROR) << "Event type '" << sel.event_type_modifier.name << "' appears more than once";
272         return false;
273       }
274     }
275   }
276   return true;
277 }
278 
AddEventType(const std::string & event_name)279 bool EventSelectionSet::AddEventType(const std::string& event_name) {
280   return AddEventGroup(std::vector<std::string>(1, event_name));
281 }
282 
AddEventType(const std::string & event_name,const SampleRate & sample_rate)283 bool EventSelectionSet::AddEventType(const std::string& event_name, const SampleRate& sample_rate) {
284   if (!AddEventGroup(std::vector<std::string>(1, event_name))) {
285     return false;
286   }
287   SetSampleRateForGroup(groups_.back(), sample_rate);
288   return true;
289 }
290 
AddEventGroup(const std::vector<std::string> & event_names)291 bool EventSelectionSet::AddEventGroup(const std::vector<std::string>& event_names) {
292   EventSelectionGroup group;
293   bool first_event = groups_.empty();
294   bool first_in_group = true;
295   for (const auto& event_name : event_names) {
296     EventSelection selection;
297     if (!BuildAndCheckEventSelection(event_name, first_event, &selection)) {
298       return false;
299     }
300     if (IsEtmEventType(selection.event_attr.type)) {
301       has_aux_trace_ = true;
302     }
303     if (first_in_group) {
304       auto& event_type = selection.event_type_modifier.event_type;
305       if (event_type.IsPmuEvent()) {
306         selection.allowed_cpus = event_type.GetPmuCpumask();
307       }
308     }
309     first_event = false;
310     first_in_group = false;
311     group.selections.emplace_back(std::move(selection));
312   }
313   if (sample_rate_) {
314     SetSampleRateForGroup(group, sample_rate_.value());
315   }
316   if (cpus_) {
317     group.cpus = cpus_.value();
318   }
319   groups_.emplace_back(std::move(group));
320   UnionSampleType();
321   return true;
322 }
323 
AddCounters(const std::vector<std::string> & event_names)324 bool EventSelectionSet::AddCounters(const std::vector<std::string>& event_names) {
325   CHECK(!groups_.empty());
326   if (groups_.size() > 1) {
327     LOG(ERROR) << "Failed to add counters. Only one event group is allowed.";
328     return false;
329   }
330   for (const auto& event_name : event_names) {
331     EventSelection selection;
332     if (!BuildAndCheckEventSelection(event_name, false, &selection)) {
333       return false;
334     }
335     // Use a big sample_period to avoid getting samples for added counters.
336     selection.event_attr.freq = 0;
337     selection.event_attr.sample_period = INFINITE_SAMPLE_PERIOD;
338     selection.event_attr.inherit = 0;
339     groups_[0].selections.emplace_back(std::move(selection));
340   }
341   // Add counters in each sample.
342   for (auto& selection : groups_[0].selections) {
343     selection.event_attr.sample_type |= PERF_SAMPLE_READ;
344     selection.event_attr.read_format |= PERF_FORMAT_GROUP;
345   }
346   return true;
347 }
348 
GetEvents() const349 std::vector<const EventType*> EventSelectionSet::GetEvents() const {
350   std::vector<const EventType*> result;
351   for (const auto& group : groups_) {
352     for (const auto& selection : group.selections) {
353       result.push_back(&selection.event_type_modifier.event_type);
354     }
355   }
356   return result;
357 }
358 
GetTracepointEvents() const359 std::vector<const EventType*> EventSelectionSet::GetTracepointEvents() const {
360   std::vector<const EventType*> result;
361   for (const auto& group : groups_) {
362     for (const auto& selection : group.selections) {
363       if (selection.event_type_modifier.event_type.type == PERF_TYPE_TRACEPOINT) {
364         result.push_back(&selection.event_type_modifier.event_type);
365       }
366     }
367   }
368   return result;
369 }
370 
ExcludeKernel() const371 bool EventSelectionSet::ExcludeKernel() const {
372   for (const auto& group : groups_) {
373     for (const auto& selection : group.selections) {
374       if (!selection.event_type_modifier.exclude_kernel) {
375         return false;
376       }
377     }
378   }
379   return true;
380 }
381 
GetEventAttrWithId() const382 EventAttrIds EventSelectionSet::GetEventAttrWithId() const {
383   EventAttrIds result;
384   for (const auto& group : groups_) {
385     for (const auto& selection : group.selections) {
386       std::vector<uint64_t> ids;
387       for (const auto& fd : selection.event_fds) {
388         ids.push_back(fd->Id());
389       }
390       result.resize(result.size() + 1);
391       result.back().attr = selection.event_attr;
392       result.back().ids = std::move(ids);
393     }
394   }
395   return result;
396 }
397 
GetEventNamesById() const398 std::unordered_map<uint64_t, std::string> EventSelectionSet::GetEventNamesById() const {
399   std::unordered_map<uint64_t, std::string> result;
400   for (const auto& group : groups_) {
401     for (const auto& selection : group.selections) {
402       for (const auto& fd : selection.event_fds) {
403         result[fd->Id()] = selection.event_type_modifier.name;
404       }
405     }
406   }
407   return result;
408 }
409 
GetCpusById() const410 std::unordered_map<uint64_t, int> EventSelectionSet::GetCpusById() const {
411   std::unordered_map<uint64_t, int> result;
412   for (const auto& group : groups_) {
413     for (const auto& selection : group.selections) {
414       for (const auto& fd : selection.event_fds) {
415         result[fd->Id()] = fd->Cpu();
416       }
417     }
418   }
419   return result;
420 }
421 
GetHardwareCountersForCpus() const422 std::map<int, size_t> EventSelectionSet::GetHardwareCountersForCpus() const {
423   std::map<int, size_t> cpu_map;
424   std::vector<int> online_cpus = GetOnlineCpus();
425 
426   for (const auto& group : groups_) {
427     size_t hardware_events = 0;
428     for (const auto& selection : group.selections) {
429       if (selection.event_type_modifier.event_type.IsHardwareEvent()) {
430         hardware_events++;
431       }
432     }
433     const std::vector<int>* pcpus = group.cpus.empty() ? &online_cpus : &group.cpus;
434     for (int cpu : *pcpus) {
435       cpu_map[cpu] += hardware_events;
436     }
437   }
438   return cpu_map;
439 }
440 
441 // Union the sample type of different event attrs can make reading sample
442 // records in perf.data easier.
UnionSampleType()443 void EventSelectionSet::UnionSampleType() {
444   uint64_t sample_type = 0;
445   for (const auto& group : groups_) {
446     for (const auto& selection : group.selections) {
447       sample_type |= selection.event_attr.sample_type;
448     }
449   }
450   for (auto& group : groups_) {
451     for (auto& selection : group.selections) {
452       selection.event_attr.sample_type = sample_type;
453     }
454   }
455 }
456 
SetEnableCondition(bool enable_on_open,bool enable_on_exec)457 void EventSelectionSet::SetEnableCondition(bool enable_on_open, bool enable_on_exec) {
458   for (auto& group : groups_) {
459     for (auto& selection : group.selections) {
460       selection.event_attr.disabled = !enable_on_open;
461       selection.event_attr.enable_on_exec = enable_on_exec;
462     }
463   }
464 }
465 
IsEnabledOnExec() const466 bool EventSelectionSet::IsEnabledOnExec() const {
467   for (const auto& group : groups_) {
468     for (const auto& selection : group.selections) {
469       if (!selection.event_attr.enable_on_exec) {
470         return false;
471       }
472     }
473   }
474   return true;
475 }
476 
SampleIdAll()477 void EventSelectionSet::SampleIdAll() {
478   for (auto& group : groups_) {
479     for (auto& selection : group.selections) {
480       selection.event_attr.sample_id_all = 1;
481     }
482   }
483 }
484 
SetSampleRateForNewEvents(const SampleRate & rate)485 void EventSelectionSet::SetSampleRateForNewEvents(const SampleRate& rate) {
486   sample_rate_ = rate;
487   for (auto& group : groups_) {
488     if (!group.set_sample_rate) {
489       SetSampleRateForGroup(group, rate);
490     }
491   }
492 }
493 
SetCpusForNewEvents(const std::vector<int> & cpus)494 void EventSelectionSet::SetCpusForNewEvents(const std::vector<int>& cpus) {
495   cpus_ = cpus;
496   for (auto& group : groups_) {
497     if (group.cpus.empty()) {
498       group.cpus = cpus_.value();
499     }
500   }
501 }
502 
SetSampleRateForGroup(EventSelectionSet::EventSelectionGroup & group,const SampleRate & rate)503 void EventSelectionSet::SetSampleRateForGroup(EventSelectionSet::EventSelectionGroup& group,
504                                               const SampleRate& rate) {
505   group.set_sample_rate = true;
506   for (auto& selection : group.selections) {
507     if (rate.UseFreq()) {
508       selection.event_attr.freq = 1;
509       selection.event_attr.sample_freq = rate.sample_freq;
510     } else {
511       selection.event_attr.freq = 0;
512       selection.event_attr.sample_period = rate.sample_period;
513     }
514   }
515 }
516 
SetBranchSampling(uint64_t branch_sample_type)517 bool EventSelectionSet::SetBranchSampling(uint64_t branch_sample_type) {
518   if (branch_sample_type != 0 &&
519       (branch_sample_type & (PERF_SAMPLE_BRANCH_ANY | PERF_SAMPLE_BRANCH_ANY_CALL |
520                              PERF_SAMPLE_BRANCH_ANY_RETURN | PERF_SAMPLE_BRANCH_IND_CALL)) == 0) {
521     LOG(ERROR) << "Invalid branch_sample_type: 0x" << std::hex << branch_sample_type;
522     return false;
523   }
524   if (branch_sample_type != 0 && !IsBranchSamplingSupported()) {
525     LOG(ERROR) << "branch stack sampling is not supported on this device.";
526     return false;
527   }
528   for (auto& group : groups_) {
529     for (auto& selection : group.selections) {
530       perf_event_attr& attr = selection.event_attr;
531       if (branch_sample_type != 0) {
532         attr.sample_type |= PERF_SAMPLE_BRANCH_STACK;
533       } else {
534         attr.sample_type &= ~PERF_SAMPLE_BRANCH_STACK;
535       }
536       attr.branch_sample_type = branch_sample_type;
537     }
538   }
539   return true;
540 }
541 
EnableFpCallChainSampling()542 void EventSelectionSet::EnableFpCallChainSampling() {
543   for (auto& group : groups_) {
544     for (auto& selection : group.selections) {
545       selection.event_attr.sample_type |= PERF_SAMPLE_CALLCHAIN;
546     }
547   }
548 }
549 
EnableDwarfCallChainSampling(uint32_t dump_stack_size)550 bool EventSelectionSet::EnableDwarfCallChainSampling(uint32_t dump_stack_size) {
551   if (!IsDwarfCallChainSamplingSupported()) {
552     LOG(ERROR) << "dwarf callchain sampling is not supported on this device.";
553     return false;
554   }
555   for (auto& group : groups_) {
556     for (auto& selection : group.selections) {
557       selection.event_attr.sample_type |=
558           PERF_SAMPLE_CALLCHAIN | PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER;
559       selection.event_attr.exclude_callchain_user = 1;
560       selection.event_attr.sample_regs_user = GetSupportedRegMask(GetMachineArch());
561       selection.event_attr.sample_stack_user = dump_stack_size;
562     }
563   }
564   return true;
565 }
566 
SetInherit(bool enable)567 void EventSelectionSet::SetInherit(bool enable) {
568   for (auto& group : groups_) {
569     for (auto& selection : group.selections) {
570       selection.event_attr.inherit = (enable ? 1 : 0);
571     }
572   }
573 }
574 
SetClockId(int clock_id)575 void EventSelectionSet::SetClockId(int clock_id) {
576   for (auto& group : groups_) {
577     for (auto& selection : group.selections) {
578       selection.event_attr.use_clockid = 1;
579       selection.event_attr.clockid = clock_id;
580     }
581   }
582 }
583 
NeedKernelSymbol() const584 bool EventSelectionSet::NeedKernelSymbol() const {
585   return !ExcludeKernel();
586 }
587 
SetRecordNotExecutableMaps(bool record)588 void EventSelectionSet::SetRecordNotExecutableMaps(bool record) {
589   // We only need to dump non-executable mmap records for the first event type.
590   groups_[0].selections[0].event_attr.mmap_data = record ? 1 : 0;
591 }
592 
RecordNotExecutableMaps() const593 bool EventSelectionSet::RecordNotExecutableMaps() const {
594   return groups_[0].selections[0].event_attr.mmap_data == 1;
595 }
596 
EnableSwitchRecord()597 void EventSelectionSet::EnableSwitchRecord() {
598   groups_[0].selections[0].event_attr.context_switch = 1;
599 }
600 
WakeupPerSample()601 void EventSelectionSet::WakeupPerSample() {
602   for (auto& group : groups_) {
603     for (auto& selection : group.selections) {
604       selection.event_attr.watermark = 0;
605       selection.event_attr.wakeup_events = 1;
606     }
607   }
608 }
609 
SetTracepointFilter(const std::string & filter)610 bool EventSelectionSet::SetTracepointFilter(const std::string& filter) {
611   // 1. Find the tracepoint event to set filter.
612   EventSelection* selection = nullptr;
613   if (!groups_.empty()) {
614     auto& group = groups_.back();
615     if (group.selections.size() == 1) {
616       if (group.selections[0].event_attr.type == PERF_TYPE_TRACEPOINT) {
617         selection = &group.selections[0];
618       }
619     }
620   }
621   if (selection == nullptr) {
622     LOG(ERROR) << "No tracepoint event before filter: " << filter;
623     return false;
624   }
625 
626   // 2. Check the format of the filter.
627   bool use_quote = false;
628   // Quotes are needed for string operands in kernel >= 4.19, probably after patch "tracing: Rewrite
629   // filter logic to be simpler and faster".
630   if (auto version = GetKernelVersion(); version && version.value() >= std::make_pair(4, 19)) {
631     use_quote = true;
632   }
633 
634   FieldNameSet used_fields;
635   auto adjusted_filter = AdjustTracepointFilter(filter, use_quote, &used_fields);
636   if (!adjusted_filter) {
637     return false;
638   }
639 
640   // 3. Check if used fields are available in the tracepoint event.
641   auto& event_type = selection->event_type_modifier.event_type;
642   if (auto opt_fields = GetFieldNamesForTracepointEvent(event_type); opt_fields) {
643     FieldNameSet& fields = opt_fields.value();
644     for (const auto& field : used_fields) {
645       if (fields.find(field) == fields.end()) {
646         LOG(ERROR) << "field name " << field << " used in \"" << filter << "\" doesn't exist in "
647                    << event_type.name << ". Available fields are "
648                    << android::base::Join(fields, ",");
649         return false;
650       }
651     }
652   }
653 
654   // 4. Connect the filter to the event.
655   selection->tracepoint_filter = adjusted_filter.value();
656   return true;
657 }
658 
OpenEventFilesOnGroup(EventSelectionGroup & group,pid_t tid,int cpu,std::string * failed_event_type)659 bool EventSelectionSet::OpenEventFilesOnGroup(EventSelectionGroup& group, pid_t tid, int cpu,
660                                               std::string* failed_event_type) {
661   std::vector<std::unique_ptr<EventFd>> event_fds;
662   // Given a tid and cpu, events on the same group should be all opened
663   // successfully or all failed to open.
664   EventFd* group_fd = nullptr;
665   for (auto& selection : group.selections) {
666     std::unique_ptr<EventFd> event_fd = EventFd::OpenEventFile(
667         selection.event_attr, tid, cpu, group_fd, selection.event_type_modifier.name, false);
668     if (!event_fd) {
669       *failed_event_type = selection.event_type_modifier.name;
670       return false;
671     }
672     LOG(VERBOSE) << "OpenEventFile for " << event_fd->Name();
673     event_fds.emplace_back(std::move(event_fd));
674     if (group_fd == nullptr) {
675       group_fd = event_fds.back().get();
676     }
677   }
678   for (size_t i = 0; i < group.selections.size(); ++i) {
679     group.selections[i].event_fds.emplace_back(std::move(event_fds[i]));
680   }
681   return true;
682 }
683 
PrepareThreads(const std::set<pid_t> & processes,const std::set<pid_t> & threads)684 static std::set<pid_t> PrepareThreads(const std::set<pid_t>& processes,
685                                       const std::set<pid_t>& threads) {
686   std::set<pid_t> result = threads;
687   for (auto& pid : processes) {
688     std::vector<pid_t> tids = GetThreadsInProcess(pid);
689     result.insert(tids.begin(), tids.end());
690   }
691   return result;
692 }
693 
OpenEventFiles()694 bool EventSelectionSet::OpenEventFiles() {
695   std::vector<int> online_cpus = GetOnlineCpus();
696 
697   auto check_if_cpus_online = [&](const std::vector<int>& cpus) {
698     if (cpus.size() == 1 && cpus[0] == -1) {
699       return true;
700     }
701     for (int cpu : cpus) {
702       if (std::find(online_cpus.begin(), online_cpus.end(), cpu) == online_cpus.end()) {
703         LOG(ERROR) << "cpu " << cpu << " is not online.";
704         return false;
705       }
706     }
707     return true;
708   };
709 
710   std::set<pid_t> threads = PrepareThreads(processes_, threads_);
711   for (auto& group : groups_) {
712     const std::vector<int>* pcpus = &group.cpus;
713     if (!group.selections[0].allowed_cpus.empty()) {
714       // override cpu list if event's PMU has a cpumask as those PMUs are
715       // agnostic to cpu and it's meaningless to specify cpus for them.
716       pcpus = &group.selections[0].allowed_cpus;
717     }
718     if (pcpus->empty()) {
719       pcpus = &online_cpus;
720     } else if (!check_if_cpus_online(*pcpus)) {
721       return false;
722     }
723 
724     size_t success_count = 0;
725     std::string failed_event_type;
726     for (const auto tid : threads) {
727       for (const auto& cpu : *pcpus) {
728         if (OpenEventFilesOnGroup(group, tid, cpu, &failed_event_type)) {
729           success_count++;
730         }
731       }
732     }
733     // We can't guarantee to open perf event file successfully for each thread on each cpu.
734     // Because threads may exit between PrepareThreads() and OpenEventFilesOnGroup(), and
735     // cpus may be offlined between GetOnlineCpus() and OpenEventFilesOnGroup().
736     // So we only check that we can at least monitor one thread for each event group.
737     if (success_count == 0) {
738       int error_number = errno;
739       PLOG(ERROR) << "failed to open perf event file for event_type " << failed_event_type;
740       if (error_number == EMFILE) {
741         LOG(ERROR) << "Please increase hard limit of open file numbers.";
742       }
743       return false;
744     }
745   }
746   return ApplyFilters();
747 }
748 
ApplyFilters()749 bool EventSelectionSet::ApplyFilters() {
750   return ApplyAddrFilters() && ApplyTracepointFilters();
751 }
752 
ApplyAddrFilters()753 bool EventSelectionSet::ApplyAddrFilters() {
754   if (addr_filters_.empty()) {
755     return true;
756   }
757   if (!has_aux_trace_) {
758     LOG(ERROR) << "addr filters only take effect in cs-etm instruction tracing";
759     return false;
760   }
761 
762   // Check filter count limit.
763   size_t required_etm_filter_count = 0;
764   for (auto& filter : addr_filters_) {
765     // A range filter needs two etm filters.
766     required_etm_filter_count +=
767         (filter.type == AddrFilter::FILE_RANGE || filter.type == AddrFilter::KERNEL_RANGE) ? 2 : 1;
768   }
769   size_t etm_filter_count = ETMRecorder::GetInstance().GetAddrFilterPairs() * 2;
770   if (etm_filter_count < required_etm_filter_count) {
771     LOG(ERROR) << "needed " << required_etm_filter_count << " etm filters, but only "
772                << etm_filter_count << " filters are available.";
773     return false;
774   }
775 
776   std::string filter_str;
777   for (auto& filter : addr_filters_) {
778     if (!filter_str.empty()) {
779       filter_str += ',';
780     }
781     filter_str += filter.ToString();
782   }
783 
784   for (auto& group : groups_) {
785     for (auto& selection : group.selections) {
786       if (IsEtmEventType(selection.event_type_modifier.event_type.type)) {
787         for (auto& event_fd : selection.event_fds) {
788           if (!event_fd->SetFilter(filter_str)) {
789             return false;
790           }
791         }
792       }
793     }
794   }
795   return true;
796 }
797 
ApplyTracepointFilters()798 bool EventSelectionSet::ApplyTracepointFilters() {
799   for (auto& group : groups_) {
800     for (auto& selection : group.selections) {
801       if (!selection.tracepoint_filter.empty()) {
802         for (auto& event_fd : selection.event_fds) {
803           if (!event_fd->SetFilter(selection.tracepoint_filter)) {
804             return false;
805           }
806         }
807       }
808     }
809   }
810   return true;
811 }
812 
ReadCounter(EventFd * event_fd,CounterInfo * counter)813 static bool ReadCounter(EventFd* event_fd, CounterInfo* counter) {
814   if (!event_fd->ReadCounter(&counter->counter)) {
815     return false;
816   }
817   counter->tid = event_fd->ThreadId();
818   counter->cpu = event_fd->Cpu();
819   return true;
820 }
821 
ReadCounters(std::vector<CountersInfo> * counters)822 bool EventSelectionSet::ReadCounters(std::vector<CountersInfo>* counters) {
823   counters->clear();
824   for (size_t i = 0; i < groups_.size(); ++i) {
825     for (auto& selection : groups_[i].selections) {
826       CountersInfo counters_info;
827       counters_info.group_id = i;
828       counters_info.event_name = selection.event_type_modifier.event_type.name;
829       counters_info.event_modifier = selection.event_type_modifier.modifier;
830       counters_info.counters = selection.hotplugged_counters;
831       for (auto& event_fd : selection.event_fds) {
832         CounterInfo counter;
833         if (!ReadCounter(event_fd.get(), &counter)) {
834           return false;
835         }
836         counters_info.counters.push_back(counter);
837       }
838       counters->push_back(counters_info);
839     }
840   }
841   return true;
842 }
843 
MmapEventFiles(size_t min_mmap_pages,size_t max_mmap_pages,size_t aux_buffer_size,size_t record_buffer_size,bool allow_truncating_samples,bool exclude_perf)844 bool EventSelectionSet::MmapEventFiles(size_t min_mmap_pages, size_t max_mmap_pages,
845                                        size_t aux_buffer_size, size_t record_buffer_size,
846                                        bool allow_truncating_samples, bool exclude_perf) {
847   record_read_thread_.reset(new simpleperf::RecordReadThread(
848       record_buffer_size, groups_[0].selections[0].event_attr, min_mmap_pages, max_mmap_pages,
849       aux_buffer_size, allow_truncating_samples, exclude_perf));
850   return true;
851 }
852 
PrepareToReadMmapEventData(const std::function<bool (Record *)> & callback)853 bool EventSelectionSet::PrepareToReadMmapEventData(const std::function<bool(Record*)>& callback) {
854   // Prepare record callback function.
855   record_callback_ = callback;
856   if (!record_read_thread_->RegisterDataCallback(*loop_,
857                                                  [this]() { return ReadMmapEventData(true); })) {
858     return false;
859   }
860   std::vector<EventFd*> event_fds;
861   for (auto& group : groups_) {
862     for (auto& selection : group.selections) {
863       for (auto& event_fd : selection.event_fds) {
864         event_fds.push_back(event_fd.get());
865       }
866     }
867   }
868   return record_read_thread_->AddEventFds(event_fds);
869 }
870 
SyncKernelBuffer()871 bool EventSelectionSet::SyncKernelBuffer() {
872   return record_read_thread_->SyncKernelBuffer();
873 }
874 
875 // Read records from the RecordBuffer. If with_time_limit is false, read until the RecordBuffer is
876 // empty, otherwise stop after 100 ms or when the record buffer is empty.
ReadMmapEventData(bool with_time_limit)877 bool EventSelectionSet::ReadMmapEventData(bool with_time_limit) {
878   uint64_t start_time_in_ns;
879   if (with_time_limit) {
880     start_time_in_ns = GetSystemClock();
881   }
882   std::unique_ptr<Record> r;
883   while ((r = record_read_thread_->GetRecord()) != nullptr) {
884     if (!record_callback_(r.get())) {
885       return false;
886     }
887     if (with_time_limit && (GetSystemClock() - start_time_in_ns) >= 1e8) {
888       break;
889     }
890   }
891   return true;
892 }
893 
FinishReadMmapEventData()894 bool EventSelectionSet::FinishReadMmapEventData() {
895   return ReadMmapEventData(false);
896 }
897 
CloseEventFiles()898 void EventSelectionSet::CloseEventFiles() {
899   if (record_read_thread_) {
900     record_read_thread_->StopReadThread();
901   }
902   for (auto& group : groups_) {
903     for (auto& event : group.selections) {
904       event.event_fds.clear();
905     }
906   }
907 }
908 
StopWhenNoMoreTargets(double check_interval_in_sec)909 bool EventSelectionSet::StopWhenNoMoreTargets(double check_interval_in_sec) {
910   return loop_->AddPeriodicEvent(SecondToTimeval(check_interval_in_sec),
911                                  [&]() { return CheckMonitoredTargets(); });
912 }
913 
CheckMonitoredTargets()914 bool EventSelectionSet::CheckMonitoredTargets() {
915   if (!HasSampler()) {
916     return loop_->ExitLoop();
917   }
918   for (const auto& tid : threads_) {
919     if (IsThreadAlive(tid)) {
920       return true;
921     }
922   }
923   for (const auto& pid : processes_) {
924     if (IsThreadAlive(pid)) {
925       return true;
926     }
927   }
928   return loop_->ExitLoop();
929 }
930 
HasSampler()931 bool EventSelectionSet::HasSampler() {
932   for (auto& group : groups_) {
933     for (auto& sel : group.selections) {
934       if (!sel.event_fds.empty()) {
935         return true;
936       }
937     }
938   }
939   return false;
940 }
941 
SetEnableEvents(bool enable)942 bool EventSelectionSet::SetEnableEvents(bool enable) {
943   for (auto& group : groups_) {
944     for (auto& sel : group.selections) {
945       for (auto& fd : sel.event_fds) {
946         if (!fd->SetEnableEvent(enable)) {
947           return false;
948         }
949       }
950     }
951   }
952   return true;
953 }
954 
EnableETMEvents()955 bool EventSelectionSet::EnableETMEvents() {
956   for (auto& group : groups_) {
957     for (auto& sel : group.selections) {
958       if (!sel.event_type_modifier.event_type.IsEtmEvent()) {
959         continue;
960       }
961       for (auto& fd : sel.event_fds) {
962         if (!fd->SetEnableEvent(true)) {
963           return false;
964         }
965       }
966     }
967   }
968   return true;
969 }
970 
DisableETMEvents()971 bool EventSelectionSet::DisableETMEvents() {
972   for (auto& group : groups_) {
973     for (auto& sel : group.selections) {
974       if (!sel.event_type_modifier.event_type.IsEtmEvent()) {
975         continue;
976       }
977       // When using ETR, ETM data is flushed to the aux buffer of the last cpu disabling ETM events.
978       // To avoid overflowing the aux buffer for one cpu, rotate the last cpu disabling ETM events.
979       if (etm_event_cpus_.empty()) {
980         for (const auto& fd : sel.event_fds) {
981           etm_event_cpus_.insert(fd->Cpu());
982         }
983         if (etm_event_cpus_.empty()) {
984           continue;
985         }
986         etm_event_cpus_it_ = etm_event_cpus_.begin();
987       }
988       int last_disabled_cpu = *etm_event_cpus_it_;
989       if (++etm_event_cpus_it_ == etm_event_cpus_.end()) {
990         etm_event_cpus_it_ = etm_event_cpus_.begin();
991       }
992 
993       for (auto& fd : sel.event_fds) {
994         if (fd->Cpu() != last_disabled_cpu) {
995           if (!fd->SetEnableEvent(false)) {
996             return false;
997           }
998         }
999       }
1000       for (auto& fd : sel.event_fds) {
1001         if (fd->Cpu() == last_disabled_cpu) {
1002           if (!fd->SetEnableEvent(false)) {
1003             return false;
1004           }
1005         }
1006       }
1007     }
1008   }
1009   return true;
1010 }
1011 
1012 }  // namespace simpleperf
1013