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