linux/rust/kernel/devres.rs
Linus Torvalds 58809f614e drm next for 6.18-rc1
cross-subsystem:
 - i2c-hid: Make elan touch controllers power on after panel is enabled
 - dt bindings for STM32MP25 SoC
 - pci vgaarb: use screen_info helpers
 - rust pin-init updates
 - add MEI driver for late binding firmware update/load
 
 uapi:
 - add ioctl for reassigning GEM handles
 - provide boot_display attribute on boot-up devices
 
 core:
 - document DRM_MODE_PAGE_FLIP_EVENT
 - add vendor specific recovery method to drm device wedged uevent
 
 gem:
 - Simplify gpuvm locking
 
 ttm:
 - add interface to populate buffers
 
 sched:
 - Fix race condition in trace code
 
 atomic:
 - Reallow no-op async page flips
 
 display:
 - dp: Fix command length
 
 video:
 - Improve pixel-format handling for struct screen_info
 
 rust:
 - drop Opaque<> from ioctl args
 - Alloc:
 - BorrowedPage type and AsPageIter traits
 - Implement Vmalloc::to_page() and VmallocPageIter
 - DMA/Scatterlist:
 - Add dma::DataDirection and type alias for dma_addr_t
 - Abstraction for struct scatterlist and sg_table
 - DRM:
 - simplify use of generics
 - add DriverFile type alias
 - drop Object::SIZE
 - Rust:
 - pin-init tree merge
 - Various methods for AsBytes and FromBytes traits
 
 gpuvm:
 - Support madvice in Xe driver
 
 gpusvm:
 - fix hmm_pfn_to_map_order usage in gpusvm
 
 bridge:
 - Improve and fix ref counting on bridge management
 - cdns-dsi: Various improvements to mode setting
 - Support Solomon SSD2825 plus DT bindings
 - Support Waveshare DSI2DPI plus DT bindings
 - Support Content Protection property
 - display-connector: Improve DP display detection
 - Add support for Radxa Ra620 plus DT bindings
 - adv7511: Provide SPD and HDMI infoframes
 - it6505: Replace crypto_shash with sha()
 - synopsys: Add support for DW DPTX Controller plus DT bindings
 - adv7511: Write full Audio infoframe
 - ite6263: Support vendor-specific infoframes
 - simple: Add support for Realtek RTD2171 DP-to-HDMI plus DT bindings
 
 panel:
 - panel-edp: Support mt8189 Chromebooks; Support BOE NV140WUM-N64;
   Support SHP LQ134Z1; Fixes
 - panel-simple: Support Olimex LCD-OLinuXino-5CTS plus DT bindings
 - Support Samsung AMS561RA01
 - Support Hydis HV101HD1 plus DT bindings
 - ilitek-ili9881c: Refactor mode setting; Add support for Bestar
   BSD1218-A101KL68 LCD plus DT bindings
 - lvds: Add support for Ampire AMP19201200B5TZQW-T03 to DT bindings
 - edp: Add support for additonal mt8189 Chromebook panels
 - lvds: Add DT bindings for EDT ETML0700Z8DHA
 
 amdgpu:
 - add CRIU support for gem objects
 - RAS updates
 - VCN SRAM load fixes
 - EDID read fixes
 - eDP ALPM support
 - Documentation updates
 - Rework PTE flag generation
 - DCE6 fixes
 - VCN devcoredump cleanup
 - MMHUB client id fixes
 - VCN 5.0.1 RAS support
 - SMU 13.0.x updates
 - Expanded PCIe DPC support
 - Expanded VCN reset support
 - VPE per queue reset support
 - give kernel jobs unique id for tracing
 - pre-populate exported buffers
 - cyan skillfish updates
 - make vbios build number available in sysfs
 - userq updates
 - HDCP updates
 - support MMIO remap page as ttm pool
 - JPEG parser updates
 - DCE6 DC updates
 - use devm for i2c buses
 - GPUVM locking updates
 - Drop non-DC DCE11 code
 - improve fallback handling for pixel encoding
 
 amdkfd:
 - SVM/page migration fixes
 - debugfs fixes
 - add CRIO support for gem objects
 - SVM updates
 
 radeon:
 - use dev_warn_once in CS parsers
 
 xe:
 - add madvise interface
 - add DRM_IOCTL_XE_VM_QUERY_MEMORY_RANGE_ATTRS to query VMA count
   and memory attributes
 - drop L# bank mask reporting from media GT3 on Xe3+.
 - add SLPC power_profile sysfs interface
 - add configs attribs to add post/mid context-switch commands
 - handle firmware reported hardware errors notifying userspace with
   device wedged uevent
 - use same dir structure across sysfs/debugfs
 - cleanup and future proof vram region init
 - add G-states and PCI link states to debugfs
 - Add SRIOV support for CCS surfaces on Xe2+
 - Enable SRIOV PF mode by default on supported platforms
 - move flush to common code
 - extended core workarounds for Xe2/3
 - use DRM scheduler for delayed GT TLB invalidations
 - configs improvements and allow VF device enablement
 - prep work to expose mmio regions to userspace
 - VF migration support added
 - prepare GPU SVM for THP migration
 - start fixing XE_PAGE_SIZE vs PAGE_SIZE
 - add PSMI support for hw validation
 - resize VF bars to max possible size according to number of VFs
 - Ensure GT is in C0 during resume
 - pre-populate exported buffers
 - replace xe_hmm with gpusvm
 - add more SVM GT stats to debugfs
 - improve fake pci and WA kunnit handle for new platform testing
 - Test GuC to GuC comms to add debugging
 - use attribute groups to simplify sysfs registration
 - add Late Binding firmware code to interact with MEI
 
 i915:
 - apply multiple JSL/EHL/Gen7/Gen6 workarounds properly
 - protect against overflow in active_engine()
 - Use try_cmpxchg64() in __active_lookup()
 - include GuC registers in error state
 - get rid of dev->struct_mutex
 - iopoll: generalize read_poll_timout
 - lots more display refactoring
 - Reject HBR3 in any eDP Panel
 - Prune modes for YUV420
 - Display Wa fix, additions, and updates
 - DP: Fix 2.7 Gbps link training on g4x
 - DP: Adjust the idle pattern handling
 - DP: Shuffle the link training code a bit
 - Don't set/read the DSI C clock divider on GLK
 - Enable_psr kernel parameter changes
 - Type-C enabled/disconnected dp-alt sink
 - Wildcat Lake enabling
 - DP HDR updates
 - DRAM detection
 - wait PSR idle on dsb commit
 - Remove FBC modulo 4 restriction for ADL-P+
 - panic: refactor framebuffer allocation
 
 habanalabs:
 - debug/visibility improvements
 - vmalloc-backed coherent mmap support
 - HLDIO infrastructure
 
 nova-core:
 - various register!() macro improvements
 - minor vbios/firmware fixes/refactoring
 - advance firmware boot stages; process Booter and patch signatures
 - process GSP and GSP bootloader
 - Add r570.144 firmware bindings and update to it
 - Move GSP boot code to own module
 - Use new pin-init features to store driver's private data in a single
  allocation
 - Update ARef import from sync::aref
 
 nova-drm:
 - Update ARef import from sync::aref
 
 tyr:
 - initial driver skeleton for a rust driver for ARM Mali GPUs
 - capable of powering up, query metadata and provide it to userspace.
 
 msm:
 - GPU and Core:
 - in DT bindings describe clocks per GPU type
 - GMU bandwidth voting for x1-85
 - a623/a663 speedbins
 - cleanup some remaining no-iommu leftovers after VM_BIND conversion
 - fix GEM obj 32b size truncation
 - add missing VM_BIND param validation
 - IFPC for x1-85 and a750
 - register xml and gen_header.py sync from mesa
 - Display:
 - add missing bindings for display on SC8180X
 - added DisplayPort MST bindings
 - conversion from round_rate() to determine_rate()
 
 amdxdna:
 - add IOCTL_AMDXDNA_GET_ARRAY
 - support user space allocated buffers
 - streamline PM interfaces
 - Refactoring wrt. hardware contexts
 - improve error reporting
 
 nouveau:
 - use GSP firmware by default
 - improve error reporting
 - Pre-populate exported buffers
 
 ast:
 - Clean up detection of DRAM config
 
 exynos:
 - add DSIM bridge driver support for Exynos7870
 - Document Exynos7870 DSIM compatible in dt-binding
 
 panthor:
 - Print task/pid on errors
 - Add support for Mali G710, G510, G310, Gx15, Gx20, Gx25
 - Improve cache flushing
 - Fail VM bind if BO has offset
 
 renesas:
 - convert to RUNTIME_PM_OPS
 
 rcar-du:
 - Make number of lanes configurable
 - Use RUNTIME_PM_OPS
 - Add support for DSI commands
 
 rocket:
 - Add driver for Rockchip NPU plus DT bindings
 - Use kfree() and sizeof() correctly
 - Test DMA status
 
 rockchip:
 - dsi2: Add support for RK3576 plus DT bindings
 - Add support for RK3588 DPTX output
 
 tidss:
 - Use crtc_ fields for programming display mode
 - Remove other drivers from aperture
 
 pixpaper:
 - Add support for Mayqueen Pixpaper plus DT bindings
 
 v3d:
 - Support querying nubmer of GPU resets for KHR_robustness
 
 stm:
 - Clean up logging
 - ltdc: Add support support for STM32MP257F-EV1 plus DT bindings
 
 sitronix:
 - st7571-i2c: Add support for inverted displays and 2-bit grayscale
 
 tidss:
 - Convert to kernel's FIELD_ macros
 
 vesadrm:
 - Support 8-bit palette mode
 
 imagination:
 - Improve power management
 - Add support for TH1520 GPU
 - Support Risc-V architectures
 
 v3d:
 - Improve job management and locking
 
 vkms:
 - Support variants of ARGB8888, ARGB16161616, RGB565, RGB888 and P01x
 - Spport YUV with 16-bit components
 -----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCgAdFiEEEKbZHaGwW9KfbeusDHTzWXnEhr4FAmjcpjkACgkQDHTzWXnE
 hr7Q7g/5AcxXqLUx7wvmDga9TpzIjDD+C+MOt568RpFQ9cYprI+/86ma7ELCpuNe
 dVgeobxQb/jyhf4acdBU+t5aZz+j8VPhPtIPrPY2kOVDuL1NfeQNS8VmGNpFhR+0
 6hqVrtfvbYdLBrAHrU/V/RwZlBJvI/D/I2QGuvZZwWzCBgYd4u4bGuRyBCvGDxOD
 CTPaEqYyzjvpVuzu7AGQk655WkZQnyPmiezIl2lit1meEMMMv80HePkyWHclZo7Q
 hMqsEasSp5w5Q5EpYqVr1z5IdBAV1O53oor9W573J3kEoB4o1zEsTPfLO4N1dgXo
 bfvc24uW3zyChWY2hWyRKvOzvAoClnjfY6whv9NRP0Qi4UjzhLlNOpmhm9cst/J+
 uj2Nn8UJtyvFJbTmDvoocpgdhq2mkGKdIVhVQ6tG7PjihFmyQRF7PJZjb+0Vee7L
 53F0c4d6HiBI4DHa+lH6fgQUBspIvSfmcnR0ACg29NByib+JEoPSPb4ET+uZ8lLd
 IbQvNiCdnUduYDCKfo5ea/FesP8AXy1KfSa+z7oEEFYHbbkc7PSztUagEyZdS/yS
 FnnYqmo/DidmyM4nxDQUII+UDqjng7fo+l4BzIhL12pR693KzCf0mexMr6SA24ny
 gasN97923OTle1J9xrPrKavkx6WjswZCvOaG7ZbnJB47ydJVu5w=
 =ZVKY
 -----END PGP SIGNATURE-----

Merge tag 'drm-next-2025-10-01' of https://gitlab.freedesktop.org/drm/kernel

Pull drm updates from Dave Airlie:
 "cross-subsystem:
   - i2c-hid: Make elan touch controllers power on after panel is
     enabled
   - dt bindings for STM32MP25 SoC
   - pci vgaarb: use screen_info helpers
   - rust pin-init updates
   - add MEI driver for late binding firmware update/load

  uapi:
   - add ioctl for reassigning GEM handles
   - provide boot_display attribute on boot-up devices

  core:
   - document DRM_MODE_PAGE_FLIP_EVENT
   - add vendor specific recovery method to drm device wedged uevent

  gem:
   - Simplify gpuvm locking

  ttm:
   - add interface to populate buffers

  sched:
   - Fix race condition in trace code

  atomic:
   - Reallow no-op async page flips

  display:
   - dp: Fix command length

  video:
   - Improve pixel-format handling for struct screen_info

  rust:
   - drop Opaque<> from ioctl args
   - Alloc:
       - BorrowedPage type and AsPageIter traits
       - Implement Vmalloc::to_page() and VmallocPageIter
   - DMA/Scatterlist:
       - Add dma::DataDirection and type alias for dma_addr_t
       - Abstraction for struct scatterlist and sg_table
   - DRM:
       - simplify use of generics
       - add DriverFile type alias
       - drop Object::SIZE
   - Rust:
       - pin-init tree merge
       - Various methods for AsBytes and FromBytes traits

  gpuvm:
   - Support madvice in Xe driver

  gpusvm:
   - fix hmm_pfn_to_map_order usage in gpusvm

  bridge:
   - Improve and fix ref counting on bridge management
   - cdns-dsi: Various improvements to mode setting
   - Support Solomon SSD2825 plus DT bindings
   - Support Waveshare DSI2DPI plus DT bindings
   - Support Content Protection property
   - display-connector: Improve DP display detection
   - Add support for Radxa Ra620 plus DT bindings
   - adv7511: Provide SPD and HDMI infoframes
   - it6505: Replace crypto_shash with sha()
   - synopsys: Add support for DW DPTX Controller plus DT bindings
   - adv7511: Write full Audio infoframe
   - ite6263: Support vendor-specific infoframes
   - simple: Add support for Realtek RTD2171 DP-to-HDMI plus DT bindings

  panel:
   - panel-edp: Support mt8189 Chromebooks; Support BOE NV140WUM-N64;
     Support SHP LQ134Z1; Fixes
   - panel-simple: Support Olimex LCD-OLinuXino-5CTS plus DT bindings
   - Support Samsung AMS561RA01
   - Support Hydis HV101HD1 plus DT bindings
   - ilitek-ili9881c: Refactor mode setting; Add support for Bestar
     BSD1218-A101KL68 LCD plus DT bindings
   - lvds: Add support for Ampire AMP19201200B5TZQW-T03 to DT bindings
   - edp: Add support for additonal mt8189 Chromebook panels
   - lvds: Add DT bindings for EDT ETML0700Z8DHA

  amdgpu:
   - add CRIU support for gem objects
   - RAS updates
   - VCN SRAM load fixes
   - EDID read fixes
   - eDP ALPM support
   - Documentation updates
   - Rework PTE flag generation
   - DCE6 fixes
   - VCN devcoredump cleanup
   - MMHUB client id fixes
   - VCN 5.0.1 RAS support
   - SMU 13.0.x updates
   - Expanded PCIe DPC support
   - Expanded VCN reset support
   - VPE per queue reset support
   - give kernel jobs unique id for tracing
   - pre-populate exported buffers
   - cyan skillfish updates
   - make vbios build number available in sysfs
   - userq updates
   - HDCP updates
   - support MMIO remap page as ttm pool
   - JPEG parser updates
   - DCE6 DC updates
   - use devm for i2c buses
   - GPUVM locking updates
   - Drop non-DC DCE11 code
   - improve fallback handling for pixel encoding

  amdkfd:
   - SVM/page migration fixes
   - debugfs fixes
   - add CRIO support for gem objects
   - SVM updates

  radeon:
   - use dev_warn_once in CS parsers

  xe:
   - add madvise interface
   - add DRM_IOCTL_XE_VM_QUERY_MEMORY_RANGE_ATTRS to query VMA count
     and memory attributes
   - drop L# bank mask reporting from media GT3 on Xe3+.
   - add SLPC power_profile sysfs interface
   - add configs attribs to add post/mid context-switch commands
   - handle firmware reported hardware errors notifying userspace with
     device wedged uevent
   - use same dir structure across sysfs/debugfs
   - cleanup and future proof vram region init
   - add G-states and PCI link states to debugfs
   - Add SRIOV support for CCS surfaces on Xe2+
   - Enable SRIOV PF mode by default on supported platforms
   - move flush to common code
   - extended core workarounds for Xe2/3
   - use DRM scheduler for delayed GT TLB invalidations
   - configs improvements and allow VF device enablement
   - prep work to expose mmio regions to userspace
   - VF migration support added
   - prepare GPU SVM for THP migration
   - start fixing XE_PAGE_SIZE vs PAGE_SIZE
   - add PSMI support for hw validation
   - resize VF bars to max possible size according to number of VFs
   - Ensure GT is in C0 during resume
   - pre-populate exported buffers
   - replace xe_hmm with gpusvm
   - add more SVM GT stats to debugfs
   - improve fake pci and WA kunnit handle for new platform testing
   - Test GuC to GuC comms to add debugging
   - use attribute groups to simplify sysfs registration
   - add Late Binding firmware code to interact with MEI

  i915:
   - apply multiple JSL/EHL/Gen7/Gen6 workarounds properly
   - protect against overflow in active_engine()
   - Use try_cmpxchg64() in __active_lookup()
   - include GuC registers in error state
   - get rid of dev->struct_mutex
   - iopoll: generalize read_poll_timout
   - lots more display refactoring
   - Reject HBR3 in any eDP Panel
   - Prune modes for YUV420
   - Display Wa fix, additions, and updates
   - DP: Fix 2.7 Gbps link training on g4x
   - DP: Adjust the idle pattern handling
   - DP: Shuffle the link training code a bit
   - Don't set/read the DSI C clock divider on GLK
   - Enable_psr kernel parameter changes
   - Type-C enabled/disconnected dp-alt sink
   - Wildcat Lake enabling
   - DP HDR updates
   - DRAM detection
   - wait PSR idle on dsb commit
   - Remove FBC modulo 4 restriction for ADL-P+
   - panic: refactor framebuffer allocation

  habanalabs:
   - debug/visibility improvements
   - vmalloc-backed coherent mmap support
   - HLDIO infrastructure

  nova-core:
   - various register!() macro improvements
   - minor vbios/firmware fixes/refactoring
   - advance firmware boot stages; process Booter and patch signatures
   - process GSP and GSP bootloader
   - Add r570.144 firmware bindings and update to it
   - Move GSP boot code to own module
   - Use new pin-init features to store driver's private data in a
     single allocation
   - Update ARef import from sync::aref

  nova-drm:
   - Update ARef import from sync::aref

  tyr:
   - initial driver skeleton for a rust driver for ARM Mali GPUs
   - capable of powering up, query metadata and provide it to userspace.

  msm:
   - GPU and Core:
      - in DT bindings describe clocks per GPU type
      - GMU bandwidth voting for x1-85
      - a623/a663 speedbins
      - cleanup some remaining no-iommu leftovers after VM_BIND conversion
      - fix GEM obj 32b size truncation
      - add missing VM_BIND param validation
      - IFPC for x1-85 and a750
      - register xml and gen_header.py sync from mesa
   - Display:
      - add missing bindings for display on SC8180X
      - added DisplayPort MST bindings
      - conversion from round_rate() to determine_rate()

  amdxdna:
   - add IOCTL_AMDXDNA_GET_ARRAY
   - support user space allocated buffers
   - streamline PM interfaces
   - Refactoring wrt. hardware contexts
   - improve error reporting

  nouveau:
   - use GSP firmware by default
   - improve error reporting
   - Pre-populate exported buffers

  ast:
   - Clean up detection of DRAM config

  exynos:
   - add DSIM bridge driver support for Exynos7870
   - Document Exynos7870 DSIM compatible in dt-binding

  panthor:
   - Print task/pid on errors
   - Add support for Mali G710, G510, G310, Gx15, Gx20, Gx25
   - Improve cache flushing
   - Fail VM bind if BO has offset

  renesas:
   - convert to RUNTIME_PM_OPS

  rcar-du:
   - Make number of lanes configurable
   - Use RUNTIME_PM_OPS
   - Add support for DSI commands

  rocket:
   - Add driver for Rockchip NPU plus DT bindings
   - Use kfree() and sizeof() correctly
   - Test DMA status

  rockchip:
   - dsi2: Add support for RK3576 plus DT bindings
   - Add support for RK3588 DPTX output

  tidss:
   - Use crtc_ fields for programming display mode
   - Remove other drivers from aperture

  pixpaper:
   - Add support for Mayqueen Pixpaper plus DT bindings

  v3d:
   - Support querying nubmer of GPU resets for KHR_robustness

  stm:
   - Clean up logging
   - ltdc: Add support support for STM32MP257F-EV1 plus DT bindings

  sitronix:
   - st7571-i2c: Add support for inverted displays and 2-bit grayscale

  tidss:
   - Convert to kernel's FIELD_ macros

  vesadrm:
   - Support 8-bit palette mode

  imagination:
   - Improve power management
   - Add support for TH1520 GPU
   - Support Risc-V architectures

  v3d:
   - Improve job management and locking

  vkms:
   - Support variants of ARGB8888, ARGB16161616, RGB565, RGB888 and P01x
   - Spport YUV with 16-bit components"

* tag 'drm-next-2025-10-01' of https://gitlab.freedesktop.org/drm/kernel: (1455 commits)
  drm/amd: Add name to modes from amdgpu_connector_add_common_modes()
  drm/amd: Drop some common modes from amdgpu_connector_add_common_modes()
  drm/amdgpu: update MODULE_PARM_DESC for freesync_video
  drm/amd: Use dynamic array size declaration for amdgpu_connector_add_common_modes()
  drm/amd/display: Share dce100_validate_global with DCE6-8
  drm/amd/display: Share dce100_validate_bandwidth with DCE6-8
  drm/amdgpu: Fix fence signaling race condition in userqueue
  amd/amdkfd: enhance kfd process check in switch partition
  amd/amdkfd: resolve a race in amdgpu_amdkfd_device_fini_sw
  drm/amd/display: Reject modes with too high pixel clock on DCE6-10
  drm/amd: Drop unnecessary check in amdgpu_connector_add_common_modes()
  drm/amd/display: Only enable common modes for eDP and LVDS
  drm/amdgpu: remove the redeclaration of variable i
  drm/amdgpu/userq: assign an error code for invalid userq va
  drm/amdgpu: revert "rework reserved VMID handling" v2
  drm/amdgpu: remove leftover from enforcing isolation by VMID
  drm/amdgpu: Add fallback to pipe reset if KCQ ring reset fails
  accel/habanalabs: add Infineon version check
  accel/habanalabs/gaudi2: read preboot status after recovering from dirty state
  accel/habanalabs: add HL_GET_P_STATE passthrough type
  ...
2025-10-02 12:47:25 -07:00

367 lines
13 KiB
Rust

// SPDX-License-Identifier: GPL-2.0
//! Devres abstraction
//!
//! [`Devres`] represents an abstraction for the kernel devres (device resource management)
//! implementation.
use crate::{
alloc::Flags,
bindings,
device::{Bound, Device},
error::{to_result, Error, Result},
ffi::c_void,
prelude::*,
revocable::{Revocable, RevocableGuard},
sync::{aref::ARef, rcu, Completion},
types::{ForeignOwnable, Opaque, ScopeGuard},
};
use pin_init::Wrapper;
/// [`Devres`] inner data accessed from [`Devres::callback`].
#[pin_data]
struct Inner<T: Send> {
#[pin]
data: Revocable<T>,
/// Tracks whether [`Devres::callback`] has been completed.
#[pin]
devm: Completion,
/// Tracks whether revoking [`Self::data`] has been completed.
#[pin]
revoke: Completion,
}
/// This abstraction is meant to be used by subsystems to containerize [`Device`] bound resources to
/// manage their lifetime.
///
/// [`Device`] bound resources should be freed when either the resource goes out of scope or the
/// [`Device`] is unbound respectively, depending on what happens first. In any case, it is always
/// guaranteed that revoking the device resource is completed before the corresponding [`Device`]
/// is unbound.
///
/// To achieve that [`Devres`] registers a devres callback on creation, which is called once the
/// [`Device`] is unbound, revoking access to the encapsulated resource (see also [`Revocable`]).
///
/// After the [`Devres`] has been unbound it is not possible to access the encapsulated resource
/// anymore.
///
/// [`Devres`] users should make sure to simply free the corresponding backing resource in `T`'s
/// [`Drop`] implementation.
///
/// # Examples
///
/// ```no_run
/// # use kernel::{bindings, device::{Bound, Device}, devres::Devres, io::{Io, IoRaw}};
/// # use core::ops::Deref;
///
/// // See also [`pci::Bar`] for a real example.
/// struct IoMem<const SIZE: usize>(IoRaw<SIZE>);
///
/// impl<const SIZE: usize> IoMem<SIZE> {
/// /// # Safety
/// ///
/// /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs
/// /// virtual address space.
/// unsafe fn new(paddr: usize) -> Result<Self>{
/// // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is
/// // valid for `ioremap`.
/// let addr = unsafe { bindings::ioremap(paddr as bindings::phys_addr_t, SIZE) };
/// if addr.is_null() {
/// return Err(ENOMEM);
/// }
///
/// Ok(IoMem(IoRaw::new(addr as usize, SIZE)?))
/// }
/// }
///
/// impl<const SIZE: usize> Drop for IoMem<SIZE> {
/// fn drop(&mut self) {
/// // SAFETY: `self.0.addr()` is guaranteed to be properly mapped by `Self::new`.
/// unsafe { bindings::iounmap(self.0.addr() as *mut c_void); };
/// }
/// }
///
/// impl<const SIZE: usize> Deref for IoMem<SIZE> {
/// type Target = Io<SIZE>;
///
/// fn deref(&self) -> &Self::Target {
/// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`.
/// unsafe { Io::from_raw(&self.0) }
/// }
/// }
/// # fn no_run(dev: &Device<Bound>) -> Result<(), Error> {
/// // SAFETY: Invalid usage for example purposes.
/// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };
/// let devres = KBox::pin_init(Devres::new(dev, iomem), GFP_KERNEL)?;
///
/// let res = devres.try_access().ok_or(ENXIO)?;
/// res.write8(0x42, 0x0);
/// # Ok(())
/// # }
/// ```
///
/// # Invariants
///
/// [`Self::inner`] is guaranteed to be initialized and is always accessed read-only.
#[pin_data(PinnedDrop)]
pub struct Devres<T: Send> {
dev: ARef<Device>,
/// Pointer to [`Self::devres_callback`].
///
/// Has to be stored, since Rust does not guarantee to always return the same address for a
/// function. However, the C API uses the address as a key.
callback: unsafe extern "C" fn(*mut c_void),
/// Contains all the fields shared with [`Self::callback`].
// TODO: Replace with `UnsafePinned`, once available.
//
// Subsequently, the `drop_in_place()` in `Devres::drop` and `Devres::new` as well as the
// explicit `Send` and `Sync' impls can be removed.
#[pin]
inner: Opaque<Inner<T>>,
_add_action: (),
}
impl<T: Send> Devres<T> {
/// Creates a new [`Devres`] instance of the given `data`.
///
/// The `data` encapsulated within the returned `Devres` instance' `data` will be
/// (revoked)[`Revocable`] once the device is detached.
pub fn new<'a, E>(
dev: &'a Device<Bound>,
data: impl PinInit<T, E> + 'a,
) -> impl PinInit<Self, Error> + 'a
where
T: 'a,
Error: From<E>,
{
try_pin_init!(&this in Self {
dev: dev.into(),
callback: Self::devres_callback,
// INVARIANT: `inner` is properly initialized.
inner <- Opaque::pin_init(try_pin_init!(Inner {
devm <- Completion::new(),
revoke <- Completion::new(),
data <- Revocable::new(data),
})),
// TODO: Replace with "initializer code blocks" [1] once available.
//
// [1] https://github.com/Rust-for-Linux/pin-init/pull/69
_add_action: {
// SAFETY: `this` is a valid pointer to uninitialized memory.
let inner = unsafe { &raw mut (*this.as_ptr()).inner };
// SAFETY:
// - `dev.as_raw()` is a pointer to a valid bound device.
// - `inner` is guaranteed to be a valid for the duration of the lifetime of `Self`.
// - `devm_add_action()` is guaranteed not to call `callback` until `this` has been
// properly initialized, because we require `dev` (i.e. the *bound* device) to
// live at least as long as the returned `impl PinInit<Self, Error>`.
to_result(unsafe {
bindings::devm_add_action(dev.as_raw(), Some(*callback), inner.cast())
}).inspect_err(|_| {
let inner = Opaque::cast_into(inner);
// SAFETY: `inner` is a valid pointer to an `Inner<T>` and valid for both reads
// and writes.
unsafe { core::ptr::drop_in_place(inner) };
})?;
},
})
}
fn inner(&self) -> &Inner<T> {
// SAFETY: By the type invairants of `Self`, `inner` is properly initialized and always
// accessed read-only.
unsafe { &*self.inner.get() }
}
fn data(&self) -> &Revocable<T> {
&self.inner().data
}
#[allow(clippy::missing_safety_doc)]
unsafe extern "C" fn devres_callback(ptr: *mut kernel::ffi::c_void) {
// SAFETY: In `Self::new` we've passed a valid pointer to `Inner` to `devm_add_action()`,
// hence `ptr` must be a valid pointer to `Inner`.
let inner = unsafe { &*ptr.cast::<Inner<T>>() };
// Ensure that `inner` can't be used anymore after we signal completion of this callback.
let inner = ScopeGuard::new_with_data(inner, |inner| inner.devm.complete_all());
if !inner.data.revoke() {
// If `revoke()` returns false, it means that `Devres::drop` already started revoking
// `data` for us. Hence we have to wait until `Devres::drop` signals that it
// completed revoking `data`.
inner.revoke.wait_for_completion();
}
}
fn remove_action(&self) -> bool {
// SAFETY:
// - `self.dev` is a valid `Device`,
// - the `action` and `data` pointers are the exact same ones as given to
// `devm_add_action()` previously,
(unsafe {
bindings::devm_remove_action_nowarn(
self.dev.as_raw(),
Some(self.callback),
core::ptr::from_ref(self.inner()).cast_mut().cast(),
)
} == 0)
}
/// Return a reference of the [`Device`] this [`Devres`] instance has been created with.
pub fn device(&self) -> &Device {
&self.dev
}
/// Obtain `&'a T`, bypassing the [`Revocable`].
///
/// This method allows to directly obtain a `&'a T`, bypassing the [`Revocable`], by presenting
/// a `&'a Device<Bound>` of the same [`Device`] this [`Devres`] instance has been created with.
///
/// # Errors
///
/// An error is returned if `dev` does not match the same [`Device`] this [`Devres`] instance
/// has been created with.
///
/// # Examples
///
/// ```no_run
/// # #![cfg(CONFIG_PCI)]
/// # use kernel::{device::Core, devres::Devres, pci};
///
/// fn from_core(dev: &pci::Device<Core>, devres: Devres<pci::Bar<0x4>>) -> Result {
/// let bar = devres.access(dev.as_ref())?;
///
/// let _ = bar.read32(0x0);
///
/// // might_sleep()
///
/// bar.write32(0x42, 0x0);
///
/// Ok(())
/// }
/// ```
pub fn access<'a>(&'a self, dev: &'a Device<Bound>) -> Result<&'a T> {
if self.dev.as_raw() != dev.as_raw() {
return Err(EINVAL);
}
// SAFETY: `dev` being the same device as the device this `Devres` has been created for
// proves that `self.data` hasn't been revoked and is guaranteed to not be revoked as long
// as `dev` lives; `dev` lives at least as long as `self`.
Ok(unsafe { self.data().access() })
}
/// [`Devres`] accessor for [`Revocable::try_access`].
pub fn try_access(&self) -> Option<RevocableGuard<'_, T>> {
self.data().try_access()
}
/// [`Devres`] accessor for [`Revocable::try_access_with`].
pub fn try_access_with<R, F: FnOnce(&T) -> R>(&self, f: F) -> Option<R> {
self.data().try_access_with(f)
}
/// [`Devres`] accessor for [`Revocable::try_access_with_guard`].
pub fn try_access_with_guard<'a>(&'a self, guard: &'a rcu::Guard) -> Option<&'a T> {
self.data().try_access_with_guard(guard)
}
}
// SAFETY: `Devres` can be send to any task, if `T: Send`.
unsafe impl<T: Send> Send for Devres<T> {}
// SAFETY: `Devres` can be shared with any task, if `T: Sync`.
unsafe impl<T: Send + Sync> Sync for Devres<T> {}
#[pinned_drop]
impl<T: Send> PinnedDrop for Devres<T> {
fn drop(self: Pin<&mut Self>) {
// SAFETY: When `drop` runs, it is guaranteed that nobody is accessing the revocable data
// anymore, hence it is safe not to wait for the grace period to finish.
if unsafe { self.data().revoke_nosync() } {
// We revoked `self.data` before the devres action did, hence try to remove it.
if !self.remove_action() {
// We could not remove the devres action, which means that it now runs concurrently,
// hence signal that `self.data` has been revoked by us successfully.
self.inner().revoke.complete_all();
// Wait for `Self::devres_callback` to be done using this object.
self.inner().devm.wait_for_completion();
}
} else {
// `Self::devres_callback` revokes `self.data` for us, hence wait for it to be done
// using this object.
self.inner().devm.wait_for_completion();
}
// INVARIANT: At this point it is guaranteed that `inner` can't be accessed any more.
//
// SAFETY: `inner` is valid for dropping.
unsafe { core::ptr::drop_in_place(self.inner.get()) };
}
}
/// Consume `data` and [`Drop::drop`] `data` once `dev` is unbound.
fn register_foreign<P>(dev: &Device<Bound>, data: P) -> Result
where
P: ForeignOwnable + Send + 'static,
{
let ptr = data.into_foreign();
#[allow(clippy::missing_safety_doc)]
unsafe extern "C" fn callback<P: ForeignOwnable>(ptr: *mut kernel::ffi::c_void) {
// SAFETY: `ptr` is the pointer to the `ForeignOwnable` leaked above and hence valid.
drop(unsafe { P::from_foreign(ptr.cast()) });
}
// SAFETY:
// - `dev.as_raw()` is a pointer to a valid and bound device.
// - `ptr` is a valid pointer the `ForeignOwnable` devres takes ownership of.
to_result(unsafe {
// `devm_add_action_or_reset()` also calls `callback` on failure, such that the
// `ForeignOwnable` is released eventually.
bindings::devm_add_action_or_reset(dev.as_raw(), Some(callback::<P>), ptr.cast())
})
}
/// Encapsulate `data` in a [`KBox`] and [`Drop::drop`] `data` once `dev` is unbound.
///
/// # Examples
///
/// ```no_run
/// use kernel::{device::{Bound, Device}, devres};
///
/// /// Registration of e.g. a class device, IRQ, etc.
/// struct Registration;
///
/// impl Registration {
/// fn new() -> Self {
/// // register
///
/// Self
/// }
/// }
///
/// impl Drop for Registration {
/// fn drop(&mut self) {
/// // unregister
/// }
/// }
///
/// fn from_bound_context(dev: &Device<Bound>) -> Result {
/// devres::register(dev, Registration::new(), GFP_KERNEL)
/// }
/// ```
pub fn register<T, E>(dev: &Device<Bound>, data: impl PinInit<T, E>, flags: Flags) -> Result
where
T: Send + 'static,
Error: From<E>,
{
let data = KBox::pin_init(data, flags)?;
register_foreign(dev, data)
}