Skip to content

Commit 71fef57

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 d75d1d9 commit 71fef57

File tree

5 files changed

+191
-0
lines changed

5 files changed

+191
-0
lines changed

MAINTAINERS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7034,6 +7034,7 @@ F: include/linux/property.h
70347034
F: lib/kobj*
70357035
F: rust/kernel/device.rs
70367036
F: rust/kernel/device_id.rs
7037+
F: rust/kernel/devres.rs
70377038
F: rust/kernel/driver.rs
70387039

70397040
DRIVERS FOR OMAP ADAPTIVE VOLTAGE SCALING (AVS)

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
@@ -12,6 +12,7 @@
1212
#include "build_assert.c"
1313
#include "build_bug.c"
1414
#include "cred.c"
15+
#include "device.c"
1516
#include "err.c"
1617
#include "fs.c"
1718
#include "io.c"

rust/kernel/devres.rs

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

rust/kernel/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ mod build_assert;
4141
pub mod cred;
4242
pub mod device;
4343
pub mod device_id;
44+
pub mod devres;
4445
pub mod driver;
4546
pub mod error;
4647
#[cfg(CONFIG_RUST_FW_LOADER_ABSTRACTIONS)]

0 commit comments

Comments
 (0)