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
//! This module provides interface to wrap a stackful synchronous code into an
//! asynchronous command loop.
//!
//! **NOTE** This module documentation should be viewed as a continuation of
//! [the `drone_core` documentation](drone_core::proc_loop).
//!
//! To provide an example, imagine a C library for FAT32 file system. Here is
//! how it could be wrapped:
//!
//! ```
//! # #![feature(never_type)]
//! use core::{future::Future, pin::Pin, slice};
//! use drone_core::ffi::{c_char, CString};
//! use drone_cortex_m::{
//!     proc_loop::{self, Context as _, ProcLoop, Sess as _},
//!     sv,
//! };
//! use futures::prelude::*;
//!
//! use drone_cortex_m::sv::{SwitchBackService, SwitchContextService};
//!
//! // Stackful fibers need a supervisor.
//! sv! {
//!     pub struct Sv;
//!     static SERVICES;
//!
//!     // These services are required for stackful fibers.
//!     SwitchContextService;
//!     SwitchBackService;
//! }
//!
//! // Here is the library API.
//! extern "C" {
//!     fn f_read(name: *const c_char, buf: *mut u8, count: u32) -> u32;
//!     fn f_write(name: *const c_char, buf: *const u8, count: u32) -> u32;
//! }
//!
//! // The library is expecting to be linked with the following two function.
//!
//! #[no_mangle]
//! pub extern "C" fn disk_read(buf: *mut u8, sector: u32, count: u32) -> u32 {
//!     // We need to recreate the Yielder with correct type parameters.
//!     let yielder = unsafe { proc_loop::Yielder::<Sv, FatfsRes>::new() };
//!     // Redirect the request to the command loop. This call is blocking.
//!     let req_res = yielder.req(Req::DiskRead { buf, sector, count });
//!     // The result variant must correspond to the request variant.
//!     unsafe { req_res.disk_read }
//! }
//!
//! #[no_mangle]
//! pub extern "C" fn disk_write(buf: *const u8, sector: u32, count: u32) -> u32 {
//!     let yielder = unsafe { proc_loop::Yielder::<Sv, FatfsRes>::new() };
//!     let req_res = yielder.req(Req::DiskWrite { buf, sector, count });
//!     // The result variant must correspond to the request variant.
//!     unsafe { req_res.disk_write }
//! }
//!
//! // We need to map the two functions above to the corresponding functions below.
//!
//! pub async fn disk_read_async(buf: &mut [u8], sector: u32) -> u32 {
//!     // Serve `disk_read` asynchronously.
//!     unimplemented!()
//! }
//!
//! pub async fn disk_write_async(buf: &[u8], sector: u32) -> u32 {
//!     // Serve `disk_write` asynchronously.
//!     unimplemented!()
//! }
//!
//! // All possible commands. We can use only `'static` lifetimes here. That is
//! // why we use `*const str`, `*const [u8]`, `*mut [u8]` instead of `&str`,
//! // `&[u8]`, `&mut [u8]`.
//! pub enum Cmd {
//!     Read { name: *const str, buf: *mut [u8] },
//!     Write { name: *const str, buf: *const [u8] },
//! }
//!
//! // Results for each of the commands above.
//! pub union CmdRes {
//!     pub read: u32,
//!     pub write: u32,
//! }
//!
//! // All possible requests used by `disk_read` and `disk_write` functions above.
//! pub enum Req {
//!     DiskRead {
//!         buf: *mut u8,
//!         sector: u32,
//!         count: u32,
//!     },
//!     DiskWrite {
//!         buf: *const u8,
//!         sector: u32,
//!         count: u32,
//!     },
//! }
//!
//! // Results for each of the requests above.
//! pub union ReqRes {
//!     pub disk_read: u32,
//!     pub disk_write: u32,
//! }
//!
//! // The use of raw pointers requires this.
//! unsafe impl Send for Cmd {}
//! unsafe impl Send for Req {}
//!
//! // This type will never be instantiated. It is used only to define associated
//! // items with `ProcLoop` trait.
//! pub struct FatfsRes;
//!
//! // This is the type that implements the high-level API of our library.
//! pub struct FatfsSess<'sess>(&'sess mut proc_loop::Fiber<Sv, FatfsRes>);
//!
//! impl ProcLoop for FatfsRes {
//!     type Context = proc_loop::Yielder<Sv, FatfsRes>;
//!     type Cmd = Cmd;
//!     type CmdRes = CmdRes;
//!     type Req = Req;
//!     type ReqRes = ReqRes;
//!
//!     const STACK_SIZE: usize = 0x800;
//!
//!     fn run_cmd(cmd: Cmd, _context: Self::Context) -> CmdRes {
//!         match cmd {
//!             Cmd::Read { name, buf } => {
//!                 // Rebind lifetimes for the raw pointers.
//!                 let name = unsafe { &*buf };
//!                 let buf = unsafe { &mut *buf };
//!                 // Call the library function synchronously. This will block.
//!                 let read = unsafe {
//!                     f_read(
//!                         CString::new(name).unwrap().as_ptr(),
//!                         buf.as_mut_ptr(),
//!                         buf.len() as u32,
//!                     )
//!                 };
//!                 // The result variant must correspond to the command variant.
//!                 CmdRes { read }
//!             }
//!             Cmd::Write { name, buf } => {
//!                 let name = unsafe { &*buf };
//!                 let buf = unsafe { &*buf };
//!                 let write = unsafe {
//!                     f_write(
//!                         CString::new(name).unwrap().as_ptr(),
//!                         buf.as_ptr(),
//!                         buf.len() as u32,
//!                     )
//!                 };
//!                 // The result variant must correspond to the command variant.
//!                 CmdRes { write }
//!             }
//!         }
//!     }
//! }
//!
//! impl proc_loop::Sess for FatfsSess<'_> {
//!     type ProcLoop = FatfsRes;
//!     type Fiber = proc_loop::Fiber<Sv, FatfsRes>;
//!     type Error = !;
//!
//!     fn fib(&mut self) -> Pin<&mut Self::Fiber> {
//!         Pin::new(self.0)
//!     }
//!
//!     fn run_req(
//!         &mut self,
//!         req: <Self::ProcLoop as ProcLoop>::Req,
//!     ) -> Pin<
//!         Box<
//!             dyn Future<Output = Result<<Self::ProcLoop as ProcLoop>::ReqRes, Self::Error>>
//!                 + Send
//!                 + '_,
//!         >,
//!     > {
//!         match req {
//!             Req::DiskRead { buf, sector, count } => {
//!                 let slice = unsafe { slice::from_raw_parts_mut(buf, count as usize) };
//!                 Box::pin(disk_read_async(slice, sector).map(|disk_read| {
//!                     // The result variant must correspond to the request variant.
//!                     Ok(ReqRes { disk_read })
//!                 }))
//!             }
//!             Req::DiskWrite { buf, sector, count } => {
//!                 let slice = unsafe { slice::from_raw_parts(buf, count as usize) };
//!                 Box::pin(disk_write_async(slice, sector).map(|disk_write| {
//!                     // The result variant must correspond to the request variant.
//!                     Ok(ReqRes { disk_write })
//!                 }))
//!             }
//!         }
//!     }
//! }
//!
//! // The high-level API to our library.
//! impl FatfsSess<'_> {
//!     pub async fn read<'a>(&'a mut self, name: &'a str, buf: &'a mut [u8]) -> Result<u32, !> {
//!         let res = self.cmd(Cmd::Read { name, buf }).await?;
//!         // The result variant must correspond to the command variant.
//!         Ok(unsafe { res.read })
//!     }
//!
//!     pub async fn write<'a>(&'a mut self, name: &'a str, buf: &'a [u8]) -> Result<u32, !> {
//!         let res = self.cmd(Cmd::Write { name, buf }).await?;
//!         // The result variant must correspond to the command variant.
//!         Ok(unsafe { res.write })
//!     }
//! }
//!
//! // Here is how we use the defined command loop in asynchronous context.
//! # fn main() {
//! async {
//!     let mut fatfs_proc = proc_loop::Fiber::<Sv, FatfsRes>::new();
//!     let mut fatfs_sess = FatfsSess(&mut fatfs_proc);
//!     let mut buf = [0; 10];
//!     fatfs_sess.read("file1.txt", &mut buf).await?;
//!     fatfs_sess.write("file2.txt", b"hello there!\n").await?;
//!     Ok::<(), !>(())
//! };
//! # }
//! ```

#[doc(no_inline)]
pub use drone_core::proc_loop::*;

use crate::{
    fib::{self, FiberState},
    sv::{SvCall, SwitchBackService, SwitchContextService},
};
use core::pin::Pin;

type InnerYielder<Sv, T> = fib::Yielder<Sv, InnerIn<T>, InnerOut<T>, !>;
type InnerFiber<Sv, T> = fib::FiberProc<Sv, InnerIn<T>, InnerOut<T>, !, CmdLoop<Sv, T>>;
type InnerIn<T> = In<<T as ProcLoop>::Cmd, <T as ProcLoop>::ReqRes>;
type InnerOut<T> = Out<<T as ProcLoop>::Req, <T as ProcLoop>::CmdRes>;
type CmdLoop<Sv, T> =
    fn(In<<T as ProcLoop>::Cmd, <T as ProcLoop>::ReqRes>, InnerYielder<Sv, T>) -> !;

/// A wrapper for [`fib::FiberProc`] that runs the command loop `T`.
pub struct Fiber<Sv, T>(InnerFiber<Sv, T>)
where
    Sv: SvCall<SwitchBackService>,
    Sv: SvCall<SwitchContextService>,
    T: ProcLoop<Context = Yielder<Sv, T>>;

/// Yielder for [`Fiber`]'s [`fib::FiberProc`].
pub struct Yielder<Sv, T>(InnerYielder<Sv, T>)
where
    Sv: SvCall<SwitchBackService>,
    Sv: SvCall<SwitchContextService>,
    T: ProcLoop<Context = Self>;

#[allow(clippy::new_without_default)]
impl<Sv, T> Fiber<Sv, T>
where
    Sv: SvCall<SwitchBackService>,
    Sv: SvCall<SwitchContextService>,
    T: ProcLoop<Context = Yielder<Sv, T>>,
{
    /// Creates a new command loop for `T`.
    ///
    /// # Panics
    ///
    /// If MPU is not present.
    pub fn new() -> Self {
        unsafe { Self::new_with(fib::new_proc) }
    }

    /// Creates a new command loop for `T`, without MPU.
    ///
    /// # Safety
    ///
    /// Unprotected from stack overflow.
    pub unsafe fn new_unchecked() -> Self {
        Self::new_with(fib::new_proc_unchecked)
    }

    unsafe fn new_with(f: unsafe fn(usize, CmdLoop<Sv, T>) -> InnerFiber<Sv, T>) -> Self {
        T::on_create();
        Self(f(T::STACK_SIZE, Self::cmd_loop))
    }

    fn cmd_loop(mut input: In<T::Cmd, T::ReqRes>, yielder: InnerYielder<Sv, T>) -> ! {
        T::on_enter();
        loop {
            input = yielder.proc_yield(Out::CmdRes(T::run_cmd(
                unsafe { input.into_cmd() },
                Yielder(yielder),
            )));
        }
    }
}

impl<Sv, T> Drop for Fiber<Sv, T>
where
    Sv: SvCall<SwitchBackService>,
    Sv: SvCall<SwitchContextService>,
    T: ProcLoop<Context = Yielder<Sv, T>>,
{
    fn drop(&mut self) {
        T::on_drop();
    }
}

impl<Sv, T> fib::Fiber for Fiber<Sv, T>
where
    Sv: SvCall<SwitchBackService>,
    Sv: SvCall<SwitchContextService>,
    T: ProcLoop<Context = Yielder<Sv, T>>,
{
    type Input = InnerIn<T>;
    type Yield = InnerOut<T>;
    type Return = !;

    #[inline]
    fn resume(mut self: Pin<&mut Self>, input: InnerIn<T>) -> FiberState<InnerOut<T>, !> {
        Pin::new(&mut self.0).resume(input)
    }
}

impl<Sv, T> Context<T::Req, T::ReqRes> for Yielder<Sv, T>
where
    Sv: SvCall<SwitchBackService>,
    Sv: SvCall<SwitchContextService>,
    T: ProcLoop<Context = Self>,
{
    #[inline]
    unsafe fn new() -> Self {
        Self(fib::Yielder::new())
    }

    #[inline]
    fn req(self, req: T::Req) -> T::ReqRes {
        unsafe { self.0.proc_yield(Out::Req(req)).into_req_res() }
    }
}

impl<Sv, T> Clone for Yielder<Sv, T>
where
    Sv: SvCall<SwitchBackService>,
    Sv: SvCall<SwitchContextService>,
    T: ProcLoop<Context = Self>,
{
    fn clone(&self) -> Self {
        unsafe { Self::new() }
    }
}

impl<Sv, T> Copy for Yielder<Sv, T>
where
    Sv: SvCall<SwitchBackService>,
    Sv: SvCall<SwitchContextService>,
    T: ProcLoop<Context = Self>,
{
}