virtio_queue/desc/
split.rs

1// Portions Copyright 2017 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE-BSD-3-Clause file.
4//
5// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
6//
7// Copyright © 2019 Intel Corporation
8//
9// Copyright (C) 2020-2021 Alibaba Cloud. All rights reserved.
10//
11// SPDX-License-Identifier: Apache-2.0 AND BSD-3-Clause
12//! split descriptor
13
14use vm_memory::{ByteValued, GuestAddress, Le16, Le32, Le64};
15
16use virtio_bindings::bindings::virtio_ring::{
17    VRING_DESC_F_INDIRECT, VRING_DESC_F_NEXT, VRING_DESC_F_WRITE,
18};
19
20/// A virtio descriptor constraints with C representation.
21///
22/// # Example
23///
24/// ```rust
25/// # use virtio_bindings::bindings::virtio_ring::{VRING_DESC_F_NEXT, VRING_DESC_F_WRITE};
26/// # use virtio_queue::mock::MockSplitQueue;
27/// use virtio_queue::{desc::{split::Descriptor as SplitDescriptor, RawDescriptor}, Queue, QueueOwnedT};
28/// use vm_memory::{GuestAddress, GuestMemoryMmap};
29///
30/// # fn populate_queue(m: &GuestMemoryMmap) -> Queue {
31/// #    let vq = MockSplitQueue::new(m, 16);
32/// #    let mut q = vq.create_queue().unwrap();
33/// #
34/// #    // We have only one chain: (0, 1).
35/// #    let desc = RawDescriptor::from(SplitDescriptor::new(0x1000, 0x1000, VRING_DESC_F_NEXT as u16, 1));
36/// #    vq.desc_table().store(0, desc);
37/// #    let desc = RawDescriptor::from(SplitDescriptor::new(0x2000, 0x1000, VRING_DESC_F_WRITE as u16, 0));
38/// #    vq.desc_table().store(1, desc);
39/// #
40/// #    vq.avail().ring().ref_at(0).unwrap().store(u16::to_le(0));
41/// #    vq.avail().idx().store(u16::to_le(1));
42/// #    q
43/// # }
44/// let m = &GuestMemoryMmap::<()>::from_ranges(&[(GuestAddress(0), 0x10000)]).unwrap();
45/// // Populate the queue with descriptor chains and update the available ring accordingly.
46/// let mut queue = populate_queue(m);
47/// let mut i = queue.iter(m).unwrap();
48/// let mut c = i.next().unwrap();
49///
50/// // Get the first descriptor and access its fields.
51/// let desc = c.next().unwrap();
52/// let _addr = desc.addr();
53/// let _len = desc.len();
54/// let _flags = desc.flags();
55/// let _next = desc.next();
56/// let _is_write_only = desc.is_write_only();
57/// let _has_next = desc.has_next();
58/// let _refers_to_ind_table = desc.refers_to_indirect_table();
59/// ```
60/// A virtio split descriptor constraints with C representation.
61#[repr(C)]
62#[derive(Default, Clone, Copy, Debug)]
63pub struct Descriptor {
64    /// Guest physical address of device specific data.
65    addr: Le64,
66
67    /// Length of device specific data.
68    len: Le32,
69
70    /// Includes next, write, and indirect bits.
71    flags: Le16,
72
73    /// Index into the descriptor table of the next descriptor if flags has the `next` bit set.
74    next: Le16,
75}
76
77#[allow(clippy::len_without_is_empty)]
78impl Descriptor {
79    /// Create a new descriptor.
80    ///
81    /// # Arguments
82    /// * `addr` - the guest physical address of the descriptor buffer.
83    /// * `len` - the length of the descriptor buffer.
84    /// * `flags` - the `flags` for the descriptor.
85    /// * `next` - the `next` field of the descriptor.
86    pub fn new(addr: u64, len: u32, flags: u16, next: u16) -> Self {
87        Descriptor {
88            addr: addr.into(),
89            len: len.into(),
90            flags: flags.into(),
91            next: next.into(),
92        }
93    }
94
95    /// Return the guest physical address of the descriptor buffer.
96    pub fn addr(&self) -> GuestAddress {
97        GuestAddress(self.addr.into())
98    }
99
100    /// Return the length of the descriptor buffer.
101    pub fn len(&self) -> u32 {
102        self.len.into()
103    }
104
105    /// Return the flags for this descriptor, including next, write and indirect bits.
106    pub fn flags(&self) -> u16 {
107        self.flags.into()
108    }
109
110    /// Return the value stored in the `next` field of the descriptor.
111    pub fn next(&self) -> u16 {
112        self.next.into()
113    }
114
115    /// Check whether this descriptor refers to a buffer containing an indirect descriptor table.
116    pub fn refers_to_indirect_table(&self) -> bool {
117        self.flags() & VRING_DESC_F_INDIRECT as u16 != 0
118    }
119
120    /// Check whether the `VIRTQ_DESC_F_NEXT` is set for the descriptor.
121    pub fn has_next(&self) -> bool {
122        self.flags() & VRING_DESC_F_NEXT as u16 != 0
123    }
124
125    /// Check if the driver designated this as a write only descriptor.
126    ///
127    /// If this is false, this descriptor is read only.
128    /// Write only means the the emulated device can write and the driver can read.
129    pub fn is_write_only(&self) -> bool {
130        self.flags() & VRING_DESC_F_WRITE as u16 != 0
131    }
132}
133
134#[cfg(any(test, feature = "test-utils"))]
135impl Descriptor {
136    /// Set the guest physical address of the descriptor buffer.
137    pub fn set_addr(&mut self, addr: u64) {
138        self.addr = addr.into();
139    }
140
141    /// Set the length of the descriptor buffer.
142    pub fn set_len(&mut self, len: u32) {
143        self.len = len.into();
144    }
145
146    /// Set the flags for this descriptor.
147    pub fn set_flags(&mut self, flags: u16) {
148        self.flags = flags.into();
149    }
150
151    /// Set the value stored in the `next` field of the descriptor.
152    pub fn set_next(&mut self, next: u16) {
153        self.next = next.into();
154    }
155}
156
157// SAFETY: This is safe because `Descriptor` contains only wrappers over POD types and
158// all accesses through safe `vm-memory` API will validate any garbage that could be
159// included in there.
160unsafe impl ByteValued for Descriptor {}
161
162/// Represents the contents of an element from the used virtqueue ring.
163// Note that the `ByteValued` implementation of this structure expects the `VirtqUsedElem` to store
164// only plain old data types.
165#[repr(C)]
166#[derive(Clone, Copy, Default, Debug)]
167pub struct VirtqUsedElem {
168    id: Le32,
169    len: Le32,
170}
171
172impl VirtqUsedElem {
173    /// Create a new `VirtqUsedElem` instance.
174    ///
175    /// # Arguments
176    /// * `id` - the index of the used descriptor chain.
177    /// * `len` - the total length of the descriptor chain which was used (written to).
178    #[allow(unused)]
179    pub(crate) fn new(id: u32, len: u32) -> Self {
180        VirtqUsedElem {
181            id: id.into(),
182            len: len.into(),
183        }
184    }
185}
186
187#[cfg(any(test, feature = "test-utils"))]
188#[allow(clippy::len_without_is_empty)]
189impl VirtqUsedElem {
190    /// Get the index of the used descriptor chain.
191    pub fn id(&self) -> u32 {
192        self.id.into()
193    }
194
195    /// Get `length` field of the used ring entry.
196    pub fn len(&self) -> u32 {
197        self.len.into()
198    }
199}
200
201// SAFETY: This is safe because `VirtqUsedElem` contains only wrappers over POD types
202// and all accesses through safe `vm-memory` API will validate any garbage that could be
203// included in there.
204unsafe impl ByteValued for VirtqUsedElem {}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209    use memoffset::offset_of;
210    use std::mem::{align_of, size_of};
211
212    #[test]
213    fn test_descriptor_offset() {
214        assert_eq!(size_of::<Descriptor>(), 16);
215        assert_eq!(offset_of!(Descriptor, addr), 0);
216        assert_eq!(offset_of!(Descriptor, len), 8);
217        assert_eq!(offset_of!(Descriptor, flags), 12);
218        assert_eq!(offset_of!(Descriptor, next), 14);
219        assert!(align_of::<Descriptor>() <= 16);
220    }
221
222    #[test]
223    fn test_descriptor_getter_setter() {
224        let mut desc = Descriptor::new(0, 0, 0, 0);
225
226        desc.set_addr(0x1000);
227        assert_eq!(desc.addr(), GuestAddress(0x1000));
228        desc.set_len(0x2000);
229        assert_eq!(desc.len(), 0x2000);
230        desc.set_flags(VRING_DESC_F_NEXT as u16);
231        assert_eq!(desc.flags(), VRING_DESC_F_NEXT as u16);
232        assert!(desc.has_next());
233        assert!(!desc.is_write_only());
234        assert!(!desc.refers_to_indirect_table());
235        desc.set_flags(VRING_DESC_F_WRITE as u16);
236        assert_eq!(desc.flags(), VRING_DESC_F_WRITE as u16);
237        assert!(!desc.has_next());
238        assert!(desc.is_write_only());
239        assert!(!desc.refers_to_indirect_table());
240        desc.set_flags(VRING_DESC_F_INDIRECT as u16);
241        assert_eq!(desc.flags(), VRING_DESC_F_INDIRECT as u16);
242        assert!(!desc.has_next());
243        assert!(!desc.is_write_only());
244        assert!(desc.refers_to_indirect_table());
245        desc.set_next(3);
246        assert_eq!(desc.next(), 3);
247    }
248
249    #[test]
250    fn test_descriptor_copy() {
251        let e1 = Descriptor::new(1, 2, VRING_DESC_F_NEXT as u16, 3);
252        let mut e2 = Descriptor::default();
253
254        e2.as_mut_slice().copy_from_slice(e1.as_slice());
255        assert_eq!(e1.addr(), e2.addr());
256        assert_eq!(e1.len(), e2.len());
257        assert_eq!(e1.flags(), e2.flags());
258        assert_eq!(e1.next(), e2.next());
259    }
260
261    #[test]
262    fn test_used_elem_offset() {
263        assert_eq!(offset_of!(VirtqUsedElem, id), 0);
264        assert_eq!(offset_of!(VirtqUsedElem, len), 4);
265        assert_eq!(size_of::<VirtqUsedElem>(), 8);
266    }
267
268    #[test]
269    fn test_used_elem_copy() {
270        let e1 = VirtqUsedElem::new(3, 15);
271        let mut e2 = VirtqUsedElem::new(0, 0);
272
273        e2.as_mut_slice().copy_from_slice(e1.as_slice());
274        assert_eq!(e1.id, e2.id);
275        assert_eq!(e1.len, e2.len);
276    }
277}