Skip to content

Commit 5abe57e

Browse files
author
Danilo Krummrich
committed
rust: add devres abstraction
Add a Rust abstraction for the kernel's devres (device resource management) implementation. The Devres type acts as a container to manage the lifetime and accessibility of device bound resources. Therefore it registers a devres callback and revokes access to the resource on invocation. Users of the Devres abstraction can simply free the corresponding resources in their Drop implementation, which is invoked when either the Devres instance goes out of scope or the devres callback leads to the resource being revoked, which implies a call to drop_in_place(). Signed-off-by: Danilo Krummrich <[email protected]>
1 parent b1c72ac commit 5abe57e

File tree

4 files changed

+192
-0
lines changed

4 files changed

+192
-0
lines changed

rust/helpers/device.c

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
#include <linux/device.h>
4+
5+
int rust_helper_devm_add_action(struct device *dev,
6+
void (*action)(void *),
7+
void *data)
8+
{
9+
return devm_add_action(dev, action, data);
10+
}

rust/helpers/helpers.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
#include "bug.c"
1212
#include "build_assert.c"
1313
#include "build_bug.c"
14+
#include "device.c"
1415
#include "err.c"
1516
#include "io.c"
1617
#include "kunit.c"

rust/kernel/devres.rs

Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! Devres abstraction
4+
//!
5+
//! [`Devres`] represents an abstraction for the kernel devres (device resource management)
6+
//! implementation.
7+
8+
use crate::{
9+
alloc::Flags,
10+
bindings,
11+
device::Device,
12+
error::{Error, Result},
13+
prelude::*,
14+
revocable::Revocable,
15+
sync::Arc,
16+
};
17+
18+
use core::ffi::c_void;
19+
use core::ops::Deref;
20+
21+
#[pin_data]
22+
struct DevresInner<T> {
23+
#[pin]
24+
data: Revocable<T>,
25+
}
26+
27+
/// This abstraction is meant to be used by subsystems to containerize [`Device`] bound resources to
28+
/// manage their lifetime.
29+
///
30+
/// [`Device`] bound resources should be freed when either the resource goes out of scope or the
31+
/// [`Device`] is unbound respectively, depending on what happens first.
32+
///
33+
/// To achieve that [`Devres`] registers a devres callback on creation, which is called once the
34+
/// [`Device`] is unbound, revoking access to the encapsulated resource (see also [`Revocable`]).
35+
///
36+
/// After the [`Devres`] has been unbound it is not possible to access the encapsulated resource
37+
/// anymore.
38+
///
39+
/// [`Devres`] users should make sure to simply free the corresponding backing resource in `T`'s
40+
/// [`Drop`] implementation.
41+
///
42+
/// # Example
43+
///
44+
/// ```no_run
45+
/// # use kernel::{bindings, c_str, device::Device, devres::Devres, io::Io};
46+
/// # use core::ops::Deref;
47+
///
48+
/// // See also [`pci::Bar`] for a real example.
49+
/// struct IoMem<const SIZE: usize>(Io<SIZE>);
50+
///
51+
/// impl<const SIZE: usize> IoMem<SIZE> {
52+
/// /// # Safety
53+
/// ///
54+
/// /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs
55+
/// /// virtual address space.
56+
/// unsafe fn new(paddr: usize) -> Result<Self>{
57+
///
58+
/// // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is
59+
/// // valid for `ioremap`.
60+
/// let addr = unsafe { bindings::ioremap(paddr as _, SIZE.try_into().unwrap()) };
61+
/// if addr.is_null() {
62+
/// return Err(ENOMEM);
63+
/// }
64+
///
65+
/// // SAFETY: `addr` is guaranteed to be the start of a valid I/O mapped memory region of
66+
/// // size `SIZE`.
67+
/// let io = unsafe { Io::new(addr as _, SIZE)? };
68+
///
69+
/// Ok(IoMem(io))
70+
/// }
71+
/// }
72+
///
73+
/// impl<const SIZE: usize> Drop for IoMem<SIZE> {
74+
/// fn drop(&mut self) {
75+
/// // SAFETY: Safe as by the invariant of `Io`.
76+
/// unsafe { bindings::iounmap(self.0.base_addr() as _); };
77+
/// }
78+
/// }
79+
///
80+
/// impl<const SIZE: usize> Deref for IoMem<SIZE> {
81+
/// type Target = Io<SIZE>;
82+
///
83+
/// fn deref(&self) -> &Self::Target {
84+
/// &self.0
85+
/// }
86+
/// }
87+
///
88+
/// # fn no_run() -> Result<(), Error> {
89+
/// # // SAFETY: Invalid usage; just for the example to get an `ARef<Device>` instance.
90+
/// # let dev = unsafe { Device::from_raw(core::ptr::null_mut()) };
91+
///
92+
/// // SAFETY: Invalid usage for example purposes.
93+
/// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };
94+
/// let devres = Devres::new(&dev, iomem, GFP_KERNEL)?;
95+
///
96+
/// let res = devres.try_access().ok_or(ENXIO)?;
97+
/// res.writel(0x42, 0x0);
98+
/// # Ok(())
99+
/// # }
100+
/// ```
101+
pub struct Devres<T>(Arc<DevresInner<T>>);
102+
103+
impl<T> DevresInner<T> {
104+
fn new(dev: &Device, data: T, flags: Flags) -> Result<Arc<DevresInner<T>>> {
105+
let inner = Arc::pin_init(
106+
pin_init!( DevresInner {
107+
data <- Revocable::new(data),
108+
}),
109+
flags,
110+
)?;
111+
112+
// Convert `Arc<DevresInner>` into a raw pointer and make devres own this reference until
113+
// `Self::devres_callback` is called.
114+
let data = inner.clone().into_raw();
115+
116+
// SAFETY: `devm_add_action` guarantees to call `Self::devres_callback` once `dev` is
117+
// detached.
118+
let ret = unsafe {
119+
bindings::devm_add_action(dev.as_raw(), Some(Self::devres_callback), data as _)
120+
};
121+
122+
if ret != 0 {
123+
// SAFETY: We just created another reference to `inner` in order to pass it to
124+
// `bindings::devm_add_action`. If `bindings::devm_add_action` fails, we have to drop
125+
// this reference accordingly.
126+
let _ = unsafe { Arc::from_raw(data) };
127+
return Err(Error::from_errno(ret));
128+
}
129+
130+
Ok(inner)
131+
}
132+
133+
#[allow(clippy::missing_safety_doc)]
134+
unsafe extern "C" fn devres_callback(ptr: *mut c_void) {
135+
let ptr = ptr as *mut DevresInner<T>;
136+
// Devres owned this memory; now that we received the callback, drop the `Arc` and hence the
137+
// reference.
138+
// SAFETY: Safe, since we leaked an `Arc` reference to devm_add_action() in
139+
// `DevresInner::new`.
140+
let inner = unsafe { Arc::from_raw(ptr) };
141+
142+
inner.data.revoke();
143+
}
144+
}
145+
146+
impl<T> Devres<T> {
147+
/// Creates a new [`Devres`] instance of the given `data`. The `data` encapsulated within the
148+
/// returned `Devres` instance' `data` will be revoked once the device is detached.
149+
pub fn new(dev: &Device, data: T, flags: Flags) -> Result<Self> {
150+
let inner = DevresInner::new(dev, data, flags)?;
151+
152+
Ok(Devres(inner))
153+
}
154+
155+
/// Same as [Devres::new`], but does not return a `Devres` instance. Instead the given `data`
156+
/// is owned by devres and will be revoked / dropped, once the device is detached.
157+
pub fn new_foreign_owned(dev: &Device, data: T, flags: Flags) -> Result {
158+
let _ = DevresInner::new(dev, data, flags)?;
159+
160+
Ok(())
161+
}
162+
}
163+
164+
impl<T> Deref for Devres<T> {
165+
type Target = Revocable<T>;
166+
167+
fn deref(&self) -> &Self::Target {
168+
&self.0.data
169+
}
170+
}
171+
172+
impl<T> Drop for Devres<T> {
173+
fn drop(&mut self) {
174+
// Revoke the data, such that it gets dropped already and the actual resource is freed.
175+
// `DevresInner` has to stay alive until the devres callback has been called. This is
176+
// necessary since we don't know when `Devres` is dropped and calling
177+
// `devm_remove_action()` instead could race with `devres_release_all()`.
178+
self.revoke();
179+
}
180+
}

rust/kernel/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ pub mod block;
3939
mod build_assert;
4040
pub mod device;
4141
pub mod device_id;
42+
pub mod devres;
4243
pub mod driver;
4344
pub mod error;
4445
#[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)]

0 commit comments

Comments
 (0)