Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix SPI async busy wait #35

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/dma/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ impl<'d> ChannelAndRequest<'d> {
Transfer::new_write_raw(&mut self.channel, self.request, buf, peri_addr, options)
}

pub unsafe fn write_raw_with_spi_fix<'a, W: Word>(
&'a mut self,
buf: *const W,
buf_len: usize,
peri_addr: *mut W,
options: TransferOptions,
) -> Transfer<'a> {
Transfer::new_write_raw_with_spi_fix(&mut self.channel, self.request, buf, buf_len, peri_addr, options)
}

#[allow(dead_code)]
pub unsafe fn write_repeated<'a, W: Word>(
&'a mut self,
Expand Down
24 changes: 24 additions & 0 deletions src/dma/v2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,30 @@ impl<'a> Transfer<'a> {
)
}

/// Create a new write DMA transfer (memory to peripheral), using raw pointers.
pub unsafe fn new_write_raw_with_spi_fix<W: Word>(
HaoboGu marked this conversation as resolved.
Show resolved Hide resolved
channel: impl Peripheral<P = impl Channel> + 'a,
request: Request,
buf: *const W,
fixed_buf_len: usize,
peri_addr: *mut W,
options: TransferOptions,
) -> Self {
into_ref!(channel);

Self::new_inner(
channel.map_into(),
request,
Dir::MemoryToPeripheral,
peri_addr as *const u32,
buf as *mut u32,
fixed_buf_len,
true,
W::size(),
options,
)
}

/// Create a new write DMA transfer (memory to peripheral), writing the same value repeatedly.
pub unsafe fn new_write_repeated<W: Word>(
channel: impl Peripheral<P = impl Channel> + 'a,
Expand Down
101 changes: 80 additions & 21 deletions src/spi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,26 @@
//! - SPI_CS_SELECT: v53, v68,
//! - SPI_SUPPORT_DIRECTIO: v53, v68

use core::future::poll_fn;
use core::marker::PhantomData;
use core::ptr;
use core::task::Poll;

use embassy_futures::join::join;
use embassy_futures::yield_now;
use embassy_hal_internal::{into_ref, Peripheral, PeripheralRef};
use embassy_sync::waitqueue::AtomicWaker;
// re-export
pub use embedded_hal::spi::{Mode, MODE_0, MODE_1, MODE_2, MODE_3};
use futures_util::future::{select, Either};

use self::consts::*;
use crate::dma::{self, word, ChannelAndRequest};
use crate::gpio::AnyPin;
use crate::interrupt::typelevel::Interrupt as _;
use crate::mode::{Async, Blocking, Mode as PeriMode};
pub use crate::pac::spi::vals::{AddrLen, AddrPhaseFormat, DataPhaseFormat, TransMode};
use crate::time::Hertz;
use crate::{interrupt, pac};

#[cfg(any(hpm53, hpm68, hpm6e))]
mod consts {
Expand All @@ -33,7 +37,32 @@ mod consts {
pub const FIFO_SIZE: usize = 4;
}

// NOTE: SPI end interrupt is not working under DMA mode
// - MARK: interrupt handler

/// Interrupt handler.
pub struct InterruptHandler<T: Instance> {
_phantom: PhantomData<T>,
}

impl<T: Instance> interrupt::typelevel::Handler<T::Interrupt> for InterruptHandler<T> {
unsafe fn on_interrupt() {
on_interrupt(T::info().regs, T::state());

// PLIC ack is handled by typelevel Handler
}
}

unsafe fn on_interrupt(r: pac::spi::Spi, s: &'static State) {
let status = r.intr_st().read();

if status.endint() {
s.waker.wake();

r.intr_en().modify(|w| w.set_endinten(false));
}

r.intr_st().write_value(status); // W1C
}

// - MARK: Helper enums

Expand Down Expand Up @@ -378,6 +407,7 @@ impl<'d> Spi<'d, Async> {
sclk: impl Peripheral<P = impl SclkPin<T>> + 'd,
mosi: impl Peripheral<P = impl MosiPin<T>> + 'd,
miso: impl Peripheral<P = impl MisoPin<T>> + 'd,
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
tx_dma: impl Peripheral<P = impl TxDma<T>> + 'd,
rx_dma: impl Peripheral<P = impl RxDma<T>> + 'd,
config: Config,
Expand Down Expand Up @@ -410,6 +440,7 @@ impl<'d> Spi<'d, Async> {
peri: impl Peripheral<P = T> + 'd,
sclk: impl Peripheral<P = impl SclkPin<T>> + 'd,
miso: impl Peripheral<P = impl MisoPin<T>> + 'd,
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
rx_dma: impl Peripheral<P = impl RxDma<T>> + 'd,
config: Config,
) -> Self {
Expand Down Expand Up @@ -441,6 +472,7 @@ impl<'d> Spi<'d, Async> {
peri: impl Peripheral<P = T> + 'd,
sclk: impl Peripheral<P = impl SclkPin<T>> + 'd,
mosi: impl Peripheral<P = impl MosiPin<T>> + 'd,
_irq: impl interrupt::typelevel::Binding<T::Interrupt, InterruptHandler<T>> + 'd,
tx_dma: impl Peripheral<P = impl TxDma<T>> + 'd,
config: Config,
) -> Self {
Expand Down Expand Up @@ -500,27 +532,55 @@ impl<'d> Spi<'d, Async> {
}

let r = self.info.regs;
let s = self.state;

self.set_word_size(W::CONFIG);

self.configure_transfer(data.len(), 0, &TransferConfig::default())?;

r.intr_en().modify(|w| {
w.set_endinten(true);
});

r.ctrl().modify(|w| w.set_txdmaen(true));

let tx_dst = r.data().as_ptr() as *mut W;
let mut opts = dma::TransferOptions::default();
opts.burst = dma::Burst::from_size(FIFO_SIZE / 2);
let tx_f = unsafe { self.tx_dma.as_mut().unwrap().write(data, tx_dst, opts) };
let opts = dma::TransferOptions::default(); // BUG: Busrt size must be 1(default) for SPI. or else END interrupt will not be triggered.

//let tx_f = unsafe { self.tx_dma.as_mut().unwrap().write(data, tx_dst, opts) };
// BUG: No idea why "+1" is needed here, but without it, END interrupt will not be triggered.
// BUG: "+n"(n>1) also triggers END interrupt, but the data seems not correct.
let tx_f = unsafe {
self.tx_dma
.as_mut()
.unwrap()
.write_raw_with_spi_fix(data.as_ptr(), data.len() + 1, tx_dst, opts)
};

tx_f.await;
let end_f = poll_fn(move |cx| {
s.waker.register(cx.waker());
if r.intr_en().read().endinten() {
return Poll::Pending;
} else {
return Poll::Ready(());
}
});

r.ctrl().modify(|w| w.set_txdmaen(false));
// NOTE: if "+n"(n>1) is used, tx_f never finishes, use select instead of join
// join only works for "+1"
join(end_f, tx_f).await;

// NOTE: SPI end(finish) interrupt is not working under DMA mode, a busy-loop wait is necessary for TX mode.
// The same goes for `transfer` fn.
while r.status().read().spiactive() {
yield_now().await;
/*
match select(end_f, tx_f).await {
Either::Left((_v, _)) => (),
Either::Right((_v, end_f)) => {
end_f.await;
defmt::println!("end f");
}
}
*/

r.ctrl().modify(|w| w.set_txdmaen(false));

Ok(())
}
Expand Down Expand Up @@ -584,11 +644,6 @@ impl<'d> Spi<'d, Async> {
w.set_txdmaen(false);
});

// See `write`
while r.status().read().spiactive() {
yield_now().await;
}

Ok(())
}

Expand All @@ -605,8 +660,10 @@ impl<'d> Spi<'d, Async> {
/// In-place bidirectional transfer, using DMA.
///
/// This writes the contents of `data` on MOSI, and puts the received data on MISO in `data`, at the same time.
pub async fn transfer_in_place<W: Word>(&mut self, data: &mut [W], config: &TransferConfig) -> Result<(), Error> {
self.transfer_inner(data, data, config).await
pub async fn transfer_in_place<W: Word>(&mut self, data: &mut [W]) -> Result<(), Error> {
let mut config = TransferConfig::default();
config.transfer_mode = TransMode::WRITE_READ_TOGETHER;
self.transfer_inner(data, data, &config).await
}
}

Expand Down Expand Up @@ -639,6 +696,10 @@ impl<'d, M: PeriMode> Spi<'d, M> {

this.enable_and_configure(&config).unwrap();

unsafe {
T::Interrupt::enable();
}

this
}

Expand Down Expand Up @@ -1152,8 +1213,6 @@ impl<'d, W: Word> embedded_hal_async::spi::SpiBus<W> for Spi<'d, Async> {
}

async fn transfer_in_place(&mut self, words: &mut [W]) -> Result<(), Self::Error> {
let mut options = TransferConfig::default();
options.transfer_mode = TransMode::WRITE_READ_TOGETHER;
self.transfer_in_place(words, &options).await
self.transfer_in_place(words).await
}
}
Loading