xref: /linux/rust/kernel/devres.rs (revision 71d4e7233f235871b13553e504e591ace6b54373)
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::{
12         Bound,
13         Device, //
14     },
15     error::to_result,
16     prelude::*,
17     revocable::{
18         Revocable,
19         RevocableGuard, //
20     },
21     sync::{
22         aref::ARef,
23         rcu,
24         Arc, //
25     },
26     types::{
27         ForeignOwnable,
28         Opaque, //
29     },
30 };
31 
32 /// Inner type that embeds a `struct devres_node` and the `Revocable<T>`.
33 #[repr(C)]
34 #[pin_data]
35 struct Inner<T> {
36     #[pin]
37     node: Opaque<bindings::devres_node>,
38     #[pin]
39     data: Revocable<T>,
40 }
41 
42 /// This abstraction is meant to be used by subsystems to containerize [`Device`] bound resources to
43 /// manage their lifetime.
44 ///
45 /// [`Device`] bound resources should be freed when either the resource goes out of scope or the
46 /// [`Device`] is unbound respectively, depending on what happens first. In any case, it is always
47 /// guaranteed that revoking the device resource is completed before the corresponding [`Device`]
48 /// is unbound.
49 ///
50 /// To achieve that [`Devres`] registers a devres callback on creation, which is called once the
51 /// [`Device`] is unbound, revoking access to the encapsulated resource (see also [`Revocable`]).
52 ///
53 /// After the [`Devres`] has been unbound it is not possible to access the encapsulated resource
54 /// anymore.
55 ///
56 /// [`Devres`] users should make sure to simply free the corresponding backing resource in `T`'s
57 /// [`Drop`] implementation.
58 ///
59 /// # Examples
60 ///
61 /// ```no_run
62 /// use kernel::{
63 ///     bindings,
64 ///     device::{
65 ///         Bound,
66 ///         Device,
67 ///     },
68 ///     devres::Devres,
69 ///     io::{
70 ///         Io,
71 ///         IoBase,
72 ///         Mmio,
73 ///         MmioRaw,
74 ///         MmioBackend,
75 ///         PhysAddr,
76 ///         Region, //
77 ///     },
78 ///     prelude::*,
79 /// };
80 /// use core::ops::Deref;
81 ///
82 /// // See also [`pci::Bar`] for a real example.
83 /// struct IoMem<const SIZE: usize>(MmioRaw<Region<SIZE>>);
84 ///
85 /// impl<const SIZE: usize> IoMem<SIZE> {
86 ///     /// # Safety
87 ///     ///
88 ///     /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs
89 ///     /// virtual address space.
90 ///     unsafe fn new(paddr: usize) -> Result<Self>{
91 ///         // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is
92 ///         // valid for `ioremap`.
93 ///         let addr = unsafe { bindings::ioremap(paddr as PhysAddr, SIZE) };
94 ///         if addr.is_null() {
95 ///             return Err(ENOMEM);
96 ///         }
97 ///
98 ///         Ok(IoMem(MmioRaw::new_region(addr as usize, SIZE)?))
99 ///     }
100 /// }
101 ///
102 /// impl<const SIZE: usize> Drop for IoMem<SIZE> {
103 ///     fn drop(&mut self) {
104 ///         // SAFETY: `self.0.addr()` is guaranteed to be properly mapped by `Self::new`.
105 ///         unsafe { bindings::iounmap(self.0.addr() as *mut c_void); };
106 ///     }
107 /// }
108 ///
109 /// impl<'a, const SIZE: usize> IoBase<'a> for &'a IoMem<SIZE> {
110 ///    type Backend = MmioBackend;
111 ///    type Target = Region<SIZE>;
112 ///
113 ///    fn as_view(self) -> Mmio<'a, Region<SIZE>> {
114 ///         // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`.
115 ///         unsafe { Mmio::from_raw(self.0) }
116 ///    }
117 /// }
118 /// # fn no_run(dev: &Device<Bound>) -> Result<(), Error> {
119 /// // SAFETY: Invalid usage for example purposes.
120 /// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };
121 /// let devres = Devres::new(dev, iomem)?;
122 ///
123 /// let res = devres.try_access().ok_or(ENXIO)?;
124 /// res.write8(0x42, 0x0);
125 /// # Ok(())
126 /// # }
127 /// ```
128 pub struct Devres<T: Send + 'static> {
129     dev: ARef<Device>,
130     inner: Arc<Inner<T>>,
131 }
132 
133 // Calling the FFI functions from the `base` module directly from the `Devres<T>` impl may result in
134 // them being called directly from driver modules. This happens since the Rust compiler will use
135 // monomorphisation, so it might happen that functions are instantiated within the calling driver
136 // module. For now, work around this with `#[inline(never)]` helpers.
137 //
138 // TODO: Remove once a more generic solution has been implemented. For instance, we may be able to
139 // leverage `bindgen` to take care of this depending on whether a symbol is (already) exported.
140 mod base {
141     use kernel::{
142         bindings,
143         prelude::*, //
144     };
145 
146     #[inline(never)]
147     #[allow(clippy::missing_safety_doc)]
148     pub(super) unsafe fn devres_node_init(
149         node: *mut bindings::devres_node,
150         release: bindings::dr_node_release_t,
151         free: bindings::dr_node_free_t,
152     ) {
153         // SAFETY: Safety requirements are the same as `bindings::devres_node_init`.
154         unsafe { bindings::devres_node_init(node, release, free) }
155     }
156 
157     #[inline(never)]
158     #[allow(clippy::missing_safety_doc)]
159     pub(super) unsafe fn devres_set_node_dbginfo(
160         node: *mut bindings::devres_node,
161         name: *const c_char,
162         size: usize,
163     ) {
164         // SAFETY: Safety requirements are the same as `bindings::devres_set_node_dbginfo`.
165         unsafe { bindings::devres_set_node_dbginfo(node, name, size) }
166     }
167 
168     #[inline(never)]
169     #[allow(clippy::missing_safety_doc)]
170     pub(super) unsafe fn devres_node_add(
171         dev: *mut bindings::device,
172         node: *mut bindings::devres_node,
173     ) {
174         // SAFETY: Safety requirements are the same as `bindings::devres_node_add`.
175         unsafe { bindings::devres_node_add(dev, node) }
176     }
177 
178     #[must_use]
179     #[inline(never)]
180     #[allow(clippy::missing_safety_doc)]
181     pub(super) unsafe fn devres_node_remove(
182         dev: *mut bindings::device,
183         node: *mut bindings::devres_node,
184     ) -> bool {
185         // SAFETY: Safety requirements are the same as `bindings::devres_node_remove`.
186         unsafe { bindings::devres_node_remove(dev, node) }
187     }
188 }
189 
190 impl<T: Send + 'static> Devres<T> {
191     /// Creates a new [`Devres`] instance of the given `data`.
192     ///
193     /// The `data` encapsulated within the returned `Devres` instance' `data` will be
194     /// (revoked)[`Revocable`] once the device is detached.
195     pub fn new<E>(dev: &Device<Bound>, data: impl PinInit<T, E>) -> Result<Self>
196     where
197         Error: From<E>,
198     {
199         let inner = Arc::pin_init::<Error>(
200             try_pin_init!(Inner {
201                 node <- Opaque::ffi_init(|node: *mut bindings::devres_node| {
202                     // SAFETY: `node` is a valid pointer to an uninitialized `struct devres_node`.
203                     unsafe {
204                         base::devres_node_init(
205                             node,
206                             Some(Self::devres_node_release),
207                             Some(Self::devres_node_free_node),
208                         )
209                     };
210 
211                     // SAFETY: `node` is a valid pointer to an uninitialized `struct devres_node`.
212                     unsafe {
213                         base::devres_set_node_dbginfo(
214                             node,
215                             // TODO: Use `core::any::type_name::<T>()` once it is a `const fn`,
216                             // such that we can convert the `&str` to a `&CStr` at compile-time.
217                             c"Devres<T>".as_char_ptr(),
218                             core::mem::size_of::<Revocable<T>>(),
219                         )
220                     };
221                 }),
222                 data <- Revocable::new(data),
223             }),
224             GFP_KERNEL,
225         )?;
226 
227         // SAFETY:
228         // - `dev` is a valid pointer to a bound `struct device`.
229         // - `node` is a valid pointer to a `struct devres_node`.
230         // - `devres_node_add()` is guaranteed not to call `devres_node_release()` for the entire
231         //    lifetime of `dev`.
232         unsafe { base::devres_node_add(dev.as_raw(), inner.node.get()) };
233 
234         // Take additional reference count for `devres_node_add()`.
235         core::mem::forget(inner.clone());
236 
237         Ok(Self {
238             dev: dev.into(),
239             inner,
240         })
241     }
242 
243     fn data(&self) -> &Revocable<T> {
244         &self.inner.data
245     }
246 
247     #[allow(clippy::missing_safety_doc)]
248     unsafe extern "C" fn devres_node_release(
249         _dev: *mut bindings::device,
250         node: *mut bindings::devres_node,
251     ) {
252         let node = Opaque::cast_from(node);
253 
254         // SAFETY: `node` is in the same allocation as its container.
255         let inner = unsafe { kernel::container_of!(node, Inner<T>, node) };
256 
257         // SAFETY: `inner` is a valid `Inner<T>` pointer.
258         let inner = unsafe { &*inner };
259 
260         inner.data.revoke();
261     }
262 
263     #[allow(clippy::missing_safety_doc)]
264     unsafe extern "C" fn devres_node_free_node(node: *mut bindings::devres_node) {
265         let node = Opaque::cast_from(node);
266 
267         // SAFETY: `node` is in the same allocation as its container.
268         let inner = unsafe { kernel::container_of!(node, Inner<T>, node) };
269 
270         // SAFETY: `inner` points to the entire `Inner<T>` allocation.
271         drop(unsafe { Arc::from_raw(inner) });
272     }
273 
274     fn remove_node(&self) -> bool {
275         // SAFETY:
276         // - `self.device().as_raw()` is a valid pointer to a bound `struct device`.
277         // - `self.inner.node.get()` is a valid pointer to a `struct devres_node`.
278         unsafe { base::devres_node_remove(self.device().as_raw(), self.inner.node.get()) }
279     }
280 
281     /// Return a reference of the [`Device`] this [`Devres`] instance has been created with.
282     pub fn device(&self) -> &Device {
283         &self.dev
284     }
285 
286     /// Obtain `&'a T`, bypassing the [`Revocable`].
287     ///
288     /// This method allows to directly obtain a `&'a T`, bypassing the [`Revocable`], by presenting
289     /// a `&'a Device<Bound>` of the same [`Device`] this [`Devres`] instance has been created with.
290     ///
291     /// # Errors
292     ///
293     /// An error is returned if `dev` does not match the same [`Device`] this [`Devres`] instance
294     /// has been created with.
295     ///
296     /// # Examples
297     ///
298     /// ```no_run
299     /// #![cfg(CONFIG_PCI)]
300     /// use kernel::{
301     ///     device::Core,
302     ///     devres::Devres,
303     ///     io::Io,
304     ///     pci, //
305     /// };
306     ///
307     /// fn from_core(dev: &pci::Device<Core<'_>>, devres: Devres<pci::Bar<'_, 0x4>>) -> Result {
308     ///     let bar = devres.access(dev.as_ref())?;
309     ///
310     ///     let _ = bar.read32(0x0);
311     ///
312     ///     // might_sleep()
313     ///
314     ///     bar.write32(0x42, 0x0);
315     ///
316     ///     Ok(())
317     /// }
318     /// ```
319     pub fn access<'a>(&'a self, dev: &'a Device<Bound>) -> Result<&'a T> {
320         if self.dev.as_raw() != dev.as_raw() {
321             return Err(EINVAL);
322         }
323 
324         // SAFETY: `dev` being the same device as the device this `Devres` has been created for
325         // proves that `self.data` hasn't been revoked and is guaranteed to not be revoked as long
326         // as `dev` lives; `dev` lives at least as long as `self`.
327         Ok(unsafe { self.data().access() })
328     }
329 
330     /// [`Devres`] accessor for [`Revocable::try_access`].
331     pub fn try_access(&self) -> Option<RevocableGuard<'_, T>> {
332         self.data().try_access()
333     }
334 
335     /// [`Devres`] accessor for [`Revocable::try_access_with`].
336     pub fn try_access_with<R, F: FnOnce(&T) -> R>(&self, f: F) -> Option<R> {
337         self.data().try_access_with(f)
338     }
339 
340     /// [`Devres`] accessor for [`Revocable::try_access_with_guard`].
341     pub fn try_access_with_guard<'a>(&'a self, guard: &'a rcu::Guard) -> Option<&'a T> {
342         self.data().try_access_with_guard(guard)
343     }
344 }
345 
346 // SAFETY: `Devres` can be send to any task, if `T: Send`.
347 unsafe impl<T: Send> Send for Devres<T> {}
348 
349 // SAFETY: `Devres` can be shared with any task, if `T: Sync`.
350 unsafe impl<T: Send + Sync> Sync for Devres<T> {}
351 
352 impl<T: Send + 'static> Drop for Devres<T> {
353     fn drop(&mut self) {
354         // SAFETY: When `drop` runs, it is guaranteed that nobody is accessing the revocable data
355         // anymore, hence it is safe not to wait for the grace period to finish.
356         if unsafe { self.data().revoke_nosync() } {
357             // We revoked `self.data` before devres did, hence try to remove it.
358             if self.remove_node() {
359                 // SAFETY: In `Self::new` we have taken an additional reference count of `self.data`
360                 // for `devres_node_add()`. Since `remove_node()` was successful, we have to drop
361                 // this additional reference count.
362                 drop(unsafe { Arc::from_raw(Arc::as_ptr(&self.inner)) });
363             }
364         }
365     }
366 }
367 
368 /// Consume `data` and [`Drop::drop`] `data` once `dev` is unbound.
369 fn register_foreign<P>(dev: &Device<Bound>, data: P) -> Result
370 where
371     P: ForeignOwnable + Send + 'static,
372 {
373     let ptr = data.into_foreign();
374 
375     #[allow(clippy::missing_safety_doc)]
376     unsafe extern "C" fn callback<P: ForeignOwnable>(ptr: *mut kernel::ffi::c_void) {
377         // SAFETY: `ptr` is the pointer to the `ForeignOwnable` leaked above and hence valid.
378         drop(unsafe { P::from_foreign(ptr.cast()) });
379     }
380 
381     // SAFETY:
382     // - `dev.as_raw()` is a pointer to a valid and bound device.
383     // - `ptr` is a valid pointer the `ForeignOwnable` devres takes ownership of.
384     to_result(unsafe {
385         // `devm_add_action_or_reset()` also calls `callback` on failure, such that the
386         // `ForeignOwnable` is released eventually.
387         bindings::devm_add_action_or_reset(dev.as_raw(), Some(callback::<P>), ptr.cast())
388     })
389 }
390 
391 /// Encapsulate `data` in a [`KBox`] and [`Drop::drop`] `data` once `dev` is unbound.
392 ///
393 /// # Examples
394 ///
395 /// ```no_run
396 /// use kernel::{
397 ///     device::{
398 ///         Bound,
399 ///         Device, //
400 ///     },
401 ///     devres, //
402 /// };
403 ///
404 /// /// Registration of e.g. a class device, IRQ, etc.
405 /// struct Registration;
406 ///
407 /// impl Registration {
408 ///     fn new() -> Self {
409 ///         // register
410 ///
411 ///         Self
412 ///     }
413 /// }
414 ///
415 /// impl Drop for Registration {
416 ///     fn drop(&mut self) {
417 ///        // unregister
418 ///     }
419 /// }
420 ///
421 /// fn from_bound_context(dev: &Device<Bound>) -> Result {
422 ///     devres::register(dev, Registration::new(), GFP_KERNEL)
423 /// }
424 /// ```
425 pub fn register<T, E>(dev: &Device<Bound>, data: impl PinInit<T, E>, flags: Flags) -> Result
426 where
427     T: Send + 'static,
428     Error: From<E>,
429 {
430     let data = KBox::pin_init(data, flags)?;
431 
432     register_foreign(dev, data)
433 }
434