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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
//! Virtqueue implementation
use super::VirtIoMmioHeader;
use alloc::{boxed::Box, vec::Vec};
use core::{
    fmt::Debug,
    ptr::{read_volatile, write_volatile},
};
use keos::addressing::{Pa, Va};

/// Command for the virtqueue.
#[derive(Copy, Clone, Debug, PartialEq)]
#[repr(u32)]
pub enum VirtQueueEntryCmd {
    /// Read
    Read = 0,
    /// Write
    Write = 1,
}

/// An entry for the virtqueue.
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct VirtQueueEntry {
    pub addr: Pa,
    pub size: usize,
    pub sector: usize,
    pub cmd: VirtQueueEntryCmd,
}

/// A container for holding virtqueue.
#[repr(C)]
pub struct VirtQueue<T>
where
    T: core::ops::Deref<Target = [VirtQueueEntry]>,
{
    entries: T,
}

impl<T> core::ops::Index<usize> for VirtQueue<T>
where
    T: core::ops::Deref<Target = [VirtQueueEntry]>,
{
    type Output = VirtQueueEntry;

    fn index(&self, index: usize) -> &Self::Output {
        assert!(index < self.entries.len());
        unsafe {
            ((self.entries.as_ptr() as *const _ as usize
                + core::mem::size_of::<VirtQueueEntry>() * index)
                as *const VirtQueueEntry)
                .as_ref()
                .unwrap()
        }
    }
}
impl<T> core::ops::IndexMut<usize> for VirtQueue<T>
where
    T: core::ops::Deref<Target = [VirtQueueEntry]> + core::ops::DerefMut,
{
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        assert!(index < self.entries.len());
        unsafe {
            ((self.entries.as_mut_ptr() as *mut _ as usize
                + core::mem::size_of::<VirtQueueEntry>() * index)
                as *mut VirtQueueEntry)
                .as_mut()
                .unwrap()
        }
    }
}

impl VirtQueue<Box<[VirtQueueEntry]>> {
    /// Create a new virtqueue.
    pub fn new(size: usize) -> Self {
        let entries = (0..size)
            .map(|_| VirtQueueEntry {
                addr: Pa::ZERO,
                size: 0,
                sector: 0,
                cmd: VirtQueueEntryCmd::Read,
            })
            .collect::<Vec<_>>()
            .into_boxed_slice();
        VirtQueue { entries }
    }
    /// Get a virtual address of the virtqueue.
    pub fn virt_queue_ptr(&self) -> usize {
        self.entries.as_ptr() as *const _ as usize
    }
}
impl VirtQueue<&'static [VirtQueueEntry]> {
    /// Get a virtqueue from Va.
    pub unsafe fn new_from_raw_ptr(size: usize, queue_va: Va) -> Self {
        let entries = unsafe {
            core::slice::from_raw_parts(queue_va.into_usize() as *mut VirtQueueEntry, size)
        };

        VirtQueue { entries }
    }
}

impl<T> VirtQueue<T>
where
    T: core::ops::Deref<Target = [VirtQueueEntry]>,
{
    /// Get a fetcher object of the virtqueue.
    pub fn fetcher<'a>(&'a mut self, mmio: &'a mut VirtIoMmioHeader) -> VirtQueueFetcher<T> {
        let head = unsafe { read_volatile(&mmio.queue_head as *const u32) as usize };
        let tail = unsafe { read_volatile(&mmio.queue_tail as *const u32) as usize };
        VirtQueueFetcher {
            inner: self,
            mmio,
            head,
            tail,
        }
    }
}

/// Fetcher object for the virtqueue.
pub struct VirtQueueFetcher<'a, T>
where
    T: core::ops::Deref<Target = [VirtQueueEntry]>,
{
    inner: &'a mut VirtQueue<T>,
    mmio: &'a mut VirtIoMmioHeader,
    head: usize,
    tail: usize,
}

impl<'a, T> VirtQueueFetcher<'a, T>
where
    T: core::ops::Deref<Target = [VirtQueueEntry]>,
{
    fn charge(&self) -> usize {
        (self.head - self.tail) as usize
    }

    fn size(&self) -> usize {
        self.inner.entries.len()
    }

    fn is_empty(&self) -> bool {
        self.head == self.tail
    }

    fn is_full(&self) -> bool {
        self.size() == self.charge()
    }
}

impl<'a> VirtQueueFetcher<'a, &'static [VirtQueueEntry]> {
    /// Pop a single entry to the virtqueue.
    pub fn pop_back(&mut self) -> Option<VirtQueueEntry> {
        if !self.is_empty() {
            let size = self.size();
            let r = self.inner.entries[self.tail];
            self.tail = (self.tail + 1) % size;
            Some(r)
        } else {
            None
        }
    }
    /// Acknowledge the consumed request.
    pub fn ack(self) -> Result<(), ()> {
        // The sequence of the update in this function
        // is really important. Do not change the order.
        unsafe {
            if read_volatile(&mut self.mmio.queue_tail) != self.tail as u32 {
                write_volatile(&mut self.mmio.queue_tail, self.tail as u32);
            }
            // This check is required to verify the change we made into mmio area.
            if read_volatile(&self.mmio.queue_head) == self.head as u32
                && read_volatile(&self.mmio.queue_tail) == self.tail as u32
            {
                if read_volatile(&self.mmio.status) != super::VirtIoStatus::READY as u32 {
                    return Err(());
                }
                Ok(())
            } else {
                Err(())
            }
        }
    }
}

impl<'a> VirtQueueFetcher<'a, Box<[VirtQueueEntry]>> {
    /// Push a single entry to the virtqueue.
    ///
    /// This does not ring the doorbell.
    pub fn push_front(&mut self, value: VirtQueueEntry) -> Result<(), VirtQueueEntry> {
        if !self.is_full() {
            let size = self.size();
            self.inner.entries[self.head] = value;
            self.head = (self.head + 1) % size;
            Ok(())
        } else {
            Err(value)
        }
    }

    /// Kick the doorbell to request commands to the VMM.
    pub fn kick(mut self) -> Result<(), ()> {
        // The sequence of the update in this function
        // is really important. Do not change the order.
        unsafe {
            if read_volatile(&self.mmio.queue_head) != self.head as u32 {
                write_volatile(&mut self.mmio.queue_head, self.head as u32);
                self.tail = read_volatile(&self.mmio.queue_tail) as usize;
            }
            // This check is required to verify the change we made into mmio area.
            if read_volatile(&self.mmio.queue_head) == self.head as u32
                && read_volatile(&self.mmio.queue_tail) == self.tail as u32
            {
                if read_volatile(&self.mmio.status) != super::VirtIoStatus::READY as u32 {
                    return Err(());
                }
                Ok(())
            } else {
                Err(())
            }
        }
    }
}

impl<'a, T> Debug for VirtQueueFetcher<'a, T>
where
    T: core::ops::Deref<Target = [VirtQueueEntry]>,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("VirtQueue")
            .field("size", &self.inner.entries.len())
            .field("head", &self.head)
            .field("tail", &self.tail)
            .finish()
    }
}