synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-bench / src / pmu.rs
| 1 | //! Opt-in ARM CPU PMU counters for diagnostics (issue #64). Never on by default. |
| 2 | //! |
| 3 | //! Nothing in the store, the service, or the default `run`/`floor`/`bounds` paths uses |
| 4 | //! this module. Only `synapse-bench pmu-diag` ([`crate::pmu_diag`]) opens counters, and |
| 5 | //! its controls run with [`PmuMode::Disabled`], which makes no system call at all. |
| 6 | //! |
| 7 | //! Backend: Linux `perf_event_open(2)` called through `libc::syscall`, one counting (not |
| 8 | //! sampling) event group per CPU PMU. Sources, quoted in `docs/BENCH_PMU_DIAGNOSTICS.md`: |
| 9 | //! - `perf_event_open(2)` (man-pages): attribute layout (`PERF_ATTR_SIZE_VER0` = 64 |
| 10 | //! bytes), `read_format` with `PERF_FORMAT_TOTAL_TIME_ENABLED | _RUNNING`, the |
| 11 | //! `inherit` bit (counts threads created after the open; not usable with |
| 12 | //! `PERF_FORMAT_GROUP`, so each counter is read on its own fd), the `ioctl` enable, |
| 13 | //! disable and reset requests, the `EACCES`/`EPERM` permission errors and |
| 14 | //! `/proc/sys/kernel/perf_event_paranoid`. |
| 15 | //! - Arm common architectural PMU event numbers, as the kernel defines them in |
| 16 | //! `include/linux/perf/arm_pmuv3.h`: `INST_RETIRED` 0x0008, `BR_MIS_PRED` 0x0010, |
| 17 | //! `CPU_CYCLES` 0x0011, `BR_PRED` 0x0012. They are only used after the PMU's own |
| 18 | //! sysfs event description (`events/<name>` = `event=0x....`) confirms the same |
| 19 | //! number; an absent or different description is `UNSUPPORTED_EVENT`. |
| 20 | //! |
| 21 | //! Attribution: GB10 has two CPU PMUs, one per core class (Cortex-A725, MIDR part |
| 22 | //! 0xD87, and Cortex-X925, MIDR part 0xD85). Each event is opened on each PMU by that |
| 23 | //! PMU's dynamic `type`, so a count belongs to exactly one core class and only grows |
| 24 | //! while the measured task runs on that class. Counts are never scaled by |
| 25 | //! `time_enabled / time_running`. `exclude_kernel` and `exclude_hv` are set: counters |
| 26 | //! measure user-space execution only, and a task blocked in `fdatasync` is off CPU and |
| 27 | //! counts nothing, so storage wait is never attributed to branch prediction. |
| 28 | //! |
| 29 | //! Refusal: any open failure refuses the whole sample with `INSTRUMENT_UNAVAILABLE` and |
| 30 | //! a reason code (`PERMISSION_DENIED`, `UNSUPPORTED_EVENT`, `COUNTER_UNAVAILABLE`, |
| 31 | //! `NO_PMU`, `UNSUPPORTED_PLATFORM`, the vocabulary of Omega issue #453). A refused |
| 32 | //! sample carries no counts, never zeros. |
| 33 | |
| 34 | use serde::{Deserialize, Serialize}; |
| 35 | use std::path::Path; |
| 36 | |
| 37 | /// One architected event this module counts. |
| 38 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 39 | pub struct EventSpec { |
| 40 | /// Lower-case sysfs name (`/sys/bus/event_source/devices/<pmu>/events/<name>`). |
| 41 | pub name: &'static str, |
| 42 | /// Arm common architectural event number (`arm_pmuv3.h`). |
| 43 | pub arm_event: u16, |
| 44 | } |
| 45 | |
| 46 | /// The counted events, in group order (the first is the group leader). |
| 47 | pub const EVENTS: [EventSpec; 4] = [ |
| 48 | EventSpec { |
| 49 | name: "cpu_cycles", |
| 50 | arm_event: 0x0011, |
| 51 | }, |
| 52 | EventSpec { |
| 53 | name: "inst_retired", |
| 54 | arm_event: 0x0008, |
| 55 | }, |
| 56 | EventSpec { |
| 57 | name: "br_pred", |
| 58 | arm_event: 0x0012, |
| 59 | }, |
| 60 | EventSpec { |
| 61 | name: "br_mis_pred", |
| 62 | arm_event: 0x0010, |
| 63 | }, |
| 64 | ]; |
| 65 | |
| 66 | /// Where the kernel exposes sysfs on a real host. |
| 67 | pub const SYSFS_ROOT: &str = "/sys"; |
| 68 | |
| 69 | /// CPU core class behind one PMU. |
| 70 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] |
| 71 | pub enum CoreClass { |
| 72 | CortexA725, |
| 73 | CortexX925, |
| 74 | /// The MIDR was unreadable or names another part. |
| 75 | Unknown, |
| 76 | } |
| 77 | |
| 78 | impl CoreClass { |
| 79 | /// Class from a `midr_el1` value (implementer 0x41 Arm; part number bits 15:4). |
| 80 | pub fn from_midr(midr: u64) -> Self { |
| 81 | let implementer = (midr >> 24) & 0xff; |
| 82 | let part = (midr >> 4) & 0xfff; |
| 83 | match (implementer, part) { |
| 84 | (0x41, 0xd87) => Self::CortexA725, |
| 85 | (0x41, 0xd85) => Self::CortexX925, |
| 86 | _ => Self::Unknown, |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | pub fn code(self) -> &'static str { |
| 91 | match self { |
| 92 | Self::CortexA725 => "a725", |
| 93 | Self::CortexX925 => "x925", |
| 94 | Self::Unknown => "unknown", |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | /// What the PMU's sysfs description says about one event. |
| 100 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 101 | pub struct EventDiscovery { |
| 102 | pub name: String, |
| 103 | pub arm_event: u16, |
| 104 | /// Raw contents of `events/<name>`, `None` when absent. |
| 105 | pub sysfs_encoding: Option<String>, |
| 106 | /// True only when the sysfs encoding parses to exactly `arm_event`. |
| 107 | pub verified: bool, |
| 108 | } |
| 109 | |
| 110 | /// One CPU PMU found in sysfs. |
| 111 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 112 | pub struct PmuDevice { |
| 113 | pub name: String, |
| 114 | /// Dynamic `perf_event_attr.type` from `<pmu>/type`. |
| 115 | pub perf_type: u32, |
| 116 | pub cpus: Vec<usize>, |
| 117 | pub core_class: CoreClass, |
| 118 | /// `midr_el1` of the first listed CPU, as read. |
| 119 | pub midr: Option<String>, |
| 120 | pub events: Vec<EventDiscovery>, |
| 121 | } |
| 122 | |
| 123 | impl PmuDevice { |
| 124 | pub fn all_events_verified(&self) -> bool { |
| 125 | EVENTS.iter().all(|spec| { |
| 126 | self.events |
| 127 | .iter() |
| 128 | .any(|e| e.name == spec.name && e.arm_event == spec.arm_event && e.verified) |
| 129 | }) |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | /// Everything discovered about the host's PMU access, recorded in `raw.json`. |
| 134 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 135 | pub struct Discovery { |
| 136 | pub sysfs_root: String, |
| 137 | /// `/proc/sys/kernel/perf_event_paranoid` (`None` when unreadable). |
| 138 | pub perf_event_paranoid: Option<i64>, |
| 139 | pub devices: Vec<PmuDevice>, |
| 140 | } |
| 141 | |
| 142 | /// Parse a kernel CPU list such as `0-4,10-14`. |
| 143 | pub fn parse_cpu_list(s: &str) -> Option<Vec<usize>> { |
| 144 | let mut out = Vec::new(); |
| 145 | for part in s.trim().split(',').filter(|p| !p.is_empty()) { |
| 146 | match part.split_once('-') { |
| 147 | Some((a, b)) => { |
| 148 | let (a, b): (usize, usize) = (a.parse().ok()?, b.parse().ok()?); |
| 149 | if a > b { |
| 150 | return None; |
| 151 | } |
| 152 | out.extend(a..=b); |
| 153 | } |
| 154 | None => out.push(part.parse().ok()?), |
| 155 | } |
| 156 | } |
| 157 | Some(out) |
| 158 | } |
| 159 | |
| 160 | /// Parse a sysfs event description `event=0x0011[,...]` to its event number. |
| 161 | pub fn parse_event_encoding(s: &str) -> Option<u64> { |
| 162 | s.trim() |
| 163 | .split(',') |
| 164 | .find_map(|kv| kv.trim().strip_prefix("event=")) |
| 165 | .and_then(|v| match v.strip_prefix("0x") { |
| 166 | Some(h) => u64::from_str_radix(h, 16).ok(), |
| 167 | None => v.parse().ok(), |
| 168 | }) |
| 169 | } |
| 170 | |
| 171 | fn read_trim(path: &Path) -> Option<String> { |
| 172 | std::fs::read_to_string(path) |
| 173 | .ok() |
| 174 | .map(|s| s.trim().to_string()) |
| 175 | } |
| 176 | |
| 177 | /// Discover CPU PMUs under `sysfs_root` (`/sys` on a host; a temporary tree in tests). |
| 178 | /// A device counts as a CPU PMU when it has `type`, `cpus` and `events/cpu_cycles`. |
| 179 | pub fn discover(sysfs_root: &Path, paranoid_path: &Path) -> Discovery { |
| 180 | let mut devices = Vec::new(); |
| 181 | let dir = sysfs_root.join("bus/event_source/devices"); |
| 182 | let mut names: Vec<String> = std::fs::read_dir(&dir) |
| 183 | .map(|rd| { |
| 184 | rd.filter_map(|e| e.ok()) |
| 185 | .map(|e| e.file_name().to_string_lossy().into_owned()) |
| 186 | .collect() |
| 187 | }) |
| 188 | .unwrap_or_default(); |
| 189 | names.sort(); |
| 190 | for name in names { |
| 191 | let d = dir.join(&name); |
| 192 | if !d.join("events/cpu_cycles").exists() { |
| 193 | continue; |
| 194 | } |
| 195 | let (Some(perf_type), Some(cpus)) = ( |
| 196 | read_trim(&d.join("type")).and_then(|t| t.parse::<u32>().ok()), |
| 197 | read_trim(&d.join("cpus")).and_then(|c| parse_cpu_list(&c)), |
| 198 | ) else { |
| 199 | continue; |
| 200 | }; |
| 201 | let midr = cpus.first().and_then(|c| { |
| 202 | read_trim(&sysfs_root.join(format!( |
| 203 | "devices/system/cpu/cpu{c}/regs/identification/midr_el1" |
| 204 | ))) |
| 205 | }); |
| 206 | let core_class = midr |
| 207 | .as_deref() |
| 208 | .and_then(|m| u64::from_str_radix(m.trim_start_matches("0x"), 16).ok()) |
| 209 | .map(CoreClass::from_midr) |
| 210 | .unwrap_or(CoreClass::Unknown); |
| 211 | let events = EVENTS |
| 212 | .iter() |
| 213 | .map(|spec| { |
| 214 | let enc = read_trim(&d.join("events").join(spec.name)); |
| 215 | let verified = enc |
| 216 | .as_deref() |
| 217 | .and_then(parse_event_encoding) |
| 218 | .is_some_and(|v| v == u64::from(spec.arm_event)); |
| 219 | EventDiscovery { |
| 220 | name: spec.name.into(), |
| 221 | arm_event: spec.arm_event, |
| 222 | sysfs_encoding: enc, |
| 223 | verified, |
| 224 | } |
| 225 | }) |
| 226 | .collect(); |
| 227 | devices.push(PmuDevice { |
| 228 | name, |
| 229 | perf_type, |
| 230 | cpus, |
| 231 | core_class, |
| 232 | midr, |
| 233 | events, |
| 234 | }); |
| 235 | } |
| 236 | Discovery { |
| 237 | sysfs_root: sysfs_root.display().to_string(), |
| 238 | perf_event_paranoid: read_trim(paranoid_path).and_then(|s| s.parse().ok()), |
| 239 | devices, |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | /// Discovery on the running host. |
| 244 | pub fn discover_host() -> Discovery { |
| 245 | discover( |
| 246 | Path::new(SYSFS_ROOT), |
| 247 | Path::new("/proc/sys/kernel/perf_event_paranoid"), |
| 248 | ) |
| 249 | } |
| 250 | |
| 251 | /// Whether counters are opened at all. |
| 252 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 253 | pub enum PmuMode { |
| 254 | /// No system call, no counter, no file descriptor (default and every control run). |
| 255 | Disabled, |
| 256 | Enabled, |
| 257 | } |
| 258 | |
| 259 | /// Affinity of the measured thread (and every thread it creates) during a window. |
| 260 | /// Serialized as `unpinned`, `a725` or `x925`. |
| 261 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] |
| 262 | #[serde(try_from = "String", into = "String")] |
| 263 | pub enum AffinityPolicy { |
| 264 | /// Scheduler's choice; a counter that ran part of the window cannot tell migration |
| 265 | /// from multiplexing and is reported as `PartialResidency`. |
| 266 | Unpinned, |
| 267 | /// Pinned to every CPU of one core class. |
| 268 | Pinned(CoreClass), |
| 269 | } |
| 270 | |
| 271 | impl TryFrom<String> for AffinityPolicy { |
| 272 | type Error = String; |
| 273 | fn try_from(s: String) -> Result<Self, String> { |
| 274 | Self::parse(&s).ok_or_else(|| format!("affinity {s:?}: expected unpinned, a725 or x925")) |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | impl From<AffinityPolicy> for String { |
| 279 | fn from(a: AffinityPolicy) -> String { |
| 280 | a.code().to_string() |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | impl AffinityPolicy { |
| 285 | pub fn parse(s: &str) -> Option<Self> { |
| 286 | match s { |
| 287 | "unpinned" => Some(Self::Unpinned), |
| 288 | "a725" => Some(Self::Pinned(CoreClass::CortexA725)), |
| 289 | "x925" => Some(Self::Pinned(CoreClass::CortexX925)), |
| 290 | _ => None, |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | pub fn code(self) -> &'static str { |
| 295 | match self { |
| 296 | Self::Unpinned => "unpinned", |
| 297 | Self::Pinned(c) => c.code(), |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | /// Why a sample has no counts. Serialized next to `status: INSTRUMENT_UNAVAILABLE`. |
| 303 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 304 | #[serde(rename_all = "SCREAMING_SNAKE_CASE")] |
| 305 | pub enum UnavailableReason { |
| 306 | /// `EACCES` or `EPERM` (CAP_PERFMON missing or `perf_event_paranoid` too high). |
| 307 | PermissionDenied, |
| 308 | /// The PMU's sysfs description lacks the event or gives another number, or the |
| 309 | /// kernel refuses the type or config (`ENOENT`, `ENODEV`, `EOPNOTSUPP`). |
| 310 | UnsupportedEvent, |
| 311 | /// Any other open, enable, disable, or read failure (`EINVAL`, `EBUSY`, `EMFILE`...). |
| 312 | CounterUnavailable, |
| 313 | /// No CPU PMU in sysfs. |
| 314 | NoPmu, |
| 315 | /// Not Linux, or the kernel has no `perf_event_open` (`ENOSYS`). |
| 316 | UnsupportedPlatform, |
| 317 | } |
| 318 | |
| 319 | impl UnavailableReason { |
| 320 | /// Classify an errno from `perf_event_open`. |
| 321 | pub fn from_open_errno(errno: i32) -> Self { |
| 322 | match errno { |
| 323 | libc::EACCES | libc::EPERM => Self::PermissionDenied, |
| 324 | libc::ENOENT | libc::ENODEV | libc::EOPNOTSUPP => Self::UnsupportedEvent, |
| 325 | libc::ENOSYS => Self::UnsupportedPlatform, |
| 326 | _ => Self::CounterUnavailable, |
| 327 | } |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | /// How a counter that was read relates to the window. |
| 332 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 333 | #[serde(rename_all = "SCREAMING_SNAKE_CASE")] |
| 334 | pub enum CounterState { |
| 335 | /// `time_running == time_enabled > 0`: counted for the whole time the task ran. |
| 336 | Counted, |
| 337 | /// Pinned to this PMU's class and `0 < time_running < time_enabled`: the kernel |
| 338 | /// time-shared the hardware counter. The raw count covers only `time_running`. |
| 339 | Multiplexed, |
| 340 | /// Unpinned and `0 < time_running < time_enabled`: the task migrated between core |
| 341 | /// classes and/or the counter was multiplexed; the two cannot be told apart. |
| 342 | PartialResidency, |
| 343 | /// `time_running == 0` and count 0: the task never ran on this class. |
| 344 | NotScheduled, |
| 345 | } |
| 346 | |
| 347 | /// A read that contradicts the counter contract (refused, never repaired). |
| 348 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 349 | pub enum MalformedRead { |
| 350 | RunningExceedsEnabled { running: u64, enabled: u64 }, |
| 351 | CountWithoutRunningTime { value: u64 }, |
| 352 | } |
| 353 | |
| 354 | impl std::fmt::Display for MalformedRead { |
| 355 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 356 | match self { |
| 357 | Self::RunningExceedsEnabled { running, enabled } => { |
| 358 | write!( |
| 359 | f, |
| 360 | "time_running {running} ns exceeds time_enabled {enabled} ns" |
| 361 | ) |
| 362 | } |
| 363 | Self::CountWithoutRunningTime { value } => { |
| 364 | write!(f, "count {value} with zero time_running") |
| 365 | } |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | /// Classify one `(value, time_enabled, time_running)` read. Pure: used both when |
| 371 | /// sampling and when verifying sealed evidence. |
| 372 | pub fn classify( |
| 373 | value: u64, |
| 374 | enabled_ns: u64, |
| 375 | running_ns: u64, |
| 376 | pinned_to_this_class: bool, |
| 377 | ) -> Result<CounterState, MalformedRead> { |
| 378 | if running_ns > enabled_ns { |
| 379 | return Err(MalformedRead::RunningExceedsEnabled { |
| 380 | running: running_ns, |
| 381 | enabled: enabled_ns, |
| 382 | }); |
| 383 | } |
| 384 | if running_ns == 0 { |
| 385 | return if value == 0 { |
| 386 | Ok(CounterState::NotScheduled) |
| 387 | } else { |
| 388 | Err(MalformedRead::CountWithoutRunningTime { value }) |
| 389 | }; |
| 390 | } |
| 391 | Ok(if running_ns == enabled_ns { |
| 392 | CounterState::Counted |
| 393 | } else if pinned_to_this_class { |
| 394 | CounterState::Multiplexed |
| 395 | } else { |
| 396 | CounterState::PartialResidency |
| 397 | }) |
| 398 | } |
| 399 | |
| 400 | /// One counter read. `raw_count` is exactly what the kernel returned, never scaled. |
| 401 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 402 | pub struct CounterReading { |
| 403 | pub event: String, |
| 404 | pub arm_event: u16, |
| 405 | pub pmu: String, |
| 406 | pub core_class: CoreClass, |
| 407 | pub raw_count: u64, |
| 408 | pub time_enabled_ns: u64, |
| 409 | pub time_running_ns: u64, |
| 410 | pub state: CounterState, |
| 411 | } |
| 412 | |
| 413 | /// Outcome of one instrumented window. |
| 414 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 415 | #[serde(tag = "status", rename_all = "SCREAMING_SNAKE_CASE")] |
| 416 | pub enum PmuSample { |
| 417 | /// Control run: no counters were opened. |
| 418 | Disabled, |
| 419 | /// Counters could not be used. No counts exist for this window. |
| 420 | InstrumentUnavailable { |
| 421 | reason: UnavailableReason, |
| 422 | detail: String, |
| 423 | }, |
| 424 | Counted { |
| 425 | readings: Vec<CounterReading>, |
| 426 | }, |
| 427 | } |
| 428 | |
| 429 | /// `perf_event_attr` truncated to `PERF_ATTR_SIZE_VER0` (64 bytes), which every kernel |
| 430 | /// since 2.6.31 accepts (`perf_event_open(2)`, `size` field). Field order and widths |
| 431 | /// follow `include/uapi/linux/perf_event.h`. |
| 432 | #[repr(C)] |
| 433 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 434 | pub struct PerfEventAttr { |
| 435 | pub type_: u32, |
| 436 | pub size: u32, |
| 437 | pub config: u64, |
| 438 | pub sample_period: u64, |
| 439 | pub sample_type: u64, |
| 440 | pub read_format: u64, |
| 441 | /// Bit field: bit 0 `disabled`, 1 `inherit`, 5 `exclude_kernel`, 6 `exclude_hv`. |
| 442 | pub flags: u64, |
| 443 | pub wakeup_events: u32, |
| 444 | pub bp_type: u32, |
| 445 | pub config1: u64, |
| 446 | } |
| 447 | |
| 448 | pub const PERF_ATTR_SIZE_VER0: u32 = 64; |
| 449 | const _: () = assert!(std::mem::size_of::<PerfEventAttr>() == PERF_ATTR_SIZE_VER0 as usize); |
| 450 | |
| 451 | pub const PERF_FORMAT_TOTAL_TIME_ENABLED: u64 = 1 << 0; |
| 452 | pub const PERF_FORMAT_TOTAL_TIME_RUNNING: u64 = 1 << 1; |
| 453 | pub const ATTR_FLAG_DISABLED: u64 = 1 << 0; |
| 454 | pub const ATTR_FLAG_INHERIT: u64 = 1 << 1; |
| 455 | pub const ATTR_FLAG_EXCLUDE_KERNEL: u64 = 1 << 5; |
| 456 | pub const ATTR_FLAG_EXCLUDE_HV: u64 = 1 << 6; |
| 457 | /// `_IO('$', 0)`, `_IO('$', 1)`, `_IO('$', 3)`. |
| 458 | pub const PERF_EVENT_IOC_ENABLE: u64 = 0x2400; |
| 459 | pub const PERF_EVENT_IOC_DISABLE: u64 = 0x2401; |
| 460 | pub const PERF_EVENT_IOC_RESET: u64 = 0x2403; |
| 461 | pub const PERF_IOC_FLAG_GROUP: u64 = 1; |
| 462 | pub const PERF_FLAG_FD_CLOEXEC: u64 = 1 << 3; |
| 463 | |
| 464 | /// Attribute for one counting event on `pmu`: user space only, inherited by threads |
| 465 | /// created after the open; the group leader starts disabled. |
| 466 | pub fn event_attr(perf_type: u32, arm_event: u16, leader: bool) -> PerfEventAttr { |
| 467 | let mut flags = ATTR_FLAG_INHERIT | ATTR_FLAG_EXCLUDE_KERNEL | ATTR_FLAG_EXCLUDE_HV; |
| 468 | if leader { |
| 469 | flags |= ATTR_FLAG_DISABLED; |
| 470 | } |
| 471 | PerfEventAttr { |
| 472 | type_: perf_type, |
| 473 | size: PERF_ATTR_SIZE_VER0, |
| 474 | config: u64::from(arm_event), |
| 475 | read_format: PERF_FORMAT_TOTAL_TIME_ENABLED | PERF_FORMAT_TOTAL_TIME_RUNNING, |
| 476 | flags, |
| 477 | ..Default::default() |
| 478 | } |
| 479 | } |
| 480 | |
| 481 | /// The system calls a session makes. [`LinuxPerf`] is the real one; tests script a |
| 482 | /// fake to exercise refusals and multiplexing on any host. |
| 483 | pub trait PerfBackend { |
| 484 | /// `perf_event_open(attr, pid = 0, cpu = -1, group_fd, PERF_FLAG_FD_CLOEXEC)`. |
| 485 | fn open(&mut self, attr: &PerfEventAttr, group_fd: i32) -> Result<i32, i32>; |
| 486 | fn ioctl_group(&mut self, fd: i32, request: u64) -> Result<(), i32>; |
| 487 | /// `[value, time_enabled, time_running]`. |
| 488 | fn read3(&mut self, fd: i32) -> Result<[u64; 3], i32>; |
| 489 | fn close(&mut self, fd: i32); |
| 490 | } |
| 491 | |
| 492 | /// Real backend: `libc::syscall(SYS_perf_event_open, ...)`. |
| 493 | #[derive(Debug, Default)] |
| 494 | pub struct LinuxPerf; |
| 495 | |
| 496 | fn last_errno() -> i32 { |
| 497 | std::io::Error::last_os_error() |
| 498 | .raw_os_error() |
| 499 | .unwrap_or(libc::EIO) |
| 500 | } |
| 501 | |
| 502 | impl PerfBackend for LinuxPerf { |
| 503 | #[cfg(target_os = "linux")] |
| 504 | fn open(&mut self, attr: &PerfEventAttr, group_fd: i32) -> Result<i32, i32> { |
| 505 | // SAFETY: `attr` points to a live, initialized 64-byte `perf_event_attr` whose |
| 506 | // `size` field says 64; the kernel only reads it (or writes `size` on E2BIG, |
| 507 | // which cannot happen for VER0). pid 0 = calling thread, cpu -1 = any CPU. |
| 508 | let fd = unsafe { |
| 509 | libc::syscall( |
| 510 | libc::SYS_perf_event_open, |
| 511 | attr as *const PerfEventAttr, |
| 512 | 0 as libc::pid_t, |
| 513 | -1 as libc::c_int, |
| 514 | group_fd as libc::c_int, |
| 515 | PERF_FLAG_FD_CLOEXEC as libc::c_ulong, |
| 516 | ) |
| 517 | }; |
| 518 | if fd < 0 { |
| 519 | Err(last_errno()) |
| 520 | } else { |
| 521 | Ok(fd as i32) |
| 522 | } |
| 523 | } |
| 524 | |
| 525 | #[cfg(not(target_os = "linux"))] |
| 526 | fn open(&mut self, _attr: &PerfEventAttr, _group_fd: i32) -> Result<i32, i32> { |
| 527 | Err(libc::ENOSYS) |
| 528 | } |
| 529 | |
| 530 | fn ioctl_group(&mut self, fd: i32, request: u64) -> Result<(), i32> { |
| 531 | // SAFETY: `fd` is a perf event fd this session opened and still owns; the |
| 532 | // enable/disable/reset requests take an integer flag argument, no pointer. |
| 533 | let rc = unsafe { libc::ioctl(fd, request as _, PERF_IOC_FLAG_GROUP) }; |
| 534 | if rc < 0 { |
| 535 | Err(last_errno()) |
| 536 | } else { |
| 537 | Ok(()) |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | fn read3(&mut self, fd: i32) -> Result<[u64; 3], i32> { |
| 542 | let mut buf = [0u64; 3]; |
| 543 | // SAFETY: `buf` is 24 writable bytes owned by this frame; `fd` is owned. |
| 544 | let n = unsafe { libc::read(fd, buf.as_mut_ptr().cast(), std::mem::size_of_val(&buf)) }; |
| 545 | if n < 0 { |
| 546 | Err(last_errno()) |
| 547 | } else if n as usize != std::mem::size_of_val(&buf) { |
| 548 | Err(libc::EIO) |
| 549 | } else { |
| 550 | Ok(buf) |
| 551 | } |
| 552 | } |
| 553 | |
| 554 | fn close(&mut self, fd: i32) { |
| 555 | // SAFETY: closes an fd this session opened exactly once. |
| 556 | unsafe { libc::close(fd) }; |
| 557 | } |
| 558 | } |
| 559 | |
| 560 | struct OpenEvent { |
| 561 | fd: i32, |
| 562 | spec: EventSpec, |
| 563 | } |
| 564 | |
| 565 | struct OpenGroup { |
| 566 | device: PmuDevice, |
| 567 | events: Vec<OpenEvent>, |
| 568 | } |
| 569 | |
| 570 | /// Counters for one measured window. Open before the window (and before the window |
| 571 | /// creates threads, so `inherit` covers them), then [`PmuSession::start`] and |
| 572 | /// [`PmuSession::stop`] around the measured work. |
| 573 | pub struct PmuSession<B: PerfBackend> { |
| 574 | backend: B, |
| 575 | groups: Vec<OpenGroup>, |
| 576 | refusal: Option<(UnavailableReason, String)>, |
| 577 | mode: PmuMode, |
| 578 | affinity: AffinityPolicy, |
| 579 | } |
| 580 | |
| 581 | impl<B: PerfBackend> PmuSession<B> { |
| 582 | /// Open one group per discovered device. Fails closed: any refusal closes every |
| 583 | /// fd already opened and the session yields only `InstrumentUnavailable`. |
| 584 | /// `PmuMode::Disabled` touches nothing. |
| 585 | pub fn open( |
| 586 | backend: B, |
| 587 | mode: PmuMode, |
| 588 | discovery: &Discovery, |
| 589 | affinity: AffinityPolicy, |
| 590 | ) -> Self { |
| 591 | let mut s = Self { |
| 592 | groups: Vec::new(), |
| 593 | refusal: None, |
| 594 | mode, |
| 595 | affinity, |
| 596 | backend, |
| 597 | }; |
| 598 | if mode == PmuMode::Disabled { |
| 599 | return s; |
| 600 | } |
| 601 | if discovery.devices.is_empty() { |
| 602 | s.refusal = Some(( |
| 603 | UnavailableReason::NoPmu, |
| 604 | format!( |
| 605 | "no CPU PMU under {}/bus/event_source/devices", |
| 606 | discovery.sysfs_root |
| 607 | ), |
| 608 | )); |
| 609 | return s; |
| 610 | } |
| 611 | if let Some(d) = discovery.devices.iter().find(|d| !d.all_events_verified()) { |
| 612 | let missing: Vec<String> = d |
| 613 | .events |
| 614 | .iter() |
| 615 | .filter(|e| !e.verified) |
| 616 | .map(|e| format!("{} (sysfs {:?})", e.name, e.sysfs_encoding)) |
| 617 | .collect(); |
| 618 | s.refusal = Some(( |
| 619 | UnavailableReason::UnsupportedEvent, |
| 620 | format!( |
| 621 | "{}: event description absent or not the architected number: {}", |
| 622 | d.name, |
| 623 | missing.join(", ") |
| 624 | ), |
| 625 | )); |
| 626 | return s; |
| 627 | } |
| 628 | for d in &discovery.devices { |
| 629 | let mut group = OpenGroup { |
| 630 | device: d.clone(), |
| 631 | events: Vec::new(), |
| 632 | }; |
| 633 | let mut leader_fd = -1; |
| 634 | for (i, spec) in EVENTS.iter().enumerate() { |
| 635 | let attr = event_attr(d.perf_type, spec.arm_event, i == 0); |
| 636 | match s.backend.open(&attr, leader_fd) { |
| 637 | Ok(fd) => { |
| 638 | if i == 0 { |
| 639 | leader_fd = fd; |
| 640 | } |
| 641 | group.events.push(OpenEvent { fd, spec: *spec }); |
| 642 | } |
| 643 | Err(errno) => { |
| 644 | s.groups.push(group); |
| 645 | s.close_all(); |
| 646 | s.refusal = Some(( |
| 647 | UnavailableReason::from_open_errno(errno), |
| 648 | format!( |
| 649 | "perf_event_open({} type {} event {:#06x} {}): {}", |
| 650 | d.name, |
| 651 | d.perf_type, |
| 652 | spec.arm_event, |
| 653 | spec.name, |
| 654 | std::io::Error::from_raw_os_error(errno) |
| 655 | ), |
| 656 | )); |
| 657 | return s; |
| 658 | } |
| 659 | } |
| 660 | } |
| 661 | s.groups.push(group); |
| 662 | } |
| 663 | s |
| 664 | } |
| 665 | |
| 666 | fn close_all(&mut self) { |
| 667 | for g in self.groups.drain(..) { |
| 668 | for e in g.events.iter().rev() { |
| 669 | self.backend.close(e.fd); |
| 670 | } |
| 671 | } |
| 672 | } |
| 673 | |
| 674 | fn group_ioctl(&mut self, request: u64, what: &str) { |
| 675 | if self.refusal.is_some() { |
| 676 | return; |
| 677 | } |
| 678 | let leaders: Vec<(String, i32)> = self |
| 679 | .groups |
| 680 | .iter() |
| 681 | .filter_map(|g| g.events.first().map(|e| (g.device.name.clone(), e.fd))) |
| 682 | .collect(); |
| 683 | for (name, fd) in leaders { |
| 684 | if let Err(errno) = self.backend.ioctl_group(fd, request) { |
| 685 | self.refusal = Some(( |
| 686 | UnavailableReason::CounterUnavailable, |
| 687 | format!( |
| 688 | "{what} {name}: {}", |
| 689 | std::io::Error::from_raw_os_error(errno) |
| 690 | ), |
| 691 | )); |
| 692 | return; |
| 693 | } |
| 694 | } |
| 695 | } |
| 696 | |
| 697 | /// Reset and enable every group (no-op when disabled or refused). |
| 698 | pub fn start(&mut self) { |
| 699 | if self.mode == PmuMode::Disabled { |
| 700 | return; |
| 701 | } |
| 702 | self.group_ioctl(PERF_EVENT_IOC_RESET, "reset"); |
| 703 | self.group_ioctl(PERF_EVENT_IOC_ENABLE, "enable"); |
| 704 | } |
| 705 | |
| 706 | /// Disable, read, classify, and close every counter. |
| 707 | pub fn stop(mut self) -> PmuSample { |
| 708 | if self.mode == PmuMode::Disabled { |
| 709 | return PmuSample::Disabled; |
| 710 | } |
| 711 | self.group_ioctl(PERF_EVENT_IOC_DISABLE, "disable"); |
| 712 | let mut readings = Vec::new(); |
| 713 | if self.refusal.is_none() { |
| 714 | 'outer: for gi in 0..self.groups.len() { |
| 715 | let dev = self.groups[gi].device.clone(); |
| 716 | let pinned_here = self.affinity == AffinityPolicy::Pinned(dev.core_class) |
| 717 | && dev.core_class != CoreClass::Unknown; |
| 718 | for ei in 0..self.groups[gi].events.len() { |
| 719 | let (fd, spec) = { |
| 720 | let e = &self.groups[gi].events[ei]; |
| 721 | (e.fd, e.spec) |
| 722 | }; |
| 723 | let raw = match self.backend.read3(fd) { |
| 724 | Ok(v) => v, |
| 725 | Err(errno) => { |
| 726 | self.refusal = Some(( |
| 727 | UnavailableReason::CounterUnavailable, |
| 728 | format!( |
| 729 | "read {} {}: {}", |
| 730 | dev.name, |
| 731 | spec.name, |
| 732 | std::io::Error::from_raw_os_error(errno) |
| 733 | ), |
| 734 | )); |
| 735 | break 'outer; |
| 736 | } |
| 737 | }; |
| 738 | match classify(raw[0], raw[1], raw[2], pinned_here) { |
| 739 | Ok(state) => readings.push(CounterReading { |
| 740 | event: spec.name.into(), |
| 741 | arm_event: spec.arm_event, |
| 742 | pmu: dev.name.clone(), |
| 743 | core_class: dev.core_class, |
| 744 | raw_count: raw[0], |
| 745 | time_enabled_ns: raw[1], |
| 746 | time_running_ns: raw[2], |
| 747 | state, |
| 748 | }), |
| 749 | Err(m) => { |
| 750 | self.refusal = Some(( |
| 751 | UnavailableReason::CounterUnavailable, |
| 752 | format!("{} {}: malformed read: {m}", dev.name, spec.name), |
| 753 | )); |
| 754 | break 'outer; |
| 755 | } |
| 756 | } |
| 757 | } |
| 758 | } |
| 759 | } |
| 760 | self.close_all(); |
| 761 | match self.refusal.take() { |
| 762 | Some((reason, detail)) => PmuSample::InstrumentUnavailable { reason, detail }, |
| 763 | None => PmuSample::Counted { readings }, |
| 764 | } |
| 765 | } |
| 766 | } |
| 767 | |
| 768 | impl<B: PerfBackend> Drop for PmuSession<B> { |
| 769 | fn drop(&mut self) { |
| 770 | self.close_all(); |
| 771 | } |
| 772 | } |
| 773 | |
| 774 | /// The calling thread's CPU affinity, so a pinned window can restore it afterwards. |
| 775 | pub struct AffinityGuard { |
| 776 | #[cfg(target_os = "linux")] |
| 777 | saved: Option<libc::cpu_set_t>, |
| 778 | } |
| 779 | |
| 780 | /// Pin the calling thread (threads it creates inherit the mask) to `cpus`. |
| 781 | /// `AffinityPolicy::Unpinned` changes nothing. |
| 782 | pub fn apply_affinity( |
| 783 | policy: AffinityPolicy, |
| 784 | discovery: &Discovery, |
| 785 | ) -> Result<AffinityGuard, String> { |
| 786 | let cpus: Vec<usize> = match policy { |
| 787 | AffinityPolicy::Unpinned => { |
| 788 | return Ok(AffinityGuard { |
| 789 | #[cfg(target_os = "linux")] |
| 790 | saved: None, |
| 791 | }) |
| 792 | } |
| 793 | AffinityPolicy::Pinned(class) => discovery |
| 794 | .devices |
| 795 | .iter() |
| 796 | .filter(|d| d.core_class == class) |
| 797 | .flat_map(|d| d.cpus.iter().copied()) |
| 798 | .collect(), |
| 799 | }; |
| 800 | if cpus.is_empty() { |
| 801 | return Err(format!( |
| 802 | "affinity {}: no PMU in sysfs names that core class", |
| 803 | policy.code() |
| 804 | )); |
| 805 | } |
| 806 | pin_to(&cpus) |
| 807 | } |
| 808 | |
| 809 | #[cfg(target_os = "linux")] |
| 810 | fn pin_to(cpus: &[usize]) -> Result<AffinityGuard, String> { |
| 811 | // SAFETY: `cpu_set_t` is a plain bit array; all-zero is the empty set. |
| 812 | let mut saved: libc::cpu_set_t = unsafe { std::mem::zeroed() }; |
| 813 | // SAFETY: `saved` is a valid, exclusively borrowed cpu_set_t of the given size. |
| 814 | let rc = |
| 815 | unsafe { libc::sched_getaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &mut saved) }; |
| 816 | if rc != 0 { |
| 817 | return Err(format!( |
| 818 | "sched_getaffinity: {}", |
| 819 | std::io::Error::last_os_error() |
| 820 | )); |
| 821 | } |
| 822 | // SAFETY: as above. |
| 823 | let mut set: libc::cpu_set_t = unsafe { std::mem::zeroed() }; |
| 824 | for &c in cpus { |
| 825 | if c >= libc::CPU_SETSIZE as usize { |
| 826 | return Err(format!("cpu {c} outside cpu_set_t")); |
| 827 | } |
| 828 | // SAFETY: `c` is checked against CPU_SETSIZE above. |
| 829 | unsafe { libc::CPU_SET(c, &mut set) }; |
| 830 | } |
| 831 | // SAFETY: `set` is a valid cpu_set_t; pid 0 is the calling thread. |
| 832 | let rc = unsafe { libc::sched_setaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &set) }; |
| 833 | if rc != 0 { |
| 834 | return Err(format!( |
| 835 | "sched_setaffinity: {}", |
| 836 | std::io::Error::last_os_error() |
| 837 | )); |
| 838 | } |
| 839 | Ok(AffinityGuard { saved: Some(saved) }) |
| 840 | } |
| 841 | |
| 842 | #[cfg(not(target_os = "linux"))] |
| 843 | fn pin_to(_cpus: &[usize]) -> Result<AffinityGuard, String> { |
| 844 | Err("CPU affinity is only implemented on Linux".into()) |
| 845 | } |
| 846 | |
| 847 | impl Drop for AffinityGuard { |
| 848 | fn drop(&mut self) { |
| 849 | #[cfg(target_os = "linux")] |
| 850 | if let Some(saved) = self.saved.take() { |
| 851 | // SAFETY: restores the mask read by `pin_to` on the same thread. |
| 852 | unsafe { libc::sched_setaffinity(0, std::mem::size_of::<libc::cpu_set_t>(), &saved) }; |
| 853 | } |
| 854 | } |
| 855 | } |