Skip to content

Commit 84ba47b

Browse files
hoshinolinajannau
authored andcommitted
rust: of: Add Node::address_as_resource()
Used for hand-rolled of_reserved_mem handling. Signed-off-by: Asahi Lina <lina@asahilina.net> Signed-off-by: Janne Grunau <j@jannau.net>
1 parent 61b78bb commit 84ba47b

2 files changed

Lines changed: 35 additions & 1 deletion

File tree

rust/kernel/io/resource.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,17 @@ impl Resource {
105105
unsafe { &*ptr.cast() }
106106
}
107107

108+
/// Creates a [`Resource`] from a valid pointer.
109+
///
110+
/// # Safety
111+
///
112+
/// The caller must ensure that the pointer points at a valid `bindings::resource`
113+
pub(crate) fn new_from_ptr(ptr: *const bindings::resource) -> Self {
114+
Resource {
115+
0: unsafe { Opaque::<bindings::resource>::new(*ptr) },
116+
}
117+
}
118+
108119
/// A helper to abstract the common pattern of requesting a region.
109120
fn request_region_checked(
110121
&self,

rust/kernel/of.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
//! Device Tree / Open Firmware abstractions.
44
5-
use crate::{bindings, device_id::RawDeviceId, prelude::*};
5+
use crate::{
6+
bindings, device_id::RawDeviceId, error::to_result, io::resource::Resource, prelude::*,
7+
};
68
// Note: Most OF functions turn into inline dummies with CONFIG_OF(_*) disabled.
79
// We have to either add config conditionals to helpers.c or here; let's do it
810
// here for now. In the future, once bindgen can auto-generate static inline
@@ -251,6 +253,27 @@ impl Node {
251253
}
252254
}
253255

256+
/// Translate device tree address and return as resource
257+
pub fn address_as_resource(&self, index: usize) -> Result<Resource> {
258+
#[cfg(not(CONFIG_OF))]
259+
{
260+
Err(EINVAL)
261+
}
262+
#[cfg(CONFIG_OF)]
263+
{
264+
let mut res = core::mem::MaybeUninit::<bindings::resource>::uninit();
265+
// SAFETY: This function is safe to call as long as the arguments are valid pointers.
266+
let ret = unsafe {
267+
bindings::of_address_to_resource(self.raw_node, index.try_into()?, res.as_mut_ptr())
268+
};
269+
to_result(ret)?;
270+
// SAFETY: We have checked the return value above, so the resource must be initialized now
271+
let res = unsafe { res.assume_init() };
272+
273+
Ok(Resource::new_from_ptr(&res))
274+
}
275+
}
276+
254277
#[allow(unused_variables)]
255278
/// Look up a node property by name, returning a `Property` object if found.
256279
pub fn find_property(&self, propname: &CStr) -> Option<Property<'_>> {

0 commit comments

Comments
 (0)