aya_ebpf/maps/perf/
perf_event_array.rs1use core::{cell::UnsafeCell, marker::PhantomData, mem};
2
3use crate::{
4 bindings::{bpf_map_def, bpf_map_type::BPF_MAP_TYPE_PERF_EVENT_ARRAY, BPF_F_CURRENT_CPU},
5 helpers::bpf_perf_event_output,
6 maps::PinningType,
7 EbpfContext,
8};
9
10#[repr(transparent)]
11pub struct PerfEventArray<T> {
12 def: UnsafeCell<bpf_map_def>,
13 _t: PhantomData<T>,
14}
15
16unsafe impl<T: Sync> Sync for PerfEventArray<T> {}
17
18impl<T> PerfEventArray<T> {
19 pub const fn new(flags: u32) -> PerfEventArray<T> {
20 PerfEventArray {
21 def: UnsafeCell::new(bpf_map_def {
22 type_: BPF_MAP_TYPE_PERF_EVENT_ARRAY,
23 key_size: mem::size_of::<u32>() as u32,
24 value_size: mem::size_of::<u32>() as u32,
25 max_entries: 0,
26 map_flags: flags,
27 id: 0,
28 pinning: PinningType::None as u32,
29 }),
30 _t: PhantomData,
31 }
32 }
33
34 pub const fn pinned(flags: u32) -> PerfEventArray<T> {
35 PerfEventArray {
36 def: UnsafeCell::new(bpf_map_def {
37 type_: BPF_MAP_TYPE_PERF_EVENT_ARRAY,
38 key_size: mem::size_of::<u32>() as u32,
39 value_size: mem::size_of::<u32>() as u32,
40 max_entries: 0,
41 map_flags: flags,
42 id: 0,
43 pinning: PinningType::ByName as u32,
44 }),
45 _t: PhantomData,
46 }
47 }
48
49 pub fn output<C: EbpfContext>(&self, ctx: &C, data: &T, flags: u32) {
50 self.output_at_index(ctx, BPF_F_CURRENT_CPU as u32, data, flags)
51 }
52
53 pub fn output_at_index<C: EbpfContext>(&self, ctx: &C, index: u32, data: &T, flags: u32) {
54 let flags = u64::from(flags) << 32 | u64::from(index);
55 unsafe {
56 bpf_perf_event_output(
57 ctx.as_ptr(),
58 self.def.get() as *mut _,
59 flags,
60 data as *const _ as *mut _,
61 mem::size_of::<T>() as u64,
62 );
63 }
64 }
65}