devices/virtio/queue/
split_descriptor_chain.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//! Split virtqueue descriptor chain iterator
6
7#![deny(missing_docs)]
8
9use anyhow::bail;
10use anyhow::Context;
11use anyhow::Result;
12use base::trace;
13use data_model::Le16;
14use data_model::Le32;
15use data_model::Le64;
16use vm_memory::GuestAddress;
17use vm_memory::GuestMemory;
18use zerocopy::FromBytes;
19use zerocopy::Immutable;
20use zerocopy::IntoBytes;
21use zerocopy::KnownLayout;
22
23use crate::virtio::descriptor_chain::Descriptor;
24use crate::virtio::descriptor_chain::DescriptorAccess;
25use crate::virtio::descriptor_chain::DescriptorChainIter;
26use crate::virtio::descriptor_chain::VIRTQ_DESC_F_NEXT;
27use crate::virtio::descriptor_chain::VIRTQ_DESC_F_WRITE;
28
29/// A single virtio split queue descriptor (`struct virtq_desc` in the spec).
30#[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)]
31#[repr(C)]
32pub struct Desc {
33    /// Guest address of memory described by this descriptor.
34    pub addr: Le64,
35
36    /// Length of this descriptor's memory region in bytes.
37    pub len: Le32,
38
39    /// `VIRTQ_DESC_F_*` flags for this descriptor.
40    pub flags: Le16,
41
42    /// Index of the next descriptor in the chain (only valid if `flags & VIRTQ_DESC_F_NEXT`).
43    pub next: Le16,
44}
45
46/// Iterator over the descriptors of a split virtqueue descriptor chain.
47pub struct SplitDescriptorChain {
48    /// Current descriptor index within `desc_table`, or `None` if the iterator is exhausted.
49    index: Option<u16>,
50
51    /// Number of descriptors returned by the iterator already.
52    /// If `count` reaches `queue_size`, the chain has a loop and is therefore invalid.
53    count: u16,
54
55    queue_size: u16,
56
57    desc_table: GuestAddress,
58}
59
60impl SplitDescriptorChain {
61    /// Construct a new iterator over a split virtqueue descriptor chain.
62    ///
63    /// # Arguments
64    /// * `desc_table` - Guest physical address of the descriptor table.
65    /// * `queue_size` - Total number of entries in the descriptor table.
66    /// * `index` - The index of the first descriptor in the chain.
67    pub fn new(desc_table: GuestAddress, queue_size: u16, index: u16) -> SplitDescriptorChain {
68        trace!("starting split descriptor chain head={index}");
69        SplitDescriptorChain {
70            index: Some(index),
71            count: 0,
72            queue_size,
73            desc_table,
74        }
75    }
76}
77
78impl DescriptorChainIter for SplitDescriptorChain {
79    fn next(&mut self, mem: &GuestMemory) -> Result<Option<Descriptor>> {
80        let index = match self.index {
81            Some(index) => index,
82            None => return Ok(None),
83        };
84
85        if index >= self.queue_size {
86            bail!(
87                "out of bounds descriptor index {} for queue size {}",
88                index,
89                self.queue_size
90            );
91        }
92
93        if self.count >= self.queue_size {
94            bail!("descriptor chain loop detected");
95        }
96        self.count += 1;
97
98        let desc_addr = self
99            .desc_table
100            .checked_add((index as u64) * 16)
101            .context("integer overflow")?;
102        let desc = mem
103            .read_obj_from_addr::<Desc>(desc_addr)
104            .with_context(|| format!("failed to read desc {:#x}", desc_addr.offset()))?;
105
106        let address: u64 = desc.addr.into();
107        let len: u32 = desc.len.into();
108        let flags: u16 = desc.flags.into();
109        let next: u16 = desc.next.into();
110
111        trace!("{index:5}: addr={address:#016x} len={len:#08x} flags={flags:#x}");
112
113        let unexpected_flags = flags & !(VIRTQ_DESC_F_WRITE | VIRTQ_DESC_F_NEXT);
114        if unexpected_flags != 0 {
115            bail!("unexpected flags in descriptor {index}: {unexpected_flags:#x}")
116        }
117
118        let access = if flags & VIRTQ_DESC_F_WRITE != 0 {
119            DescriptorAccess::DeviceWrite
120        } else {
121            DescriptorAccess::DeviceRead
122        };
123
124        self.index = if flags & VIRTQ_DESC_F_NEXT != 0 {
125            Some(next)
126        } else {
127            None
128        };
129
130        Ok(Some(Descriptor {
131            address,
132            len,
133            access,
134        }))
135    }
136
137    fn count(&self) -> u16 {
138        self.count
139    }
140
141    fn id(&self) -> Option<u16> {
142        None
143    }
144}