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

Runtime interrupt handler binding #1121

Closed
Closed
Show file tree
Hide file tree
Changes from all 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
2 changes: 1 addition & 1 deletion esp-hal-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ ufmt-write = { version = "0.1.0", optional = true }
# corresponding feature.
esp32 = { version = "0.28.0", features = ["critical-section"], optional = true }
esp32c2 = { version = "0.17.0", features = ["critical-section"], optional = true }
esp32c3 = { version = "0.20.0", features = ["critical-section"], optional = true }
esp32c3 = { path = "/projects/esp/esp-pacs/esp32c3", version = "0.20.0", features = ["critical-section"], optional = true }
esp32c6 = { version = "0.11.0", features = ["critical-section"], optional = true }
esp32h2 = { version = "0.7.0", features = ["critical-section"], optional = true }
esp32p4 = { git = "https://github.com/esp-rs/esp-pacs", rev = "c801d10", optional = true }
Expand Down
53 changes: 33 additions & 20 deletions esp-hal-common/src/gpio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,15 @@ use core::{convert::Infallible, marker::PhantomData};
#[cfg(any(adc, dac))]
pub(crate) use crate::analog;
pub(crate) use crate::gpio;
use crate::peripherals::{GPIO, IO_MUX};
#[cfg(any(xtensa, esp32c3))]
pub(crate) use crate::rtc_pins;
pub use crate::soc::gpio::*;
#[cfg(feature = "async")]
use crate::AsyncMode;
use crate::{
peripherals::{GPIO, IO_MUX},
BlockingMode,
};

/// Convenience type-alias for a no-pin / don't care - pin
pub type NoPinType = Gpio0<Unknown>;
Expand Down Expand Up @@ -1485,19 +1490,38 @@ impl<MODE> embedded_hal_async::digital::Wait for AnyPin<Input<MODE>> {
}

/// General Purpose Input/Output driver
pub struct IO {
pub struct IO<MODE> {
_io_mux: IO_MUX,
pub pins: Pins,
_mode: PhantomData<MODE>,
}

impl IO {
pub fn new(gpio: GPIO, io_mux: IO_MUX) -> Self {
#[cfg(feature = "async")]
impl IO<AsyncMode> {
pub fn new_async(mut gpio: GPIO, io_mux: IO_MUX) -> IO<AsyncMode> {
crate::peripherals::bind_gpio_interrupt(&mut gpio, asynch::handle_gpio_interrupt);
let pins = gpio.split();
let io = IO {
IO {
_io_mux: io_mux,
pins,
};
io
_mode: PhantomData::default(),
}
}
}

impl IO<BlockingMode> {
pub fn new(gpio: GPIO, io_mux: IO_MUX) -> IO<BlockingMode> {
let pins = gpio.split();
IO {
_io_mux: io_mux,
pins,
_mode: PhantomData::default(),
}
}

pub fn set_interrupt_handler(&mut self, handler: unsafe extern "C" fn() -> ()) {
let mut gpio = unsafe { crate::peripherals::GPIO::steal() };
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this probably needs to be in a critical section? maybe all the bind functions do, but especially this one as we may get a race condition updating the handler in operation 🤔

crate::peripherals::bind_gpio_interrupt(&mut gpio, handler);
}
}

Expand Down Expand Up @@ -2734,19 +2758,8 @@ mod asynch {
});
}

#[cfg(not(any(esp32p4)))]
#[interrupt]
unsafe fn GPIO() {
handle_gpio_interrupt();
}

#[cfg(any(esp32p4))]
#[interrupt]
unsafe fn GPIO_INT0() {
handle_gpio_interrupt();
}

fn handle_gpio_interrupt() {
#[handler]
pub(super) fn handle_gpio_interrupt() {
let intrs_bank0 = InterruptStatusRegisterAccessBank0::interrupt_status_read();

#[cfg(any(esp32, esp32s2, esp32s3, esp32p4))]
Expand Down
7 changes: 7 additions & 0 deletions esp-hal-common/src/interrupt/riscv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,13 @@ mod vectored {
Ok(())
}

/// Bind the given interrupt to the given handler
pub unsafe fn bind_interrupt(interrupt: Interrupt, handler: unsafe extern "C" fn() -> ()) {
let ptr = &peripherals::__EXTERNAL_INTERRUPTS[interrupt as usize]._handler as *const _
as *mut unsafe extern "C" fn() -> ();
ptr.write_volatile(handler);
}

/// Enables an interrupt at a given priority, maps it to the given CPU
/// interrupt and assigns the given priority.
///
Expand Down
7 changes: 7 additions & 0 deletions esp-hal-common/src/interrupt/xtensa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,13 @@ mod vectored {
Ok(())
}

/// Bind the given interrupt to the given handler
pub unsafe fn bind_interrupt(interrupt: Interrupt, handler: unsafe extern "C" fn() -> ()) {
let ptr = &peripherals::__INTERRUPTS[interrupt as usize]._handler as *const _
as *mut unsafe extern "C" fn() -> ();
ptr.write_volatile(handler);
}

fn interrupt_level_to_cpu_interrupt(
level: Priority,
is_edge: bool,
Expand Down
8 changes: 8 additions & 0 deletions esp-hal-common/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,3 +450,11 @@ impl<T, const SIZE: usize> FlashSafeDma<T, SIZE> {
self.inner
}
}

/// Driver mode async
#[non_exhaustive]
pub struct AsyncMode;

/// Driver mode non-async
#[non_exhaustive]
pub struct BlockingMode;
14 changes: 13 additions & 1 deletion esp-hal-common/src/peripheral.rs
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ mod peripheral_macros {
#[doc(hidden)]
#[macro_export]
macro_rules! peripherals {
($($(#[$cfg:meta])? $name:ident <= $from_pac:tt),*$(,)?) => {
($($(#[$cfg:meta])? $name:ident <= $from_pac:tt $(($($interrupt:ident),*))? ),*$(,)?) => {

/// Contains the generated peripherals which implement [`Peripheral`]
mod peripherals {
Expand Down Expand Up @@ -282,6 +282,18 @@ mod peripheral_macros {
$(
pub use peripherals::$name;
)*

$(
$(
$(
paste::paste!{
pub fn [<bind_ $interrupt:lower _interrupt >](_peripheral: &mut peripherals::$name, handler: unsafe extern "C" fn() -> ()) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I struggle to parse macros, so I might be missing something here, should this just be a method on the peripheral itself?

E.g

impl GPIO {
 fn bind_interrupt(&mut self, handler: extern "C" fn()) {}
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's brilliant! Much better

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should also cfg this method away if neither of the rt features are enabled too, that would be a fun one to debug if we didn't :D.

unsafe { $crate::interrupt::bind_interrupt($crate::peripherals::Interrupt::$interrupt, handler); }
}
}
)*
)*
)*
}
}

Expand Down
2 changes: 1 addition & 1 deletion esp-hal-common/src/soc/esp32c3/peripherals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ crate::peripherals! {
DS <= DS,
EFUSE <= EFUSE,
EXTMEM <= EXTMEM,
GPIO <= GPIO,
GPIO <= GPIO (GPIO,GPIO_NMI),
GPIO_SD <= GPIO_SD,
HMAC <= HMAC,
I2C0 <= I2C0,
Expand Down
2 changes: 1 addition & 1 deletion esp-hal-common/src/soc/esp32s3/peripherals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ crate::peripherals! {
DS <= DS,
EFUSE <= EFUSE,
EXTMEM <= EXTMEM,
GPIO <= GPIO,
GPIO <= GPIO (GPIO,GPIO_NMI),
GPIO_SD <= GPIO_SD,
HMAC <= HMAC,
I2C0 <= I2C0,
Expand Down
60 changes: 60 additions & 0 deletions esp-hal-procmacros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,66 @@ pub fn interrupt(args: TokenStream, input: TokenStream) -> TokenStream {
.into()
}

#[cfg(feature = "interrupt")]
#[proc_macro_attribute]
pub fn handler(args: TokenStream, input: TokenStream) -> TokenStream {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need this macro? Won't the type system i.e the set_interrupt_handler function how handle ensuring that the type is of extern "C" with no arguments?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, this is just sugar to hide the extern "C"

use proc_macro::Span;
use proc_macro_error::abort;
use syn::{parse::Error as ParseError, spanned::Spanned, ItemFn, ReturnType, Type};

use self::interrupt::{check_attr_whitelist, WhiteListCaller};

let mut f: ItemFn = syn::parse(input).expect("`#[handler]` must be applied to a function");

let attr_args = match NestedMeta::parse_meta_list(args.into()) {
Ok(v) => v,
Err(e) => {
return TokenStream::from(darling::Error::from(e).write_errors());
}
};

if attr_args.len() > 0 {
abort!(Span::call_site(), "This attribute accepts no arguments")
}

// XXX should we blacklist other attributes?

if let Err(error) = check_attr_whitelist(&f.attrs, WhiteListCaller::Interrupt) {
return error;
}

let valid_signature = f.sig.constness.is_none()
&& f.sig.abi.is_none()
&& f.sig.generics.params.is_empty()
&& f.sig.generics.where_clause.is_none()
&& f.sig.variadic.is_none()
&& match f.sig.output {
ReturnType::Default => true,
ReturnType::Type(_, ref ty) => match **ty {
Type::Tuple(ref tuple) => tuple.elems.is_empty(),
Type::Never(..) => true,
_ => false,
},
}
&& f.sig.inputs.len() <= 1;

if !valid_signature {
return ParseError::new(
f.span(),
"`#[handler]` handlers must have signature `[unsafe] fn([&mut Context]) [-> !]`",
)
.to_compile_error()
.into();
}

f.sig.abi = syn::parse_quote!(extern "C");

quote!(
#f
)
.into()
}

/// Create an enum for erased GPIO pins, using the enum-dispatch pattern
///
/// Only used internally
Expand Down
2 changes: 1 addition & 1 deletion esp32c3-hal/examples/embassy_wait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ async fn main(_spawner: Spawner) {
esp32c3_hal::timer::TimerGroup::new(peripherals.TIMG0, &clocks),
);

let io = IO::new(peripherals.GPIO, peripherals.IO_MUX);
let io = IO::new_async(peripherals.GPIO, peripherals.IO_MUX);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How does creating IO in a blocking way, prevent async calls on the pins produced? I guess the pins also need a type state :(.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we just make the async handler accessible, and document then if you want to mix async pins and interrupt pins, you must make sure to call the async handler too?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh yes ... type state everywhere

I like the idea of letting the user mix-and-match async and blocking - on the other hand forcing users to not misuse the API at compile time feels a bit cleaner. I wonder if the freedom of mixing async and blocking is something that people would like to have.

In that case it could be nice if we could at least somehow check they are calling our async handler at runtime - no idea how to do that unfortunately

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if the freedom of mixing async and blocking is something that people would like to have.

Yes, people have requested it a few times.

I've been thinking some more about this a bit, I think we really want to avoid type states in the pins. I think we can figure something out with IO mux to always call the async handler after the user handler or something like that, but this would need some thorough documentation as it would probably be quite easy to break things.

// GPIO 9 as input
let mut input = io.pins.gpio9.into_pull_down_input();

Expand Down
8 changes: 5 additions & 3 deletions esp32c3-hal/examples/gpio_interrupt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ fn main() -> ! {
let clocks = ClockControl::boot_defaults(system.clock_control).freeze();

// Set GPIO5 as an output
let io = IO::new(peripherals.GPIO, peripherals.IO_MUX);
let mut io = IO::new(peripherals.GPIO, peripherals.IO_MUX);
io.set_interrupt_handler(handler);

let mut led = io.pins.gpio5.into_push_pull_output();

// Set GPIO9 as an input
Expand All @@ -46,8 +48,8 @@ fn main() -> ! {
}
}

#[interrupt]
fn GPIO() {
#[handler]
fn handler() {
critical_section::with(|cs| {
esp_println::println!("GPIO interrupt");
BUTTON
Expand Down
2 changes: 1 addition & 1 deletion esp32s3-hal/examples/embassy_wait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ async fn main(_spawner: Spawner) {
embassy::init(&clocks, timer_group0);
}

let io = IO::new(peripherals.GPIO, peripherals.IO_MUX);
let io = IO::new_async(peripherals.GPIO, peripherals.IO_MUX);
// GPIO 0 as input
let mut input = io.pins.gpio0.into_pull_down_input();

Expand Down
10 changes: 5 additions & 5 deletions esp32s3-hal/examples/gpio_interrupt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ use esp32s3_hal::{
clock::ClockControl,
gpio::{Event, Gpio0, Input, PullDown, IO},
interrupt,
macros::ram,
peripherals::{self, Peripherals},
prelude::*,
xtensa_lx,
Expand All @@ -30,7 +29,9 @@ fn main() -> ! {
let clocks = ClockControl::boot_defaults(system.clock_control).freeze();

// Set GPIO15 as an output, and set its state high initially.
let io = IO::new(peripherals.GPIO, peripherals.IO_MUX);
let mut io = IO::new(peripherals.GPIO, peripherals.IO_MUX);
io.set_interrupt_handler(handler);

let mut led = io.pins.gpio15.into_push_pull_output();
let mut button = io.pins.gpio0.into_pull_down_input();
button.listen(Event::FallingEdge);
Expand All @@ -51,9 +52,8 @@ fn main() -> ! {
}
}

#[ram]
#[interrupt]
fn GPIO() {
#[handler]
fn handler() {
esp_println::println!(
"GPIO Interrupt with priority {}",
xtensa_lx::interrupt::get_level()
Expand Down
Loading