• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2021 Google Inc. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "perf_counters.h"
16 
17 #include <cstring>
18 #include <memory>
19 #include <vector>
20 
21 #if defined HAVE_LIBPFM
22 #include "perfmon/pfmlib.h"
23 #include "perfmon/pfmlib_perf_event.h"
24 #endif
25 
26 namespace benchmark {
27 namespace internal {
28 
29 constexpr size_t PerfCounterValues::kMaxCounters;
30 
31 #if defined HAVE_LIBPFM
32 
Read(const std::vector<int> & leaders)33 size_t PerfCounterValues::Read(const std::vector<int>& leaders) {
34   // Create a pointer for multiple reads
35   const size_t bufsize = values_.size() * sizeof(values_[0]);
36   char* ptr = reinterpret_cast<char*>(values_.data());
37   size_t size = bufsize;
38   for (int lead : leaders) {
39     auto read_bytes = ::read(lead, ptr, size);
40     if (read_bytes >= ssize_t(sizeof(uint64_t))) {
41       // Actual data bytes are all bytes minus initial padding
42       std::size_t data_bytes = read_bytes - sizeof(uint64_t);
43       // This should be very cheap since it's in hot cache
44       std::memmove(ptr, ptr + sizeof(uint64_t), data_bytes);
45       // Increment our counters
46       ptr += data_bytes;
47       size -= data_bytes;
48     } else {
49       int err = errno;
50       GetErrorLogInstance() << "Error reading lead " << lead << " errno:" << err
51                             << " " << ::strerror(err) << "\n";
52       return 0;
53     }
54   }
55   return (bufsize - size) / sizeof(uint64_t);
56 }
57 
58 const bool PerfCounters::kSupported = true;
59 
Initialize()60 bool PerfCounters::Initialize() { return pfm_initialize() == PFM_SUCCESS; }
61 
IsCounterSupported(const std::string & name)62 bool PerfCounters::IsCounterSupported(const std::string& name) {
63   perf_event_attr_t attr;
64   std::memset(&attr, 0, sizeof(attr));
65   pfm_perf_encode_arg_t arg;
66   std::memset(&arg, 0, sizeof(arg));
67   arg.attr = &attr;
68   const int mode = PFM_PLM3;  // user mode only
69   int ret = pfm_get_os_event_encoding(name.c_str(), mode, PFM_OS_PERF_EVENT_EXT,
70                                       &arg);
71   return (ret == PFM_SUCCESS);
72 }
73 
Create(const std::vector<std::string> & counter_names)74 PerfCounters PerfCounters::Create(
75     const std::vector<std::string>& counter_names) {
76   // Valid counters will populate these arrays but we start empty
77   std::vector<std::string> valid_names;
78   std::vector<int> counter_ids;
79   std::vector<int> leader_ids;
80 
81   // Resize to the maximum possible
82   valid_names.reserve(counter_names.size());
83   counter_ids.reserve(counter_names.size());
84 
85   const int kCounterMode = PFM_PLM3;  // user mode only
86 
87   // Group leads will be assigned on demand. The idea is that once we cannot
88   // create a counter descriptor, the reason is that this group has maxed out
89   // so we set the group_id again to -1 and retry - giving the algorithm a
90   // chance to create a new group leader to hold the next set of counters.
91   int group_id = -1;
92 
93   // Loop through all performance counters
94   for (size_t i = 0; i < counter_names.size(); ++i) {
95     // we are about to push into the valid names vector
96     // check if we did not reach the maximum
97     if (valid_names.size() == PerfCounterValues::kMaxCounters) {
98       // Log a message if we maxed out and stop adding
99       GetErrorLogInstance()
100           << counter_names.size() << " counters were requested. The maximum is "
101           << PerfCounterValues::kMaxCounters << " and " << valid_names.size()
102           << " were already added. All remaining counters will be ignored\n";
103       // stop the loop and return what we have already
104       break;
105     }
106 
107     // Check if this name is empty
108     const auto& name = counter_names[i];
109     if (name.empty()) {
110       GetErrorLogInstance()
111           << "A performance counter name was the empty string\n";
112       continue;
113     }
114 
115     // Here first means first in group, ie the group leader
116     const bool is_first = (group_id < 0);
117 
118     // This struct will be populated by libpfm from the counter string
119     // and then fed into the syscall perf_event_open
120     struct perf_event_attr attr {};
121     attr.size = sizeof(attr);
122 
123     // This is the input struct to libpfm.
124     pfm_perf_encode_arg_t arg{};
125     arg.attr = &attr;
126     const int pfm_get = pfm_get_os_event_encoding(name.c_str(), kCounterMode,
127                                                   PFM_OS_PERF_EVENT, &arg);
128     if (pfm_get != PFM_SUCCESS) {
129       GetErrorLogInstance()
130           << "Unknown performance counter name: " << name << "\n";
131       continue;
132     }
133 
134     // We then proceed to populate the remaining fields in our attribute struct
135     // Note: the man page for perf_event_create suggests inherit = true and
136     // read_format = PERF_FORMAT_GROUP don't work together, but that's not the
137     // case.
138     attr.disabled = is_first;
139     attr.inherit = true;
140     attr.pinned = is_first;
141     attr.exclude_kernel = true;
142     attr.exclude_user = false;
143     attr.exclude_hv = true;
144 
145     // Read all counters in a group in one read.
146     attr.read_format = PERF_FORMAT_GROUP;
147 
148     int id = -1;
149     while (id < 0) {
150       static constexpr size_t kNrOfSyscallRetries = 5;
151       // Retry syscall as it was interrupted often (b/64774091).
152       for (size_t num_retries = 0; num_retries < kNrOfSyscallRetries;
153            ++num_retries) {
154         id = perf_event_open(&attr, 0, -1, group_id, 0);
155         if (id >= 0 || errno != EINTR) {
156           break;
157         }
158       }
159       if (id < 0) {
160         // If the file descriptor is negative we might have reached a limit
161         // in the current group. Set the group_id to -1 and retry
162         if (group_id >= 0) {
163           // Create a new group
164           group_id = -1;
165         } else {
166           // At this point we have already retried to set a new group id and
167           // failed. We then give up.
168           break;
169         }
170       }
171     }
172 
173     // We failed to get a new file descriptor. We might have reached a hard
174     // hardware limit that cannot be resolved even with group multiplexing
175     if (id < 0) {
176       GetErrorLogInstance() << "***WARNING** Failed to get a file descriptor "
177                                "for performance counter "
178                             << name << ". Ignoring\n";
179 
180       // We give up on this counter but try to keep going
181       // as the others would be fine
182       continue;
183     }
184     if (group_id < 0) {
185       // This is a leader, store and assign it to the current file descriptor
186       leader_ids.push_back(id);
187       group_id = id;
188     }
189     // This is a valid counter, add it to our descriptor's list
190     counter_ids.push_back(id);
191     valid_names.push_back(name);
192   }
193 
194   // Loop through all group leaders activating them
195   // There is another option of starting ALL counters in a process but
196   // that would be far reaching an intrusion. If the user is using PMCs
197   // by themselves then this would have a side effect on them. It is
198   // friendlier to loop through all groups individually.
199   for (int lead : leader_ids) {
200     if (ioctl(lead, PERF_EVENT_IOC_ENABLE) != 0) {
201       // This should never happen but if it does, we give up on the
202       // entire batch as recovery would be a mess.
203       GetErrorLogInstance() << "***WARNING*** Failed to start counters. "
204                                "Claring out all counters.\n";
205 
206       // Close all peformance counters
207       for (int id : counter_ids) {
208         ::close(id);
209       }
210 
211       // Return an empty object so our internal state is still good and
212       // the process can continue normally without impact
213       return NoCounters();
214     }
215   }
216 
217   return PerfCounters(std::move(valid_names), std::move(counter_ids),
218                       std::move(leader_ids));
219 }
220 
CloseCounters() const221 void PerfCounters::CloseCounters() const {
222   if (counter_ids_.empty()) {
223     return;
224   }
225   for (int lead : leader_ids_) {
226     ioctl(lead, PERF_EVENT_IOC_DISABLE);
227   }
228   for (int fd : counter_ids_) {
229     close(fd);
230   }
231 }
232 #else   // defined HAVE_LIBPFM
Read(const std::vector<int> &)233 size_t PerfCounterValues::Read(const std::vector<int>&) { return 0; }
234 
235 const bool PerfCounters::kSupported = false;
236 
Initialize()237 bool PerfCounters::Initialize() { return false; }
238 
IsCounterSupported(const std::string &)239 bool PerfCounters::IsCounterSupported(const std::string&) { return false; }
240 
Create(const std::vector<std::string> & counter_names)241 PerfCounters PerfCounters::Create(
242     const std::vector<std::string>& counter_names) {
243   if (!counter_names.empty()) {
244     GetErrorLogInstance() << "Performance counters not supported.";
245   }
246   return NoCounters();
247 }
248 
CloseCounters() const249 void PerfCounters::CloseCounters() const {}
250 #endif  // defined HAVE_LIBPFM
251 
PerfCountersMeasurement(const std::vector<std::string> & counter_names)252 PerfCountersMeasurement::PerfCountersMeasurement(
253     const std::vector<std::string>& counter_names)
254     : start_values_(counter_names.size()), end_values_(counter_names.size()) {
255   counters_ = PerfCounters::Create(counter_names);
256 }
257 
operator =(PerfCounters && other)258 PerfCounters& PerfCounters::operator=(PerfCounters&& other) noexcept {
259   if (this != &other) {
260     CloseCounters();
261 
262     counter_ids_ = std::move(other.counter_ids_);
263     leader_ids_ = std::move(other.leader_ids_);
264     counter_names_ = std::move(other.counter_names_);
265   }
266   return *this;
267 }
268 }  // namespace internal
269 }  // namespace benchmark
270