devices/virtio/queue/
split_queue.rs

1// Copyright 2017 The ChromiumOS Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use std::num::Wrapping;
6use std::sync::atomic::fence;
7use std::sync::atomic::AtomicU16;
8use std::sync::atomic::Ordering;
9
10use anyhow::bail;
11use anyhow::Context;
12use anyhow::Result;
13use base::error;
14use base::Event;
15use data_model::Le32;
16use serde::Deserialize;
17use serde::Serialize;
18use snapshot::AnySnapshot;
19use virtio_sys::virtio_ring::VIRTIO_RING_F_EVENT_IDX;
20use vm_memory::GuestAddress;
21use vm_memory::GuestMemory;
22use zerocopy::FromBytes;
23use zerocopy::Immutable;
24use zerocopy::IntoBytes;
25use zerocopy::KnownLayout;
26
27use crate::virtio::queue::validate_queue_area;
28use crate::virtio::DescriptorChain;
29use crate::virtio::Interrupt;
30use crate::virtio::QueueConfig;
31use crate::virtio::SplitDescriptorChain;
32
33#[allow(dead_code)]
34const VIRTQ_USED_F_NO_NOTIFY: u16 = 0x1;
35#[allow(dead_code)]
36const VIRTQ_AVAIL_F_NO_INTERRUPT: u16 = 0x1;
37
38/// An activated virtio queue with split queue layout.
39#[derive(Debug)]
40pub struct SplitQueue {
41    mem: GuestMemory,
42
43    event: Event,
44    interrupt: Interrupt,
45
46    /// The queue size in elements the driver selected. This is always guaranteed to be a power of
47    /// two, as required for split virtqueues.
48    size: u16,
49
50    /// MSI-X vector for the queue. Don't care for INTx
51    vector: u16,
52
53    /// Guest physical address of the descriptor table
54    desc_table: GuestAddress,
55
56    /// Guest physical address of the available ring
57    avail_ring: GuestAddress,
58
59    /// Guest physical address of the used ring
60    used_ring: GuestAddress,
61
62    next_avail: Wrapping<u16>,
63    next_used: Wrapping<u16>,
64
65    // Device feature bits accepted by the driver
66    features: u64,
67    last_used: Wrapping<u16>,
68}
69
70#[derive(Serialize, Deserialize)]
71pub struct SplitQueueSnapshot {
72    size: u16,
73    vector: u16,
74    desc_table: GuestAddress,
75    avail_ring: GuestAddress,
76    used_ring: GuestAddress,
77    next_avail: Wrapping<u16>,
78    next_used: Wrapping<u16>,
79    features: u64,
80    last_used: Wrapping<u16>,
81}
82
83#[repr(C)]
84#[derive(FromBytes, Immutable, IntoBytes, KnownLayout)]
85struct virtq_used_elem {
86    id: Le32,
87    len: Le32,
88}
89
90impl SplitQueue {
91    /// Constructs an activated split virtio queue with the given configuration.
92    pub fn new(
93        config: &QueueConfig,
94        mem: &GuestMemory,
95        event: Event,
96        interrupt: Interrupt,
97    ) -> Result<SplitQueue> {
98        let size = config.size();
99        if !size.is_power_of_two() {
100            bail!("split queue size {size} is not a power of 2");
101        }
102
103        let desc_table = config.desc_table();
104        let avail_ring = config.avail_ring();
105        let used_ring = config.used_ring();
106
107        // Validate addresses and queue size don't overflow and are within guest memory.
108        let ring_sizes = Self::ring_sizes(size, desc_table, avail_ring, used_ring);
109        let rings = ring_sizes.iter().zip([
110            ("descriptor table", 16),
111            ("available ring", 2),
112            ("used ring", 4),
113        ]);
114
115        for ((addr, size), (name, alignment)) in rings {
116            validate_queue_area(mem, *addr, *size, alignment, name)?;
117        }
118
119        // GuestMemory keeps these mappings alive for the lifetime of the queue.
120        Ok(SplitQueue {
121            mem: mem.clone(),
122            event,
123            interrupt,
124            size,
125            vector: config.vector(),
126            desc_table: config.desc_table(),
127            avail_ring: config.avail_ring(),
128            used_ring: config.used_ring(),
129            features: config.acked_features(),
130            next_avail: config.next_avail(),
131            next_used: config.next_used(),
132
133            // WARNING: last_used controls interrupt suppression
134            // (VIRTIO_RING_F_EVENT_IDX). The only safe value initial value is
135            // zero (unless restoring a snapshot and the value that was stored
136            // on the device is known; however we do not bother with that in our
137            // snapshot system since it is much simpler to just use the zero
138            // value and send a potentially spurious interrupt on restore).
139            last_used: Wrapping(0),
140        })
141    }
142
143    pub fn vhost_user_reclaim(&mut self, vring_base: u16) {
144        self.next_avail = Wrapping(vring_base);
145        // The vhost-user spec says:
146        //
147        //     For the Used Ring, the device only needs the next descriptor index at which to put
148        //     new descriptors, which is the value in the vring structure in memory, so this value
149        //     is not covered by this message.
150        //
151        // So, we read the value from guest memory.
152        let used_index_addr = self.used_ring.unchecked_add(2);
153        self.next_used = self
154            .mem
155            .read_obj_from_addr_volatile(used_index_addr)
156            .unwrap();
157
158        // Since the backend has not told us what its actual last_used value
159        // was, we have to assume that an interrupt must be sent when next
160        // available descriptor is used, so we set this to zero.
161        //
162        // But wait, one might ask, why can't we just assume the vhost-user
163        // backend has already sent interrupts for any descriptors it marked
164        // used before it stopped processing the queue? Then we could just
165        // initialize last_used as `last_used == next_used`, which would skip
166        // spurious interrupts and be more efficient. Right?
167        //
168        // If VIRTIO_RING_F_EVENT_IDX is enabled, then no. The reason is the
169        // device could be in an interrupt suppressed state and so it may indeed
170        // have marked some descriptors used, but not yet sent an interrupt for
171        // them. Once we set last_used = next_used, no interrupts will be sent
172        // to the driver until the driver updates next_used (see
173        // queue_wants_interrupt for details), but the driver will
174        // never wake up the device isn't sending any interrupts. Thus, the
175        // device stalls.
176        //
177        // NOTE: this value is not used by the snapshot/restore process, but we
178        // still want to pick a reasonable value here in case it is used in the
179        // future.
180        self.last_used = Wrapping(0);
181    }
182
183    pub fn next_avail_to_process(&self) -> u16 {
184        self.next_avail.0
185    }
186
187    /// Return the actual size of the queue, as the driver may not set up a
188    /// queue as big as the device allows.
189    pub fn size(&self) -> u16 {
190        self.size
191    }
192
193    /// Getter for vector field
194    pub fn vector(&self) -> u16 {
195        self.vector
196    }
197
198    /// Getter for descriptor area
199    pub fn desc_table(&self) -> GuestAddress {
200        self.desc_table
201    }
202
203    /// Getter for driver area
204    pub fn avail_ring(&self) -> GuestAddress {
205        self.avail_ring
206    }
207
208    /// Getter for device area
209    pub fn used_ring(&self) -> GuestAddress {
210        self.used_ring
211    }
212
213    /// Get a reference to the queue's "kick event"
214    pub fn event(&self) -> &Event {
215        &self.event
216    }
217
218    /// Get a reference to the queue's interrupt
219    pub fn interrupt(&self) -> &Interrupt {
220        &self.interrupt
221    }
222
223    // Return `index` modulo the currently configured queue size.
224    fn wrap_queue_index(&self, index: Wrapping<u16>) -> u16 {
225        // We know that `self.size` is a power of two (enforced by `new()`), so the modulus can
226        // be calculated with a bitmask rather than actual division.
227        debug_assert!(self.size.is_power_of_two());
228        index.0 & self.size.wrapping_sub(1)
229    }
230
231    fn ring_sizes(
232        queue_size: u16,
233        desc_table: GuestAddress,
234        avail_ring: GuestAddress,
235        used_ring: GuestAddress,
236    ) -> Vec<(GuestAddress, usize)> {
237        let queue_size = queue_size as usize;
238        vec![
239            (desc_table, 16 * queue_size),
240            (avail_ring, 6 + 2 * queue_size),
241            (used_ring, 6 + 8 * queue_size),
242        ]
243    }
244
245    // Set the `avail_event` field in the used ring.
246    //
247    // This allows the device to inform the driver that driver-to-device notification
248    // (kicking the ring) is not necessary until the driver reaches the `avail_index` descriptor.
249    //
250    // This value is only used if the `VIRTIO_F_EVENT_IDX` feature has been negotiated.
251    fn set_avail_event(&mut self, avail_index: Wrapping<u16>) {
252        fence(Ordering::SeqCst);
253
254        let avail_event_addr = self.used_ring.unchecked_add(4 + 8 * u64::from(self.size));
255        self.mem
256            .write_obj_at_addr_volatile(avail_index.0, avail_event_addr)
257            .unwrap();
258    }
259
260    // Query the value of a single-bit flag in the available ring.
261    //
262    // Returns `true` if `flag` is currently set (by the driver) in the available ring flags.
263    fn get_avail_flag(&self, flag: u16) -> bool {
264        fence(Ordering::SeqCst);
265
266        let avail_flags: u16 = self
267            .mem
268            .read_obj_from_addr_volatile(self.avail_ring)
269            .unwrap();
270
271        avail_flags & flag == flag
272    }
273
274    // Get the `used_event` field in the available ring.
275    //
276    // The returned value is the index of the next descriptor chain entry for which the driver
277    // needs to be notified upon use.  Entries before this index may be used without notifying
278    // the driver.
279    //
280    // This value is only valid if the `VIRTIO_F_EVENT_IDX` feature has been negotiated.
281    fn get_used_event(&self) -> Wrapping<u16> {
282        fence(Ordering::SeqCst);
283
284        let used_event_addr = self.avail_ring.unchecked_add(4 + 2 * u64::from(self.size));
285        let used_event: u16 = self
286            .mem
287            .read_obj_from_addr_volatile(used_event_addr)
288            .unwrap();
289
290        Wrapping(used_event)
291    }
292
293    /// Get the first available descriptor chain without removing it from the queue.
294    /// Call `pop_peeked` to remove the returned descriptor chain from the queue.
295    pub fn peek(&mut self) -> Option<DescriptorChain> {
296        // Get a `VolatileSlice` covering the `struct virtq_avail` fixed header (`flags` and `idx`)
297        // and variable-length `ring`. This ensures that the raw pointers generated below point into
298        // valid `GuestMemory` regions.
299        let avail_ring_size = 2 * size_of::<u16>() + (size_of::<u16>() * usize::from(self.size));
300        let avail_ring_vslice = self
301            .mem
302            .get_slice_at_addr(self.avail_ring, avail_ring_size)
303            .unwrap();
304
305        // SAFETY: offset of `virtq_avail.idx` (2) is always within the `VolatileSlice` bounds.
306        let avail_index_ptr = unsafe { avail_ring_vslice.as_mut_ptr().add(2) } as *mut u16;
307        // SAFETY: `GuestMemory::get_slice_at_addr()` returns a valid `VolatileSlice`, and
308        // `avail_index_ptr` is a valid `*mut u16` contained within that slice.
309        let avail_index_atomic = unsafe { AtomicU16::from_ptr(avail_index_ptr) };
310
311        // Check if the driver has published any new descriptors beyond `self.next_avail`. This uses
312        // a `Relaxed` load because we do not need a memory barrier if there are no new descriptors.
313        // If the ring is not empty, the `fence()` below will provide the necessary ordering,
314        // pairing with the write memory barrier in the driver.
315        let avail_index: u16 = avail_index_atomic.load(Ordering::Relaxed);
316        let next_avail = self.next_avail;
317        if next_avail.0 == avail_index {
318            return None;
319        }
320
321        // This fence ensures that subsequent reads from the descriptor do not
322        // get reordered and happen only after fetching the available_index and
323        // checking that there is a slot available.
324        fence(Ordering::Acquire);
325
326        // Calculate the offset of `ring[next_avail % size]` within `struct virtq_avail`.
327        let ring_offset = 4 + (usize::from(self.wrap_queue_index(next_avail)) * 2);
328        debug_assert!(ring_offset + size_of::<u16>() <= avail_ring_size);
329        // SAFETY: The available ring index was wrapped to fall within the queue size above, so
330        // `ring_offset` is always in bounds.
331        let ring_ptr = unsafe { avail_ring_vslice.as_ptr().add(ring_offset) } as *const u16;
332        // SAFETY: `ring_ptr` is a valid `*const u16` within `avail_ring_vslice`.
333        let descriptor_index: u16 = unsafe { std::ptr::read_volatile(ring_ptr) };
334
335        let chain = SplitDescriptorChain::new(self.desc_table, self.size, descriptor_index);
336        DescriptorChain::new(chain, &self.mem, descriptor_index)
337            .map_err(|e| {
338                error!("{:#}", e);
339                e
340            })
341            .ok()
342    }
343
344    /// Remove the first available descriptor chain from the queue.
345    /// This function should only be called immediately following `peek` and must be passed a
346    /// reference to the same `DescriptorChain` returned by the most recent `peek`.
347    pub(super) fn pop_peeked(&mut self, _descriptor_chain: &DescriptorChain) {
348        self.next_avail += Wrapping(1);
349        if self.features & ((1u64) << VIRTIO_RING_F_EVENT_IDX) != 0 {
350            self.set_avail_event(self.next_avail);
351        }
352    }
353
354    pub(super) fn try_pop_length(&mut self, length: usize) -> Option<Vec<DescriptorChain>> {
355        let mut remain_len = length;
356        let mut descriptors = vec![];
357        while remain_len > 0 {
358            match self.peek() {
359                Some(desc) => {
360                    let available_bytes = desc.writer.available_bytes();
361                    descriptors.push(desc);
362                    self.next_avail += Wrapping(1);
363                    if available_bytes >= remain_len {
364                        if self.features & ((1u64) << VIRTIO_RING_F_EVENT_IDX) != 0 {
365                            self.set_avail_event(self.next_avail);
366                        }
367                        return Some(descriptors);
368                    } else {
369                        remain_len -= available_bytes;
370                    }
371                }
372                None => {
373                    if self.features & ((1u64) << VIRTIO_RING_F_EVENT_IDX) != 0 {
374                        self.set_avail_event(self.next_avail);
375                    }
376                    // Reverse the effect of pop
377                    self.next_avail -= Wrapping(descriptors.len() as u16);
378                    return None;
379                }
380            }
381        }
382        None
383    }
384
385    /// Puts multiple available descriptor heads into the used ring for use by the guest.
386    pub fn add_used_with_bytes_written_batch(
387        &mut self,
388        desc_chains: impl IntoIterator<Item = (DescriptorChain, u32)>,
389    ) {
390        // Get a `VolatileSlice` covering the `struct virtq_used` fixed header (`flags` and `idx`)
391        // and variable-length `ring`. This ensures that the raw pointers generated below point into
392        // valid `GuestMemory` regions.
393        let used_ring_size =
394            2 * size_of::<u16>() + (size_of::<virtq_used_elem>() * usize::from(self.size));
395        let used_ring_vslice = self
396            .mem
397            .get_slice_at_addr(self.used_ring, used_ring_size)
398            .unwrap();
399
400        // SAFETY: `elems_ptr` is always a valid pointer due to `used_ring_vslice()`.
401        let elems_ptr = unsafe { used_ring_vslice.as_mut_ptr().add(4) } as *mut virtq_used_elem;
402
403        // SAFETY: `used_index_ptr` is always a valid pointer due to `used_ring_vslice()`.
404        let used_index_ptr = unsafe { used_ring_vslice.as_mut_ptr().add(2) } as *mut u16;
405
406        // SAFETY: `used_index_ptr` is always a valid pointer
407        let used_index_atomic = unsafe { AtomicU16::from_ptr(used_index_ptr) };
408
409        let mut next_used = self.next_used;
410        for (desc_chain, len) in desc_chains {
411            let desc_index = desc_chain.index();
412            debug_assert!(desc_index < self.size);
413            let id = Le32::from(u32::from(desc_index));
414            let len = Le32::from(len);
415
416            let wrapped_index = usize::from(self.wrap_queue_index(next_used));
417            // SAFETY: `wrapped_index` is always in bounds due to `wrap_queue_index()`.
418            let elem_ptr = unsafe { elems_ptr.add(wrapped_index) };
419
420            // SAFETY: `elem_ptr` is always a valid pointer
421            unsafe {
422                std::ptr::write_volatile(std::ptr::addr_of_mut!((*elem_ptr).id), id);
423                std::ptr::write_volatile(std::ptr::addr_of_mut!((*elem_ptr).len), len);
424            };
425
426            next_used += Wrapping(1);
427        }
428
429        if next_used != self.next_used {
430            fence(Ordering::Release);
431            used_index_atomic.store(next_used.0, Ordering::Relaxed);
432            self.next_used = next_used;
433        }
434    }
435
436    /// Returns if the queue should have an interrupt sent based on its state.
437    ///
438    /// This function implements `VIRTIO_RING_F_EVENT_IDX`, otherwise known as
439    /// interrupt suppression. The virtio spec provides the driver with a field,
440    /// `used_event`, which says that once we write that descriptor (or several
441    /// in the case of a flurry of `add_used` calls), we should send a
442    /// notification. Because the values involved wrap around `u16::MAX`, and to
443    /// avoid checking the condition on every `add_used` call, the math is a
444    /// little complicated.
445    ///
446    /// The critical inequality is:
447    /// ```text
448    ///      (next_used - 1) - used_event < next_used - last_used
449    /// ```
450    ///
451    /// For illustration purposes, we label it as `A < B`, where
452    /// `A = (next_used -1) - used_event`, and `B = next_used - last_used`.
453    ///
454    /// `A` and `B` represent two distances, measured in a wrapping ring of size
455    /// `u16::MAX`. In the "send intr" case, the inequality is true. In the
456    /// "don't send intr" case, the inequality is false. We must be very careful
457    /// in assigning a direction to the ring, so that when we
458    /// graph the subtraction operations, we are measuring the right distance
459    /// (similar to how DC circuits are analyzed).
460    ///
461    /// The two distances are as follows:
462    ///  * `A` is the distance between the driver's requested notification point, and the current
463    ///    position in the ring.
464    ///
465    ///  * `B` is the distance between the last time we notified the guest, and the current position
466    ///    in the ring.
467    ///
468    /// If we graph these distances for the situation where we want to notify
469    /// the guest, and when we don't want to notify the guest, we see that
470    /// `A < B` becomes true the moment `next_used - 1` passes `used_event`. See
471    /// the graphs at the bottom of this comment block for a more visual
472    /// explanation.
473    ///
474    /// Once an interrupt is sent, we have a final useful property: last_used
475    /// moves up next_used, which causes the inequality to be false. Thus, we
476    /// won't send notifications again until `used_event` is moved forward by
477    /// the driver.
478    ///
479    /// Finally, let's talk about a couple of ways to write this inequality
480    /// that don't work, and critically, explain *why*.
481    ///
482    /// First, a naive reading of the virtio spec might lead us to ask: why not
483    /// just use the following inequality:
484    /// ```text
485    ///      next_used - 1 >= used_event
486    /// ```
487    ///
488    /// because that's much simpler, right? The trouble is that the ring wraps,
489    /// so it could be that a smaller index is actually ahead of a larger one.
490    /// That's why we have to use distances in the ring instead.
491    ///
492    /// Second, one might look at the correct inequality:
493    /// ```text
494    ///      (next_used - 1) - used_event < next_used - last_used
495    /// ```
496    ///
497    /// And try to simplify it to:
498    /// ```text
499    ///      last_used - 1 < used_event
500    /// ```
501    ///
502    /// Functionally, this won't work because next_used isn't present at all
503    /// anymore. (Notifications will never be sent.) But why is that? The algebra
504    /// here *appears* to work out, but all semantic meaning is lost. There are
505    /// two explanations for why this happens:
506    /// * The intuitive one: the terms in the inequality are not actually separable; in other words,
507    ///   (next_used - last_used) is an inseparable term, so subtracting next_used from both sides
508    ///   of the original inequality and zeroing them out is semantically invalid. But why aren't
509    ///   they separable? See below.
510    /// * The theoretical one: canceling like terms relies a vector space law: a + x = b + x => a =
511    ///   b (cancellation law). For congruences / equality under modulo, this law is satisfied, but
512    ///   for inequalities under mod, it is not; therefore, we cannot cancel like terms.
513    ///
514    /// ```text
515    /// ┌──────────────────────────────────┐
516    /// │                                  │
517    /// │                                  │
518    /// │                                  │
519    /// │           ┌────────────  next_used - 1
520    /// │           │A                   x
521    /// │           │       ┌────────────x────────────┐
522    /// │           │       │            x            │
523    /// │           │       │                         │
524    /// │           │       │               │         │
525    /// │           │       │               │         │
526    /// │     used_event  xxxx        + ◄───┘       xxxxx last_used
527    /// │                   │                         │      │
528    /// │                   │        Send intr        │      │
529    /// │                   │                         │      │
530    /// │                   └─────────────────────────┘      │
531    /// │                                                    │
532    /// │ B                                                  │
533    /// └────────────────────────────────────────────────────┘
534    ///
535    ///             ┌───────────────────────────────────────────────────┐
536    ///             │                                                 A │
537    ///             │       ┌────────────────────────┐                  │
538    ///             │       │                        │                  │
539    ///             │       │                        │                  │
540    ///             │       │              │         │                  │
541    ///             │       │              │         │                  │
542    ///       used_event  xxxx             │       xxxxx last_used      │
543    ///                     │        + ◄───┘         │       │          │
544    ///                     │                        │       │          │
545    ///                     │     Don't send intr    │       │          │
546    ///                     │                        │       │          │
547    ///                     └───────────x────────────┘       │          │
548    ///                                 x                    │          │
549    ///                              next_used - 1           │          │
550    ///                              │  │                  B │          │
551    ///                              │  └────────────────────┘          │
552    ///                              │                                  │
553    ///                              └──────────────────────────────────┘
554    /// ```
555    fn queue_wants_interrupt(&self) -> bool {
556        if self.features & ((1u64) << VIRTIO_RING_F_EVENT_IDX) != 0 {
557            let used_event = self.get_used_event();
558            self.next_used - used_event - Wrapping(1) < self.next_used - self.last_used
559        } else {
560            !self.get_avail_flag(VIRTQ_AVAIL_F_NO_INTERRUPT)
561        }
562    }
563
564    /// inject interrupt into guest on this queue
565    /// return true: interrupt is injected into guest for this queue
566    ///        false: interrupt isn't injected
567    pub fn trigger_interrupt(&mut self) -> bool {
568        if self.queue_wants_interrupt() {
569            self.last_used = self.next_used;
570            self.interrupt.signal_used_queue(self.vector);
571            true
572        } else {
573            false
574        }
575    }
576
577    pub fn snapshot(&self) -> anyhow::Result<AnySnapshot> {
578        AnySnapshot::to_any(SplitQueueSnapshot {
579            size: self.size,
580            vector: self.vector,
581            desc_table: self.desc_table,
582            avail_ring: self.avail_ring,
583            used_ring: self.used_ring,
584            next_avail: self.next_avail,
585            next_used: self.next_used,
586            features: self.features,
587            last_used: self.last_used,
588        })
589        .context("failed to serialize MsixConfigSnapshot")
590    }
591
592    pub fn restore(
593        queue_value: AnySnapshot,
594        mem: &GuestMemory,
595        event: Event,
596        interrupt: Interrupt,
597    ) -> anyhow::Result<SplitQueue> {
598        let s: SplitQueueSnapshot = AnySnapshot::from_any(queue_value)?;
599        let queue = SplitQueue {
600            mem: mem.clone(),
601            event,
602            interrupt,
603            size: s.size,
604            vector: s.vector,
605            desc_table: s.desc_table,
606            avail_ring: s.avail_ring,
607            used_ring: s.used_ring,
608            next_avail: s.next_avail,
609            next_used: s.next_used,
610            features: s.features,
611            last_used: s.last_used,
612        };
613        Ok(queue)
614    }
615}
616
617#[cfg(test)]
618mod tests {
619    use std::convert::TryInto;
620    use std::mem::offset_of;
621
622    use data_model::Le16;
623    use data_model::Le32;
624    use data_model::Le64;
625    use zerocopy::FromBytes;
626    use zerocopy::Immutable;
627    use zerocopy::IntoBytes;
628    use zerocopy::KnownLayout;
629
630    use super::*;
631    use crate::virtio::create_descriptor_chain;
632    use crate::virtio::Desc;
633    use crate::virtio::Interrupt;
634    use crate::virtio::Queue;
635
636    const GUEST_MEMORY_SIZE: u64 = 0x10000;
637    const DESC_OFFSET: u64 = 0;
638    const AVAIL_OFFSET: u64 = 0x200;
639    const USED_OFFSET: u64 = 0x400;
640    const QUEUE_SIZE: usize = 0x10;
641    const BUFFER_OFFSET: u64 = 0x8000;
642    const BUFFER_LEN: u32 = 0x400;
643
644    #[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)]
645    #[repr(C)]
646    struct Avail {
647        flags: Le16,
648        idx: Le16,
649        ring: [Le16; QUEUE_SIZE],
650        used_event: Le16,
651    }
652
653    impl Default for Avail {
654        fn default() -> Self {
655            Avail {
656                flags: Le16::from(0u16),
657                idx: Le16::from(0u16),
658                ring: [Le16::from(0u16); QUEUE_SIZE],
659                used_event: Le16::from(0u16),
660            }
661        }
662    }
663
664    #[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)]
665    #[repr(C)]
666    struct UsedElem {
667        id: Le32,
668        len: Le32,
669    }
670
671    impl Default for UsedElem {
672        fn default() -> Self {
673            UsedElem {
674                id: Le32::from(0u32),
675                len: Le32::from(0u32),
676            }
677        }
678    }
679
680    #[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)]
681    #[repr(C, packed)]
682    struct Used {
683        flags: Le16,
684        idx: Le16,
685        used_elem_ring: [UsedElem; QUEUE_SIZE],
686        avail_event: Le16,
687    }
688
689    impl Default for Used {
690        fn default() -> Self {
691            Used {
692                flags: Le16::from(0u16),
693                idx: Le16::from(0u16),
694                used_elem_ring: [UsedElem::default(); QUEUE_SIZE],
695                avail_event: Le16::from(0u16),
696            }
697        }
698    }
699
700    fn setup_vq(queue: &mut QueueConfig, mem: &GuestMemory) -> Queue {
701        let desc = Desc {
702            addr: Le64::from(BUFFER_OFFSET),
703            len: Le32::from(BUFFER_LEN),
704            flags: Le16::from(0u16),
705            next: Le16::from(1u16),
706        };
707        let _ = mem.write_obj_at_addr(desc, GuestAddress(DESC_OFFSET));
708
709        let avail = Avail::default();
710        let _ = mem.write_obj_at_addr(avail, GuestAddress(AVAIL_OFFSET));
711
712        let used = Used::default();
713        let _ = mem.write_obj_at_addr(used, GuestAddress(USED_OFFSET));
714
715        queue.set_desc_table(GuestAddress(DESC_OFFSET));
716        queue.set_avail_ring(GuestAddress(AVAIL_OFFSET));
717        queue.set_used_ring(GuestAddress(USED_OFFSET));
718        queue.ack_features((1u64) << VIRTIO_RING_F_EVENT_IDX);
719        queue.set_ready(true);
720
721        queue
722            .activate(mem, Event::new().unwrap(), Interrupt::new_for_test())
723            .expect("QueueConfig::activate failed")
724    }
725
726    fn fake_desc_chain(mem: &GuestMemory) -> DescriptorChain {
727        create_descriptor_chain(mem, GuestAddress(0), GuestAddress(0), Vec::new(), 0)
728            .expect("failed to create descriptor chain")
729    }
730
731    #[test]
732    fn rejects_unaligned_rings() {
733        let mem = GuestMemory::new(&[(GuestAddress(0), GUEST_MEMORY_SIZE)]).unwrap();
734        let rings = [
735            (
736                QueueConfig::set_desc_table as fn(&mut QueueConfig, GuestAddress),
737                "descriptor table",
738                DESC_OFFSET + 8,
739            ),
740            (
741                QueueConfig::set_avail_ring,
742                "available ring",
743                AVAIL_OFFSET + 1,
744            ),
745            (QueueConfig::set_used_ring, "used ring", USED_OFFSET + 2),
746        ];
747        for (set_addr, name, addr) in rings {
748            let mut config = QueueConfig::new(QUEUE_SIZE as u16, 0);
749            config.set_desc_table(GuestAddress(DESC_OFFSET));
750            config.set_avail_ring(GuestAddress(AVAIL_OFFSET));
751            config.set_used_ring(GuestAddress(USED_OFFSET));
752            set_addr(&mut config, GuestAddress(addr));
753            config.set_ready(true);
754
755            let err = config
756                .activate(&mem, Event::new().unwrap(), Interrupt::new_for_test())
757                .unwrap_err();
758            let msg = format!("{err:#}");
759            assert!(msg.contains(&format!("{name} is not aligned")), "{msg}");
760        }
761    }
762
763    #[test]
764    fn rejects_rings_outside_guest_memory() {
765        let mem = GuestMemory::new(&[(GuestAddress(0), GUEST_MEMORY_SIZE)]).unwrap();
766        let rings = [
767            (
768                QueueConfig::set_desc_table as fn(&mut QueueConfig, GuestAddress),
769                "descriptor table",
770                16,
771            ),
772            (
773                QueueConfig::set_avail_ring,
774                "available ring",
775                4 + 2 * QUEUE_SIZE,
776            ),
777            (QueueConfig::set_used_ring, "used ring", 4 + 8 * QUEUE_SIZE),
778        ];
779        for (set_addr, name, partial_size) in rings {
780            // Cover fully unmapped rings and ones whose end is outside RAM. For
781            // the available and used rings, only the event index is outside RAM.
782            for addr in [GUEST_MEMORY_SIZE, GUEST_MEMORY_SIZE - partial_size as u64] {
783                let mut config = QueueConfig::new(QUEUE_SIZE as u16, 0);
784                config.set_desc_table(GuestAddress(DESC_OFFSET));
785                config.set_avail_ring(GuestAddress(AVAIL_OFFSET));
786                config.set_used_ring(GuestAddress(USED_OFFSET));
787                set_addr(&mut config, GuestAddress(addr));
788                config.set_ready(true);
789
790                let err = config
791                    .activate(&mem, Event::new().unwrap(), Interrupt::new_for_test())
792                    .unwrap_err();
793                let msg = format!("{err:#}");
794                assert!(
795                    msg.contains(&format!("{name} is not in guest memory")),
796                    "{msg}"
797                );
798            }
799        }
800    }
801
802    #[test]
803    fn queue_event_id_guest_fast() {
804        let mut queue =
805            QueueConfig::new(QUEUE_SIZE.try_into().unwrap(), 1 << VIRTIO_RING_F_EVENT_IDX);
806        let memory_start_addr = GuestAddress(0x0);
807        let mem = GuestMemory::new(&[(memory_start_addr, GUEST_MEMORY_SIZE)]).unwrap();
808        let mut queue = setup_vq(&mut queue, &mem);
809
810        // Offset of used_event within Avail structure
811        let used_event_offset = offset_of!(Avail, used_event) as u64;
812        let used_event_address = GuestAddress(AVAIL_OFFSET + used_event_offset);
813
814        // Assume driver submit 0x100 req to device,
815        // device has handled them, so increase self.next_used to 0x100
816        let mut device_generate: Wrapping<u16> = Wrapping(0x100);
817        for _ in 0..device_generate.0 {
818            queue.add_used_with_bytes_written(fake_desc_chain(&mem), BUFFER_LEN);
819        }
820
821        // At this moment driver hasn't handled any interrupts yet, so it
822        // should inject interrupt.
823        assert_eq!(queue.trigger_interrupt(), true);
824
825        // Driver handle all the interrupts and update avail.used_event to 0x100
826        let mut driver_handled = device_generate;
827        let _ = mem.write_obj_at_addr(Le16::from(driver_handled.0), used_event_address);
828
829        // At this moment driver have handled all the interrupts, and
830        // device doesn't generate more data, so interrupt isn't needed.
831        assert_eq!(queue.trigger_interrupt(), false);
832
833        // Assume driver submit another u16::MAX - 0x100 req to device,
834        // Device has handled all of them, so increase self.next_used to u16::MAX
835        for _ in device_generate.0..u16::MAX {
836            queue.add_used_with_bytes_written(fake_desc_chain(&mem), BUFFER_LEN);
837        }
838        device_generate = Wrapping(u16::MAX);
839
840        // At this moment driver just handled 0x100 interrupts, so it
841        // should inject interrupt.
842        assert_eq!(queue.trigger_interrupt(), true);
843
844        // driver handle all the interrupts and update avail.used_event to u16::MAX
845        driver_handled = device_generate;
846        let _ = mem.write_obj_at_addr(Le16::from(driver_handled.0), used_event_address);
847
848        // At this moment driver have handled all the interrupts, and
849        // device doesn't generate more data, so interrupt isn't needed.
850        assert_eq!(queue.trigger_interrupt(), false);
851
852        // Assume driver submit another 1 request,
853        // device has handled it, so wrap self.next_used to 0
854        queue.add_used_with_bytes_written(fake_desc_chain(&mem), BUFFER_LEN);
855        device_generate += Wrapping(1);
856
857        // At this moment driver has handled all the previous interrupts, so it
858        // should inject interrupt again.
859        assert_eq!(queue.trigger_interrupt(), true);
860
861        // driver handle that interrupts and update avail.used_event to 0
862        driver_handled = device_generate;
863        let _ = mem.write_obj_at_addr(Le16::from(driver_handled.0), used_event_address);
864
865        // At this moment driver have handled all the interrupts, and
866        // device doesn't generate more data, so interrupt isn't needed.
867        assert_eq!(queue.trigger_interrupt(), false);
868    }
869
870    #[test]
871    fn queue_event_id_guest_slow() {
872        let mut queue =
873            QueueConfig::new(QUEUE_SIZE.try_into().unwrap(), 1 << VIRTIO_RING_F_EVENT_IDX);
874        let memory_start_addr = GuestAddress(0x0);
875        let mem = GuestMemory::new(&[(memory_start_addr, GUEST_MEMORY_SIZE)]).unwrap();
876        let mut queue = setup_vq(&mut queue, &mem);
877
878        // Offset of used_event within Avail structure
879        let used_event_offset = offset_of!(Avail, used_event) as u64;
880        let used_event_address = GuestAddress(AVAIL_OFFSET + used_event_offset);
881
882        // Assume driver submit 0x100 req to device,
883        // device have handled 0x100 req, so increase self.next_used to 0x100
884        let mut device_generate: Wrapping<u16> = Wrapping(0x100);
885        for _ in 0..device_generate.0 {
886            queue.add_used_with_bytes_written(fake_desc_chain(&mem), BUFFER_LEN);
887        }
888
889        // At this moment driver hasn't handled any interrupts yet, so it
890        // should inject interrupt.
891        assert_eq!(queue.trigger_interrupt(), true);
892
893        // Driver handle part of the interrupts and update avail.used_event to 0x80
894        let mut driver_handled = Wrapping(0x80);
895        let _ = mem.write_obj_at_addr(Le16::from(driver_handled.0), used_event_address);
896
897        // At this moment driver hasn't finished last interrupt yet,
898        // so interrupt isn't needed.
899        assert_eq!(queue.trigger_interrupt(), false);
900
901        // Assume driver submit another 1 request,
902        // device has handled it, so increment self.next_used.
903        queue.add_used_with_bytes_written(fake_desc_chain(&mem), BUFFER_LEN);
904        device_generate += Wrapping(1);
905
906        // At this moment driver hasn't finished last interrupt yet,
907        // so interrupt isn't needed.
908        assert_eq!(queue.trigger_interrupt(), false);
909
910        // Assume driver submit another u16::MAX - 0x101 req to device,
911        // Device has handled all of them, so increase self.next_used to u16::MAX
912        for _ in device_generate.0..u16::MAX {
913            queue.add_used_with_bytes_written(fake_desc_chain(&mem), BUFFER_LEN);
914        }
915        device_generate = Wrapping(u16::MAX);
916
917        // At this moment driver hasn't finished last interrupt yet,
918        // so interrupt isn't needed.
919        assert_eq!(queue.trigger_interrupt(), false);
920
921        // driver handle most of the interrupts and update avail.used_event to u16::MAX - 1,
922        driver_handled = device_generate - Wrapping(1);
923        let _ = mem.write_obj_at_addr(Le16::from(driver_handled.0), used_event_address);
924
925        // Assume driver submit another 1 request,
926        // device has handled it, so wrap self.next_used to 0
927        queue.add_used_with_bytes_written(fake_desc_chain(&mem), BUFFER_LEN);
928        device_generate += Wrapping(1);
929
930        // At this moment driver has already finished the last interrupt(0x100),
931        // and device service other request, so new interrupt is needed.
932        assert_eq!(queue.trigger_interrupt(), true);
933
934        // Assume driver submit another 1 request,
935        // device has handled it, so increment self.next_used to 1
936        queue.add_used_with_bytes_written(fake_desc_chain(&mem), BUFFER_LEN);
937        device_generate += Wrapping(1);
938
939        // At this moment driver hasn't finished last interrupt((Wrapping(0)) yet,
940        // so interrupt isn't needed.
941        assert_eq!(queue.trigger_interrupt(), false);
942
943        // driver handle all the remain interrupts and wrap avail.used_event to 0x1.
944        driver_handled = device_generate;
945        let _ = mem.write_obj_at_addr(Le16::from(driver_handled.0), used_event_address);
946
947        // At this moment driver has handled all the interrupts, and
948        // device doesn't generate more data, so interrupt isn't needed.
949        assert_eq!(queue.trigger_interrupt(), false);
950
951        // Assume driver submit another 1 request,
952        // device has handled it, so increase self.next_used.
953        queue.add_used_with_bytes_written(fake_desc_chain(&mem), BUFFER_LEN);
954        device_generate += Wrapping(1);
955
956        // At this moment driver has finished all the previous interrupts, so it
957        // should inject interrupt again.
958        assert_eq!(queue.trigger_interrupt(), true);
959    }
960}