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::Device,
12 error::{Error, Result},
13 ffi::c_void,
14 prelude::*,
15 revocable::{Revocable, RevocableGuard},
16 sync::{rcu, Arc, Completion},
17 types::ARef,
18};
19
20#[pin_data]
21struct DevresInner<T> {
22 dev: ARef<Device>,
23 callback: unsafe extern "C" fn(*mut c_void),
24 #[pin]
25 data: Revocable<T>,
26 #[pin]
27 revoke: Completion,
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. In any case, it is always
35/// guaranteed that revoking the device resource is completed before the corresponding [`Device`]
36/// is unbound.
37///
38/// To achieve that [`Devres`] registers a devres callback on creation, which is called once the
39/// [`Device`] is unbound, revoking access to the encapsulated resource (see also [`Revocable`]).
40///
41/// After the [`Devres`] has been unbound it is not possible to access the encapsulated resource
42/// anymore.
43///
44/// [`Devres`] users should make sure to simply free the corresponding backing resource in `T`'s
45/// [`Drop`] implementation.
46///
47/// # Example
48///
49/// ```no_run
50/// # use kernel::{bindings, c_str, device::Device, devres::Devres, io::{Io, IoRaw}};
51/// # use core::ops::Deref;
52///
53/// // See also [`pci::Bar`] for a real example.
54/// struct IoMem<const SIZE: usize>(IoRaw<SIZE>);
55///
56/// impl<const SIZE: usize> IoMem<SIZE> {
57/// /// # Safety
58/// ///
59/// /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs
60/// /// virtual address space.
61/// unsafe fn new(paddr: usize) -> Result<Self>{
62/// // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is
63/// // valid for `ioremap`.
64/// let addr = unsafe { bindings::ioremap(paddr as _, SIZE as _) };
65/// if addr.is_null() {
66/// return Err(ENOMEM);
67/// }
68///
69/// Ok(IoMem(IoRaw::new(addr as _, SIZE)?))
70/// }
71/// }
72///
73/// impl<const SIZE: usize> Drop for IoMem<SIZE> {
74/// fn drop(&mut self) {
75/// // SAFETY: `self.0.addr()` is guaranteed to be properly mapped by `Self::new`.
76/// unsafe { bindings::iounmap(self.0.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/// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`.
85/// unsafe { Io::from_raw(&self.0) }
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::get_device(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.write8(0x42, 0x0);
98/// # Ok(())
99/// # }
100/// ```
101pub struct Devres<T>(Arc<DevresInner<T>>);
102
103impl<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 dev: dev.into(),
108 callback: Self::devres_callback,
109 data <- Revocable::new(data),
110 revoke <- Completion::new(),
111 }),
112 flags,
113 )?;
114
115 // Convert `Arc<DevresInner>` into a raw pointer and make devres own this reference until
116 // `Self::devres_callback` is called.
117 let data = inner.clone().into_raw();
118
119 // SAFETY: `devm_add_action` guarantees to call `Self::devres_callback` once `dev` is
120 // detached.
121 let ret =
122 unsafe { bindings::devm_add_action(dev.as_raw(), Some(inner.callback), data as _) };
123
124 if ret != 0 {
125 // SAFETY: We just created another reference to `inner` in order to pass it to
126 // `bindings::devm_add_action`. If `bindings::devm_add_action` fails, we have to drop
127 // this reference accordingly.
128 let _ = unsafe { Arc::from_raw(data) };
129 return Err(Error::from_errno(ret));
130 }
131
132 Ok(inner)
133 }
134
135 fn as_ptr(&self) -> *const Self {
136 self as _
137 }
138
139 fn remove_action(this: &Arc<Self>) -> bool {
140 // SAFETY:
141 // - `self.inner.dev` is a valid `Device`,
142 // - the `action` and `data` pointers are the exact same ones as given to devm_add_action()
143 // previously,
144 // - `self` is always valid, even if the action has been released already.
145 let success = unsafe {
146 bindings::devm_remove_action_nowarn(
147 this.dev.as_raw(),
148 Some(this.callback),
149 this.as_ptr() as _,
150 )
151 } == 0;
152
153 if success {
154 // SAFETY: We leaked an `Arc` reference to devm_add_action() in `DevresInner::new`; if
155 // devm_remove_action_nowarn() was successful we can (and have to) claim back ownership
156 // of this reference.
157 let _ = unsafe { Arc::from_raw(this.as_ptr()) };
158 }
159
160 success
161 }
162
163 #[allow(clippy::missing_safety_doc)]
164 unsafe extern "C" fn devres_callback(ptr: *mut kernel::ffi::c_void) {
165 let ptr = ptr as *mut DevresInner<T>;
166 // Devres owned this memory; now that we received the callback, drop the `Arc` and hence the
167 // reference.
168 // SAFETY: Safe, since we leaked an `Arc` reference to devm_add_action() in
169 // `DevresInner::new`.
170 let inner = unsafe { Arc::from_raw(ptr) };
171
172 if !inner.data.revoke() {
173 // If `revoke()` returns false, it means that `Devres::drop` already started revoking
174 // `inner.data` for us. Hence we have to wait until `Devres::drop()` signals that it
175 // completed revoking `inner.data`.
176 inner.revoke.wait_for_completion();
177 }
178 }
179}
180
181impl<T> Devres<T> {
182 /// Creates a new [`Devres`] instance of the given `data`. The `data` encapsulated within the
183 /// returned `Devres` instance' `data` will be revoked once the device is detached.
184 pub fn new(dev: &Device, data: T, flags: Flags) -> Result<Self> {
185 let inner = DevresInner::new(dev, data, flags)?;
186
187 Ok(Devres(inner))
188 }
189
190 /// Same as [`Devres::new`], but does not return a `Devres` instance. Instead the given `data`
191 /// is owned by devres and will be revoked / dropped, once the device is detached.
192 pub fn new_foreign_owned(dev: &Device, data: T, flags: Flags) -> Result {
193 let _ = DevresInner::new(dev, data, flags)?;
194
195 Ok(())
196 }
197
198 /// [`Devres`] accessor for [`Revocable::try_access`].
199 pub fn try_access(&self) -> Option<RevocableGuard<'_, T>> {
200 self.0.data.try_access()
201 }
202
203 /// [`Devres`] accessor for [`Revocable::try_access_with_guard`].
204 pub fn try_access_with_guard<'a>(&'a self, guard: &'a rcu::Guard) -> Option<&'a T> {
205 self.0.data.try_access_with_guard(guard)
206 }
207}
208
209impl<T> Drop for Devres<T> {
210 fn drop(&mut self) {
211 // SAFETY: When `drop` runs, it is guaranteed that nobody is accessing the revocable data
212 // anymore, hence it is safe not to wait for the grace period to finish.
213 if unsafe { self.0.data.revoke_nosync() } {
214 // We revoked `self.0.data` before the devres action did, hence try to remove it.
215 if !DevresInner::remove_action(&self.0) {
216 // We could not remove the devres action, which means that it now runs concurrently,
217 // hence signal that `self.0.data` has been revoked successfully.
218 self.0.revoke.complete_all();
219 }
220 }
221 }
222}