Skip to main content

strat9_kernel/hardware/nic/
mod.rs

1//! Network driver integration layer.
2//!
3//! Thin kernel glue that wires external crates (`net-core`, `e1000`, …)
4//! to kernel services (PCI, DMA allocator, VFS schemes).
5
6pub mod common;
7pub mod data_plane;
8pub mod e1000_drv;
9pub mod e1000e_drv;
10pub mod igc_drv;
11pub mod pcnet_drv;
12pub mod rtl8139_drv;
13pub mod scheme;
14pub mod virtio_net;
15
16pub use net_core::{NetError, NetworkDevice, MTU};
17
18use alloc::{format, string::String, sync::Arc, vec::Vec};
19use spin::RwLock;
20
21struct NetDeviceEntry {
22    iface: String,
23    device: Arc<dyn NetworkDevice>,
24}
25
26static NET_DEVICES: RwLock<Vec<NetDeviceEntry>> = RwLock::new(Vec::new());
27
28/// Map a driver name to a FreeBSD-style interface prefix.
29///
30/// | Driver          | Prefix   | Example |
31/// |-----------------|----------|---------|
32/// | e1000 / Intel   | `em`     | `em0`   |
33/// | VirtIO-net      | `vtnet`  | `vtnet0`|
34/// | (other)         | `net`    | `net0`  |
35fn bsd_prefix(driver_name: &str) -> &'static str {
36    let lower = driver_name.as_bytes();
37    // Match common patterns without pulling in a full lowercase comparison
38    if lower.len() >= 4
39        && (lower[0] | 0x20) == b'e'
40        && (lower[1] | 0x20) == b'1'
41        && lower[2] == b'0'
42        && lower[3] == b'0'
43    {
44        return "em"; // Intel PRO/1000 family
45    }
46    if lower.len() >= 6
47        && (lower[0] | 0x20) == b'v'
48        && (lower[1] | 0x20) == b'i'
49        && (lower[2] | 0x20) == b'r'
50        && (lower[3] | 0x20) == b't'
51        && (lower[4] | 0x20) == b'i'
52        && (lower[5] | 0x20) == b'o'
53    {
54        return "vtnet"; // VirtIO
55    }
56    "net" // fallback
57}
58
59/// Counters per-prefix so that `em0`, `em1`, `vtnet0` are independent.
60static PREFIX_COUNTERS: RwLock<Vec<(String, usize)>> = RwLock::new(Vec::new());
61
62/// Performs the next index for operation.
63fn next_index_for(prefix: &str) -> usize {
64    let mut counters = PREFIX_COUNTERS.write();
65    for entry in counters.iter_mut() {
66        if entry.0 == prefix {
67            let idx = entry.1;
68            entry.1 += 1;
69            return idx;
70        }
71    }
72    counters.push((String::from(prefix), 1));
73    0
74}
75
76// ---------------------------------------------------------------------------
77// NIC interrupt dispatch (see idt.rs:nic_handler)
78// ---------------------------------------------------------------------------
79
80/// IRQ line of the first registered NIC.  Written once by the NIC driver's
81/// `init()`; read by `nic_handler` in the IDT to send EOI.
82pub static NIC_IRQ_LINE: core::sync::atomic::AtomicU8 = core::sync::atomic::AtomicU8::new(0xFF);
83
84/// Global reference to the first NIC device, used by `nic_handler` to call
85/// `handle_interrupt()`.  Set via `set_nic_device()` after PCI probe.
86///
87/// # TODO (multi-NIC)
88///
89/// This only supports a single NIC.  When multiple NICs are present the
90/// handler should iterate all registered devices or use per-IRQ dispatch.
91static NIC_DEVICE: spin::Mutex<Option<Arc<dyn NetworkDevice>>> = spin::Mutex::new(None);
92
93/// Store a NIC device reference and its IRQ line for the IDT handler.
94///
95/// Called from NIC drivers (`e1000_drv`, `e1000e_drv`, …) after successful
96/// initialisation.
97pub fn set_nic_device(dev: Arc<dyn NetworkDevice>, irq: u8) {
98    NIC_IRQ_LINE.store(irq, core::sync::atomic::Ordering::Relaxed);
99    *NIC_DEVICE.lock() = Some(dev);
100    log::info!("NIC dispatch set for IRQ {}", irq);
101}
102
103// ---------------------------------------------------------------------------
104// strate-net wakeup on NIC IRQ (point 1)
105// ---------------------------------------------------------------------------
106
107/// Cached task ID of the strate-net process, registered from the boot
108/// sequence after strate-net is spawned.  Zero = not yet known; the NIC
109/// handler will skip the wakeup and rely on strate-net's periodic polling.
110///
111/// # TODO
112///
113/// Wire up registration : either via a syscall from strate-net itself or
114/// by scanning `get_all_tasks()` from a safe (non-IRQ) context after init
115/// spawns strate-net.
116static STRATE_NET_TID: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(0);
117
118/// Register the strate-net task ID so the NIC IRQ handler can wake it.
119pub fn register_strate_net_tid(tid: u64) {
120    STRATE_NET_TID.store(tid, core::sync::atomic::Ordering::Relaxed);
121    log::info!("NIC: strate-net task {} registered for IRQ wakeup", tid);
122}
123
124/// Called from `idt.rs:nic_handler`.  Dispatches to the registered NIC's
125/// `handle_interrupt()` (reads ICR, coalescing, TX reclaim).
126/// If the N2 data plane is active, drains received packets into the RX
127/// ring before waking strate-net (zero-syscall data path).
128pub fn handle_interrupt() {
129    // Phase 1 : hardware interrupt handling (brief, must hold NIC_DEVICE lock).
130    let dev = {
131        let guard = NIC_DEVICE.lock();
132        guard.as_ref().map(|d| {
133            d.handle_interrupt();
134            d.clone()
135        })
136    };
137    let dev = match dev {
138        Some(d) => d,
139        None => {
140            crate::serial_println!("[net] IRQ: no NIC device registered");
141            return;
142        }
143    };
144
145    // Phase 2 : drain N2 rings (no NIC_DEVICE lock held, IRQs may still be
146    // disabled by the IDT entry). Holding only NIC_DATA_PLANE here.
147    if let Some(ref dp) = *NIC_DATA_PLANE.lock() {
148        // Drain pending RX packets from HW into the N2 RX ring.
149        let mut buf = [0u8; 2048];
150        let mut rx_count = 0usize;
151        let mut backpressure = false;
152        while let Ok(n) = dev.receive(&mut buf) {
153            if n > 0 {
154                rx_count += 1;
155                if rx_count <= 3 {
156                    crate::serial_println!("[net] IRQ rx {} bytes (slot {})", n, rx_count);
157                }
158            }
159            if dp.push_rx(0, &buf[..n]).is_err() {
160                crate::serial_println!("[net] IRQ RX ring full, backpressure");
161                backpressure = true;
162                break;
163            }
164        }
165        if rx_count > 3 {
166            crate::serial_println!("[net] IRQ rx total {} packets", rx_count);
167        }
168        if rx_count == 0 {
169            crate::serial_println!("[net] IRQ rx: no packets received from HW");
170        }
171
172        // N1 : notify scheduler if the RX ring is full (backpressure).
173        if backpressure {
174            crate::ipc::n1::notify_scheduler(crate::ipc::n1::N1Event::NicBackpressure);
175        }
176
177        // Notify consumer (strate-net) that new RX data is available.
178        if rx_count > 0 {
179            dp.notify_rx_consumer(0);
180        }
181
182        // Drain pending TX packets from the N2 TX ring into HW.
183        let mut tx_buf = [0u8; 2048];
184        while let Ok(Some(n)) = dp.pop_tx(0, &mut tx_buf) {
185            if dev.transmit(&tx_buf[..n]).is_err() {
186                break;
187            }
188        }
189
190        // N1 : check for scheduler flow-control hints (non-blocking).
191        if let Some(event) = crate::ipc::n1::poll_nic_events() {
192            log::trace!("[net] N1 sched→NIC event: {:?}", event);
193        }
194    } else {
195        crate::serial_println!("[net] IRQ: N2 data plane not initialized");
196    }
197
198    let tid_u64 = STRATE_NET_TID.load(core::sync::atomic::Ordering::Relaxed);
199    if tid_u64 != 0 {
200        let _ = crate::process::scheduler::wake_task(crate::process::TaskId(tid_u64));
201    } else {
202        crate::serial_println!("[net] IRQ: strate-net not registered (TID=0)");
203    }
204}
205
206/// Performs the register device operation.
207pub fn register_device(device: Arc<dyn NetworkDevice>) -> String {
208    let prefix = bsd_prefix(device.name());
209    let idx = next_index_for(prefix);
210    let iface = format!("{}{}", prefix, idx);
211    let mac = device.mac_address();
212    log::info!(
213        "[net] {} -> {} (MAC {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x})",
214        device.name(),
215        iface,
216        mac[0],
217        mac[1],
218        mac[2],
219        mac[3],
220        mac[4],
221        mac[5],
222    );
223    let mut devs = NET_DEVICES.write();
224    devs.push(NetDeviceEntry {
225        iface: iface.clone(),
226        device,
227    });
228    iface
229}
230
231/// Returns device.
232pub fn get_device(name: &str) -> Option<Arc<dyn NetworkDevice>> {
233    NET_DEVICES
234        .read()
235        .iter()
236        .find(|e| e.iface == name)
237        .map(|e| e.device.clone())
238}
239
240/// Returns default device.
241pub fn get_default_device() -> Option<Arc<dyn NetworkDevice>> {
242    NET_DEVICES.read().first().map(|e| e.device.clone())
243}
244
245/// Performs the list interfaces operation.
246pub fn list_interfaces() -> Vec<String> {
247    NET_DEVICES.read().iter().map(|e| e.iface.clone()).collect()
248}
249
250/// Call `poll()` on every registered NIC (watchdog + link check).
251/// Safe to call from any non-IRQ context (allocates via get_all_tasks).
252///
253/// # TODO
254///
255/// Hook this into a kernel workqueue or periodic thread instead of
256/// the APIC timer tick : SpinLock::lock reads percpu data (GS:[0])
257/// which is unsafe during the swapgs→iretq window.
258pub fn poll_all() {
259    let guard = NET_DEVICES.read();
260    for entry in guard.iter() {
261        entry.device.poll();
262    }
263}
264
265/// Try to discover strate-net and cache its task ID.
266pub fn try_register_strate_net() {
267    if STRATE_NET_TID.load(core::sync::atomic::Ordering::Relaxed) != 0 {
268        return;
269    }
270    if let Some(tasks) = crate::process::get_all_tasks() {
271        for t in &tasks {
272            if t.name == "strate-net" {
273                register_strate_net_tid(t.id.0);
274                return;
275            }
276        }
277    }
278}
279
280/// Performs the init operation.
281pub fn init() {
282    log::info!("[net] Scanning for network devices...");
283    // Probe modern Intel first, then legacy fallback.
284    e1000e_drv::init();
285    igc_drv::init();
286    e1000_drv::init();
287    pcnet_drv::init();
288    rtl8139_drv::init();
289    virtio_net::init();
290    if let Err(e) = scheme::register_net_scheme() {
291        log::warn!("[net] Failed to register net scheme: {:?}", e);
292    }
293    // Initialise the N2 data plane if any NIC was registered.
294    init_data_plane();
295}
296
297// ── N2 data-plane global instance ─────────────────────────────────────────
298
299use data_plane::NicDataPlane;
300use spin::Mutex;
301
302/// Global NIC data plane, lazily initialised after NIC detection.
303static NIC_DATA_PLANE: Mutex<Option<NicDataPlane>> = Mutex::new(None);
304
305/// Initialise the N2 data plane with one ring pair per registered device.
306/// Each device gets a single RX/TX pair (RSS queues extend this).
307fn init_data_plane() {
308    let count = NET_DEVICES.read().len();
309    if count == 0 {
310        log::debug!("[net] No NIC devices found : skipping data plane init");
311        return;
312    }
313    // One ring pair per NIC for now; RSS would create one per queue.
314    match NicDataPlane::new(count, 256, 2048) {
315        Ok(dp) => {
316            *NIC_DATA_PLANE.lock() = Some(dp);
317            log::info!("[net] N2 data plane initialised with {} queue(s)", count);
318        }
319        Err(e) => {
320            log::warn!("[net] Failed to initialise N2 data plane: {}", e);
321        }
322    }
323}
324
325/// Access the global N2 data plane (returns None if not yet initialised).
326pub fn data_plane() -> &'static Mutex<Option<NicDataPlane>> {
327    &NIC_DATA_PLANE
328}