1 // Copyright 2022 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/android/thread_instruction_count.h"
7 #include "base/check_op.h"
8 #include "base/logging.h"
9 #include "base/no_destructor.h"
10 #include "base/numerics/safe_conversions.h"
11 #include "base/threading/thread_local_storage.h"
13 #include <linux/perf_event.h>
14 #include <sys/syscall.h>
22 constexpr int kPerfFdOpenFailed = -1;
24 ThreadLocalStorage::Slot& InstructionCounterFdSlot() {
25 static NoDestructor<ThreadLocalStorage::Slot> fd_slot([](void* fd_ptr) {
26 int fd = checked_cast<int>(reinterpret_cast<intptr_t>(fd_ptr));
33 // Opens a new file descriptor that emits the value of
34 // PERF_COUNT_HW_INSTRUCTIONS in userspace (excluding kernel and hypervisor
35 // instructions) for the given |thread_id|, or 0 for the calling thread.
37 // Returns kPerfFdOpenFailed if opening the file descriptor failed.
38 int OpenInstructionCounterFdForThread(int thread_id) {
39 struct perf_event_attr pe = {0};
40 pe.type = PERF_TYPE_HARDWARE;
41 pe.size = sizeof(struct perf_event_attr);
42 pe.config = PERF_COUNT_HW_INSTRUCTIONS;
43 pe.exclude_kernel = 1;
46 long fd = syscall(__NR_perf_event_open, &pe, thread_id, /* cpu */ -1,
47 /* group_fd */ -1, /* flags */ 0);
49 PLOG(ERROR) << "perf_event_open: omitting instruction counters";
50 return kPerfFdOpenFailed;
52 return checked_cast<int>(fd);
55 // Retrieves the active perf counter FD for the current thread, performing
56 // lazy-initialization if necessary.
57 int InstructionCounterFdForCurrentThread() {
58 auto& slot = InstructionCounterFdSlot();
59 int fd = checked_cast<int>(reinterpret_cast<intptr_t>(slot.Get()));
61 fd = OpenInstructionCounterFdForThread(0);
62 slot.Set(reinterpret_cast<void*>(fd));
70 bool ThreadInstructionCount::IsSupported() {
71 return InstructionCounterFdForCurrentThread() > 0;
75 ThreadInstructionCount ThreadInstructionCount::Now() {
76 DCHECK(IsSupported());
77 int fd = InstructionCounterFdForCurrentThread();
79 return ThreadInstructionCount();
81 uint64_t instructions = 0;
82 ssize_t bytes_read = read(fd, &instructions, sizeof(instructions));
83 CHECK_EQ(bytes_read, static_cast<ssize_t>(sizeof(instructions)))
84 << "Short reads of small size from kernel memory is not expected. If "
85 "this fails, use HANDLE_EINTR.";
86 return ThreadInstructionCount(instructions);
89 } // namespace android