Skip to main content

strat9_abi/
net.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//! Shared-memory network queue ABI.
24//!
25//! This module is the single source of truth for the layout that the kernel
26//! and a userspace networking strate share.  It is deliberately independent
27//! of the device model: any NIC (e1000, virtio-net, vmxnet3, …) can expose a
28//! `NetQueueHeader` region and let the stack drive its rings directly.
29//!
30//! Design rules:
31//! - one producer and one consumer per direction (RX and TX);
32//! - free-running `head`/`tail` counters, power-of-two ring size;
33//! - frame slots live in a pool inside the same mapped region;
34//! - slot ownership is tracked by a bitmap, not by a free list, so the
35//!   consumer can release a slot without another ring;
36//! - no allocation, no lock, no syscall once the region is mapped.
37//!
38//! Layout (all offsets stable, region is page-aligned):
39//!
40//! ```text
41//! 0x0000  NetQueueHeader
42//! 0x0100  RX descriptors  (NET_RING_SLOTS × 16 bytes)
43//! 0x1100  TX descriptors  (NET_RING_SLOTS × 16 bytes)
44//! 0x2100  statistics / reserved
45//! 0x3000  RX frame pool   (NET_POOL_SLOTS × 2048 bytes)
46//! 0x83000 TX frame pool   (NET_POOL_SLOTS × 2048 bytes)
47//! 0x103000 end
48//! ```
49// The ring primitives in this module are `unsafe fn` whose contracts are
50// documented per function; the workspace denies `unsafe_op_in_unsafe_fn`, so
51// opt this wire-format module out rather than wrapping every pointer access.
52#![allow(unsafe_op_in_unsafe_fn)]
53
54use core::sync::atomic::{AtomicU32, AtomicU64, Ordering};
55
56/// `"STNQ"` little-endian.
57pub const NET_QUEUE_MAGIC: u32 = 0x514E_5453;
58/// Current ABI revision.
59pub const NET_QUEUE_ABI: u16 = 1;
60
61/// A frame slot is a fixed 2 KiB cell (enough for a 1514-byte frame plus
62/// headroom and a future 1500-byte jumbo-lite path).
63pub const NET_FRAME_SIZE: usize = 2048;
64/// Number of descriptors in each direction (must be a power of two).
65pub const NET_RING_SLOTS: usize = 256;
66/// Number of frame slots in each pool (must be a multiple of 64).
67pub const NET_POOL_SLOTS: usize = 256;
68
69pub const NET_QUEUE_HDR_SIZE: usize = 0x100;
70pub const NET_RX_DESC_OFF: usize = 0x100;
71pub const NET_TX_DESC_OFF: usize = 0x1100;
72pub const NET_STATS_OFF: usize = 0x2100;
73pub const NET_RX_POOL_OFF: usize = 0x3000;
74pub const NET_TX_POOL_OFF: usize = NET_RX_POOL_OFF + NET_POOL_SLOTS * NET_FRAME_SIZE;
75pub const NET_QUEUE_SIZE: usize = NET_TX_POOL_OFF + NET_POOL_SLOTS * NET_FRAME_SIZE;
76
77const _: () = assert!(NET_RING_SLOTS.is_power_of_two());
78const _: () = assert!(NET_POOL_SLOTS % 64 == 0);
79const _: () = assert!(NET_QUEUE_SIZE % 4096 == 0);
80const _: () = assert!(NET_QUEUE_SIZE / 4096 == 0x103);
81
82/// Frame descriptor flags.
83pub mod fd_flags {
84    /// Last descriptor of a packet.
85    pub const EOP: u16 = 1 << 0;
86    /// First descriptor of a packet.
87    pub const SOP: u16 = 1 << 1;
88    /// Device computed a valid L4 checksum.
89    pub const CSUM_OK: u16 = 1 << 2;
90    /// Request a completion for this packet.
91    pub const NEED_COMP: u16 = 1 << 3;
92    /// VLAN tag present in `vlan`.
93    pub const VLAN: u16 = 1 << 4;
94    /// Frame was truncated by the device.
95    pub const TRUNCATED: u16 = 1 << 5;
96}
97
98/// Negotiated device features.  Kept as plain `u64` bits so the ABI does not
99/// depend on `bitflags`.
100pub mod features {
101    pub const CSUM_TX: u64 = 1 << 0;
102    pub const CSUM_RX: u64 = 1 << 1;
103    pub const TSO_TX: u64 = 1 << 2;
104    pub const LRO_RX: u64 = 1 << 3;
105    pub const VLAN_TX: u64 = 1 << 4;
106    pub const VLAN_RX: u64 = 1 << 5;
107    pub const RSS: u64 = 1 << 6;
108    pub const DATA_RING: u64 = 1 << 7;
109    pub const ZC_TX: u64 = 1 << 8;
110    pub const ZC_RX: u64 = 1 << 9;
111    pub const MULTI_QUEUE: u64 = 1 << 10;
112    pub const POLLING: u64 = 1 << 11;
113
114    pub const ALL: u64 = CSUM_TX
115        | CSUM_RX
116        | TSO_TX
117        | LRO_RX
118        | VLAN_TX
119        | VLAN_RX
120        | RSS
121        | DATA_RING
122        | ZC_TX
123        | ZC_RX
124        | MULTI_QUEUE
125        | POLLING;
126}
127
128/// Link flags returned by `SYS_NET_LINK`.
129pub mod link_flags {
130    pub const UP: u32 = 1 << 0;
131    pub const FULL_DUPLEX: u32 = 1 << 1;
132    pub const CARRIER: u32 = 1 << 2;
133}
134
135/// Event kinds delivered to a bound IPC port.
136pub mod event {
137    pub const RX_READY: u32 = 1;
138    pub const TX_DONE: u32 = 2;
139    pub const LINK_UP: u32 = 3;
140    pub const LINK_DOWN: u32 = 4;
141    pub const QUEUE_ERROR: u32 = 5;
142    pub const RESET: u32 = 6;
143    pub const DEVICE_ADD: u32 = 7;
144    pub const DEVICE_REMOVE: u32 = 8;
145    pub const QUIESCE: u32 = 9;
146    pub const RESUME: u32 = 10;
147}
148
149/// One frame descriptor, 16 bytes.
150#[repr(C)]
151#[derive(Debug, Clone, Copy, PartialEq, Eq)]
152pub struct NetFrameDesc {
153    /// Index in the RX or TX pool.
154    pub slot: u32,
155    /// Payload length in bytes.
156    pub len: u16,
157    /// `fd_flags`.
158    pub flags: u16,
159    /// VLAN tag when `fd_flags::VLAN` is set, zero otherwise.
160    pub vlan: u16,
161    /// Reserved for RSS/queue steering.
162    pub rss: u16,
163    /// Reserved, must be zero.
164    pub reserved: u32,
165}
166
167const _: () = assert!(core::mem::size_of::<NetFrameDesc>() == 16);
168
169/// A single-producer / single-consumer descriptor ring.
170///
171/// `head` is the consumer index, `tail` the producer index.  Both are
172/// free-running; the array index is `counter & (size - 1)`.  The size must be
173/// a power of two.
174#[repr(C)]
175pub struct NetRing {
176    pub head: AtomicU32,
177    pub tail: AtomicU32,
178    pub size: u32,
179    pub flags: u32,
180}
181
182impl NetRing {
183    pub const fn new(size: u32) -> Self {
184        Self {
185            head: AtomicU32::new(0),
186            tail: AtomicU32::new(0),
187            size,
188            flags: 0,
189        }
190    }
191
192    #[inline]
193    pub fn len(&self) -> u32 {
194        self.tail
195            .load(Ordering::Acquire)
196            .wrapping_sub(self.head.load(Ordering::Acquire))
197    }
198
199    #[inline]
200    pub fn is_empty(&self) -> bool {
201        self.len() == 0
202    }
203
204    /// Publish one descriptor.  Single producer only.
205    ///
206    /// # Safety
207    /// `descs` must point to `self.size` valid `NetFrameDesc` entries.
208    #[inline]
209    pub unsafe fn push(&self, descs: *mut NetFrameDesc, desc: NetFrameDesc) -> bool {
210        let tail = self.tail.load(Ordering::Relaxed);
211        let head = self.head.load(Ordering::Acquire);
212        if tail.wrapping_sub(head) >= self.size {
213            return false;
214        }
215        let mask = (self.size - 1) as usize;
216        core::ptr::write(descs.add((tail as usize) & mask), desc);
217        self.tail.store(tail.wrapping_add(1), Ordering::Release);
218        true
219    }
220
221    /// Consume one descriptor.  Single consumer only.
222    ///
223    /// # Safety
224    /// `descs` must point to `self.size` valid `NetFrameDesc` entries.
225    #[inline]
226    pub unsafe fn pop(&self, descs: *const NetFrameDesc) -> Option<NetFrameDesc> {
227        let head = self.head.load(Ordering::Relaxed);
228        let tail = self.tail.load(Ordering::Acquire);
229        if head == tail {
230            return None;
231        }
232        let mask = (self.size - 1) as usize;
233        let desc = core::ptr::read(descs.add((head as usize) & mask));
234        self.head.store(head.wrapping_add(1), Ordering::Release);
235        Some(desc)
236    }
237}
238
239const _: () = assert!(core::mem::size_of::<NetRing>() == 16);
240
241/// Header of a shared network queue.
242///
243/// The structure is placed at offset 0 of the mapped region.  It contains
244/// only atomics and plain integers so it has the same layout in kernel and
245/// userspace.
246#[repr(C)]
247pub struct NetQueueHeader {
248    pub magic: u32,
249    pub abi: u16,
250    pub flags: u16,
251    pub qid: u16,
252    pub frame_size: u16,
253    pub slots: u16,
254    pub reserved0: u16,
255    /// Negotiated `features::*` bits.
256    pub features: AtomicU64,
257    pub rx: NetRing,
258    pub tx: NetRing,
259    /// Slot allocation bitmaps (bit set = slot owned).
260    pub rx_bitmap: [AtomicU64; 4],
261    pub tx_bitmap: [AtomicU64; 4],
262    pub rx_dropped: AtomicU64,
263    pub tx_dropped: AtomicU64,
264    pub irq_count: AtomicU64,
265    pub poll_count: AtomicU64,
266    /// Device generation; bumped on hotplug/reset.
267    pub epoch: AtomicU32,
268    /// `link_flags::*`.
269    pub link: AtomicU32,
270    /// Last observed link speed in Mbps (0 = unknown).
271    pub speed_mbps: AtomicU32,
272    /// Maximum transmission unit (IP payload).
273    pub mtu: AtomicU32,
274    pub reserved: [u8; 64],
275}
276
277const _: () = assert!(core::mem::size_of::<NetQueueHeader>() <= NET_QUEUE_HDR_SIZE);
278
279impl NetQueueHeader {
280    /// Initialise a raw header in place.
281    ///
282    /// # Safety
283    /// `ptr` must point to at least `NET_QUEUE_SIZE` writable bytes aligned
284    /// to 8 bytes.
285    pub unsafe fn init(ptr: *mut Self, qid: u16, features: u64, mtu: u32, epoch: u32) {
286        core::ptr::write(
287            ptr,
288            Self {
289                magic: NET_QUEUE_MAGIC,
290                abi: NET_QUEUE_ABI,
291                flags: 0,
292                qid,
293                frame_size: NET_FRAME_SIZE as u16,
294                slots: NET_RING_SLOTS as u16,
295                reserved0: 0,
296                features: AtomicU64::new(features),
297                rx: NetRing::new(NET_RING_SLOTS as u32),
298                tx: NetRing::new(NET_RING_SLOTS as u32),
299                rx_bitmap: [
300                    AtomicU64::new(0),
301                    AtomicU64::new(0),
302                    AtomicU64::new(0),
303                    AtomicU64::new(0),
304                ],
305                tx_bitmap: [
306                    AtomicU64::new(0),
307                    AtomicU64::new(0),
308                    AtomicU64::new(0),
309                    AtomicU64::new(0),
310                ],
311                rx_dropped: AtomicU64::new(0),
312                tx_dropped: AtomicU64::new(0),
313                irq_count: AtomicU64::new(0),
314                poll_count: AtomicU64::new(0),
315                epoch: AtomicU32::new(epoch),
316                link: AtomicU32::new(0),
317                speed_mbps: AtomicU32::new(0),
318                mtu: AtomicU32::new(mtu),
319                reserved: [0u8; 64],
320            },
321        );
322    }
323
324    #[inline]
325    pub fn is_valid(&self) -> bool {
326        self.magic == NET_QUEUE_MAGIC
327            && self.abi == NET_QUEUE_ABI
328            && self.frame_size as usize == NET_FRAME_SIZE
329            && self.slots as usize == NET_RING_SLOTS
330    }
331
332    #[inline]
333    pub fn as_ptr(&self) -> *mut u8 {
334        self as *const Self as *mut u8
335    }
336
337    /// # Safety
338    /// `self` must be the header of a valid `NET_QUEUE_SIZE` region.
339    #[inline]
340    pub unsafe fn rx_descs(&self) -> *mut NetFrameDesc {
341        self.as_ptr().add(NET_RX_DESC_OFF) as *mut NetFrameDesc
342    }
343
344    /// # Safety
345    /// `self` must be the header of a valid `NET_QUEUE_SIZE` region.
346    #[inline]
347    pub unsafe fn tx_descs(&self) -> *mut NetFrameDesc {
348        self.as_ptr().add(NET_TX_DESC_OFF) as *mut NetFrameDesc
349    }
350
351    /// # Safety
352    /// `self` must be the header of a valid `NET_QUEUE_SIZE` region.
353    #[inline]
354    pub unsafe fn rx_slot(&self, slot: u32) -> *mut u8 {
355        debug_assert!((slot as usize) < NET_POOL_SLOTS);
356        self.as_ptr()
357            .add(NET_RX_POOL_OFF + slot as usize * self.frame_size as usize)
358    }
359
360    /// # Safety
361    /// `self` must be the header of a valid `NET_QUEUE_SIZE` region.
362    #[inline]
363    pub unsafe fn tx_slot(&self, slot: u32) -> *mut u8 {
364        debug_assert!((slot as usize) < NET_POOL_SLOTS);
365        self.as_ptr()
366            .add(NET_TX_POOL_OFF + slot as usize * self.frame_size as usize)
367    }
368
369    /// Allocate a free RX slot.
370    #[inline]
371    pub fn alloc_rx_slot(&self) -> Option<u32> {
372        bitmap_alloc(&self.rx_bitmap)
373    }
374
375    /// Release an RX slot previously returned by `alloc_rx_slot`.
376    #[inline]
377    pub fn free_rx_slot(&self, slot: u32) {
378        bitmap_free(&self.rx_bitmap, slot);
379    }
380
381    /// Allocate a free TX slot.
382    #[inline]
383    pub fn alloc_tx_slot(&self) -> Option<u32> {
384        bitmap_alloc(&self.tx_bitmap)
385    }
386
387    /// Release a TX slot previously returned by `alloc_tx_slot`.
388    #[inline]
389    pub fn free_tx_slot(&self, slot: u32) {
390        bitmap_free(&self.tx_bitmap, slot);
391    }
392
393    /// Publish an RX descriptor (kernel/device side).
394    ///
395    /// # Safety
396    /// `self` must be a valid header and the caller must be the single RX
397    /// producer.
398    #[inline]
399    pub unsafe fn rx_push(&self, desc: NetFrameDesc) -> bool {
400        self.rx.push(self.rx_descs(), desc)
401    }
402
403    /// Consume an RX descriptor (stack side).
404    ///
405    /// # Safety
406    /// `self` must be a valid header and the caller must be the single RX
407    /// consumer.
408    #[inline]
409    pub unsafe fn rx_pop(&self) -> Option<NetFrameDesc> {
410        self.rx.pop(self.rx_descs())
411    }
412
413    /// Publish a TX descriptor (stack side).
414    ///
415    /// # Safety
416    /// `self` must be a valid header and the caller must be the single TX
417    /// producer.
418    #[inline]
419    pub unsafe fn tx_push(&self, desc: NetFrameDesc) -> bool {
420        self.tx.push(self.tx_descs(), desc)
421    }
422
423    /// Consume a TX descriptor (kernel/device side).
424    ///
425    /// # Safety
426    /// `self` must be a valid header and the caller must be the single TX
427    /// consumer.
428    #[inline]
429    pub unsafe fn tx_pop(&self) -> Option<NetFrameDesc> {
430        self.tx.pop(self.tx_descs())
431    }
432}
433
434/// Allocate the first zero bit of a 256-bit bitmap.
435#[inline]
436pub fn bitmap_alloc(words: &[AtomicU64; 4]) -> Option<u32> {
437    for (index, word) in words.iter().enumerate() {
438        loop {
439            let current = word.load(Ordering::Relaxed);
440            if current == u64::MAX {
441                break;
442            }
443            let bit = (!current).trailing_zeros();
444            let mask = 1u64 << bit;
445            if word
446                .compare_exchange_weak(current, current | mask, Ordering::AcqRel, Ordering::Relaxed)
447                .is_ok()
448            {
449                return Some(index as u32 * 64 + bit);
450            }
451        }
452    }
453    None
454}
455
456/// Clear a bit in a 256-bit bitmap.
457#[inline]
458pub fn bitmap_free(words: &[AtomicU64; 4], slot: u32) {
459    let index = (slot as usize) / 64;
460    if index >= words.len() {
461        return;
462    }
463    let mask = 1u64 << (slot % 64);
464    words[index].fetch_and(!mask, Ordering::Release);
465}
466
467/// Result of `SYS_NET_QUEUE_MAP`.
468#[repr(C)]
469#[derive(Debug, Clone, Copy, Default)]
470pub struct NetQueueMap {
471    pub base: u64,
472    pub len: u64,
473    pub qid: u16,
474    pub frame_size: u16,
475    pub slots: u16,
476    pub flags: u16,
477}
478
479/// Result of `SYS_NET_LINK`.
480#[repr(C)]
481#[derive(Debug, Clone, Copy, Default)]
482pub struct NetLinkInfo {
483    pub mac: [u8; 6],
484    pub _pad: u16,
485    pub mtu: u32,
486    pub flags: u32,
487    pub speed_mbps: u32,
488    pub epoch: u32,
489}
490
491/// Queue statistics.
492#[repr(C)]
493#[derive(Debug, Clone, Copy, Default)]
494pub struct NetStats {
495    pub rx_packets: u64,
496    pub rx_bytes: u64,
497    pub rx_dropped: u64,
498    pub tx_packets: u64,
499    pub tx_bytes: u64,
500    pub tx_dropped: u64,
501    pub irqs: u64,
502    pub polls: u64,
503}
504
505/// Result of `SYS_NET_QUEUE_INFO`.
506#[repr(C)]
507#[derive(Debug, Clone, Copy, Default)]
508pub struct NetQueueInfo {
509    pub features: u64,
510    pub qid: u16,
511    pub slots: u16,
512    pub frame_size: u16,
513    pub _pad0: u16,
514    pub epoch: u32,
515    pub mtu: u32,
516    pub stats: NetStats,
517}
518
519/// Event delivered to a port bound with `SYS_NET_IRQ_BIND`.
520#[repr(C)]
521#[derive(Debug, Clone, Copy, Default)]
522pub struct NetEvent {
523    pub kind: u32,
524    pub qid: u16,
525    pub flags: u16,
526    pub epoch: u32,
527    pub _pad: u32,
528    pub data: u64,
529}
530
531/// One entry of a batched RX/TX request.
532#[repr(C)]
533#[derive(Debug, Clone, Copy)]
534pub struct NetFrame {
535    /// User buffer address (RX: destination, TX: source).
536    pub addr: u64,
537    /// Buffer length.
538    pub len: u32,
539    /// Descriptor flags (see `fd_flags`).
540    pub flags: u32,
541}