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