Skip to main content

strat9_kernel/hardware/nic/
net_queue.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.
24//!
25//! A `NetQueue` owns one `NET_QUEUE_SIZE` region allocated from the shared
26//! ring allocator.  The region is mapped into the networking strate with
27//! `SYS_NET_QUEUE_MAP`, so both sides address the same descriptor rings and
28//! frame pools.  The kernel keeps a page table (`vas`/`phys`) because the
29//! pages are not guaranteed to be physically contiguous.
30//!
31//! The queue is the data plane primitive: once mapped, RX and TX are driven
32//! by the descriptor rings and the `kick`/IRQ notifications, without a
33//! syscall per packet.
34
35use alloc::{sync::Arc, vec::Vec};
36use core::sync::atomic::{AtomicU64, AtomicU8, Ordering};
37
38use crate::{
39    ipc::shared_ring::{self, RingId, SharedRing},
40    sync::{SpinLock, WaitQueue},
41};
42use strat9_abi::net::{
43    features, link_flags, NetFrameDesc, NetQueueHeader, NET_FRAME_SIZE, NET_QUEUE_SIZE,
44};
45
46/// Per-queue event counter and wait queue.
47///
48/// The counter is monotonic and lives outside the shared region: the device
49/// only needs to call `notify()` (from IRQ or poll context), and the consumer
50/// waits on it.  A consumer remembers the last sequence it observed so a
51/// wakeup that races with the check is never lost.
52pub struct QueueEvent {
53    seq: AtomicU64,
54    waiters: WaitQueue,
55}
56
57impl QueueEvent {
58    pub const fn new() -> Self {
59        Self {
60            seq: AtomicU64::new(0),
61            waiters: WaitQueue::new(),
62        }
63    }
64
65    #[inline]
66    pub fn notify(&self) {
67        self.seq.fetch_add(1, Ordering::Release);
68        self.waiters.wake_all();
69    }
70
71    #[inline]
72    pub fn sequence(&self) -> u64 {
73        self.seq.load(Ordering::Acquire)
74    }
75
76    /// Block until the sequence differs from `seen`, then update `seen`.
77    #[inline]
78    pub fn wait(&self, seen: &mut u64) {
79        self.waiters.wait_until(|| {
80            let current = self.seq.load(Ordering::Acquire);
81            if current != *seen {
82                *seen = current;
83                Some(())
84            } else {
85                None
86            }
87        });
88    }
89
90    /// Non-blocking variant.
91    #[inline]
92    pub fn poll(&self, seen: &mut u64) -> bool {
93        let current = self.seq.load(Ordering::Acquire);
94        if current != *seen {
95            *seen = current;
96            true
97        } else {
98            false
99        }
100    }
101}
102
103impl Default for QueueEvent {
104    fn default() -> Self {
105        Self::new()
106    }
107}
108
109/// One shared RX/TX queue pair for a network device.
110pub struct NetQueue {
111    pub qid: u16,
112    pub dev_id: u64,
113    pub ring_id: RingId,
114    ring: Arc<SharedRing>,
115    /// Kernel virtual address of each page, in mapping order.
116    vas: Vec<u64>,
117    /// Physical address of each page, in mapping order.
118    phys: Vec<u64>,
119    header: *mut NetQueueHeader,
120    pub event: Arc<QueueEvent>,
121    /// IRQ vector bound to this queue (0xFF = polling).
122    pub irq: AtomicU8,
123    /// IPC port bound to this queue (0 = none).
124    pub port: AtomicU64,
125    /// Feature mask negotiated with the device.
126    pub features: AtomicU64,
127    /// Serialises queue teardown against the IRQ handler.
128    pub alive: AtomicU8,
129    /// True once the region has been mapped into a userspace strate.
130    mapped: core::sync::atomic::AtomicBool,
131    /// User virtual base of the mapping, 0 when unmapped.
132    mapped_base: AtomicU64,
133    /// Task that owns the mapping, 0 when unmapped.
134    mapped_owner: AtomicU64,
135    /// Descriptor popped by a consumer whose buffer was too small.  It must
136    /// be returned before the next descriptor to preserve ordering.
137    pending_rx: SpinLock<Option<NetFrameDesc>>,
138}
139
140// SAFETY: all shared accesses go through atomics in the header, or through
141// the single-producer/single-consumer descriptor rings.  `vas`/`phys` are
142// immutable after construction.  `header` points into a shared region whose
143// lifetime is tied to `ring` (held by this struct).
144unsafe impl Send for NetQueue {}
145unsafe impl Sync for NetQueue {}
146
147impl NetQueue {
148    /// Allocate and initialise a queue region.
149    pub fn new(
150        dev_id: u64,
151        qid: u16,
152        feature_mask: u64,
153        mtu: u32,
154        epoch: u32,
155    ) -> Result<Arc<Self>, &'static str> {
156        let ring_id = shared_ring::create_ring(NET_QUEUE_SIZE)
157            .map_err(|_| "failed to allocate network queue region")?;
158        let ring = shared_ring::get_ring(ring_id).ok_or("network queue region disappeared")?;
159
160        let phys = ring.frame_phys_addrs();
161        if phys.is_empty() {
162            let _ = shared_ring::destroy_ring(ring_id);
163            return Err("empty network queue region");
164        }
165        let vas = phys
166            .iter()
167            .map(|pa| crate::memory::phys_to_virt(*pa) as u64)
168            .collect::<Vec<_>>();
169
170        let header = vas[0] as *mut NetQueueHeader;
171        // SAFETY: `vas[0]` points to the first page of a region of
172        // `NET_QUEUE_SIZE` bytes, which is at least `size_of::<NetQueueHeader>()`
173        // and 8-byte aligned (page aligned).
174        unsafe {
175            NetQueueHeader::init(header, qid, feature_mask, mtu, epoch);
176        }
177
178        Ok(Arc::new(Self {
179            qid,
180            dev_id,
181            ring_id,
182            ring,
183            vas,
184            phys,
185            header,
186            event: Arc::new(QueueEvent::new()),
187            irq: AtomicU8::new(0xFF),
188            port: AtomicU64::new(0),
189            features: AtomicU64::new(feature_mask),
190            alive: AtomicU8::new(1),
191            mapped: core::sync::atomic::AtomicBool::new(false),
192            mapped_base: AtomicU64::new(0),
193            mapped_owner: AtomicU64::new(0),
194            pending_rx: SpinLock::new(None),
195        }))
196    }
197
198    #[inline]
199    pub fn header(&self) -> &NetQueueHeader {
200        // SAFETY: `header` is valid for the lifetime of `self` (backed by
201        // `ring`, which is held by `self`).
202        unsafe { &*self.header }
203    }
204
205    #[inline]
206    pub fn header_mut_ptr(&self) -> *mut NetQueueHeader {
207        self.header
208    }
209
210    #[inline]
211    pub fn region(&self) -> &Arc<SharedRing> {
212        &self.ring
213    }
214
215    /// Reserve the single userspace mapping for `owner`.  Returns `false` if
216    /// another live task owns it.  A mapping left behind by a dead task is
217    /// reclaimed (hot-restart).
218    pub fn try_map(&self, owner: u64) -> bool {
219        if self
220            .mapped
221            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
222            .is_ok()
223        {
224            self.mapped_owner.store(owner, Ordering::Release);
225            return true;
226        }
227
228        let previous = self.mapped_owner.load(Ordering::Acquire);
229        if previous != 0
230            && previous != owner
231            && crate::process::get_task_by_id(crate::process::TaskId::from_u64(previous)).is_none()
232        {
233            // The previous owner died without unmapping; its address space
234            // is gone, so only the bookkeeping needs to be reset.
235            self.mapped_owner.store(owner, Ordering::Release);
236            return true;
237        }
238        false
239    }
240
241    /// Release the mapping reservation after a failed map.
242    pub fn unmap_reservation(&self) {
243        self.mapped_base.store(0, Ordering::Release);
244        self.mapped_owner.store(0, Ordering::Release);
245        self.mapped.store(false, Ordering::Release);
246    }
247
248    /// Record the user base of a successful mapping.
249    pub fn set_mapped_base(&self, base: u64) {
250        self.mapped_base.store(base, Ordering::Release);
251    }
252
253    /// Take the user base of the mapping (0 if none).
254    pub fn take_mapped_base(&self) -> u64 {
255        self.mapped_base.swap(0, Ordering::AcqRel)
256    }
257
258    #[inline]
259    pub fn phys_pages(&self) -> &[u64] {
260        &self.phys
261    }
262
263    #[inline]
264    pub fn is_alive(&self) -> bool {
265        self.alive.load(Ordering::Acquire) != 0
266    }
267
268    /// Mark the queue dead and wake any waiter.  The region is released when
269    /// the last `Arc<NetQueue>` is dropped.
270    pub fn shutdown(&self) {
271        self.alive.store(0, Ordering::Release);
272        self.event.notify();
273    }
274
275    /// Translate a byte offset in the region to its kernel VA.
276    #[inline]
277    fn ptr_at(&self, offset: usize) -> Option<*mut u8> {
278        if offset >= NET_QUEUE_SIZE {
279            return None;
280        }
281        let page = offset / 4096;
282        let delta = offset % 4096;
283        // SAFETY: `delta < 4096`, so the result stays inside the page whose
284        // base address was recorded in `vas` for this region.
285        self.vas
286            .get(page)
287            .map(|base| unsafe { (*base as *mut u8).add(delta) })
288    }
289
290    /// Physical address of a byte offset in the region.
291    #[inline]
292    pub fn phys_at(&self, offset: usize) -> Option<u64> {
293        if offset >= NET_QUEUE_SIZE {
294            return None;
295        }
296        let page = offset / 4096;
297        let delta = offset % 4096;
298        self.phys.get(page).map(|base| *base + delta as u64)
299    }
300
301    /// Physical address of an RX slot (for programming DMA).
302    #[inline]
303    pub fn rx_slot_phys(&self, slot: u32) -> Option<u64> {
304        if slot as usize >= strat9_abi::net::NET_POOL_SLOTS {
305            return None;
306        }
307        let off = strat9_abi::net::NET_RX_POOL_OFF + slot as usize * NET_FRAME_SIZE;
308        self.phys_at(off)
309    }
310
311    /// Physical address of a TX slot.
312    #[inline]
313    pub fn tx_slot_phys(&self, slot: u32) -> Option<u64> {
314        if slot as usize >= strat9_abi::net::NET_POOL_SLOTS {
315            return None;
316        }
317        let off = strat9_abi::net::NET_TX_POOL_OFF + slot as usize * NET_FRAME_SIZE;
318        self.phys_at(off)
319    }
320
321    /// Kernel VA of an RX slot.
322    #[inline]
323    pub fn rx_slot_ptr(&self, slot: u32) -> Option<*mut u8> {
324        if slot as usize >= strat9_abi::net::NET_POOL_SLOTS {
325            return None;
326        }
327        let off = strat9_abi::net::NET_RX_POOL_OFF + slot as usize * NET_FRAME_SIZE;
328        self.ptr_at(off)
329    }
330
331    /// Kernel VA of a TX slot.
332    #[inline]
333    pub fn tx_slot_ptr(&self, slot: u32) -> Option<*mut u8> {
334        if slot as usize >= strat9_abi::net::NET_POOL_SLOTS {
335            return None;
336        }
337        let off = strat9_abi::net::NET_TX_POOL_OFF + slot as usize * NET_FRAME_SIZE;
338        self.ptr_at(off)
339    }
340
341    /// Copy a frame into an RX slot and publish it.
342    ///
343    /// Called from the IRQ/poll path.  Returns `false` if the ring or the
344    /// slot pool is full.
345    pub fn push_rx(&self, frame: &[u8]) -> bool {
346        if frame.len() > NET_FRAME_SIZE {
347            self.header().rx_dropped.fetch_add(1, Ordering::Relaxed);
348            return false;
349        }
350        let Some(slot) = self.header().alloc_rx_slot() else {
351            self.header().rx_dropped.fetch_add(1, Ordering::Relaxed);
352            return false;
353        };
354        let Some(dst) = self.rx_slot_ptr(slot) else {
355            self.header().free_rx_slot(slot);
356            return false;
357        };
358        // SAFETY: `dst` points to a `NET_FRAME_SIZE` slot owned by us.
359        unsafe {
360            core::ptr::copy_nonoverlapping(frame.as_ptr(), dst, frame.len());
361        }
362        let desc = NetFrameDesc {
363            slot,
364            len: frame.len() as u16,
365            flags: strat9_abi::net::fd_flags::SOP | strat9_abi::net::fd_flags::EOP,
366            vlan: 0,
367            rss: 0,
368            reserved: 0,
369        };
370        // SAFETY: single RX producer (IRQ/poll path serialised by the caller).
371        if unsafe { self.header().rx_push(desc) } {
372            true
373        } else {
374            self.header().free_rx_slot(slot);
375            self.header().rx_dropped.fetch_add(1, Ordering::Relaxed);
376            false
377        }
378    }
379
380    /// Pop one RX descriptor (stack side).  A descriptor previously returned
381    /// with `putback_rx` is served first to preserve ordering.
382    pub fn pop_rx(&self) -> Option<NetFrameDesc> {
383        if let Some(desc) = self.pending_rx.lock().take() {
384            return Some(desc);
385        }
386        // SAFETY: single RX consumer.
387        unsafe { self.header().rx_pop() }
388    }
389
390    /// Put back an RX descriptor whose consumer buffer was too small.
391    pub fn putback_rx(&self, desc: NetFrameDesc) {
392        *self.pending_rx.lock() = Some(desc);
393    }
394
395    /// Release an RX slot after the stack copied its payload.
396    pub fn release_rx(&self, slot: u32) {
397        self.header().free_rx_slot(slot);
398    }
399
400    /// Allocate a TX slot and return its kernel VA.
401    pub fn alloc_tx(&self) -> Option<(u32, *mut u8)> {
402        let slot = self.header().alloc_tx_slot()?;
403        match self.tx_slot_ptr(slot) {
404            Some(ptr) => Some((slot, ptr)),
405            None => {
406                self.header().free_tx_slot(slot);
407                None
408            }
409        }
410    }
411
412    /// Publish a TX descriptor after the stack filled the slot.
413    pub fn push_tx(&self, desc: NetFrameDesc) -> bool {
414        if desc.slot as usize >= strat9_abi::net::NET_POOL_SLOTS {
415            return false;
416        }
417        // SAFETY: single TX producer.
418        if unsafe { self.header().tx_push(desc) } {
419            true
420        } else {
421            self.header().free_tx_slot(desc.slot);
422            self.header().tx_dropped.fetch_add(1, Ordering::Relaxed);
423            false
424        }
425    }
426
427    /// Pop one TX descriptor (kernel/device side).
428    pub fn pop_tx(&self) -> Option<NetFrameDesc> {
429        // SAFETY: single TX consumer.
430        unsafe { self.header().tx_pop() }
431    }
432
433    /// Release a transmitted TX slot.
434    pub fn release_tx(&self, slot: u32) {
435        self.header().free_tx_slot(slot);
436    }
437
438    /// Update the shared link state.
439    pub fn set_link(&self, up: bool, speed_mbps: u32) {
440        let mut flags = 0;
441        if up {
442            flags |= link_flags::UP | link_flags::CARRIER | link_flags::FULL_DUPLEX;
443        }
444        self.header().link.store(flags, Ordering::Release);
445        self.header()
446            .speed_mbps
447            .store(speed_mbps, Ordering::Relaxed);
448    }
449
450    /// Current feature mask.
451    #[inline]
452    pub fn feature_mask(&self) -> u64 {
453        self.features.load(Ordering::Acquire)
454    }
455
456    /// Negotiate features and MTU after the driver has probed the device.
457    pub fn configure(&self, mask: u64, mtu: u32) {
458        self.set_features(mask);
459        self.header().mtu.store(mtu, Ordering::Release);
460    }
461
462    /// Enable features after negotiation.
463    #[inline]
464    pub fn set_features(&self, mask: u64) {
465        self.features.store(mask & features::ALL, Ordering::Release);
466        self.header()
467            .features
468            .store(mask & features::ALL, Ordering::Release);
469    }
470}
471
472impl Drop for NetQueue {
473    fn drop(&mut self) {
474        self.alive.store(0, Ordering::Release);
475        // Wake waiters before revoking mappings, then release the pages.
476        self.event.notify();
477        let _ = shared_ring::destroy_ring(self.ring_id);
478    }
479}
480
481/// A set of queues for one device.
482pub struct NetQueues {
483    pub queues: Vec<Arc<NetQueue>>,
484}
485
486impl NetQueues {
487    pub fn new() -> Self {
488        Self { queues: Vec::new() }
489    }
490
491    pub fn push(&mut self, queue: Arc<NetQueue>) {
492        self.queues.push(queue);
493    }
494
495    pub fn get(&self, qid: u16) -> Option<&Arc<NetQueue>> {
496        self.queues.iter().find(|q| q.qid == qid)
497    }
498
499    pub fn len(&self) -> usize {
500        self.queues.len()
501    }
502
503    pub fn is_empty(&self) -> bool {
504        self.queues.is_empty()
505    }
506}
507
508impl Default for NetQueues {
509    fn default() -> Self {
510        Self::new()
511    }
512}
513
514/// Global serialisation for queue creation/teardown.
515pub static QUEUE_LOCK: SpinLock<()> = SpinLock::new(());