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