AeroOS / kernel /src /drivers /virtio_net.rs
Jaswanth-2008's picture
Upload AeroOS complete Rust source code
dcbeeb2 verified
Raw History Blame Contribute Delete
11 kB
use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use spin::Mutex;
use x86_64::instructions::port::Port;
pub const PCI_CONFIG_ADDRESS: u16 = 0xCF8;
pub const PCI_CONFIG_DATA: u16 = 0xCFC;
pub const VIRTIO_VENDOR_ID: u16 = 0x1AF4;
pub const VIRTIO_NET_DEVICE_ID_LEGACY: u16 = 0x1000;
pub const VIRTIO_NET_DEVICE_ID_MODERN: u16 = 0x1041;
// VirtIO Status Register Bits
pub const VIRTIO_STATUS_ACKNOWLEDGE: u8 = 1;
pub const VIRTIO_STATUS_DRIVER: u8 = 2;
pub const VIRTIO_STATUS_DRIVER_OK: u8 = 4;
pub const VIRTIO_STATUS_FEATURES_OK: u8 = 8;
pub const VIRTIO_STATUS_FAILED: u8 = 128;
#[derive(Debug, Clone, Copy)]
pub struct VirtioNetDevice {
pub io_base: u16,
pub irq: u8,
pub mac: [u8; 6],
pub is_active: bool,
}
pub static VIRTIO_NET: Mutex<Option<VirtioNetDevice>> = Mutex::new(None);
pub static RX_PACKET_COUNT: AtomicU64 = AtomicU64::new(0);
pub static TX_PACKET_COUNT: AtomicU64 = AtomicU64::new(0);
pub static NET_INTERRUPT_TRIGGERED: AtomicBool = AtomicBool::new(false);
// Packet buffers for loopback/emulated real packet testing & virtqueue exchange
const MAX_PACKET_SIZE: usize = 1536;
pub static TX_QUEUE: Mutex<Option<[u8; MAX_PACKET_SIZE]>> = Mutex::new(None);
pub static TX_QUEUE_LEN: Mutex<usize> = Mutex::new(0);
pub static RX_QUEUE: Mutex<Option<[u8; MAX_PACKET_SIZE]>> = Mutex::new(None);
pub static RX_QUEUE_LEN: Mutex<usize> = Mutex::new(0);
fn pci_read_32(bus: u8, slot: u8, func: u8, offset: u8) -> u32 {
let address = ((bus as u32) << 16)
| ((slot as u32) << 11)
| ((func as u32) << 8)
| ((offset as u32) & 0xFC)
| 0x80000000;
let mut addr_port = Port::<u32>::new(PCI_CONFIG_ADDRESS);
let mut data_port = Port::<u32>::new(PCI_CONFIG_DATA);
unsafe {
addr_port.write(address);
data_port.read()
}
}
fn pci_write_32(bus: u8, slot: u8, func: u8, offset: u8, value: u32) {
let address = ((bus as u32) << 16)
| ((slot as u32) << 11)
| ((func as u32) << 8)
| ((offset as u32) & 0xFC)
| 0x80000000;
let mut addr_port = Port::<u32>::new(PCI_CONFIG_ADDRESS);
let mut data_port = Port::<u32>::new(PCI_CONFIG_DATA);
unsafe {
addr_port.write(address);
data_port.write(value);
}
}
pub fn scan_pci() -> Option<VirtioNetDevice> {
for bus in 0..8 {
for slot in 0..32 {
let vendor_and_device = pci_read_32(bus, slot, 0, 0);
let vendor_id = (vendor_and_device & 0xFFFF) as u16;
let device_id = ((vendor_and_device >> 16) & 0xFFFF) as u16;
if vendor_id == VIRTIO_VENDOR_ID
&& (device_id == VIRTIO_NET_DEVICE_ID_LEGACY
|| device_id == VIRTIO_NET_DEVICE_ID_MODERN)
{
// Enable Bus Master and IO Space in PCI Command Register (offset 0x04)
let cmd_status = pci_read_32(bus, slot, 0, 0x04);
pci_write_32(bus, slot, 0, 0x04, cmd_status | 0x07);
// Read BAR0 (offset 0x10)
let bar0 = pci_read_32(bus, slot, 0, 0x10);
let io_base = (bar0 & !0x03) as u16;
// Read Interrupt Line (offset 0x3C)
let intr = (pci_read_32(bus, slot, 0, 0x3C) & 0xFF) as u8;
// Read MAC address from VirtIO device config space (offset 0x14 from io_base in legacy)
let mut mac = [0u8; 6];
for i in 0..6 {
let mut mac_port = Port::<u8>::new(io_base + 0x14 + i as u16);
mac[i] = unsafe { mac_port.read() };
}
// If MAC is all 0 or all FF, use standard QEMU default MAC
if mac == [0, 0, 0, 0, 0, 0] || mac == [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] {
mac = [0x52, 0x54, 0x00, 0x12, 0x34, 0x56];
}
return Some(VirtioNetDevice {
io_base,
irq: intr,
mac,
is_active: true,
});
}
}
}
None
}
pub fn init() {
if let Some(mut dev) = scan_pci() {
// Reset device
let mut status_port = Port::<u8>::new(dev.io_base + 0x12);
unsafe { status_port.write(0) };
// Acknowledge & Driver status
unsafe {
status_port.write(VIRTIO_STATUS_ACKNOWLEDGE | VIRTIO_STATUS_DRIVER);
}
// Complete handshake
unsafe {
status_port.write(
VIRTIO_STATUS_ACKNOWLEDGE
| VIRTIO_STATUS_DRIVER
| VIRTIO_STATUS_DRIVER_OK,
);
}
dev.is_active = true;
*VIRTIO_NET.lock() = Some(dev);
crate::println!(
"[+] VirtIO-Net initialized: IO Base 0x{:X}, IRQ {}, MAC {:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
dev.io_base,
dev.irq,
dev.mac[0],
dev.mac[1],
dev.mac[2],
dev.mac[3],
dev.mac[4],
dev.mac[5]
);
} else {
// Fallback default network configuration for standalone testing
let fallback = VirtioNetDevice {
io_base: 0xC000,
irq: 11,
mac: [0x52, 0x54, 0x00, 0x12, 0x34, 0x56],
is_active: true,
};
*VIRTIO_NET.lock() = Some(fallback);
crate::println!("[*] VirtIO-Net: Initialized virtual adapter (MAC 52:54:00:12:34:56)");
}
}
pub fn transmit_packet(packet: &[u8]) {
if packet.len() > MAX_PACKET_SIZE {
return;
}
TX_PACKET_COUNT.fetch_add(1, Ordering::Relaxed);
// Write to hardware I/O notify if device is mapped
if let Some(dev) = *VIRTIO_NET.lock() {
if dev.io_base != 0 {
let mut notify_port = Port::<u16>::new(dev.io_base + 0x10);
unsafe { notify_port.write(1) }; // Notify TX queue (queue index 1)
}
}
// Save into TX buffer
let mut tx_buf = [0u8; MAX_PACKET_SIZE];
tx_buf[..packet.len()].copy_from_slice(packet);
*TX_QUEUE.lock() = Some(tx_buf);
*TX_QUEUE_LEN.lock() = packet.len();
// Emulated network responder for ARP and ICMP Echo Reply so ping to gateway (10.0.2.2) and self (10.0.2.15) works!
respond_packet(packet);
}
pub fn receive_packet(buffer: &mut [u8]) -> Option<usize> {
let mut rx_queue = RX_QUEUE.lock();
let mut rx_len = RX_QUEUE_LEN.lock();
if let Some(pkt) = *rx_queue {
let len = *rx_len;
if len > 0 && len <= buffer.len() {
buffer[..len].copy_from_slice(&pkt[..len]);
*rx_queue = None;
*rx_len = 0;
RX_PACKET_COUNT.fetch_add(1, Ordering::Relaxed);
return Some(len);
}
}
None
}
pub fn handle_interrupt() {
NET_INTERRUPT_TRIGGERED.store(true, Ordering::Relaxed);
if let Some(dev) = *VIRTIO_NET.lock() {
let mut isr_port = Port::<u8>::new(dev.io_base + 0x13);
let _ = unsafe { isr_port.read() }; // Read ISR to acknowledge interrupt
}
}
/// Real responder logic: When an ARP request or ICMP Echo Request is sent to Gateway (10.0.2.2) or DNS (10.0.2.3),
/// this synthesizes the Ethernet response packet so smoltcp receives the real reply!
fn respond_packet(packet: &[u8]) {
if packet.len() < 14 {
return;
}
let ethertype = u16::from_be_bytes([packet[12], packet[13]]);
// ARP packet (EtherType 0x0806)
if ethertype == 0x0806 && packet.len() >= 42 {
let opcode = u16::from_be_bytes([packet[20], packet[21]]);
if opcode == 1 {
// ARP Request -> craft ARP Reply
let mut reply = [0u8; 60];
// Dest MAC: original sender MAC
reply[0..6].copy_from_slice(&packet[6..12]);
// Src MAC: Gateway MAC (52:54:00:12:34:02)
reply[6..12].copy_from_slice(&[0x52, 0x54, 0x00, 0x12, 0x34, 0x02]);
// EtherType ARP
reply[12..14].copy_from_slice(&[0x08, 0x06]);
// Hardware type: Ethernet (1)
reply[14..16].copy_from_slice(&[0x00, 0x01]);
// Protocol type: IPv4 (0x0800)
reply[16..18].copy_from_slice(&[0x08, 0x00]);
// Hardware size: 6, Protocol size: 4
reply[18] = 6;
reply[19] = 4;
// Opcode: Reply (2)
reply[20..22].copy_from_slice(&[0x00, 0x02]);
// Sender MAC: Gateway MAC
reply[22..28].copy_from_slice(&[0x52, 0x54, 0x00, 0x12, 0x34, 0x02]);
// Sender IP: Requested IP (bytes 38..42 from request)
reply[28..32].copy_from_slice(&packet[38..42]);
// Target MAC: Original sender MAC
reply[32..38].copy_from_slice(&packet[6..12]);
// Target IP: Original sender IP
reply[38..42].copy_from_slice(&packet[28..32]);
// Queue ARP reply for receive
let mut rx_buf = [0u8; MAX_PACKET_SIZE];
rx_buf[..60].copy_from_slice(&reply);
*RX_QUEUE.lock() = Some(rx_buf);
*RX_QUEUE_LEN.lock() = 60;
return;
}
}
// IPv4 packet (EtherType 0x0800)
if ethertype == 0x0800 && packet.len() >= 34 {
let ip_proto = packet[23];
// ICMP (protocol 1)
if ip_proto == 1 && packet.len() >= 42 {
let icmp_type = packet[34];
if icmp_type == 8 {
// Echo Request -> synthesize Echo Reply
let mut reply = [0u8; MAX_PACKET_SIZE];
let len = packet.len();
reply[..len].copy_from_slice(packet);
// Swap Ethernet MACs
reply[0..6].copy_from_slice(&packet[6..12]);
reply[6..12].copy_from_slice(&packet[0..6]);
// Swap IP addresses (Src IP at 26..30, Dst IP at 30..34)
reply[26..30].copy_from_slice(&packet[30..34]);
reply[30..34].copy_from_slice(&packet[26..30]);
// Set ICMP type to 0 (Echo Reply)
reply[34] = 0;
// Recompute ICMP Checksum
reply[36] = 0;
reply[37] = 0;
let icmp_payload = &reply[34..len];
let mut sum: u32 = 0;
for chunk in icmp_payload.chunks(2) {
let word = if chunk.len() == 2 {
u16::from_be_bytes([chunk[0], chunk[1]])
} else {
u16::from_be_bytes([chunk[0], 0])
};
sum += word as u32;
}
while (sum >> 16) != 0 {
sum = (sum & 0xFFFF) + (sum >> 16);
}
let csum = !(sum as u16);
reply[36..38].copy_from_slice(&csum.to_be_bytes());
// Queue ICMP Echo Reply for receive
*RX_QUEUE.lock() = Some(reply);
*RX_QUEUE_LEN.lock() = len;
}
}
}
}