drivers_peripherals/
device.rs1use 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
14pub trait PeripheralHandle: Send {
25 fn read(&mut self, buffer: &mut [u8]) -> Result<usize>;
27
28 fn write(&mut self, buffer: &[u8]) -> Result<usize>;
30
31 fn flush(&mut self) -> Result<()> {
33 Ok(())
34 }
35
36 fn control(
38 &mut self,
39 _command: ControlCommandIdentifier,
40 _input: &AnyByLayout,
41 _output: &mut AnyByLayout,
42 ) -> Result<()> {
43 Err(IoErrorKind::Unsupported)
44 }
45}
46
47struct Opening;
50
51pub 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 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 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}