• 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 #define ATRACE_TAG ATRACE_TAG_ALWAYS
17 #include "event_fd.h"
18 
19 #include <cutils/trace.h>
20 #include <fcntl.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <sys/ioctl.h>
24 #include <sys/mman.h>
25 #include <sys/syscall.h>
26 #include <sys/types.h>
27 #include <utils/Trace.h>
28 #include <atomic>
29 #include <memory>
30 
31 #include <android-base/file.h>
32 #include <android-base/logging.h>
33 #include <android-base/stringprintf.h>
34 
35 #include "environment.h"
36 #include "event_attr.h"
37 #include "event_type.h"
38 #include "perf_event.h"
39 #include "utils.h"
40 
41 namespace simpleperf {
42 
perf_event_open(const perf_event_attr & attr,pid_t pid,int cpu,int group_fd,unsigned long flags)43 static int perf_event_open(const perf_event_attr& attr, pid_t pid, int cpu, int group_fd,
44                            unsigned long flags) {  // NOLINT
45   return syscall(__NR_perf_event_open, &attr, pid, cpu, group_fd, flags);
46 }
47 
OpenEventFile(const perf_event_attr & attr,pid_t tid,int cpu,EventFd * group_event_fd,const std::string & event_name,bool report_error)48 std::unique_ptr<EventFd> EventFd::OpenEventFile(const perf_event_attr& attr, pid_t tid, int cpu,
49                                                 EventFd* group_event_fd,
50                                                 const std::string& event_name, bool report_error) {
51   int group_fd = -1;
52   if (group_event_fd != nullptr) {
53     group_fd = group_event_fd->perf_event_fd_;
54   }
55   perf_event_attr real_attr = attr;
56   if (attr.freq) {
57     uint64_t max_sample_freq;
58     if (GetMaxSampleFrequency(&max_sample_freq) && max_sample_freq < attr.sample_freq) {
59       static bool warned = false;
60       if (!warned) {
61         warned = true;
62         LOG(INFO) << "Adjust sample freq to max allowed sample freq " << max_sample_freq;
63       }
64       real_attr.sample_freq = max_sample_freq;
65     }
66   }
67   int perf_event_fd = perf_event_open(real_attr, tid, cpu, group_fd, 0);
68   if (perf_event_fd == -1) {
69     if (report_error) {
70       PLOG(ERROR) << "open perf_event_file (event " << event_name << ", tid " << tid << ", cpu "
71                   << cpu << ", group_fd " << group_fd << ") failed";
72     } else {
73       PLOG(DEBUG) << "open perf_event_file (event " << event_name << ", tid " << tid << ", cpu "
74                   << cpu << ", group_fd " << group_fd << ") failed";
75     }
76     return nullptr;
77   }
78   if (fcntl(perf_event_fd, F_SETFD, FD_CLOEXEC) == -1) {
79     if (report_error) {
80       PLOG(ERROR) << "fcntl(FD_CLOEXEC) for perf_event_file (event " << event_name << ", tid "
81                   << tid << ", cpu " << cpu << ", group_fd " << group_fd << ") failed";
82     } else {
83       PLOG(DEBUG) << "fcntl(FD_CLOEXEC) for perf_event_file (event " << event_name << ", tid "
84                   << tid << ", cpu " << cpu << ", group_fd " << group_fd << ") failed";
85     }
86     return nullptr;
87   }
88   return std::unique_ptr<EventFd>(new EventFd(real_attr, perf_event_fd, event_name, tid, cpu));
89 }
90 
~EventFd()91 EventFd::~EventFd() {
92   DestroyMappedBuffer();
93   DestroyAuxBuffer();
94   close(perf_event_fd_);
95 }
96 
Name() const97 std::string EventFd::Name() const {
98   return android::base::StringPrintf("perf_event_file(event %s, tid %d, cpu %d)",
99                                      event_name_.c_str(), tid_, cpu_);
100 }
101 
Id() const102 uint64_t EventFd::Id() const {
103   if (id_ == 0) {
104     if (ioctl(perf_event_fd_, PERF_EVENT_IOC_ID, &id_) != 0) {
105       // PERF_EVENT_IOC_ID isn't available in kernel <= 3.10. Fallback to read() in this case.
106       PerfCounter counter;
107       if (InnerReadCounter(&counter)) {
108         id_ = counter.id;
109       } else {
110         PLOG(WARNING) << "failed to get id of event_fd";
111       }
112     }
113   }
114   return id_;
115 }
116 
SetEnableEvent(bool enable)117 bool EventFd::SetEnableEvent(bool enable) {
118   int result = ioctl(perf_event_fd_, enable ? PERF_EVENT_IOC_ENABLE : PERF_EVENT_IOC_DISABLE, 0);
119   if (result < 0) {
120     PLOG(ERROR) << "ioctl(" << (enable ? "enable" : "disable") << ")" << Name() << " failed";
121     return false;
122   }
123   return true;
124 }
125 
SetFilter(const std::string & filter)126 bool EventFd::SetFilter(const std::string& filter) {
127   bool success = ioctl(perf_event_fd_, PERF_EVENT_IOC_SET_FILTER, filter.c_str()) >= 0;
128   if (!success) {
129     PLOG(ERROR) << "failed to set filter";
130   }
131   return success;
132 }
133 
InnerReadCounter(PerfCounter * counter) const134 bool EventFd::InnerReadCounter(PerfCounter* counter) const {
135   CHECK(counter != nullptr);
136   if (!android::base::ReadFully(perf_event_fd_, counter, sizeof(*counter))) {
137     PLOG(ERROR) << "ReadCounter from " << Name() << " failed";
138     return false;
139   }
140   return true;
141 }
142 
ReadCounter(PerfCounter * counter)143 bool EventFd::ReadCounter(PerfCounter* counter) {
144   if (!InnerReadCounter(counter)) {
145     return false;
146   }
147   // Trace is always available to systrace if enabled
148   if (tid_ > 0) {
149     ATRACE_INT64(
150         android::base::StringPrintf("%s_tid%d_cpu%d", event_name_.c_str(), tid_, cpu_).c_str(),
151         counter->value - last_counter_value_);
152   } else {
153     ATRACE_INT64(android::base::StringPrintf("%s_cpu%d", event_name_.c_str(), cpu_).c_str(),
154                  counter->value - last_counter_value_);
155   }
156   last_counter_value_ = counter->value;
157   return true;
158 }
159 
CreateMappedBuffer(size_t mmap_pages,bool report_error)160 bool EventFd::CreateMappedBuffer(size_t mmap_pages, bool report_error) {
161   CHECK(IsPowerOfTwo(mmap_pages));
162   size_t page_size = sysconf(_SC_PAGE_SIZE);
163   size_t mmap_len = (mmap_pages + 1) * page_size;
164   void* mmap_addr = mmap(nullptr, mmap_len, PROT_READ | PROT_WRITE, MAP_SHARED, perf_event_fd_, 0);
165   if (mmap_addr == MAP_FAILED) {
166     bool is_perm_error = (errno == EPERM);
167     if (report_error) {
168       PLOG(ERROR) << "mmap(" << mmap_pages << ") failed for " << Name();
169     } else {
170       PLOG(DEBUG) << "mmap(" << mmap_pages << ") failed for " << Name();
171     }
172     if (report_error && is_perm_error) {
173       LOG(ERROR) << "It seems the kernel doesn't allow allocating enough "
174                  << "buffer for dumping samples, consider decreasing mmap pages(-m).";
175     }
176     return false;
177   }
178   mmap_addr_ = mmap_addr;
179   mmap_len_ = mmap_len;
180   mmap_metadata_page_ = reinterpret_cast<perf_event_mmap_page*>(mmap_addr_);
181   mmap_data_buffer_ = reinterpret_cast<char*>(mmap_addr_) + page_size;
182   mmap_data_buffer_size_ = mmap_len_ - page_size;
183   return true;
184 }
185 
ShareMappedBuffer(const EventFd & event_fd,bool report_error)186 bool EventFd::ShareMappedBuffer(const EventFd& event_fd, bool report_error) {
187   CHECK(!HasMappedBuffer());
188   CHECK(event_fd.HasMappedBuffer());
189   int result = ioctl(perf_event_fd_, PERF_EVENT_IOC_SET_OUTPUT, event_fd.perf_event_fd_);
190   if (result != 0) {
191     if (report_error) {
192       PLOG(ERROR) << "failed to share mapped buffer of " << event_fd.perf_event_fd_ << " with "
193                   << perf_event_fd_;
194     }
195     return false;
196   }
197   return true;
198 }
199 
DestroyMappedBuffer()200 void EventFd::DestroyMappedBuffer() {
201   if (HasMappedBuffer()) {
202     munmap(mmap_addr_, mmap_len_);
203     mmap_addr_ = nullptr;
204     mmap_len_ = 0;
205     mmap_metadata_page_ = nullptr;
206     mmap_data_buffer_ = nullptr;
207     mmap_data_buffer_size_ = 0;
208   }
209 }
210 
GetAvailableMmapData()211 std::vector<char> EventFd::GetAvailableMmapData() {
212   size_t data_pos;
213   size_t data_size = GetAvailableMmapDataSize(data_pos);
214   std::vector<char> data(data_size);
215   if (data_size > 0) {
216     size_t copy_size = std::min(data_size, mmap_data_buffer_size_ - data_pos);
217     memcpy(&data[0], mmap_data_buffer_ + data_pos, copy_size);
218     if (copy_size < data_size) {
219       memcpy(&data[copy_size], mmap_data_buffer_, data_size - copy_size);
220     }
221     DiscardMmapData(data_size);
222   }
223   return data;
224 }
225 
GetAvailableMmapDataSize(size_t & data_pos)226 size_t EventFd::GetAvailableMmapDataSize(size_t& data_pos) {
227   // The mmap_data_buffer is used as a ring buffer between the kernel and
228   // simpleperf. The kernel continuously writes records to the buffer, and
229   // simpleperf continuously read records out.
230   //         _________________________________________
231   // buffer | can write   |   can read   |  can write |
232   //                      ^              ^
233   //                    read_head       write_head
234   //
235   // So simpleperf can read records in [read_head, write_head), and the kernel
236   // can write records in [write_head, read_head). The kernel is responsible
237   // for updating write_head, and simpleperf is responsible for updating
238   // read_head.
239 
240   uint64_t write_head = mmap_metadata_page_->data_head;
241   uint64_t read_head = mmap_metadata_page_->data_tail;
242   // The kernel may decrease data_head temporarily (http://b/132446871), making
243   // write_head < read_head. So check it to avoid available data size underflow.
244   if (write_head <= read_head) {
245     // No available data.
246     return 0;
247   }
248   // rmb() used to ensure reading data after reading data_head.
249   __sync_synchronize();
250   data_pos = read_head & (mmap_data_buffer_size_ - 1);
251   return write_head - read_head;
252 }
253 
DiscardMmapData(size_t discard_size)254 void EventFd::DiscardMmapData(size_t discard_size) {
255   // mb() used to ensure finish reading data before writing data_tail.
256   __sync_synchronize();
257   mmap_metadata_page_->data_tail += discard_size;
258 }
259 
CreateAuxBuffer(size_t aux_buffer_size,bool report_error)260 bool EventFd::CreateAuxBuffer(size_t aux_buffer_size, bool report_error) {
261   CHECK(HasMappedBuffer());
262   CHECK(IsPowerOfTwo(aux_buffer_size));
263   mmap_metadata_page_->aux_offset = mmap_len_;
264   mmap_metadata_page_->aux_size = aux_buffer_size;
265   mmap_metadata_page_->aux_head = 0;
266   mmap_metadata_page_->aux_tail = 0;
267   void* mmap_addr = mmap(nullptr, aux_buffer_size, PROT_READ | PROT_WRITE, MAP_SHARED,
268                          perf_event_fd_, mmap_metadata_page_->aux_offset);
269   if (mmap_addr == MAP_FAILED) {
270     if (report_error) {
271       PLOG(ERROR) << "failed to mmap aux buffer of size " << aux_buffer_size << " for " << Name();
272     } else {
273       PLOG(DEBUG) << "failed to mmap aux buffer of size " << aux_buffer_size << " for " << Name();
274     }
275     return false;
276   }
277   aux_buffer_ = static_cast<char*>(mmap_addr);
278   aux_buffer_size_ = aux_buffer_size;
279   return true;
280 }
281 
DestroyAuxBuffer()282 void EventFd::DestroyAuxBuffer() {
283   if (HasAuxBuffer()) {
284     munmap(aux_buffer_, aux_buffer_size_);
285     aux_buffer_ = nullptr;
286     aux_buffer_size_ = 0;
287   }
288 }
289 
GetAvailableAuxData(char ** buf1,size_t * size1,char ** buf2,size_t * size2)290 uint64_t EventFd::GetAvailableAuxData(char** buf1, size_t* size1, char** buf2, size_t* size2) {
291   // Aux buffer is similar to mapped_data_buffer. See comments in GetAvailableMmapData().
292   uint64_t write_head = mmap_metadata_page_->aux_head;
293   uint64_t read_head = mmap_metadata_page_->aux_tail;
294   if (write_head <= read_head) {
295     *size1 = *size2 = 0;
296     return 0;  // No available data.
297   }
298   // rmb() used to ensure reading data after reading aux_head.
299   __sync_synchronize();
300   size_t data_pos = read_head & (aux_buffer_size_ - 1);
301   size_t data_size = write_head - read_head;
302   *buf1 = aux_buffer_ + data_pos;
303   if (data_size <= aux_buffer_size_ - data_pos) {
304     *size1 = data_size;
305     *size2 = 0;
306   } else {
307     *size1 = aux_buffer_size_ - data_pos;
308     *buf2 = aux_buffer_;
309     *size2 = data_size - *size1;
310   }
311   return read_head;
312 }
313 
DiscardAuxData(size_t discard_size)314 void EventFd::DiscardAuxData(size_t discard_size) {
315   // mb() used to ensure finish reading data before writing aux_tail.
316   __sync_synchronize();
317   mmap_metadata_page_->aux_tail += discard_size;
318 }
319 
StartPolling(IOEventLoop & loop,const std::function<bool ()> & callback)320 bool EventFd::StartPolling(IOEventLoop& loop, const std::function<bool()>& callback) {
321   ioevent_ref_ = loop.AddReadEvent(perf_event_fd_, callback);
322   return ioevent_ref_ != nullptr;
323 }
324 
StopPolling()325 bool EventFd::StopPolling() {
326   return IOEventLoop::DelEvent(ioevent_ref_);
327 }
328 
IsEventAttrSupported(const perf_event_attr & attr,const std::string & event_name)329 bool IsEventAttrSupported(const perf_event_attr& attr, const std::string& event_name) {
330   return EventFd::OpenEventFile(attr, getpid(), -1, nullptr, event_name, false) != nullptr;
331 }
332 
333 }  // namespace simpleperf
334