[PATCH v3 1/7] rust: Add `parent_unchecked` function to `Device`

Markus Probst posted 7 patches 3 weeks, 3 days ago
Only 3 patches received!
There is a newer version of this series
[PATCH v3 1/7] rust: Add `parent_unchecked` function to `Device`
Posted by Markus Probst 3 weeks, 3 days ago
This allows mfd sub-devices to access the bus device of their parent.

The existing safe `parent` function has been made public for
consistency.

Signed-off-by: Markus Probst <markus.probst@posteo.de>
---
 rust/kernel/device.rs | 25 +++++++++++++++++++++++--
 1 file changed, 23 insertions(+), 2 deletions(-)

diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs
index 94e0548e7687..a53fb8a388e8 100644
--- a/rust/kernel/device.rs
+++ b/rust/kernel/device.rs
@@ -340,8 +340,7 @@ pub(crate) fn as_raw(&self) -> *mut bindings::device {
     }
 
     /// Returns a reference to the parent device, if any.
-    #[cfg_attr(not(CONFIG_AUXILIARY_BUS), expect(dead_code))]
-    pub(crate) fn parent(&self) -> Option<&Device> {
+    pub fn parent(&self) -> Option<&Device> {
         // SAFETY:
         // - By the type invariant `self.as_raw()` is always valid.
         // - The parent device is only ever set at device creation.
@@ -358,6 +357,28 @@ pub(crate) fn parent(&self) -> Option<&Device> {
         }
     }
 
+    /// Returns a reference to the parent device as bus device.
+    ///
+    /// # Safety
+    ///
+    /// Callers must ensure that the device has a parent, that is contained in `T`.
+    pub unsafe fn parent_unchecked<T: AsBusDevice<Ctx>>(&self) -> &T {
+        // SAFETY:
+        // - By the type invariant `self.as_raw()` is always valid.
+        // - The parent device is only ever set at device creation.
+        let parent_raw = unsafe { (*self.as_raw()).parent };
+
+        // SAFETY:
+        // - The safety requirements guarantee that the device has a parent, thus `parent_raw`
+        //   must be a pointer to a valid `struct device`.
+        // - `parent_raw` is valid for the lifetime of `self`, since a `struct device` holds a
+        //   reference count of its parent.
+        let parent = unsafe { Device::from_raw(parent_raw) };
+
+        // SAFETY: The safety requirements guarantee that the parent device is contained in `T`.
+        unsafe { T::from_device(parent) }
+    }
+
     /// Convert a raw C `struct device` pointer to a `&'a Device`.
     ///
     /// # Safety

-- 
2.52.0