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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
//! # BBQueue
//!
//! BBQueue, short for "BipBuffer Queue", is a (work in progress) Single Producer Single Consumer,
//! lockless, no_std, thread safe, queue, based on [BipBuffers].
//!
//! [BipBuffers]: https://www.codeproject.com/Articles/3479/%2FArticles%2F3479%2FThe-Bip-Buffer-The-Circular-Buffer-with-a-Twist
//!
//! It is designed (primarily) to be a First-In, First-Out queue for use with DMA on embedded
//! systems.
//!
//! While Circular/Ring Buffers allow you to send data between two threads (or from an interrupt to
//! main code), you must push the data one piece at a time. With BBQueue, you instead are granted a
//! block of contiguous memory, which can be filled (or emptied) by a DMA engine.
//!
//! ## Using in a single threaded context
//!
//! ```rust
//! use bbqueue::{BBQueue, bbq};
//!
//! fn main() {
//!     // Create a statically allocated instance
//!     let bbq = bbq!(1024).unwrap();
//!
//!     // Obtain a write grant of size 128 bytes
//!     let mut wgr = bbq.grant(128).unwrap();
//!
//!     // Fill the buffer with data
//!     wgr.copy_from_slice(&[0xAFu8; 128]);
//!
//!     // Commit the write, to make the data available to be read
//!     bbq.commit(wgr.len(), wgr);
//!
//!     // Obtain a read grant of all available and contiguous bytes
//!     let rgr = bbq.read().unwrap();
//!
//!     for i in 0..128 {
//!         assert_eq!(rgr[i], 0xAFu8);
//!     }
//!
//!     // Release the bytes, allowing the space
//!     // to be re-used for writing
//!     bbq.release(rgr.len(), rgr);
//! }
//! ```
//!
//! ## Using in a multi-threaded environment (or with interrupts, etc.)
//!
//! ```rust
//! use bbqueue::{BBQueue, bbq};
//! use std::thread::spawn;
//!
//! fn main() {
//!     // Create a statically allocated instance
//!     let bbq = bbq!(1024).unwrap();
//!     let (mut tx, mut rx) = bbq.split();
//!
//!     let txt = spawn(move || {
//!         for tx_i in 0..128 {
//!             'inner: loop {
//!                 match tx.grant(4) {
//!                     Ok(mut gr) => {
//!                         gr.copy_from_slice(&[tx_i as u8; 4]);
//!                         tx.commit(4, gr);
//!                         break 'inner;
//!                     }
//!                     _ => {}
//!                 }
//!             }
//!         }
//!     });
//!
//!     let rxt = spawn(move || {
//!         for rx_i in 0..128 {
//!             'inner: loop {
//!                 match rx.read() {
//!                     Ok(mut gr) => {
//!                         if gr.len() < 4 {
//!                             rx.release(0, gr);
//!                             continue 'inner;
//!                         }
//!
//!                         assert_eq!(&gr[..4], &[rx_i as u8; 4]);
//!                         rx.release(4, gr);
//!                         break 'inner;
//!                     }
//!                     _ => {}
//!                 }
//!             }
//!         }
//!     });
//!
//!     txt.join().unwrap();
//!     rxt.join().unwrap();
//! }
//! ```

#![cfg_attr(not(feature = "std"), no_std)]

use core::cmp::min;
use core::ops::{Deref, DerefMut};
use core::ptr::NonNull;
use core::result::Result as CoreResult;
use core::slice::from_raw_parts;
use core::slice::from_raw_parts_mut;
use core::sync::atomic::{
    AtomicBool,
    AtomicUsize,
    Ordering::{
        Acquire,
        Relaxed,
        Release,
    },
};

/// Result type used by the `BBQueue` interfaces
pub type Result<T> = CoreResult<T, Error>;

/// Error type used by the `BBQueue` interfaces
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Error {
    InsufficientSize,
    GrantInProgress,
}

/// A single producer, single consumer, thread safe queue
#[derive(Debug)]
pub struct BBQueue {
    // Underlying data storage
    buf: NonNull<[u8]>,

    /// Where the next byte will be written
    write: AtomicUsize,

    /// Where the next byte will be read from
    read: AtomicUsize,

    /// Used in the inverted case to mark the end of the
    /// readable streak. Otherwise will == unsafe { self.buf.as_mut().len() }.
    /// Writer is responsible for placing this at the correct
    /// place when entering an inverted condition, and Reader
    /// is responsible for moving it back to unsafe { self.buf.as_mut().len() }
    /// when exiting the inverted condition
    last: AtomicUsize,

    /// Used by the Writer to remember what bytes are currently
    /// allowed to be written to, but are not yet ready to be
    /// read from
    reserve: AtomicUsize,

    /// Is there an active read grant?
    read_in_progress: AtomicBool,

    /// Have we already split?
    already_split: AtomicBool,
}

impl BBQueue {
    /// Create a new BBQueue with a given backing buffer. After giving this
    /// buffer to `BBQueue::new(), the backing buffer must not be used, or
    /// undefined behavior could occur!
    ///
    /// Additionally, when using `BBQueue::split()`, the `BBQueue` struct must
    /// never be moved, otherwise `Producer` and `Consumer` could corrupt memory
    ///
    /// Consider using the `bbq!()` macro to safely create a statically
    /// allocated instance, or enable the "std" feature, and instead use the
    /// `BBQueue::new_boxed()` constructor.
    pub unsafe fn unpinned_new(buf: &'static mut [u8]) -> Self {
        let sz = buf.len();
        assert!(sz != 0);
        BBQueue {
            buf: NonNull::new_unchecked(buf),

            /// Owned by the writer
            write: AtomicUsize::new(0),

            /// Owned by the reader
            read: AtomicUsize::new(0),

            /// Cooperatively owned
            last: AtomicUsize::new(sz),

            /// Owned by the Writer, "private"
            reserve: AtomicUsize::new(0),

            /// Owned by the Reader, "private"
            read_in_progress: AtomicBool::new(false),

            already_split: AtomicBool::new(false),
        }
    }

    /// Request a writable, contiguous section of memory of exactly
    /// `sz` bytes. If the buffer size requested is not available,
    /// an error will be returned.
    pub fn grant(&mut self, sz: usize) -> Result<GrantW> {
        // Writer component. Must never write to `read`,
        // be careful writing to `load`

        let write = self.write.load(Relaxed);

        if self.reserve.load(Relaxed) != write {
            // GRANT IN PROCESS, do not allow further grants
            // until the current one has been completed
            return Err(Error::GrantInProgress);
        }

        let read = self.read.load(Acquire);
        let max = unsafe { self.buf.as_mut().len() };

        let already_inverted = write < read;

        let start = if already_inverted {
            if (write + sz) < read {
                // Inverted, room is still available
                write
            } else {
                // Inverted, no room is available
                return Err(Error::InsufficientSize);
            }
        } else {
            if write + sz <= max {
                // Non inverted condition
                write
            } else {
                // Not inverted, but need to go inverted

                // NOTE: We check sz < read, NOT <=, because
                // write must never == read in an inverted condition, since
                // we will then not be able to tell if we are inverted or not
                if sz < read {
                    // Invertible situation
                    0
                } else {
                    // Not invertible, no space
                    return Err(Error::InsufficientSize);
                }
            }
        };

        // Safe write, only viewed by this task
        self.reserve.store(start + sz, Relaxed);

        let c = unsafe { self.buf.as_mut().as_mut_ptr() };
        let d = unsafe { from_raw_parts_mut(c, max) };

        Ok(GrantW {
            buf: &mut d[start..self.reserve.load(Relaxed)],
        })
    }

    /// Request a writable, contiguous section of memory of up to
    /// `sz` bytes. If a buffer of size `sz` is not available, but
    /// some space (0 < available < sz) is available, then a grant
    /// will be given for the remaining size. If no space is available
    /// for writing, an error will be returned
    pub fn grant_max(&mut self, mut sz: usize) -> Result<GrantW> {
        // Writer component. Must never write to `read`,
        // be careful writing to `load`

        let write = self.write.load(Relaxed);

        if self.reserve.load(Relaxed) != write {
            // GRANT IN PROCESS, do not allow further grants
            // until the current one has been completed
            return Err(Error::GrantInProgress);
        }

        let read = self.read.load(Acquire);
        let max = unsafe { self.buf.as_mut().len() };

        let already_inverted = write < read;

        let start = if already_inverted {
            // In inverted case, read is always > write
            let remain = read - write - 1;

            if remain != 0 {
                sz = min(remain, sz);
                write
            } else {
                // Inverted, no room is available
                return Err(Error::InsufficientSize);
            }
        } else {
            if write != max {
                // Some (or all) room remaining in un-inverted case
                sz = min(max - write, sz);
                write
            } else {
                // Not inverted, but need to go inverted

                // NOTE: We check read > 1, NOT read > 1, because
                // write must never == read in an inverted condition, since
                // we will then not be able to tell if we are inverted or not
                if read > 1 {
                    sz = min(read - 1, sz);
                    0
                } else {
                    // Not invertible, no space
                    return Err(Error::InsufficientSize);
                }
            }
        };

        // Safe write, only viewed by this task
        self.reserve.store(start + sz, Relaxed);

        let c = unsafe { self.buf.as_mut().as_mut_ptr() };
        let d = unsafe { from_raw_parts_mut(c, max) };


        Ok(GrantW {
            buf: &mut d[start..self.reserve.load(Relaxed)],
        })
    }

    /// Finalizes a writable grant given by `grant()` or `grant_max()`.
    /// This makes the data available to be read via `read()`.
    ///
    /// If `used` is larger than the given grant, this function will panic.
    pub fn commit(&mut self, used: usize, grant: GrantW) {
        // Writer component. Must never write to READ,
        // be careful writing to LAST

        // Verify we are not committing more than the given
        // grant
        let len = grant.buf.len();
        assert!(len >= used);

        // Verify we are committing OUR grant
        assert!(self.is_our_grant(&grant.buf));

        drop(grant);

        let write = self.write.load(Relaxed);
        self.reserve.fetch_sub(len - used, Relaxed);

        // Inversion case, we have begun writing
        if (self.reserve.load(Relaxed) < write) && (write != unsafe { self.buf.as_mut().len() }) {
            // This has potential for danger. We have two writers!
            // MOVING LAST BACKWARDS
            self.last.store(write, Release);
        }

        // This has some potential for danger. The other thread (READ)
        // does look at this variable!
        // MOVING WRITE FORWARDS
        self.write.store(self.reserve.load(Relaxed), Release);
    }

    /// Obtains a contiguous slice of committed bytes. This slice may not
    /// contain ALL available bytes, if the writer has wrapped around. The
    /// remaining bytes will be available after all readable bytes are
    /// released
    pub fn read(&mut self) -> Result<GrantR> {
        if self.read_in_progress.load(Relaxed) {
            return Err(Error::GrantInProgress);
        }

        let write = self.write.load(Acquire);
        let mut last = self.last.load(Acquire);
        let mut read = self.read.load(Relaxed);
        let max = unsafe { self.buf.as_mut().len() };

        // Resolve the inverted case or end of read
        if (read == last) && (write < read) {
            read = 0;
            // This has some room for error, the other thread reads this
            // Impact to Grant:
            //   Grant checks if read < write to see if inverted. If not inverted, but
            //     no space left, Grant will initiate an inversion, but will not trigger it
            // Impact to Commit:
            //   Commit does not check read, but if Grant has started an inversion,
            //   grant could move Last to the prior write position
            // MOVING READ BACKWARDS!
            self.read.store(0, Release);
            if last != max {
                // This is pretty tricky, we have two writers!
                // MOVING LAST FORWARDS
                self.last.store(max, Release);
                last = max;
            }
        }

        let sz = if write < read {
            // Inverted, only believe last
            last
        } else {
            // Not inverted, only believe write
            write
        } - read;

        if sz == 0 {
            return Err(Error::InsufficientSize);
        }

        self.read_in_progress.store(true, Relaxed);

        let c = unsafe { self.buf.as_mut().as_ptr() };
        let d = unsafe { from_raw_parts(c, max) };

        Ok(GrantR {
            buf: &d[read..read+sz],
        })
    }

    /// Release a sequence of bytes from the buffer, allowing the space
    /// to be used by later writes
    ///
    /// If `used` is larger than the given grant, this function will panic.
    pub fn release(&self, used: usize, grant: GrantR) {
        assert!(used <= grant.buf.len());

        // Verify we are committing OUR grant
        assert!(self.is_our_grant(&grant.buf));

        drop(grant);

        // This should be fine, purely incrementing
        let _ = self.read.fetch_add(used, Release);

        self.read_in_progress.store(false, Relaxed);
    }

    fn is_our_grant(&self, gr_buf: &[u8]) -> bool {
        let start = unsafe { self.buf.as_ref().as_ptr() as usize };
        let end_plus_one = start + unsafe { self.buf.as_ref().len() };
        let buf = gr_buf.as_ptr() as usize;

        (buf >= start) && (buf < end_plus_one)
    }


}

impl BBQueue {
    /// This method takes a `BBQueue`, and returns a set of SPSC handles
    /// that may be given to separate threads. May only be called once
    /// per `BBQueue` object, or this function will panic
    pub fn split(&self) -> (Producer, Consumer) {
        assert!(!self.already_split.swap(true, Relaxed));

        let nn1 = unsafe { NonNull::new_unchecked(self as *const _ as *mut _) };
        let nn2 = unsafe { NonNull::new_unchecked(self as *const _ as *mut _) };

        (
            Producer {
                bbq: nn1,
            },
            Consumer {
                bbq: nn2,
            },
        )
    }
}

#[cfg(feature = "std")]
impl BBQueue {
    /// Creates a Boxed `BBQueue`
    ///
    /// NOTE: This function essentially "leaks" the backing buffer
    /// (e.g. `BBQueue::new_boxed(1024)` will leak 1024 bytes). This
    /// may be changed in the future.
    pub fn new_boxed(capacity: usize) -> Box<Self> {
        let data: &mut [u8] = Box::leak(vec![0; capacity].into_boxed_slice());
        Box::new(unsafe { Self::unpinned_new(data) })
    }

    /// Splits a boxed `BBQueue` into a producer and consumer
    pub fn split_box(queue: Box<Self>) -> (Producer, Consumer) {
        let self_ref = Box::leak(queue);
        Self::split(self_ref)
    }
}

/// A structure representing a contiguous region of memory that
/// may be written to, and potentially "committed" to the queue
#[derive(Debug, PartialEq)]
pub struct GrantW {
    buf: &'static mut [u8],
}

/// A structure representing a contiguous region of memory that
/// may be read from, and potentially "released" (or cleared)
/// from the queue
#[derive(Debug, PartialEq)]
pub struct GrantR {
    buf: &'static [u8],
}

impl GrantW {
    pub fn buf(&mut self) -> &mut [u8] {
        self.buf
    }
}

impl GrantR {
    pub fn buf(&self) -> &[u8] {
        self.buf
    }
}

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

    fn deref(&self) -> &Self::Target {
        self.buf
    }
}

impl DerefMut for GrantW {
    fn deref_mut(&mut self) -> &mut [u8] {
        self.buf
    }
}

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

    fn deref(&self) -> &Self::Target {
        self.buf
    }
}

unsafe impl Send for Consumer {}

/// An opaque structure, capable of reading data from the queue
pub struct Consumer {
    /// The underlying `BBQueue` object`
    bbq: NonNull<BBQueue>,
}

unsafe impl Send for Producer {}

/// An opaque structure, capable of writing data to the queue
pub struct Producer {
    /// The underlying `BBQueue` object`
    bbq: NonNull<BBQueue>,
}

impl Producer {
    /// Request a writable, contiguous section of memory of exactly
    /// `sz` bytes. If the buffer size requested is not available,
    /// an error will be returned.
    #[inline(always)]
    pub fn grant(&mut self, sz: usize) -> Result<GrantW> {
        unsafe { self.bbq.as_mut().grant(sz) }
    }

    /// Request a writable, contiguous section of memory of up to
    /// `sz` bytes. If a buffer of size `sz` is not available, but
    /// some space (0 < available < sz) is available, then a grant
    /// will be given for the remaining size. If no space is available
    /// for writing, an error will be returned
    #[inline(always)]
    pub fn grant_max(&mut self, sz: usize) -> Result<GrantW> {
        unsafe { self.bbq.as_mut().grant_max(sz) }
    }

    /// Finalizes a writable grant given by `grant()` or `grant_max()`.
    /// This makes the data available to be read via `read()`.
    ///
    /// If `used` is larger than the given grant, this function will panic.
    #[inline(always)]
    pub fn commit(&mut self, used: usize, grant: GrantW) {
        unsafe { self.bbq.as_mut().commit(used, grant) }
    }
}

impl Consumer {
    /// Obtains a contiguous slice of committed bytes. This slice may not
    /// contain ALL available bytes, if the writer has wrapped around. The
    /// remaining bytes will be available after all readable bytes are
    /// released
    #[inline(always)]
    pub fn read(&mut self) -> Result<GrantR> {
        unsafe { self.bbq.as_mut().read() }
    }

    /// Release a sequence of bytes from the buffer, allowing the space
    /// to be used by later writes
    ///
    /// If `used` is larger than the given grant, this function will panic.
    #[inline(always)]
    pub fn release(&mut self, used: usize, grant: GrantR) {
        unsafe { self.bbq.as_mut().release(used, grant) }
    }
}

/// Statically allocate a `BBQueue` singleton object with a given size (in bytes).
///
/// This function must only ever be called once in the same place
/// per function. For example:
///
/// ```rust,ignore
/// // this creates two separate/distinct buffers, and is an acceptable usage
/// let bbq1 = bbq!(1024).unwrap(); // Returns Some(BBQueue)
/// let bbq2 = bbq!(1024).unwrap(); // Returns Some(BBQueue)
///
/// // this is a bad example, as the same instance is executed twice!
/// // On the first call, this macro will return `Some(BBQueue)`. On the
/// // second call, this macro will return `None`!
/// for _ in 0..2 {
///     let _ = bbq!(1024).unwrap();
/// }
/// ```
///
/// If you are using this in a cortex-m microcontroller system,
/// consider using the cortex_m_bbq!() macro instead.
#[macro_export]
macro_rules! bbq {
    ($expr:expr) => {
        {
            use core::sync::atomic::{AtomicBool, Ordering};

            static TAKEN: AtomicBool = AtomicBool::new(false);

            if TAKEN.compare_and_swap(false, true, Ordering::AcqRel) {
                None
            } else {
                unsafe { $crate::unchecked_bbq!($expr) }
            }
        }
    }
}

/// Like the `bbq!()` macro, but wraps the initialization in a cortex-m
/// "critical section" by disabling interrupts
#[cfg_attr(feature="cortex-m", macro_export)]
#[allow(unused_macros)]
macro_rules! cortex_m_bbq {
    ($expr:expr) => {
        cortex_m::interrupt::free(|_|
            unsafe { $crate::unchecked_bbq!($expr) }
        )
    }
}

/// This macro does try to provide similar guarantees as `bbq!()`,
/// but is not thread safe.
#[macro_export]
macro_rules! unchecked_bbq {
    ($expr:expr) => {
        {
            static mut BUFFER: [u8; $expr] = [0u8; $expr];

            // Really, this shouldn't be an option. But for now, there is
            // no stable way to get an uninitialized static, so we pay the
            // option cost for compatibility
            static mut BBQ: Option<BBQueue> = None;

            if BBQ.is_some() {
                None
            } else {
                BBQ = Some(BBQueue::unpinned_new(&mut BUFFER));
                BBQ.as_mut()
            }
        }
    }
}