kernel/network/
ethernet_interface.rs

1//!
2//! Ethernet network interface adapter.
3//!
4//! This bridges Ethernet-capable devices into the NetworkManager without
5//! tying the core network stack to a specific device driver implementation.
6
7use alloc::string::String;
8use alloc::sync::Arc;
9use alloc::vec::Vec;
10use spin::Mutex;
11
12use crate::device::network::{DevicePacket, EthernetDevice, MacAddress};
13use crate::network::ipv4::Ipv4Address;
14use crate::network::{InterfaceStats, NetworkInterface};
15
16pub struct EthernetNetworkInterface {
17    name: String,
18    device: Arc<dyn EthernetDevice>,
19    ip_address: Mutex<Option<Ipv4Address>>,
20}
21
22impl EthernetNetworkInterface {
23    pub fn new(name: &str, device: Arc<dyn EthernetDevice>) -> Self {
24        Self {
25            name: String::from(name),
26            device,
27            ip_address: Mutex::new(None),
28        }
29    }
30}
31
32impl NetworkInterface for EthernetNetworkInterface {
33    fn name(&self) -> &str {
34        &self.name
35    }
36
37    fn mac_address(&self) -> MacAddress {
38        self.device.mac_address().unwrap_or(MacAddress::new([0; 6]))
39    }
40
41    fn ip_address(&self) -> Option<Ipv4Address> {
42        *self.ip_address.lock()
43    }
44
45    fn set_ip_address(&self, ip: Ipv4Address) {
46        *self.ip_address.lock() = Some(ip);
47    }
48
49    fn send(&self, packet: DevicePacket) -> Result<(), &'static str> {
50        self.device.send_packet(packet)
51    }
52
53    fn poll(&self) -> Result<Vec<DevicePacket>, &'static str> {
54        self.device.receive_packets()
55    }
56
57    fn stats(&self) -> InterfaceStats {
58        let stats = self.device.get_stats();
59        InterfaceStats {
60            tx_packets: stats.tx_packets,
61            tx_bytes: stats.tx_bytes,
62            rx_packets: stats.rx_packets,
63            rx_bytes: stats.rx_bytes,
64            drops: stats.dropped,
65            errors: stats.rx_errors + stats.tx_errors,
66        }
67    }
68}