| 1 | // |
| 2 | // SPDX-FileCopyrightText: Copyright 2025-2026 Arm Limited and/or its affiliates <open-source-office@arm.com> |
| 3 | // |
| 4 | // SPDX-License-Identifier: Apache-2.0 |
| 5 | // |
| 6 | |
| 7 | #include <stdlib.h> |
| 8 | #include <stdio.h> |
| 9 | #include <unistd.h> |
| 10 | #include <string.h> |
| 11 | #include <sys/ioctl.h> |
| 12 | #include <linux/perf_event.h> |
| 13 | #include <syscall.h> |
| 14 | |
| 15 | |
| 16 | static long |
| 17 | perf_event_open(struct perf_event_attr *hw_event, pid_t pid, |
| 18 | int cpu, int group_fd, unsigned long flags) |
| 19 | { |
| 20 | int ret; |
| 21 | |
| 22 | ret = syscall(__NR_perf_event_open, hw_event, pid, cpu, |
| 23 | group_fd, flags); |
| 24 | return ret; |
| 25 | } |
| 26 | |
| 27 | int |
| 28 | open_counter(int perfEvent) |
| 29 | { |
| 30 | struct perf_event_attr pe; |
| 31 | int fd; |
| 32 | |
| 33 | memset(&pe, 0, sizeof(struct perf_event_attr)); |
| 34 | pe.type = PERF_TYPE_HARDWARE; |
| 35 | pe.size = sizeof(struct perf_event_attr); |
| 36 | pe.config = perfEvent; |
| 37 | pe.disabled = 1; |
| 38 | pe.exclude_kernel = 1; |
| 39 | pe.exclude_hv = 1; |
| 40 | |
| 41 | fd = perf_event_open(&pe, 0, -1, -1, 0); |
| 42 | if (fd == -1) { |
| 43 | printf("Error opening leader %llx\n", pe.config); |
| 44 | exit(EXIT_FAILURE); |
| 45 | } |
| 46 | return fd; |
| 47 | } |
| 48 | |
| 49 | void start_counter(int fd) { |
| 50 | ioctl(fd, PERF_EVENT_IOC_RESET, 0); |
| 51 | ioctl(fd, PERF_EVENT_IOC_ENABLE, 0); |
| 52 | } |
| 53 | |
| 54 | long long get_counter(int fd) { |
| 55 | long long count; |
| 56 | read(fd, &count, sizeof(long long)); |
| 57 | return count; |
| 58 | } |
| 59 | |
| 60 | long long stop_counter(int fd) { |
| 61 | long long count; |
| 62 | ioctl(fd, PERF_EVENT_IOC_DISABLE, 0); |
| 63 | read(fd, &count, sizeof(long long)); |
| 64 | return count; |
| 65 | } |
| 66 | |
| 67 | int |
| 68 | open_instruction_counter(void) { |
| 69 | return open_counter(PERF_COUNT_HW_INSTRUCTIONS); |
| 70 | } |
| 71 | |
| 72 | int |
| 73 | open_cycle_counter(void) { |
| 74 | return open_counter(PERF_COUNT_HW_CPU_CYCLES); |
| 75 | } |