2021-01-05 01:57:05 +01:00
|
|
|
use core::pin::Pin;
|
2021-01-03 01:40:40 +01:00
|
|
|
use core::sync::atomic::{compiler_fence, Ordering};
|
|
|
|
use core::{cell::UnsafeCell, marker::PhantomData};
|
|
|
|
|
2021-01-05 01:57:05 +01:00
|
|
|
use crate::fmt::*;
|
2021-01-03 01:40:40 +01:00
|
|
|
use crate::interrupt::OwnedInterrupt;
|
|
|
|
|
2021-01-05 01:57:05 +01:00
|
|
|
pub trait PeripheralState {
|
2021-01-03 01:40:40 +01:00
|
|
|
fn on_interrupt(&mut self);
|
|
|
|
}
|
|
|
|
|
2021-01-05 01:57:05 +01:00
|
|
|
pub struct PeripheralMutex<I: OwnedInterrupt, S: PeripheralState> {
|
|
|
|
inner: Option<(I, UnsafeCell<S>)>,
|
|
|
|
not_send: PhantomData<*mut ()>,
|
2021-01-03 01:40:40 +01:00
|
|
|
}
|
|
|
|
|
2021-01-05 01:57:05 +01:00
|
|
|
impl<I: OwnedInterrupt, S: PeripheralState> PeripheralMutex<I, S> {
|
|
|
|
pub fn new(irq: I, state: S) -> Self {
|
2021-01-03 01:40:40 +01:00
|
|
|
Self {
|
2021-01-05 01:57:05 +01:00
|
|
|
inner: Some((irq, UnsafeCell::new(state))),
|
2021-01-03 01:40:40 +01:00
|
|
|
not_send: PhantomData,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-05 01:57:05 +01:00
|
|
|
pub fn with<R>(self: Pin<&mut Self>, f: impl FnOnce(&mut I, &mut S) -> R) -> R {
|
|
|
|
let this = unsafe { self.get_unchecked_mut() };
|
|
|
|
let (irq, state) = unwrap!(this.inner.as_mut());
|
|
|
|
|
|
|
|
irq.disable();
|
2021-01-03 01:40:40 +01:00
|
|
|
compiler_fence(Ordering::SeqCst);
|
|
|
|
|
2021-01-05 01:57:05 +01:00
|
|
|
irq.set_handler(
|
|
|
|
|p| {
|
|
|
|
// 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 can't have preempted a with() call because the irq is disabled during it.
|
|
|
|
let state = unsafe { &mut *(p as *mut S) };
|
|
|
|
state.on_interrupt();
|
|
|
|
},
|
|
|
|
state.get() as *mut (),
|
|
|
|
);
|
|
|
|
|
|
|
|
// Safety: it's OK to get a &mut to the state, since the irq is disabled.
|
|
|
|
let state = unsafe { &mut *state.get() };
|
|
|
|
|
|
|
|
let r = f(irq, state);
|
2021-01-03 01:40:40 +01:00
|
|
|
|
|
|
|
compiler_fence(Ordering::SeqCst);
|
2021-01-05 01:57:05 +01:00
|
|
|
irq.enable();
|
2021-01-03 01:40:40 +01:00
|
|
|
|
|
|
|
r
|
|
|
|
}
|
|
|
|
|
2021-01-05 01:57:05 +01:00
|
|
|
pub fn free(self: Pin<&mut Self>) -> (I, S) {
|
|
|
|
let this = unsafe { self.get_unchecked_mut() };
|
|
|
|
let (irq, state) = unwrap!(this.inner.take());
|
2021-01-03 01:40:40 +01:00
|
|
|
irq.disable();
|
2021-01-04 22:25:39 +01:00
|
|
|
irq.remove_handler();
|
2021-01-05 01:57:05 +01:00
|
|
|
(irq, state.into_inner())
|
2021-01-03 01:40:40 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-01-05 01:57:05 +01:00
|
|
|
impl<I: OwnedInterrupt, S: PeripheralState> Drop for PeripheralMutex<I, S> {
|
2021-01-03 01:40:40 +01:00
|
|
|
fn drop(&mut self) {
|
2021-01-05 01:57:05 +01:00
|
|
|
if let Some((irq, state)) = &mut self.inner {
|
|
|
|
irq.disable();
|
|
|
|
irq.remove_handler();
|
|
|
|
}
|
2021-01-03 01:40:40 +01:00
|
|
|
}
|
|
|
|
}
|