File size: 1,716 Bytes
dcbeeb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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)
    }
}