Skip to main content

strate_net_silo/
device.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! smoltcp device backend for strate-net.
24//!
25//! Two implementations:
26//!
27//! * [`SharedNetDevice`] : drives the kernel `NetQueue` region directly.
28//!   RX/TX descriptors are read/written in mapped memory; no syscall and no
29//!   copy between the kernel and the stack.
30//! * [`LegacyNetDevice`] : the original `SYS_NET_RECV` / `SYS_NET_SEND`
31//!   copy path, kept as a fallback when the shared region cannot be mapped.
32//!
33//! The `Device` trait is implemented once for the [`NetDevice`] enum so the
34//! smoltcp `Interface` is monomorphised over a single type.
35
36use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
37
38use alloc::sync::Arc;
39
40use smoltcp::{
41    phy::{self, Checksum, Device, DeviceCapabilities, Medium},
42    time::Instant,
43};
44use strat9_abi::net::{NetFrameDesc, NetQueueHeader, NET_FRAME_SIZE};
45use strate_net::syscalls::{call, net_recv, net_send, proc_yield, Error};
46
47use crate::{log, log_errno, sleep_micros};
48
49pub(crate) const MAX_FRAME_SIZE: usize = 1514;
50const NET_SEND_RETRY_LIMIT: usize = 8;
51
52static RX_ERR_LOG_BUDGET: AtomicUsize = AtomicUsize::new(16);
53static TX_ERR_LOG_BUDGET: AtomicUsize = AtomicUsize::new(16);
54static TX_SUCCESS_COUNT: AtomicUsize = AtomicUsize::new(0);
55static TX_DROP_COUNT: AtomicUsize = AtomicUsize::new(0);
56
57/// Backend selected at startup.
58pub(crate) enum NetDevice {
59    Shared(SharedNetDevice),
60    Legacy(LegacyNetDevice),
61}
62
63impl NetDevice {
64    /// Build the shared-memory backend from `SYS_NET_QUEUE_MAP`.
65    ///
66    /// # Safety
67    /// `header` must point to a valid `NetQueueHeader` mapped read/write.
68    pub(crate) unsafe fn shared(
69        dev_handle: u64,
70        queues: alloc::vec::Vec<SharedQueue>,
71        mac: [u8; 6],
72        features: u64,
73    ) -> Self {
74        NetDevice::Shared(SharedNetDevice {
75            dev_handle,
76            queues,
77            mac,
78            features,
79            rr_rx: 0,
80            rr_tx: 0,
81        })
82    }
83
84    pub(crate) fn legacy() -> Self {
85        NetDevice::Legacy(LegacyNetDevice)
86    }
87
88    /// Flush pending TX descriptors to the device (one doorbell per poll).
89    pub(crate) fn flush(&mut self) {
90        if let NetDevice::Shared(device) = self {
91            device.flush();
92        }
93    }
94
95    #[allow(dead_code)] // Retained device accessor.
96    pub(crate) fn mac(&self) -> [u8; 6] {
97        match self {
98            NetDevice::Shared(device) => device.mac,
99            NetDevice::Legacy(_) => [0; 6],
100        }
101    }
102}
103
104impl Device for NetDevice {
105    type RxToken<'a> = NetRxToken;
106    type TxToken<'a> = NetTxToken;
107
108    fn receive(&mut self, _timestamp: Instant) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
109        match self {
110            NetDevice::Shared(device) => device.receive_shared(),
111            NetDevice::Legacy(_) => legacy_receive(),
112        }
113    }
114
115    fn transmit(&mut self, _timestamp: Instant) -> Option<Self::TxToken<'_>> {
116        match self {
117            NetDevice::Shared(device) => device.transmit_shared(),
118            NetDevice::Legacy(_) => Some(NetTxToken::Legacy(LegacyTxToken)),
119        }
120    }
121
122    fn capabilities(&self) -> DeviceCapabilities {
123        let mut caps = DeviceCapabilities::default();
124        // smoltcp expects the *medium* MTU here (Ethernet frame size); it
125        // subtracts the 14-byte header to obtain the IP MTU (1500).
126        caps.max_transmission_unit = MAX_FRAME_SIZE;
127        caps.medium = Medium::Ethernet;
128        caps.max_burst_size = Some(16);
129
130        let features = match self {
131            NetDevice::Shared(device) => device.features,
132            NetDevice::Legacy(_) => 0,
133        };
134        if features & strat9_abi::net::features::CSUM_RX != 0 {
135            // The NIC validates RX checksums and drops bad frames; smoltcp
136            // must still compute TX checksums (`Checksum::Tx` = TX only).
137            caps.checksum.ipv4 = Checksum::Tx;
138            caps.checksum.tcp = Checksum::Tx;
139            caps.checksum.udp = Checksum::Tx;
140            caps.checksum.icmpv4 = Checksum::Tx;
141            caps.checksum.icmpv6 = Checksum::Tx;
142        }
143        caps
144    }
145}
146
147// ---------------------------------------------------------------------------
148// Shared-memory backend
149// ---------------------------------------------------------------------------
150
151pub(crate) struct SharedQueue {
152    pub qid: u16,
153    pub header: *mut NetQueueHeader,
154    pub tx_pending: Arc<AtomicBool>,
155}
156
157pub(crate) struct SharedNetDevice {
158    dev_handle: u64,
159    queues: alloc::vec::Vec<SharedQueue>,
160    #[allow(dead_code)] // Retained shared-device metadata.
161    mac: [u8; 6],
162    features: u64,
163    rr_rx: usize,
164    rr_tx: usize,
165}
166
167// SAFETY: the shared header is only accessed through the ABI's single
168// producer/consumer rings and atomics; `SharedNetDevice` is owned by the
169// single strate-net poll thread.
170unsafe impl Send for SharedNetDevice {}
171
172impl SharedNetDevice {
173    fn receive_shared(&mut self) -> Option<(NetRxToken, NetTxToken)> {
174        let count = self.queues.len();
175        if count == 0 {
176            return None;
177        }
178        for offset in 0..count {
179            let index = (self.rr_rx + offset) % count;
180            // Allocate the TX token first: smoltcp uses it for immediate
181            // replies (ACK, ICMP) and expects a writable buffer.
182            let Some(tx) = self.transmit_for(index) else {
183                continue;
184            };
185            let header = self.queues[index].header;
186            // SAFETY: `header` is a valid mapped region; the RX ring has a
187            // single consumer (this thread).
188            let Some(desc) = (unsafe { (*header).rx_pop() }) else {
189                continue;
190            };
191            let ptr = unsafe { (*header).rx_slot(desc.slot) };
192            self.rr_rx = (index + 1) % count;
193            let token = NetRxToken::Shared(SharedRxToken {
194                header,
195                slot: desc.slot,
196                ptr,
197                len: desc.len as usize,
198                released: false,
199            });
200            return Some((token, tx));
201        }
202        None
203    }
204
205    fn transmit_for(&self, index: usize) -> Option<NetTxToken> {
206        let queue = self.queues.get(index)?;
207        let slot = unsafe { (*queue.header).alloc_tx_slot() }?;
208        let ptr = unsafe { (*queue.header).tx_slot(slot) };
209        Some(NetTxToken::Shared(SharedTxToken {
210            header: queue.header,
211            slot,
212            ptr,
213            pending: queue.tx_pending.clone(),
214            released: false,
215        }))
216    }
217
218    fn transmit_shared(&mut self) -> Option<NetTxToken> {
219        let count = self.queues.len();
220        if count == 0 {
221            return None;
222        }
223        for offset in 0..count {
224            let index = (self.rr_tx + offset) % count;
225            if let Some(token) = self.transmit_for(index) {
226                self.rr_tx = (index + 1) % count;
227                return Some(token);
228            }
229        }
230        None
231    }
232
233    pub(crate) fn flush(&mut self) {
234        for queue in self.queues.iter() {
235            if queue.tx_pending.swap(false, Ordering::AcqRel) {
236                if call::net_kick(self.dev_handle as usize, queue.qid as usize).is_err() {
237                    // Keep the flag set so the next poll retries the doorbell.
238                    queue.tx_pending.store(true, Ordering::Release);
239                }
240            }
241        }
242    }
243}
244
245// ---------------------------------------------------------------------------
246// Legacy copy backend
247// ---------------------------------------------------------------------------
248
249pub(crate) struct LegacyNetDevice;
250
251fn legacy_receive() -> Option<(NetRxToken, NetTxToken)> {
252    let mut buf = [0u8; MAX_FRAME_SIZE];
253    match net_recv(&mut buf) {
254        Ok(n) if n > 0 => {
255            let len = core::cmp::min(n, MAX_FRAME_SIZE);
256            Some((
257                NetRxToken::Legacy(LegacyRxToken { buf, len }),
258                NetTxToken::Legacy(LegacyTxToken),
259            ))
260        }
261        Err(e) => {
262            if e.to_errno() != 11 && RX_ERR_LOG_BUDGET.load(Ordering::Relaxed) > 0 {
263                RX_ERR_LOG_BUDGET.fetch_sub(1, Ordering::Relaxed);
264                log_errno("[strate-net] net_recv errno=", e);
265            }
266            None
267        }
268        _ => None,
269    }
270}
271
272// ---------------------------------------------------------------------------
273// Tokens
274// ---------------------------------------------------------------------------
275
276pub(crate) enum NetRxToken {
277    Shared(SharedRxToken),
278    Legacy(LegacyRxToken),
279}
280
281impl phy::RxToken for NetRxToken {
282    fn consume<R, F>(self, f: F) -> R
283    where
284        F: FnOnce(&[u8]) -> R,
285    {
286        match self {
287            NetRxToken::Shared(token) => token.consume(f),
288            NetRxToken::Legacy(token) => token.consume(f),
289        }
290    }
291}
292
293pub(crate) enum NetTxToken {
294    Shared(SharedTxToken),
295    Legacy(LegacyTxToken),
296}
297
298impl phy::TxToken for NetTxToken {
299    fn consume<R, F>(self, len: usize, f: F) -> R
300    where
301        F: FnOnce(&mut [u8]) -> R,
302    {
303        match self {
304            NetTxToken::Shared(token) => token.consume(len, f),
305            NetTxToken::Legacy(token) => token.consume(len, f),
306        }
307    }
308}
309
310pub(crate) struct SharedRxToken {
311    header: *mut NetQueueHeader,
312    slot: u32,
313    ptr: *mut u8,
314    len: usize,
315    released: bool,
316}
317
318impl SharedRxToken {
319    fn consume<R, F>(mut self, f: F) -> R
320    where
321        F: FnOnce(&[u8]) -> R,
322    {
323        // SAFETY: the descriptor was popped from the RX ring and the slot is
324        // owned by this consumer until `free_rx_slot`.
325        let out = unsafe { f(core::slice::from_raw_parts(self.ptr, self.len)) };
326        unsafe { (*self.header).free_rx_slot(self.slot) };
327        self.released = true;
328        out
329    }
330}
331
332impl Drop for SharedRxToken {
333    fn drop(&mut self) {
334        if !self.released {
335            // SAFETY: the slot is still owned by this token.
336            unsafe { (*self.header).free_rx_slot(self.slot) };
337        }
338    }
339}
340
341pub(crate) struct SharedTxToken {
342    header: *mut NetQueueHeader,
343    slot: u32,
344    ptr: *mut u8,
345    pending: Arc<AtomicBool>,
346    released: bool,
347}
348
349impl SharedTxToken {
350    fn consume<R, F>(mut self, len: usize, f: F) -> R
351    where
352        F: FnOnce(&mut [u8]) -> R,
353    {
354        if self.slot == u32::MAX || len > NET_FRAME_SIZE {
355            if self.slot != u32::MAX {
356                unsafe { (*self.header).free_tx_slot(self.slot) };
357            }
358            self.released = true;
359            return f(&mut []);
360        }
361        // SAFETY: the slot was allocated for this token; the closure writes
362        // at most `len` bytes into a `NET_FRAME_SIZE` slot.
363        let out = unsafe { f(core::slice::from_raw_parts_mut(self.ptr, len)) };
364        let desc = NetFrameDesc {
365            slot: self.slot,
366            len: len as u16,
367            flags: strat9_abi::net::fd_flags::SOP
368                | strat9_abi::net::fd_flags::EOP
369                | strat9_abi::net::fd_flags::NEED_COMP,
370            vlan: 0,
371            rss: 0,
372            reserved: 0,
373        };
374        // SAFETY: single TX producer (this thread).
375        if unsafe { (*self.header).tx_push(desc) } {
376            self.pending.store(true, Ordering::Release);
377        } else {
378            unsafe { (*self.header).free_tx_slot(self.slot) };
379            TX_DROP_COUNT.fetch_add(1, Ordering::Relaxed);
380        }
381        self.released = true;
382        out
383    }
384}
385
386impl Drop for SharedTxToken {
387    fn drop(&mut self) {
388        if !self.released && self.slot != u32::MAX {
389            // SAFETY: the slot is still owned by this token.
390            unsafe { (*self.header).free_tx_slot(self.slot) };
391        }
392    }
393}
394
395pub(crate) struct LegacyRxToken {
396    buf: [u8; MAX_FRAME_SIZE],
397    len: usize,
398}
399
400impl phy::RxToken for LegacyRxToken {
401    fn consume<R, F>(self, f: F) -> R
402    where
403        F: FnOnce(&[u8]) -> R,
404    {
405        f(&self.buf[..self.len])
406    }
407}
408
409pub(crate) struct LegacyTxToken;
410
411impl phy::TxToken for LegacyTxToken {
412    fn consume<R, F>(self, len: usize, f: F) -> R
413    where
414        F: FnOnce(&mut [u8]) -> R,
415    {
416        if len > MAX_FRAME_SIZE {
417            log("[strate-net] TX frame too large\n");
418            return f(&mut []);
419        }
420
421        let mut buf = [0u8; MAX_FRAME_SIZE];
422        let ret = f(&mut buf[..len]);
423        let mut last_err = None;
424        for attempt in 0..NET_SEND_RETRY_LIMIT {
425            match net_send(&buf[..len]) {
426                Ok(_) => {
427                    TX_SUCCESS_COUNT.fetch_add(1, Ordering::Relaxed);
428                    last_err = None;
429                    break;
430                }
431                Err(e @ (Error::Again | Error::QueueFull)) => {
432                    last_err = Some(e);
433                    let _ = proc_yield();
434                }
435                Err(e @ Error::IoError) if attempt + 1 < NET_SEND_RETRY_LIMIT => {
436                    last_err = Some(e);
437                    sleep_micros(50);
438                }
439                Err(e) => {
440                    last_err = Some(e);
441                    break;
442                }
443            }
444        }
445
446        if let Some(e) = last_err {
447            TX_DROP_COUNT.fetch_add(1, Ordering::Relaxed);
448            if TX_ERR_LOG_BUDGET.load(Ordering::Relaxed) > 0 {
449                TX_ERR_LOG_BUDGET.fetch_sub(1, Ordering::Relaxed);
450                log_errno("[strate-net] net_send errno=", e);
451            }
452        }
453
454        ret
455    }
456}