aya/maps/xdp/
dev_map.rs

1//! An array of network devices.
2
3use std::{
4    borrow::{Borrow, BorrowMut},
5    num::NonZeroU32,
6    os::fd::{AsFd, AsRawFd},
7};
8
9use aya_obj::generated::bpf_devmap_val;
10
11use super::XdpMapError;
12use crate::{
13    maps::{check_bounds, check_kv_size, IterableMap, MapData, MapError},
14    programs::ProgramFd,
15    sys::{bpf_map_lookup_elem, bpf_map_update_elem, SyscallError},
16    Pod, FEATURES,
17};
18
19/// An array of network devices.
20///
21/// XDP programs can use this map to redirect to other network
22/// devices.
23///
24/// # Minimum kernel version
25///
26/// The minimum kernel version required to use this feature is 4.14.
27///
28/// # Examples
29/// ```no_run
30/// # let mut bpf = aya::Ebpf::load(&[])?;
31/// use aya::maps::xdp::DevMap;
32///
33/// let mut devmap = DevMap::try_from(bpf.map_mut("IFACES").unwrap())?;
34/// // Lookups at index 2 will redirect packets to interface with index 3 (e.g. eth1)
35/// devmap.set(2, 3, None, 0);
36///
37/// # Ok::<(), aya::EbpfError>(())
38/// ```
39///
40/// # See also
41///
42/// Kernel documentation: <https://docs.kernel.org/next/bpf/map_devmap.html>
43#[doc(alias = "BPF_MAP_TYPE_DEVMAP")]
44pub struct DevMap<T> {
45    pub(crate) inner: T,
46}
47
48impl<T: Borrow<MapData>> DevMap<T> {
49    pub(crate) fn new(map: T) -> Result<Self, MapError> {
50        let data = map.borrow();
51
52        if FEATURES.devmap_prog_id() {
53            check_kv_size::<u32, bpf_devmap_val>(data)?;
54        } else {
55            check_kv_size::<u32, u32>(data)?;
56        }
57
58        Ok(Self { inner: map })
59    }
60
61    /// Returns the number of elements in the array.
62    ///
63    /// This corresponds to the value of `bpf_map_def::max_entries` on the eBPF side.
64    pub fn len(&self) -> u32 {
65        self.inner.borrow().obj.max_entries()
66    }
67
68    /// Returns the target interface index and optional program at a given index.
69    ///
70    /// # Errors
71    ///
72    /// Returns [`MapError::OutOfBounds`] if `index` is out of bounds, [`MapError::SyscallError`]
73    /// if `bpf_map_lookup_elem` fails.
74    pub fn get(&self, index: u32, flags: u64) -> Result<DevMapValue, MapError> {
75        let data = self.inner.borrow();
76        check_bounds(data, index)?;
77        let fd = data.fd().as_fd();
78
79        let value = if FEATURES.devmap_prog_id() {
80            bpf_map_lookup_elem::<_, bpf_devmap_val>(fd, &index, flags).map(|value| {
81                value.map(|value| DevMapValue {
82                    if_index: value.ifindex,
83                    // SAFETY: map writes use fd, map reads use id.
84                    // https://github.com/torvalds/linux/blob/2dde18cd1d8fac735875f2e4987f11817cc0bc2c/include/uapi/linux/bpf.h#L6228
85                    prog_id: NonZeroU32::new(unsafe { value.bpf_prog.id }),
86                })
87            })
88        } else {
89            bpf_map_lookup_elem::<_, u32>(fd, &index, flags).map(|value| {
90                value.map(|ifindex| DevMapValue {
91                    if_index: ifindex,
92                    prog_id: None,
93                })
94            })
95        };
96        value
97            .map_err(|(_, io_error)| SyscallError {
98                call: "bpf_map_lookup_elem",
99                io_error,
100            })?
101            .ok_or(MapError::KeyNotFound)
102    }
103
104    /// An iterator over the elements of the array.
105    pub fn iter(&self) -> impl Iterator<Item = Result<DevMapValue, MapError>> + '_ {
106        (0..self.len()).map(move |i| self.get(i, 0))
107    }
108}
109
110impl<T: BorrowMut<MapData>> DevMap<T> {
111    /// Sets the target interface index at index, and optionally a chained program.
112    ///
113    /// When redirecting using `index`, packets will be transmitted by the interface with
114    /// `target_if_index`.
115    ///
116    /// Starting from Linux kernel 5.8, another XDP program can be passed in that will be run before
117    /// actual transmission. It can be used to modify the packet before transmission with NIC
118    /// specific data (MAC address update, checksum computations, etc) or other purposes.
119    ///
120    /// The chained program must be loaded with the `BPF_XDP_DEVMAP` attach type. When using
121    /// `aya-ebpf`, that means XDP programs that specify the `map = "devmap"` argument. See the
122    /// kernel-space `aya_ebpf::xdp` for more information.
123    ///
124    /// # Errors
125    ///
126    /// Returns [`MapError::OutOfBounds`] if `index` is out of bounds, [`MapError::SyscallError`]
127    /// if `bpf_map_update_elem` fails, [`MapError::ProgIdNotSupported`] if the kernel does not
128    /// support chained programs and one is provided.
129    pub fn set(
130        &mut self,
131        index: u32,
132        target_if_index: u32,
133        program: Option<&ProgramFd>,
134        flags: u64,
135    ) -> Result<(), XdpMapError> {
136        let data = self.inner.borrow_mut();
137        check_bounds(data, index)?;
138        let fd = data.fd().as_fd();
139
140        let res = if FEATURES.devmap_prog_id() {
141            let mut value = unsafe { std::mem::zeroed::<bpf_devmap_val>() };
142            value.ifindex = target_if_index;
143            // Default is valid as the kernel will only consider fd > 0:
144            // https://github.com/torvalds/linux/blob/2dde18cd1d8fac735875f2e4987f11817cc0bc2c/kernel/bpf/devmap.c#L866
145            // https://github.com/torvalds/linux/blob/2dde18cd1d8fac735875f2e4987f11817cc0bc2c/kernel/bpf/devmap.c#L918
146            value.bpf_prog.fd = program
147                .map(|prog| prog.as_fd().as_raw_fd())
148                .unwrap_or_default();
149            bpf_map_update_elem(fd, Some(&index), &value, flags)
150        } else {
151            if program.is_some() {
152                return Err(XdpMapError::ChainedProgramNotSupported);
153            }
154            bpf_map_update_elem(fd, Some(&index), &target_if_index, flags)
155        };
156
157        res.map_err(|(_, io_error)| {
158            MapError::from(SyscallError {
159                call: "bpf_map_update_elem",
160                io_error,
161            })
162        })?;
163        Ok(())
164    }
165}
166
167impl<T: Borrow<MapData>> IterableMap<u32, DevMapValue> for DevMap<T> {
168    fn map(&self) -> &MapData {
169        self.inner.borrow()
170    }
171
172    fn get(&self, key: &u32) -> Result<DevMapValue, MapError> {
173        self.get(*key, 0)
174    }
175}
176
177unsafe impl Pod for bpf_devmap_val {}
178
179#[derive(Clone, Copy, Debug)]
180/// The value of a device map.
181pub struct DevMapValue {
182    /// Target interface index to redirect to.
183    pub if_index: u32,
184    /// Chained XDP program ID.
185    pub prog_id: Option<NonZeroU32>,
186}