• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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 "src/profiling/perf/event_reader.h"
18 
19 #include <linux/perf_event.h>
20 #include <sys/ioctl.h>
21 #include <sys/mman.h>
22 #include <sys/syscall.h>
23 #include <sys/types.h>
24 #include <unistd.h>
25 
26 #include "perfetto/ext/base/utils.h"
27 #include "src/profiling/perf/regs_parsing.h"
28 
29 namespace perfetto {
30 namespace profiling {
31 
32 namespace {
33 
34 template <typename T>
ReadValue(T * value_out,const char * ptr)35 const char* ReadValue(T* value_out, const char* ptr) {
36   memcpy(value_out, reinterpret_cast<const void*>(ptr), sizeof(T));
37   return ptr + sizeof(T);
38 }
39 
40 template <typename T>
ReadValues(T * out,const char * ptr,size_t num_values)41 const char* ReadValues(T* out, const char* ptr, size_t num_values) {
42   size_t sz = sizeof(T) * num_values;
43   memcpy(out, reinterpret_cast<const void*>(ptr), sz);
44   return ptr + sz;
45 }
46 
IsPowerOfTwo(size_t v)47 bool IsPowerOfTwo(size_t v) {
48   return (v != 0 && ((v & (v - 1)) == 0));
49 }
50 
perf_event_open(perf_event_attr * attr,pid_t pid,int cpu,int group_fd,unsigned long flags)51 static int perf_event_open(perf_event_attr* attr,
52                            pid_t pid,
53                            int cpu,
54                            int group_fd,
55                            unsigned long flags) {
56   return static_cast<int>(
57       syscall(__NR_perf_event_open, attr, pid, cpu, group_fd, flags));
58 }
59 
PerfEventOpen(uint32_t cpu,perf_event_attr * perf_attr,int group_fd=-1)60 base::ScopedFile PerfEventOpen(uint32_t cpu,
61                                perf_event_attr* perf_attr,
62                                int group_fd = -1) {
63   base::ScopedFile perf_fd{perf_event_open(perf_attr, /*pid=*/-1,
64                                            static_cast<int>(cpu), group_fd,
65                                            PERF_FLAG_FD_CLOEXEC)};
66   return perf_fd;
67 }
68 
69 // If counting tracepoints, set an event filter if requested.
MaybeApplyTracepointFilter(int fd,const PerfCounter & event)70 bool MaybeApplyTracepointFilter(int fd, const PerfCounter& event) {
71   if (event.type != PerfCounter::Type::kTracepoint ||
72       event.tracepoint_filter.empty()) {
73     return true;
74   }
75   PERFETTO_DCHECK(event.attr_type == PERF_TYPE_TRACEPOINT);
76 
77   if (ioctl(fd, PERF_EVENT_IOC_SET_FILTER, event.tracepoint_filter.c_str())) {
78     PERFETTO_PLOG("Failed ioctl to set event filter");
79     return false;
80   }
81   return true;
82 }
83 
84 }  // namespace
85 
PerfRingBuffer(PerfRingBuffer && other)86 PerfRingBuffer::PerfRingBuffer(PerfRingBuffer&& other) noexcept
87     : metadata_page_(other.metadata_page_),
88       mmap_sz_(other.mmap_sz_),
89       data_buf_(other.data_buf_),
90       data_buf_sz_(other.data_buf_sz_) {
91   other.metadata_page_ = nullptr;
92   other.mmap_sz_ = 0;
93   other.data_buf_ = nullptr;
94   other.data_buf_sz_ = 0;
95 }
96 
operator =(PerfRingBuffer && other)97 PerfRingBuffer& PerfRingBuffer::operator=(PerfRingBuffer&& other) noexcept {
98   if (this == &other)
99     return *this;
100 
101   this->~PerfRingBuffer();
102   new (this) PerfRingBuffer(std::move(other));
103   return *this;
104 }
105 
~PerfRingBuffer()106 PerfRingBuffer::~PerfRingBuffer() {
107   if (!valid())
108     return;
109 
110   if (munmap(reinterpret_cast<void*>(metadata_page_), mmap_sz_) != 0)
111     PERFETTO_PLOG("failed munmap");
112 }
113 
Allocate(int perf_fd,size_t data_page_count)114 base::Optional<PerfRingBuffer> PerfRingBuffer::Allocate(
115     int perf_fd,
116     size_t data_page_count) {
117   // perf_event_open requires the ring buffer to be a power of two in size.
118   PERFETTO_DCHECK(IsPowerOfTwo(data_page_count));
119 
120   PerfRingBuffer ret;
121 
122   // mmap request is one page larger than the buffer size (for the metadata).
123   ret.data_buf_sz_ = data_page_count * base::kPageSize;
124   ret.mmap_sz_ = ret.data_buf_sz_ + base::kPageSize;
125 
126   // If PROT_WRITE, kernel won't overwrite unread samples.
127   void* mmap_addr = mmap(nullptr, ret.mmap_sz_, PROT_READ | PROT_WRITE,
128                          MAP_SHARED, perf_fd, 0);
129   if (mmap_addr == MAP_FAILED) {
130     PERFETTO_PLOG("failed mmap");
131     return base::nullopt;
132   }
133 
134   // Expected layout is [ metadata page ] [ data pages ... ]
135   ret.metadata_page_ = reinterpret_cast<perf_event_mmap_page*>(mmap_addr);
136   ret.data_buf_ = reinterpret_cast<char*>(mmap_addr) + base::kPageSize;
137   PERFETTO_CHECK(ret.metadata_page_->data_offset == base::kPageSize);
138   PERFETTO_CHECK(ret.metadata_page_->data_size == ret.data_buf_sz_);
139 
140   PERFETTO_DCHECK(IsPowerOfTwo(ret.data_buf_sz_));
141 
142   return base::make_optional(std::move(ret));
143 }
144 
145 // See |perf_output_put_handle| for the necessary synchronization between the
146 // kernel and this userspace thread (which are using the same shared memory, but
147 // might be on different cores).
148 // TODO(rsavitski): is there false sharing between |data_tail| and |data_head|?
149 // Is there an argument for maintaining our own copy of |data_tail| instead of
150 // reloading it?
ReadRecordNonconsuming()151 char* PerfRingBuffer::ReadRecordNonconsuming() {
152   static_assert(sizeof(std::atomic<uint64_t>) == sizeof(uint64_t), "");
153 
154   PERFETTO_DCHECK(valid());
155 
156   // |data_tail| is written only by this userspace thread, so we can safely read
157   // it without any synchronization.
158   uint64_t read_offset = metadata_page_->data_tail;
159 
160   // |data_head| is written by the kernel, perform an acquiring load such that
161   // the payload reads below are ordered after this load.
162   uint64_t write_offset =
163       reinterpret_cast<std::atomic<uint64_t>*>(&metadata_page_->data_head)
164           ->load(std::memory_order_acquire);
165 
166   PERFETTO_DCHECK(read_offset <= write_offset);
167   if (write_offset == read_offset)
168     return nullptr;  // no new data
169 
170   size_t read_pos = static_cast<size_t>(read_offset & (data_buf_sz_ - 1));
171 
172   // event header (64 bits) guaranteed to be contiguous
173   PERFETTO_DCHECK(read_pos <= data_buf_sz_ - sizeof(perf_event_header));
174   PERFETTO_DCHECK(0 == reinterpret_cast<size_t>(data_buf_ + read_pos) %
175                            alignof(perf_event_header));
176 
177   perf_event_header* evt_header =
178       reinterpret_cast<perf_event_header*>(data_buf_ + read_pos);
179   uint16_t evt_size = evt_header->size;
180 
181   // event wrapped - reconstruct it, and return a pointer to the buffer
182   if (read_pos + evt_size > data_buf_sz_) {
183     PERFETTO_DLOG("PerfRingBuffer: returning reconstructed event");
184 
185     size_t prefix_sz = data_buf_sz_ - read_pos;
186     memcpy(&reconstructed_record_[0], data_buf_ + read_pos, prefix_sz);
187     memcpy(&reconstructed_record_[0] + prefix_sz, data_buf_,
188            evt_size - prefix_sz);
189     return &reconstructed_record_[0];
190   } else {
191     // usual case - contiguous sample
192     return data_buf_ + read_pos;
193   }
194 }
195 
Consume(size_t bytes)196 void PerfRingBuffer::Consume(size_t bytes) {
197   PERFETTO_DCHECK(valid());
198 
199   // Advance |data_tail|, which is written only by this thread. The store of the
200   // updated value needs to have release semantics such that the preceding
201   // payload reads are ordered before it. The reader in this case is the kernel,
202   // which reads |data_tail| to calculate the available ring buffer capacity
203   // before trying to store a new record.
204   uint64_t updated_tail = metadata_page_->data_tail + bytes;
205   reinterpret_cast<std::atomic<uint64_t>*>(&metadata_page_->data_tail)
206       ->store(updated_tail, std::memory_order_release);
207 }
208 
EventReader(uint32_t cpu,perf_event_attr event_attr,base::ScopedFile perf_fd,PerfRingBuffer ring_buffer)209 EventReader::EventReader(uint32_t cpu,
210                          perf_event_attr event_attr,
211                          base::ScopedFile perf_fd,
212                          PerfRingBuffer ring_buffer)
213     : cpu_(cpu),
214       event_attr_(event_attr),
215       perf_fd_(std::move(perf_fd)),
216       ring_buffer_(std::move(ring_buffer)) {}
217 
operator =(EventReader && other)218 EventReader& EventReader::operator=(EventReader&& other) noexcept {
219   if (this == &other)
220     return *this;
221 
222   this->~EventReader();
223   new (this) EventReader(std::move(other));
224   return *this;
225 }
226 
ConfigureEvents(uint32_t cpu,const EventConfig & event_cfg)227 base::Optional<EventReader> EventReader::ConfigureEvents(
228     uint32_t cpu,
229     const EventConfig& event_cfg) {
230   auto leader_fd = PerfEventOpen(cpu, event_cfg.perf_attr());
231   if (!leader_fd) {
232     PERFETTO_PLOG("Failed perf_event_open");
233     return base::nullopt;
234   }
235   if (!MaybeApplyTracepointFilter(leader_fd.get(), event_cfg.timebase_event()))
236     return base::nullopt;
237 
238   auto ring_buffer =
239       PerfRingBuffer::Allocate(leader_fd.get(), event_cfg.ring_buffer_pages());
240   if (!ring_buffer.has_value()) {
241     return base::nullopt;
242   }
243 
244   return base::make_optional<EventReader>(cpu, *event_cfg.perf_attr(),
245                                           std::move(leader_fd),
246                                           std::move(ring_buffer.value()));
247 }
248 
ReadUntilSample(std::function<void (uint64_t)> records_lost_callback)249 base::Optional<ParsedSample> EventReader::ReadUntilSample(
250     std::function<void(uint64_t)> records_lost_callback) {
251   for (;;) {
252     char* event = ring_buffer_.ReadRecordNonconsuming();
253     if (!event)
254       return base::nullopt;  // caught up with the writer
255 
256     auto* event_hdr = reinterpret_cast<const perf_event_header*>(event);
257 
258     if (event_hdr->type == PERF_RECORD_SAMPLE) {
259       ParsedSample sample = ParseSampleRecord(cpu_, event);
260       ring_buffer_.Consume(event_hdr->size);
261       return base::make_optional(std::move(sample));
262     }
263 
264     if (event_hdr->type == PERF_RECORD_LOST) {
265       /*
266        * struct {
267        *   struct perf_event_header header;
268        *   u64 id;
269        *   u64 lost;
270        *   struct sample_id sample_id;
271        * };
272        */
273       uint64_t records_lost = *reinterpret_cast<const uint64_t*>(
274           event + sizeof(perf_event_header) + sizeof(uint64_t));
275 
276       records_lost_callback(records_lost);
277       ring_buffer_.Consume(event_hdr->size);
278       continue;  // keep looking for a sample
279     }
280 
281     // Kernel had to throttle irqs.
282     if (event_hdr->type == PERF_RECORD_THROTTLE ||
283         event_hdr->type == PERF_RECORD_UNTHROTTLE) {
284       ring_buffer_.Consume(event_hdr->size);
285       continue;  // keep looking for a sample
286     }
287 
288     PERFETTO_DFATAL_OR_ELOG("Unsupported event type [%zu]",
289                             static_cast<size_t>(event_hdr->type));
290     ring_buffer_.Consume(event_hdr->size);
291   }
292 }
293 
294 // Generally, samples can belong to any cpu (which can be recorded with
295 // PERF_SAMPLE_CPU). However, this producer uses only cpu-scoped events,
296 // therefore it is already known.
ParseSampleRecord(uint32_t cpu,const char * record_start)297 ParsedSample EventReader::ParseSampleRecord(uint32_t cpu,
298                                             const char* record_start) {
299   if (event_attr_.sample_type &
300       (~uint64_t(PERF_SAMPLE_TID | PERF_SAMPLE_TIME | PERF_SAMPLE_STACK_USER |
301                  PERF_SAMPLE_REGS_USER | PERF_SAMPLE_CALLCHAIN |
302                  PERF_SAMPLE_READ))) {
303     PERFETTO_FATAL("Unsupported sampling option");
304   }
305 
306   auto* event_hdr = reinterpret_cast<const perf_event_header*>(record_start);
307   size_t sample_size = event_hdr->size;
308 
309   ParsedSample sample = {};
310   sample.common.cpu = cpu;
311   sample.common.cpu_mode = event_hdr->misc & PERF_RECORD_MISC_CPUMODE_MASK;
312 
313   // Parse the payload, which consists of concatenated data for each
314   // |attr.sample_type| flag.
315   const char* parse_pos = record_start + sizeof(perf_event_header);
316 
317   if (event_attr_.sample_type & PERF_SAMPLE_TID) {
318     uint32_t pid = 0;
319     uint32_t tid = 0;
320     parse_pos = ReadValue(&pid, parse_pos);
321     parse_pos = ReadValue(&tid, parse_pos);
322     sample.common.pid = static_cast<pid_t>(pid);
323     sample.common.tid = static_cast<pid_t>(tid);
324   }
325 
326   if (event_attr_.sample_type & PERF_SAMPLE_TIME) {
327     parse_pos = ReadValue(&sample.common.timestamp, parse_pos);
328   }
329 
330   if (event_attr_.sample_type & PERF_SAMPLE_READ) {
331     parse_pos = ReadValue(&sample.common.timebase_count, parse_pos);
332   }
333 
334   if (event_attr_.sample_type & PERF_SAMPLE_CALLCHAIN) {
335     uint64_t chain_len = 0;
336     parse_pos = ReadValue(&chain_len, parse_pos);
337     sample.kernel_ips.resize(static_cast<size_t>(chain_len));
338     parse_pos = ReadValues<uint64_t>(sample.kernel_ips.data(), parse_pos,
339                                      static_cast<size_t>(chain_len));
340   }
341 
342   if (event_attr_.sample_type & PERF_SAMPLE_REGS_USER) {
343     // Can be empty, e.g. if we sampled a kernel thread.
344     sample.regs = ReadPerfUserRegsData(&parse_pos);
345   }
346 
347   if (event_attr_.sample_type & PERF_SAMPLE_STACK_USER) {
348     // Maximum possible sampled stack size for this sample. Can be lower than
349     // the requested size if there wasn't enough room in the sample (which is
350     // limited to 64k).
351     uint64_t max_stack_size;
352     parse_pos = ReadValue(&max_stack_size, parse_pos);
353 
354     const char* stack_start = parse_pos;
355     parse_pos += max_stack_size;  // skip to dyn_size
356 
357     // Payload written conditionally, e.g. kernel threads don't have a
358     // user stack.
359     if (max_stack_size > 0) {
360       uint64_t filled_stack_size;
361       parse_pos = ReadValue(&filled_stack_size, parse_pos);
362       PERFETTO_DLOG("sampled stack size: %" PRIu64 " / %" PRIu64 "",
363                     filled_stack_size, max_stack_size);
364 
365       // copy stack bytes into a vector
366       size_t payload_sz = static_cast<size_t>(filled_stack_size);
367       sample.stack.resize(payload_sz);
368       memcpy(sample.stack.data(), stack_start, payload_sz);
369 
370       // remember whether the stack sample is (most likely) truncated
371       sample.stack_maxed = (filled_stack_size == max_stack_size);
372     }
373   }
374 
375   PERFETTO_CHECK(parse_pos == record_start + sample_size);
376   return sample;
377 }
378 
EnableEvents()379 void EventReader::EnableEvents() {
380   int ret = ioctl(perf_fd_.get(), PERF_EVENT_IOC_ENABLE);
381   PERFETTO_CHECK(ret == 0);
382 }
383 
DisableEvents()384 void EventReader::DisableEvents() {
385   int ret = ioctl(perf_fd_.get(), PERF_EVENT_IOC_DISABLE);
386   PERFETTO_CHECK(ret == 0);
387 }
388 
389 }  // namespace profiling
390 }  // namespace perfetto
391