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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! A bbqueue based collection of single- and double- ended, async/await
//! byte buffer queues.
//!
//! This extends the underlying bbqueue type exposed by the ABI crate, allowing
//! for async kernel-to-kernel (including driver services) usage.

use core::ops::{Deref, DerefMut};

use crate::fmt;
use abi::bbqueue_ipc::{BBBuffer, Consumer as InnerConsumer, Producer as InnerProducer};
use abi::bbqueue_ipc::{GrantR as InnerGrantR, GrantW as InnerGrantW};
use maitake::sync::Mutex;
use maitake::sync::WaitCell;
use mnemos_alloc::containers::{Arc, ArrayBuf};
use tracing::{self, info, trace};

struct BBQStorage {
    commit_waitcell: WaitCell,
    release_waitcell: WaitCell,
    // note: producer lives here so we don't need a separate Arc just for the
    // Mutex<InnerProducer>. consumer is owned by the consumer handle.
    producer: Mutex<Option<InnerProducer<'static>>>,

    ring: BBBuffer,
    _array: ArrayBuf<u8>,
}

pub struct BidiHandle {
    producer: SpscProducer,
    consumer: Consumer,
}

impl BidiHandle {
    pub fn producer(&self) -> &SpscProducer {
        &self.producer
    }

    pub fn consumer(&self) -> &Consumer {
        &self.consumer
    }

    pub fn split(self) -> (SpscProducer, Consumer) {
        (self.producer, self.consumer)
    }
}

pub async fn new_bidi_channel(capacity_a: usize, capacity_b: usize) -> (BidiHandle, BidiHandle) {
    let (a_prod, a_cons) = new_spsc_channel(capacity_a).await;
    let (b_prod, b_cons) = new_spsc_channel(capacity_b).await;
    let a = BidiHandle {
        producer: a_prod,
        consumer: b_cons,
    };
    let b = BidiHandle {
        producer: b_prod,
        consumer: a_cons,
    };
    (a, b)
}

pub struct SpscProducer {
    storage: Arc<BBQStorage>,
    producer: InnerProducer<'static>,
}

#[derive(Clone)]
pub struct MpscProducer {
    storage: Arc<BBQStorage>,
}

pub struct Consumer {
    storage: Arc<BBQStorage>,
    consumer: InnerConsumer<'static>,
}

impl SpscProducer {
    pub async fn into_mpmc_producer(self) -> MpscProducer {
        let SpscProducer { storage, producer } = self;
        *storage.producer.lock().await = Some(producer);
        MpscProducer { storage }
    }
}

pub async fn new_spsc_channel(capacity: usize) -> (SpscProducer, Consumer) {
    info!(capacity, "Creating new mpsc BBQueue channel");
    let mut _array = ArrayBuf::new_uninit(capacity).await;

    let ring = BBBuffer::new();

    unsafe {
        let (ptr, len) = _array.ptrlen();
        ring.initialize(ptr.as_ptr().cast(), len);
    }

    let storage = Arc::new(BBQStorage {
        commit_waitcell: WaitCell::new(),
        release_waitcell: WaitCell::new(),
        producer: Mutex::new(None),
        ring,
        _array,
    })
    .await;

    // Now that we've allocated storage, the producer can be created.

    let bbbuffer = &storage.ring as *const BBBuffer as *mut BBBuffer;

    let (prod, cons) = unsafe {
        let prod = BBBuffer::take_producer(bbbuffer);
        let cons = BBBuffer::take_consumer(bbbuffer);

        (prod, cons)
    };

    let prod = SpscProducer {
        storage: storage.clone(),
        producer: prod,
    };
    let cons = Consumer {
        storage,
        consumer: cons,
    };

    info!("Channel created successfully");

    (prod, cons)
}

pub struct GrantW {
    grant: InnerGrantW<'static>,
    storage: Arc<BBQStorage>,
}

impl Deref for GrantW {
    type Target = [u8];

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        self.grant.deref()
    }
}

impl DerefMut for GrantW {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.grant.deref_mut()
    }
}

impl GrantW {
    pub fn commit(self, used: usize) {
        self.grant.commit(used);
        // If we freed up any space, notify the waker on the reader side
        if used != 0 {
            self.storage.commit_waitcell.wake();
        }
    }
}

pub struct GrantR {
    grant: InnerGrantR<'static>,
    storage: Arc<BBQStorage>,
}

impl Deref for GrantR {
    type Target = [u8];

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        self.grant.deref()
    }
}

impl DerefMut for GrantR {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.grant.deref_mut()
    }
}

impl GrantR {
    pub fn release(self, used: usize) {
        self.grant.release(used);
        // If we freed up any space, notify the waker on the reader side
        if used != 0 {
            self.storage.release_waitcell.wake();
        }
    }
}

unsafe impl Send for GrantR {}
unsafe impl Sync for GrantR {}

#[inline]
async fn producer_send_grant_max(
    max: usize,
    producer: &InnerProducer<'static>,
    storage: &Arc<BBQStorage>,
) -> GrantW {
    loop {
        let wait = storage.release_waitcell.subscribe().await;
        match producer.grant_max_remaining(max) {
            Ok(wgr) => {
                trace!(size = wgr.len(), "Got bbqueue max write grant");
                return GrantW {
                    grant: wgr,
                    storage: storage.clone(),
                };
            }
            Err(_) => {
                trace!("awaiting bbqueue max write grant");
                // Uh oh! Couldn't get a send grant. We need to wait for the reader
                // to release some bytes first.
                wait.await.unwrap();

                trace!("awoke for bbqueue max write grant");
            }
        }
    }
}

async fn producer_send_grant_exact(
    size: usize,
    producer: &InnerProducer<'static>,
    storage: &Arc<BBQStorage>,
) -> GrantW {
    loop {
        let wait = storage.release_waitcell.subscribe().await;
        match producer.grant_exact(size) {
            Ok(wgr) => {
                trace!("Got bbqueue exact write grant",);
                return GrantW {
                    grant: wgr,
                    storage: storage.clone(),
                };
            }
            Err(_) => {
                trace!("awaiting bbqueue exact write grant");
                // Uh oh! Couldn't get a send grant. We need to wait for the reader
                // to release some bytes first.
                wait.await.unwrap();
                trace!("awoke for bbqueue exact write grant");
            }
        }
    }
}

// async methods
impl MpscProducer {
    #[tracing::instrument(
        name = "MpscProducer::send_grant_max",
        level = "trace",
        skip(self),
        fields(queue = ?fmt::ptr(self.storage.deref())),
    )]
    pub async fn send_grant_max(&self, max: usize) -> GrantW {
        let producer = self.storage.producer.lock().await;
        let producer = producer.as_ref().unwrap();
        producer_send_grant_max(max, producer, &self.storage).await
    }

    #[tracing::instrument(
        name = "MpscProducer::send_grant_exact",
        level = "trace",
        skip(self),
        fields(queue = ?fmt::ptr(self.storage.deref())),
    )]
    pub async fn send_grant_exact(&self, size: usize) -> GrantW {
        let producer = self.storage.producer.lock().await;
        let producer = producer.as_ref().unwrap();
        producer_send_grant_exact(size, producer, &self.storage).await
    }
}

impl SpscProducer {
    #[tracing::instrument(
        name = "SpscProducer::send_grant_max",
        level = "trace",
        skip(self),
        fields(queue = ?fmt::ptr(self.storage.deref())),
    )]
    pub async fn send_grant_max(&self, max: usize) -> GrantW {
        producer_send_grant_max(max, &self.producer, &self.storage).await
    }

    #[tracing::instrument(
        name = "SpscProducer::send_grant_exact",
        level = "trace",
        skip(self),
        fields(queue = ?fmt::ptr(self.storage.deref())),
    )]
    pub async fn send_grant_exact(&self, size: usize) -> GrantW {
        producer_send_grant_exact(size, &self.producer, &self.storage).await
    }
}

impl Consumer {
    #[tracing::instrument(
        name = "Consumer::read_grant",
        level = "trace",
        skip(self),
        fields(queue = ?fmt::ptr(self.storage.deref())),
    )]
    pub async fn read_grant(&self) -> GrantR {
        loop {
            let wait = self.storage.commit_waitcell.subscribe().await;
            match self.consumer.read() {
                Ok(rgr) => {
                    trace!(size = rgr.len(), "Got bbqueue read grant",);
                    return GrantR {
                        grant: rgr,
                        storage: self.storage.clone(),
                    };
                }
                Err(_) => {
                    trace!("awaiting bbqueue read grant");
                    // Uh oh! Couldn't get a read grant. We need to wait for the writer
                    // to commit some bytes first.
                    wait.await.unwrap();
                    trace!("awoke for bbqueue read grant");
                }
            }
        }
    }
}

// sync methods
impl SpscProducer {
    #[tracing::instrument(
        name = "SpscProducer::send_grant_exact_sync",
        level = "trace",
        skip(self),
        fields(queue = ?fmt::ptr(self.storage.deref())),
    )]
    pub fn send_grant_exact_sync(&self, size: usize) -> Option<GrantW> {
        self.producer.grant_exact(size).ok().map(|wgr| GrantW {
            grant: wgr,
            storage: self.storage.clone(),
        })
    }

    #[tracing::instrument(
        name = "SpscProducer::send_grant_max_sync",
        level = "trace",
        skip(self),
        fields(queue = ?fmt::ptr(self.storage.deref())),
    )]
    pub fn send_grant_max_sync(&self, max: usize) -> Option<GrantW> {
        self.producer
            .grant_max_remaining(max)
            .ok()
            .map(|wgr| GrantW {
                grant: wgr,
                storage: self.storage.clone(),
            })
    }
}

impl MpscProducer {
    #[tracing::instrument(
        name = "MpscProducer::send_grant_exact_sync",
        level = "trace",
        skip(self),
        fields(queue = ?fmt::ptr(self.storage.deref())),
    )]
    pub fn send_grant_exact_sync(&self, size: usize) -> Option<GrantW> {
        let producer = self.storage.producer.try_lock()?;
        let wgr = producer.as_ref()?.grant_exact(size).ok()?;
        Some(GrantW {
            grant: wgr,
            storage: self.storage.clone(),
        })
    }

    #[tracing::instrument(
        name = "MpscProducer::send_grant_max_sync",
        level = "trace",
        skip(self),
        fields(queue = ?fmt::ptr(self.storage.deref())),
    )]
    pub fn send_grant_max_sync(&self, max: usize) -> Option<GrantW> {
        let producer = self.storage.producer.try_lock()?;
        let wgr = producer.as_ref()?.grant_max_remaining(max).ok()?;
        Some(GrantW {
            grant: wgr,
            storage: self.storage.clone(),
        })
    }
}

impl Consumer {
    #[tracing::instrument(
        name = "Consumer::read_grant_sync",
        level = "trace",
        skip(self),
        fields(queue = ?fmt::ptr(self.storage.deref())),
    )]
    pub fn read_grant_sync(&self) -> Option<GrantR> {
        self.consumer.read().ok().map(|rgr| GrantR {
            grant: rgr,
            storage: self.storage.clone(),
        })
    }
}