Skip to main content

kernel/irq/
request.rs

1// SPDX-License-Identifier: GPL-2.0
2// SPDX-FileCopyrightText: Copyright 2025 Collabora ltd.
3
4//! This module provides types like [`Registration`] and
5//! [`ThreadedRegistration`], which allow users to register handlers for a given
6//! IRQ line.
7
8use core::marker::PhantomPinned;
9
10use crate::alloc::Allocator;
11use crate::device::{Bound, Device};
12use crate::devres::Devres;
13use crate::error::to_result;
14use crate::irq::flags::Flags;
15use crate::prelude::*;
16use crate::str::CStr;
17use crate::sync::{aref::ARef, Arc};
18
19/// The value that can be returned from a [`Handler`] or a [`ThreadedHandler`].
20#[repr(u32)]
21pub enum IrqReturn {
22    /// The interrupt was not from this device or was not handled.
23    None = bindings::irqreturn_IRQ_NONE,
24
25    /// The interrupt was handled by this device.
26    Handled = bindings::irqreturn_IRQ_HANDLED,
27}
28
29/// Callbacks for an IRQ handler.
30pub trait Handler: Sync + 'static {
31    /// The hard IRQ handler.
32    ///
33    /// This is executed in interrupt context, hence all corresponding
34    /// limitations do apply.
35    ///
36    /// All work that does not necessarily need to be executed from
37    /// interrupt context, should be deferred to a threaded handler.
38    /// See also [`ThreadedRegistration`].
39    fn handle(&self, device: &Device<Bound>) -> IrqReturn;
40}
41
42impl<T: ?Sized + Handler + Send> Handler for Arc<T> {
43    fn handle(&self, device: &Device<Bound>) -> IrqReturn {
44        T::handle(self, device)
45    }
46}
47
48impl<T: ?Sized + Handler, A: Allocator + 'static> Handler for Box<T, A> {
49    fn handle(&self, device: &Device<Bound>) -> IrqReturn {
50        T::handle(self, device)
51    }
52}
53
54/// # Invariants
55///
56/// - `self.irq` is the same as the one passed to `request_{threaded}_irq`.
57/// - `&self` was passed to `request_{threaded}_irq` as the cookie. It is guaranteed to be unique
58///   by the type system, since each call to `new` will return a different instance of
59///   `Registration`.
60/// - `self.handler` points to a valid instance of the handler `T` that lives at least until
61///   `Self::drop` completes.
62#[pin_data(PinnedDrop)]
63struct RegistrationInner {
64    irq: u32,
65    dev: ARef<Device>,
66    handler: *const c_void,
67    #[pin]
68    _pin: PhantomPinned,
69}
70
71impl RegistrationInner {
72    fn synchronize(&self) {
73        // SAFETY: safe as per the invariants of `RegistrationInner`
74        unsafe { bindings::synchronize_irq(self.irq) };
75    }
76}
77
78#[pinned_drop]
79impl PinnedDrop for RegistrationInner {
80    fn drop(self: Pin<&mut Self>) {
81        // SAFETY:
82        //
83        // Safe as per the invariants of `RegistrationInner` and:
84        //
85        // - `RegistrationInner` is `!Unpin` and was initialized using
86        // pin-init, so it occupied the same memory location for the entirety of
87        // its lifetime.
88        //
89        // Notice that this will block until all handlers finish executing,
90        // i.e.: at no point will &self be invalid while the handler is running.
91        unsafe {
92            bindings::free_irq(
93                self.irq,
94                core::ptr::from_mut::<Self>(self.get_unchecked_mut()).cast::<c_void>(),
95            )
96        };
97    }
98}
99
100// SAFETY: `RegistrationInner` has no interior mutability and `handler` points to a `Sync` handler.
101unsafe impl Sync for RegistrationInner {}
102
103// SAFETY: It is safe to send `RegistrationInner` across threads.
104unsafe impl Send for RegistrationInner {}
105
106/// A request for an IRQ line for a given device.
107///
108/// # Invariants
109///
110/// - `ìrq` is the number of an interrupt source of `dev`.
111/// - `irq` has not been registered yet.
112pub struct IrqRequest<'a> {
113    dev: &'a Device<Bound>,
114    irq: u32,
115}
116
117impl<'a> IrqRequest<'a> {
118    /// Creates a new IRQ request for the given device and IRQ number.
119    ///
120    /// # Safety
121    ///
122    /// - `irq` should be a valid IRQ number for `dev`.
123    pub(crate) unsafe fn new(dev: &'a Device<Bound>, irq: u32) -> Self {
124        // INVARIANT: `irq` is a valid IRQ number for `dev`.
125        IrqRequest { dev, irq }
126    }
127
128    /// Returns the IRQ number of an [`IrqRequest`].
129    pub fn irq(&self) -> u32 {
130        self.irq
131    }
132}
133
134/// A registration of an IRQ handler for a given IRQ line.
135///
136/// # Examples
137///
138/// The following is an example of using `Registration`. It uses a
139/// [`Completion`] to coordinate between the IRQ
140/// handler and process context. [`Completion`] uses interior mutability, so the
141/// handler can signal with [`Completion::complete_all()`] and the process
142/// context can wait with [`Completion::wait_for_completion()`] even though
143/// there is no way to get a mutable reference to the any of the fields in
144/// `Data`.
145///
146/// [`Completion`]: kernel::sync::Completion
147/// [`Completion::complete_all()`]: kernel::sync::Completion::complete_all
148/// [`Completion::wait_for_completion()`]: kernel::sync::Completion::wait_for_completion
149///
150/// ```
151/// use kernel::device::{Bound, Device};
152/// use kernel::irq::{self, Flags, IrqRequest, IrqReturn, Registration};
153/// use kernel::prelude::*;
154/// use kernel::sync::{Arc, Completion};
155///
156/// // Data shared between process and IRQ context.
157/// #[pin_data]
158/// struct Data {
159///     #[pin]
160///     completion: Completion,
161/// }
162///
163/// impl irq::Handler for Data {
164///     // Executed in IRQ context.
165///     fn handle(&self, _dev: &Device<Bound>) -> IrqReturn {
166///         self.completion.complete_all();
167///         IrqReturn::Handled
168///     }
169/// }
170///
171/// // Registers an IRQ handler for the given IrqRequest.
172/// //
173/// // This runs in process context and assumes `request` was previously acquired from a device.
174/// fn register_irq(
175///     handler: impl PinInit<Data, Error>,
176///     request: IrqRequest<'_>,
177/// ) -> Result<Arc<Registration<Data>>> {
178///     let registration = Registration::new(request, Flags::SHARED, c"my_device", handler);
179///
180///     let registration = Arc::pin_init(registration, GFP_KERNEL)?;
181///
182///     registration.handler().completion.wait_for_completion();
183///
184///     Ok(registration)
185/// }
186/// # Ok::<(), Error>(())
187/// ```
188///
189/// # Invariants
190///
191/// * We own an irq handler whose cookie is a pointer to `Self::inner`.
192#[pin_data]
193pub struct Registration<T: Handler> {
194    #[pin]
195    inner: Devres<RegistrationInner>,
196
197    #[pin]
198    handler: T,
199
200    /// Pinned because we need address stability so that we can pass a pointer
201    /// to the callback.
202    #[pin]
203    _pin: PhantomPinned,
204}
205
206impl<T: Handler> Registration<T> {
207    /// Registers the IRQ handler with the system for the given IRQ number.
208    pub fn new<'a>(
209        request: IrqRequest<'a>,
210        flags: Flags,
211        name: &'static CStr,
212        handler: impl PinInit<T, Error> + 'a,
213    ) -> impl PinInit<Self, Error> + 'a {
214        try_pin_init!(&this in Self {
215            handler <- handler,
216            inner <- Devres::new(
217                request.dev,
218                try_pin_init!(&inner_this in RegistrationInner {
219                    irq: request.irq,
220                    dev: request.dev.into(),
221                    // SAFETY: `this` is a valid pointer to the `Registration` instance.
222                    handler: unsafe { &raw const (*this.as_ptr()).handler }.cast(),
223                    _pin: PhantomPinned,
224                    _: {
225                        // SAFETY:
226                        // - The callbacks are valid for use with request_irq.
227                        // - If this succeeds, the slot is guaranteed to be valid until the
228                        //   destructor of Self runs, which will deregister the callbacks
229                        //   before the memory location becomes invalid.
230                        // - When request_irq is called, everything that handle_irq_callback will
231                        //   touch has already been initialized, so it's safe for the callback to
232                        //   be called immediately.
233                        to_result(unsafe {
234                            bindings::request_irq(
235                                request.irq,
236                                Some(handle_irq_callback::<T>),
237                                flags.into_inner(),
238                                name.as_char_ptr(),
239                                inner_this.as_ptr().cast::<c_void>(),
240                            )
241                        })?;
242                    },
243                })
244            ),
245            _pin: PhantomPinned,
246        })
247    }
248
249    /// Returns a reference to the handler that was registered with the system.
250    pub fn handler(&self) -> &T {
251        &self.handler
252    }
253
254    /// Wait for pending IRQ handlers on other CPUs.
255    ///
256    /// This will attempt to access the inner [`Devres`] container.
257    pub fn try_synchronize(&self) -> Result {
258        let inner = self.inner.try_access().ok_or(ENODEV)?;
259        inner.synchronize();
260        Ok(())
261    }
262
263    /// Wait for pending IRQ handlers on other CPUs.
264    pub fn synchronize(&self, dev: &Device<Bound>) -> Result {
265        let inner = self.inner.access(dev)?;
266        inner.synchronize();
267        Ok(())
268    }
269}
270
271/// # Safety
272///
273/// This function should be only used as the callback in `request_irq`.
274unsafe extern "C" fn handle_irq_callback<T: Handler>(_irq: i32, ptr: *mut c_void) -> c_uint {
275    // SAFETY: `ptr` is a pointer to `RegistrationInner` set in `Registration::new`
276    let inner = unsafe { &*(ptr as *const RegistrationInner) };
277    // SAFETY: `inner.handler` is a pointer to `T` set in `Registration::new`
278    let handler = unsafe { &*inner.handler.cast::<T>() };
279    // SAFETY: The irq callback is removed before the device is unbound, so the fact that the irq
280    // callback is running implies that the device has not yet been unbound.
281    let device = unsafe { inner.dev.as_bound() };
282
283    T::handle(handler, device) as c_uint
284}
285
286/// The value that can be returned from [`ThreadedHandler::handle`].
287#[repr(u32)]
288pub enum ThreadedIrqReturn {
289    /// The interrupt was not from this device or was not handled.
290    None = bindings::irqreturn_IRQ_NONE,
291
292    /// The interrupt was handled by this device.
293    Handled = bindings::irqreturn_IRQ_HANDLED,
294
295    /// The handler wants the handler thread to wake up.
296    WakeThread = bindings::irqreturn_IRQ_WAKE_THREAD,
297}
298
299/// Callbacks for a threaded IRQ handler.
300pub trait ThreadedHandler: Sync + 'static {
301    /// The hard IRQ handler.
302    ///
303    /// This is executed in interrupt context, hence all corresponding
304    /// limitations do apply. All work that does not necessarily need to be
305    /// executed from interrupt context, should be deferred to the threaded
306    /// handler, i.e. [`ThreadedHandler::handle_threaded`].
307    ///
308    /// The default implementation returns [`ThreadedIrqReturn::WakeThread`].
309    #[expect(unused_variables)]
310    fn handle(&self, device: &Device<Bound>) -> ThreadedIrqReturn {
311        ThreadedIrqReturn::WakeThread
312    }
313
314    /// The threaded IRQ handler.
315    ///
316    /// This is executed in process context. The kernel creates a dedicated
317    /// `kthread` for this purpose.
318    fn handle_threaded(&self, device: &Device<Bound>) -> IrqReturn;
319}
320
321impl<T: ?Sized + ThreadedHandler + Send> ThreadedHandler for Arc<T> {
322    fn handle(&self, device: &Device<Bound>) -> ThreadedIrqReturn {
323        T::handle(self, device)
324    }
325
326    fn handle_threaded(&self, device: &Device<Bound>) -> IrqReturn {
327        T::handle_threaded(self, device)
328    }
329}
330
331impl<T: ?Sized + ThreadedHandler, A: Allocator + 'static> ThreadedHandler for Box<T, A> {
332    fn handle(&self, device: &Device<Bound>) -> ThreadedIrqReturn {
333        T::handle(self, device)
334    }
335
336    fn handle_threaded(&self, device: &Device<Bound>) -> IrqReturn {
337        T::handle_threaded(self, device)
338    }
339}
340
341/// A registration of a threaded IRQ handler for a given IRQ line.
342///
343/// Two callbacks are required: one to handle the IRQ, and one to handle any
344/// other work in a separate thread.
345///
346/// The thread handler is only called if the IRQ handler returns
347/// [`ThreadedIrqReturn::WakeThread`].
348///
349/// # Examples
350///
351/// The following is an example of using [`ThreadedRegistration`]. It uses a
352/// [`Mutex`](kernel::sync::Mutex) to provide interior mutability.
353///
354/// ```
355/// use kernel::device::{Bound, Device};
356/// use kernel::irq::{
357///   self, Flags, IrqRequest, IrqReturn, ThreadedHandler, ThreadedIrqReturn,
358///   ThreadedRegistration,
359/// };
360/// use kernel::prelude::*;
361/// use kernel::sync::{Arc, Mutex};
362///
363/// // Declare a struct that will be passed in when the interrupt fires. The u32
364/// // merely serves as an example of some internal data.
365/// //
366/// // [`irq::ThreadedHandler::handle`] takes `&self`. This example
367/// // illustrates how interior mutability can be used when sharing the data
368/// // between process context and IRQ context.
369/// #[pin_data]
370/// struct Data {
371///     #[pin]
372///     value: Mutex<u32>,
373/// }
374///
375/// impl ThreadedHandler for Data {
376///     // This will run (in a separate kthread) if and only if
377///     // [`ThreadedHandler::handle`] returns [`WakeThread`], which it does by
378///     // default.
379///     fn handle_threaded(&self, _dev: &Device<Bound>) -> IrqReturn {
380///         let mut data = self.value.lock();
381///         *data += 1;
382///         IrqReturn::Handled
383///     }
384/// }
385///
386/// // Registers a threaded IRQ handler for the given [`IrqRequest`].
387/// //
388/// // This is executing in process context and assumes that `request` was
389/// // previously acquired from a device.
390/// fn register_threaded_irq(
391///     handler: impl PinInit<Data, Error>,
392///     request: IrqRequest<'_>,
393/// ) -> Result<Arc<ThreadedRegistration<Data>>> {
394///     let registration =
395///         ThreadedRegistration::new(request, Flags::SHARED, c"my_device", handler);
396///
397///     let registration = Arc::pin_init(registration, GFP_KERNEL)?;
398///
399///     {
400///         // The data can be accessed from process context too.
401///         let mut data = registration.handler().value.lock();
402///         *data += 1;
403///     }
404///
405///     Ok(registration)
406/// }
407/// # Ok::<(), Error>(())
408/// ```
409///
410/// # Invariants
411///
412/// * We own an irq handler whose cookie is a pointer to `Self::inner`.
413#[pin_data]
414pub struct ThreadedRegistration<T: ThreadedHandler> {
415    #[pin]
416    inner: Devres<RegistrationInner>,
417
418    #[pin]
419    handler: T,
420
421    /// Pinned because we need address stability so that we can pass a pointer
422    /// to the callback.
423    #[pin]
424    _pin: PhantomPinned,
425}
426
427impl<T: ThreadedHandler> ThreadedRegistration<T> {
428    /// Registers the IRQ handler with the system for the given IRQ number.
429    pub fn new<'a>(
430        request: IrqRequest<'a>,
431        flags: Flags,
432        name: &'static CStr,
433        handler: impl PinInit<T, Error> + 'a,
434    ) -> impl PinInit<Self, Error> + 'a {
435        try_pin_init!(&this in Self {
436            handler <- handler,
437            inner <- Devres::new(
438                request.dev,
439                try_pin_init!(&inner_this in RegistrationInner {
440                    irq: request.irq,
441                    dev: request.dev.into(),
442                    // SAFETY: `this` is a valid pointer to the `ThreadedRegistration` instance.
443                    handler: unsafe { &raw const (*this.as_ptr()).handler }.cast(),
444                    _pin: PhantomPinned,
445                    _: {
446                        // SAFETY:
447                        // - The callbacks are valid for use with request_threaded_irq.
448                        // - If this succeeds, the slot is guaranteed to be valid until the
449                        //   destructor of Self runs, which will deregister the callbacks
450                        //   before the memory location becomes invalid.
451                        // - When request_threaded_irq is called, everything that the two callbacks
452                        //   will touch has already been initialized, so it's safe for the
453                        //   callbacks to be called immediately.
454                        to_result(unsafe {
455                            bindings::request_threaded_irq(
456                                request.irq,
457                                Some(handle_threaded_irq_callback::<T>),
458                                Some(thread_fn_callback::<T>),
459                                flags.into_inner(),
460                                name.as_char_ptr(),
461                                inner_this.as_ptr().cast::<c_void>(),
462                            )
463                        })?;
464                    },
465                })
466            ),
467            _pin: PhantomPinned,
468        })
469    }
470
471    /// Returns a reference to the handler that was registered with the system.
472    pub fn handler(&self) -> &T {
473        &self.handler
474    }
475
476    /// Wait for pending IRQ handlers on other CPUs.
477    ///
478    /// This will attempt to access the inner [`Devres`] container.
479    pub fn try_synchronize(&self) -> Result {
480        let inner = self.inner.try_access().ok_or(ENODEV)?;
481        inner.synchronize();
482        Ok(())
483    }
484
485    /// Wait for pending IRQ handlers on other CPUs.
486    pub fn synchronize(&self, dev: &Device<Bound>) -> Result {
487        let inner = self.inner.access(dev)?;
488        inner.synchronize();
489        Ok(())
490    }
491}
492
493/// # Safety
494///
495/// This function should be only used as the callback in `request_threaded_irq`.
496unsafe extern "C" fn handle_threaded_irq_callback<T: ThreadedHandler>(
497    _irq: i32,
498    ptr: *mut c_void,
499) -> c_uint {
500    // SAFETY: `ptr` is a pointer to `RegistrationInner` set in `ThreadedRegistration::new`
501    let inner = unsafe { &*(ptr as *const RegistrationInner) };
502    // SAFETY: `inner.handler` is a pointer to `T` set in `ThreadedRegistration::new`
503    let handler = unsafe { &*inner.handler.cast::<T>() };
504    // SAFETY: The irq callback is removed before the device is unbound, so the fact that the irq
505    // callback is running implies that the device has not yet been unbound.
506    let device = unsafe { inner.dev.as_bound() };
507
508    T::handle(handler, device) as c_uint
509}
510
511/// # Safety
512///
513/// This function should be only used as the callback in `request_threaded_irq`.
514unsafe extern "C" fn thread_fn_callback<T: ThreadedHandler>(_irq: i32, ptr: *mut c_void) -> c_uint {
515    // SAFETY: `ptr` is a pointer to `RegistrationInner` set in `ThreadedRegistration::new`
516    let inner = unsafe { &*(ptr as *const RegistrationInner) };
517    // SAFETY: `inner.handler` is a pointer to `T` set in `ThreadedRegistration::new`
518    let handler = unsafe { &*inner.handler.cast::<T>() };
519    // SAFETY: The irq callback is removed before the device is unbound, so the fact that the irq
520    // callback is running implies that the device has not yet been unbound.
521    let device = unsafe { inner.dev.as_bound() };
522
523    T::handle_threaded(handler, device) as c_uint
524}