AeroOS / kernel /src /net /device.rs
Jaswanth-2008's picture
Upload AeroOS complete Rust source code
dcbeeb2 verified
Raw History Blame Contribute Delete
1.72 kB
use smoltcp::phy::{Device, DeviceCapabilities, Medium, RxToken, TxToken};
use smoltcp::time::Instant;
use crate::drivers::virtio_net;
pub struct VirtioNetPhy {
rx_buffer: [u8; 1536],
}
impl VirtioNetPhy {
pub const fn new() -> Self {
Self {
rx_buffer: [0u8; 1536],
}
}
}
pub struct VirtioRxToken<'a> {
buffer: &'a mut [u8],
}
impl<'a> RxToken for VirtioRxToken<'a> {
fn consume<R, F>(self, f: F) -> R
where
F: FnOnce(&[u8]) -> R,
{
f(self.buffer)
}
}
pub struct VirtioTxToken;
impl TxToken for VirtioTxToken {
fn consume<R, F>(self, len: usize, f: F) -> R
where
F: FnOnce(&mut [u8]) -> R,
{
let mut buffer = [0u8; 1536];
let result = f(&mut buffer[..len]);
virtio_net::transmit_packet(&buffer[..len]);
result
}
}
impl Device for VirtioNetPhy {
type RxToken<'a> = VirtioRxToken<'a> where Self: 'a;
type TxToken<'a> = VirtioTxToken where Self: 'a;
fn capabilities(&self) -> DeviceCapabilities {
let mut caps = DeviceCapabilities::default();
caps.max_transmission_unit = 1500;
caps.medium = Medium::Ethernet;
caps
}
fn receive(&mut self, _timestamp: Instant) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
if let Some(len) = virtio_net::receive_packet(&mut self.rx_buffer) {
Some((
VirtioRxToken {
buffer: &mut self.rx_buffer[..len],
},
VirtioTxToken,
))
} else {
None
}
}
fn transmit(&mut self, _timestamp: Instant) -> Option<Self::TxToken<'_>> {
Some(VirtioTxToken)
}
}