Skip to main content

aya_friday/maps/array/
per_cpu_array.rs

1use std::{
2    borrow::{Borrow, BorrowMut},
3    marker::PhantomData,
4    os::fd::AsFd as _,
5};
6
7use crate::{
8    Pod,
9    maps::{IterableMap, MapData, MapError, PerCpuValues, check_bounds, check_kv_size},
10    sys::{SyscallError, bpf_map_lookup_elem_per_cpu, bpf_map_update_elem_per_cpu},
11};
12
13/// A per-CPU fixed-size array.
14///
15/// The size of the array is defined on the eBPF side using the `bpf_map_def::max_entries` field.
16/// All the entries are zero-initialized when the map is created.
17///
18/// # Minimum kernel version
19///
20/// The minimum kernel version required to use this feature is 4.6.
21///
22/// # Examples
23/// ```no_run
24/// # #[derive(thiserror::Error, Debug)]
25/// # enum Error {
26/// #     #[error(transparent)]
27/// #     IO(#[from] std::io::Error),
28/// #     #[error(transparent)]
29/// #     Map(#[from] aya::maps::MapError),
30/// #     #[error(transparent)]
31/// #     Ebpf(#[from] aya::EbpfError)
32/// # }
33/// # let mut bpf = aya::Ebpf::load(&[])?;
34/// use aya::maps::{PerCpuArray, PerCpuValues};
35/// use aya::util::nr_cpus;
36///
37/// let mut array = PerCpuArray::try_from(bpf.map_mut("ARRAY").unwrap())?;
38///
39/// // set array[1] = 42 for all cpus
40/// let nr_cpus = nr_cpus().map_err(|(_, error)| error)?;
41/// array.set(1, PerCpuValues::try_from(vec![42u32; nr_cpus])?, 0)?;
42///
43/// // retrieve the values at index 1 for all cpus
44/// let values = array.get(&1, 0)?;
45/// assert_eq!(values.len(), nr_cpus);
46/// for cpu_val in values.iter() {
47///     assert_eq!(*cpu_val, 42u32);
48/// }
49/// # Ok::<(), Error>(())
50/// ```
51#[doc(alias = "BPF_MAP_TYPE_PERCPU_ARRAY")]
52pub struct PerCpuArray<T, V: Pod> {
53    pub(crate) inner: T,
54    _v: PhantomData<V>,
55}
56
57impl<T: Borrow<MapData>, V: Pod> PerCpuArray<T, V> {
58    pub(crate) fn new(map: T) -> Result<Self, MapError> {
59        let data = map.borrow();
60        check_kv_size::<u32, V>(data)?;
61
62        Ok(Self {
63            inner: map,
64            _v: PhantomData,
65        })
66    }
67
68    /// Returns the number of elements in the array.
69    ///
70    /// This corresponds to the value of `bpf_map_def::max_entries` on the eBPF side.
71    pub fn len(&self) -> u32 {
72        self.inner.borrow().obj.max_entries()
73    }
74
75    /// Returns a slice of values - one for each CPU - stored at the given index.
76    ///
77    /// # Errors
78    ///
79    /// Returns [`MapError::OutOfBounds`] if `index` is out of bounds, [`MapError::SyscallError`]
80    /// if `bpf_map_lookup_elem` fails.
81    pub fn get(&self, index: &u32, flags: u64) -> Result<PerCpuValues<V>, MapError> {
82        let data = self.inner.borrow();
83        check_bounds(data, *index)?;
84        let fd = data.fd().as_fd();
85
86        let value =
87            bpf_map_lookup_elem_per_cpu(fd, index, flags).map_err(|io_error| SyscallError {
88                call: "bpf_map_lookup_elem",
89                io_error,
90            })?;
91        value.ok_or(MapError::KeyNotFound)
92    }
93
94    /// An iterator over the elements of the array. The iterator item type is
95    /// `Result<PerCpuValues<V>, MapError>`.
96    pub fn iter(&self) -> impl Iterator<Item = Result<PerCpuValues<V>, MapError>> + '_ {
97        (0..self.len()).map(move |i| self.get(&i, 0))
98    }
99}
100
101impl<T: BorrowMut<MapData>, V: Pod> PerCpuArray<T, V> {
102    /// Sets the values - one for each CPU - at the given index.
103    ///
104    /// # Errors
105    ///
106    /// Returns [`MapError::OutOfBounds`] if `index` is out of bounds, [`MapError::SyscallError`]
107    /// if `bpf_map_update_elem` fails.
108    pub fn set(&mut self, index: u32, values: PerCpuValues<V>, flags: u64) -> Result<(), MapError> {
109        let data = self.inner.borrow_mut();
110        check_bounds(data, index)?;
111        let fd = data.fd().as_fd();
112
113        bpf_map_update_elem_per_cpu(fd, &index, &values, flags).map_err(|io_error| {
114            SyscallError {
115                call: "bpf_map_update_elem",
116                io_error,
117            }
118        })?;
119        Ok(())
120    }
121}
122
123impl<T: Borrow<MapData>, V: Pod> IterableMap<u32, PerCpuValues<V>> for PerCpuArray<T, V> {
124    fn map(&self) -> &MapData {
125        self.inner.borrow()
126    }
127
128    fn get(&self, key: &u32) -> Result<PerCpuValues<V>, MapError> {
129        self.get(key, 0)
130    }
131}