// SPDX-License-Identifier: GPL-2.012//! Devres abstraction3//!4//! [`Devres`] represents an abstraction for the kernel devres (device resource management)5//! implementation.67use crate::{8alloc::Flags,9bindings,10device::{Bound, Device},11error::{to_result, Error, Result},12ffi::c_void,13prelude::*,14revocable::{Revocable, RevocableGuard},15sync::{aref::ARef, rcu, Completion},16types::{ForeignOwnable, Opaque, ScopeGuard},17};1819use pin_init::Wrapper;2021/// [`Devres`] inner data accessed from [`Devres::callback`].22#[pin_data]23struct Inner<T: Send> {24#[pin]25data: Revocable<T>,26/// Tracks whether [`Devres::callback`] has been completed.27#[pin]28devm: Completion,29/// Tracks whether revoking [`Self::data`] has been completed.30#[pin]31revoke: Completion,32}3334/// This abstraction is meant to be used by subsystems to containerize [`Device`] bound resources to35/// manage their lifetime.36///37/// [`Device`] bound resources should be freed when either the resource goes out of scope or the38/// [`Device`] is unbound respectively, depending on what happens first. In any case, it is always39/// guaranteed that revoking the device resource is completed before the corresponding [`Device`]40/// is unbound.41///42/// To achieve that [`Devres`] registers a devres callback on creation, which is called once the43/// [`Device`] is unbound, revoking access to the encapsulated resource (see also [`Revocable`]).44///45/// After the [`Devres`] has been unbound it is not possible to access the encapsulated resource46/// anymore.47///48/// [`Devres`] users should make sure to simply free the corresponding backing resource in `T`'s49/// [`Drop`] implementation.50///51/// # Examples52///53/// ```no_run54/// # use kernel::{bindings, device::{Bound, Device}, devres::Devres, io::{Io, IoRaw}};55/// # use core::ops::Deref;56///57/// // See also [`pci::Bar`] for a real example.58/// struct IoMem<const SIZE: usize>(IoRaw<SIZE>);59///60/// impl<const SIZE: usize> IoMem<SIZE> {61/// /// # Safety62/// ///63/// /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs64/// /// virtual address space.65/// unsafe fn new(paddr: usize) -> Result<Self>{66/// // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is67/// // valid for `ioremap`.68/// let addr = unsafe { bindings::ioremap(paddr as bindings::phys_addr_t, SIZE) };69/// if addr.is_null() {70/// return Err(ENOMEM);71/// }72///73/// Ok(IoMem(IoRaw::new(addr as usize, SIZE)?))74/// }75/// }76///77/// impl<const SIZE: usize> Drop for IoMem<SIZE> {78/// fn drop(&mut self) {79/// // SAFETY: `self.0.addr()` is guaranteed to be properly mapped by `Self::new`.80/// unsafe { bindings::iounmap(self.0.addr() as *mut c_void); };81/// }82/// }83///84/// impl<const SIZE: usize> Deref for IoMem<SIZE> {85/// type Target = Io<SIZE>;86///87/// fn deref(&self) -> &Self::Target {88/// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`.89/// unsafe { Io::from_raw(&self.0) }90/// }91/// }92/// # fn no_run(dev: &Device<Bound>) -> Result<(), Error> {93/// // SAFETY: Invalid usage for example purposes.94/// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };95/// let devres = KBox::pin_init(Devres::new(dev, iomem), GFP_KERNEL)?;96///97/// let res = devres.try_access().ok_or(ENXIO)?;98/// res.write8(0x42, 0x0);99/// # Ok(())100/// # }101/// ```102///103/// # Invariants104///105/// [`Self::inner`] is guaranteed to be initialized and is always accessed read-only.106#[pin_data(PinnedDrop)]107pub struct Devres<T: Send> {108dev: ARef<Device>,109/// Pointer to [`Self::devres_callback`].110///111/// Has to be stored, since Rust does not guarantee to always return the same address for a112/// function. However, the C API uses the address as a key.113callback: unsafe extern "C" fn(*mut c_void),114/// Contains all the fields shared with [`Self::callback`].115// TODO: Replace with `UnsafePinned`, once available.116//117// Subsequently, the `drop_in_place()` in `Devres::drop` and `Devres::new` as well as the118// explicit `Send` and `Sync' impls can be removed.119#[pin]120inner: Opaque<Inner<T>>,121_add_action: (),122}123124impl<T: Send> Devres<T> {125/// Creates a new [`Devres`] instance of the given `data`.126///127/// The `data` encapsulated within the returned `Devres` instance' `data` will be128/// (revoked)[`Revocable`] once the device is detached.129pub fn new<'a, E>(130dev: &'a Device<Bound>,131data: impl PinInit<T, E> + 'a,132) -> impl PinInit<Self, Error> + 'a133where134T: 'a,135Error: From<E>,136{137try_pin_init!(&this in Self {138dev: dev.into(),139callback: Self::devres_callback,140// INVARIANT: `inner` is properly initialized.141inner <- Opaque::pin_init(try_pin_init!(Inner {142devm <- Completion::new(),143revoke <- Completion::new(),144data <- Revocable::new(data),145})),146// TODO: Replace with "initializer code blocks" [1] once available.147//148// [1] https://github.com/Rust-for-Linux/pin-init/pull/69149_add_action: {150// SAFETY: `this` is a valid pointer to uninitialized memory.151let inner = unsafe { &raw mut (*this.as_ptr()).inner };152153// SAFETY:154// - `dev.as_raw()` is a pointer to a valid bound device.155// - `inner` is guaranteed to be a valid for the duration of the lifetime of `Self`.156// - `devm_add_action()` is guaranteed not to call `callback` until `this` has been157// properly initialized, because we require `dev` (i.e. the *bound* device) to158// live at least as long as the returned `impl PinInit<Self, Error>`.159to_result(unsafe {160bindings::devm_add_action(dev.as_raw(), Some(*callback), inner.cast())161}).inspect_err(|_| {162let inner = Opaque::cast_into(inner);163164// SAFETY: `inner` is a valid pointer to an `Inner<T>` and valid for both reads165// and writes.166unsafe { core::ptr::drop_in_place(inner) };167})?;168},169})170}171172fn inner(&self) -> &Inner<T> {173// SAFETY: By the type invairants of `Self`, `inner` is properly initialized and always174// accessed read-only.175unsafe { &*self.inner.get() }176}177178fn data(&self) -> &Revocable<T> {179&self.inner().data180}181182#[allow(clippy::missing_safety_doc)]183unsafe extern "C" fn devres_callback(ptr: *mut kernel::ffi::c_void) {184// SAFETY: In `Self::new` we've passed a valid pointer to `Inner` to `devm_add_action()`,185// hence `ptr` must be a valid pointer to `Inner`.186let inner = unsafe { &*ptr.cast::<Inner<T>>() };187188// Ensure that `inner` can't be used anymore after we signal completion of this callback.189let inner = ScopeGuard::new_with_data(inner, |inner| inner.devm.complete_all());190191if !inner.data.revoke() {192// If `revoke()` returns false, it means that `Devres::drop` already started revoking193// `data` for us. Hence we have to wait until `Devres::drop` signals that it194// completed revoking `data`.195inner.revoke.wait_for_completion();196}197}198199fn remove_action(&self) -> bool {200// SAFETY:201// - `self.dev` is a valid `Device`,202// - the `action` and `data` pointers are the exact same ones as given to203// `devm_add_action()` previously,204(unsafe {205bindings::devm_remove_action_nowarn(206self.dev.as_raw(),207Some(self.callback),208core::ptr::from_ref(self.inner()).cast_mut().cast(),209)210} == 0)211}212213/// Return a reference of the [`Device`] this [`Devres`] instance has been created with.214pub fn device(&self) -> &Device {215&self.dev216}217218/// Obtain `&'a T`, bypassing the [`Revocable`].219///220/// This method allows to directly obtain a `&'a T`, bypassing the [`Revocable`], by presenting221/// a `&'a Device<Bound>` of the same [`Device`] this [`Devres`] instance has been created with.222///223/// # Errors224///225/// An error is returned if `dev` does not match the same [`Device`] this [`Devres`] instance226/// has been created with.227///228/// # Examples229///230/// ```no_run231/// # #![cfg(CONFIG_PCI)]232/// # use kernel::{device::Core, devres::Devres, pci};233///234/// fn from_core(dev: &pci::Device<Core>, devres: Devres<pci::Bar<0x4>>) -> Result {235/// let bar = devres.access(dev.as_ref())?;236///237/// let _ = bar.read32(0x0);238///239/// // might_sleep()240///241/// bar.write32(0x42, 0x0);242///243/// Ok(())244/// }245/// ```246pub fn access<'a>(&'a self, dev: &'a Device<Bound>) -> Result<&'a T> {247if self.dev.as_raw() != dev.as_raw() {248return Err(EINVAL);249}250251// SAFETY: `dev` being the same device as the device this `Devres` has been created for252// proves that `self.data` hasn't been revoked and is guaranteed to not be revoked as long253// as `dev` lives; `dev` lives at least as long as `self`.254Ok(unsafe { self.data().access() })255}256257/// [`Devres`] accessor for [`Revocable::try_access`].258pub fn try_access(&self) -> Option<RevocableGuard<'_, T>> {259self.data().try_access()260}261262/// [`Devres`] accessor for [`Revocable::try_access_with`].263pub fn try_access_with<R, F: FnOnce(&T) -> R>(&self, f: F) -> Option<R> {264self.data().try_access_with(f)265}266267/// [`Devres`] accessor for [`Revocable::try_access_with_guard`].268pub fn try_access_with_guard<'a>(&'a self, guard: &'a rcu::Guard) -> Option<&'a T> {269self.data().try_access_with_guard(guard)270}271}272273// SAFETY: `Devres` can be send to any task, if `T: Send`.274unsafe impl<T: Send> Send for Devres<T> {}275276// SAFETY: `Devres` can be shared with any task, if `T: Sync`.277unsafe impl<T: Send + Sync> Sync for Devres<T> {}278279#[pinned_drop]280impl<T: Send> PinnedDrop for Devres<T> {281fn drop(self: Pin<&mut Self>) {282// SAFETY: When `drop` runs, it is guaranteed that nobody is accessing the revocable data283// anymore, hence it is safe not to wait for the grace period to finish.284if unsafe { self.data().revoke_nosync() } {285// We revoked `self.data` before the devres action did, hence try to remove it.286if !self.remove_action() {287// We could not remove the devres action, which means that it now runs concurrently,288// hence signal that `self.data` has been revoked by us successfully.289self.inner().revoke.complete_all();290291// Wait for `Self::devres_callback` to be done using this object.292self.inner().devm.wait_for_completion();293}294} else {295// `Self::devres_callback` revokes `self.data` for us, hence wait for it to be done296// using this object.297self.inner().devm.wait_for_completion();298}299300// INVARIANT: At this point it is guaranteed that `inner` can't be accessed any more.301//302// SAFETY: `inner` is valid for dropping.303unsafe { core::ptr::drop_in_place(self.inner.get()) };304}305}306307/// Consume `data` and [`Drop::drop`] `data` once `dev` is unbound.308fn register_foreign<P>(dev: &Device<Bound>, data: P) -> Result309where310P: ForeignOwnable + Send + 'static,311{312let ptr = data.into_foreign();313314#[allow(clippy::missing_safety_doc)]315unsafe extern "C" fn callback<P: ForeignOwnable>(ptr: *mut kernel::ffi::c_void) {316// SAFETY: `ptr` is the pointer to the `ForeignOwnable` leaked above and hence valid.317drop(unsafe { P::from_foreign(ptr.cast()) });318}319320// SAFETY:321// - `dev.as_raw()` is a pointer to a valid and bound device.322// - `ptr` is a valid pointer the `ForeignOwnable` devres takes ownership of.323to_result(unsafe {324// `devm_add_action_or_reset()` also calls `callback` on failure, such that the325// `ForeignOwnable` is released eventually.326bindings::devm_add_action_or_reset(dev.as_raw(), Some(callback::<P>), ptr.cast())327})328}329330/// Encapsulate `data` in a [`KBox`] and [`Drop::drop`] `data` once `dev` is unbound.331///332/// # Examples333///334/// ```no_run335/// use kernel::{device::{Bound, Device}, devres};336///337/// /// Registration of e.g. a class device, IRQ, etc.338/// struct Registration;339///340/// impl Registration {341/// fn new() -> Self {342/// // register343///344/// Self345/// }346/// }347///348/// impl Drop for Registration {349/// fn drop(&mut self) {350/// // unregister351/// }352/// }353///354/// fn from_bound_context(dev: &Device<Bound>) -> Result {355/// devres::register(dev, Registration::new(), GFP_KERNEL)356/// }357/// ```358pub fn register<T, E>(dev: &Device<Bound>, data: impl PinInit<T, E>, flags: Flags) -> Result359where360T: Send + 'static,361Error: From<E>,362{363let data = KBox::pin_init(data, flags)?;364365register_foreign(dev, data)366}367368369