use core::cell::Cell;
use core::cell::UnsafeCell;
use core::mem::ManuallyDrop;
use core::ops::Range;
use core::sync::atomic::compiler_fence;
use core::sync::atomic::Ordering;
use crate::pac;
use crate::Sio;
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum Error {
InvalidCore,
Unresponsive,
}
#[cfg(all(target_arch = "arm", target_os = "none"))]
fn install_stack_guard(stack_limit: *mut usize) {
unsafe {
cortex_m::register::msplim::write(stack_limit as u32);
}
}
#[cfg(not(all(target_arch = "arm", target_os = "none")))]
#[inline(always)]
fn install_stack_guard(_stack_limit: *mut usize) {
}
#[inline(always)]
fn core1_setup(stack_limit: *mut usize) {
install_stack_guard(stack_limit);
#[cfg(all(target_arch = "arm", target_os = "none"))]
unsafe {
crate::arch::enable_coprocessors()
};
}
fn enable_actlr_extexclall() {
unsafe {
(*cortex_m::peripheral::ICB::PTR)
.actlr
.modify(|w| w | (1 << 29));
}
}
pub struct Multicore<'p> {
cores: [Core<'p>; 2],
}
#[repr(C, align(32))]
pub struct Stack<const SIZE: usize> {
mem: UnsafeCell<[usize; SIZE]>,
taken: Cell<bool>,
}
impl<const SIZE: usize> Default for Stack<SIZE> {
fn default() -> Self {
Self::new()
}
}
unsafe impl<const SIZE: usize> Sync for Stack<SIZE> {}
impl<const SIZE: usize> Stack<SIZE> {
pub const fn new() -> Stack<SIZE> {
const { assert!(SIZE >= 64, "Stack too small") };
Stack {
mem: UnsafeCell::new([0; SIZE]),
taken: Cell::new(false),
}
}
pub fn take(&self) -> Option<StackAllocation> {
let taken = critical_section::with(|_| self.taken.replace(true));
if taken {
None
} else {
unsafe {
let start = self.mem.get() as *mut usize;
let end = start.add(SIZE);
Some(StackAllocation::from_raw_parts(start, end))
}
}
}
pub unsafe fn reset(&self) {
self.taken.replace(false);
}
}
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct StackAllocation {
mem: Range<*mut usize>,
}
impl StackAllocation {
fn get(&self) -> Range<*mut usize> {
self.mem.clone()
}
pub unsafe fn from_raw_parts(start: *mut usize, end: *mut usize) -> Self {
StackAllocation { mem: start..end }
}
}
impl<const SIZE: usize> From<&Stack<SIZE>> for Option<StackAllocation> {
fn from(stack: &Stack<SIZE>) -> Self {
let taken = critical_section::with(|_| stack.taken.replace(true));
if taken {
None
} else {
unsafe {
let start = stack.mem.get() as *mut usize;
let end = start.add(SIZE);
Some(StackAllocation::from_raw_parts(start, end))
}
}
}
}
impl<'p> Multicore<'p> {
pub fn new(
psm: &'p mut pac::PSM,
ppb: &'p mut pac::PPB,
sio: &'p mut crate::sio::SioFifo,
) -> Self {
Self {
cores: [
Core { inner: None },
Core {
inner: Some((psm, ppb, sio)),
},
],
}
}
pub fn cores(&mut self) -> &mut [Core<'p>] {
&mut self.cores
}
}
pub struct Core<'p> {
inner: Option<(
&'p mut pac::PSM,
&'p mut pac::PPB,
&'p mut crate::sio::SioFifo,
)>,
}
impl Core<'_> {
pub fn id(&self) -> u8 {
match self.inner {
None => 0,
Some(..) => 1,
}
}
pub fn spawn<F>(&mut self, stack: StackAllocation, entry: F) -> Result<(), Error>
where
F: FnOnce() + Send + 'static,
{
enable_actlr_extexclall();
if let Some((psm, ppb, fifo)) = self.inner.as_mut() {
extern "C" fn core1_startup<F: FnOnce()>(
_: u64,
_: u64,
entry: *mut ManuallyDrop<F>,
stack_limit: *mut usize,
) -> ! {
enable_actlr_extexclall();
core1_setup(stack_limit);
let entry = unsafe { ManuallyDrop::take(&mut *entry) };
compiler_fence(Ordering::SeqCst);
let peripherals = unsafe { pac::Peripherals::steal() };
let mut sio = Sio::new(peripherals.SIO);
sio.fifo.write_blocking(1);
entry();
loop {
crate::arch::wfe()
}
}
psm.frce_off().modify(|_, w| w.proc1().set_bit());
while !psm.frce_off().read().proc1().bit_is_set() {
crate::arch::nop();
}
psm.frce_off().modify(|_, w| w.proc1().clear_bit());
let stack = stack.get();
let mut stack_ptr = stack.end;
let misalignment_offset = stack_ptr.align_offset(8);
let mut entry = ManuallyDrop::new(entry);
unsafe {
stack_ptr = stack_ptr.sub(misalignment_offset);
stack_ptr = stack_ptr.sub(1);
stack_ptr.cast::<*mut usize>().write(stack.start);
stack_ptr = stack_ptr.sub(1);
stack_ptr.cast::<*mut ManuallyDrop<F>>().write(&mut entry);
}
compiler_fence(Ordering::Release);
let vector_table = ppb.vtor().read().bits();
let cmd_seq = [
0,
0,
1,
vector_table as usize,
stack_ptr as usize,
core1_startup::<F> as *const () as usize,
];
let mut seq = 0;
let mut fails = 0;
loop {
let cmd = cmd_seq[seq] as u32;
if cmd == 0 {
fifo.drain();
crate::arch::sev();
}
fifo.write_blocking(cmd);
let response = fifo.read_blocking();
if cmd == response {
seq += 1;
} else {
seq = 0;
fails += 1;
if fails > 16 {
drop(ManuallyDrop::into_inner(entry));
return Err(Error::Unresponsive);
}
}
if seq >= cmd_seq.len() {
break;
}
}
fifo.read_blocking();
Ok(())
} else {
Err(Error::InvalidCore)
}
}
}