Skip to main content

rdif_eth/
lib.rs

1#![no_std]
2
3extern crate alloc;
4
5use alloc::boxed::Box;
6use core::ptr::NonNull;
7
8pub use dma_api;
9pub use rdif_base::{DriverGeneric, KError, io};
10
11// ---------------------------------------------------------------------------
12// Error
13// ---------------------------------------------------------------------------
14
15/// Errors that can occur during network device operations.
16#[derive(thiserror::Error, Debug)]
17pub enum NetError {
18    /// The requested operation is not supported by the device.
19    #[error("Operation not supported")]
20    NotSupported,
21
22    /// The operation should be retried later (e.g. queue full).
23    #[error("Operation should be retried")]
24    Retry,
25
26    /// Insufficient memory to complete the operation.
27    #[error("Insufficient memory")]
28    NoMemory,
29
30    /// The network link is down.
31    #[error("Link down")]
32    LinkDown,
33
34    /// An unspecified error occurred.
35    #[error("Other error: {0}")]
36    Other(Box<dyn core::error::Error>),
37}
38
39impl From<NetError> for io::ErrorKind {
40    fn from(value: NetError) -> Self {
41        match value {
42            NetError::NotSupported => io::ErrorKind::Unsupported,
43            NetError::Retry => io::ErrorKind::Interrupted,
44            NetError::NoMemory => io::ErrorKind::OutOfMemory,
45            NetError::LinkDown => io::ErrorKind::NotAvailable,
46            NetError::Other(e) => io::ErrorKind::Other(e),
47        }
48    }
49}
50
51impl From<dma_api::DmaError> for NetError {
52    fn from(value: dma_api::DmaError) -> Self {
53        match value {
54            dma_api::DmaError::NoMemory => NetError::NoMemory,
55            e => NetError::Other(Box::new(e)),
56        }
57    }
58}
59
60// ---------------------------------------------------------------------------
61// DMA buffer helpers
62// ---------------------------------------------------------------------------
63
64/// Queue configuration needed by the upper layer DMA pool.
65#[derive(Debug, Clone, Copy)]
66pub struct QueueConfig {
67    /// DMA addressing mask for the device.
68    pub dma_mask: u64,
69
70    /// Required alignment for buffer addresses (in bytes).
71    pub align: usize,
72
73    /// DMA packet buffer size in bytes.
74    pub buf_size: usize,
75
76    /// Descriptor ring size.
77    pub ring_size: usize,
78}
79
80/// DMA buffer passed from the runtime queue layer to a driver queue.
81#[derive(Clone, Copy, Debug)]
82pub struct DmaBuffer {
83    /// CPU virtual address for drivers that need to build descriptors from a
84    /// slice or write transport-specific headers.
85    pub virt: NonNull<u8>,
86    /// Device-visible DMA address for hardware descriptors.
87    pub bus_addr: u64,
88    /// Buffer length in bytes.
89    pub len: usize,
90}
91
92/// Bitmask tracking up to 64 queue identifiers.
93#[repr(transparent)]
94#[derive(Debug, Clone, Copy)]
95pub struct IdList(u64);
96
97impl IdList {
98    pub const fn none() -> Self {
99        Self(0)
100    }
101
102    pub fn contains(&self, id: usize) -> bool {
103        (self.0 & (1 << id)) != 0
104    }
105
106    pub fn insert(&mut self, id: usize) {
107        self.0 |= 1 << id;
108    }
109
110    pub fn remove(&mut self, id: usize) {
111        self.0 &= !(1 << id);
112    }
113
114    pub fn iter(&self) -> impl Iterator<Item = usize> {
115        let bits = self.0;
116        (0..64).filter(move |i| (bits & (1 << i)) != 0)
117    }
118}
119
120/// Event returned by [`Interface::handle_irq`] indicating which queues have
121/// completed operations.
122#[derive(Debug, Clone, Copy)]
123pub struct Event {
124    /// Bitmask of TX queue IDs that have completion events.
125    pub tx_queue: IdList,
126    /// Bitmask of RX queue IDs that have completion events.
127    pub rx_queue: IdList,
128}
129
130impl Event {
131    pub const fn none() -> Self {
132        Self {
133            tx_queue: IdList::none(),
134            rx_queue: IdList::none(),
135        }
136    }
137}
138
139/// Core interface that network device drivers must implement.
140///
141/// Provides device-level operations: queue creation, interrupt management,
142/// and MAC address retrieval. Individual packet I/O goes through the queue
143/// traits ([`ITxQueue`] / [`IRxQueue`]).
144pub trait Interface: DriverGeneric {
145    /// Returns the device's 6-byte MAC address.
146    fn mac_address(&self) -> [u8; 6];
147
148    /// Create a new transmit queue. Returns `None` if no more queues are
149    /// available.
150    fn create_tx_queue(&mut self) -> Option<Box<dyn ITxQueue>>;
151
152    /// Create a new receive queue. Returns `None` if no more queues are
153    /// available.
154    fn create_rx_queue(&mut self) -> Option<Box<dyn IRxQueue>>;
155
156    /// Enable device interrupts.
157    fn enable_irq(&mut self);
158
159    /// Disable device interrupts.
160    fn disable_irq(&mut self);
161
162    /// Check whether device interrupts are currently enabled.
163    fn is_irq_enabled(&self) -> bool;
164
165    /// Handle a device interrupt, returning which queues have events.
166    fn handle_irq(&mut self) -> Event;
167}
168
169// ---------------------------------------------------------------------------
170// Transmit queue
171// ---------------------------------------------------------------------------
172
173/// Transmit queue interface.
174///
175/// A driver creates one or more TX queues via [`Interface::create_tx_queue`]
176/// and exchanges DMA buffer bus addresses with the caller.
177pub trait ITxQueue: Send + 'static {
178    /// Queue identifier (unique within the device).
179    fn id(&self) -> usize;
180
181    /// DMA buffer configuration for this queue.
182    fn config(&self) -> QueueConfig;
183
184    /// Submit a DMA buffer for transmission.
185    ///
186    /// `bus_addr` must point to a DMA-capable buffer whose first `len` bytes
187    /// contain the packet to be transmitted.
188    fn submit(&mut self, buffer: DmaBuffer) -> Result<(), NetError>;
189
190    /// Reclaim the next completed transmit buffer.
191    ///
192    /// Returns the buffer bus address when the device has completed sending it.
193    fn reclaim(&mut self) -> Option<u64>;
194}
195
196// ---------------------------------------------------------------------------
197// Receive queue
198// ---------------------------------------------------------------------------
199
200/// Receive queue interface.
201///
202/// A driver creates one or more RX queues via [`Interface::create_rx_queue`]
203/// and exchanges DMA buffer bus addresses with the caller.
204pub trait IRxQueue: Send + 'static {
205    /// Queue identifier (unique within the device).
206    fn id(&self) -> usize;
207
208    /// DMA buffer configuration for this queue.
209    fn config(&self) -> QueueConfig;
210
211    /// Submit an empty DMA buffer to hardware.
212    ///
213    /// `bus_addr` must point to a DMA-capable buffer whose total size is `len`.
214    fn submit(&mut self, buffer: DmaBuffer) -> Result<(), NetError>;
215
216    /// Reclaim the next completed receive buffer.
217    ///
218    /// Returns the buffer bus address and the received byte count.
219    fn reclaim(&mut self) -> Option<(u64, usize)>;
220}