Skip to content

Commit

Permalink
aya-bpf: Add docs to map types and methods
Browse files Browse the repository at this point in the history
Signed-off-by: Michal Rostecki <[email protected]>
  • Loading branch information
vadorovsky committed Feb 27, 2023
1 parent d9878a6 commit e0f2aed
Show file tree
Hide file tree
Showing 5 changed files with 260 additions and 1 deletion.
142 changes: 142 additions & 0 deletions bpf/aya-bpf/src/maps/hash_map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,28 @@ use crate::{
maps::PinningType,
};

/// A hash map that can be shared between eBPF programs and user space.
///
/// # Minimum kernel version
///
/// The minimum kernel version required to use this feature is 3.19.
///
/// # Examples
///
/// ```no_run
/// use aya_bpf::{macros::map, maps::HashMap};
/// # use aya_bpf::programs::LsmContext;
///
/// #[map]
/// static mut MY_MAP: HashMap<u32, u32> = HashMap::with_max_entries(1024, 0);
///
/// # unsafe fn try_test(ctx: &LsmContext) -> Result<i32, i32> {
/// let key: u32 = 13;
/// let value: u32 = 42;
/// MY_MAP.insert(&key, &value, 0).map_err(|e| e as i32)?;
/// # Ok(0)
/// # }
/// ```
#[repr(transparent)]
pub struct HashMap<K, V> {
def: UnsafeCell<bpf_map_def>,
Expand All @@ -21,6 +43,16 @@ pub struct HashMap<K, V> {
unsafe impl<K: Sync, V: Sync> Sync for HashMap<K, V> {}

impl<K, V> HashMap<K, V> {
/// Creates a `HashMap` with the maximum number of elements.
///
/// # Examples
///
/// ```no_run
/// use aya_bpf::{macros::map, maps::HashMap};
///
/// #[map]
/// static mut MY_MAP: HashMap<u32, u32> = HashMap::with_max_entries(1024, 0);
/// ```
pub const fn with_max_entries(max_entries: u32, flags: u32) -> HashMap<K, V> {
HashMap {
def: UnsafeCell::new(build_def::<K, V>(
Expand All @@ -34,6 +66,17 @@ impl<K, V> HashMap<K, V> {
}
}

/// Creates an empty `HashMap<K, V>` with the specified maximum number of
/// elements, and pins it to the BPF file system (BPFFS).
///
/// # Examples
///
/// ```no_run
/// use aya_bpf::{macros::map, maps::HashMap};
///
/// #[map]
/// static mut MY_MAP: HashMap<u32, u32> = HashMap::pinned(1024, 0);
/// ```
pub const fn pinned(max_entries: u32, flags: u32) -> HashMap<K, V> {
HashMap {
def: UnsafeCell::new(build_def::<K, V>(
Expand All @@ -52,6 +95,27 @@ impl<K, V> HashMap<K, V> {
/// make guarantee on the atomicity of `insert` or `remove`, and any element removed from the
/// map might get aliased by another element in the map, causing garbage to be read, or
/// corruption in case of writes.
///
/// # Examples
///
/// ```no_run
/// use aya_bpf::{macros::map, maps::HashMap};
/// # use aya_bpf::programs::XdpContext;
///
/// #[map]
/// static REDIRECT_PORTS: HashMap<u16, u16> = HashMap::with_max_entries(1024, 0);
///
/// # fn parse_source(ctx: &XdpContext) -> u16 { 0 }
/// # fn try_test(ctx: &XdpContext) -> Result<i32, i32> {
/// // Source port of the packet.
/// let source: u16 = parse_source(&ctx);
/// // Port to which we want redirect the packet to.
/// let redirect = MY_MAP.get(&source);
///
/// // Redirect the packet.
/// # Ok(0)
/// # }
/// ```
#[inline]
pub unsafe fn get(&self, key: &K) -> Option<&V> {
get(self.def.get(), key)
Expand All @@ -74,11 +138,47 @@ impl<K, V> HashMap<K, V> {
get_ptr_mut(self.def.get(), key)
}

/// Inserts a key-value pair into the map.
///
/// # Examples
///
/// ```no_run
/// use aya_bpf::{macros::map, maps::HashMap};
/// # use aya_bpf::programs::TracePointContext;
///
/// #[map]
/// static PID_TO_TGID: HashMap<u32, u32> = HashMap::with_max_entries(1024, 0);
///
/// # unsafe fn try_test(ctx: &LsmContext) -> Result<i32, i32> {
/// let pid: u32 = 13;
/// let tgid: u32 = 42;
/// PID_TO_TGID.insert(&pid, &tgid, 0).map_err(|e| e as i32)?;
/// # Ok(0)
/// # }
/// ```
#[inline]
pub fn insert(&self, key: &K, value: &V, flags: u64) -> Result<(), c_long> {
insert(self.def.get(), key, value, flags)
}

/// Removes a key-value pair from the map.
///
/// # Examples
///
/// ```no_run
/// use aya_bpf::{macros::map, maps::HashMap};
/// # use aya_bpf::programs::TracePointContext;
///
/// #[map]
/// PROCESSES: HashMap<u32, u32> = HashMap::with_max_entries(1024, 0);
///
/// # fn try_test(ctx: &TracePointContext) -> Result<i32, i32> {
/// let pid: u32 = ctx.pid();
/// // Remove the currently exiting process from the map.
/// PROCESSES.remove(&pid).map_err(|e| e as i32)?;
/// # Ok(0)
/// # }
/// ```
#[inline]
pub fn remove(&self, key: &K) -> Result<(), c_long> {
remove(self.def.get(), key)
Expand All @@ -95,6 +195,7 @@ pub struct LruHashMap<K, V> {
unsafe impl<K: Sync, V: Sync> Sync for LruHashMap<K, V> {}

impl<K, V> LruHashMap<K, V> {
/// Creates an `LruHashMap` with the maximum number of elements.
pub const fn with_max_entries(max_entries: u32, flags: u32) -> LruHashMap<K, V> {
LruHashMap {
def: UnsafeCell::new(build_def::<K, V>(
Expand All @@ -108,6 +209,8 @@ impl<K, V> LruHashMap<K, V> {
}
}

/// Creates an `LruHashMap` pinned in the BPFFS filesystem, with the maximum
/// number of elements.
pub const fn pinned(max_entries: u32, flags: u32) -> LruHashMap<K, V> {
LruHashMap {
def: UnsafeCell::new(build_def::<K, V>(
Expand Down Expand Up @@ -148,17 +251,46 @@ impl<K, V> LruHashMap<K, V> {
get_ptr_mut(self.def.get(), key)
}

/// Returns a mutable copy of the value associated with the key.
#[inline]
pub fn insert(&self, key: &K, value: &V, flags: u64) -> Result<(), c_long> {
insert(self.def.get(), key, value, flags)
}

/// Inserts a key-value pair into the map.
#[inline]
pub fn remove(&self, key: &K) -> Result<(), c_long> {
remove(self.def.get(), key)
}
}

/// A hash map that can be shared between eBPF programs and user space. Each
/// CPU has its own separate copy of the map. The copies are not synchronized
/// in any way.
///
/// Due to limits defined in the kernel, the `K` and `V` types cannot be larger
/// than 32KB in size.
///
/// # Minimum kernel version
///
/// The minimum kernel version required to use this feature is 4.6.
///
/// # Examples
///
/// ```no_run
/// use aya_bpf::{macros::map, maps::PerCpuHashMap};
/// # use aya_bpf::programs::LsmContext;
///
/// #[map]
/// static mut MY_MAP: PerCpuHashMap<u32, u32> = PerCpuHashMap::with_max_entries(1024, 0);
///
/// # unsafe fn try_test(ctx: &LsmContext) -> Result<i32, i32> {
/// let key: u32 = 13;
/// let value: u32 = 42;
/// MY_MAP.insert(&key, &value, 0).map_err(|e| e as i32)?;
/// # Ok(0)
/// # }
/// ```
#[repr(transparent)]
pub struct PerCpuHashMap<K, V> {
def: UnsafeCell<bpf_map_def>,
Expand All @@ -169,6 +301,7 @@ pub struct PerCpuHashMap<K, V> {
unsafe impl<K, V> Sync for PerCpuHashMap<K, V> {}

impl<K, V> PerCpuHashMap<K, V> {
/// Creates a `PerCpuHashMap` with the maximum number of elements.
pub const fn with_max_entries(max_entries: u32, flags: u32) -> PerCpuHashMap<K, V> {
PerCpuHashMap {
def: UnsafeCell::new(build_def::<K, V>(
Expand All @@ -182,6 +315,8 @@ impl<K, V> PerCpuHashMap<K, V> {
}
}

/// Creates a `PerCpuHashMap` pinned in the BPFFS filesystem, with the maximum
/// number of elements.
pub const fn pinned(max_entries: u32, flags: u32) -> PerCpuHashMap<K, V> {
PerCpuHashMap {
def: UnsafeCell::new(build_def::<K, V>(
Expand Down Expand Up @@ -222,11 +357,13 @@ impl<K, V> PerCpuHashMap<K, V> {
get_ptr_mut(self.def.get(), key)
}

/// Returns a mutable copy of the value associated with the key.
#[inline]
pub fn insert(&self, key: &K, value: &V, flags: u64) -> Result<(), c_long> {
insert(self.def.get(), key, value, flags)
}

/// Inserts a key-value pair into the map.
#[inline]
pub fn remove(&self, key: &K) -> Result<(), c_long> {
remove(self.def.get(), key)
Expand All @@ -243,6 +380,7 @@ pub struct LruPerCpuHashMap<K, V> {
unsafe impl<K, V> Sync for LruPerCpuHashMap<K, V> {}

impl<K, V> LruPerCpuHashMap<K, V> {
/// Creates an `LruPerCpuHashMap` with the maximum number of elements.
pub const fn with_max_entries(max_entries: u32, flags: u32) -> LruPerCpuHashMap<K, V> {
LruPerCpuHashMap {
def: UnsafeCell::new(build_def::<K, V>(
Expand All @@ -256,6 +394,8 @@ impl<K, V> LruPerCpuHashMap<K, V> {
}
}

/// Creates an `LruPerCpuHashMap` pinned in the BPFFS filesystem, with the maximum
/// number of elements.
pub const fn pinned(max_entries: u32, flags: u32) -> LruPerCpuHashMap<K, V> {
LruPerCpuHashMap {
def: UnsafeCell::new(build_def::<K, V>(
Expand Down Expand Up @@ -296,11 +436,13 @@ impl<K, V> LruPerCpuHashMap<K, V> {
get_ptr_mut(self.def.get(), key)
}

/// Returns a mutable copy of the value associated with the key.
#[inline]
pub fn insert(&self, key: &K, value: &V, flags: u64) -> Result<(), c_long> {
insert(self.def.get(), key, value, flags)
}

/// Inserts a key-value pair into the map.
#[inline]
pub fn remove(&self, key: &K) -> Result<(), c_long> {
remove(self.def.get(), key)
Expand Down
6 changes: 6 additions & 0 deletions bpf/aya-bpf/src/maps/lpm_trie.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ impl<K> Key<K> {
}

impl<K, V> LpmTrie<K, V> {
/// Creates an `LpmTrie` map with the maximum number of elements.
pub const fn with_max_entries(max_entries: u32, flags: u32) -> LpmTrie<K, V> {
let flags = flags | BPF_F_NO_PREALLOC;
LpmTrie {
Expand All @@ -47,6 +48,8 @@ impl<K, V> LpmTrie<K, V> {
}
}

/// Creates an `LpmTrie` map pinned in the BPPFS filesystem, with the
/// maximum number of elements.
pub const fn pinned(max_entries: u32, flags: u32) -> LpmTrie<K, V> {
let flags = flags | BPF_F_NO_PREALLOC;
LpmTrie {
Expand All @@ -61,6 +64,7 @@ impl<K, V> LpmTrie<K, V> {
}
}

/// Returns a copy of the value associated with the key.
#[inline]
pub fn get(&self, key: &Key<K>) -> Option<&V> {
unsafe {
Expand All @@ -71,6 +75,7 @@ impl<K, V> LpmTrie<K, V> {
}
}

/// Inserts a key-value pair into the map.
#[inline]
pub fn insert(&self, key: &Key<K>, value: &V, flags: u64) -> Result<(), c_long> {
let ret = unsafe {
Expand All @@ -84,6 +89,7 @@ impl<K, V> LpmTrie<K, V> {
(ret == 0).then_some(()).ok_or(ret)
}

/// Removes a key from the map.
#[inline]
pub fn remove(&self, key: &Key<K>) -> Result<(), c_long> {
let ret = unsafe {
Expand Down
39 changes: 39 additions & 0 deletions bpf/aya-bpf/src/maps/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,42 @@
//! Data structures used to store eBPF programs data and share them with the
//! user space.
//!
//! The eBPF platform provides data structures - maps in eBPF speak - that are
//! used store data and share it with the user space. When you define a static
//! variable of a map type (i.e. [`HashMap`](crate::maps::HashMap), that map gets
//! initialized during the eBPF object load into the kernel and is ready to
//! use by programs.
//!
//!
//! # Typed maps
//!
//! The eBPF API includes many map types each supporting different operations.
//!
//! Each type of map provides methods to access and modify the data in the map
//! (i.e. [`get`](crate::maps::HashMap::get), [`get_ptr_mut`](crate::maps::HashMap::get_ptr_mut),
//! [`insert`](crate::maps::HashMap::insert) and, [`remove`](crate::maps::HashMap::remove)).
//!
//! For example:
//!
//! ```no_run
//! # #![allow(dead_code)]
//! use aya_bpf::{macros::map, maps::HashMap};
//! # use aya_bpf::programs::TracePointContext;
//!
//! #[map]
//! static PID_TO_TGID: HashMap<u32, u32> = HashMap::with_max_entries(1024, 0);
//!
//! # fn try_test(ctx: &TracePointContext) -> Result<i32, i32> {
//! let pid: u32 = ctx.pid();
//! let tgid: u32 = ctx.tgid();
//! PID_TO_TGID.insert(&pid, &tgid, 0).map_err(|e| e as i32)?;
//! # Ok(0)
//! # }
//! ```
//!
//! Please refer to documentation for each map type for more details.
#[repr(u32)]
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) enum PinningType {
Expand Down
Loading

0 comments on commit e0f2aed

Please sign in to comment.