Skip to main content

esp_hal/interrupt/
mod.rs

1//! # Interrupt support
2//!
3//! This module contains code to configure and handle peripheral interrupts.
4//!
5//! ## Overview
6//!
7//! Peripheral interrupt requests are not handled by the CPU directly. Instead, they are routed
8//! through the interrupt matrix, which maps peripheral interrupts to CPU interrupts. There are
9//! more peripheral interrupt signals than CPU interrupts, and multiple peripheral interrupts can
10//! be routed to the same CPU interrupt. A set of CPU interrupts are configured to run a default
11//! handler routine, which polls the interrupt controller and calls the appropriate handlers for the
12//! pending peripheral interrupts.
13//!
14//! This default handler implements interrupt nesting - meaning a higher [`Priority`] interrupt can
15//! preempt a lower priority interrupt handler. The number of priorities is a chip-specific detail.
16//!
17//! ## Usage
18//!
19//! Peripheral drivers manage interrupts for you. Where appropriate, a `set_interrupt_handler`
20//! function is provided to register a function that handles interrupts at a chosen priority
21//! level. Interrupt handler functions need to be marked by the [`#[handler]`][crate::handler]
22//! attribute. These drivers also provide `listen` and `unlisten` functions that control whether an
23//! interrupt will be generated for the matching event or not. For more information and examples,
24//! consult the documentation of the specific peripheral drivers.
25//!
26//! If you are writing your own peripheral driver, you will need to first register interrupt
27//! handlers using the [peripheral singletons'][crate::peripherals::I2C0] `bind_X_interrupt`
28//! functions. You can use the matching `enable` and `disable` functions to control the peripheral
29//! interrupt in the interrupt matrix, or you can, depending on the peripheral, set or clear the
30//! appropriate enable bits in the `int_ena` register.
31//!
32//! ## Software Interrupts
33//!
34//! The [`software`] module implements software interrupts using peripheral interrupt signals.
35#![cfg_attr(
36    multi_core,
37    doc = "Those signals can also carry cross-core communication."
38)]
39#![cfg_attr(
40    multi_core,
41    doc = "
42## Inter-Processor Call (IPC)
43
44The [`ipc`] module queues requests on a CPU, and raises the IPC interrupt of that CPU.
45"
46)]
47#![cfg_attr(
48    all(feature = "rt", multi_core, xtensa),
49    doc = "The HAL reserves `FROM_CPU_INTR0` and `FROM_CPU_INTR1` for this path."
50)]
51#![cfg_attr(
52    all(feature = "rt", single_core, context_switch_source = "from_cpu"),
53    doc = "The HAL reserves `FROM_CPU_INTR0` to switch tasks."
54)]
55#![cfg_attr(
56    all(feature = "rt", context_switch_source = "software0"),
57    doc = "
58## Context Switching
59
60The HAL defines the `Software0` interrupt handler, and switches tasks in that interrupt.
61"
62)]
63
64use crate::{peripherals::Interrupt, system::Cpu};
65
66cfg_select! {
67    esp32 => {
68        use crate::peripherals::{DPORT as INTERRUPT_CORE0, DPORT as INTERRUPT_CORE1};
69    }
70    _ => {
71        use crate::peripherals::INTERRUPT_CORE0;
72        #[cfg(multi_core)]
73        use crate::peripherals::INTERRUPT_CORE1;
74    }
75}
76
77#[cfg_attr(riscv, path = "riscv.rs")]
78#[cfg_attr(xtensa, path = "xtensa.rs")]
79mod arch;
80pub use arch::*;
81
82use crate::pac;
83
84unstable_module! {
85    pub mod software;
86
87    #[cfg(multi_core)]
88    pub mod ipc;
89
90    #[cfg(feature = "rt")]
91    #[doc(hidden)]
92    pub mod __rtos_implementation;
93}
94
95#[cfg(feature = "rt")]
96#[unsafe(no_mangle)]
97extern "C" fn EspDefaultHandler() {
98    panic!("Unhandled interrupt on {:?}", crate::system::Cpu::current());
99}
100
101/// Default (unhandled) interrupt handler
102#[instability::unstable]
103pub const DEFAULT_INTERRUPT_HANDLER: InterruptHandler = InterruptHandler::new(
104    {
105        unsafe extern "C" {
106            fn EspDefaultHandler();
107        }
108
109        unsafe {
110            core::mem::transmute::<unsafe extern "C" fn(), extern "C" fn()>(EspDefaultHandler)
111        }
112    },
113    Priority::min(),
114);
115
116/// Trait implemented by drivers that support registering an
117/// [`InterruptHandler`].
118#[instability::unstable]
119pub trait InterruptConfigurable: crate::private::Sealed {
120    #[doc = cfg_select! {
121        multi_core => "Registers an interrupt handler for the peripheral on the current core.",
122        _ => "Registers an interrupt handler for the peripheral.",
123    }]
124    #[doc = ""]
125    /// Replaces any previously registered interrupt handlers. Some peripherals
126    /// offer a shared interrupt handler for multiple purposes. The caller must
127    /// honor this constraint.
128    ///
129    /// The default/unhandled interrupt handler can be restored with
130    /// [`DEFAULT_INTERRUPT_HANDLER`].
131    fn set_interrupt_handler(&mut self, handler: InterruptHandler);
132}
133
134/// Represents an ISR callback function.
135#[derive(Copy, Clone, Debug)]
136#[cfg_attr(feature = "defmt", derive(defmt::Format))]
137#[instability::unstable]
138pub struct IsrCallback {
139    f: extern "C" fn(),
140}
141
142impl IsrCallback {
143    /// Creates a new callback from the callback function.
144    pub fn new(f: extern "C" fn()) -> Self {
145        // a valid fn pointer is non zero
146        Self { f }
147    }
148
149    /// Returns the address of the callback.
150    pub fn address(self) -> usize {
151        self.f as usize
152    }
153
154    /// The callback function.
155    ///
156    /// This is aligned and can be called.
157    pub fn callback(self) -> extern "C" fn() {
158        self.f
159    }
160}
161
162impl PartialEq for IsrCallback {
163    fn eq(&self, other: &Self) -> bool {
164        core::ptr::fn_addr_eq(self.callback(), other.callback())
165    }
166}
167
168/// An interrupt handler.
169#[cfg_attr(
170    multi_core,
171    doc = r"
172
173**Note**: Interrupts are handled on the core they were setup on. If a driver is initialized
174on core 0, and moved to core 1, core 0 will still handle the interrupt."
175)]
176#[derive(Copy, Clone, Debug)]
177#[cfg_attr(feature = "defmt", derive(defmt::Format))]
178#[instability::unstable]
179pub struct InterruptHandler {
180    f: extern "C" fn(),
181    prio: Priority,
182}
183
184impl InterruptHandler {
185    /// Creates a new [`InterruptHandler`] which will call the given function at
186    /// the given priority.
187    pub const fn new(f: extern "C" fn(), prio: Priority) -> Self {
188        Self { f, prio }
189    }
190
191    /// The Isr callback.
192    #[inline]
193    pub fn handler(&self) -> IsrCallback {
194        IsrCallback::new(self.f)
195    }
196
197    /// Returns the priority used when registering the interrupt.
198    #[inline]
199    pub fn priority(&self) -> Priority {
200        self.prio
201    }
202}
203
204const STATUS_WORDS: usize = property!("interrupts.status_registers");
205
206/// Representation of peripheral-interrupt status bits.
207#[derive(Clone, Copy, Default, Debug)]
208#[instability::unstable]
209pub struct InterruptStatus {
210    // Every set bit names a variant of `Interrupt`.
211    status: [u32; STATUS_WORDS],
212}
213
214impl InterruptStatus {
215    /// Returns the status of a particular peripheral interrupt.
216    #[instability::unstable]
217    #[inline]
218    pub fn is_pending(interrupt: Interrupt) -> bool {
219        let word = (interrupt as usize) / 32;
220        let bit = (interrupt as usize) % 32;
221        let mut status_word = 0;
222        for cpu in Cpu::all() {
223            status_word |= Self::interrupt_status_word(cpu, word);
224        }
225        (status_word & (1 << bit)) != 0
226    }
227
228    #[inline]
229    fn interrupt_status_word(cpu: Cpu, word: usize) -> u32 {
230        match cpu {
231            Cpu::ProCpu => {
232                cfg_select! {
233                    esp32p4 => {
234                        if word == 4 {
235                            // Discontiguous, cannot be part of the standard status array
236                            return INTERRUPT_CORE0::regs().core_0_intr_status4().read().bits();
237                        }
238                    }
239                    _ => {}
240                }
241
242                INTERRUPT_CORE0::regs()
243                    .core_0_intr_status(word)
244                    .read()
245                    .bits()
246            }
247            #[cfg(multi_core)]
248            Cpu::AppCpu => {
249                cfg_select! {
250                    esp32p4 => {
251                        if word == 4 {
252                            // Discontiguous, cannot be part of the standard status array
253                            return INTERRUPT_CORE1::regs().core_1_intr_status4().read().bits();
254                        }
255                    }
256                    _ => {}
257                }
258
259                INTERRUPT_CORE1::regs()
260                    .core_1_intr_status(word)
261                    .read()
262                    .bits()
263            }
264        }
265    }
266
267    /// Returns the status of peripheral interrupts.
268    ///
269    /// A status bit with no [`Interrupt`] variant reads as clear.
270    #[instability::unstable]
271    pub fn current() -> InterruptStatus {
272        let cpu = Cpu::current();
273        InterruptStatus {
274            // `Interrupt::MASK` and the status registers can have different word counts.
275            status: core::array::from_fn(|word| {
276                Self::interrupt_status_word(cpu, word)
277                    & Interrupt::MASK.get(word).copied().unwrap_or(0)
278            }),
279        }
280    }
281
282    /// Is the given interrupt bit set.
283    #[instability::unstable]
284    pub fn is_set(&self, interrupt: u8) -> bool {
285        (self.status[interrupt as usize / 32] & (1 << (interrupt % 32))) != 0
286    }
287
288    /// Sets the given interrupt status bit.
289    #[instability::unstable]
290    pub fn set(&mut self, interrupt: Interrupt) {
291        let interrupt = interrupt as usize;
292        self.status[interrupt / 32] |= 1 << (interrupt % 32);
293    }
294
295    /// Returns an iterator over the set interrupt status bits.
296    #[instability::unstable]
297    pub fn iterator(&self) -> InterruptStatusIterator {
298        InterruptStatusIterator {
299            status: *self,
300            idx: 0,
301        }
302    }
303}
304
305/// Iterator over set interrupt status bits
306#[derive(Debug, Clone)]
307#[instability::unstable]
308pub struct InterruptStatusIterator {
309    status: InterruptStatus,
310    idx: usize,
311}
312
313impl Iterator for InterruptStatusIterator {
314    type Item = Interrupt;
315
316    #[inline(always)]
317    fn next(&mut self) -> Option<Self::Item> {
318        for i in self.idx..STATUS_WORDS {
319            if let Some(bit) = self.status.status[i].lowest_one() {
320                self.status.status[i] ^= 1 << bit;
321                self.idx = i;
322                let nr = (bit + 32 * i as u32) as u16;
323                // SAFETY: every set bit in `InterruptStatus` names a variant of `Interrupt`.
324                return Some(unsafe { core::mem::transmute::<u16, Interrupt>(nr) });
325            }
326        }
327        self.idx = usize::MAX;
328        None
329    }
330}
331
332// Peripheral interrupt API.
333
334fn vector_entry(interrupt: Interrupt) -> &'static pac::Vector {
335    unsafe extern "Rust" {
336        #[cfg(xtensa)]
337        static __INTERRUPTS: pac::Vector;
338        #[cfg(riscv)]
339        static __EXTERNAL_INTERRUPTS: pac::Vector;
340    }
341
342    // SAFETY: Interrupt numbers are guaranteed to be valid and in range because we use the
343    // Interrupt enum, which is generated from the list of valid peripheral interrupts in the PAC.
344    unsafe {
345        cfg_select! {
346            xtensa => (&__INTERRUPTS as *const pac::Vector)
347                .add(interrupt as usize)
348                .as_ref_unchecked(),
349            riscv => (&__EXTERNAL_INTERRUPTS as *const pac::Vector)
350                .add(interrupt as usize)
351                .as_ref_unchecked(),
352            _ => {
353                compile_error!("Unsupported architecture");
354            }
355        }
356    }
357}
358
359/// Returns the currently bound interrupt handler.
360#[instability::unstable]
361pub fn bound_handler(interrupt: Interrupt) -> Option<IsrCallback> {
362    unsafe {
363        let vector = vector_entry(interrupt);
364
365        let addr = vector._handler;
366        if addr as usize == 0 {
367            return None;
368        }
369
370        Some(IsrCallback::new(core::mem::transmute::<
371            unsafe extern "C" fn(),
372            extern "C" fn(),
373        >(addr)))
374    }
375}
376
377/// Binds the given handler to a peripheral interrupt.
378///
379/// The interrupt handler will be enabled at the specified priority level.
380///
381/// The interrupt handler will be called on the core where it is registered.
382/// Only one interrupt handler can be bound to a peripheral interrupt.
383#[instability::unstable]
384pub fn bind_handler(interrupt: Interrupt, handler: InterruptHandler) {
385    bind_vector(interrupt, handler);
386    enable(interrupt, handler.priority());
387}
388
389/// Binds `handler` to `interrupt` without enabling the peripheral interrupt.
390pub(crate) fn bind_vector(interrupt: Interrupt, handler: InterruptHandler) {
391    unsafe {
392        let vector = vector_entry(interrupt);
393        let ptr = (&raw const vector._handler).cast::<usize>().cast_mut();
394
395        #[cfg(all(riscv, write_vec_table_monitoring))]
396        if crate::soc::trap_section_protected() {
397            crate::debugger::DEBUGGER_LOCK.lock(|| {
398                let wp = crate::debugger::clear_watchpoint(1);
399                ptr.write_volatile(handler.handler().address());
400                crate::debugger::restore_watchpoint(1, wp);
401            });
402            return;
403        }
404
405        ptr.write_volatile(handler.handler().address());
406    }
407}
408
409/// Enables a peripheral interrupt at a given priority, using vectored CPU interrupts.
410///
411/// Interrupts must still be enabled globally for interrupts to be serviced.
412///
413/// Internally maps the interrupt to the appropriate CPU interrupt
414/// for the specified priority level.
415#[inline]
416#[instability::unstable]
417pub fn enable(interrupt: Interrupt, level: Priority) {
418    enable_on_cpu(Cpu::current(), interrupt, level);
419}
420
421pub(crate) fn enable_on_cpu(cpu: Cpu, interrupt: Interrupt, level: Priority) {
422    let cpu_interrupt = priority_to_cpu_interrupt(interrupt, level);
423    map_raw(cpu, interrupt, cpu_interrupt as u32);
424}
425
426/// Disables the given peripheral interrupt.
427///
428/// Internally maps the interrupt to a disabled CPU interrupt.
429#[inline]
430#[instability::unstable]
431pub fn disable(core: Cpu, interrupt: Interrupt) {
432    map_raw(core, interrupt, DISABLED_CPU_INTERRUPT)
433}
434
435pub(super) fn map_raw(core: Cpu, interrupt: Interrupt, cpu_interrupt: u32) {
436    match core {
437        Cpu::ProCpu => {
438            INTERRUPT_CORE0::regs()
439                .core_0_intr_map(interrupt as usize)
440                .modify(|_, w| unsafe { w.map().bits(cpu_interrupt as u8) });
441        }
442        #[cfg(multi_core)]
443        Cpu::AppCpu => {
444            INTERRUPT_CORE1::regs()
445                .core_1_intr_map(interrupt as usize)
446                .modify(|_, w| unsafe { w.map().bits(cpu_interrupt as u8) });
447        }
448    }
449}
450
451/// Returns the CPU interrupt assigned to peripheral interrupt.
452#[cfg(all(feature = "rt", gpio_driver_supported))]
453pub(crate) fn mapped_to(cpu: Cpu, interrupt: Interrupt) -> Option<CpuInterrupt> {
454    mapped_to_raw(cpu, interrupt as u32)
455}
456
457#[cfg(feature = "rt")]
458#[crate::ram]
459pub(crate) fn mapped_to_raw(cpu: Cpu, interrupt: u32) -> Option<CpuInterrupt> {
460    let cpu_intr = match cpu {
461        Cpu::ProCpu => INTERRUPT_CORE0::regs()
462            .core_0_intr_map(interrupt as usize)
463            .read()
464            .map()
465            .bits() as u32,
466        #[cfg(multi_core)]
467        Cpu::AppCpu => INTERRUPT_CORE1::regs()
468            .core_1_intr_map(interrupt as usize)
469            .read()
470            .map()
471            .bits() as u32,
472    };
473    CpuInterrupt::from_u32(cpu_intr)
474}
475
476/// Represents the priority level of running code.
477///
478/// Interrupts at or below this level are masked.
479#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
480#[cfg_attr(feature = "defmt", derive(defmt::Format))]
481#[non_exhaustive]
482pub enum RunLevel {
483    /// Thread mode.
484    ///
485    /// This is the lowest level. No interrupts are masked by the run level.
486    ThreadMode,
487
488    /// An elevated level, usually an interrupt handler's.
489    Interrupt(ElevatedRunLevel),
490}
491
492impl RunLevel {
493    #[procmacros::doc_replace]
494    /// Returns the current run level.
495    ///
496    /// # Examples
497    ///
498    /// ```rust, no_run
499    /// # {before_snippet}
500    /// use esp_hal::interrupt::RunLevel;
501    ///
502    /// let level = RunLevel::current();
503    /// println!("Current run level: {:?}", level);
504    /// # {after_snippet}
505    /// ```
506    #[inline]
507    pub fn current() -> Self {
508        let raw = current_raw_runlevel();
509        unwrap!(Self::try_from_u32(raw))
510    }
511
512    /// Changes the current run level to the specified level and returns the previous level.
513    ///
514    /// # Safety
515    ///
516    /// Must only be used to raise the run level and to restore it to a previous
517    /// value. Must not be used to arbitrarily lower the run level.
518    #[inline]
519    #[instability::unstable]
520    pub unsafe fn change(to: Self) -> Self {
521        unsafe { change_current_runlevel(to) }
522    }
523
524    #[procmacros::doc_replace]
525    /// Returns whether the run level indicates thread mode.
526    ///
527    /// Thread mode means the CPU is not executing an interrupt handler.
528    ///
529    /// # Examples
530    ///
531    /// ```rust, no_run
532    /// # {before_snippet}
533    /// use esp_hal::interrupt::RunLevel;
534    ///
535    /// let level = RunLevel::current();
536    ///
537    /// if level.is_thread() {
538    ///     println!("Running in thread mode");
539    /// } else {
540    ///     println!("Running in an interrupt handler");
541    /// }
542    /// # {after_snippet}
543    /// ```
544    #[inline]
545    pub fn is_thread(&self) -> bool {
546        matches!(self, RunLevel::ThreadMode)
547    }
548
549    pub(crate) fn try_from_u32(priority: u32) -> Result<Self, PriorityError> {
550        if priority == 0 {
551            Ok(RunLevel::ThreadMode)
552        } else {
553            ElevatedRunLevel::try_from_u32(priority).map(RunLevel::Interrupt)
554        }
555    }
556}
557
558impl PartialEq<ElevatedRunLevel> for RunLevel {
559    fn eq(&self, other: &ElevatedRunLevel) -> bool {
560        *self == RunLevel::Interrupt(*other)
561    }
562}
563
564impl PartialEq<Priority> for RunLevel {
565    fn eq(&self, other: &Priority) -> bool {
566        let runlevel = ElevatedRunLevel::from(*other);
567        *self == RunLevel::Interrupt(runlevel)
568    }
569}
570
571impl From<RunLevel> for u32 {
572    fn from(level: RunLevel) -> Self {
573        match level {
574            RunLevel::ThreadMode => 0,
575            RunLevel::Interrupt(priority) => priority as u32,
576        }
577    }
578}
579
580/// Priority Level Error.
581#[derive(Copy, Clone, Debug, PartialEq, Eq)]
582#[cfg_attr(feature = "defmt", derive(defmt::Format))]
583#[instability::unstable]
584pub enum PriorityError {
585    /// The priority is not valid.
586    InvalidInterruptPriority,
587}
588
589#[instability::unstable]
590impl TryFrom<u32> for RunLevel {
591    type Error = PriorityError;
592
593    fn try_from(priority: u32) -> Result<Self, Self::Error> {
594        Self::try_from_u32(priority)
595    }
596}
597
598#[cfg(feature = "rt")]
599pub(crate) fn setup_interrupts() {
600    // disable all known peripheral interrupts
601    for peripheral_interrupt in 0..255 {
602        crate::peripherals::Interrupt::try_from(peripheral_interrupt)
603            .map(|intr| {
604                #[cfg(multi_core)]
605                disable(Cpu::AppCpu, intr);
606                disable(Cpu::ProCpu, intr);
607            })
608            .ok();
609    }
610
611    unsafe { crate::interrupt::init_vectoring() };
612}
613
614#[inline(always)]
615#[cfg(feature = "rt")]
616fn should_handle(core: Cpu, interrupt_nr: u32, level: u32) -> bool {
617    if let Some(cpu_interrupt) = crate::interrupt::mapped_to_raw(core, interrupt_nr)
618        && cpu_interrupt.is_vectored()
619        && cpu_interrupt.level() == level
620    {
621        true
622    } else {
623        false
624    }
625}