⚠️ VeridianOS Kernel Documentation - This is low-level kernel code. All functions are unsafe unless explicitly marked otherwise. no_std

veridian_kernel/drivers/
network.rs

1//! Network Device Drivers
2//!
3//! Implements network device drivers including Ethernet, Wi-Fi, and loopback.
4
5use alloc::{boxed::Box, collections::BTreeMap, string::String, sync::Arc, vec, vec::Vec};
6
7use spin::{Mutex, RwLock};
8
9use crate::{
10    error::KernelError,
11    services::driver_framework::{DeviceClass, DeviceInfo, DeviceStatus, Driver},
12    sync::once_lock::OnceLock,
13};
14
15/// Network packet buffer
16#[derive(Debug, Clone)]
17pub struct NetworkPacket {
18    pub data: Vec<u8>,
19    pub length: usize,
20    pub timestamp: u64,
21}
22
23impl NetworkPacket {
24    pub fn new(data: Vec<u8>) -> Self {
25        let length = data.len();
26        Self {
27            data,
28            length,
29            timestamp: crate::arch::timer::get_ticks(),
30        }
31    }
32}
33
34/// Network interface statistics
35#[derive(Debug, Clone, Default)]
36pub struct NetworkStats {
37    pub rx_packets: u64,
38    pub tx_packets: u64,
39    pub rx_bytes: u64,
40    pub tx_bytes: u64,
41    pub rx_errors: u64,
42    pub tx_errors: u64,
43    pub rx_dropped: u64,
44    pub tx_dropped: u64,
45    pub collisions: u64,
46}
47
48/// Network interface state
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum InterfaceState {
51    Down,
52    Up,
53    Testing,
54    Unknown,
55}
56
57/// Network interface configuration
58#[derive(Debug, Clone)]
59pub struct InterfaceConfig {
60    pub name: String,
61    pub mac_address: [u8; 6],
62    pub mtu: u16,
63    pub state: InterfaceState,
64    pub ip_address: Option<[u8; 4]>,
65    pub netmask: Option<[u8; 4]>,
66    pub gateway: Option<[u8; 4]>,
67}
68
69impl InterfaceConfig {
70    pub fn new(name: String, mac_address: [u8; 6]) -> Self {
71        Self {
72            name,
73            mac_address,
74            mtu: 1500, // Standard Ethernet MTU
75            state: InterfaceState::Down,
76            ip_address: None,
77            netmask: None,
78            gateway: None,
79        }
80    }
81}
82
83/// Network device trait
84pub trait NetworkDevice: Send + Sync {
85    /// Get device name
86    fn name(&self) -> &str;
87
88    /// Get interface configuration
89    fn get_config(&self) -> InterfaceConfig;
90
91    /// Set interface configuration
92    fn set_config(&mut self, config: InterfaceConfig) -> Result<(), KernelError>;
93
94    /// Bring interface up
95    fn up(&mut self) -> Result<(), KernelError>;
96
97    /// Bring interface down
98    fn down(&mut self) -> Result<(), KernelError>;
99
100    /// Send a packet
101    fn send_packet(&mut self, packet: NetworkPacket) -> Result<(), KernelError>;
102
103    /// Receive a packet (non-blocking)
104    fn receive_packet(&mut self) -> Result<Option<NetworkPacket>, KernelError>;
105
106    /// Get interface statistics
107    fn get_stats(&self) -> NetworkStats;
108
109    /// Reset interface statistics
110    fn reset_stats(&mut self);
111
112    /// Check if link is up
113    fn link_up(&self) -> bool;
114
115    /// Get link speed in Mbps
116    fn link_speed(&self) -> u32;
117}
118
119/// Ethernet driver implementation
120#[allow(dead_code)] // Future-phase driver stub
121pub struct EthernetDriver {
122    name: String,
123    config: Mutex<InterfaceConfig>,
124    stats: Mutex<NetworkStats>,
125    rx_queue: Mutex<Vec<NetworkPacket>>,
126    tx_queue: Mutex<Vec<NetworkPacket>>,
127    device_info: DeviceInfo,
128    enabled: Mutex<bool>,
129}
130
131impl EthernetDriver {
132    /// Create a new Ethernet driver
133    pub fn new(name: String, mac_address: [u8; 6], device_info: DeviceInfo) -> Self {
134        Self {
135            config: Mutex::new(InterfaceConfig::new(name.clone(), mac_address)),
136            stats: Mutex::new(NetworkStats::default()),
137            rx_queue: Mutex::new(Vec::new()),
138            tx_queue: Mutex::new(Vec::new()),
139            device_info,
140            enabled: Mutex::new(false),
141            name,
142        }
143    }
144
145    /// Process transmitted packets
146    fn process_tx_queue(&mut self) -> Result<(), KernelError> {
147        let mut tx_queue = self.tx_queue.lock();
148        let mut stats = self.stats.lock();
149
150        // Simulate packet transmission
151        for packet in tx_queue.drain(..) {
152            // Route through hardware NIC via net::device layer
153            let _ = crate::net::device::with_device_mut(&self.name, |dev| {
154                let net_packet = crate::net::Packet::from_bytes(&packet.data);
155                dev.transmit(&net_packet)
156            });
157            stats.tx_packets += 1;
158            stats.tx_bytes += packet.length as u64;
159        }
160
161        Ok(())
162    }
163
164    /// Simulate packet reception
165    pub fn simulate_receive(&self, data: Vec<u8>) {
166        let packet = NetworkPacket::new(data);
167        let mut rx_queue = self.rx_queue.lock();
168        let mut stats = self.stats.lock();
169
170        stats.rx_packets += 1;
171        stats.rx_bytes += packet.length as u64;
172
173        rx_queue.push(packet);
174        crate::println!("[ETH] Received packet ({} bytes)", stats.rx_bytes);
175    }
176}
177
178impl NetworkDevice for EthernetDriver {
179    fn name(&self) -> &str {
180        &self.name
181    }
182
183    fn get_config(&self) -> InterfaceConfig {
184        self.config.lock().clone()
185    }
186
187    fn set_config(&mut self, config: InterfaceConfig) -> Result<(), KernelError> {
188        *self.config.lock() = config;
189        crate::println!("[ETH] Updated interface configuration for {}", self.name);
190        Ok(())
191    }
192
193    fn up(&mut self) -> Result<(), KernelError> {
194        self.config.lock().state = InterfaceState::Up;
195        *self.enabled.lock() = true;
196        crate::println!("[ETH] Interface {} is up", self.name);
197        Ok(())
198    }
199
200    fn down(&mut self) -> Result<(), KernelError> {
201        self.config.lock().state = InterfaceState::Down;
202        *self.enabled.lock() = false;
203        crate::println!("[ETH] Interface {} is down", self.name);
204        Ok(())
205    }
206
207    fn send_packet(&mut self, packet: NetworkPacket) -> Result<(), KernelError> {
208        if !*self.enabled.lock() {
209            return Err(KernelError::InvalidState {
210                expected: "up",
211                actual: "down",
212            });
213        }
214
215        self.tx_queue.lock().push(packet);
216        self.process_tx_queue()?;
217        Ok(())
218    }
219
220    fn receive_packet(&mut self) -> Result<Option<NetworkPacket>, KernelError> {
221        if !*self.enabled.lock() {
222            return Ok(None);
223        }
224
225        Ok(self.rx_queue.lock().pop())
226    }
227
228    fn get_stats(&self) -> NetworkStats {
229        self.stats.lock().clone()
230    }
231
232    fn reset_stats(&mut self) {
233        *self.stats.lock() = NetworkStats::default();
234        crate::println!("[ETH] Reset statistics for {}", self.name);
235    }
236
237    fn link_up(&self) -> bool {
238        *self.enabled.lock() && self.config.lock().state == InterfaceState::Up
239    }
240
241    fn link_speed(&self) -> u32 {
242        if self.link_up() {
243            1000 // 1 Gbps
244        } else {
245            0
246        }
247    }
248}
249
250impl Driver for EthernetDriver {
251    fn name(&self) -> &str {
252        "ethernet"
253    }
254
255    fn supported_classes(&self) -> Vec<DeviceClass> {
256        vec![DeviceClass::Network]
257    }
258
259    fn supports_device(&self, device: &DeviceInfo) -> bool {
260        device.class == DeviceClass::Network
261    }
262
263    fn probe(&mut self, _device: &DeviceInfo) -> Result<(), KernelError> {
264        crate::println!("[ETH] Probing device: {}", _device.name);
265        // Validate device is Ethernet via PCI class code
266        if _device.class != DeviceClass::Network {
267            return Err(KernelError::InvalidArgument {
268                name: "device_class",
269                value: "not_network",
270            });
271        }
272        Ok(())
273    }
274
275    fn attach(&mut self, _device: &DeviceInfo) -> Result<(), KernelError> {
276        crate::println!("[ETH] Attaching to device: {}", _device.name);
277
278        // Initialize hardware -- MMIO setup delegated to EthernetDevice::with_mmio()
279        // when BAR0 is available from PCI enumeration
280
281        self.up()?;
282
283        crate::println!("[ETH] Successfully attached to {}", _device.name);
284        Ok(())
285    }
286
287    fn detach(&mut self, _device: &DeviceInfo) -> Result<(), KernelError> {
288        crate::println!("[ETH] Detaching from device: {}", _device.name);
289
290        self.down()?;
291
292        crate::println!("[ETH] Successfully detached from {}", _device.name);
293        Ok(())
294    }
295
296    fn suspend(&mut self) -> Result<(), KernelError> {
297        self.down()
298    }
299
300    fn resume(&mut self) -> Result<(), KernelError> {
301        self.up()
302    }
303
304    fn handle_interrupt(&mut self, _irq: u8) -> Result<(), KernelError> {
305        crate::println!("[ETH] Handling interrupt {} for {}", _irq, self.name);
306
307        // Poll hardware NIC for received packets and sync statistics
308        let _ = crate::net::device::with_device_mut(&self.name, |dev| {
309            while let Ok(Some(pkt)) = dev.receive() {
310                let net_pkt = NetworkPacket::new(pkt.data().to_vec());
311                self.rx_queue.lock().push(net_pkt);
312            }
313        });
314
315        Ok(())
316    }
317
318    fn read(&mut self, _offset: u64, buffer: &mut [u8]) -> Result<usize, KernelError> {
319        // For network devices, reading could return received packets
320        if let Some(packet) = self.receive_packet()? {
321            let copy_len = buffer.len().min(packet.data.len());
322            buffer[..copy_len].copy_from_slice(&packet.data[..copy_len]);
323            Ok(copy_len)
324        } else {
325            Ok(0)
326        }
327    }
328
329    fn write(&mut self, _offset: u64, data: &[u8]) -> Result<usize, KernelError> {
330        // For network devices, writing sends packets
331        let packet = NetworkPacket::new(data.to_vec());
332        self.send_packet(packet)?;
333        Ok(data.len())
334    }
335
336    fn ioctl(&mut self, cmd: u32, _arg: u64) -> Result<u64, KernelError> {
337        match cmd {
338            0x1000 => {
339                // Get interface status
340                Ok(if self.link_up() { 1 } else { 0 })
341            }
342            0x1001 => {
343                // Get link speed
344                Ok(self.link_speed() as u64)
345            }
346            0x1002 => {
347                // Reset statistics
348                self.reset_stats();
349                Ok(0)
350            }
351            _ => Err(KernelError::InvalidArgument {
352                name: "ioctl_cmd",
353                value: "unknown",
354            }),
355        }
356    }
357}
358
359/// Loopback network device
360pub struct LoopbackDriver {
361    name: String,
362    config: Mutex<InterfaceConfig>,
363    stats: Mutex<NetworkStats>,
364    enabled: Mutex<bool>,
365}
366
367impl Default for LoopbackDriver {
368    fn default() -> Self {
369        Self::new()
370    }
371}
372
373impl LoopbackDriver {
374    pub fn new() -> Self {
375        let loopback_mac = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
376        let mut config = InterfaceConfig::new(String::from("lo"), loopback_mac);
377        config.ip_address = Some([127, 0, 0, 1]);
378        config.netmask = Some([255, 0, 0, 0]);
379        config.mtu = 65535; // Loopback can have larger MTU (max for u16)
380
381        Self {
382            name: String::from("loopback"),
383            config: Mutex::new(config),
384            stats: Mutex::new(NetworkStats::default()),
385            enabled: Mutex::new(false),
386        }
387    }
388}
389
390impl NetworkDevice for LoopbackDriver {
391    fn name(&self) -> &str {
392        &self.name
393    }
394
395    fn get_config(&self) -> InterfaceConfig {
396        self.config.lock().clone()
397    }
398
399    fn set_config(&mut self, config: InterfaceConfig) -> Result<(), KernelError> {
400        *self.config.lock() = config;
401        Ok(())
402    }
403
404    fn up(&mut self) -> Result<(), KernelError> {
405        self.config.lock().state = InterfaceState::Up;
406        *self.enabled.lock() = true;
407        crate::println!("[LOOP] Loopback interface is up");
408        Ok(())
409    }
410
411    fn down(&mut self) -> Result<(), KernelError> {
412        self.config.lock().state = InterfaceState::Down;
413        *self.enabled.lock() = false;
414        crate::println!("[LOOP] Loopback interface is down");
415        Ok(())
416    }
417
418    fn send_packet(&mut self, packet: NetworkPacket) -> Result<(), KernelError> {
419        if !*self.enabled.lock() {
420            return Err(KernelError::InvalidState {
421                expected: "up",
422                actual: "down",
423            });
424        }
425
426        // Loopback immediately "receives" what it sends
427        let mut stats = self.stats.lock();
428        stats.tx_packets += 1;
429        stats.tx_bytes += packet.length as u64;
430        stats.rx_packets += 1;
431        stats.rx_bytes += packet.length as u64;
432
433        crate::println!("[LOOP] Looped packet ({} bytes)", packet.length);
434        Ok(())
435    }
436
437    fn receive_packet(&mut self) -> Result<Option<NetworkPacket>, KernelError> {
438        // Loopback doesn't queue packets
439        Ok(None)
440    }
441
442    fn get_stats(&self) -> NetworkStats {
443        self.stats.lock().clone()
444    }
445
446    fn reset_stats(&mut self) {
447        *self.stats.lock() = NetworkStats::default();
448    }
449
450    fn link_up(&self) -> bool {
451        *self.enabled.lock()
452    }
453
454    fn link_speed(&self) -> u32 {
455        u32::MAX // Infinite speed for loopback
456    }
457}
458
459impl Driver for LoopbackDriver {
460    fn name(&self) -> &str {
461        "loopback"
462    }
463
464    fn supported_classes(&self) -> Vec<DeviceClass> {
465        vec![] // Loopback is not a hardware device
466    }
467
468    fn supports_device(&self, _device: &DeviceInfo) -> bool {
469        false // Loopback doesn't attach to hardware
470    }
471
472    fn probe(&mut self, _device: &DeviceInfo) -> Result<(), KernelError> {
473        Err(KernelError::OperationNotSupported {
474            operation: "probe on loopback",
475        })
476    }
477
478    fn attach(&mut self, _device: &DeviceInfo) -> Result<(), KernelError> {
479        Err(KernelError::OperationNotSupported {
480            operation: "attach on loopback",
481        })
482    }
483
484    fn detach(&mut self, _device: &DeviceInfo) -> Result<(), KernelError> {
485        Err(KernelError::OperationNotSupported {
486            operation: "detach on loopback",
487        })
488    }
489
490    fn suspend(&mut self) -> Result<(), KernelError> {
491        self.down()
492    }
493
494    fn resume(&mut self) -> Result<(), KernelError> {
495        self.up()
496    }
497
498    fn handle_interrupt(&mut self, _irq: u8) -> Result<(), KernelError> {
499        Err(KernelError::OperationNotSupported {
500            operation: "interrupt on loopback",
501        })
502    }
503
504    fn read(&mut self, _offset: u64, _buffer: &mut [u8]) -> Result<usize, KernelError> {
505        Ok(0) // No data to read from loopback
506    }
507
508    fn write(&mut self, _offset: u64, data: &[u8]) -> Result<usize, KernelError> {
509        let packet = NetworkPacket::new(data.to_vec());
510        self.send_packet(packet)?;
511        Ok(data.len())
512    }
513
514    fn ioctl(&mut self, cmd: u32, _arg: u64) -> Result<u64, KernelError> {
515        match cmd {
516            0x1000 => Ok(if self.link_up() { 1 } else { 0 }),
517            0x1001 => Ok(self.link_speed() as u64),
518            0x1002 => {
519                self.reset_stats();
520                Ok(0)
521            }
522            _ => Err(KernelError::InvalidArgument {
523                name: "ioctl_cmd",
524                value: "unknown",
525            }),
526        }
527    }
528}
529
530/// Network interface manager
531pub struct NetworkManager {
532    interfaces: RwLock<BTreeMap<String, Arc<Mutex<dyn NetworkDevice>>>>,
533    default_route: RwLock<Option<String>>,
534}
535
536impl Default for NetworkManager {
537    fn default() -> Self {
538        Self::new()
539    }
540}
541
542impl NetworkManager {
543    pub fn new() -> Self {
544        Self {
545            interfaces: RwLock::new(BTreeMap::new()),
546            default_route: RwLock::new(None),
547        }
548    }
549
550    /// Register a network interface
551    pub fn register_interface(
552        &self,
553        name: String,
554        device: Arc<Mutex<dyn NetworkDevice>>,
555    ) -> Result<(), KernelError> {
556        if self.interfaces.read().contains_key(&name) {
557            return Err(KernelError::AlreadyExists {
558                resource: "network interface",
559                id: 0,
560            });
561        }
562
563        self.interfaces.write().insert(name.clone(), device);
564        crate::println!("[NET] Registered interface: {}", name);
565        Ok(())
566    }
567
568    /// Unregister a network interface
569    pub fn unregister_interface(&self, name: &str) -> Result<(), KernelError> {
570        if self.interfaces.write().remove(name).is_some() {
571            crate::println!("[NET] Unregistered interface: {}", name);
572            Ok(())
573        } else {
574            Err(KernelError::NotFound {
575                resource: "network interface",
576                id: 0,
577            })
578        }
579    }
580
581    /// Get interface by name
582    pub fn get_interface(&self, name: &str) -> Option<Arc<Mutex<dyn NetworkDevice>>> {
583        self.interfaces.read().get(name).cloned()
584    }
585
586    /// List all interfaces
587    pub fn list_interfaces(&self) -> Vec<String> {
588        self.interfaces.read().keys().cloned().collect()
589    }
590
591    /// Set default route
592    pub fn set_default_route(&self, interface: String) {
593        *self.default_route.write() = Some(interface);
594        crate::println!("[NET] Set default route to interface");
595    }
596
597    /// Get network statistics for all interfaces
598    pub fn get_global_stats(&self) -> NetworkStats {
599        let mut total_stats = NetworkStats::default();
600
601        for interface in self.interfaces.read().values() {
602            let stats = interface.lock().get_stats();
603            total_stats.rx_packets += stats.rx_packets;
604            total_stats.tx_packets += stats.tx_packets;
605            total_stats.rx_bytes += stats.rx_bytes;
606            total_stats.tx_bytes += stats.tx_bytes;
607            total_stats.rx_errors += stats.rx_errors;
608            total_stats.tx_errors += stats.tx_errors;
609            total_stats.rx_dropped += stats.rx_dropped;
610            total_stats.tx_dropped += stats.tx_dropped;
611            total_stats.collisions += stats.collisions;
612        }
613
614        total_stats
615    }
616}
617
618/// Global network manager instance
619static NETWORK_MANAGER: OnceLock<NetworkManager> = OnceLock::new();
620
621/// Initialize network subsystem
622pub fn init() {
623    let _ = NETWORK_MANAGER.set(NetworkManager::new());
624
625    // Create and register loopback interface
626    let loopback = Arc::new(Mutex::new(LoopbackDriver::new()));
627    get_network_manager()
628        .register_interface(String::from("lo"), loopback.clone())
629        .expect("failed to register loopback interface");
630
631    // Bring up loopback interface
632    loopback
633        .lock()
634        .up()
635        .expect("failed to bring up loopback interface");
636
637    // Register Ethernet driver with driver framework
638    let driver_framework = crate::services::driver_framework::get_driver_framework();
639
640    // Create a dummy Ethernet driver for demonstration
641    let dummy_device = DeviceInfo {
642        id: 0,
643        name: String::from("Dummy Ethernet"),
644        class: DeviceClass::Network,
645        device_id: None,
646        driver: None,
647        bus: String::from("pci"),
648        address: 0,
649        irq: Some(11),
650        dma_channels: Vec::new(),
651        io_ports: Vec::new(),
652        memory_regions: Vec::new(),
653        status: DeviceStatus::Uninitialized,
654    };
655
656    let ethernet_driver = EthernetDriver::new(
657        String::from("eth0"),
658        [0x52, 0x54, 0x00, 0x12, 0x34, 0x56], // Random MAC
659        dummy_device,
660    );
661
662    if let Err(_e) = driver_framework.register_driver(Box::new(ethernet_driver)) {
663        crate::println!("[NET] Failed to register Ethernet driver: {}", _e);
664    }
665
666    crate::println!("[NET] Network subsystem initialized");
667}
668
669/// Check if network manager has been initialized
670pub fn is_network_initialized() -> bool {
671    NETWORK_MANAGER.get().is_some()
672}
673
674/// Get the global network manager
675pub fn get_network_manager() -> &'static NetworkManager {
676    NETWORK_MANAGER
677        .get()
678        .expect("Network manager not initialized")
679}