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 "event_attr.h"
29 #include "event_fd.h"
30 #include "event_type.h"
31 #include "InplaceSamplerClient.h"
32 #include "IOEventLoop.h"
33 #include "perf_event.h"
34 #include "record.h"
35 #include "RecordReadThread.h"
36 
37 constexpr double DEFAULT_PERIOD_TO_DETECT_CPU_HOTPLUG_EVENTS_IN_SEC = 0.5;
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 // EventSelectionSet helps to monitor events. It is used in following steps:
70 // 1. Create an EventSelectionSet, and add event types to monitor by calling
71 //    AddEventType() or AddEventGroup().
72 // 2. Define how to monitor events by calling SetEnableOnExec(), SampleIdAll(),
73 //    SetSampleFreq(), etc.
74 // 3. Start monitoring by calling OpenEventFilesForCpus() or
75 //    OpenEventFilesForThreadsOnCpus(). If SetEnableOnExec() has been called
76 //    in step 2, monitor will be delayed until the monitored thread calls
77 //    exec().
78 // 4. Read counters by calling ReadCounters(), or read mapped event records
79 //    by calling MmapEventFiles(), PrepareToReadMmapEventData() and
80 //    FinishReadMmapEventData().
81 // 5. Stop monitoring automatically in the destructor of EventSelectionSet by
82 //    closing perf event files.
83 
84 class EventSelectionSet {
85  public:
86   EventSelectionSet(bool for_stat_cmd);
87   ~EventSelectionSet();
88 
empty()89   bool empty() const { return groups_.empty(); }
90 
91   bool AddEventType(const std::string& event_name, size_t* group_id = nullptr);
92   bool AddEventGroup(const std::vector<std::string>& event_names, size_t* group_id = nullptr);
93   std::vector<const EventType*> GetEvents() const;
94   std::vector<const EventType*> GetTracepointEvents() const;
95   bool ExcludeKernel() const;
HasAuxTrace()96   bool HasAuxTrace() const { return has_aux_trace_; }
97   bool HasInplaceSampler() const;
98   std::vector<EventAttrWithId> GetEventAttrWithId() const;
99 
100   void SetEnableOnExec(bool enable);
101   bool GetEnableOnExec();
102   void SampleIdAll();
103   void SetSampleSpeed(size_t group_id, const SampleSpeed& speed);
104   bool SetBranchSampling(uint64_t branch_sample_type);
105   void EnableFpCallChainSampling();
106   bool EnableDwarfCallChainSampling(uint32_t dump_stack_size);
107   void SetInherit(bool enable);
108   void SetClockId(int clock_id);
109   bool NeedKernelSymbol() const;
110   void SetRecordNotExecutableMaps(bool record);
111   bool RecordNotExecutableMaps() const;
SetIncludeFilters(std::vector<std::string> && filters)112   void SetIncludeFilters(std::vector<std::string>&& filters) {
113     include_filters_ = std::move(filters);
114   }
115 
AddMonitoredProcesses(const std::set<pid_t> & processes)116   void AddMonitoredProcesses(const std::set<pid_t>& processes) {
117     processes_.insert(processes.begin(), processes.end());
118   }
119 
AddMonitoredThreads(const std::set<pid_t> & threads)120   void AddMonitoredThreads(const std::set<pid_t>& threads) {
121     threads_.insert(threads.begin(), threads.end());
122   }
123 
GetMonitoredProcesses()124   const std::set<pid_t>& GetMonitoredProcesses() const { return processes_; }
125 
GetMonitoredThreads()126   const std::set<pid_t>& GetMonitoredThreads() const { return threads_; }
127 
HasMonitoredTarget()128   bool HasMonitoredTarget() const {
129     return !processes_.empty() || !threads_.empty();
130   }
131 
GetIOEventLoop()132   IOEventLoop* GetIOEventLoop() {
133     return loop_.get();
134   }
135 
136   bool OpenEventFiles(const std::vector<int>& on_cpus);
137   bool ReadCounters(std::vector<CountersInfo>* counters);
138   bool MmapEventFiles(size_t min_mmap_pages, size_t max_mmap_pages, size_t aux_buffer_size,
139                       size_t record_buffer_size, bool allow_cutting_samples);
140   bool PrepareToReadMmapEventData(const std::function<bool(Record*)>& callback);
141   bool SyncKernelBuffer();
142   bool FinishReadMmapEventData();
143 
GetRecordStat()144   const simpleperf::RecordStat& GetRecordStat() {
145     return record_read_thread_->GetStat();
146   }
147 
148   // If monitored_cpus is empty, monitor all cpus.
149   bool HandleCpuHotplugEvents(const std::vector<int>& monitored_cpus,
150                               double check_interval_in_sec =
151                                   DEFAULT_PERIOD_TO_DETECT_CPU_HOTPLUG_EVENTS_IN_SEC);
152 
153   // Stop profiling if all monitored processes/threads don't exist.
154   bool StopWhenNoMoreTargets(double check_interval_in_sec =
155                                  DEFAULT_PERIOD_TO_CHECK_MONITORED_TARGETS_IN_SEC);
156 
157   bool SetEnableEvents(bool enable);
158 
159  private:
160   struct EventSelection {
161     EventTypeAndModifier event_type_modifier;
162     perf_event_attr event_attr;
163     std::vector<std::unique_ptr<EventFd>> event_fds;
164     std::vector<std::unique_ptr<InplaceSamplerClient>> inplace_samplers;
165     // counters for event files closed for cpu hotplug events
166     std::vector<CounterInfo> hotplugged_counters;
167   };
168   typedef std::vector<EventSelection> EventSelectionGroup;
169 
170   bool BuildAndCheckEventSelection(const std::string& event_name, bool first_event,
171                                    EventSelection* selection);
172   void UnionSampleType();
173   bool IsUserSpaceSamplerGroup(EventSelectionGroup& group);
174   bool OpenUserSpaceSamplersOnGroup(EventSelectionGroup& group,
175                                     const std::map<pid_t, std::set<pid_t>>& process_map);
176   bool OpenEventFilesOnGroup(EventSelectionGroup& group, pid_t tid, int cpu,
177                              std::string* failed_event_type);
178   bool ApplyFilters();
179   bool ReadMmapEventData(bool with_time_limit);
180 
181   bool DetectCpuHotplugEvents();
182   bool HandleCpuOnlineEvent(int cpu);
183   bool HandleCpuOfflineEvent(int cpu);
184   bool CreateMappedBufferForCpu(int cpu);
185   bool CheckMonitoredTargets();
186   bool HasSampler();
187 
188   const bool for_stat_cmd_;
189 
190   std::vector<EventSelectionGroup> groups_;
191   std::set<pid_t> processes_;
192   std::set<pid_t> threads_;
193 
194   std::unique_ptr<IOEventLoop> loop_;
195   std::function<bool(Record*)> record_callback_;
196 
197   std::set<int> monitored_cpus_;
198   std::vector<int> online_cpus_;
199 
200   std::unique_ptr<simpleperf::RecordReadThread> record_read_thread_;
201 
202   bool has_aux_trace_ = false;
203   std::vector<std::string> include_filters_;
204 
205   DISALLOW_COPY_AND_ASSIGN(EventSelectionSet);
206 };
207 
208 bool IsBranchSamplingSupported();
209 bool IsDwarfCallChainSamplingSupported();
210 bool IsDumpingRegsForTracepointEventsSupported();
211 bool IsSettingClockIdSupported();
212 bool IsMmap2Supported();
213 
214 #endif  // SIMPLE_PERF_EVENT_SELECTION_SET_H_
215