devices/virtio/
queue.rs

1// Copyright 2023 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
5//! virtqueue interface
6
7#![deny(missing_docs)]
8
9use std::ops::Deref;
10use std::ops::DerefMut;
11
12pub mod packed_descriptor_chain;
13mod packed_queue;
14pub mod split_descriptor_chain;
15mod split_queue;
16
17use std::num::Wrapping;
18
19use anyhow::bail;
20use anyhow::Context;
21use anyhow::Result;
22use base::warn;
23use base::Event;
24use cros_async::AsyncError;
25use cros_async::EventAsync;
26use futures::channel::oneshot;
27use futures::select_biased;
28use futures::FutureExt;
29use packed_queue::PackedQueue;
30use serde::Deserialize;
31use serde::Serialize;
32use snapshot::AnySnapshot;
33use split_queue::SplitQueue;
34use virtio_sys::virtio_config::VIRTIO_F_RING_PACKED;
35use vm_memory::GuestAddress;
36use vm_memory::GuestMemory;
37
38use crate::virtio::DescriptorChain;
39use crate::virtio::Interrupt;
40use crate::virtio::VIRTIO_MSI_NO_VECTOR;
41
42fn validate_queue_area(
43    mem: &GuestMemory,
44    addr: GuestAddress,
45    size: usize,
46    alignment: u64,
47    name: &str,
48) -> Result<()> {
49    if addr.offset() % alignment != 0 {
50        bail!(
51            "virtio queue {} is not aligned to {} bytes: start:0x{:08x}",
52            name,
53            alignment,
54            addr.offset(),
55        );
56    }
57    if !mem.is_valid_range(addr, size as u64) {
58        bail!(
59            "virtio queue {} is not in guest memory: start:0x{:08x} size:0x{:08x}",
60            name,
61            addr.offset(),
62            size,
63        );
64    }
65    Ok(())
66}
67
68/// A virtio queue's parameters.
69///
70/// `QueueConfig` can be converted into a running `Queue` by calling [`QueueConfig::activate()`].
71pub struct QueueConfig {
72    /// Whether this queue has already been activated.
73    activated: bool,
74
75    /// The maximal size in elements offered by the device
76    max_size: u16,
77
78    /// The queue size in elements the driver selected. This is always guaranteed to be a power of
79    /// two less than or equal to `max_size`, as required for split virtqueues. These invariants
80    /// are enforced by `set_size()`.
81    size: u16,
82
83    /// Indicates if the queue is finished with configuration
84    ready: bool,
85
86    /// MSI-X vector for the queue. Don't care for INTx
87    vector: u16,
88
89    /// Ring features (e.g. `VIRTIO_RING_F_EVENT_IDX`, `VIRTIO_F_RING_PACKED`) offered by the
90    /// device
91    features: u64,
92
93    // Device feature bits accepted by the driver
94    acked_features: u64,
95
96    /// Guest physical address of the descriptor table
97    desc_table: GuestAddress,
98
99    /// Guest physical address of the available ring (driver area)
100    ///
101    /// TODO(b/290657008): update field and accessor names to match the current virtio spec
102    avail_ring: GuestAddress,
103
104    /// Guest physical address of the used ring (device area)
105    used_ring: GuestAddress,
106
107    /// Initial available ring index when the queue is activated.
108    next_avail: Wrapping<u16>,
109
110    /// Initial used ring index when the queue is activated.
111    next_used: Wrapping<u16>,
112}
113
114#[derive(Serialize, Deserialize)]
115struct QueueConfigSnapshot {
116    activated: bool,
117    max_size: u16,
118    size: u16,
119    ready: bool,
120    vector: u16,
121    features: u64,
122    acked_features: u64,
123    desc_table: GuestAddress,
124    avail_ring: GuestAddress,
125    used_ring: GuestAddress,
126    next_avail: Wrapping<u16>,
127    next_used: Wrapping<u16>,
128}
129
130impl QueueConfig {
131    /// Constructs a virtio queue configuration with the given `max_size`.
132    pub fn new(max_size: u16, features: u64) -> Self {
133        assert!(max_size > 0);
134        assert!(max_size <= Queue::MAX_SIZE);
135        QueueConfig {
136            activated: false,
137            max_size,
138            size: max_size,
139            ready: false,
140            vector: VIRTIO_MSI_NO_VECTOR,
141            desc_table: GuestAddress(0),
142            avail_ring: GuestAddress(0),
143            used_ring: GuestAddress(0),
144            features,
145            acked_features: 0,
146            next_used: Wrapping(0),
147            next_avail: Wrapping(0),
148        }
149    }
150
151    /// Returns the maximum size of this queue.
152    pub fn max_size(&self) -> u16 {
153        self.max_size
154    }
155
156    /// Returns the currently configured size of the queue.
157    pub fn size(&self) -> u16 {
158        self.size
159    }
160
161    /// Sets the queue size.
162    pub fn set_size(&mut self, val: u16) {
163        if self.ready {
164            warn!("ignoring write to size on ready queue");
165            return;
166        }
167
168        if val > self.max_size {
169            warn!(
170                "requested queue size {} is larger than max_size {}",
171                val, self.max_size
172            );
173            return;
174        }
175
176        self.size = val;
177    }
178
179    /// Returns the currently configured interrupt vector.
180    pub fn vector(&self) -> u16 {
181        self.vector
182    }
183
184    /// Sets the interrupt vector for this queue.
185    pub fn set_vector(&mut self, val: u16) {
186        if self.ready {
187            warn!("ignoring write to vector on ready queue");
188            return;
189        }
190
191        self.vector = val;
192    }
193
194    /// Getter for descriptor area
195    pub fn desc_table(&self) -> GuestAddress {
196        self.desc_table
197    }
198
199    /// Setter for descriptor area
200    pub fn set_desc_table(&mut self, val: GuestAddress) {
201        if self.ready {
202            warn!("ignoring write to desc_table on ready queue");
203            return;
204        }
205
206        self.desc_table = val;
207    }
208
209    /// Getter for driver area
210    pub fn avail_ring(&self) -> GuestAddress {
211        self.avail_ring
212    }
213
214    /// Setter for driver area
215    pub fn set_avail_ring(&mut self, val: GuestAddress) {
216        if self.ready {
217            warn!("ignoring write to avail_ring on ready queue");
218            return;
219        }
220
221        self.avail_ring = val;
222    }
223
224    /// Getter for device area
225    pub fn used_ring(&self) -> GuestAddress {
226        self.used_ring
227    }
228
229    /// Setter for device area
230    pub fn set_used_ring(&mut self, val: GuestAddress) {
231        if self.ready {
232            warn!("ignoring write to used_ring on ready queue");
233            return;
234        }
235
236        self.used_ring = val;
237    }
238
239    /// Getter for next_avail index
240    pub fn next_avail(&self) -> Wrapping<u16> {
241        self.next_avail
242    }
243
244    /// Setter for next_avail index
245    pub fn set_next_avail(&mut self, val: Wrapping<u16>) {
246        if self.ready {
247            warn!("ignoring write to next_avail on ready queue");
248            return;
249        }
250
251        self.next_avail = val;
252    }
253
254    /// Getter for next_used index
255    pub fn next_used(&self) -> Wrapping<u16> {
256        self.next_used
257    }
258
259    /// Setter for next_used index
260    pub fn set_next_used(&mut self, val: Wrapping<u16>) {
261        if self.ready {
262            warn!("ignoring write to next_used on ready queue");
263            return;
264        }
265
266        self.next_used = val;
267    }
268
269    /// Returns the features that have been acknowledged by the driver.
270    pub fn acked_features(&self) -> u64 {
271        self.acked_features
272    }
273
274    /// Acknowledges that this set of features should be enabled on this queue.
275    pub fn ack_features(&mut self, features: u64) {
276        self.acked_features |= features & self.features;
277    }
278
279    /// Return whether the driver has enabled this queue.
280    pub fn ready(&self) -> bool {
281        self.ready
282    }
283
284    /// Signal that the driver has completed queue configuration.
285    pub fn set_ready(&mut self, enable: bool) {
286        self.ready = enable;
287    }
288
289    /// Convert the queue configuration into an active queue.
290    pub fn activate(
291        &mut self,
292        mem: &GuestMemory,
293        event: Event,
294        interrupt: Interrupt,
295    ) -> Result<Queue> {
296        if !self.ready {
297            bail!("attempted to activate a non-ready queue");
298        }
299
300        if self.activated {
301            bail!("queue is already activated");
302        }
303        // If VIRTIO_F_RING_PACKED feature bit is set, create a packed queue, otherwise create a
304        // split queue
305        let queue: Queue = if ((self.acked_features >> VIRTIO_F_RING_PACKED) & 1) != 0 {
306            let pq = PackedQueue::new(self, mem, event, interrupt)
307                .context("Failed to create a packed queue.")?;
308            Queue::PackedVirtQueue(pq)
309        } else {
310            let sq = SplitQueue::new(self, mem, event, interrupt)
311                .context("Failed to create a split queue.")?;
312            Queue::SplitVirtQueue(sq)
313        };
314
315        self.activated = true;
316        Ok(queue)
317    }
318
319    /// Reset queue to a clean state
320    pub fn reset(&mut self) {
321        self.activated = false;
322        self.ready = false;
323        self.size = self.max_size;
324        self.vector = VIRTIO_MSI_NO_VECTOR;
325        self.desc_table = GuestAddress(0);
326        self.avail_ring = GuestAddress(0);
327        self.used_ring = GuestAddress(0);
328        self.next_avail = Wrapping(0);
329        self.next_used = Wrapping(0);
330        self.acked_features = 0;
331    }
332
333    /// Take snapshot of queue configuration
334    pub fn snapshot(&self) -> Result<AnySnapshot> {
335        AnySnapshot::to_any(QueueConfigSnapshot {
336            activated: self.activated,
337            max_size: self.max_size,
338            size: self.size,
339            ready: self.ready,
340            vector: self.vector,
341            features: self.features,
342            acked_features: self.acked_features,
343            desc_table: self.desc_table,
344            avail_ring: self.avail_ring,
345            used_ring: self.used_ring,
346            next_avail: self.next_avail,
347            next_used: self.next_used,
348        })
349        .context("error serializing")
350    }
351
352    /// Restore queue configuration from snapshot
353    pub fn restore(&mut self, data: AnySnapshot) -> Result<()> {
354        let snap: QueueConfigSnapshot =
355            AnySnapshot::from_any(data).context("error deserializing")?;
356        self.activated = snap.activated;
357        self.max_size = snap.max_size;
358        self.size = snap.size;
359        self.ready = snap.ready;
360        self.vector = snap.vector;
361        self.features = snap.features;
362        self.acked_features = snap.acked_features;
363        self.desc_table = snap.desc_table;
364        self.avail_ring = snap.avail_ring;
365        self.used_ring = snap.used_ring;
366        self.next_avail = snap.next_avail;
367        self.next_used = snap.next_used;
368        Ok(())
369    }
370}
371
372/// Usage: define_queue_method!(method_name, return_type[, mut][, arg1: arg1_type, arg2: arg2_type,
373/// ...])
374///
375/// - `method_name`: The name of the method to be defined (as an identifier).
376/// - `return_type`: The return type of the method.
377/// - `mut` (optional): Include this keyword if the method requires a mutable reference to `self`
378///   (`&mut self`).
379/// - `arg1: arg1_type, arg2: arg2_type, ...` (optional): Include method parameters as a
380///   comma-separated list of `name: type` pairs, if the method takes any arguments.
381macro_rules! define_queue_method {
382    (
383        $(#[$doc:meta])*
384        $method:ident, $return_type:ty, $( $var:ident : $vartype:ty ),*
385    ) => {
386        $(#[$doc])*
387        pub fn $method(&self, $($var: $vartype),*) -> $return_type {
388            match self {
389                Queue::SplitVirtQueue(sq) => sq.$method($($var),*),
390                Queue::PackedVirtQueue(pq) => pq.$method($($var),*),
391            }
392        }
393    };
394    (
395        $(#[$doc:meta])*
396        $method:ident, $return_type:ty, mut, $( $var:ident : $vartype:ty ),*
397    ) => {
398        $(#[$doc])*
399        pub fn $method(&mut self, $($var: $vartype),*) -> $return_type {
400            match self {
401                Queue::SplitVirtQueue(sq) => sq.$method($($var),*),
402                Queue::PackedVirtQueue(pq) => pq.$method($($var),*),
403            }
404        }
405    };
406}
407
408/// Virtqueue interface representing different types of virtqueues
409/// The struct of each queue type is wrapped in the enum variants
410#[derive(Debug)]
411pub enum Queue {
412    /// Split virtqueue type in virtio v1.2 spec: <https://docs.oasis-open.org/virtio/virtio/v1.2/csd01/virtio-v1.2-csd01.html#x1-350007>
413    SplitVirtQueue(SplitQueue),
414    /// Packed virtqueue type in virtio v1.2 spec: <https://docs.oasis-open.org/virtio/virtio/v1.2/csd01/virtio-v1.2-csd01.html#x1-720008>
415    PackedVirtQueue(PackedQueue),
416}
417
418impl Queue {
419    /// Largest valid number of entries in a virtqueue.
420    pub const MAX_SIZE: u16 = 32768;
421
422    /// Asynchronously read the next descriptor chain from the queue.
423    /// Returns a `DescriptorChain` when it is `await`ed.
424    pub async fn next_async(
425        &mut self,
426        eventfd: &mut EventAsync,
427    ) -> std::result::Result<DescriptorChain, AsyncError> {
428        loop {
429            // Check if there are more descriptors available.
430            if let Some(chain) = self.pop() {
431                return Ok(chain);
432            }
433            eventfd.next_val().await?;
434        }
435    }
436
437    /// Get the first available descriptor chain without removing it from the queue.
438    /// Call `pop()` on the returned [`PeekedDescriptorChain`] to remove it from the queue.
439    pub fn peek(&mut self) -> Option<PeekedDescriptorChain> {
440        let desc_chain = match self {
441            Queue::SplitVirtQueue(q) => q.peek(),
442            Queue::PackedVirtQueue(q) => q.peek(),
443        }?;
444
445        Some(PeekedDescriptorChain::new(self, desc_chain))
446    }
447
448    /// If a new DescriptorChain is available, returns one and removes it from the queue.
449    pub fn pop(&mut self) -> Option<DescriptorChain> {
450        self.peek().map(PeekedDescriptorChain::pop)
451    }
452
453    /// try to pop DescriptorChain and collect until writable descriptors' total length
454    /// bigger than request_length. If no enough descriptors, return None.
455    pub fn try_pop_length(&mut self, request_length: usize) -> Option<Vec<DescriptorChain>> {
456        match self {
457            Queue::SplitVirtQueue(q) => q.try_pop_length(request_length),
458            Queue::PackedVirtQueue(_q) => {
459                unimplemented!()
460            }
461        }
462    }
463
464    /// Returns `None` if stop_rx receives a value; otherwise returns the result
465    /// of waiting for the next descriptor.
466    pub async fn next_async_interruptable(
467        &mut self,
468        queue_event: &mut EventAsync,
469        mut stop_rx: &mut oneshot::Receiver<()>,
470    ) -> std::result::Result<Option<DescriptorChain>, AsyncError> {
471        select_biased! {
472            avail_desc_res = self.next_async(queue_event).fuse() => {
473                Ok(Some(avail_desc_res?))
474            }
475            _ = stop_rx => Ok(None),
476        }
477    }
478
479    /// inject interrupt into guest on this queue
480    /// return true: interrupt is injected into guest for this queue
481    ///        false: interrupt isn't injected
482    pub fn trigger_interrupt(&mut self) -> bool {
483        match self {
484            Queue::SplitVirtQueue(sq) => sq.trigger_interrupt(),
485            Queue::PackedVirtQueue(pq) => pq.trigger_interrupt(),
486        }
487    }
488
489    /// Restore queue from snapshot
490    pub fn restore(
491        queue_config: &QueueConfig,
492        queue_value: AnySnapshot,
493        mem: &GuestMemory,
494        event: Event,
495        interrupt: Interrupt,
496    ) -> anyhow::Result<Queue> {
497        if queue_config.acked_features & 1 << VIRTIO_F_RING_PACKED != 0 {
498            PackedQueue::restore(queue_value, mem, event, interrupt).map(Queue::PackedVirtQueue)
499        } else {
500            SplitQueue::restore(queue_value, mem, event, interrupt).map(Queue::SplitVirtQueue)
501        }
502    }
503
504    /// "Reclaim" a queue that was given to a vhost-user backend and is now being taken back using
505    /// VHOST_USER_GET_VRING_BASE.
506    ///
507    /// The `Queue` will have stale fields if the vhost-user backend fulfilled any virtqueue
508    /// requests. This function updates the `Queue` to pick up where the backend left off.
509    pub fn vhost_user_reclaim(&mut self, vring_base: u16) {
510        match self {
511            Queue::SplitVirtQueue(q) => q.vhost_user_reclaim(vring_base),
512            Queue::PackedVirtQueue(q) => q.vhost_user_reclaim(vring_base),
513        }
514    }
515
516    /// Getter for the next index of the available ring that device will process.
517    ///
518    /// Not to be confused with the available ring's index field, which is the next index for the
519    /// driver to fill.
520    pub fn next_avail_to_process(&self) -> u16 {
521        match self {
522            Queue::SplitVirtQueue(q) => q.next_avail_to_process(),
523            Queue::PackedVirtQueue(q) => q.next_avail_to_process(),
524        }
525    }
526
527    define_queue_method!(
528        /// Getter for vector field
529        vector,
530        u16,
531    );
532
533    define_queue_method!(
534        /// Getter for descriptor area
535        desc_table,
536        GuestAddress,
537    );
538
539    define_queue_method!(
540        /// Getter for driver area
541        avail_ring,
542        GuestAddress,
543    );
544
545    define_queue_method!(
546        /// Getter for device area
547        used_ring,
548        GuestAddress,
549    );
550
551    define_queue_method!(
552        /// Return the actual size of the queue, as the driver may not set up a
553        /// queue as big as the device allows.
554        size,
555        u16,
556    );
557
558    define_queue_method!(
559        /// Get a reference to the queue's event.
560        event,
561        &Event,
562    );
563
564    define_queue_method!(
565        /// Get a reference to the queue's interrupt.
566        interrupt,
567        &Interrupt,
568    );
569
570    /// Puts an available descriptor head into the used ring for use by the guest, using the number
571    /// of bytes written to `DescriptorChain`.
572    pub fn add_used(&mut self, desc_chain: DescriptorChain) {
573        let len: u32 = desc_chain.writer.bytes_written().try_into().unwrap();
574        self.add_used_with_bytes_written(desc_chain, len);
575    }
576
577    /// Puts an available descriptor head into the used ring for use by the guest, explicitly
578    /// specifying the number of bytes written.
579    pub fn add_used_with_bytes_written(&mut self, desc_chain: DescriptorChain, len: u32) {
580        let iter = std::iter::once((desc_chain, len));
581        match self {
582            Queue::SplitVirtQueue(q) => q.add_used_with_bytes_written_batch(iter),
583            Queue::PackedVirtQueue(q) => q.add_used_with_bytes_written_batch(iter),
584        }
585    }
586
587    /// add a batch of descriptor chain into used in one time with each descriptor chain
588    /// specifying the number of bytes written with `desc_chain.writer.bytes_written()`
589    pub fn add_used_batch(&mut self, desc_chains: impl IntoIterator<Item = DescriptorChain>) {
590        let iter = desc_chains.into_iter().map(|desc_chain| {
591            let len: u32 = desc_chain.writer.bytes_written().try_into().unwrap();
592            (desc_chain, len)
593        });
594        match self {
595            Queue::SplitVirtQueue(q) => q.add_used_with_bytes_written_batch(iter),
596            Queue::PackedVirtQueue(q) => q.add_used_with_bytes_written_batch(iter),
597        }
598    }
599
600    define_queue_method!(
601        /// Take snapshot of queue's current status
602        snapshot,
603        Result<AnySnapshot>,
604    );
605}
606
607/// A `DescriptorChain` that has been peeked from a `Queue` but not popped yet.
608///
609/// Call [`pop()`](Self::pop) to pop this descriptor chain from the `Queue` and receive the
610/// contained `DescriptorChain` object.
611///
612/// This object holds a mutable reference to the `Queue` to ensure it is not possible to pop or peek
613/// another descriptor while a peek is already active. Either `pop()` or drop this object before
614/// attempting to manipulate the `Queue` again.
615pub struct PeekedDescriptorChain<'q> {
616    queue: &'q mut Queue,
617    desc_chain: DescriptorChain,
618}
619
620impl<'q> PeekedDescriptorChain<'q> {
621    /// Create a `PeekedDescriptorChain` that holds a mutable reference to its `Queue`.
622    /// Use [`Queue::peek()`] rather than calling this function.
623    fn new(queue: &'q mut Queue, desc_chain: DescriptorChain) -> Self {
624        PeekedDescriptorChain { queue, desc_chain }
625    }
626
627    /// Pop this descriptor chain from the queue.
628    pub fn pop(self) -> DescriptorChain {
629        match self.queue {
630            Queue::SplitVirtQueue(q) => q.pop_peeked(&self.desc_chain),
631            Queue::PackedVirtQueue(q) => q.pop_peeked(&self.desc_chain),
632        }
633        self.desc_chain
634    }
635}
636
637impl Deref for PeekedDescriptorChain<'_> {
638    type Target = DescriptorChain;
639
640    fn deref(&self) -> &Self::Target {
641        &self.desc_chain
642    }
643}
644
645impl DerefMut for PeekedDescriptorChain<'_> {
646    fn deref_mut(&mut self) -> &mut Self::Target {
647        &mut self.desc_chain
648    }
649}