Merge pull request #85 from embassy-rs/no-free

Simplify PeripheralMutex
This commit is contained in:
Dario Nieuwenhuis 2021-03-18 20:51:31 +01:00 committed by GitHub
commit e912355bb2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 38 additions and 100 deletions

View File

@ -1,30 +1,20 @@
use core::cell::UnsafeCell; use core::cell::UnsafeCell;
use core::marker::{PhantomData, PhantomPinned}; use core::marker::{PhantomData, PhantomPinned};
use core::mem::MaybeUninit;
use core::pin::Pin; use core::pin::Pin;
use core::sync::atomic::{compiler_fence, Ordering}; use core::sync::atomic::{compiler_fence, Ordering};
use embassy::interrupt::{Interrupt, InterruptExt}; use embassy::interrupt::{Interrupt, InterruptExt};
use crate::fmt::assert;
pub trait PeripheralState { pub trait PeripheralState {
type Interrupt: Interrupt; type Interrupt: Interrupt;
fn on_interrupt(&mut self); fn on_interrupt(&mut self);
} }
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Life {
Ready,
Created,
Freed,
}
pub struct PeripheralMutex<S: PeripheralState> { pub struct PeripheralMutex<S: PeripheralState> {
life: Life, state: UnsafeCell<S>,
state: MaybeUninit<UnsafeCell<S>>, // Init if life != Freed irq_setup_done: bool,
irq: MaybeUninit<S::Interrupt>, // Init if life != Freed irq: S::Interrupt,
_not_send: PhantomData<*mut ()>, _not_send: PhantomData<*mut ()>,
_pinned: PhantomPinned, _pinned: PhantomPinned,
@ -33,87 +23,61 @@ pub struct PeripheralMutex<S: PeripheralState> {
impl<S: PeripheralState> PeripheralMutex<S> { impl<S: PeripheralState> PeripheralMutex<S> {
pub fn new(state: S, irq: S::Interrupt) -> Self { pub fn new(state: S, irq: S::Interrupt) -> Self {
Self { Self {
life: Life::Created, irq,
state: MaybeUninit::new(UnsafeCell::new(state)), irq_setup_done: false,
irq: MaybeUninit::new(irq),
state: UnsafeCell::new(state),
_not_send: PhantomData, _not_send: PhantomData,
_pinned: PhantomPinned, _pinned: PhantomPinned,
} }
} }
/// safety: self must be pinned. pub fn register_interrupt(self: Pin<&mut Self>) {
unsafe fn setup(&mut self) { let this = unsafe { self.get_unchecked_mut() };
assert!(self.life == Life::Created); if this.irq_setup_done {
return;
}
let irq = &mut *self.irq.as_mut_ptr(); this.irq.disable();
irq.disable();
compiler_fence(Ordering::SeqCst); compiler_fence(Ordering::SeqCst);
irq.set_handler(|p| { this.irq.set_handler(|p| {
// Safety: it's OK to get a &mut to the state, since // Safety: it's OK to get a &mut to the state, since
// - We're in the IRQ, no one else can't preempt us // - We're in the IRQ, no one else can't preempt us
// - We can't have preempted a with() call because the irq is disabled during it. // - We can't have preempted a with() call because the irq is disabled during it.
let state = &mut *(p as *mut S); let state = unsafe { &mut *(p as *mut S) };
state.on_interrupt(); state.on_interrupt();
}); });
irq.set_handler_context(self.state.as_mut_ptr() as *mut ()); this.irq
.set_handler_context((&mut this.state) as *mut _ as *mut ());
compiler_fence(Ordering::SeqCst); compiler_fence(Ordering::SeqCst);
irq.enable(); this.irq.enable();
self.life = Life::Ready; this.irq_setup_done = true;
} }
pub fn with<R>(self: Pin<&mut Self>, f: impl FnOnce(&mut S, &mut S::Interrupt) -> R) -> R { pub fn with<R>(self: Pin<&mut Self>, f: impl FnOnce(&mut S, &mut S::Interrupt) -> R) -> R {
let this = unsafe { self.get_unchecked_mut() }; let this = unsafe { self.get_unchecked_mut() };
if this.life != Life::Ready {
unsafe { this.setup() }
}
let irq = unsafe { &mut *this.irq.as_mut_ptr() }; this.irq.disable();
irq.disable();
compiler_fence(Ordering::SeqCst); compiler_fence(Ordering::SeqCst);
// Safety: it's OK to get a &mut to the state, since the irq is disabled. // Safety: it's OK to get a &mut to the state, since the irq is disabled.
let state = unsafe { &mut *(*this.state.as_ptr()).get() }; let state = unsafe { &mut *this.state.get() };
let r = f(state, irq); let r = f(state, &mut this.irq);
compiler_fence(Ordering::SeqCst); compiler_fence(Ordering::SeqCst);
irq.enable(); this.irq.enable();
r r
} }
pub fn try_free(self: Pin<&mut Self>) -> Option<(S, S::Interrupt)> {
let this = unsafe { self.get_unchecked_mut() };
if this.life != Life::Freed {
return None;
}
unsafe { &mut *this.irq.as_mut_ptr() }.disable();
compiler_fence(Ordering::SeqCst);
this.life = Life::Freed;
let state = unsafe { this.state.as_ptr().read().into_inner() };
let irq = unsafe { this.irq.as_ptr().read() };
Some((state, irq))
}
pub fn free(self: Pin<&mut Self>) -> (S, S::Interrupt) {
unwrap!(self.try_free())
}
} }
impl<S: PeripheralState> Drop for PeripheralMutex<S> { impl<S: PeripheralState> Drop for PeripheralMutex<S> {
fn drop(&mut self) { fn drop(&mut self) {
if self.life != Life::Freed { self.irq.disable();
let irq = unsafe { &mut *self.irq.as_mut_ptr() }; self.irq.remove_handler();
irq.disable();
irq.remove_handler();
}
} }
} }

View File

@ -201,36 +201,15 @@ impl<'a, U: Instance, T: TimerInstance, P1: ConfigurablePpi, P2: ConfigurablePpi
fn inner(self: Pin<&mut Self>) -> Pin<&mut PeripheralMutex<State<'a, U, T, P1, P2>>> { fn inner(self: Pin<&mut Self>) -> Pin<&mut PeripheralMutex<State<'a, U, T, P1, P2>>> {
unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().inner) } unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().inner) }
} }
pub fn free(self: Pin<&mut Self>) -> (U, T, P1, P2, U::Interrupt) {
let (mut state, irq) = self.inner().free();
state.stop();
(
state.uarte,
state.timer,
state.ppi_channel_1,
state.ppi_channel_2,
irq,
)
}
}
impl<'a, U: Instance, T: TimerInstance, P1: ConfigurablePpi, P2: ConfigurablePpi> Drop
for BufferedUarte<'a, U, T, P1, P2>
{
fn drop(&mut self) {
let inner = unsafe { Pin::new_unchecked(&mut self.inner) };
if let Some((mut state, _irq)) = inner.try_free() {
state.stop();
}
}
} }
impl<'a, U: Instance, T: TimerInstance, P1: ConfigurablePpi, P2: ConfigurablePpi> AsyncBufRead impl<'a, U: Instance, T: TimerInstance, P1: ConfigurablePpi, P2: ConfigurablePpi> AsyncBufRead
for BufferedUarte<'a, U, T, P1, P2> for BufferedUarte<'a, U, T, P1, P2>
{ {
fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<&[u8]>> { fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<&[u8]>> {
self.inner().with(|state, _irq| { let mut inner = self.inner();
inner.as_mut().register_interrupt();
inner.with(|state, _irq| {
// Conservative compiler fence to prevent optimizations that do not // Conservative compiler fence to prevent optimizations that do not
// take in to account actions by DMA. The fence has been placed here, // take in to account actions by DMA. The fence has been placed here,
// before any DMA action has started // before any DMA action has started
@ -253,7 +232,9 @@ impl<'a, U: Instance, T: TimerInstance, P1: ConfigurablePpi, P2: ConfigurablePpi
} }
fn consume(self: Pin<&mut Self>, amt: usize) { fn consume(self: Pin<&mut Self>, amt: usize) {
self.inner().with(|state, irq| { let mut inner = self.inner();
inner.as_mut().register_interrupt();
inner.with(|state, irq| {
trace!("consume {:?}", amt); trace!("consume {:?}", amt);
state.rx.pop(amt); state.rx.pop(amt);
irq.pend(); irq.pend();
@ -265,7 +246,9 @@ impl<'a, U: Instance, T: TimerInstance, P1: ConfigurablePpi, P2: ConfigurablePpi
for BufferedUarte<'a, U, T, P1, P2> for BufferedUarte<'a, U, T, P1, P2>
{ {
fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize>> { fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize>> {
self.inner().with(|state, irq| { let mut inner = self.inner();
inner.as_mut().register_interrupt();
inner.with(|state, irq| {
trace!("poll_write: {:?}", buf.len()); trace!("poll_write: {:?}", buf.len());
let tx_buf = state.tx.push_buf(); let tx_buf = state.tx.push_buf();
@ -293,10 +276,10 @@ impl<'a, U: Instance, T: TimerInstance, P1: ConfigurablePpi, P2: ConfigurablePpi
} }
} }
impl<'a, U: Instance, T: TimerInstance, P1: ConfigurablePpi, P2: ConfigurablePpi> impl<'a, U: Instance, T: TimerInstance, P1: ConfigurablePpi, P2: ConfigurablePpi> Drop
State<'a, U, T, P1, P2> for State<'a, U, T, P1, P2>
{ {
fn stop(&mut self) { fn drop(&mut self) {
self.timer.tasks_stop.write(|w| unsafe { w.bits(1) }); self.timer.tasks_stop.write(|w| unsafe { w.bits(1) });
if let RxState::Receiving = self.rx_state { if let RxState::Receiving = self.rx_state {
self.uarte.tasks_stoprx.write(|w| unsafe { w.bits(1) }); self.uarte.tasks_stoprx.write(|w| unsafe { w.bits(1) });

View File

@ -238,11 +238,6 @@ impl Qspi {
unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().inner) } unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().inner) }
} }
pub fn free(self: Pin<&mut Self>) -> (QSPI, interrupt::QSPI) {
let (state, irq) = self.inner().free();
(state.inner, irq)
}
fn wait_ready<'a>(mut self: Pin<&'a mut Self>) -> impl Future<Output = ()> + 'a { fn wait_ready<'a>(mut self: Pin<&'a mut Self>) -> impl Future<Output = ()> + 'a {
poll_fn(move |cx| { poll_fn(move |cx| {
self.as_mut().inner().with(|s, _irq| { self.as_mut().inner().with(|s, _irq| {

View File

@ -120,11 +120,6 @@ impl<T: Instance> Spim<T> {
fn inner(self: Pin<&mut Self>) -> Pin<&mut PeripheralMutex<State<T>>> { fn inner(self: Pin<&mut Self>) -> Pin<&mut PeripheralMutex<State<T>>> {
unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().inner) } unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().inner) }
} }
pub fn free(self: Pin<&mut Self>) -> (T, T::Interrupt) {
let (state, irq) = self.inner().free();
(state.spim, irq)
}
} }
impl<T: Instance> FullDuplex<u8> for Spim<T> { impl<T: Instance> FullDuplex<u8> for Spim<T> {
@ -153,6 +148,7 @@ impl<T: Instance> FullDuplex<u8> for Spim<T> {
slice_in_ram_or(rx, Error::DMABufferNotInDataMemory)?; slice_in_ram_or(rx, Error::DMABufferNotInDataMemory)?;
slice_in_ram_or(tx, Error::DMABufferNotInDataMemory)?; slice_in_ram_or(tx, Error::DMABufferNotInDataMemory)?;
self.as_mut().inner().register_interrupt();
self.as_mut().inner().with(|s, _irq| { self.as_mut().inner().with(|s, _irq| {
// Conservative compiler fence to prevent optimizations that do not // Conservative compiler fence to prevent optimizations that do not
// take in to account actions by DMA. The fence has been placed here, // take in to account actions by DMA. The fence has been placed here,