xref: /linux/rust/kernel/devres.rs (revision 8f799b4e8cc0cf926019e40405dc3eab330ac643)
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         Completion, //
25     },
26     types::{
27         ForeignOwnable,
28         Opaque,
29         ScopeGuard, //
30     },
31 };
32 
33 use pin_init::Wrapper;
34 
35 /// [`Devres`] inner data accessed from [`Devres::callback`].
36 #[pin_data]
37 struct Inner<T: Send> {
38     #[pin]
39     data: Revocable<T>,
40     /// Tracks whether [`Devres::callback`] has been completed.
41     #[pin]
42     devm: Completion,
43     /// Tracks whether revoking [`Self::data`] has been completed.
44     #[pin]
45     revoke: Completion,
46 }
47 
48 /// This abstraction is meant to be used by subsystems to containerize [`Device`] bound resources to
49 /// manage their lifetime.
50 ///
51 /// [`Device`] bound resources should be freed when either the resource goes out of scope or the
52 /// [`Device`] is unbound respectively, depending on what happens first. In any case, it is always
53 /// guaranteed that revoking the device resource is completed before the corresponding [`Device`]
54 /// is unbound.
55 ///
56 /// To achieve that [`Devres`] registers a devres callback on creation, which is called once the
57 /// [`Device`] is unbound, revoking access to the encapsulated resource (see also [`Revocable`]).
58 ///
59 /// After the [`Devres`] has been unbound it is not possible to access the encapsulated resource
60 /// anymore.
61 ///
62 /// [`Devres`] users should make sure to simply free the corresponding backing resource in `T`'s
63 /// [`Drop`] implementation.
64 ///
65 /// # Examples
66 ///
67 /// ```no_run
68 /// use kernel::{
69 ///     bindings,
70 ///     device::{
71 ///         Bound,
72 ///         Device,
73 ///     },
74 ///     devres::Devres,
75 ///     io::{
76 ///         Io,
77 ///         IoRaw,
78 ///         PhysAddr,
79 ///     },
80 /// };
81 /// use core::ops::Deref;
82 ///
83 /// // See also [`pci::Bar`] for a real example.
84 /// struct IoMem<const SIZE: usize>(IoRaw<SIZE>);
85 ///
86 /// impl<const SIZE: usize> IoMem<SIZE> {
87 ///     /// # Safety
88 ///     ///
89 ///     /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs
90 ///     /// virtual address space.
91 ///     unsafe fn new(paddr: usize) -> Result<Self>{
92 ///         // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is
93 ///         // valid for `ioremap`.
94 ///         let addr = unsafe { bindings::ioremap(paddr as PhysAddr, SIZE) };
95 ///         if addr.is_null() {
96 ///             return Err(ENOMEM);
97 ///         }
98 ///
99 ///         Ok(IoMem(IoRaw::new(addr as usize, SIZE)?))
100 ///     }
101 /// }
102 ///
103 /// impl<const SIZE: usize> Drop for IoMem<SIZE> {
104 ///     fn drop(&mut self) {
105 ///         // SAFETY: `self.0.addr()` is guaranteed to be properly mapped by `Self::new`.
106 ///         unsafe { bindings::iounmap(self.0.addr() as *mut c_void); };
107 ///     }
108 /// }
109 ///
110 /// impl<const SIZE: usize> Deref for IoMem<SIZE> {
111 ///    type Target = Io<SIZE>;
112 ///
113 ///    fn deref(&self) -> &Self::Target {
114 ///         // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`.
115 ///         unsafe { Io::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 = KBox::pin_init(Devres::new(dev, iomem), GFP_KERNEL)?;
122 ///
123 /// let res = devres.try_access().ok_or(ENXIO)?;
124 /// res.write8(0x42, 0x0);
125 /// # Ok(())
126 /// # }
127 /// ```
128 ///
129 /// # Invariants
130 ///
131 /// `Self::inner` is guaranteed to be initialized and is always accessed read-only.
132 #[pin_data(PinnedDrop)]
133 pub struct Devres<T: Send> {
134     dev: ARef<Device>,
135     /// Pointer to [`Self::devres_callback`].
136     ///
137     /// Has to be stored, since Rust does not guarantee to always return the same address for a
138     /// function. However, the C API uses the address as a key.
139     callback: unsafe extern "C" fn(*mut c_void),
140     /// Contains all the fields shared with [`Self::callback`].
141     // TODO: Replace with `UnsafePinned`, once available.
142     //
143     // Subsequently, the `drop_in_place()` in `Devres::drop` and `Devres::new` as well as the
144     // explicit `Send` and `Sync' impls can be removed.
145     #[pin]
146     inner: Opaque<Inner<T>>,
147     _add_action: (),
148 }
149 
150 impl<T: Send> Devres<T> {
151     /// Creates a new [`Devres`] instance of the given `data`.
152     ///
153     /// The `data` encapsulated within the returned `Devres` instance' `data` will be
154     /// (revoked)[`Revocable`] once the device is detached.
155     pub fn new<'a, E>(
156         dev: &'a Device<Bound>,
157         data: impl PinInit<T, E> + 'a,
158     ) -> impl PinInit<Self, Error> + 'a
159     where
160         T: 'a,
161         Error: From<E>,
162     {
163         try_pin_init!(&this in Self {
164             dev: dev.into(),
165             callback: Self::devres_callback,
166             // INVARIANT: `inner` is properly initialized.
167             inner <- Opaque::pin_init(try_pin_init!(Inner {
168                     devm <- Completion::new(),
169                     revoke <- Completion::new(),
170                     data <- Revocable::new(data),
171             })),
172             // TODO: Replace with "initializer code blocks" [1] once available.
173             //
174             // [1] https://github.com/Rust-for-Linux/pin-init/pull/69
175             _add_action: {
176                 // SAFETY: `this` is a valid pointer to uninitialized memory.
177                 let inner = unsafe { &raw mut (*this.as_ptr()).inner };
178 
179                 // SAFETY:
180                 // - `dev.as_raw()` is a pointer to a valid bound device.
181                 // - `inner` is guaranteed to be a valid for the duration of the lifetime of `Self`.
182                 // - `devm_add_action()` is guaranteed not to call `callback` until `this` has been
183                 //    properly initialized, because we require `dev` (i.e. the *bound* device) to
184                 //    live at least as long as the returned `impl PinInit<Self, Error>`.
185                 to_result(unsafe {
186                     bindings::devm_add_action(dev.as_raw(), Some(*callback), inner.cast())
187                 }).inspect_err(|_| {
188                     let inner = Opaque::cast_into(inner);
189 
190                     // SAFETY: `inner` is a valid pointer to an `Inner<T>` and valid for both reads
191                     // and writes.
192                     unsafe { core::ptr::drop_in_place(inner) };
193                 })?;
194             },
195         })
196     }
197 
198     fn inner(&self) -> &Inner<T> {
199         // SAFETY: By the type invairants of `Self`, `inner` is properly initialized and always
200         // accessed read-only.
201         unsafe { &*self.inner.get() }
202     }
203 
204     fn data(&self) -> &Revocable<T> {
205         &self.inner().data
206     }
207 
208     #[allow(clippy::missing_safety_doc)]
209     unsafe extern "C" fn devres_callback(ptr: *mut kernel::ffi::c_void) {
210         // SAFETY: In `Self::new` we've passed a valid pointer to `Inner` to `devm_add_action()`,
211         // hence `ptr` must be a valid pointer to `Inner`.
212         let inner = unsafe { &*ptr.cast::<Inner<T>>() };
213 
214         // Ensure that `inner` can't be used anymore after we signal completion of this callback.
215         let inner = ScopeGuard::new_with_data(inner, |inner| inner.devm.complete_all());
216 
217         if !inner.data.revoke() {
218             // If `revoke()` returns false, it means that `Devres::drop` already started revoking
219             // `data` for us. Hence we have to wait until `Devres::drop` signals that it
220             // completed revoking `data`.
221             inner.revoke.wait_for_completion();
222         }
223     }
224 
225     fn remove_action(&self) -> bool {
226         // SAFETY:
227         // - `self.dev` is a valid `Device`,
228         // - the `action` and `data` pointers are the exact same ones as given to
229         //   `devm_add_action()` previously,
230         (unsafe {
231             bindings::devm_remove_action_nowarn(
232                 self.dev.as_raw(),
233                 Some(self.callback),
234                 core::ptr::from_ref(self.inner()).cast_mut().cast(),
235             )
236         } == 0)
237     }
238 
239     /// Return a reference of the [`Device`] this [`Devres`] instance has been created with.
240     pub fn device(&self) -> &Device {
241         &self.dev
242     }
243 
244     /// Obtain `&'a T`, bypassing the [`Revocable`].
245     ///
246     /// This method allows to directly obtain a `&'a T`, bypassing the [`Revocable`], by presenting
247     /// a `&'a Device<Bound>` of the same [`Device`] this [`Devres`] instance has been created with.
248     ///
249     /// # Errors
250     ///
251     /// An error is returned if `dev` does not match the same [`Device`] this [`Devres`] instance
252     /// has been created with.
253     ///
254     /// # Examples
255     ///
256     /// ```no_run
257     /// # #![cfg(CONFIG_PCI)]
258     /// # use kernel::{device::Core, devres::Devres, pci};
259     ///
260     /// fn from_core(dev: &pci::Device<Core>, devres: Devres<pci::Bar<0x4>>) -> Result {
261     ///     let bar = devres.access(dev.as_ref())?;
262     ///
263     ///     let _ = bar.read32(0x0);
264     ///
265     ///     // might_sleep()
266     ///
267     ///     bar.write32(0x42, 0x0);
268     ///
269     ///     Ok(())
270     /// }
271     /// ```
272     pub fn access<'a>(&'a self, dev: &'a Device<Bound>) -> Result<&'a T> {
273         if self.dev.as_raw() != dev.as_raw() {
274             return Err(EINVAL);
275         }
276 
277         // SAFETY: `dev` being the same device as the device this `Devres` has been created for
278         // proves that `self.data` hasn't been revoked and is guaranteed to not be revoked as long
279         // as `dev` lives; `dev` lives at least as long as `self`.
280         Ok(unsafe { self.data().access() })
281     }
282 
283     /// [`Devres`] accessor for [`Revocable::try_access`].
284     pub fn try_access(&self) -> Option<RevocableGuard<'_, T>> {
285         self.data().try_access()
286     }
287 
288     /// [`Devres`] accessor for [`Revocable::try_access_with`].
289     pub fn try_access_with<R, F: FnOnce(&T) -> R>(&self, f: F) -> Option<R> {
290         self.data().try_access_with(f)
291     }
292 
293     /// [`Devres`] accessor for [`Revocable::try_access_with_guard`].
294     pub fn try_access_with_guard<'a>(&'a self, guard: &'a rcu::Guard) -> Option<&'a T> {
295         self.data().try_access_with_guard(guard)
296     }
297 }
298 
299 // SAFETY: `Devres` can be send to any task, if `T: Send`.
300 unsafe impl<T: Send> Send for Devres<T> {}
301 
302 // SAFETY: `Devres` can be shared with any task, if `T: Sync`.
303 unsafe impl<T: Send + Sync> Sync for Devres<T> {}
304 
305 #[pinned_drop]
306 impl<T: Send> PinnedDrop for Devres<T> {
307     fn drop(self: Pin<&mut Self>) {
308         // SAFETY: When `drop` runs, it is guaranteed that nobody is accessing the revocable data
309         // anymore, hence it is safe not to wait for the grace period to finish.
310         if unsafe { self.data().revoke_nosync() } {
311             // We revoked `self.data` before the devres action did, hence try to remove it.
312             if !self.remove_action() {
313                 // We could not remove the devres action, which means that it now runs concurrently,
314                 // hence signal that `self.data` has been revoked by us successfully.
315                 self.inner().revoke.complete_all();
316 
317                 // Wait for `Self::devres_callback` to be done using this object.
318                 self.inner().devm.wait_for_completion();
319             }
320         } else {
321             // `Self::devres_callback` revokes `self.data` for us, hence wait for it to be done
322             // using this object.
323             self.inner().devm.wait_for_completion();
324         }
325 
326         // INVARIANT: At this point it is guaranteed that `inner` can't be accessed any more.
327         //
328         // SAFETY: `inner` is valid for dropping.
329         unsafe { core::ptr::drop_in_place(self.inner.get()) };
330     }
331 }
332 
333 /// Consume `data` and [`Drop::drop`] `data` once `dev` is unbound.
334 fn register_foreign<P>(dev: &Device<Bound>, data: P) -> Result
335 where
336     P: ForeignOwnable + Send + 'static,
337 {
338     let ptr = data.into_foreign();
339 
340     #[allow(clippy::missing_safety_doc)]
341     unsafe extern "C" fn callback<P: ForeignOwnable>(ptr: *mut kernel::ffi::c_void) {
342         // SAFETY: `ptr` is the pointer to the `ForeignOwnable` leaked above and hence valid.
343         drop(unsafe { P::from_foreign(ptr.cast()) });
344     }
345 
346     // SAFETY:
347     // - `dev.as_raw()` is a pointer to a valid and bound device.
348     // - `ptr` is a valid pointer the `ForeignOwnable` devres takes ownership of.
349     to_result(unsafe {
350         // `devm_add_action_or_reset()` also calls `callback` on failure, such that the
351         // `ForeignOwnable` is released eventually.
352         bindings::devm_add_action_or_reset(dev.as_raw(), Some(callback::<P>), ptr.cast())
353     })
354 }
355 
356 /// Encapsulate `data` in a [`KBox`] and [`Drop::drop`] `data` once `dev` is unbound.
357 ///
358 /// # Examples
359 ///
360 /// ```no_run
361 /// use kernel::{device::{Bound, Device}, devres};
362 ///
363 /// /// Registration of e.g. a class device, IRQ, etc.
364 /// struct Registration;
365 ///
366 /// impl Registration {
367 ///     fn new() -> Self {
368 ///         // register
369 ///
370 ///         Self
371 ///     }
372 /// }
373 ///
374 /// impl Drop for Registration {
375 ///     fn drop(&mut self) {
376 ///        // unregister
377 ///     }
378 /// }
379 ///
380 /// fn from_bound_context(dev: &Device<Bound>) -> Result {
381 ///     devres::register(dev, Registration::new(), GFP_KERNEL)
382 /// }
383 /// ```
384 pub fn register<T, E>(dev: &Device<Bound>, data: impl PinInit<T, E>, flags: Flags) -> Result
385 where
386     T: Send + 'static,
387     Error: From<E>,
388 {
389     let data = KBox::pin_init(data, flags)?;
390 
391     register_foreign(dev, data)
392 }
393