From nobody Sun Oct 5 00:10:09 2025 Received: from bali.collaboradmins.com (bali.collaboradmins.com [148.251.105.195]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 171B22E2657; Mon, 11 Aug 2025 16:04:09 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=148.251.105.195 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1754928251; cv=none; b=UgmAZIPY19C3GFC9rPO1msQM5zspDgh41dt4BQOdrmkPBmZx/FE+xNfRZzNcFy6zBfRZym3kRcicAmOy1Blsfk1qhpMTGigySu9zdHicKxMey59dJSAVhTeisuXA4OuDNOXZSqzCsTo6iY3ui0H19bMD1xnxHBSilAgQYZjZNuI= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1754928251; c=relaxed/simple; bh=IFTM+cCl1PzcsGLiOvasHfcz6hoVV8pnqOMPQjed5gw=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=CUXY1zzaTMT6Q6In2w59BeeaJzzLyznnYkPdOV62zFd4pk/z6K78uzmbGNZ2C8VJTM8yI8N93QoKwk314vFT8fNoswFg7SayEEk1iCA5f4bLRXfcV9MNJ/for7wviuctHnKty524ltH3OhWgPpmxWxYRk4aOQ2/zDDv5P7Rsytg= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com; spf=pass smtp.mailfrom=collabora.com; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.b=PBTgwReS; arc=none smtp.client-ip=148.251.105.195 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=collabora.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.b="PBTgwReS" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=collabora.com; s=mail; t=1754928248; bh=IFTM+cCl1PzcsGLiOvasHfcz6hoVV8pnqOMPQjed5gw=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=PBTgwReSgKRo7S541yW0NkFDWF4l2ETAzctV0cpatDLj4lhyD+WuVlOr5IqgjHjbK Feu92LYC4hTIYjnFOXr+5qiY91quhM86fI3+YCHtAUn3OklfLs5s7Qp+u44Gem47CM 5uEFdGziA2lTBspQi9vlVaHNjrgD0P+z05yynZUk8k5JIEzrMqACx+LcLZZbFhL6vN 34wrnaxX02gE3I/gT0OBcUsr0PAF3SYKY82nVYrfsj6f1sr88r1JF/U2vw4TgKU3nB Kl1olj8jztNBQ4KlDSkHRBtPfmc98rOBDAo+JjqKkp2sfwDylqnd+xaGIlXZOgfp5J zOpvDDI1i1nyg== Received: from [192.168.0.23] (unknown [IPv6:2804:14d:72b4:82f6:67c:16ff:fe57:b5a3]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) (Authenticated sender: dwlsalmeida) by bali.collaboradmins.com (Postfix) with ESMTPSA id 2A29417E0286; Mon, 11 Aug 2025 18:04:03 +0200 (CEST) From: Daniel Almeida Date: Mon, 11 Aug 2025 13:03:39 -0300 Subject: [PATCH v9 1/7] rust: irq: add irq module Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250811-topics-tyr-request_irq2-v9-1-0485dcd9bcbf@collabora.com> References: <20250811-topics-tyr-request_irq2-v9-0-0485dcd9bcbf@collabora.com> In-Reply-To: <20250811-topics-tyr-request_irq2-v9-0-0485dcd9bcbf@collabora.com> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Thomas Gleixner , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Benno Lossin Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-pci@vger.kernel.org, Joel Fernandes , Dirk Behme , Daniel Almeida X-Mailer: b4 0.14.2 Add the IRQ module. Future patches will then introduce support for IRQ registrations and handlers. Reviewed-by: Alice Ryhl Tested-by: Joel Fernandes Tested-by: Dirk Behme Signed-off-by: Daniel Almeida Reviewed-by: Andreas Hindborg --- rust/kernel/irq.rs | 11 +++++++++++ rust/kernel/lib.rs | 1 + 2 files changed, 12 insertions(+) diff --git a/rust/kernel/irq.rs b/rust/kernel/irq.rs new file mode 100644 index 0000000000000000000000000000000000000000..fae7b15effc80c936d6bffbd5b4= 150000d6c2898 --- /dev/null +++ b/rust/kernel/irq.rs @@ -0,0 +1,11 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! IRQ abstractions. +//! +//! An IRQ is an interrupt request from a device. It is used to get the CP= U's +//! attention so it can service a hardware event in a timely manner. +//! +//! The current abstractions handle IRQ requests and handlers, i.e.: it al= lows +//! drivers to register a handler for a given IRQ line. +//! +//! C header: [`include/linux/device.h`](srctree/include/linux/interrupt.h) diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index ed53169e795c0badf548025a57f946fa18bc73e3..f8db761c5c95fc66e4c55f539b1= 7fca613161ada 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -92,6 +92,7 @@ pub mod init; pub mod io; pub mod ioctl; +pub mod irq; pub mod jump_label; #[cfg(CONFIG_KUNIT)] pub mod kunit; --=20 2.50.1 From nobody Sun Oct 5 00:10:09 2025 Received: from bali.collaboradmins.com (bali.collaboradmins.com [148.251.105.195]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 8B3312E2F0B; Mon, 11 Aug 2025 16:04:14 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=148.251.105.195 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1754928256; cv=none; b=RcIgOt7wnfh2KuXXoLUpr2MtdZITfzTH5jqpye4W24ZxyqSWt0ALac30Hcq8Hr7cJtlq5fBmgcDUe0yPGPsOsqI+kmtKai3k+vP3AI5BFZeXZwMtvtKjOwyzpnhwxdw+B9Q3xevJ6si7ru1w7yrcsE/De/ErYVykDy0Mqn3KHS4= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1754928256; c=relaxed/simple; bh=53lmUqL5yPTzLf0HyVvpp4UBOwKDYAtc6kUVDMRosDI=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=VJATN4ILsEzWyQ9nt9D6r1sQCBYRZ+PVl/QvMCFFrfOEdHfKhKAcRUhHmljViQ5zDAaxDRJWa07QUkherBntGx8/3RohkwobOgHNBLfYQ//k9puivahZfgZYx+j771W86tJEGGspHpp5XHW0MZ9LQ6j1ZhjBzMFHqMkoh5YBvaE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com; spf=pass smtp.mailfrom=collabora.com; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.b=krtOAyop; arc=none smtp.client-ip=148.251.105.195 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=collabora.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.b="krtOAyop" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=collabora.com; s=mail; t=1754928252; bh=53lmUqL5yPTzLf0HyVvpp4UBOwKDYAtc6kUVDMRosDI=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=krtOAyopcZU0SEZ83hsNjZ0mJXv8o3lUxvpAkvdmlnEW7+bNxdNVKeZP+yixif2mx t6WQrFg3HptdpMIjuVwvqz73YbgRp0ps6yn7FERIj3lPdFLafde622eSs1toyGn4e0 ALPt1m0clNmTwODBA1OxGa2VXMBYe7Hl93sU/QJ5vQ/Zt1TCuszKiZ/2yagj8w5L72 n+JjFoeuNN1sHEZ1mG032NOMaFJU/yUjCdAxWeCaPk0Gn7F2c50uh7QJWYVrsV2X4C sKG383MWuz00HnlVni24wDaN5N+CmskmBdDhZTSxUfp9MX/ck8t8l9yPTSZax/5Rmo hmHvEKKR2IoCA== Received: from [192.168.0.23] (unknown [IPv6:2804:14d:72b4:82f6:67c:16ff:fe57:b5a3]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) (Authenticated sender: dwlsalmeida) by bali.collaboradmins.com (Postfix) with ESMTPSA id B562717E090E; Mon, 11 Aug 2025 18:04:08 +0200 (CEST) From: Daniel Almeida Date: Mon, 11 Aug 2025 13:03:40 -0300 Subject: [PATCH v9 2/7] rust: irq: add flags module Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250811-topics-tyr-request_irq2-v9-2-0485dcd9bcbf@collabora.com> References: <20250811-topics-tyr-request_irq2-v9-0-0485dcd9bcbf@collabora.com> In-Reply-To: <20250811-topics-tyr-request_irq2-v9-0-0485dcd9bcbf@collabora.com> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Thomas Gleixner , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Benno Lossin Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-pci@vger.kernel.org, Joel Fernandes , Dirk Behme , Daniel Almeida X-Mailer: b4 0.14.2 Manipulating IRQ flags (i.e.: IRQF_*) will soon be necessary, specially to register IRQ handlers through bindings::request_irq(). Add a kernel::irq::Flags for that purpose. Reviewed-by: Alice Ryhl Tested-by: Joel Fernandes Tested-by: Dirk Behme Signed-off-by: Daniel Almeida --- rust/kernel/irq.rs | 5 ++ rust/kernel/irq/flags.rs | 124 +++++++++++++++++++++++++++++++++++++++++++= ++++ 2 files changed, 129 insertions(+) diff --git a/rust/kernel/irq.rs b/rust/kernel/irq.rs index fae7b15effc80c936d6bffbd5b4150000d6c2898..068df2fea31de51115c30344f7e= bdb4da4ad86cc 100644 --- a/rust/kernel/irq.rs +++ b/rust/kernel/irq.rs @@ -9,3 +9,8 @@ //! drivers to register a handler for a given IRQ line. //! //! C header: [`include/linux/device.h`](srctree/include/linux/interrupt.h) + +/// Flags to be used when registering IRQ handlers. +mod flags; + +pub use flags::Flags; diff --git a/rust/kernel/irq/flags.rs b/rust/kernel/irq/flags.rs new file mode 100644 index 0000000000000000000000000000000000000000..e62820ea67755123b4f96e43312= 44bbb4fbcfd9d --- /dev/null +++ b/rust/kernel/irq/flags.rs @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright 2025 Collabora ltd. + +use crate::bindings; +use crate::prelude::*; + +/// Flags to be used when registering IRQ handlers. +/// +/// Flags can be used to request specific behaviors when registering an IRQ +/// handler, and can be combined using the `|`, `&`, and `!` operators to +/// further control the system's behavior. +/// +/// A common use case is to register a shared interrupt, as sharing the li= ne +/// between devices is increasingly common in modern systems and is even +/// required for some buses. This requires setting [`Flags::SHARED`] when +/// requesting the interrupt. Other use cases include setting the trigger = type +/// through `Flags::TRIGGER_*`, which determines when the interrupt fires,= or +/// controlling whether the interrupt is masked after the handler runs by = using +/// [`Flags::ONESHOT`]. +/// +/// If an invalid combination of flags is provided, the system will refuse= to +/// register the handler, and lower layers will enforce certain flags when +/// necessary. This means, for example, that all the +/// [`crate::irq::Registration`] for a shared interrupt have to agree on +/// [`Flags::SHARED`] and on the same trigger type, if set. +#[derive(Clone, Copy, PartialEq, Eq)] +pub struct Flags(c_ulong); + +impl Flags { + /// Use the interrupt line as already configured. + pub const TRIGGER_NONE: Flags =3D Flags::new(bindings::IRQF_TRIGGER_NO= NE); + + /// The interrupt is triggered when the signal goes from low to high. + pub const TRIGGER_RISING: Flags =3D Flags::new(bindings::IRQF_TRIGGER_= RISING); + + /// The interrupt is triggered when the signal goes from high to low. + pub const TRIGGER_FALLING: Flags =3D Flags::new(bindings::IRQF_TRIGGER= _FALLING); + + /// The interrupt is triggered while the signal is held high. + pub const TRIGGER_HIGH: Flags =3D Flags::new(bindings::IRQF_TRIGGER_HI= GH); + + /// The interrupt is triggered while the signal is held low. + pub const TRIGGER_LOW: Flags =3D Flags::new(bindings::IRQF_TRIGGER_LOW= ); + + /// Allow sharing the IRQ among several devices. + pub const SHARED: Flags =3D Flags::new(bindings::IRQF_SHARED); + + /// Set by callers when they expect sharing mismatches to occur. + pub const PROBE_SHARED: Flags =3D Flags::new(bindings::IRQF_PROBE_SHAR= ED); + + /// Flag to mark this interrupt as timer interrupt. + pub const TIMER: Flags =3D Flags::new(bindings::IRQF_TIMER); + + /// Interrupt is per CPU. + pub const PERCPU: Flags =3D Flags::new(bindings::IRQF_PERCPU); + + /// Flag to exclude this interrupt from irq balancing. + pub const NOBALANCING: Flags =3D Flags::new(bindings::IRQF_NOBALANCING= ); + + /// Interrupt is used for polling (only the interrupt that is register= ed + /// first in a shared interrupt is considered for performance reasons). + pub const IRQPOLL: Flags =3D Flags::new(bindings::IRQF_IRQPOLL); + + /// Interrupt is not reenabled after the hardirq handler finished. Use= d by + /// threaded interrupts which need to keep the irq line disabled until= the + /// threaded handler has been run. + pub const ONESHOT: Flags =3D Flags::new(bindings::IRQF_ONESHOT); + + /// Do not disable this IRQ during suspend. Does not guarantee that th= is + /// interrupt will wake the system from a suspended state. + pub const NO_SUSPEND: Flags =3D Flags::new(bindings::IRQF_NO_SUSPEND); + + /// Force enable it on resume even if [`Flags::NO_SUSPEND`] is set. + pub const FORCE_RESUME: Flags =3D Flags::new(bindings::IRQF_FORCE_RESU= ME); + + /// Interrupt cannot be threaded. + pub const NO_THREAD: Flags =3D Flags::new(bindings::IRQF_NO_THREAD); + + /// Resume IRQ early during syscore instead of at device resume time. + pub const EARLY_RESUME: Flags =3D Flags::new(bindings::IRQF_EARLY_RESU= ME); + + /// If the IRQ is shared with a [`Flags::NO_SUSPEND`] user, execute th= is + /// interrupt handler after suspending interrupts. For system wakeup d= evices + /// users need to implement wakeup detection in their interrupt handle= rs. + pub const COND_SUSPEND: Flags =3D Flags::new(bindings::IRQF_COND_SUSPE= ND); + + /// Don't enable IRQ or NMI automatically when users request it. Users= will + /// enable it explicitly by `enable_irq` or `enable_nmi` later. + pub const NO_AUTOEN: Flags =3D Flags::new(bindings::IRQF_NO_AUTOEN); + + /// Exclude from runnaway detection for IPI and similar handlers, depe= nds on + /// `PERCPU`. + pub const NO_DEBUG: Flags =3D Flags::new(bindings::IRQF_NO_DEBUG); + + pub(crate) fn into_inner(self) -> c_ulong { + self.0 + } + + const fn new(value: u32) -> Self { + build_assert!(value as u64 <=3D c_ulong::MAX as u64); + Self(value as c_ulong) + } +} + +impl core::ops::BitOr for Flags { + type Output =3D Self; + fn bitor(self, rhs: Self) -> Self::Output { + Self(self.0 | rhs.0) + } +} + +impl core::ops::BitAnd for Flags { + type Output =3D Self; + fn bitand(self, rhs: Self) -> Self::Output { + Self(self.0 & rhs.0) + } +} + +impl core::ops::Not for Flags { + type Output =3D Self; + fn not(self) -> Self::Output { + Self(!self.0) + } +} --=20 2.50.1 From nobody Sun Oct 5 00:10:09 2025 Received: from bali.collaboradmins.com (bali.collaboradmins.com [148.251.105.195]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 133B32E3399; Mon, 11 Aug 2025 16:04:18 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=148.251.105.195 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1754928261; cv=none; b=VMeEyVjeWCWjAbY1f6XxUNPVl9yxzsmwafir48Eusk82Hxop/6hhnBv8M4gvN31VL6kJ28EJlrZD6gbde4B0mP89HzgCmjeIC5UX12iQtskTUpS2K9RXKR11tWya3mCXowpTBx8qVRnC4O2OnE4xEyCKRxpwY1gLlx8W9HgR6dQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1754928261; c=relaxed/simple; bh=CkFgudXqzY3twlZ/PT9HfPEdOj0x9xvhiu+YxMJVHRE=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=GBY/mf6XHke3exjcxPzY/QvbjFcVGqhVXfNJwByqPHVIq7Be6UTUK2CE1rB4lIzzTSaZurMXbGfc+XCC/HYAHE6dvAXuTYSu89+OX06CeEuK2U3Kkgr/3GuJaJOKClBpZe1a7pVj6Eqy3ebD91eBzVpcdsnVx/axJYtXRK7RLvo= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com; spf=pass smtp.mailfrom=collabora.com; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.b=Rf/haZ7A; arc=none smtp.client-ip=148.251.105.195 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=collabora.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.b="Rf/haZ7A" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=collabora.com; s=mail; t=1754928257; bh=CkFgudXqzY3twlZ/PT9HfPEdOj0x9xvhiu+YxMJVHRE=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=Rf/haZ7AEzIcKhxhQOD2a0tu45CVpMKEHgYgMuNPd+2B4/LM2J/jhIzNzF3uOHjJw 3qscKCGIbpZNTFfb0kotPpqin8fn9I10b/HWq0MNQpP27Pqg6SOnAIy7fxMgCGcR9t sYKquk0li32er+HCprhTssd9tMuJigUl51bG/Z+mkBMlhQOzrhsSQ2fUPkWE6rb7cW 70S/2vA/linQpITG+42v2bZEiwtoBjSRvqzQKkLQ40xeeLb1sKyqE5bc5M2B4Ul3MV dUMEvaW8uMDWVbyAHCHOg9x8XiaQO0FkNNG7EmK/Z8awt1tfU9eQZJ++tyNvuAO413 neE2p2OHsXj3A== Received: from [192.168.0.23] (unknown [IPv6:2804:14d:72b4:82f6:67c:16ff:fe57:b5a3]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) (Authenticated sender: dwlsalmeida) by bali.collaboradmins.com (Postfix) with ESMTPSA id 4DB8E17E00EC; Mon, 11 Aug 2025 18:04:13 +0200 (CEST) From: Daniel Almeida Date: Mon, 11 Aug 2025 13:03:41 -0300 Subject: [PATCH v9 3/7] rust: irq: add support for non-threaded IRQs and handlers Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250811-topics-tyr-request_irq2-v9-3-0485dcd9bcbf@collabora.com> References: <20250811-topics-tyr-request_irq2-v9-0-0485dcd9bcbf@collabora.com> In-Reply-To: <20250811-topics-tyr-request_irq2-v9-0-0485dcd9bcbf@collabora.com> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Thomas Gleixner , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Benno Lossin Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-pci@vger.kernel.org, Joel Fernandes , Dirk Behme , Daniel Almeida X-Mailer: b4 0.14.2 This patch adds support for non-threaded IRQs and handlers through irq::Registration and the irq::Handler trait. Registering an irq is dependent upon having a IrqRequest that was previously allocated by a given device. This will be introduced in subsequent patches. Tested-by: Joel Fernandes Tested-by: Dirk Behme Reviewed-by: Alice Ryhl Signed-off-by: Daniel Almeida --- rust/bindings/bindings_helper.h | 1 + rust/helpers/helpers.c | 1 + rust/helpers/irq.c | 9 ++ rust/kernel/irq.rs | 5 + rust/kernel/irq/request.rs | 264 ++++++++++++++++++++++++++++++++++++= ++++ 5 files changed, 280 insertions(+) diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helpe= r.h index 84d60635e8a9baef1f1a1b2752dc0fa044f8542f..69a975da829f0c35760f71a1b32= b8fcb12c8a8dc 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -52,6 +52,7 @@ #include #include #include +#include #include #include #include diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c index 7cf7fe95e41dd51717050648d6160bebebdf4b26..44b2005d50140d34a44ae37d01c= 2ddbae6aeaa32 100644 --- a/rust/helpers/helpers.c +++ b/rust/helpers/helpers.c @@ -22,6 +22,7 @@ #include "dma.c" #include "drm.c" #include "err.c" +#include "irq.c" #include "fs.c" #include "io.c" #include "jump_label.c" diff --git a/rust/helpers/irq.c b/rust/helpers/irq.c new file mode 100644 index 0000000000000000000000000000000000000000..1faca428e2c047a656dec317185= 5c1508d67e60b --- /dev/null +++ b/rust/helpers/irq.c @@ -0,0 +1,9 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include + +int rust_helper_request_irq(unsigned int irq, irq_handler_t handler, + unsigned long flags, const char *name, void *dev) +{ + return request_irq(irq, handler, flags, name, dev); +} diff --git a/rust/kernel/irq.rs b/rust/kernel/irq.rs index 068df2fea31de51115c30344f7ebdb4da4ad86cc..c1019bc36ad1e7ae7dd3af8a8b5= c14780bf70712 100644 --- a/rust/kernel/irq.rs +++ b/rust/kernel/irq.rs @@ -13,4 +13,9 @@ /// Flags to be used when registering IRQ handlers. mod flags; =20 +/// IRQ allocation and handling. +mod request; + pub use flags::Flags; + +pub use request::{Handler, IrqRequest, IrqReturn, Registration}; diff --git a/rust/kernel/irq/request.rs b/rust/kernel/irq/request.rs new file mode 100644 index 0000000000000000000000000000000000000000..57e00ebf694d8e6e870d9ed57af= 7ee2ecf86ec05 --- /dev/null +++ b/rust/kernel/irq/request.rs @@ -0,0 +1,264 @@ +// SPDX-License-Identifier: GPL-2.0 +// SPDX-FileCopyrightText: Copyright 2025 Collabora ltd. + +//! This module provides types like [`Registration`] which allow users to +//! register handlers for a given IRQ line. + +use core::marker::PhantomPinned; + +use crate::alloc::Allocator; +use crate::device::{Bound, Device}; +use crate::devres::Devres; +use crate::error::to_result; +use crate::irq::flags::Flags; +use crate::prelude::*; +use crate::str::CStr; +use crate::sync::Arc; + +/// The value that can be returned from a [`Handler`] or a [`ThreadedHandl= er`]. +#[repr(u32)] +pub enum IrqReturn { + /// The interrupt was not from this device or was not handled. + None =3D bindings::irqreturn_IRQ_NONE, + + /// The interrupt was handled by this device. + Handled =3D bindings::irqreturn_IRQ_HANDLED, +} + +/// Callbacks for an IRQ handler. +pub trait Handler: Sync { + /// The hard IRQ handler. + /// + /// This is executed in interrupt context, hence all corresponding + /// limitations do apply. + /// + /// All work that does not necessarily need to be executed from + /// interrupt context, should be deferred to a threaded handler. + /// See also [`ThreadedRegistration`]. + fn handle(&self) -> IrqReturn; +} + +impl Handler for Arc { + fn handle(&self) -> IrqReturn { + T::handle(self) + } +} + +impl Handler for Box { + fn handle(&self) -> IrqReturn { + T::handle(self) + } +} + +/// # Invariants +/// +/// - `self.irq` is the same as the one passed to `request_{threaded}_irq`. +/// - `cookie` was passed to `request_{threaded}_irq` as the cookie. It is= guaranteed to be unique +/// by the type system, since each call to `new` will return a different= instance of +/// `Registration`. +#[pin_data(PinnedDrop)] +struct RegistrationInner { + irq: u32, + cookie: *mut c_void, +} + +impl RegistrationInner { + fn synchronize(&self) { + // SAFETY: safe as per the invariants of `RegistrationInner` + unsafe { bindings::synchronize_irq(self.irq) }; + } +} + +#[pinned_drop] +impl PinnedDrop for RegistrationInner { + fn drop(self: Pin<&mut Self>) { + // SAFETY: + // + // Safe as per the invariants of `RegistrationInner` and: + // + // - The containing struct is `!Unpin` and was initialized using + // pin-init, so it occupied the same memory location for the entir= ety of + // its lifetime. + // + // Notice that this will block until all handlers finish executing, + // i.e.: at no point will &self be invalid while the handler is ru= nning. + unsafe { bindings::free_irq(self.irq, self.cookie) }; + } +} + +// SAFETY: We only use `inner` on drop, which called at most once with no +// concurrent access. +unsafe impl Sync for RegistrationInner {} + +// SAFETY: It is safe to send `RegistrationInner` across threads. +unsafe impl Send for RegistrationInner {} + +/// A request for an IRQ line for a given device. +/// +/// # Invariants +/// +/// - `=C3=ACrq` is the number of an interrupt source of `dev`. +/// - `irq` has not been registered yet. +pub struct IrqRequest<'a> { + dev: &'a Device, + irq: u32, +} + +impl<'a> IrqRequest<'a> { + /// Creates a new IRQ request for the given device and IRQ number. + /// + /// # Safety + /// + /// - `irq` should be a valid IRQ number for `dev`. + pub(crate) unsafe fn new(dev: &'a Device, irq: u32) -> Self { + // INVARIANT: `irq` is a valid IRQ number for `dev`. + IrqRequest { dev, irq } + } + + /// Returns the IRQ number of an [`IrqRequest`]. + pub fn irq(&self) -> u32 { + self.irq + } +} + +/// A registration of an IRQ handler for a given IRQ line. +/// +/// # Examples +/// +/// The following is an example of using `Registration`. It uses a +/// [`Completion`] to coordinate between the IRQ +/// handler and process context. [`Completion`] uses interior mutability, = so the +/// handler can signal with [`Completion::complete_all()`] and the process +/// context can wait with [`Completion::wait_for_completion()`] even though +/// there is no way to get a mutable reference to the any of the fields in +/// `Data`. +/// +/// [`Completion`]: kernel::sync::Completion +/// [`Completion::complete_all()`]: kernel::sync::Completion::complete_all +/// [`Completion::wait_for_completion()`]: kernel::sync::Completion::wait_= for_completion +/// +/// ``` +/// use kernel::c_str; +/// use kernel::device::Bound; +/// use kernel::irq::{self, Flags, IrqRequest, IrqReturn, Registration}; +/// use kernel::prelude::*; +/// use kernel::sync::{Arc, Completion}; +/// +/// // Data shared between process and IRQ context. +/// #[pin_data] +/// struct Data { +/// #[pin] +/// completion: Completion, +/// } +/// +/// impl irq::Handler for Data { +/// // Executed in IRQ context. +/// fn handle(&self) -> IrqReturn { +/// self.completion.complete_all(); +/// IrqReturn::Handled +/// } +/// } +/// +/// // Registers an IRQ handler for the given IrqRequest. +/// // +/// // This runs in process context and assumes `request` was previously a= cquired from a device. +/// fn register_irq( +/// handler: impl PinInit, +/// request: IrqRequest<'_>, +/// ) -> Result>> { +/// let registration =3D Registration::new(request, Flags::SHARED, c_s= tr!("my_device"), handler); +/// +/// let registration =3D Arc::pin_init(registration, GFP_KERNEL)?; +/// +/// registration.handler().completion.wait_for_completion(); +/// +/// Ok(registration) +/// } +/// # Ok::<(), Error>(()) +/// ``` +/// +/// # Invariants +/// +/// * We own an irq handler using `&self.handler` as its private data. +#[pin_data] +pub struct Registration { + #[pin] + inner: Devres, + + #[pin] + handler: T, + + /// Pinned because we need address stability so that we can pass a poi= nter + /// to the callback. + #[pin] + _pin: PhantomPinned, +} + +impl Registration { + /// Registers the IRQ handler with the system for the given IRQ number. + pub fn new<'a>( + request: IrqRequest<'a>, + flags: Flags, + name: &'static CStr, + handler: impl PinInit + 'a, + ) -> impl PinInit + 'a { + try_pin_init!(&this in Self { + handler <- handler, + inner <- Devres::new( + request.dev, + try_pin_init!(RegistrationInner { + // SAFETY: `this` is a valid pointer to the `Registrat= ion` instance + cookie: unsafe { &raw mut (*this.as_ptr()).handler }.c= ast(), + irq: { + // SAFETY: + // - The callbacks are valid for use with request_= irq. + // - If this succeeds, the slot is guaranteed to b= e valid until the + // destructor of Self runs, which will deregiste= r the callbacks + // before the memory location becomes invalid. + to_result(unsafe { + bindings::request_irq( + request.irq, + Some(handle_irq_callback::), + flags.into_inner(), + name.as_char_ptr(), + (&raw mut (*this.as_ptr()).handler).cast(), + ) + })?; + request.irq + } + }) + ), + _pin: PhantomPinned, + }) + } + + /// Returns a reference to the handler that was registered with the sy= stem. + pub fn handler(&self) -> &T { + &self.handler + } + + /// Wait for pending IRQ handlers on other CPUs. + /// + /// This will attempt to access the inner [`Devres`] container. + pub fn try_synchronize(&self) -> Result { + let inner =3D self.inner.try_access().ok_or(ENODEV)?; + inner.synchronize(); + Ok(()) + } + + /// Wait for pending IRQ handlers on other CPUs. + pub fn synchronize(&self, dev: &Device) -> Result { + let inner =3D self.inner.access(dev)?; + inner.synchronize(); + Ok(()) + } +} + +/// # Safety +/// +/// This function should be only used as the callback in `request_irq`. +unsafe extern "C" fn handle_irq_callback(_irq: i32, ptr: *mut = c_void) -> c_uint { + // SAFETY: `ptr` is a pointer to T set in `Registration::new` + let handler =3D unsafe { &*(ptr as *const T) }; + T::handle(handler) as c_uint +} --=20 2.50.1 From nobody Sun Oct 5 00:10:09 2025 Received: from bali.collaboradmins.com (bali.collaboradmins.com [148.251.105.195]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9136D2E339E; Mon, 11 Aug 2025 16:04:23 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=148.251.105.195 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1754928265; cv=none; b=tp1tHcr5y00gWxC1ZQvJApPq1zrvbx7LOIDt3okOBFoB6NSPNKUH+dGG7tgdG0AFUEMq7OBoj/69g6BBmBOacAQ8PeNyFtISnL0/QFN8Qxdi6SY/+hsGzbk513BRiS6Mki0wY944GzGIMdWzKM9KhzMRaUuTR4U0j4ceBSjFghQ= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1754928265; c=relaxed/simple; bh=K0EhQkyhLaiw0Vz+iyHgrnyZW7UcIJtsvSPduP62RXE=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=V9l0IdWBSkjwvbSCQCrg6ERfjcRYmJqQrpmQkt67ivmQnO9b7WlaXgpDndzGYGFOvctgVF4nXA2eocw8yr7Hijh2E2rqz5Rz+uihLOfw61AltzS1ginMx45U6XJy/3Jj+ZG2v/Ftxggm+RvPAq7ZHSBvC5CSB5Fr9R6kTwJgpxE= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com; spf=pass smtp.mailfrom=collabora.com; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.b=OrhBvzmD; arc=none smtp.client-ip=148.251.105.195 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=collabora.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.b="OrhBvzmD" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=collabora.com; s=mail; t=1754928262; bh=K0EhQkyhLaiw0Vz+iyHgrnyZW7UcIJtsvSPduP62RXE=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=OrhBvzmDHxLkzvEQI9FusK9OPAwh5CVz6MUTr4qpJVP0aOMNV8FNSt8cHdhjhWuu0 +hrx9IQmdbkMfqLDQZI1PT1034ggDvQZQ1wIHycOqFF9gb1MT5GZWII7FAkGcKxc3r 246z62VpJC0OYjRoXoZWMpzO7tjIb6oKTp8x7L8M+4SSvScoHmhOiz3AoF5yvMmSt3 ggtW80VkCMAcrqXssbAwRMq82Nf1n5WhYE9hFv5vrm74iZc2oSX3jbF9ogXftIYp25 vyW7ieSBUCN315VoaumdnOif30YNHG7de4znxOSjMLS/X4wD4AIhhb1uU2KzjPBfnv N5uhQsAvTeSng== Received: from [192.168.0.23] (unknown [IPv6:2804:14d:72b4:82f6:67c:16ff:fe57:b5a3]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) (Authenticated sender: dwlsalmeida) by bali.collaboradmins.com (Postfix) with ESMTPSA id D535B17E0286; Mon, 11 Aug 2025 18:04:17 +0200 (CEST) From: Daniel Almeida Date: Mon, 11 Aug 2025 13:03:42 -0300 Subject: [PATCH v9 4/7] rust: irq: add support for threaded IRQs and handlers Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250811-topics-tyr-request_irq2-v9-4-0485dcd9bcbf@collabora.com> References: <20250811-topics-tyr-request_irq2-v9-0-0485dcd9bcbf@collabora.com> In-Reply-To: <20250811-topics-tyr-request_irq2-v9-0-0485dcd9bcbf@collabora.com> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Thomas Gleixner , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Benno Lossin Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-pci@vger.kernel.org, Joel Fernandes , Dirk Behme , Daniel Almeida X-Mailer: b4 0.14.2 This patch adds support for threaded IRQs and handlers through irq::ThreadedRegistration and the irq::ThreadedHandler trait. Threaded interrupts are more permissive in the sense that further processing is possible in a kthread. This means that said execution takes place outside of interrupt context, which is rather restrictive in many ways. Registering a threaded irq is dependent upon having an IrqRequest that was previously allocated by a given device. This will be introduced in subsequent patches. Tested-by: Joel Fernandes Tested-by: Dirk Behme Reviewed-by: Alice Ryhl Signed-off-by: Daniel Almeida --- rust/kernel/irq.rs | 5 +- rust/kernel/irq/request.rs | 228 +++++++++++++++++++++++++++++++++++++++++= +++- 2 files changed, 230 insertions(+), 3 deletions(-) diff --git a/rust/kernel/irq.rs b/rust/kernel/irq.rs index c1019bc36ad1e7ae7dd3af8a8b5c14780bf70712..20abd40566559652eccd03f77ec= 873a16b6f48b0 100644 --- a/rust/kernel/irq.rs +++ b/rust/kernel/irq.rs @@ -18,4 +18,7 @@ =20 pub use flags::Flags; =20 -pub use request::{Handler, IrqRequest, IrqReturn, Registration}; +pub use request::{ + Handler, IrqRequest, IrqReturn, Registration, ThreadedHandler, Threade= dIrqReturn, + ThreadedRegistration, +}; diff --git a/rust/kernel/irq/request.rs b/rust/kernel/irq/request.rs index 57e00ebf694d8e6e870d9ed57af7ee2ecf86ec05..4033df7d0dce1dbc9cc9b0b0f32= fb9f8aa285d6b 100644 --- a/rust/kernel/irq/request.rs +++ b/rust/kernel/irq/request.rs @@ -1,8 +1,9 @@ // SPDX-License-Identifier: GPL-2.0 // SPDX-FileCopyrightText: Copyright 2025 Collabora ltd. =20 -//! This module provides types like [`Registration`] which allow users to -//! register handlers for a given IRQ line. +//! This module provides types like [`Registration`] and +//! [`ThreadedRegistration`], which allow users to register handlers for a= given +//! IRQ line. =20 use core::marker::PhantomPinned; =20 @@ -262,3 +263,226 @@ pub fn synchronize(&self, dev: &Device) -> Res= ult { let handler =3D unsafe { &*(ptr as *const T) }; T::handle(handler) as c_uint } + +/// The value that can be returned from [`ThreadedHandler::handle`]. +#[repr(u32)] +pub enum ThreadedIrqReturn { + /// The interrupt was not from this device or was not handled. + None =3D bindings::irqreturn_IRQ_NONE, + + /// The interrupt was handled by this device. + Handled =3D bindings::irqreturn_IRQ_HANDLED, + + /// The handler wants the handler thread to wake up. + WakeThread =3D bindings::irqreturn_IRQ_WAKE_THREAD, +} + +/// Callbacks for a threaded IRQ handler. +pub trait ThreadedHandler: Sync { + /// The hard IRQ handler. + /// + /// This is executed in interrupt context, hence all corresponding + /// limitations do apply. All work that does not necessarily need to be + /// executed from interrupt context, should be deferred to the threaded + /// handler, i.e. [`ThreadedHandler::handle_threaded`]. + /// + /// The default implementation returns [`ThreadedIrqReturn::WakeThread= `]. + fn handle(&self) -> ThreadedIrqReturn { + ThreadedIrqReturn::WakeThread + } + + /// The threaded IRQ handler. + /// + /// This is executed in process context. The kernel creates a dedicated + /// `kthread` for this purpose. + fn handle_threaded(&self) -> IrqReturn; +} + +impl ThreadedHandler for Arc { + fn handle(&self) -> ThreadedIrqReturn { + T::handle(self) + } + + fn handle_threaded(&self) -> IrqReturn { + T::handle_threaded(self) + } +} + +impl ThreadedHandler for Box { + fn handle(&self) -> ThreadedIrqReturn { + T::handle(self) + } + + fn handle_threaded(&self) -> IrqReturn { + T::handle_threaded(self) + } +} + +/// A registration of a threaded IRQ handler for a given IRQ line. +/// +/// Two callbacks are required: one to handle the IRQ, and one to handle a= ny +/// other work in a separate thread. +/// +/// The thread handler is only called if the IRQ handler returns +/// [`ThreadedIrqReturn::WakeThread`]. +/// +/// # Examples +/// +/// The following is an example of using [`ThreadedRegistration`]. It uses= a +/// [`Mutex`](kernel::sync::Mutex) to provide interior mutability. +/// +/// ``` +/// use kernel::c_str; +/// use kernel::device::Bound; +/// use kernel::irq::{ +/// self, Flags, IrqRequest, IrqReturn, ThreadedHandler, ThreadedIrqRetu= rn, +/// ThreadedRegistration, +/// }; +/// use kernel::prelude::*; +/// use kernel::sync::{Arc, Mutex}; +/// +/// // Declare a struct that will be passed in when the interrupt fires. T= he u32 +/// // merely serves as an example of some internal data. +/// // +/// // [`irq::ThreadedHandler::handle`] takes `&self`. This example +/// // illustrates how interior mutability can be used when sharing the da= ta +/// // between process context and IRQ context. +/// #[pin_data] +/// struct Data { +/// #[pin] +/// value: Mutex, +/// } +/// +/// impl ThreadedHandler for Data { +/// // This will run (in a separate kthread) if and only if +/// // [`ThreadedHandler::handle`] returns [`WakeThread`], which it do= es by +/// // default. +/// fn handle_threaded(&self) -> IrqReturn { +/// let mut data =3D self.value.lock(); +/// *data +=3D 1; +/// IrqReturn::Handled +/// } +/// } +/// +/// // Registers a threaded IRQ handler for the given [`IrqRequest`]. +/// // +/// // This is executing in process context and assumes that `request` was +/// // previously acquired from a device. +/// fn register_threaded_irq( +/// handler: impl PinInit, +/// request: IrqRequest<'_>, +/// ) -> Result>> { +/// let registration =3D +/// ThreadedRegistration::new(request, Flags::SHARED, c_str!("my_d= evice"), handler); +/// +/// let registration =3D Arc::pin_init(registration, GFP_KERNEL)?; +/// +/// { +/// // The data can be accessed from process context too. +/// let mut data =3D registration.handler().value.lock(); +/// *data +=3D 1; +/// } +/// +/// Ok(registration) +/// } +/// # Ok::<(), Error>(()) +/// ``` +/// +/// # Invariants +/// +/// * We own an irq handler using `&T` as its private data. +#[pin_data] +pub struct ThreadedRegistration { + #[pin] + inner: Devres, + + #[pin] + handler: T, + + /// Pinned because we need address stability so that we can pass a poi= nter + /// to the callback. + #[pin] + _pin: PhantomPinned, +} + +impl ThreadedRegistration { + /// Registers the IRQ handler with the system for the given IRQ number. + pub fn new<'a>( + request: IrqRequest<'a>, + flags: Flags, + name: &'static CStr, + handler: impl PinInit + 'a, + ) -> impl PinInit + 'a { + try_pin_init!(&this in Self { + handler <- handler, + inner <- Devres::new( + request.dev, + try_pin_init!(RegistrationInner { + // SAFETY: `this` is a valid pointer to the `ThreadedR= egistration` instance. + cookie: unsafe { &raw mut (*this.as_ptr()).handler }.c= ast(), + irq: { + // SAFETY: + // - The callbacks are valid for use with request_= threaded_irq. + // - If this succeeds, the slot is guaranteed to b= e valid until the + // destructor of Self runs, which will deregister = the callbacks + // before the memory location becomes invalid. + to_result(unsafe { + bindings::request_threaded_irq( + request.irq, + Some(handle_threaded_irq_callback::), + Some(thread_fn_callback::), + flags.into_inner(), + name.as_char_ptr(), + (&raw mut (*this.as_ptr()).handler).cast(), + ) + })?; + request.irq + } + }) + ), + _pin: PhantomPinned, + }) + } + + /// Returns a reference to the handler that was registered with the sy= stem. + pub fn handler(&self) -> &T { + &self.handler + } + + /// Wait for pending IRQ handlers on other CPUs. + /// + /// This will attempt to access the inner [`Devres`] container. + pub fn try_synchronize(&self) -> Result { + let inner =3D self.inner.try_access().ok_or(ENODEV)?; + inner.synchronize(); + Ok(()) + } + + /// Wait for pending IRQ handlers on other CPUs. + pub fn synchronize(&self, dev: &Device) -> Result { + let inner =3D self.inner.access(dev)?; + inner.synchronize(); + Ok(()) + } +} + +/// # Safety +/// +/// This function should be only used as the callback in `request_threaded= _irq`. +unsafe extern "C" fn handle_threaded_irq_callback( + _irq: i32, + ptr: *mut c_void, +) -> c_uint { + // SAFETY: `ptr` is a pointer to T set in `ThreadedRegistration::new` + let handler =3D unsafe { &*(ptr as *const T) }; + T::handle(handler) as c_uint +} + +/// # Safety +/// +/// This function should be only used as the callback in `request_threaded= _irq`. +unsafe extern "C" fn thread_fn_callback(_irq: i32, ptr= : *mut c_void) -> c_uint { + // SAFETY: `ptr` is a pointer to T set in `ThreadedRegistration::new` + let handler =3D unsafe { &*(ptr as *const T) }; + T::handle_threaded(handler) as c_uint +} --=20 2.50.1 From nobody Sun Oct 5 00:10:09 2025 Received: from bali.collaboradmins.com (bali.collaboradmins.com [148.251.105.195]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 40EF42E3B0C; Mon, 11 Aug 2025 16:04:28 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=148.251.105.195 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1754928270; cv=none; b=agQF8eiSkQuN4nVyIsEAR+x57NnWcszPApMkJS8QBXwhWfWaNCxkeqR2JJ+wXgbWMVFacr92T+IeymgmFEv1lnIL8u0rfFstRtwKWUL/fARiYsv851f2BSaOYSZN5c9WQq71UWG0jwBwVj2xfrgM2IxwVg4+t0TsIF1amkP+NCM= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1754928270; c=relaxed/simple; bh=ftvHFAqnHwpqfL/mJ4rFGS5HSYS4tKu3Io7v1aZzEOg=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=sTH9q6FUE2b16v4uYe4EWS/iFqEkcSDy3SHSk4QJM8YQqZ8nLW0rXVAF4jw6oMsYaN0Sq7Ff+O+8ijksO5M1fMPUf/PQ+0AZAFIFyOmvbOLFXJphuUWFVNXL7rOjyjzZJXP5E483jbfgMMys8sJrPpcwZP/tGhU20eJw9USIKuw= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com; spf=pass smtp.mailfrom=collabora.com; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.b=e/NbYi8G; arc=none smtp.client-ip=148.251.105.195 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=collabora.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.b="e/NbYi8G" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=collabora.com; s=mail; t=1754928266; bh=ftvHFAqnHwpqfL/mJ4rFGS5HSYS4tKu3Io7v1aZzEOg=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=e/NbYi8GHMW4wSuhBbeRw7sYcq2qx+jxm49t2SbvANACBr3fxWKTuY10kwaOk8f6+ jhupI18JG+8zHkC3a2EwJpJEnwMd/xQI7RTL8CheG6sc3Z51WShUIZFYcoza5sPZPw DF1YeSJGcBWI/qJ7E5ssxUR/am94oSZS6CdWX7eRGNQPta9t7JMfu+icKsKlrpUFvu 3iNmxjAQH13bDYJhsj2a8ucGh7FRgzO64k6Xq5q8MCY8IJ6bYYi1gROvtELSBksSK7 diAduKOy+S605ra7/6adodLZlnUKBbvMUsQZfH6c793WQPToc4hGcD7Pba7tjBQyCE mnFwsLiUZ+YSg== Received: from [192.168.0.23] (unknown [IPv6:2804:14d:72b4:82f6:67c:16ff:fe57:b5a3]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) (Authenticated sender: dwlsalmeida) by bali.collaboradmins.com (Postfix) with ESMTPSA id 7637F17E090E; Mon, 11 Aug 2025 18:04:22 +0200 (CEST) From: Daniel Almeida Date: Mon, 11 Aug 2025 13:03:43 -0300 Subject: [PATCH v9 5/7] rust: platform: add irq accessors Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250811-topics-tyr-request_irq2-v9-5-0485dcd9bcbf@collabora.com> References: <20250811-topics-tyr-request_irq2-v9-0-0485dcd9bcbf@collabora.com> In-Reply-To: <20250811-topics-tyr-request_irq2-v9-0-0485dcd9bcbf@collabora.com> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Thomas Gleixner , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Benno Lossin Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-pci@vger.kernel.org, Joel Fernandes , Dirk Behme , Daniel Almeida X-Mailer: b4 0.14.2 These accessors can be used to retrieve a irq::Registration and irq::ThreadedRegistration from a platform device by index or name. Alternatively, drivers can retrieve an IrqRequest from a bound platform device for later use. These accessors ensure that only valid IRQ lines can ever be registered. Reviewed-by: Alice Ryhl Tested-by: Joel Fernandes Tested-by: Dirk Behme Signed-off-by: Daniel Almeida --- rust/kernel/platform.rs | 142 ++++++++++++++++++++++++++++++++++++++++++++= ++++ 1 file changed, 142 insertions(+) diff --git a/rust/kernel/platform.rs b/rust/kernel/platform.rs index 8f028c76f9fa6154f440b48921ba16573a9d3c54..6d640887f69f35fc44fb3c0db3b= 10f879b55d107 100644 --- a/rust/kernel/platform.rs +++ b/rust/kernel/platform.rs @@ -10,6 +10,7 @@ driver, error::{from_result, to_result, Result}, io::{mem::IoRequest, Resource}, + irq::{self, IrqRequest}, of, prelude::*, types::Opaque, @@ -284,6 +285,147 @@ pub fn io_request_by_name(&self, name: &CStr) -> Opti= on> { } } =20 +macro_rules! define_irq_accessor_by_index { + ($(#[$meta:meta])* $fn_name:ident, $request_fn:ident, $reg_type:ident,= $handler_trait:ident) =3D> { + $(#[$meta])* + pub fn $fn_name<'a, T: irq::$handler_trait + 'static>( + &'a self, + flags: irq::Flags, + index: u32, + name: &'static CStr, + handler: impl PinInit + 'a, + ) -> Result, Error> + 'a> { + let request =3D self.$request_fn(index)?; + + Ok(irq::$reg_type::::new( + request, + flags, + name, + handler, + )) + } + }; +} + +macro_rules! define_irq_accessor_by_name { + ($(#[$meta:meta])* $fn_name:ident, $request_fn:ident, $reg_type:ident,= $handler_trait:ident) =3D> { + $(#[$meta])* + pub fn $fn_name<'a, T: irq::$handler_trait + 'static>( + &'a self, + flags: irq::Flags, + irq_name: &CStr, + name: &'static CStr, + handler: impl PinInit + 'a, + ) -> Result, Error> + 'a> { + let request =3D self.$request_fn(irq_name)?; + + Ok(irq::$reg_type::::new( + request, + flags, + name, + handler, + )) + } + }; +} + +impl Device { + /// Returns an [`IrqRequest`] for the IRQ at the given index, if any. + pub fn irq_by_index(&self, index: u32) -> Result> { + // SAFETY: `self.as_raw` returns a valid pointer to a `struct plat= form_device`. + let irq =3D unsafe { bindings::platform_get_irq(self.as_raw(), ind= ex) }; + + if irq < 0 { + return Err(Error::from_errno(irq)); + } + + // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self= `. + Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) }) + } + + /// Returns an [`IrqRequest`] for the IRQ at the given index, but does= not + /// print an error if the IRQ cannot be obtained. + pub fn optional_irq_by_index(&self, index: u32) -> Result> { + // SAFETY: `self.as_raw` returns a valid pointer to a `struct plat= form_device`. + let irq =3D unsafe { bindings::platform_get_irq_optional(self.as_r= aw(), index) }; + + if irq < 0 { + return Err(Error::from_errno(irq)); + } + + // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self= `. + Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) }) + } + + /// Returns an [`IrqRequest`] for the IRQ with the given name, if any. + pub fn irq_by_name(&self, name: &CStr) -> Result> { + // SAFETY: `self.as_raw` returns a valid pointer to a `struct plat= form_device`. + let irq =3D unsafe { bindings::platform_get_irq_byname(self.as_raw= (), name.as_char_ptr()) }; + + if irq < 0 { + return Err(Error::from_errno(irq)); + } + + // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self= `. + Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) }) + } + + /// Returns an [`IrqRequest`] for the IRQ with the given name, but doe= s not + /// print an error if the IRQ cannot be obtained. + pub fn optional_irq_by_name(&self, name: &CStr) -> Result> { + // SAFETY: `self.as_raw` returns a valid pointer to a `struct plat= form_device`. + let irq =3D unsafe { + bindings::platform_get_irq_byname_optional(self.as_raw(), name= .as_char_ptr()) + }; + + if irq < 0 { + return Err(Error::from_errno(irq)); + } + + // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self= `. + Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) }) + } + + define_irq_accessor_by_index!( + /// Returns a [`irq::Registration`] for the IRQ at the given index. + request_irq_by_index, irq_by_index, Registration, Handler + ); + define_irq_accessor_by_name!( + /// Returns a [`irq::Registration`] for the IRQ with the given nam= e. + request_irq_by_name, irq_by_name, Registration, Handler + ); + define_irq_accessor_by_index!( + /// Does the same as [`Self::request_irq_by_index`], except that i= t does + /// not print an error message if the IRQ cannot be obtained. + request_optional_irq_by_index, optional_irq_by_index, Registration= , Handler + ); + define_irq_accessor_by_name!( + /// Does the same as [`Self::request_irq_by_name`], except that it= does + /// not print an error message if the IRQ cannot be obtained. + request_optional_irq_by_name, optional_irq_by_name, Registration, = Handler + ); + + define_irq_accessor_by_index!( + /// Returns a [`irq::ThreadedRegistration`] for the IRQ at the giv= en index. + request_threaded_irq_by_index, irq_by_index, ThreadedRegistration,= ThreadedHandler + ); + define_irq_accessor_by_name!( + /// Returns a [`irq::ThreadedRegistration`] for the IRQ with the g= iven name. + request_threaded_irq_by_name, irq_by_name, ThreadedRegistration, T= hreadedHandler + ); + define_irq_accessor_by_index!( + /// Does the same as [`Self::request_threaded_irq_by_index`], exce= pt + /// that it does not print an error message if the IRQ cannot be + /// obtained. + request_optional_threaded_irq_by_index, optional_irq_by_index, Thr= eadedRegistration, ThreadedHandler + ); + define_irq_accessor_by_name!( + /// Does the same as [`Self::request_threaded_irq_by_name`], excep= t that + /// it does not print an error message if the IRQ cannot be obtain= ed. + request_optional_threaded_irq_by_name, optional_irq_by_name, Threa= dedRegistration, ThreadedHandler + ); +} + // SAFETY: `Device` is a transparent wrapper of a type that doesn't depend= on `Device`'s generic // argument. kernel::impl_device_context_deref!(unsafe { Device }); --=20 2.50.1 From nobody Sun Oct 5 00:10:09 2025 Received: from bali.collaboradmins.com (bali.collaboradmins.com [148.251.105.195]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id C30D32E4240; Mon, 11 Aug 2025 16:04:32 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=148.251.105.195 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1754928274; cv=none; b=s19uhjRAJUqz/Nk4tEow3QMr2Fok2XoDDZURRKk0uvkFsccrUILII8NEZlBBLQ4jz8O9iaPFvDK7R2g20P2f3toSKKqkmrfojawKPriTsAZyRTcM2qOUOAU15LZhT5v629Ds89FKnKgDUas48WoATuZyivUFqfqAyhCENfIflgk= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1754928274; c=relaxed/simple; bh=mOSeltVes00yZ6zMOLeC+fORp4G9BVNpUzfSg1BVS6c=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=avTMAz8zxrlBZZ6HEWnPxoEXyXWruk/lyMsDuC9YQkS9DU0BxKnJfByC1pal14BDMRnobNW5IG4c13tv1QRy5gCFOI0+RWrI8BLuxvSt7dQyF2S57+LWrVHDct4sFaRxAez7b5mhQiOPjtMNC8UwcS0HptVLESSeO4Hc/i4PNuc= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com; spf=pass smtp.mailfrom=collabora.com; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.b=q2r0s0/i; arc=none smtp.client-ip=148.251.105.195 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=collabora.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.b="q2r0s0/i" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=collabora.com; s=mail; t=1754928271; bh=mOSeltVes00yZ6zMOLeC+fORp4G9BVNpUzfSg1BVS6c=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=q2r0s0/iQmNuyUziY3HWEmR3Tdgz7PTOEcHigllncZjuN0J+4o84m621fwU7moFDU jpfIwL4rFcqtIlCQCMfQ1OcmYx3liFbwtxJ/uLDKtcZ0vep4f0OG3eWabonqcYGEG8 Psz+YHoKQF7uWXtWGrIsQZ58ppqr3RnreGeZK7K9TlumJLUvAEp7RmjCQsFcDxKOQo 1+rL20qwFdiicngDm75ViSkfQljgDg5eX9VYQwzW02aliL1c13nLtzN9FN/aFPJlxq DSAhL+d3EklCmY+7psV1c9RX0xPgYaWuk/r+KAp3n+4lAybZZlT9isU4wezlrXN+SP 4hcfSuy2hq+eg== Received: from [192.168.0.23] (unknown [IPv6:2804:14d:72b4:82f6:67c:16ff:fe57:b5a3]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) (Authenticated sender: dwlsalmeida) by bali.collaboradmins.com (Postfix) with ESMTPSA id 0485917E00EC; Mon, 11 Aug 2025 18:04:26 +0200 (CEST) From: Daniel Almeida Date: Mon, 11 Aug 2025 13:03:44 -0300 Subject: [PATCH v9 6/7] rust: pci: add irq accessors Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250811-topics-tyr-request_irq2-v9-6-0485dcd9bcbf@collabora.com> References: <20250811-topics-tyr-request_irq2-v9-0-0485dcd9bcbf@collabora.com> In-Reply-To: <20250811-topics-tyr-request_irq2-v9-0-0485dcd9bcbf@collabora.com> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Thomas Gleixner , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Benno Lossin Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-pci@vger.kernel.org, Joel Fernandes , Dirk Behme , Daniel Almeida X-Mailer: b4 0.14.2 These accessors can be used to retrieve a irq::Registration or a irq::ThreadedRegistration from a pci device. Alternatively, drivers can retrieve an IrqRequest from a bound PCI device for later use. These accessors ensure that only valid IRQ lines can ever be registered. Reviewed-by: Alice Ryhl Tested-by: Joel Fernandes Tested-by: Dirk Behme Signed-off-by: Daniel Almeida --- rust/helpers/pci.c | 8 ++++++++ rust/kernel/pci.rs | 45 +++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/rust/helpers/pci.c b/rust/helpers/pci.c index ef9cb38c81a6a5375f72c3676cd9730aad17757b..5bf56004478c6945dc3e1a394fc= d787c656d8b2a 100644 --- a/rust/helpers/pci.c +++ b/rust/helpers/pci.c @@ -11,3 +11,11 @@ bool rust_helper_dev_is_pci(const struct device *dev) { return dev_is_pci(dev); } + +#ifndef CONFIG_PCI_MSI +int rust_helper_pci_irq_vector(struct pci_dev *pdev, unsigned int nvec) +{ + return pci_irq_vector(pdev, nvec); +} + +#endif diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs index 887ee611b55310e7edbd512f9017b708ff9d7bd8..3bf1737635a9e219c3eec3f4c5f= 8e4e07b553b86 100644 --- a/rust/kernel/pci.rs +++ b/rust/kernel/pci.rs @@ -10,8 +10,8 @@ devres::Devres, driver, error::{from_result, to_result, Result}, - io::Io, - io::IoRaw, + io::{Io, IoRaw}, + irq::{self, IrqRequest}, str::CStr, types::{ARef, Opaque}, ThisModule, @@ -431,6 +431,47 @@ pub fn iomap_region<'a>( ) -> impl PinInit, Error> + 'a { self.iomap_region_sized::<0>(bar, name) } + + /// Returns an [`IrqRequest`] for the IRQ vector at the given index, i= f any. + pub fn irq_vector(&self, index: u32) -> Result> { + // SAFETY: `self.as_raw` returns a valid pointer to a `struct pci_= dev`. + let irq =3D unsafe { crate::bindings::pci_irq_vector(self.as_raw()= , index) }; + if irq < 0 { + return Err(crate::error::Error::from_errno(irq)); + } + // SAFETY: `irq` is guaranteed to be a valid IRQ number for `&self= `. + Ok(unsafe { IrqRequest::new(self.as_ref(), irq as u32) }) + } + + /// Returns a [`kernel::irq::Registration`] for the IRQ vector at the = given + /// index. + pub fn request_irq<'a, T: crate::irq::Handler + 'static>( + &'a self, + index: u32, + flags: irq::Flags, + name: &'static CStr, + handler: impl PinInit + 'a, + ) -> Result, Error> + 'a> { + let request =3D self.irq_vector(index)?; + + Ok(irq::Registration::::new(request, flags, name, handler)) + } + + /// Returns a [`kernel::irq::ThreadedRegistration`] for the IRQ vector= at + /// the given index. + pub fn request_threaded_irq<'a, T: crate::irq::ThreadedHandler + 'stat= ic>( + &'a self, + index: u32, + flags: irq::Flags, + name: &'static CStr, + handler: impl PinInit + 'a, + ) -> Result, Error> + 'a> { + let request =3D self.irq_vector(index)?; + + Ok(irq::ThreadedRegistration::::new( + request, flags, name, handler, + )) + } } =20 impl Device { --=20 2.50.1 From nobody Sun Oct 5 00:10:09 2025 Received: from bali.collaboradmins.com (bali.collaboradmins.com [148.251.105.195]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 9E92C2E4248; Mon, 11 Aug 2025 16:04:36 +0000 (UTC) Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.client-ip=148.251.105.195 ARC-Seal: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1754928288; cv=none; b=ceotKId4ToCA9ugI6N8tvzIs4MuUo+0KqP0xaNzKAOIrHYjhQgvoB49xpYVQc0OEG6s2+8PgHmAtcWmcOrKJ2fgg9HRQ2dsLYfj8eZFB8p1LM0B1FuPIWe6SspEUHLJArpKrf4mog5eEHPelp3FLsng/wQ9OVZnUIldUNmV8w4Y= ARC-Message-Signature: i=1; a=rsa-sha256; d=subspace.kernel.org; s=arc-20240116; t=1754928288; c=relaxed/simple; bh=P0FxVoeKMOCv0FiYXIPHPq65i6gU7ma+BQ0+5+XiL0o=; h=From:Date:Subject:MIME-Version:Content-Type:Message-Id:References: In-Reply-To:To:Cc; b=Rzp1HfOdelb+pb4ik1PsYibpRQv1d51Wx9yCoGzkkmbO3Xn/Oo6F+Z9/fEOTzcDjjcdZX/RVgfotbKtvcOSBui784ODJcgc5wkgq0NbR5i6ka7+1NB/qJzH5dRGu0WB6PBIB5eoLS6KSHTRPEq0oyO8SQ9HknUUafjfQIGrwFmk= ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com; spf=pass smtp.mailfrom=collabora.com; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.b=NwlKUIO8; arc=none smtp.client-ip=148.251.105.195 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=collabora.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=collabora.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=collabora.com header.i=@collabora.com header.b="NwlKUIO8" DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=collabora.com; s=mail; t=1754928275; bh=P0FxVoeKMOCv0FiYXIPHPq65i6gU7ma+BQ0+5+XiL0o=; h=From:Date:Subject:References:In-Reply-To:To:Cc:From; b=NwlKUIO8svgXuW5be5mbCDP4YkxxRYVwCRbD4XTaXC5MF8znyqMayhQuiX6OY2L9/ BBMj2t4yGXRwaxjnH/dnO3ZbE56mHLbT5r03UFD6WB+5B1m46Zs5cg54MFC+KTDgly 4qWlqW0RmALYHbJy+uZsfMIFbwLeeqe5X3mbKD7+Y7QV9wpEzGTQTUYcZoX3Apmvfm wXK1dS4iFfCALNQ1mW8UrjF4sdPFMXcoYXETV+DkShmsVlT2I5XCgsf35jsgGAeX6p LAB8spbAo8U/HqjTQTaMOY7tkwz3tUzwMGFP8TmNtg6Au7mncq20ui1W6Hur7tGcWY oMpUUTKUqrXGA== Received: from [192.168.0.23] (unknown [IPv6:2804:14d:72b4:82f6:67c:16ff:fe57:b5a3]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (4096 bits) server-digest SHA256) (No client certificate requested) (Authenticated sender: dwlsalmeida) by bali.collaboradmins.com (Postfix) with ESMTPSA id 9BDFE17E0286; Mon, 11 Aug 2025 18:04:31 +0200 (CEST) From: Daniel Almeida Date: Mon, 11 Aug 2025 13:03:45 -0300 Subject: [PATCH v9 7/7] rust: irq: add &Device argument to irq callbacks Precedence: bulk X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Subscribe: List-Unsubscribe: MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <20250811-topics-tyr-request_irq2-v9-7-0485dcd9bcbf@collabora.com> References: <20250811-topics-tyr-request_irq2-v9-0-0485dcd9bcbf@collabora.com> In-Reply-To: <20250811-topics-tyr-request_irq2-v9-0-0485dcd9bcbf@collabora.com> To: Miguel Ojeda , Alex Gaynor , Boqun Feng , Gary Guo , =?utf-8?q?Bj=C3=B6rn_Roy_Baron?= , Andreas Hindborg , Alice Ryhl , Trevor Gross , Danilo Krummrich , Greg Kroah-Hartman , "Rafael J. Wysocki" , Thomas Gleixner , Bjorn Helgaas , =?utf-8?q?Krzysztof_Wilczy=C5=84ski?= , Benno Lossin Cc: linux-kernel@vger.kernel.org, rust-for-linux@vger.kernel.org, linux-pci@vger.kernel.org X-Mailer: b4 0.14.2 From: Alice Ryhl When working with a bus device, many operations are only possible while the device is still bound. The &Device type represents a proof in the type system that you are in a scope where the device is guaranteed to still be bound. Since we deregister irq callbacks when unbinding a device, if an irq callback is running, that implies that the device has not yet been unbound. To allow drivers to take advantage of that, add an additional argument to irq callbacks. Signed-off-by: Alice Ryhl Reviewed-by: Boqun Feng --- rust/kernel/irq/request.rs | 95 +++++++++++++++++++++++++++---------------= ---- 1 file changed, 57 insertions(+), 38 deletions(-) diff --git a/rust/kernel/irq/request.rs b/rust/kernel/irq/request.rs index 4033df7d0dce1dbc9cc9b0b0f32fb9f8aa285d6b..b150563fdef809899c7ca39221c= 4928238e31110 100644 --- a/rust/kernel/irq/request.rs +++ b/rust/kernel/irq/request.rs @@ -36,18 +36,18 @@ pub trait Handler: Sync { /// All work that does not necessarily need to be executed from /// interrupt context, should be deferred to a threaded handler. /// See also [`ThreadedRegistration`]. - fn handle(&self) -> IrqReturn; + fn handle(&self, device: &Device) -> IrqReturn; } =20 impl Handler for Arc { - fn handle(&self) -> IrqReturn { - T::handle(self) + fn handle(&self, device: &Device) -> IrqReturn { + T::handle(self, device) } } =20 impl Handler for Box { - fn handle(&self) -> IrqReturn { - T::handle(self) + fn handle(&self, device: &Device) -> IrqReturn { + T::handle(self, device) } } =20 @@ -140,7 +140,7 @@ pub fn irq(&self) -> u32 { /// /// ``` /// use kernel::c_str; -/// use kernel::device::Bound; +/// use kernel::device::{Bound, Device}; /// use kernel::irq::{self, Flags, IrqRequest, IrqReturn, Registration}; /// use kernel::prelude::*; /// use kernel::sync::{Arc, Completion}; @@ -154,7 +154,7 @@ pub fn irq(&self) -> u32 { /// /// impl irq::Handler for Data { /// // Executed in IRQ context. -/// fn handle(&self) -> IrqReturn { +/// fn handle(&self, _dev: &Device) -> IrqReturn { /// self.completion.complete_all(); /// IrqReturn::Handled /// } @@ -180,7 +180,7 @@ pub fn irq(&self) -> u32 { /// /// # Invariants /// -/// * We own an irq handler using `&self.handler` as its private data. +/// * We own an irq handler whose cookie is a pointer to `Self`. #[pin_data] pub struct Registration { #[pin] @@ -208,21 +208,24 @@ pub fn new<'a>( inner <- Devres::new( request.dev, try_pin_init!(RegistrationInner { - // SAFETY: `this` is a valid pointer to the `Registrat= ion` instance - cookie: unsafe { &raw mut (*this.as_ptr()).handler }.c= ast(), + // INVARIANT: `this` is a valid pointer to the `Regist= ration` instance + cookie: this.as_ptr().cast::(), irq: { // SAFETY: // - The callbacks are valid for use with request_= irq. // - If this succeeds, the slot is guaranteed to b= e valid until the // destructor of Self runs, which will deregiste= r the callbacks // before the memory location becomes invalid. + // - When request_irq is called, everything that h= andle_irq_callback will + // touch has already been initialized, so it's s= afe for the callback to + // be called immediately. to_result(unsafe { bindings::request_irq( request.irq, Some(handle_irq_callback::), flags.into_inner(), name.as_char_ptr(), - (&raw mut (*this.as_ptr()).handler).cast(), + this.as_ptr().cast::(), ) })?; request.irq @@ -259,9 +262,13 @@ pub fn synchronize(&self, dev: &Device) -> Resu= lt { /// /// This function should be only used as the callback in `request_irq`. unsafe extern "C" fn handle_irq_callback(_irq: i32, ptr: *mut = c_void) -> c_uint { - // SAFETY: `ptr` is a pointer to T set in `Registration::new` - let handler =3D unsafe { &*(ptr as *const T) }; - T::handle(handler) as c_uint + // SAFETY: `ptr` is a pointer to `Registration` set in `Registratio= n::new` + let registration =3D unsafe { &*(ptr as *const Registration) }; + // SAFETY: The irq callback is removed before the device is unbound, s= o the fact that the irq + // callback is running implies that the device has not yet been unboun= d. + let device =3D unsafe { registration.inner.device().as_bound() }; + + T::handle(®istration.handler, device) as c_uint } =20 /// The value that can be returned from [`ThreadedHandler::handle`]. @@ -287,7 +294,8 @@ pub trait ThreadedHandler: Sync { /// handler, i.e. [`ThreadedHandler::handle_threaded`]. /// /// The default implementation returns [`ThreadedIrqReturn::WakeThread= `]. - fn handle(&self) -> ThreadedIrqReturn { + #[expect(unused_variables)] + fn handle(&self, device: &Device) -> ThreadedIrqReturn { ThreadedIrqReturn::WakeThread } =20 @@ -295,26 +303,26 @@ fn handle(&self) -> ThreadedIrqReturn { /// /// This is executed in process context. The kernel creates a dedicated /// `kthread` for this purpose. - fn handle_threaded(&self) -> IrqReturn; + fn handle_threaded(&self, device: &Device) -> IrqReturn; } =20 impl ThreadedHandler for Arc { - fn handle(&self) -> ThreadedIrqReturn { - T::handle(self) + fn handle(&self, device: &Device) -> ThreadedIrqReturn { + T::handle(self, device) } =20 - fn handle_threaded(&self) -> IrqReturn { - T::handle_threaded(self) + fn handle_threaded(&self, device: &Device) -> IrqReturn { + T::handle_threaded(self, device) } } =20 impl ThreadedHandler for Box { - fn handle(&self) -> ThreadedIrqReturn { - T::handle(self) + fn handle(&self, device: &Device) -> ThreadedIrqReturn { + T::handle(self, device) } =20 - fn handle_threaded(&self) -> IrqReturn { - T::handle_threaded(self) + fn handle_threaded(&self, device: &Device) -> IrqReturn { + T::handle_threaded(self, device) } } =20 @@ -333,7 +341,7 @@ fn handle_threaded(&self) -> IrqReturn { /// /// ``` /// use kernel::c_str; -/// use kernel::device::Bound; +/// use kernel::device::{Bound, Device}; /// use kernel::irq::{ /// self, Flags, IrqRequest, IrqReturn, ThreadedHandler, ThreadedIrqRetu= rn, /// ThreadedRegistration, @@ -357,7 +365,7 @@ fn handle_threaded(&self) -> IrqReturn { /// // This will run (in a separate kthread) if and only if /// // [`ThreadedHandler::handle`] returns [`WakeThread`], which it do= es by /// // default. -/// fn handle_threaded(&self) -> IrqReturn { +/// fn handle_threaded(&self, _dev: &Device) -> IrqReturn { /// let mut data =3D self.value.lock(); /// *data +=3D 1; /// IrqReturn::Handled @@ -390,7 +398,7 @@ fn handle_threaded(&self) -> IrqReturn { /// /// # Invariants /// -/// * We own an irq handler using `&T` as its private data. +/// * We own an irq handler whose cookie is a pointer to `Self`. #[pin_data] pub struct ThreadedRegistration { #[pin] @@ -418,14 +426,17 @@ pub fn new<'a>( inner <- Devres::new( request.dev, try_pin_init!(RegistrationInner { - // SAFETY: `this` is a valid pointer to the `ThreadedR= egistration` instance. - cookie: unsafe { &raw mut (*this.as_ptr()).handler }.c= ast(), + // INVARIANT: `this` is a valid pointer to the `Thread= edRegistration` instance. + cookie: this.as_ptr().cast::(), irq: { // SAFETY: // - The callbacks are valid for use with request_= threaded_irq. // - If this succeeds, the slot is guaranteed to b= e valid until the - // destructor of Self runs, which will deregister = the callbacks - // before the memory location becomes invalid. + // destructor of Self runs, which will deregiste= r the callbacks + // before the memory location becomes invalid. + // - When request_threaded_irq is called, everythi= ng that the two callbacks + // will touch has already been initialized, so i= t's safe for the + // callbacks to be called immediately. to_result(unsafe { bindings::request_threaded_irq( request.irq, @@ -433,7 +444,7 @@ pub fn new<'a>( Some(thread_fn_callback::), flags.into_inner(), name.as_char_ptr(), - (&raw mut (*this.as_ptr()).handler).cast(), + this.as_ptr().cast::(), ) })?; request.irq @@ -473,16 +484,24 @@ pub fn synchronize(&self, dev: &Device) -> Res= ult { _irq: i32, ptr: *mut c_void, ) -> c_uint { - // SAFETY: `ptr` is a pointer to T set in `ThreadedRegistration::new` - let handler =3D unsafe { &*(ptr as *const T) }; - T::handle(handler) as c_uint + // SAFETY: `ptr` is a pointer to `ThreadedRegistration` set in `Thr= eadedRegistration::new` + let registration =3D unsafe { &*(ptr as *const ThreadedRegistration= ) }; + // SAFETY: The irq callback is removed before the device is unbound, s= o the fact that the irq + // callback is running implies that the device has not yet been unboun= d. + let device =3D unsafe { registration.inner.device().as_bound() }; + + T::handle(®istration.handler, device) as c_uint } =20 /// # Safety /// /// This function should be only used as the callback in `request_threaded= _irq`. unsafe extern "C" fn thread_fn_callback(_irq: i32, ptr= : *mut c_void) -> c_uint { - // SAFETY: `ptr` is a pointer to T set in `ThreadedRegistration::new` - let handler =3D unsafe { &*(ptr as *const T) }; - T::handle_threaded(handler) as c_uint + // SAFETY: `ptr` is a pointer to `ThreadedRegistration` set in `Thr= eadedRegistration::new` + let registration =3D unsafe { &*(ptr as *const ThreadedRegistration= ) }; + // SAFETY: The irq callback is removed before the device is unbound, s= o the fact that the irq + // callback is running implies that the device has not yet been unboun= d. + let device =3D unsafe { registration.inner.device().as_bound() }; + + T::handle_threaded(®istration.handler, device) as c_uint } --=20 2.50.1