[PATCH v13 3/7] rust: pci: impl AsMut<Device> for pci::Device

From: Abdiel Janulgue
Date: Fri Mar 07 2025 - 06:09:36 EST


From: Danilo Krummrich <dakr@xxxxxxxxxx>

Some device methods require mutable references, since they change the
underlying struct device without lock protection.

Hence, make it possible to retrieve a mutable reference to a Device from
a mutable pci::Device.

Signed-off-by: Danilo Krummrich <dakr@xxxxxxxxxx>
---
rust/kernel/pci.rs | 11 +++++++++++
1 file changed, 11 insertions(+)

diff --git a/rust/kernel/pci.rs b/rust/kernel/pci.rs
index 4c98b5b9aa1e..141430dac2d5 100644
--- a/rust/kernel/pci.rs
+++ b/rust/kernel/pci.rs
@@ -432,3 +432,14 @@ fn as_ref(&self) -> &device::Device {
&self.0
}
}
+
+impl AsMut<device::Device> for Device {
+ fn as_mut(&mut self) -> &mut device::Device {
+ // SAFETY:
+ // - `self.0.as_raw()` is valid by the type invariant of `device::Device`,
+ // - `struct device` is embedded in `struct pci_dev`, hence it is safe to give out a
+ // mutable reference for `device::Device` if we have a mutable reference to the
+ // corresponding `pci::Device`.
+ unsafe { &mut *self.0.as_raw().cast() }
+ }
+}
--
2.43.0