Skip to main content

file_system/fundamentals/
control.rs

1use bitflags::bitflags;
2use shared::{AnyByLayout, PlainData};
3
4use crate::{IoErrorKind, Result};
5
6bitflags! {
7    /// Direction of control commands.
8    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
9    pub struct ControlDirectionFlags: u8 {
10        const Read = 1 << 0;
11        const Write = 1 << 1;
12    }
13}
14
15struct ControlCommandInputOutput<I, O> {
16    pub _input: I,
17    pub _output: O,
18}
19
20pub trait ControlCommand: Clone + Copy {
21    /// Command payload sent to the device. Must be plain data: a payload byte
22    /// pattern can never be an invalid value of the payload type.
23    type Input: PlainData;
24    /// Command payload returned by the device. Must be plain data for the same
25    /// reason.
26    type Output: PlainData;
27
28    const IDENTIFIER: ControlCommandIdentifier;
29
30    fn cast_input(input: &AnyByLayout) -> Result<&Self::Input> {
31        input.cast().ok_or(IoErrorKind::InvalidArgument)
32    }
33
34    fn cast_output(output: &mut AnyByLayout) -> Result<&mut Self::Output> {
35        output.cast_mutable().ok_or(IoErrorKind::InvalidArgument)
36    }
37
38    fn cast<'i, 'o>(
39        input: &'i AnyByLayout,
40        output: &'o mut AnyByLayout,
41    ) -> Result<(&'i Self::Input, &'o mut Self::Output)> {
42        Ok((Self::cast_input(input)?, Self::cast_output(output)?))
43    }
44}
45
46/// Defines a control command: a unit struct implementing [`ControlCommand`].
47///
48/// The input and output types are the command payload types. They must be
49/// plain data ([`PlainData`]): every payload byte pattern is then a valid
50/// value of the payload type, so a guest can never send an invalid value such
51/// as `2` for a `bool`. A `bool` or enum cannot be a payload type because not
52/// every byte pattern is one of its values; store such values as integers in
53/// the payload and convert them with `TryFrom` where the value is read.
54///
55/// ```compile_fail,E0277
56/// use file_system::{ControlCommand, define_command};
57///
58/// // `bool` is not plain data: the payload byte `2` would be an invalid `bool`.
59/// define_command!(EXAMPLE, Read, b'x', 0, bool, ());
60/// ```
61#[macro_export]
62macro_rules! define_command {
63    ($name:ident, Read, $kind:expr, $number:expr, $I:ty, $O:ty) => {
64        $crate::define_command!(
65            $name,
66            $crate::ControlDirectionFlags::Read,
67            $kind,
68            $number,
69            $I,
70            $O
71        );
72    };
73    ($name:ident, Write, $kind:expr, $number:expr, $I:ty, $O:ty) => {
74        $crate::define_command!(
75            $name,
76            $crate::ControlDirectionFlags::Write,
77            $kind,
78            $number,
79            $I,
80            $O
81        );
82    };
83    ($name:ident, $direction:expr, $kind:expr, $number:expr, $I:ty, $O:ty) => {
84        #[derive(Clone, Copy, Debug)]
85        #[allow(non_camel_case_types)]
86        pub struct $name;
87
88        const _: () = {
89            // A payload crosses the host/guest boundary as raw bytes: both
90            // payload types must accept every bit pattern.
91            #[allow(dead_code)]
92            fn require_plain_data<T: $crate::PlainData>() {}
93            let _: fn() = require_plain_data::<$I>;
94            let _: fn() = require_plain_data::<$O>;
95        };
96
97        impl ControlCommand for $name {
98            type Input = $I;
99            type Output = $O;
100
101            const IDENTIFIER: $crate::ControlCommandIdentifier =
102                $crate::ControlCommandIdentifier::new::<$I, $O>($direction, $kind, $number);
103        }
104    };
105}
106
107#[repr(transparent)]
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub struct ControlCommandIdentifier(usize);
110
111impl ControlCommandIdentifier {
112    const NUMBER_SIZE: usize = 8;
113    const KIND_SIZE: usize = 8;
114    const SIZE_SIZE: usize = 14;
115    const MAX_SIZE: usize = (1 << Self::SIZE_SIZE) - 1;
116    const DIRECTION_SIZE: usize = 2;
117
118    const NUMBER_SHIFT: usize = 0;
119    const KIND_SHIFT: usize = Self::NUMBER_SHIFT + Self::NUMBER_SIZE; // 8
120    const SIZE_SHIFT: usize = Self::KIND_SHIFT + Self::KIND_SIZE; // 16
121    const DIRECTION_SHIFT: usize = Self::SIZE_SHIFT + Self::SIZE_SIZE; // 30
122
123    pub const fn new<I, O>(direction: ControlDirectionFlags, kind: u8, number: u8) -> Self {
124        let size = core::mem::size_of::<ControlCommandInputOutput<I, O>>();
125
126        Self::new_with_size(direction, size, kind, number)
127    }
128
129    pub const fn new_read<I, O>(kind: u8, number: u8) -> Self {
130        Self::new_with_size(
131            ControlDirectionFlags::Read,
132            size_of::<ControlCommandInputOutput<I, O>>(),
133            kind,
134            number,
135        )
136    }
137
138    pub const fn new_write<I, O>(kind: u8, number: u8) -> Self {
139        Self::new_with_size(
140            ControlDirectionFlags::Write,
141            size_of::<ControlCommandInputOutput<I, O>>(),
142            kind,
143            number,
144        )
145    }
146
147    pub const fn new_with_size(
148        direction: ControlDirectionFlags,
149        size: usize,
150        kind: u8,
151        number: u8,
152    ) -> Self {
153        assert!(
154            size <= Self::MAX_SIZE,
155            "control command size exceeds its 14-bit field"
156        );
157
158        let direction = direction.bits() as usize;
159        let kind = kind as usize;
160        let number = number as usize;
161
162        Self(
163            (direction << Self::DIRECTION_SHIFT)
164                | (size << Self::SIZE_SHIFT)
165                | (kind << Self::KIND_SHIFT)
166                | (number << Self::NUMBER_SHIFT),
167        )
168    }
169
170    /// Reconstructs an identifier received through a raw control interface.
171    ///
172    /// The identifier's current encoding occupies at most 32 bits. This
173    /// conversion preserves those bits without interpreting the command.
174    pub const fn from_raw(raw: u32) -> Self {
175        Self(raw as usize)
176    }
177
178    /// Returns the stable raw encoding used by generic control interfaces.
179    pub const fn raw(self) -> u32 {
180        self.0 as u32
181    }
182
183    pub const fn get_direction(&self) -> ControlDirectionFlags {
184        let direction = (self.0 >> Self::DIRECTION_SHIFT) & ((1 << Self::DIRECTION_SIZE) - 1);
185        ControlDirectionFlags::from_bits_retain(direction as u8)
186    }
187
188    pub const fn get_size(&self) -> usize {
189        (self.0 >> Self::SIZE_SHIFT) & ((1 << Self::SIZE_SIZE) - 1)
190    }
191
192    pub const fn get_kind(&self) -> u8 {
193        ((self.0 >> Self::KIND_SHIFT) & ((1 << Self::KIND_SIZE) - 1)) as u8
194    }
195
196    pub const fn get_number(&self) -> u8 {
197        ((self.0 >> Self::NUMBER_SHIFT) & ((1 << Self::NUMBER_SIZE) - 1)) as u8
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204
205    const MAX_ENCODED_SIZE: usize = (1 << 14) - 1;
206
207    #[test]
208    fn new_with_size_preserves_maximum_14_bit_value_in_raw_encoding() {
209        let identifier = ControlCommandIdentifier::new_with_size(
210            ControlDirectionFlags::Write,
211            MAX_ENCODED_SIZE,
212            0xAB,
213            0xCD,
214        );
215        let expected = (2u32 << 30) | ((MAX_ENCODED_SIZE as u32) << 16) | (0xABu32 << 8) | 0xCD;
216
217        assert_eq!(identifier.get_size(), MAX_ENCODED_SIZE);
218        assert_eq!(identifier.raw(), expected);
219    }
220
221    #[test]
222    #[should_panic(expected = "control command size exceeds its 14-bit field")]
223    fn new_with_size_rejects_values_above_14_bit_boundary() {
224        ControlCommandIdentifier::new_with_size(
225            ControlDirectionFlags::Write,
226            MAX_ENCODED_SIZE + 1,
227            0,
228            0,
229        );
230    }
231
232    #[test]
233    fn control_direction_flag_bit_values_and_unknown_bits() {
234        assert_eq!(ControlDirectionFlags::Read.bits(), 1 << 0);
235        assert_eq!(ControlDirectionFlags::Write.bits(), 1 << 1);
236        assert_eq!(ControlDirectionFlags::all().bits(), 0b11);
237
238        assert_eq!(ControlDirectionFlags::from_bits(1 << 2), None);
239        assert_eq!(
240            ControlDirectionFlags::from_bits_truncate(0b111),
241            ControlDirectionFlags::all()
242        );
243        assert_eq!(
244            ControlDirectionFlags::from_bits_retain(1 << 2).bits(),
245            1 << 2
246        );
247    }
248}