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.
4
5 #include "base/android/thread_instruction_count.h"
6
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"
12
13 #include <linux/perf_event.h>
14 #include <sys/syscall.h>
15 #include <unistd.h>
16
17 namespace base {
18 namespace android {
19
20 namespace {
21
22 constexpr int kPerfFdOpenFailed = -1;
23
InstructionCounterFdSlot()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));
27 if (fd > 0)
28 close(fd);
29 });
30 return *fd_slot;
31 }
32
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.
36 //
37 // Returns kPerfFdOpenFailed if opening the file descriptor failed.
OpenInstructionCounterFdForThread(int thread_id)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;
44 pe.exclude_hv = 1;
45
46 long fd = syscall(__NR_perf_event_open, &pe, thread_id, /* cpu */ -1,
47 /* group_fd */ -1, /* flags */ 0);
48 if (fd < 0) {
49 PLOG(ERROR) << "perf_event_open: omitting instruction counters";
50 return kPerfFdOpenFailed;
51 }
52 return checked_cast<int>(fd);
53 }
54
55 // Retrieves the active perf counter FD for the current thread, performing
56 // lazy-initialization if necessary.
InstructionCounterFdForCurrentThread()57 int InstructionCounterFdForCurrentThread() {
58 auto& slot = InstructionCounterFdSlot();
59 int fd = checked_cast<int>(reinterpret_cast<intptr_t>(slot.Get()));
60 if (fd == 0) {
61 fd = OpenInstructionCounterFdForThread(0);
62 slot.Set(reinterpret_cast<void*>(fd));
63 }
64 return fd;
65 }
66
67 } // namespace
68
69 // static
IsSupported()70 bool ThreadInstructionCount::IsSupported() {
71 return InstructionCounterFdForCurrentThread() > 0;
72 }
73
74 // static
Now()75 ThreadInstructionCount ThreadInstructionCount::Now() {
76 DCHECK(IsSupported());
77 int fd = InstructionCounterFdForCurrentThread();
78 if (fd <= 0)
79 return ThreadInstructionCount();
80
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);
87 }
88
89 } // namespace android
90 } // namespace base
91