1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
// Copyright 2023 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Split virtqueue descriptor chain iterator

#![deny(missing_docs)]

use anyhow::bail;
use anyhow::Context;
use anyhow::Result;
use base::trace;
use data_model::Le16;
use data_model::Le32;
use data_model::Le64;
use vm_memory::GuestAddress;
use vm_memory::GuestMemory;
use zerocopy::AsBytes;
use zerocopy::FromBytes;
use zerocopy::FromZeroes;

use crate::virtio::descriptor_chain::Descriptor;
use crate::virtio::descriptor_chain::DescriptorAccess;
use crate::virtio::descriptor_chain::DescriptorChainIter;
use crate::virtio::descriptor_chain::VIRTQ_DESC_F_NEXT;
use crate::virtio::descriptor_chain::VIRTQ_DESC_F_WRITE;

/// A single virtio split queue descriptor (`struct virtq_desc` in the spec).
#[derive(Copy, Clone, Debug, FromZeroes, FromBytes, AsBytes)]
#[repr(C)]
pub struct Desc {
    /// Guest address of memory described by this descriptor.
    pub addr: Le64,

    /// Length of this descriptor's memory region in bytes.
    pub len: Le32,

    /// `VIRTQ_DESC_F_*` flags for this descriptor.
    pub flags: Le16,

    /// Index of the next descriptor in the chain (only valid if `flags & VIRTQ_DESC_F_NEXT`).
    pub next: Le16,
}

/// Iterator over the descriptors of a split virtqueue descriptor chain.
pub struct SplitDescriptorChain<'m> {
    /// Current descriptor index within `desc_table`, or `None` if the iterator is exhausted.
    index: Option<u16>,

    /// Number of descriptors returned by the iterator already.
    /// If `count` reaches `queue_size`, the chain has a loop and is therefore invalid.
    count: u16,

    queue_size: u16,

    mem: &'m GuestMemory,
    desc_table: GuestAddress,
}

impl<'m> SplitDescriptorChain<'m> {
    /// Construct a new iterator over a split virtqueue descriptor chain.
    ///
    /// # Arguments
    /// * `mem` - The [`GuestMemory`] containing the descriptor chain.
    /// * `desc_table` - Guest physical address of the descriptor table.
    /// * `queue_size` - Total number of entries in the descriptor table.
    /// * `index` - The index of the first descriptor in the chain.
    pub fn new(
        mem: &'m GuestMemory,
        desc_table: GuestAddress,
        queue_size: u16,
        index: u16,
    ) -> SplitDescriptorChain<'m> {
        trace!("starting split descriptor chain head={index}");
        SplitDescriptorChain {
            index: Some(index),
            count: 0,
            queue_size,
            mem,
            desc_table,
        }
    }
}

impl DescriptorChainIter for SplitDescriptorChain<'_> {
    fn next(&mut self) -> Result<Option<Descriptor>> {
        let index = match self.index {
            Some(index) => index,
            None => return Ok(None),
        };

        if index >= self.queue_size {
            bail!(
                "out of bounds descriptor index {} for queue size {}",
                index,
                self.queue_size
            );
        }

        if self.count >= self.queue_size {
            bail!("descriptor chain loop detected");
        }
        self.count += 1;

        let desc_addr = self
            .desc_table
            .checked_add((index as u64) * 16)
            .context("integer overflow")?;
        let desc = self
            .mem
            .read_obj_from_addr::<Desc>(desc_addr)
            .with_context(|| format!("failed to read desc {:#x}", desc_addr.offset()))?;

        let address: u64 = desc.addr.into();
        let len: u32 = desc.len.into();
        let flags: u16 = desc.flags.into();
        let next: u16 = desc.next.into();

        trace!("{index:5}: addr={address:#016x} len={len:#08x} flags={flags:#x}");

        let unexpected_flags = flags & !(VIRTQ_DESC_F_WRITE | VIRTQ_DESC_F_NEXT);
        if unexpected_flags != 0 {
            bail!("unexpected flags in descriptor {index}: {unexpected_flags:#x}")
        }

        let access = if flags & VIRTQ_DESC_F_WRITE != 0 {
            DescriptorAccess::DeviceWrite
        } else {
            DescriptorAccess::DeviceRead
        };

        self.index = if flags & VIRTQ_DESC_F_NEXT != 0 {
            Some(next)
        } else {
            None
        };

        Ok(Some(Descriptor {
            address,
            len,
            access,
        }))
    }

    fn count(&self) -> u16 {
        self.count
    }

    fn id(&self) -> Option<u16> {
        None
    }
}