| // Copyright 2021 Google Inc. All rights reserved. | |
| // | |
| // Licensed under the Apache License, Version 2.0 (the "License"); | |
| // you may not use this file except in compliance with the License. | |
| // You may obtain a copy of the License at | |
| // | |
| // http://www.apache.org/licenses/LICENSE-2.0 | |
| // | |
| // Unless required by applicable law or agreed to in writing, software | |
| // distributed under the License is distributed on an "AS IS" BASIS, | |
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| // See the License for the specific language governing permissions and | |
| // limitations under the License. | |
| #include "perf_counters.h" | |
| #include <cerrno> | |
| #include <cinttypes> | |
| #include <cstdint> | |
| #include <cstdio> | |
| #include <cstring> | |
| #include <iterator> | |
| #include <optional> | |
| #include <string> | |
| #include <string_view> | |
| #include <utility> | |
| #include <vector> | |
| #if defined HAVE_LIBPFM | |
| #include <dirent.h> | |
| #include <fcntl.h> | |
| #include <linux/perf_event.h> | |
| #include <sched.h> | |
| #include <sys/stat.h> | |
| #include "perfmon/pfmlib.h" | |
| #include "perfmon/pfmlib_perf_event.h" | |
| #endif | |
| namespace benchmark { | |
| namespace internal { | |
| #if defined HAVE_LIBPFM | |
| size_t PerfCounterValues::Read(const std::vector<int>& leaders) { | |
| // Create a pointer for multiple reads | |
| const size_t bufsize = values_.size() * sizeof(values_[0]); | |
| char* ptr = reinterpret_cast<char*>(values_.data()); | |
| size_t size = bufsize; | |
| for (int lead : leaders) { | |
| auto read_bytes = ::read(lead, ptr, size); | |
| if (read_bytes >= ssize_t(sizeof(uint64_t))) { | |
| // Actual data bytes are all bytes minus initial padding | |
| std::size_t data_bytes = | |
| static_cast<std::size_t>(read_bytes) - sizeof(uint64_t); | |
| // This should be very cheap since it's in hot cache | |
| std::memmove(ptr, ptr + sizeof(uint64_t), data_bytes); | |
| // Increment our counters | |
| ptr += data_bytes; | |
| size -= data_bytes; | |
| } else { | |
| int err = errno; | |
| GetErrorLogInstance() << "Error reading lead " << lead << " errno:" << err | |
| << " " << ::strerror(err) << "\n"; | |
| return 0; | |
| } | |
| } | |
| return (bufsize - size) / sizeof(uint64_t); | |
| } | |
| const bool PerfCounters::kSupported = true; | |
| // Initializes libpfm only on the first call. Returns whether that single | |
| // initialization was successful. | |
| bool PerfCounters::Initialize() { | |
| // Function-scope static gets initialized only once on first call. | |
| static const bool success = []() { | |
| return pfm_initialize() == PFM_SUCCESS; | |
| }(); | |
| return success; | |
| } | |
| bool PerfCounters::IsCounterSupported(const std::string& name) { | |
| Initialize(); | |
| perf_event_attr attr; | |
| std::memset(&attr, 0, sizeof(attr)); | |
| pfm_perf_encode_arg_t arg; | |
| std::memset(&arg, 0, sizeof(arg)); | |
| arg.attr = &attr; | |
| const int mode = PFM_PLM3; // user mode only | |
| int ret = pfm_get_os_event_encoding(name.c_str(), mode, PFM_OS_PERF_EVENT_EXT, | |
| &arg); | |
| return (ret == PFM_SUCCESS); | |
| } | |
| static std::optional<std::vector<uint64_t>> QueryCPUPMUTypes() { | |
| std::vector<uint64_t> types; | |
| DIR* dir = opendir("/sys/bus/event_source/devices"); | |
| if (!dir) { | |
| return std::nullopt; | |
| } | |
| while (dirent* ent = readdir(dir)) { | |
| std::string_view name_str = ent->d_name; | |
| auto node_path = [&](const char* node) { | |
| return std::string("/sys/bus/event_source/devices/") + ent->d_name + "/" + | |
| node; | |
| }; | |
| struct stat st; | |
| if (name_str == "cpu" || name_str == "cpum_cf" || | |
| stat(node_path("cpus").c_str(), &st) == 0 || errno != ENOENT) { | |
| int type_fd = open(node_path("type").c_str(), O_RDONLY); | |
| if (type_fd < 0) { | |
| closedir(dir); | |
| return std::nullopt; | |
| } | |
| char type_str[32] = {}; | |
| ssize_t res = read(type_fd, type_str, sizeof(type_str) - 1); | |
| close(type_fd); | |
| if (res < 0) { | |
| closedir(dir); | |
| return std::nullopt; | |
| } | |
| uint64_t type; | |
| if (sscanf(type_str, "%" PRIu64, &type) != 1) { | |
| closedir(dir); | |
| return std::nullopt; | |
| } | |
| BM_VLOG(1) << "perf_counters: found CPU PMU " << name_str << " type " | |
| << type << "\n"; | |
| types.push_back(type); | |
| } | |
| } | |
| closedir(dir); | |
| return types; | |
| } | |
| static std::vector<uint64_t> GetPMUTypesForEvent(const perf_event_attr& attr) { | |
| // Replicate generic hardware events on all CPU PMUs. | |
| if (attr.type == PERF_TYPE_HARDWARE && attr.config < PERF_COUNT_HW_MAX) { | |
| if (auto types = QueryCPUPMUTypes()) { | |
| return *types; | |
| } | |
| } | |
| return {}; | |
| } | |
| // Returns the CPUs that the calling thread may run on, or an empty vector if | |
| // they cannot be determined. | |
| static std::vector<int> GetAffinityCPUs() { | |
| std::vector<int> cpus; | |
| cpu_set_t affinity; | |
| CPU_ZERO(&affinity); | |
| if (sched_getaffinity(0, sizeof(affinity), &affinity) == 0) { | |
| for (int cpu = 0; cpu < CPU_SETSIZE; ++cpu) { | |
| if (CPU_ISSET(cpu, &affinity)) { | |
| cpus.push_back(cpu); | |
| } | |
| } | |
| } | |
| return cpus; | |
| } | |
| PerfCounters PerfCounters::Create( | |
| const std::vector<std::string>& counter_names) { | |
| if (!counter_names.empty()) { | |
| Initialize(); | |
| } | |
| const int kCounterMode = PFM_PLM3; // user mode only | |
| // Group leads will be assigned on demand. The idea is that once we cannot | |
| // create a counter descriptor, the reason is that this group has maxed out | |
| // so we create a new group leader to hold the next set of counters. Events | |
| // on different PMUs, or bound to different CPUs, cannot share a group, so | |
| // there is a current group per PMU and CPU. | |
| struct Group { | |
| uint64_t pmu; | |
| int cpu; | |
| int leader; | |
| std::vector<int> counter_ids; | |
| std::vector<std::string> names; | |
| }; | |
| std::vector<Group> groups; | |
| size_t num_counters = 0; | |
| // Opens the counter `attr`, counting only on `cpu` unless it is -1, and adds | |
| // it to the current group for `pmu` and `cpu`, or to a new group if there is | |
| // none or it is full. Returns 0 if it could be opened, or else the errno of | |
| // the last failed perf_event_open call. | |
| auto add_counter = [&](perf_event_attr attr, uint64_t pmu, int cpu, | |
| const std::string& name) { | |
| Group* group = nullptr; | |
| for (auto it = groups.rbegin(); it != groups.rend(); ++it) { | |
| if (it->pmu == pmu && it->cpu == cpu) { | |
| group = &*it; | |
| break; | |
| } | |
| } | |
| int group_id = group != nullptr ? group->leader : -1; | |
| int id = -1; | |
| int open_errno = 0; | |
| while (id < 0) { | |
| // Only the group leader is pinned, and disabled until the group is | |
| // enabled below. | |
| attr.disabled = group_id < 0; | |
| attr.pinned = group_id < 0; | |
| static constexpr size_t kNrOfSyscallRetries = 5; | |
| // Retry syscall as it was interrupted often (b/64774091). | |
| for (size_t num_retries = 0; num_retries < kNrOfSyscallRetries; | |
| ++num_retries) { | |
| id = perf_event_open(&attr, 0, cpu, group_id, 0); | |
| open_errno = errno; | |
| if (id >= 0 || open_errno != EINTR) { | |
| break; | |
| } | |
| } | |
| if (id < 0) { | |
| // If the file descriptor is negative we might have reached a limit | |
| // in the current group. Retry in a new group. | |
| if (group_id >= 0) { | |
| group_id = -1; | |
| } else { | |
| // At this point we have already retried in a new group and failed. | |
| // We then give up. | |
| return open_errno; | |
| } | |
| } | |
| } | |
| if (group_id < 0) { | |
| // This is a leader, start a new group for it | |
| groups.push_back({pmu, cpu, id, {}, {}}); | |
| group = &groups.back(); | |
| } | |
| // This is a valid counter, add it to its group | |
| group->counter_ids.push_back(id); | |
| group->names.push_back(name); | |
| ++num_counters; | |
| return 0; | |
| }; | |
| // Closes the counter most recently added by add_counter() for `pmu` and | |
| // `cpu`, and removes it from its group (which is then empty if it was the | |
| // leader). | |
| auto remove_last_counter = [&](uint64_t pmu, int cpu) { | |
| for (auto it = groups.rbegin(); it != groups.rend(); ++it) { | |
| if (it->pmu == pmu && it->cpu == cpu) { | |
| ::close(it->counter_ids.back()); | |
| it->counter_ids.pop_back(); | |
| it->names.pop_back(); | |
| --num_counters; | |
| if (it->counter_ids.empty()) { | |
| groups.erase(std::next(it).base()); | |
| } | |
| return; | |
| } | |
| } | |
| }; | |
| // Loop through all performance counters | |
| for (size_t i = 0; i < counter_names.size(); ++i) { | |
| // we are about to add counters | |
| // check if we did not reach the maximum | |
| if (num_counters == PerfCounterValues::kMaxCounters) { | |
| // Log a message if we maxed out and stop adding | |
| GetErrorLogInstance() | |
| << counter_names.size() << " counters were requested. The maximum is " | |
| << PerfCounterValues::kMaxCounters << " and " << num_counters | |
| << " were already added. All remaining counters will be ignored\n"; | |
| // stop the loop and return what we have already | |
| break; | |
| } | |
| // Check if this name is empty | |
| const auto& name = counter_names[i]; | |
| if (name.empty()) { | |
| GetErrorLogInstance() | |
| << "A performance counter name was the empty string\n"; | |
| continue; | |
| } | |
| // This struct will be populated by libpfm from the counter string | |
| // and then fed into the syscall perf_event_open | |
| struct perf_event_attr attr {}; | |
| attr.size = sizeof(attr); | |
| // This is the input struct to libpfm. | |
| pfm_perf_encode_arg_t arg{}; | |
| arg.attr = &attr; | |
| const int pfm_get = pfm_get_os_event_encoding(name.c_str(), kCounterMode, | |
| PFM_OS_PERF_EVENT, &arg); | |
| if (pfm_get != PFM_SUCCESS) { | |
| GetErrorLogInstance() | |
| << "Unknown performance counter name: " << name << "\n"; | |
| continue; | |
| } | |
| // We then proceed to populate the remaining fields in our attribute struct | |
| // Note: the man page for perf_event_create suggests inherit = true and | |
| // read_format = PERF_FORMAT_GROUP don't work together, but that's not the | |
| // case. | |
| attr.inherit = true; | |
| attr.exclude_kernel = true; | |
| attr.exclude_user = false; | |
| attr.exclude_hv = true; | |
| // Read all counters in a group in one read. | |
| attr.read_format = PERF_FORMAT_GROUP; //| PERF_FORMAT_TOTAL_TIME_ENABLED | | |
| // PERF_FORMAT_TOTAL_TIME_RUNNING; | |
| // Replicate generic hardware events on all CPU PMUs, with the PMU type in | |
| // the upper bits of `config`. This requires PERF_PMU_CAP_EXTENDED_HW_TYPE, | |
| // which not all PMU drivers support (e.g. arm_pmu in Linux 6.1). | |
| bool opened = false; | |
| const std::vector<uint64_t> pmus = GetPMUTypesForEvent(attr); | |
| if (num_counters + pmus.size() > PerfCounterValues::kMaxCounters) { | |
| GetErrorLogInstance() | |
| << "***WARNING*** Opening performance counter " << name | |
| << " on each of " << pmus.size() | |
| << " CPU PMUs would exceed the maximum of " | |
| << PerfCounterValues::kMaxCounters << " counters. Ignoring\n"; | |
| continue; | |
| } | |
| for (uint64_t pmu : pmus) { | |
| perf_event_attr pmu_attr = attr; | |
| pmu_attr.config |= pmu << PERF_PMU_TYPE_SHIFT; | |
| if (const int open_errno = add_counter(pmu_attr, pmu, /*cpu=*/-1, name); | |
| open_errno != 0) { | |
| BM_VLOG(1) << "perf_counters: cannot open " << name << " on PMU type " | |
| << pmu << ": " << ::strerror(open_errno) << "\n"; | |
| } else { | |
| opened = true; | |
| } | |
| } | |
| // Otherwise, if there are several CPU PMUs, open the event once per CPU | |
| // that the thread may run on, bound to that CPU: the kernel then opens it | |
| // on the PMU of that CPU, and maps the generic event to that PMU's event. | |
| // This uses the thread's affinity when the counters are created. If the | |
| // event could not be opened on some of these CPUs, it would silently not | |
| // count while the thread runs on them, so then it is not opened at all. | |
| if (!opened && pmus.size() > 1) { | |
| const std::vector<int> cpus = GetAffinityCPUs(); | |
| if (num_counters + cpus.size() > PerfCounterValues::kMaxCounters) { | |
| GetErrorLogInstance() | |
| << "***WARNING*** Opening performance counter " << name | |
| << " on each of " << cpus.size() | |
| << " CPUs would exceed the maximum of " | |
| << PerfCounterValues::kMaxCounters << " counters. Ignoring\n"; | |
| continue; | |
| } | |
| size_t num_opened = 0; | |
| for (int cpu : cpus) { | |
| if (const int open_errno = add_counter(attr, 0, cpu, name); | |
| open_errno != 0) { | |
| GetErrorLogInstance() | |
| << "***WARNING*** Failed to open performance counter " << name | |
| << " on CPU " << cpu << ": " << ::strerror(open_errno) | |
| << ". Ignoring\n"; | |
| break; | |
| } | |
| ++num_opened; | |
| } | |
| if (num_opened < cpus.size()) { | |
| while (num_opened > 0) { | |
| remove_last_counter(0, cpus[--num_opened]); | |
| } | |
| continue; | |
| } | |
| opened = !cpus.empty(); | |
| } | |
| // Only if the event could not be opened on any CPU PMU or CPU, or is not | |
| // replicated, open it as a plain event, on a CPU PMU of the kernel's | |
| // choosing (the only one, if there is just one). Also opening it on some | |
| // PMUs or CPUs would count twice there, since all counts are summed. | |
| if (!opened && num_counters < PerfCounterValues::kMaxCounters && | |
| add_counter(attr, 0, /*cpu=*/-1, name) != 0) { | |
| // We failed to get a new file descriptor. We might have reached a hard | |
| // hardware limit that cannot be resolved even with group multiplexing | |
| GetErrorLogInstance() << "***WARNING** Failed to get a file descriptor " | |
| "for performance counter " | |
| << name << ". Ignoring\n"; | |
| } | |
| } | |
| // Reading a group leader returns the values of its members in the order they | |
| // were added, and PerfCounterValues::Read() concatenates the groups in leader | |
| // order, so list the counters group by group. | |
| std::vector<std::string> valid_names; | |
| std::vector<int> counter_ids; | |
| std::vector<int> leader_ids; | |
| valid_names.reserve(num_counters); | |
| counter_ids.reserve(num_counters); | |
| leader_ids.reserve(groups.size()); | |
| for (const Group& group : groups) { | |
| leader_ids.push_back(group.leader); | |
| counter_ids.insert(counter_ids.end(), group.counter_ids.begin(), | |
| group.counter_ids.end()); | |
| valid_names.insert(valid_names.end(), group.names.begin(), | |
| group.names.end()); | |
| } | |
| // Loop through all group leaders activating them | |
| // There is another option of starting ALL counters in a process but | |
| // that would be far reaching an intrusion. If the user is using PMCs | |
| // by themselves then this would have a side effect on them. It is | |
| // friendlier to loop through all groups individually. | |
| for (int lead : leader_ids) { | |
| if (ioctl(lead, PERF_EVENT_IOC_ENABLE) != 0) { | |
| // This should never happen but if it does, we give up on the | |
| // entire batch as recovery would be a mess. | |
| GetErrorLogInstance() << "***WARNING*** Failed to start counters. " | |
| "Clearing out all counters.\n"; | |
| // Close all performance counters | |
| for (int id : counter_ids) { | |
| ::close(id); | |
| } | |
| // Return an empty object so our internal state is still good and | |
| // the process can continue normally without impact | |
| return NoCounters(); | |
| } | |
| } | |
| return PerfCounters(std::move(valid_names), std::move(counter_ids), | |
| std::move(leader_ids)); | |
| } | |
| void PerfCounters::CloseCounters() const { | |
| if (counter_ids_.empty()) { | |
| return; | |
| } | |
| for (int lead : leader_ids_) { | |
| ioctl(lead, PERF_EVENT_IOC_DISABLE); | |
| } | |
| for (int fd : counter_ids_) { | |
| close(fd); | |
| } | |
| } | |
| #else // defined HAVE_LIBPFM | |
| size_t PerfCounterValues::Read(const std::vector<int>&) { return 0; } | |
| const bool PerfCounters::kSupported = false; | |
| bool PerfCounters::Initialize() { return false; } | |
| bool PerfCounters::IsCounterSupported(const std::string&) { return false; } | |
| PerfCounters PerfCounters::Create( | |
| const std::vector<std::string>& counter_names) { | |
| if (!counter_names.empty()) { | |
| GetErrorLogInstance() << "Performance counters not supported.\n"; | |
| } | |
| return NoCounters(); | |
| } | |
| void PerfCounters::CloseCounters() const {} | |
| #endif // defined HAVE_LIBPFM | |
| PerfCountersMeasurement::PerfCountersMeasurement( | |
| const std::vector<std::string>& counter_names) | |
| : start_values_(counter_names.size()), end_values_(counter_names.size()) { | |
| counters_ = PerfCounters::Create(counter_names); | |
| } | |
| PerfCounters& PerfCounters::operator=(PerfCounters&& other) noexcept { | |
| if (this != &other) { | |
| CloseCounters(); | |
| counter_ids_ = std::move(other.counter_ids_); | |
| leader_ids_ = std::move(other.leader_ids_); | |
| counter_names_ = std::move(other.counter_names_); | |
| } | |
| return *this; | |
| } | |
| } // namespace internal | |
| } // namespace benchmark |