Skip to main content

xarxa_driver/
lib.rs

1#![cfg_attr(not(test), no_std)]
2#![doc = include_str!("../README.md")]
3//!
4//! ## Feature flags
5#![doc = document_features::document_features!(feature_label = r#"<span class="stab portability"><code>{feature}</code></span>"#)]
6
7mod buf;
8mod meta;
9
10#[cfg(feature = "async")]
11use core::task::Waker;
12
13pub use buf::{DriverBuf, RawDriverBuf};
14pub use meta::PacketMeta;
15#[cfg(feature = "packetmeta-timestamp")]
16pub use meta::{Timestamp, TxTimestamp};
17
18/// Error returned by an operation the driver does not support.
19#[cfg(feature = "async")]
20#[cfg_attr(feature = "defmt", derive(defmt::Format))]
21#[derive(Debug, Eq, PartialEq, Copy, Clone)]
22pub struct NotSupported;
23
24/// Link state of a network device.
25#[cfg_attr(feature = "defmt", derive(defmt::Format))]
26#[derive(Debug, Eq, PartialEq, Copy, Clone)]
27pub enum LinkState {
28    /// The link is down. No frames can pass.
29    Down,
30    /// The link is up.
31    Up,
32}
33
34/// Type of medium of a network device.
35///
36/// This is `#[non_exhaustive]` so that media can be added later without breaking
37/// every driver.
38#[cfg_attr(feature = "defmt", derive(defmt::Format))]
39#[derive(Debug, Eq, PartialEq, Copy, Clone)]
40#[non_exhaustive]
41pub enum Medium {
42    /// Ethernet medium. Devices of this type send and receive Ethernet frames.
43    Ethernet,
44
45    /// IP medium. Devices of this type send and receive IP frames, without an
46    /// Ethernet header. MAC addresses are not used.
47    Ip,
48
49    /// IEEE 802.15.4 medium. Devices of this type send and receive 802.15.4
50    /// MAC frames carrying 6LoWPAN.
51    ///
52    /// [`Capabilities::max_transmission_unit`] is the whole MAC frame
53    /// without the FCS: 125 for a 127-byte PHY frame with a 2-byte FCS.
54    Ieee802154,
55}
56
57/// A hardware (link-layer) address, as reported by a driver.
58///
59/// This is `#[non_exhaustive]` so that address kinds can be added later without
60/// breaking every driver.
61#[cfg_attr(feature = "defmt", derive(defmt::Format))]
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63#[non_exhaustive]
64pub enum HardwareAddress {
65    /// An Ethernet (MAC) address.
66    Ethernet([u8; 6]),
67    /// No address, for devices that send and receive bare IP packets.
68    Ip,
69    /// An IEEE 802.15.4 extended (64-bit) address.
70    Ieee802154([u8; 8]),
71}
72
73impl HardwareAddress {
74    /// The medium this kind of address belongs to.
75    pub const fn medium(&self) -> Medium {
76        match self {
77            HardwareAddress::Ethernet(_) => Medium::Ethernet,
78            HardwareAddress::Ip => Medium::Ip,
79            HardwareAddress::Ieee802154(_) => Medium::Ieee802154,
80        }
81    }
82}
83
84/// Checksum offload capabilities for a given protocol, per direction.
85#[cfg_attr(feature = "defmt", derive(defmt::Format))]
86#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
87pub struct ChecksumOffload {
88    /// The device verifies the checksum of received packets.
89    ///
90    /// The stack then does not verify it in software.
91    pub rx: bool,
92    /// The device fills in the checksum of transmitted packets.
93    ///
94    /// The stack then writes the field as zero instead of computing it.
95    pub tx: bool,
96}
97
98impl ChecksumOffload {
99    /// No offload. The stack computes and verifies the checksum in software.
100    pub const NONE: Self = Self { rx: false, tx: false };
101    /// Offload in both directions.
102    pub const BOTH: Self = Self { rx: true, tx: true };
103}
104
105/// Checksum offload capabilities per protocol direction.
106///
107/// The stack skips the offloaded work in software.
108///
109/// The default is no offload for every protocol: the stack computes and
110/// verifies everything itself.
111///
112/// A checksum the stack does not compute is written as zero, so that a device
113/// that fills it in finds a known value there.
114///
115/// The fields are the protocols with a checksum the stack handles. IGMP is not
116/// among them: its checksum is always computed and verified in software.
117#[cfg_attr(feature = "defmt", derive(defmt::Format))]
118#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
119#[non_exhaustive]
120pub struct ChecksumCapabilities {
121    /// Offload for the IPv4 header checksum.
122    pub ipv4: ChecksumOffload,
123    /// Offload for the UDP checksum.
124    pub udp: ChecksumOffload,
125    /// Offload for the TCP checksum.
126    pub tcp: ChecksumOffload,
127    /// Offload for the ICMPv4 checksum.
128    pub icmpv4: ChecksumOffload,
129    /// Offload for the ICMPv6 checksum.
130    pub icmpv6: ChecksumOffload,
131}
132
133impl ChecksumCapabilities {
134    /// Every checksum offloaded in both directions.
135    ///
136    /// The stack computes and verifies nothing. Use this for devices where
137    /// checksums don't matter, like loopback.
138    pub fn all_offloaded() -> Self {
139        ChecksumCapabilities {
140            ipv4: ChecksumOffload::BOTH,
141            udp: ChecksumOffload::BOTH,
142            tcp: ChecksumOffload::BOTH,
143            icmpv4: ChecksumOffload::BOTH,
144            icmpv6: ChecksumOffload::BOTH,
145        }
146    }
147}
148
149/// A description of a device's capabilities.
150///
151/// This is `#[non_exhaustive]` so that capabilities can be added later without breaking
152/// every driver. Drivers live outside this crate and so cannot use a struct expression,
153/// they start from [`Default`] and overwrite the fields they care about:
154///
155/// ```
156/// # use xarxa_driver::Capabilities;
157/// let mut caps = Capabilities::default();
158/// caps.max_transmission_unit = 1514;
159/// // caps.medium = Medium::Ethernet; is the default
160/// ```
161#[cfg_attr(feature = "defmt", derive(defmt::Format))]
162#[derive(Debug, Clone)]
163#[non_exhaustive]
164pub struct Capabilities {
165    /// Medium of the device.
166    pub medium: Medium,
167
168    /// Maximum transmission unit.
169    ///
170    /// The network device is unable to send or receive frames larger than the value returned
171    /// by this function.
172    pub max_transmission_unit: usize,
173
174    /// Checksum offload.
175    ///
176    /// Which checksums the device's hardware verifies or computes, so the
177    /// stack skips them in software.
178    pub checksum: ChecksumCapabilities,
179
180    /// Headroom the driver needs in front of each frame it transmits, in bytes.
181    ///
182    /// For drivers that put a header of their own in front of the frame. Every
183    /// buffer the stack hands to [`transmit`](Driver::transmit) has at least this
184    /// much headroom.
185    ///
186    /// Default: 0.
187    pub tx_headroom: usize,
188}
189
190impl Default for Capabilities {
191    fn default() -> Self {
192        Self {
193            medium: Medium::Ethernet,
194            max_transmission_unit: 1514,
195            checksum: ChecksumCapabilities::default(),
196            tx_headroom: 0,
197        }
198    }
199}
200
201/// What a driver answers to [`Driver::rx_wanted`].
202#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
203#[cfg_attr(feature = "defmt", derive(defmt::Format))]
204pub struct RxWanted {
205    /// How many more empty buffers the driver can take right now.
206    pub count: usize,
207    /// The driver has no buffer to receive a frame into, so it can't receive
208    /// anything until it gets one. The stack keeps a buffer free for each
209    /// starved driver.
210    ///
211    /// `count` may be 0 then, for a driver that only takes a buffer once a frame
212    /// is waiting for it. The buffer is kept free for it all the same.
213    pub starved: bool,
214}
215
216/// A network device driver, sending and receiving raw network frames.
217pub trait Driver {
218    /// Get a description of the device's capabilities.
219    fn capabilities(&self) -> Capabilities;
220
221    /// Get the device's hardware address.
222    ///
223    /// The address kind must match the medium in [`capabilities`](Self::capabilities):
224    /// an Ethernet address for [`Medium::Ethernet`], [`HardwareAddress::Ip`] for
225    /// [`Medium::Ip`], an IEEE 802.15.4 extended address for [`Medium::Ieee802154`].
226    ///
227    /// The stack reads it once, when the driver is added to it. The stack has its
228    /// own way to override the address after that.
229    fn hardware_address(&self) -> HardwareAddress;
230
231    /// Get the link state.
232    ///
233    /// Devices that cannot tell, or whose link is always up, return
234    /// [`LinkState::Up`], which is the default implementation.
235    fn link_state(&mut self) -> LinkState {
236        LinkState::Up
237    }
238
239    /// Register a waker.
240    ///
241    /// The driver must wake it when:
242    /// - a frame has been received, so [`receive`](Self::receive) may return `Some`.
243    /// - there is room to transmit again, after [`can_transmit`](Self::can_transmit)
244    ///   returned `false`.
245    /// - the link state changed, so [`link_state`](Self::link_state) may return
246    ///   something new.
247    ///
248    /// Only one waker is kept. Registering another replaces it. Wakes are
249    /// allowed to be spurious.
250    ///
251    /// A registered waker is woken just once. The main loop must register it
252    /// again if it wants to be woken again.
253    ///
254    /// # Errors
255    /// - `NotSupported`: if the driver cannot wake anything. This is the default
256    ///   implementation. Such a driver can only be polled, so a caller that
257    ///   needs to sleep until the driver has something new cannot use it.
258    #[cfg(feature = "async")]
259    fn register_waker(&mut self, waker: &Waker) -> Result<(), NotSupported> {
260        let _ = waker;
261        Err(NotSupported)
262    }
263
264    /// How many more empty buffers the driver can take right now, to receive
265    /// frames into, and whether it can receive at all.
266    ///
267    /// The stack asks on poll, after each call to [`receive`](Self::receive),
268    /// and gives the driver up to [`count`](RxWanted::count) buffers with
269    /// [`rx_give`](Self::rx_give). It gives fewer if its pool runs low.
270    ///
271    /// A driver with a receive ring returns the number of slots that have no
272    /// buffer. One that reads frames into a buffer on demand can ask for one.
273    ///
274    /// Set [`starved`](RxWanted::starved) whenever the driver can't receive a
275    /// frame without another buffer, whether or not a frame is waiting. The
276    /// stack keeps a buffer aside for each starved driver, so that it can always
277    /// give it one, but only one. It must be honest: a driver that says it is
278    /// starved when it isn't takes buffers from the other interfaces, and one
279    /// that doesn't say it when it is can be left with none.
280    fn rx_wanted(&mut self) -> RxWanted;
281
282    /// Give the driver an empty buffer to receive a frame into.
283    ///
284    /// The driver owns it from then on. It hands it back with a frame in it from
285    /// [`receive`](Self::receive).
286    ///
287    /// It shouldn't drop it, except to drop a frame it received into it that it
288    /// doesn't hand back. The stack keeps a buffer free for a driver only while
289    /// the driver is starved, and it learns that from
290    /// [`rx_wanted`](Self::rx_wanted), which it asks after each `receive`. A
291    /// driver that drops its buffers some other way can be left with none to
292    /// receive into while the buffers that are free are all taken, and then
293    /// nothing guarantees it gets one again.
294    ///
295    /// The stack never gives more buffers than [`rx_wanted`](Self::rx_wanted) asked
296    /// for. The buffer has zero headroom and length.
297    fn rx_give(&mut self, buf: DriverBuf);
298
299    /// Poll for a received frame.
300    ///
301    /// Returns a buffer holding the received frame if one is available, transferring
302    /// ownership of it to the caller.
303    ///
304    /// A driver that has per-packet metadata to report, such as an identifier or a
305    /// receive timestamp, sets it on the buffer's [`PacketMeta`] here. It travels
306    /// with the packet up to the socket that receives it.
307    fn receive(&mut self) -> Option<DriverBuf>;
308
309    /// Whether the device can transmit one frame right now.
310    ///
311    /// Devices typically have a transmit packet queue. This returns
312    /// whether this queue has space to take one more frame.
313    ///
314    /// If this returns `true`, the next `transmit()` call must not fail.
315    ///
316    /// If this returns `false`, the driver must wake the waker from
317    /// `register_waker` once there is room again.
318    ///
319    /// In devices where there's no queue so transmit always succeeds, this
320    /// should always return `true`.
321    fn can_transmit(&mut self) -> bool;
322
323    /// Queue a frame for transmission, transferring ownership of the buffer to the driver.
324    ///
325    /// The driver holds the buffer until the hardware is done with it, then drops it.
326    ///
327    /// The buffer's [`PacketMeta`] is whatever the sending socket attached to the
328    /// packet (default for packets the stack generates itself). A packet sent in
329    /// fragments has it on its first fragment, and the default on the others. A
330    /// driver that supports transmit timestamping timestamps the frame if
331    /// [`request_timestamp`](PacketMeta::request_timestamp) is set, and reports
332    /// the result from [`poll_tx_timestamp`](Self::poll_tx_timestamp) tagged with the
333    /// packet's [`id`](PacketMeta::id).
334    ///
335    /// # Errors
336    /// - `DriverBuf`: the buffer itself, handed back if the frame cannot be
337    ///   queued right now (device busy or queue full).
338    fn transmit(&mut self, buf: DriverBuf) -> Result<(), DriverBuf>;
339
340    /// Poll for the timestamp of an already-transmitted packet.
341    ///
342    /// Returns the transmit timestamp of a packet previously sent with
343    /// [`PacketMeta::request_timestamp`] set, tagged with that packet's
344    /// [`PacketMeta::id`], or `None` if no timestamp is available right now.
345    ///
346    /// Transmit timestamps are reported out of band, rather than on the packet like
347    /// receive timestamps are, because a packet's transmit timestamp does not exist yet
348    /// when [`transmit`](Self::transmit) returns: it has not gone out on the wire yet.
349    ///
350    /// Callers must be robust against all of the following:
351    ///
352    /// * Timestamps become available an arbitrary time after `transmit` returned, so
353    ///   this should be polled repeatedly, not just once after sending.
354    /// * Timestamps may be reported out of order with respect to transmission.
355    /// * Timestamps may never arrive at all, e.g. because the hardware ran out of
356    ///   timestamp slots. Never block waiting for a particular `id` to show up without
357    ///   a timeout.
358    ///
359    /// Devices that do not support transmit timestamping always return `None`, which is
360    /// the default implementation.
361    #[cfg(feature = "packetmeta-timestamp")]
362    fn poll_tx_timestamp(&mut self) -> Option<TxTimestamp> {
363        None
364    }
365
366    /// Set the device's multicast hardware address filter.
367    ///
368    /// `addrs` is the full list of multicast MAC addresses to listen on. It
369    /// replaces the previous one.
370    ///
371    /// A device with no multicast filter can ignore the calls, which
372    /// is the default implementation.
373    ///
374    /// Only called for [`Medium::Ethernet`] devices. The list has no duplicates.
375    ///
376    /// It may be the same list as last time: the stack does not compare. If
377    /// applying the filter is expensive, the driver should should keep the last
378    /// list and skip if there were no changes.
379    ///
380    /// If the list does not fit the filter, receive the addresses anyway if
381    /// possible, for example by turning the filter off or switching it to
382    /// receive all multicast. Losing filter efficiency is fine, filtering out
383    /// traffic the network stack wants is not.
384    fn set_multicast_filter(&mut self, addrs: &[[u8; 6]]) {
385        let _ = addrs;
386    }
387}
388
389impl<T: Driver + ?Sized> Driver for &mut T {
390    fn capabilities(&self) -> Capabilities {
391        T::capabilities(self)
392    }
393    fn hardware_address(&self) -> HardwareAddress {
394        T::hardware_address(self)
395    }
396    fn link_state(&mut self) -> LinkState {
397        T::link_state(self)
398    }
399    #[cfg(feature = "async")]
400    fn register_waker(&mut self, waker: &Waker) -> Result<(), NotSupported> {
401        T::register_waker(self, waker)
402    }
403    fn rx_wanted(&mut self) -> RxWanted {
404        T::rx_wanted(self)
405    }
406    fn rx_give(&mut self, buf: DriverBuf) {
407        T::rx_give(self, buf)
408    }
409    fn receive(&mut self) -> Option<DriverBuf> {
410        T::receive(self)
411    }
412    fn can_transmit(&mut self) -> bool {
413        T::can_transmit(self)
414    }
415    fn transmit(&mut self, buf: DriverBuf) -> Result<(), DriverBuf> {
416        T::transmit(self, buf)
417    }
418    #[cfg(feature = "packetmeta-timestamp")]
419    fn poll_tx_timestamp(&mut self) -> Option<TxTimestamp> {
420        T::poll_tx_timestamp(self)
421    }
422    fn set_multicast_filter(&mut self, addrs: &[[u8; 6]]) {
423        T::set_multicast_filter(self, addrs)
424    }
425}