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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
//
// Copyright 2023, Colias Group, LLC
//
// SPDX-License-Identifier: BSD-2-Clause
//

use core::alloc::Layout;
use core::task::{Poll, Waker};

use sel4_async_block_io::{access::Access, Operation};
use sel4_bounce_buffer_allocator::{AbstractBounceBufferAllocator, BounceBufferAllocator};
use sel4_externally_shared::ExternallySharedRef;
use sel4_shared_ring_buffer::{
    roles::Provide, Descriptor, PeerMisbehaviorError as SharedRingBuffersPeerMisbehaviorError,
    RingBuffers,
};
use sel4_shared_ring_buffer_block_io_types::{
    BlockIORequest, BlockIORequestStatus, BlockIORequestType,
};
use sel4_shared_ring_buffer_bookkeeping::{slot_set_semaphore::*, slot_tracker::*};

pub use crate::errors::{Error, ErrorOrUserError, IOError, PeerMisbehaviorError, UserError};

pub struct OwnedSharedRingBufferBlockIO<S, A, F> {
    dma_region: ExternallySharedRef<'static, [u8]>,
    bounce_buffer_allocator: BounceBufferAllocator<A>,
    ring_buffers: RingBuffers<'static, Provide, F, BlockIORequest>,
    requests: SlotTracker<StateTypesImpl>,
    slot_set_semaphore: SlotSetSemaphore<S, NUM_SLOT_POOLS>,
}

const RING_BUFFERS_SLOT_POOL_INDEX: usize = 0;
const REQUESTS_SLOT_POOL_INDEX: usize = 1;
const NUM_SLOT_POOLS: usize = 2;

enum StateTypesImpl {}

impl SlotStateTypes for StateTypesImpl {
    type Common = ();
    type Free = ();
    type Occupied = Occupied;
}

struct Occupied {
    req: BlockIORequest,
    state: OccupiedState,
}

enum OccupiedState {
    Pending { waker: Option<Waker> },
    Canceled,
    Complete { error: Option<IOError> },
}

pub enum IssueRequestBuf<'a> {
    Read { len: usize },
    Write { buf: &'a [u8] },
}

impl<'a> IssueRequestBuf<'a> {
    pub fn new<A: Access>(operation: &'a Operation<'a, A>) -> Self {
        match operation {
            Operation::Read { buf, .. } => Self::Read { len: buf.len() },
            Operation::Write { buf, .. } => Self::Write { buf },
        }
    }

    fn len(&self) -> usize {
        match self {
            Self::Read { len } => *len,
            Self::Write { buf } => buf.len(),
        }
    }

    fn ty(&self) -> BlockIORequestType {
        match self {
            Self::Read { .. } => BlockIORequestType::Read,
            Self::Write { .. } => BlockIORequestType::Write,
        }
    }
}

pub enum PollRequestBuf<'a> {
    Read { buf: &'a mut [u8] },
    Write,
}

impl<'a> PollRequestBuf<'a> {
    pub fn new<'b, A: Access>(operation: &'a mut Operation<'b, A>) -> Self
    where
        'b: 'a,
    {
        match operation {
            Operation::Read { buf, .. } => Self::Read { buf },
            Operation::Write { .. } => Self::Write,
        }
    }
}

impl<S: SlotSemaphore, A: AbstractBounceBufferAllocator, F: FnMut()>
    OwnedSharedRingBufferBlockIO<S, A, F>
{
    pub fn new(
        dma_region: ExternallySharedRef<'static, [u8]>,
        bounce_buffer_allocator: BounceBufferAllocator<A>,
        mut ring_buffers: RingBuffers<'static, Provide, F, BlockIORequest>,
    ) -> Self {
        assert!(ring_buffers.free_mut().is_empty().unwrap());
        assert!(ring_buffers.used_mut().is_empty().unwrap());
        let n = ring_buffers.free().capacity();
        Self {
            dma_region,
            bounce_buffer_allocator,
            ring_buffers,
            requests: SlotTracker::new_with_capacity((), (), n),
            slot_set_semaphore: SlotSetSemaphore::new([n, n]),
        }
    }

    pub fn slot_set_semaphore(&self) -> &SlotSetSemaphoreHandle<S, NUM_SLOT_POOLS> {
        self.slot_set_semaphore.handle()
    }

    fn report_current_num_free_current_num_free_ring_buffers_slots(
        &mut self,
    ) -> Result<(), ErrorOrUserError> {
        let current_num_free = self.requests.num_free();
        self.slot_set_semaphore
            .report_current_num_free_slots(RING_BUFFERS_SLOT_POOL_INDEX, current_num_free)
            .unwrap();
        Ok(())
    }

    fn report_current_num_free_current_num_free_requests_slots(
        &mut self,
    ) -> Result<(), ErrorOrUserError> {
        let current_num_free = self.ring_buffers.free_mut().num_empty_slots()?;
        self.slot_set_semaphore
            .report_current_num_free_slots(REQUESTS_SLOT_POOL_INDEX, current_num_free)
            .unwrap();
        Ok(())
    }

    fn can_issue_requests(
        &mut self,
        n: usize,
    ) -> Result<bool, SharedRingBuffersPeerMisbehaviorError> {
        let can =
            self.ring_buffers.free_mut().num_empty_slots()? >= n && self.requests.num_free() >= n;
        Ok(can)
    }

    pub fn issue_read_request(
        &mut self,
        reservation: &mut SlotSetReservation<'_, S, NUM_SLOT_POOLS>,
        start_block_idx: u64,
        num_bytes: usize,
    ) -> Result<usize, ErrorOrUserError> {
        self.issue_request(
            reservation,
            start_block_idx,
            &mut IssueRequestBuf::Read { len: num_bytes },
        )
    }

    pub fn issue_write_request(
        &mut self,
        reservation: &mut SlotSetReservation<'_, S, NUM_SLOT_POOLS>,
        start_block_idx: u64,
        buf: &[u8],
    ) -> Result<usize, ErrorOrUserError> {
        self.issue_request(
            reservation,
            start_block_idx,
            &mut IssueRequestBuf::Write { buf },
        )
    }

    pub fn issue_request(
        &mut self,
        reservation: &mut SlotSetReservation<'_, S, NUM_SLOT_POOLS>,
        start_block_idx: u64,
        buf: &mut IssueRequestBuf,
    ) -> Result<usize, ErrorOrUserError> {
        if reservation.count() < 1 {
            return Err(UserError::TooManyOutstandingRequests.into());
        }

        assert!(self.can_issue_requests(1)?);

        let request_index = self.requests.peek_next_free_index().unwrap();

        let range = self
            .bounce_buffer_allocator
            .allocate(Layout::from_size_align(buf.len(), 1).unwrap())
            .map_err(|_| Error::BounceBufferAllocationError)?;

        if let IssueRequestBuf::Write { buf } = buf {
            self.dma_region
                .as_mut_ptr()
                .index(range.clone())
                .copy_from_slice(buf);
        }

        let req = BlockIORequest::new(
            BlockIORequestStatus::Pending,
            buf.ty(),
            start_block_idx.try_into().unwrap(),
            Descriptor::from_encoded_addr_range(range, request_index),
        );

        self.requests
            .occupy(Occupied {
                req,
                state: OccupiedState::Pending { waker: None },
            })
            .unwrap();

        self.ring_buffers
            .free_mut()
            .enqueue_and_commit(req)?
            .unwrap();

        self.ring_buffers.notify_mut();

        self.slot_set_semaphore.consume(reservation, 1).unwrap();

        Ok(request_index)
    }

    pub fn cancel_request(&mut self, request_index: usize) -> Result<(), ErrorOrUserError> {
        let state_value = self.requests.get_state_value_mut(request_index)?;
        let occupied = state_value.as_occupied()?;
        match &occupied.state {
            OccupiedState::Pending { .. } => {
                occupied.state = OccupiedState::Canceled;
            }
            OccupiedState::Complete { .. } => {
                let range = occupied.req.buf().encoded_addr_range();
                self.bounce_buffer_allocator.deallocate(range);
                self.requests.free(request_index, ()).unwrap();
                self.report_current_num_free_current_num_free_requests_slots()?;
            }
            _ => {
                return Err(UserError::RequestStateMismatch.into());
            }
        }
        Ok(())
    }

    pub fn poll_read_request(
        &mut self,
        request_index: usize,
        buf: &mut [u8],
        waker: Option<Waker>,
    ) -> Result<Poll<Result<(), IOError>>, ErrorOrUserError> {
        self.poll_request(request_index, &mut PollRequestBuf::Read { buf }, waker)
    }

    pub fn poll_write_request(
        &mut self,
        request_index: usize,
        waker: Option<Waker>,
    ) -> Result<Poll<Result<(), IOError>>, ErrorOrUserError> {
        self.poll_request(request_index, &mut PollRequestBuf::Write, waker)
    }

    pub fn poll_request(
        &mut self,
        request_index: usize,
        buf: &mut PollRequestBuf,
        waker: Option<Waker>,
    ) -> Result<Poll<Result<(), IOError>>, ErrorOrUserError> {
        let state_value = self.requests.get_state_value_mut(request_index)?;
        let occupied = state_value.as_occupied()?;

        Ok(match &mut occupied.state {
            OccupiedState::Pending {
                waker: ref mut waker_slot,
            } => {
                if let Some(waker) = waker {
                    waker_slot.replace(waker);
                }
                Poll::Pending
            }
            OccupiedState::Complete { error } => {
                let val = match error {
                    None => Ok(()),
                    Some(err) => Err(err.clone()),
                };

                let range = occupied.req.buf().encoded_addr_range();

                match buf {
                    PollRequestBuf::Read { buf } => {
                        self.dma_region
                            .as_mut_ptr()
                            .index(range.clone())
                            .copy_into_slice(buf);
                    }
                    PollRequestBuf::Write => {}
                }

                self.bounce_buffer_allocator.deallocate(range);

                self.requests.free(request_index, ()).unwrap();
                self.report_current_num_free_current_num_free_requests_slots()?;

                Poll::Ready(val)
            }
            _ => {
                return Err(UserError::RequestStateMismatch.into());
            }
        })
    }

    pub fn poll(&mut self) -> Result<bool, ErrorOrUserError> {
        self.report_current_num_free_current_num_free_ring_buffers_slots()?;

        let mut notify = false;

        while let Some(completed_req) = self.ring_buffers.used_mut().dequeue()? {
            let request_index = completed_req.buf().cookie();

            let state_value = self
                .requests
                .get_state_value_mut(request_index)
                .map_err(|_| PeerMisbehaviorError::OutOfBoundsCookie)?;

            let occupied = state_value
                .as_occupied()
                .map_err(|_| PeerMisbehaviorError::StateMismatch)?;

            {
                let mut observed_request = completed_req;
                observed_request.set_status(BlockIORequestStatus::Pending);
                if observed_request != occupied.req {
                    return Err(PeerMisbehaviorError::DescriptorMismatch.into());
                }
            }

            match &mut occupied.state {
                OccupiedState::Pending { waker } => {
                    let waker = waker.take();

                    let status = completed_req
                        .status()
                        .map_err(|_| PeerMisbehaviorError::InvalidDescriptor)?;

                    occupied.state = OccupiedState::Complete {
                        error: match status {
                            BlockIORequestStatus::Pending => {
                                return Err(PeerMisbehaviorError::InvalidDescriptor.into());
                            }
                            BlockIORequestStatus::Ok => None,
                            BlockIORequestStatus::IOError => Some(IOError),
                        },
                    };

                    if let Some(waker) = waker {
                        waker.wake();
                    }
                }
                OccupiedState::Canceled => {
                    let range = occupied.req.buf().encoded_addr_range();
                    self.bounce_buffer_allocator.deallocate(range);
                    self.requests.free(request_index, ()).unwrap();
                    self.report_current_num_free_current_num_free_requests_slots()?;
                }
                _ => {
                    return Err(UserError::RequestStateMismatch.into());
                }
            }

            notify = true;
        }

        if notify {
            self.ring_buffers.notify_mut();
        }

        Ok(notify)
    }
}