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