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 #ifndef SIMPLE_PERF_EVENT_SELECTION_SET_H_
18 #define SIMPLE_PERF_EVENT_SELECTION_SET_H_
19 
20 #include <functional>
21 #include <map>
22 #include <set>
23 #include <unordered_map>
24 #include <vector>
25 
26 #include <android-base/macros.h>
27 
28 #include "IOEventLoop.h"
29 #include "RecordReadThread.h"
30 #include "event_attr.h"
31 #include "event_fd.h"
32 #include "event_type.h"
33 #include "perf_event.h"
34 #include "record.h"
35 
36 namespace simpleperf {
37 
38 constexpr double DEFAULT_PERIOD_TO_CHECK_MONITORED_TARGETS_IN_SEC = 1;
39 constexpr uint64_t DEFAULT_SAMPLE_FREQ_FOR_NONTRACEPOINT_EVENT = 4000;
40 constexpr uint64_t DEFAULT_SAMPLE_PERIOD_FOR_TRACEPOINT_EVENT = 1;
41 
42 struct CounterInfo {
43   pid_t tid;
44   int cpu;
45   PerfCounter counter;
46 };
47 
48 struct CountersInfo {
49   uint32_t group_id;
50   std::string event_name;
51   std::string event_modifier;
52   std::vector<CounterInfo> counters;
53 };
54 
55 struct SampleSpeed {
56   // There are two ways to set sample speed:
57   // 1. sample_freq: take [sample_freq] samples every second.
58   // 2. sample_period: take one sample every [sample_period] events happen.
59   uint64_t sample_freq;
60   uint64_t sample_period;
sample_freqSampleSpeed61   SampleSpeed(uint64_t freq = 0, uint64_t period = 0) : sample_freq(freq), sample_period(period) {}
UseFreqSampleSpeed62   bool UseFreq() const {
63     // Only use one way to set sample speed.
64     CHECK_NE(sample_freq != 0u, sample_period != 0u);
65     return sample_freq != 0u;
66   }
67 };
68 
69 struct AddrFilter {
70   enum Type {
71     FILE_RANGE,
72     FILE_START,
73     FILE_STOP,
74     KERNEL_RANGE,
75     KERNEL_START,
76     KERNEL_STOP,
77   } type;
78   uint64_t addr;
79   uint64_t size;
80   std::string file_path;
81 
AddrFilterAddrFilter82   AddrFilter(AddrFilter::Type type, uint64_t addr, uint64_t size, const std::string& file_path)
83       : type(type), addr(addr), size(size), file_path(file_path) {}
84 
85   std::string ToString() const;
86 };
87 
88 // EventSelectionSet helps to monitor events. It is used in following steps:
89 // 1. Create an EventSelectionSet, and add event types to monitor by calling
90 //    AddEventType() or AddEventGroup().
91 // 2. Define how to monitor events by calling SetEnableOnExec(), SampleIdAll(),
92 //    SetSampleFreq(), etc.
93 // 3. Start monitoring by calling OpenEventFilesForCpus() or
94 //    OpenEventFilesForThreadsOnCpus(). If SetEnableOnExec() has been called
95 //    in step 2, monitor will be delayed until the monitored thread calls
96 //    exec().
97 // 4. Read counters by calling ReadCounters(), or read mapped event records
98 //    by calling MmapEventFiles(), PrepareToReadMmapEventData() and
99 //    FinishReadMmapEventData().
100 // 5. Stop monitoring automatically in the destructor of EventSelectionSet by
101 //    closing perf event files.
102 
103 class EventSelectionSet {
104  public:
105   EventSelectionSet(bool for_stat_cmd);
106   ~EventSelectionSet();
107 
empty()108   bool empty() const { return groups_.empty(); }
109 
110   bool AddEventType(const std::string& event_name, size_t* group_id = nullptr);
111   bool AddEventGroup(const std::vector<std::string>& event_names, size_t* group_id = nullptr);
112   std::vector<const EventType*> GetEvents() const;
113   std::vector<const EventType*> GetTracepointEvents() const;
114   bool ExcludeKernel() const;
HasAuxTrace()115   bool HasAuxTrace() const { return has_aux_trace_; }
116   std::vector<EventAttrWithId> GetEventAttrWithId() const;
117   std::unordered_map<uint64_t, std::string> GetEventNamesById() const;
118 
119   void SetEnableOnExec(bool enable);
120   bool GetEnableOnExec();
121   void SampleIdAll();
122   void SetSampleSpeed(size_t group_id, const SampleSpeed& speed);
123   bool SetBranchSampling(uint64_t branch_sample_type);
124   void EnableFpCallChainSampling();
125   bool EnableDwarfCallChainSampling(uint32_t dump_stack_size);
126   void SetInherit(bool enable);
127   void SetClockId(int clock_id);
128   bool NeedKernelSymbol() const;
129   void SetRecordNotExecutableMaps(bool record);
130   bool RecordNotExecutableMaps() const;
131   void WakeupPerSample();
SetAddrFilters(std::vector<AddrFilter> && filters)132   void SetAddrFilters(std::vector<AddrFilter>&& filters) { addr_filters_ = std::move(filters); }
133   bool SetTracepointFilter(const std::string& filter);
134 
135   template <typename Collection = std::vector<pid_t>>
AddMonitoredProcesses(const Collection & processes)136   void AddMonitoredProcesses(const Collection& processes) {
137     processes_.insert(processes.begin(), processes.end());
138   }
139 
140   template <typename Collection = std::vector<pid_t>>
AddMonitoredThreads(const Collection & threads)141   void AddMonitoredThreads(const Collection& threads) {
142     threads_.insert(threads.begin(), threads.end());
143   }
144 
GetMonitoredProcesses()145   const std::set<pid_t>& GetMonitoredProcesses() const { return processes_; }
146 
GetMonitoredThreads()147   const std::set<pid_t>& GetMonitoredThreads() const { return threads_; }
148 
ClearMonitoredTargets()149   void ClearMonitoredTargets() {
150     processes_.clear();
151     threads_.clear();
152   }
153 
HasMonitoredTarget()154   bool HasMonitoredTarget() const { return !processes_.empty() || !threads_.empty(); }
155 
GetIOEventLoop()156   IOEventLoop* GetIOEventLoop() { return loop_.get(); }
157 
158   // If cpus = {}, monitor on all cpus, with a perf event file for each cpu.
159   // If cpus = {-1}, monitor on all cpus, with a perf event file shared by all cpus.
160   // Otherwise, monitor on selected cpus, with a perf event file for each cpu.
161   bool OpenEventFiles(const std::vector<int>& cpus);
162   bool ReadCounters(std::vector<CountersInfo>* counters);
163   bool MmapEventFiles(size_t min_mmap_pages, size_t max_mmap_pages, size_t aux_buffer_size,
164                       size_t record_buffer_size, bool allow_cutting_samples, bool exclude_perf);
165   bool PrepareToReadMmapEventData(const std::function<bool(Record*)>& callback);
166   bool SyncKernelBuffer();
167   bool FinishReadMmapEventData();
168   void CloseEventFiles();
169 
GetRecordStat()170   const simpleperf::RecordStat& GetRecordStat() { return record_read_thread_->GetStat(); }
171 
172   // Stop profiling if all monitored processes/threads don't exist.
173   bool StopWhenNoMoreTargets(
174       double check_interval_in_sec = DEFAULT_PERIOD_TO_CHECK_MONITORED_TARGETS_IN_SEC);
175 
176   bool SetEnableEvents(bool enable);
177 
178  private:
179   struct EventSelection {
180     EventTypeAndModifier event_type_modifier;
181     perf_event_attr event_attr;
182     std::vector<std::unique_ptr<EventFd>> event_fds;
183     // counters for event files closed for cpu hotplug events
184     std::vector<CounterInfo> hotplugged_counters;
185     std::vector<int> allowed_cpus;
186     std::string tracepoint_filter;
187   };
188   typedef std::vector<EventSelection> EventSelectionGroup;
189 
190   bool BuildAndCheckEventSelection(const std::string& event_name, bool first_event,
191                                    EventSelection* selection);
192   void UnionSampleType();
193   bool OpenEventFilesOnGroup(EventSelectionGroup& group, pid_t tid, int cpu,
194                              std::string* failed_event_type);
195   bool ApplyFilters();
196   bool ApplyAddrFilters();
197   bool ApplyTracepointFilters();
198   bool ReadMmapEventData(bool with_time_limit);
199 
200   bool CheckMonitoredTargets();
201   bool HasSampler();
202 
203   const bool for_stat_cmd_;
204 
205   std::vector<EventSelectionGroup> groups_;
206   std::set<pid_t> processes_;
207   std::set<pid_t> threads_;
208 
209   std::unique_ptr<IOEventLoop> loop_;
210   std::function<bool(Record*)> record_callback_;
211 
212   std::unique_ptr<simpleperf::RecordReadThread> record_read_thread_;
213 
214   bool has_aux_trace_ = false;
215   std::vector<AddrFilter> addr_filters_;
216 
217   DISALLOW_COPY_AND_ASSIGN(EventSelectionSet);
218 };
219 
220 bool IsBranchSamplingSupported();
221 bool IsDwarfCallChainSamplingSupported();
222 bool IsDumpingRegsForTracepointEventsSupported();
223 bool IsSettingClockIdSupported();
224 bool IsMmap2Supported();
225 
226 }  // namespace simpleperf
227 
228 #endif  // SIMPLE_PERF_EVENT_SELECTION_SET_H_
229