1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
//! Owned perf ring destination shared by task and IRQ producers.
use alloc::sync::{Arc, Weak};
use core::{
any::Any,
sync::atomic::{AtomicBool, AtomicU64, Ordering},
};
struct PerfRingState {
ring_vaddr: usize,
ring_len: usize,
_anchor: Arc<dyn Any + Send + Sync>,
writer_active: AtomicBool,
lost_records: AtomicU64,
}
/// Kernel mapping geometry, lifetime, and producer serialization as one value.
#[derive(Clone)]
pub(crate) struct PerfRingOutput {
state: Arc<PerfRingState>,
}
/// Non-owning reference retained by an event while the VMA or a redirect owns
/// the actual ring output.
#[derive(Clone)]
pub(crate) struct PerfRingWeak {
state: Weak<PerfRingState>,
}
/// Context that owns a perf event's output.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PerfOutputScope {
/// Generation-bearing scheduler thread identity encoded as `u64`.
Task(u64),
/// Logical CPU id for a system-wide event.
Cpu(usize),
}
/// Invalid `PERF_EVENT_IOC_SET_OUTPUT` relationship.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PerfOutputRedirectError {
/// An event cannot redirect output to itself.
SameEvent,
/// Source and target do not share one task or CPU perf context.
DifferentScope,
}
/// Own-ring and redirect state with one coherent selection point.
pub(crate) struct PerfOutputRoute {
owned: Option<PerfRingWeak>,
redirect: Option<PerfRingOutput>,
}
impl core::fmt::Debug for PerfOutputRoute {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("PerfOutputRoute")
.field("has_own_ring", &self.owned().is_some())
.field("redirected", &self.redirect.is_some())
.finish()
}
}
/// Exclusive, bounded producer lease for one perf ring.
pub(crate) struct PerfRingWriteGuard<'a> {
state: &'a PerfRingState,
}
impl Drop for PerfRingWriteGuard<'_> {
fn drop(&mut self) {
self.state.writer_active.store(false, Ordering::Release);
}
}
impl PerfRingOutput {
/// Builds an output snapshot from live ring geometry.
pub(crate) fn new(
ring_vaddr: usize,
ring_len: usize,
anchor: Arc<dyn Any + Send + Sync>,
) -> Self {
Self {
state: Arc::new(PerfRingState {
ring_vaddr,
ring_len,
_anchor: anchor,
writer_active: AtomicBool::new(false),
lost_records: AtomicU64::new(0),
}),
}
}
/// Returns the kernel virtual address of the perf header page.
pub(crate) fn ring_vaddr(&self) -> usize {
self.state.ring_vaddr
}
/// Returns the complete mapping length, including the header page.
pub(crate) fn ring_len(&self) -> usize {
self.state.ring_len
}
/// Returns a non-owning event-side reference to this ring.
pub(crate) fn downgrade(&self) -> PerfRingWeak {
PerfRingWeak {
state: Arc::downgrade(&self.state),
}
}
/// Builds the opaque VMA retainer for this ring.
///
/// Retaining the complete output keeps both the backing pages and the
/// shared producer gate live for exactly as long as the mapping or a
/// redirected event can publish records.
pub(crate) fn mapping_anchor(&self) -> Arc<dyn Any + Send + Sync> {
Arc::new(self.clone())
}
/// Tries to reserve the ring for one kernel producer.
///
/// Hard-IRQ producers never wait: one failed CAS drops the record. Process
/// producers use the same gate, so a redirected or inherited output cannot
/// race an overflow running on another CPU.
pub(crate) fn try_begin_write(&self) -> Option<PerfRingWriteGuard<'_>> {
self.state
.writer_active
.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
.ok()
.map(|_| PerfRingWriteGuard { state: &self.state })
}
/// Accounts one record dropped because another producer owns the ring.
pub(crate) fn record_contention_drop(&self) {
self.state.lost_records.fetch_add(1, Ordering::Relaxed);
}
/// Returns the number of records dropped at the bounded writer gate.
#[cfg(all(test, not(axtest)))]
pub(crate) fn contention_drops(&self) -> u64 {
self.state.lost_records.load(Ordering::Relaxed)
}
}
impl PerfRingWeak {
/// Upgrades while either the user VMA or a redirect still owns the ring.
pub(crate) fn upgrade(&self) -> Option<PerfRingOutput> {
self.state.upgrade().map(|state| PerfRingOutput { state })
}
}
impl PerfOutputRoute {
/// Creates an event with no mmap ring and no redirect.
pub(crate) const fn new() -> Self {
Self {
owned: None,
redirect: None,
}
}
/// Publishes the event's own mmap ring without retaining the VMA.
pub(crate) fn publish_owned(&mut self, output: &PerfRingOutput) {
self.owned = Some(output.downgrade());
}
/// Returns the event's own ring while a VMA or redirect still pins it.
pub(crate) fn owned(&self) -> Option<PerfRingOutput> {
self.owned.as_ref()?.upgrade()
}
/// Returns the effective output and whether it is redirected.
pub(crate) fn effective(&self) -> Option<(PerfRingOutput, bool)> {
self.redirect
.clone()
.map(|output| (output, true))
.or_else(|| self.owned().map(|output| (output, false)))
}
/// Returns the currently selected output for use as another event's
/// redirect target. This follows an existing redirect, matching Linux's
/// output-chain semantics.
pub(crate) fn effective_output(&self) -> Option<PerfRingOutput> {
self.effective().map(|(output, _)| output)
}
/// Atomically replaces the redirect target.
pub(crate) fn redirect(&mut self, output: PerfRingOutput) {
self.redirect = Some(output);
}
/// Detaches a redirect so future writes use the event's own ring.
pub(crate) fn detach(&mut self) {
self.redirect = None;
}
/// Withdraws every output during final teardown.
pub(crate) fn clear(&mut self) {
self.redirect = None;
self.owned = None;
}
}
/// Validates the Linux same-context output relationship.
pub(crate) const fn validate_output_redirect(
source_id: u64,
target_id: u64,
source_scope: PerfOutputScope,
target_scope: PerfOutputScope,
) -> Result<(), PerfOutputRedirectError> {
if source_id == target_id {
return Err(PerfOutputRedirectError::SameEvent);
}
let same_scope = match (source_scope, target_scope) {
(PerfOutputScope::Task(source), PerfOutputScope::Task(target)) => source == target,
(PerfOutputScope::Cpu(source), PerfOutputScope::Cpu(target)) => source == target,
_ => false,
};
if !same_scope {
return Err(PerfOutputRedirectError::DifferentScope);
}
Ok(())
}