use core::{cell::UnsafeCell, mem, num::NonZeroU32, ptr::NonNull};
use aya_ebpf_bindings::bindings::bpf_devmap_val;
use aya_ebpf_cty::c_void;
use super::try_redirect_map;
use crate::{
bindings::{bpf_map_def, bpf_map_type::BPF_MAP_TYPE_DEVMAP},
helpers::bpf_map_lookup_elem,
maps::PinningType,
};
#[repr(transparent)]
pub struct DevMap {
def: UnsafeCell<bpf_map_def>,
}
unsafe impl Sync for DevMap {}
impl DevMap {
pub const fn with_max_entries(max_entries: u32, flags: u32) -> DevMap {
DevMap {
def: UnsafeCell::new(bpf_map_def {
type_: BPF_MAP_TYPE_DEVMAP,
key_size: mem::size_of::<u32>() as u32,
value_size: mem::size_of::<bpf_devmap_val>() as u32,
max_entries,
map_flags: flags,
id: 0,
pinning: PinningType::None as u32,
}),
}
}
pub const fn pinned(max_entries: u32, flags: u32) -> DevMap {
DevMap {
def: UnsafeCell::new(bpf_map_def {
type_: BPF_MAP_TYPE_DEVMAP,
key_size: mem::size_of::<u32>() as u32,
value_size: mem::size_of::<bpf_devmap_val>() as u32,
max_entries,
map_flags: flags,
id: 0,
pinning: PinningType::ByName as u32,
}),
}
}
#[inline(always)]
pub fn get(&self, index: u32) -> Option<DevMapValue> {
unsafe {
let value = bpf_map_lookup_elem(
self.def.get() as *mut _,
&index as *const _ as *const c_void,
);
NonNull::new(value as *mut bpf_devmap_val).map(|p| DevMapValue {
if_index: p.as_ref().ifindex,
prog_id: NonZeroU32::new(p.as_ref().bpf_prog.id),
})
}
}
#[inline(always)]
pub fn redirect(&self, index: u32, flags: u64) -> Result<u32, u32> {
try_redirect_map(&self.def, index, flags)
}
}
#[derive(Clone, Copy)]
pub struct DevMapValue {
pub if_index: u32,
pub prog_id: Option<NonZeroU32>,
}