Skip to main content

drivers_peripherals/
device.rs

1//! Generic character-device wrapper around a peripheral handle.
2
3use core::task::Poll;
4use portable_atomic::{AtomicBool, Ordering};
5
6use alloc::boxed::Box;
7use file_system::{
8    BaseOperations, CharacterDevice, Context, ControlCommandIdentifier, IoErrorKind,
9    MountOperations, Result, Size, ready,
10};
11use shared::AnyByLayout;
12use synchronization::{blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex};
13
14/// Class-specific handle wrapped by [`PeripheralDevice`].
15///
16/// Every method is a single synchronous attempt. It must return promptly
17/// without waiting for hardware, because it runs on the executor. A peripheral
18/// that would have to wait returns `IoErrorKind::WouldBlock` (for example when a
19/// UART reports `WouldBlock`), and the caller decides whether to retry. Callers
20/// do not retain buffers past the call.
21///
22/// `control` forwards command identifiers that the class defined itself. The
23/// base never interprets them.
24pub trait PeripheralHandle: Send {
25    /// Read available bytes into `buffer`. `Ok(0)` means end of stream.
26    fn read(&mut self, buffer: &mut [u8]) -> Result<usize>;
27
28    /// Write bytes from `buffer` and return the number accepted.
29    fn write(&mut self, buffer: &[u8]) -> Result<usize>;
30
31    /// Push queued output without waiting for the device to drain, if supported.
32    fn flush(&mut self) -> Result<()> {
33        Ok(())
34    }
35
36    /// Class-defined control. The default rejects every command.
37    fn control(
38        &mut self,
39        _command: ControlCommandIdentifier,
40        _input: &AnyByLayout,
41        _output: &mut AnyByLayout,
42    ) -> Result<()> {
43        Err(IoErrorKind::Unsupported)
44    }
45}
46
47/// Marker stored in an opening's `Context`. Only the context that acquired the
48/// device carries it, so closing a cloned context cannot release the device.
49struct Opening;
50
51/// Character device exposing a [`PeripheralHandle`] through the VFS polling contract.
52///
53/// Opening is exclusive: while one opening is held, another `open` returns
54/// `IoErrorKind::ResourceBusy`. The exclusivity is released by `close` on the
55/// opening's own context. A context created by `clone_context` does not own
56/// the device. Read, write, flush and control never return `Pending`; they run
57/// once through `ready` and return `WouldBlock` if the handle is in use.
58/// Reads and writes ignore the absolute position because the device is a stream.
59pub struct PeripheralDevice<H> {
60    opened: AtomicBool,
61    handle: Mutex<CriticalSectionRawMutex, H>,
62}
63
64impl<H: PeripheralHandle> PeripheralDevice<H> {
65    pub const fn new(handle: H) -> Self {
66        Self {
67            opened: AtomicBool::new(false),
68            handle: Mutex::new(handle),
69        }
70    }
71
72    /// Runs `operation` on the handle once, without waiting for the lock.
73    fn with_handle<R>(&self, operation: impl FnOnce(&mut H) -> Result<R>) -> Result<R> {
74        let mut handle = self
75            .handle
76            .try_lock()
77            .map_err(|_| IoErrorKind::WouldBlock)?;
78        operation(&mut handle)
79    }
80}
81
82impl<H: PeripheralHandle> BaseOperations for PeripheralDevice<H> {
83    fn open(&self, context: &mut Context) -> Result<()> {
84        self.opened
85            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
86            .map_err(|_| IoErrorKind::ResourceBusy)?;
87        context.set_private_data(Box::new(Opening));
88        Ok(())
89    }
90
91    fn close(&self, context: &mut Context) -> Result<()> {
92        if context.take_private_data_of_type::<Opening>().is_some() {
93            self.opened.store(false, Ordering::Release);
94        }
95        Ok(())
96    }
97
98    fn read(
99        &self,
100        _: &mut Context,
101        _cx: &mut core::task::Context<'_>,
102        buffer: &mut [u8],
103        _absolute_position: Size,
104    ) -> Poll<Result<usize>> {
105        ready(|| self.with_handle(|handle| handle.read(buffer)))
106    }
107
108    fn write(
109        &self,
110        _: &mut Context,
111        _cx: &mut core::task::Context<'_>,
112        buffer: &[u8],
113        _absolute_position: Size,
114    ) -> Poll<Result<usize>> {
115        ready(|| self.with_handle(|handle| handle.write(buffer)))
116    }
117
118    fn flush(&self, _: &mut Context, _cx: &mut core::task::Context<'_>) -> Poll<Result<()>> {
119        ready(|| self.with_handle(|handle| handle.flush()))
120    }
121
122    fn control(
123        &self,
124        _: &mut Context,
125        _cx: &mut core::task::Context<'_>,
126        command: ControlCommandIdentifier,
127        input: &AnyByLayout,
128        output: &mut AnyByLayout,
129    ) -> Poll<Result<()>> {
130        ready(|| self.with_handle(|handle| handle.control(command, input, output)))
131    }
132
133    fn clone_context(&self, _: &Context) -> Result<Context> {
134        Ok(Context::new_empty())
135    }
136}
137
138impl<H: PeripheralHandle> MountOperations for PeripheralDevice<H> {}
139
140impl<H: PeripheralHandle> CharacterDevice for PeripheralDevice<H> {}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145    use core::task::Waker;
146
147    #[derive(Default)]
148    struct Sink {
149        written: usize,
150    }
151
152    impl PeripheralHandle for Sink {
153        fn read(&mut self, buffer: &mut [u8]) -> Result<usize> {
154            buffer.fill(0);
155            Ok(buffer.len())
156        }
157
158        fn write(&mut self, buffer: &[u8]) -> Result<usize> {
159            self.written += buffer.len();
160            Ok(buffer.len())
161        }
162    }
163
164    #[test]
165    fn open_is_exclusive_and_only_the_owning_context_releases_it() {
166        let device = PeripheralDevice::new(Sink::default());
167        let mut owner = Context::new_empty();
168        let mut clone = device.clone_context(&owner).unwrap();
169
170        device.open(&mut owner).unwrap();
171        assert_eq!(
172            device.open(&mut Context::new_empty()),
173            Err(IoErrorKind::ResourceBusy)
174        );
175
176        // Closing a context that does not own the opening keeps the device held.
177        device.close(&mut clone).unwrap();
178        assert_eq!(
179            device.open(&mut Context::new_empty()),
180            Err(IoErrorKind::ResourceBusy)
181        );
182
183        device.close(&mut owner).unwrap();
184        device.open(&mut Context::new_empty()).unwrap();
185    }
186
187    #[test]
188    fn read_and_write_run_once_and_never_pend() {
189        let device = PeripheralDevice::new(Sink::default());
190        let mut context = Context::new_empty();
191        let mut cx = core::task::Context::from_waker(Waker::noop());
192        let mut buffer = [1u8; 3];
193
194        assert_eq!(
195            device.read(&mut context, &mut cx, &mut buffer, 0),
196            Poll::Ready(Ok(3))
197        );
198        assert_eq!(buffer, [0; 3]);
199        assert_eq!(
200            device.write(&mut context, &mut cx, b"abcd", 0),
201            Poll::Ready(Ok(4))
202        );
203        assert_eq!(device.with_handle(|handle| Ok(handle.written)), Ok(4));
204    }
205}