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 } 179