Skip to main content

virtual_file_system/
pipe.rs

1use alloc::collections::VecDeque;
2use core::{
3    cell::RefCell,
4    task::{Context as TaskContext, Poll, Waker},
5};
6use file_system::{
7    AccessFlags, BaseOperations, Context, IoErrorKind, MountOperations, Operation, ReadyEvents,
8    Result, Size, notify_readiness,
9};
10use synchronization::blocking_mutex::{Mutex, raw::CriticalSectionRawMutex};
11
12/// Atomic write limit advertised by the native SDK's picolibc.
13pub const PIPE_BUF: usize = 512;
14
15/// Maximum simultaneous openings (including duplicates) of one pipe.
16/// Slots are reserved during open, never allocated on the I/O path.
17pub const MAX_PIPE_OPENINGS: usize = 16;
18type WakeBatch = [Option<Waker>; MAX_PIPE_OPENINGS];
19
20#[derive(Debug)]
21struct Slot {
22    access: Option<AccessFlags>,
23    waiter: Option<(Operation, Waker)>,
24}
25#[derive(Debug)]
26struct State {
27    buffer: VecDeque<u8>,
28    readers: usize,
29    writers: usize,
30    slots: [Slot; MAX_PIPE_OPENINGS],
31}
32impl State {
33    fn notify(&mut self, operation: Operation, wake: &mut WakeBatch) {
34        for (index, slot) in self.slots.iter_mut().enumerate() {
35            if slot
36                .waiter
37                .as_ref()
38                .is_some_and(|(kind, _)| *kind == operation)
39            {
40                wake[index] = slot.waiter.take().map(|(_, waker)| waker);
41            }
42        }
43    }
44}
45struct Opening {
46    access: AccessFlags,
47    slot: usize,
48}
49
50/// Bounded FIFO. Each opening owns one independent waiter registration.
51/// The final writer closing makes an empty read return EOF.
52#[derive(Debug)]
53pub struct Pipe {
54    state: Mutex<CriticalSectionRawMutex, RefCell<State>>,
55    capacity: usize,
56}
57impl Pipe {
58    pub fn new(capacity: usize) -> Self {
59        Self {
60            state: Mutex::new(RefCell::new(State {
61                buffer: VecDeque::with_capacity(capacity),
62                readers: 0,
63                writers: 0,
64                slots: core::array::from_fn(|_| Slot {
65                    access: None,
66                    waiter: None,
67                }),
68            })),
69            capacity,
70        }
71    }
72
73    pub(crate) fn open_context(&self, access: AccessFlags) -> Result<Context> {
74        // Allocate the device-owned context before entering the critical section.
75        let mut context = Context::new(Some(Opening { access, slot: 0 }));
76        let slot = self.state.lock(|state| {
77            let mut state = state.borrow_mut();
78            let slot = state
79                .slots
80                .iter()
81                .position(|slot| slot.access.is_none())
82                .ok_or(IoErrorKind::SystemFileLimit)?;
83            state.slots[slot].access = Some(access);
84            state.readers += usize::from(access.contains(AccessFlags::Read));
85            state.writers += usize::from(access.contains(AccessFlags::Write));
86            Ok::<_, IoErrorKind>(slot)
87        })?;
88        context
89            .get_private_data_mutable_of_type::<Opening>()
90            .unwrap()
91            .slot = slot;
92        notify_readiness();
93        Ok(context)
94    }
95
96    fn opening(context: &Context, required: AccessFlags) -> Result<&Opening> {
97        let opening = context
98            .get_private_data_of_type::<Opening>()
99            .ok_or(IoErrorKind::BadDescriptor)?;
100        if !opening.access.contains(required) {
101            return Err(IoErrorKind::BadDescriptor);
102        }
103        Ok(opening)
104    }
105
106    fn atomic_write_limit(&self) -> usize {
107        self.capacity.min(PIPE_BUF)
108    }
109
110    pub(crate) fn readiness(&self, access: AccessFlags, interests: ReadyEvents) -> ReadyEvents {
111        self.state.lock(|state| {
112            let state = state.borrow();
113            let mut events = ReadyEvents::empty();
114            if access.contains(AccessFlags::Read) {
115                events.set(ReadyEvents::HANGUP, state.writers == 0);
116                events.set(
117                    ReadyEvents::READ,
118                    interests.contains(ReadyEvents::READ) && !state.buffer.is_empty(),
119                );
120            }
121            if access.contains(AccessFlags::Write) {
122                events.set(ReadyEvents::ERROR, state.readers == 0);
123                events.set(
124                    ReadyEvents::WRITE,
125                    interests.contains(ReadyEvents::WRITE)
126                        && state.readers != 0
127                        && self.capacity - state.buffer.len() >= self.atomic_write_limit(),
128                );
129            }
130            events
131        })
132    }
133
134    pub(crate) fn bytes_available(&self) -> usize {
135        self.state.lock(|state| state.borrow().buffer.len())
136    }
137
138    fn transact(
139        &self,
140        kind: Operation,
141        registration: Option<(usize, &Waker)>,
142        operation: impl FnOnce(&mut State) -> Result<usize>,
143    ) -> Poll<Result<usize>> {
144        // Waker vtables are arbitrary code. Clone/drop/wake outside the lock.
145        let mut registration = registration.map(|(slot, waker)| (slot, waker.clone()));
146        let mut retired = None;
147        let mut wake: WakeBatch = core::array::from_fn(|_| None);
148        let result = self.state.lock(|state| {
149            let mut state = state.borrow_mut();
150            let result = operation(&mut state);
151            if result == Err(IoErrorKind::WouldBlock) && registration.is_some() {
152                let (slot, waker) = registration.take().unwrap();
153                retired = state.slots[slot].waiter.replace((kind, waker));
154                return Poll::Pending;
155            }
156            if let Some((slot, _)) = registration.as_ref() {
157                retired = state.slots[*slot].waiter.take();
158            }
159            if result.as_ref().is_ok_and(|count| *count > 0) {
160                state.notify(
161                    if kind == Operation::Read {
162                        Operation::Write
163                    } else {
164                        Operation::Read
165                    },
166                    &mut wake,
167                );
168            }
169            Poll::Ready(result)
170        });
171        drop(retired);
172        drop(registration);
173        for waker in wake.into_iter().flatten() {
174            waker.wake();
175        }
176        if matches!(result, Poll::Ready(Ok(count)) if count != 0) {
177            notify_readiness();
178        }
179        result
180    }
181
182    fn read_inner(
183        &self,
184        data: &mut [u8],
185        delimiter: Option<&[u8]>,
186        registration: Option<(usize, &Waker)>,
187    ) -> Poll<Result<usize>> {
188        self.transact(Operation::Read, registration, |state| {
189            if data.is_empty() {
190                return Ok(0);
191            }
192            if state.buffer.is_empty() && state.writers > 0 {
193                return Err(IoErrorKind::WouldBlock);
194            }
195            let mut length = 0;
196            while length < data.len() {
197                let Some(byte) = state.buffer.pop_front() else {
198                    break;
199                };
200                data[length] = byte;
201                length += 1;
202                if delimiter.is_some_and(|delimiter| data[..length].ends_with(delimiter)) {
203                    break;
204                }
205            }
206            Ok(length)
207        })
208    }
209
210    fn write_inner(
211        &self,
212        data: &[u8],
213        registration: Option<(usize, &Waker)>,
214    ) -> Poll<Result<usize>> {
215        self.transact(Operation::Write, registration, |state| {
216            if data.is_empty() {
217                return Ok(0);
218            }
219            if state.readers == 0 {
220                return Err(IoErrorKind::BrokenPipe);
221            }
222            let free = self.capacity - state.buffer.len();
223            if free == 0 || (data.len() <= self.atomic_write_limit() && data.len() > free) {
224                return Err(IoErrorKind::WouldBlock);
225            }
226            let length = data.len().min(free);
227            state.buffer.extend(&data[..length]);
228            Ok(length)
229        })
230    }
231}
232impl BaseOperations for Pipe {
233    fn close(&self, context: &mut Context) -> Result<()> {
234        let opening = context
235            .take_private_data_of_type::<Opening>()
236            .ok_or(IoErrorKind::BadDescriptor)?;
237        let mut retired = None;
238        let mut wake: WakeBatch = core::array::from_fn(|_| None);
239        self.state.lock(|state| {
240            let mut state = state.borrow_mut();
241            let slot = &mut state.slots[opening.slot];
242            slot.access = None;
243            retired = slot.waiter.take();
244            state.readers -= usize::from(opening.access.contains(AccessFlags::Read));
245            state.writers -= usize::from(opening.access.contains(AccessFlags::Write));
246            if state.readers == 0 {
247                state.notify(Operation::Write, &mut wake);
248            }
249            if state.writers == 0 {
250                state.notify(Operation::Read, &mut wake);
251            }
252        });
253        drop(retired);
254        for waker in wake.into_iter().flatten() {
255            waker.wake();
256        }
257        notify_readiness();
258        Ok(())
259    }
260    fn clone_context(&self, context: &Context) -> Result<Context> {
261        self.open_context(
262            context
263                .get_private_data_of_type::<Opening>()
264                .ok_or(IoErrorKind::BadDescriptor)?
265                .access,
266        )
267    }
268    fn cancel_operation(&self, context: &mut Context, operation: Operation) {
269        let Some(opening) = context.get_private_data_of_type::<Opening>() else {
270            return;
271        };
272        let retired = self.state.lock(|state| {
273            let mut state = state.borrow_mut();
274            let slot = &mut state.slots[opening.slot];
275            if slot
276                .waiter
277                .as_ref()
278                .is_some_and(|(kind, _)| *kind == operation)
279            {
280                slot.waiter.take()
281            } else {
282                None
283            }
284        });
285        drop(retired);
286    }
287
288    fn read(
289        &self,
290        context: &mut Context,
291        cx: &mut TaskContext<'_>,
292        data: &mut [u8],
293        _: Size,
294    ) -> Poll<Result<usize>> {
295        let opening = Self::opening(context, AccessFlags::Read)?;
296        self.read_inner(data, None, Some((opening.slot, cx.waker())))
297    }
298    fn read_until(
299        &self,
300        context: &mut Context,
301        cx: &mut TaskContext<'_>,
302        data: &mut [u8],
303        _: Size,
304        delimiter: &[u8],
305    ) -> Poll<Result<usize>> {
306        let opening = Self::opening(context, AccessFlags::Read)?;
307        if delimiter.is_empty() {
308            return Poll::Ready(Err(IoErrorKind::InvalidArgument));
309        }
310        self.read_inner(data, Some(delimiter), Some((opening.slot, cx.waker())))
311    }
312    fn write(
313        &self,
314        context: &mut Context,
315        cx: &mut TaskContext<'_>,
316        data: &[u8],
317        _: Size,
318    ) -> Poll<Result<usize>> {
319        let opening = Self::opening(context, AccessFlags::Write)?;
320        self.write_inner(data, Some((opening.slot, cx.waker())))
321    }
322}
323impl MountOperations for Pipe {}
324
325#[cfg(test)]
326mod regression_tests {
327    extern crate std;
328    use super::*;
329    #[test]
330    fn short_read_does_not_pop_beyond_available_bytes() {
331        let pipe = Pipe::new(4);
332        let mut reader = pipe.open_context(AccessFlags::Read).unwrap();
333        let mut writer = pipe.open_context(AccessFlags::Write).unwrap();
334        assert_eq!(pipe.write_sync(&mut writer, b"hi", 0).unwrap(), 2);
335        let mut output = [0; 8];
336        assert_eq!(pipe.read_sync(&mut reader, &mut output, 0).unwrap(), 2);
337        assert_eq!(&output[..2], b"hi");
338    }
339    #[test]
340    fn writes_are_bounded_by_the_configured_capacity() {
341        let pipe = Pipe::new(4);
342        let _reader = pipe.open_context(AccessFlags::Read).unwrap();
343        let mut writer = pipe.open_context(AccessFlags::Write).unwrap();
344        assert_eq!(pipe.write_sync(&mut writer, b"abcdef", 0).unwrap(), 4);
345        assert_eq!(
346            pipe.write_sync(&mut writer, b"x", 0),
347            Err(IoErrorKind::WouldBlock)
348        );
349    }
350    #[test]
351    fn eof_waits_for_every_writer_and_preserves_buffered_data() {
352        let pipe = Pipe::new(4);
353        let mut reader = pipe.open_context(AccessFlags::Read).unwrap();
354        let mut writer = pipe.open_context(AccessFlags::Write).unwrap();
355        let mut duplicate = pipe.clone_context(&writer).unwrap();
356        assert_eq!(
357            pipe.read_sync(&mut reader, &mut [0; 1], 0),
358            Err(IoErrorKind::WouldBlock)
359        );
360        pipe.write_sync(&mut writer, b"hi", 0).unwrap();
361        pipe.close(&mut writer).unwrap();
362        let mut output = [0; 8];
363        assert_eq!(pipe.read_sync(&mut reader, &mut output, 0).unwrap(), 2);
364        assert_eq!(
365            pipe.read_sync(&mut reader, &mut output, 0),
366            Err(IoErrorKind::WouldBlock)
367        );
368        pipe.close(&mut duplicate).unwrap();
369        assert_eq!(pipe.read_sync(&mut reader, &mut output, 0).unwrap(), 0);
370        pipe.close(&mut reader).unwrap();
371        let mut writer = pipe.open_context(AccessFlags::Write).unwrap();
372        assert_eq!(
373            pipe.write_sync(&mut writer, b"x", 0),
374            Err(IoErrorKind::BrokenPipe)
375        );
376    }
377}
378
379#[cfg(test)]
380#[allow(
381    clippy::disallowed_types,
382    reason = "host-only waker tests use std::task::Wake and std atomics"
383)]
384#[path = "pipe_tests.rs"]
385mod polling_tests;