devices/virtio/queue/
packed_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//! Packed virtqueue descriptor chain iterator
6
7#![deny(missing_docs)]
8
9use anyhow::bail;
10use anyhow::Context;
11use anyhow::Result;
12use base::error;
13use base::trace;
14use data_model::Le16;
15use data_model::Le32;
16use data_model::Le64;
17use vm_memory::GuestAddress;
18use vm_memory::GuestMemory;
19use zerocopy::FromBytes;
20use zerocopy::Immutable;
21use zerocopy::IntoBytes;
22use zerocopy::KnownLayout;
23
24use crate::virtio::descriptor_chain::Descriptor;
25use crate::virtio::descriptor_chain::DescriptorAccess;
26use crate::virtio::descriptor_chain::DescriptorChainIter;
27use crate::virtio::descriptor_chain::VIRTQ_DESC_F_AVAIL;
28use crate::virtio::descriptor_chain::VIRTQ_DESC_F_NEXT;
29use crate::virtio::descriptor_chain::VIRTQ_DESC_F_USED;
30use crate::virtio::descriptor_chain::VIRTQ_DESC_F_WRITE;
31
32/// Enable events
33pub const RING_EVENT_FLAGS_ENABLE: u16 = 0x0;
34/// Disable events
35pub const RING_EVENT_FLAGS_DISABLE: u16 = 0x1;
36
37/// Enable events for a specific descriptor.
38/// Only valid if VIRTIO_F_RING_EVENT_IDX has been negotiated.
39pub const RING_EVENT_FLAGS_DESC: u16 = 0x2;
40
41/// A packed virtio packed queue descriptor (`struct pvirtq_desc` in the spec).
42#[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)]
43#[repr(C)]
44pub struct PackedDesc {
45    /// Guest address of memory buffer address
46    pub addr: Le64,
47
48    /// Memory buffer length in bytes
49    pub len: Le32,
50
51    /// Buffer ID
52    pub id: Le16,
53
54    /// The flags depending on descriptor type
55    pub flags: Le16,
56}
57
58impl PackedDesc {
59    pub fn addr(&self) -> u64 {
60        self.addr.into()
61    }
62
63    pub fn len(&self) -> u32 {
64        self.len.into()
65    }
66
67    pub fn flags(&self) -> u16 {
68        self.flags.into()
69    }
70
71    pub fn id(&self) -> u16 {
72        self.id.into()
73    }
74
75    pub fn has_next(&self) -> bool {
76        self.flags() & VIRTQ_DESC_F_NEXT != 0
77    }
78
79    pub fn is_available(&self, wrap_value: u16) -> bool {
80        let avail = (self.flags() & VIRTQ_DESC_F_AVAIL) != 0;
81        let used = (self.flags() & VIRTQ_DESC_F_USED) != 0;
82        let wrap = wrap_value != 0;
83        avail != used && avail == wrap
84    }
85}
86
87#[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)]
88#[repr(C)]
89pub struct PackedDescEvent {
90    pub desc: Le16,
91    pub flag: Le16,
92}
93
94impl PackedDescEvent {
95    pub fn notification_type(&self) -> PackedNotificationType {
96        let flag: u16 = self.flag.into();
97
98        if flag == RING_EVENT_FLAGS_DISABLE {
99            PackedNotificationType::Disable
100        } else if flag == RING_EVENT_FLAGS_DESC {
101            PackedNotificationType::Desc(self.desc.into())
102        } else if flag == RING_EVENT_FLAGS_ENABLE {
103            PackedNotificationType::Enable
104        } else {
105            let desc: u16 = self.desc.into();
106            error!("Unknown packed desc event flag:{:x}, desc:{:x}", flag, desc);
107            PackedNotificationType::Enable
108        }
109    }
110}
111
112pub enum PackedNotificationType {
113    Enable,
114    Disable,
115    Desc(u16),
116}
117
118pub struct PackedDescriptorChain {
119    avail_wrap_counter: bool,
120
121    /// Current descriptor index within `desc_table`, or `None` if the iterator is exhausted.
122    index: Option<u16>,
123
124    /// Number of descriptors returned by the iterator already.
125    /// If `count` reaches `queue_size`, the chain has a loop and is therefore invalid.
126    count: u16,
127
128    /// Buffer Id, which locates at the last descriptor in the chain
129    id: Option<u16>,
130
131    queue_size: u16,
132
133    desc_table: GuestAddress,
134}
135
136impl PackedDescriptorChain {
137    /// Construct a new iterator over a packed virtqueue descriptor chain.
138    ///
139    /// # Arguments
140    /// * `desc_table` - Guest physical address of the descriptor table.
141    /// * `queue_size` - Total number of entries in the descriptor table.
142    /// * `avail_wrap_counter` - Current device wrap counter polarity.
143    /// * `index` - The index of the first descriptor in the chain.
144    pub fn new(
145        desc_table: GuestAddress,
146        queue_size: u16,
147        avail_wrap_counter: bool,
148        index: u16,
149    ) -> PackedDescriptorChain {
150        trace!("starting packed descriptor chain head={index}");
151        PackedDescriptorChain {
152            index: Some(index),
153            count: 0,
154            id: None,
155            queue_size,
156            desc_table,
157            avail_wrap_counter,
158        }
159    }
160}
161
162impl DescriptorChainIter for PackedDescriptorChain {
163    fn next(&mut self, mem: &GuestMemory) -> Result<Option<Descriptor>> {
164        let index = match self.index {
165            Some(index) => index,
166            None => {
167                return Ok(None);
168            }
169        };
170
171        if index >= self.queue_size {
172            bail!(
173                "out of bounds descriptor index {} for queue size {}",
174                index,
175                self.queue_size
176            );
177        }
178
179        if self.count >= self.queue_size {
180            bail!("descriptor chain loop detected");
181        }
182
183        let desc_addr = self
184            .desc_table
185            .checked_add((index as u64) * 16)
186            .context("integer overflow")?;
187        let desc = mem
188            .read_obj_from_addr::<PackedDesc>(desc_addr)
189            .with_context(|| format!("failed to read desc {:#x}", desc_addr.offset()))?;
190
191        let address: u64 = desc.addr();
192        let len: u32 = desc.len();
193        let flags: u16 = desc.flags();
194
195        trace!("{index:5}: addr={address:#016x} len={len:#08x} flags={flags:#x}");
196
197        if !desc.is_available(self.avail_wrap_counter as u16) {
198            // Missing a descriptor mid-chain means it is malformed.
199            bail!("descriptor {index} in the chain is not available");
200        }
201
202        if len == 0 {
203            bail!("invalid zero-length descriptor");
204        }
205
206        let unexpected_flags = flags
207            & !(VIRTQ_DESC_F_WRITE | VIRTQ_DESC_F_NEXT | VIRTQ_DESC_F_AVAIL | VIRTQ_DESC_F_USED);
208        if unexpected_flags != 0 {
209            bail!("unexpected flags in descriptor {index}: {unexpected_flags:#x}")
210        }
211
212        let access = if flags & VIRTQ_DESC_F_WRITE != 0 {
213            DescriptorAccess::DeviceWrite
214        } else {
215            DescriptorAccess::DeviceRead
216        };
217
218        // If VIRTQ_DESC_F_NEXT exists, the next descriptor in descriptor chain
219        // is the next element in descriptor table. When index reaches the end of
220        // descriptor table, we need to flip avail_wrap_counter.
221        if desc.has_next() {
222            if index + 1 < self.queue_size {
223                self.index = Some(index + 1);
224            } else {
225                self.index = Some(0);
226                self.avail_wrap_counter = !self.avail_wrap_counter;
227            }
228        } else {
229            self.id = Some(desc.id());
230            self.index = None;
231        }
232
233        self.count += 1;
234
235        Ok(Some(Descriptor {
236            address,
237            len,
238            access,
239        }))
240    }
241
242    fn count(&self) -> u16 {
243        self.count
244    }
245
246    fn id(&self) -> Option<u16> {
247        self.id
248    }
249}