Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. kernel/interrupt_controller.rs

kernel/
interrupt_controller.rs

1// Copyright 2025 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14
15use core::cell::UnsafeCell;
16
17use crate::scheduler::{PreemptDisableGuard, RescheduleReason};
18use crate::{Kernel, scheduler};
19
20/// This trait provides a generic interface to an architecture's interrupt
21/// controller, such as a RISC-V PLIC or an Arm NVIC.
22pub trait InterruptController {
23    type InterruptHandler: Copy + Sync + Send + 'static;
24
25    /// Called early in the kernel::main() function.
26    fn early_init(&self) {}
27
28    /// Enable a specific interrupt by its IRQ number.
29    fn enable_interrupt(irq: u32);
30
31    /// Disable a specific interrupt by its IRQ number.
32    fn disable_interrupt(irq: u32);
33
34    /// Userspace handling of the interrupt is complete.  Called
35    /// from [`syscall_defs::interrupt_ack(object_handle: u32, signal_mask: Signals)`]
36    fn userspace_interrupt_ack(irq: u32);
37
38    /// Userspace interrupt handlers call [`userspace_interrupt_handler_enter(kernel: K, irq: u32)`]
39    /// to mask the interrupt prior to the interrupt object being signalled.  The interrupt
40    /// is unmasked from userspace by [`userspace_interrupt_ack(irq: u32)`].
41    fn userspace_interrupt_handler_enter<K: Kernel>(kernel: K, irq: u32);
42
43    /// Userspace interrupt handler is complete.
44    ///
45    /// This consumes the `InterruptGuard` by value. When it goes out of scope,
46    /// its `Drop` implementation will handle thread termination checks and
47    /// deferred rescheduling.
48    fn userspace_interrupt_handler_exit<K: Kernel>(kernel: K, irq: u32, guard: InterruptGuard<K>);
49
50    /// Kernel interrupt handler has started.
51    fn kernel_interrupt_handler_enter<K: Kernel>(kernel: K, irq: u32);
52
53    /// Kernel interrupt handler is complete.
54    ///
55    /// This consumes the `InterruptGuard` by value. When it goes out of scope,
56    /// its `Drop` implementation will handle thread termination checks and
57    /// deferred rescheduling.
58    fn kernel_interrupt_handler_exit<K: Kernel>(kernel: K, irq: u32, guard: InterruptGuard<K>);
59
60    /// Globally enable interrupts.
61    fn enable_interrupts();
62
63    /// Globally disable interrupts.
64    fn disable_interrupts();
65
66    /// Returns `true` if interrupts are globally enabled.
67    fn interrupts_enabled() -> bool;
68
69    /// Trigger an interrupt by IRQ.  This may not be supported
70    /// on all interrupt controllers.
71    fn trigger_interrupt(irq: u32);
72}
73
74pub struct InterruptGuard<K: Kernel> {
75    kernel: K,
76    preempt_guard: Option<PreemptDisableGuard<K>>,
77    from_userspace: bool,
78    reason: RescheduleReason,
79}
80
81impl<K: Kernel> InterruptGuard<K> {
82    pub fn new(kernel: K, from_userspace: bool) -> Self {
83        Self {
84            kernel,
85            preempt_guard: Some(crate::scheduler::PreemptDisableGuard::new(kernel)),
86            from_userspace,
87            reason: RescheduleReason::Preempted,
88        }
89    }
90
91    pub fn set_reschedule_reason(&mut self, reason: RescheduleReason) {
92        self.reason = reason;
93    }
94
95    pub fn from_userspace(&self) -> bool {
96        self.from_userspace
97    }
98}
99
100impl<K: Kernel> Drop for InterruptGuard<K> {
101    fn drop(&mut self) {
102        if let Some(guard) = self.preempt_guard.take() {
103            drop(guard);
104        }
105        handle_thread_termination(self.kernel, self.from_userspace);
106        scheduler::try_deferred_reschedule(self.kernel, self.reason);
107    }
108}
109
110/// Handle conditional termination of interrupted thread
111///
112/// Checks if the current thread is terminating and was interrupted from userspace.
113/// If so, exit the thread.
114///
115/// This should be called when returning to interrupt or exception.
116pub fn handle_thread_termination<K: Kernel>(kernel: K, from_userspace: bool) {
117    if !from_userspace {
118        return;
119    }
120
121    let sched = kernel.get_scheduler().lock(kernel);
122    if sched.current_thread().is_terminating() {
123        sched.thread_exit(kernel);
124    }
125}
126
127/// StaticContext provides a context with Send & Sync for
128/// use with static instances of ForeignRc.
129pub struct StaticContext<T> {
130    inner: UnsafeCell<Option<T>>,
131}
132
133impl<T: Clone> StaticContext<T> {
134    pub const fn new() -> Self {
135        Self {
136            inner: UnsafeCell::new(None),
137        }
138    }
139
140    /// # Safety
141    /// Users of [`StaticContext::set()`] must ensure that
142    /// their calls into them are not done concurrently.
143    pub unsafe fn set(&self, val: T) {
144        unsafe { *self.inner.get() = Some(val) };
145    }
146
147    /// # Safety
148    /// Users of [`StaticContext::get()`] must ensure that
149    /// their calls into them are not done concurrently.
150    pub unsafe fn get(&self) -> Option<T> {
151        unsafe { (*self.inner.get()).clone() }
152    }
153}
154
155unsafe impl<T> Sync for StaticContext<T> {}
156unsafe impl<T> Send for StaticContext<T> {}
157
158pub type InterruptTableEntry<I> = Option<<I as InterruptController>::InterruptHandler>;