// SPDX-License-Identifier: GPL-2.012//! This module provides a wrapper for the C `struct request` type.3//!4//! C header: [`include/linux/blk-mq.h`](srctree/include/linux/blk-mq.h)56use crate::{7bindings,8block::mq::Operations,9error::Result,10sync::{11aref::{ARef, AlwaysRefCounted},12atomic::Relaxed,13Refcount,14},15types::Opaque,16};17use core::{marker::PhantomData, ptr::NonNull};1819/// A wrapper around a blk-mq [`struct request`]. This represents an IO request.20///21/// # Implementation details22///23/// There are four states for a request that the Rust bindings care about:24///25/// 1. Request is owned by block layer (refcount 0).26/// 2. Request is owned by driver but with zero [`ARef`]s in existence27/// (refcount 1).28/// 3. Request is owned by driver with exactly one [`ARef`] in existence29/// (refcount 2).30/// 4. Request is owned by driver with more than one [`ARef`] in existence31/// (refcount > 2).32///33///34/// We need to track 1 and 2 to ensure we fail tag to request conversions for35/// requests that are not owned by the driver.36///37/// We need to track 3 and 4 to ensure that it is safe to end the request and hand38/// back ownership to the block layer.39///40/// Note that the driver can still obtain new `ARef` even if there is no `ARef`s in existence by41/// using `tag_to_rq`, hence the need to distinguish B and C.42///43/// The states are tracked through the private `refcount` field of44/// `RequestDataWrapper`. This structure lives in the private data area of the C45/// [`struct request`].46///47/// # Invariants48///49/// * `self.0` is a valid [`struct request`] created by the C portion of the50/// kernel.51/// * The private data area associated with this request must be an initialized52/// and valid `RequestDataWrapper<T>`.53/// * `self` is reference counted by atomic modification of54/// `self.wrapper_ref().refcount()`.55///56/// [`struct request`]: srctree/include/linux/blk-mq.h57///58#[repr(transparent)]59pub struct Request<T>(Opaque<bindings::request>, PhantomData<T>);6061impl<T: Operations> Request<T> {62/// Create an [`ARef<Request>`] from a [`struct request`] pointer.63///64/// # Safety65///66/// * The caller must own a refcount on `ptr` that is transferred to the67/// returned [`ARef`].68/// * The type invariants for [`Request`] must hold for the pointee of `ptr`.69///70/// [`struct request`]: srctree/include/linux/blk-mq.h71pub(crate) unsafe fn aref_from_raw(ptr: *mut bindings::request) -> ARef<Self> {72// INVARIANT: By the safety requirements of this function, invariants are upheld.73// SAFETY: By the safety requirement of this function, we own a74// reference count that we can pass to `ARef`.75unsafe { ARef::from_raw(NonNull::new_unchecked(ptr.cast())) }76}7778/// Notify the block layer that a request is going to be processed now.79///80/// The block layer uses this hook to do proper initializations such as81/// starting the timeout timer. It is a requirement that block device82/// drivers call this function when starting to process a request.83///84/// # Safety85///86/// The caller must have exclusive ownership of `self`, that is87/// `self.wrapper_ref().refcount() == 2`.88pub(crate) unsafe fn start_unchecked(this: &ARef<Self>) {89// SAFETY: By type invariant, `self.0` is a valid `struct request` and90// we have exclusive access.91unsafe { bindings::blk_mq_start_request(this.0.get()) };92}9394/// Try to take exclusive ownership of `this` by dropping the refcount to 0.95/// This fails if `this` is not the only [`ARef`] pointing to the underlying96/// [`Request`].97///98/// If the operation is successful, [`Ok`] is returned with a pointer to the99/// C [`struct request`]. If the operation fails, `this` is returned in the100/// [`Err`] variant.101///102/// [`struct request`]: srctree/include/linux/blk-mq.h103fn try_set_end(this: ARef<Self>) -> Result<*mut bindings::request, ARef<Self>> {104// To hand back the ownership, we need the current refcount to be 2.105// Since we can race with `TagSet::tag_to_rq`, this needs to atomically reduce106// refcount to 0. `Refcount` does not provide a way to do this, so use the underlying107// atomics directly.108if let Err(_old) = this109.wrapper_ref()110.refcount()111.as_atomic()112.cmpxchg(2, 0, Relaxed)113{114return Err(this);115}116117let request_ptr = this.0.get();118core::mem::forget(this);119120Ok(request_ptr)121}122123/// Notify the block layer that the request has been completed without errors.124///125/// This function will return [`Err`] if `this` is not the only [`ARef`]126/// referencing the request.127pub fn end_ok(this: ARef<Self>) -> Result<(), ARef<Self>> {128let request_ptr = Self::try_set_end(this)?;129130// SAFETY: By type invariant, `this.0` was a valid `struct request`. The131// success of the call to `try_set_end` guarantees that there are no132// `ARef`s pointing to this request. Therefore it is safe to hand it133// back to the block layer.134unsafe {135bindings::blk_mq_end_request(136request_ptr,137bindings::BLK_STS_OK as bindings::blk_status_t,138)139};140141Ok(())142}143144/// Complete the request by scheduling `Operations::complete` for145/// execution.146///147/// The function may be scheduled locally, via SoftIRQ or remotely via IPMI.148/// See `blk_mq_complete_request_remote` in [`blk-mq.c`] for details.149///150/// [`blk-mq.c`]: srctree/block/blk-mq.c151pub fn complete(this: ARef<Self>) {152let ptr = ARef::into_raw(this).cast::<bindings::request>().as_ptr();153// SAFETY: By type invariant, `self.0` is a valid `struct request`154if !unsafe { bindings::blk_mq_complete_request_remote(ptr) } {155// SAFETY: We released a refcount above that we can reclaim here.156let this = unsafe { Request::aref_from_raw(ptr) };157T::complete(this);158}159}160161/// Return a pointer to the [`RequestDataWrapper`] stored in the private area162/// of the request structure.163///164/// # Safety165///166/// - `this` must point to a valid allocation of size at least size of167/// [`Self`] plus size of [`RequestDataWrapper`].168pub(crate) unsafe fn wrapper_ptr(this: *mut Self) -> NonNull<RequestDataWrapper> {169let request_ptr = this.cast::<bindings::request>();170// SAFETY: By safety requirements for this function, `this` is a171// valid allocation.172let wrapper_ptr =173unsafe { bindings::blk_mq_rq_to_pdu(request_ptr).cast::<RequestDataWrapper>() };174// SAFETY: By C API contract, `wrapper_ptr` points to a valid allocation175// and is not null.176unsafe { NonNull::new_unchecked(wrapper_ptr) }177}178179/// Return a reference to the [`RequestDataWrapper`] stored in the private180/// area of the request structure.181pub(crate) fn wrapper_ref(&self) -> &RequestDataWrapper {182// SAFETY: By type invariant, `self.0` is a valid allocation. Further,183// the private data associated with this request is initialized and184// valid. The existence of `&self` guarantees that the private data is185// valid as a shared reference.186unsafe { Self::wrapper_ptr(core::ptr::from_ref(self).cast_mut()).as_ref() }187}188}189190/// A wrapper around data stored in the private area of the C [`struct request`].191///192/// [`struct request`]: srctree/include/linux/blk-mq.h193pub(crate) struct RequestDataWrapper {194/// The Rust request refcount has the following states:195///196/// - 0: The request is owned by C block layer.197/// - 1: The request is owned by Rust abstractions but there are no [`ARef`] references to it.198/// - 2+: There are [`ARef`] references to the request.199refcount: Refcount,200}201202impl RequestDataWrapper {203/// Return a reference to the refcount of the request that is embedding204/// `self`.205pub(crate) fn refcount(&self) -> &Refcount {206&self.refcount207}208209/// Return a pointer to the refcount of the request that is embedding the210/// pointee of `this`.211///212/// # Safety213///214/// - `this` must point to a live allocation of at least the size of `Self`.215pub(crate) unsafe fn refcount_ptr(this: *mut Self) -> *mut Refcount {216// SAFETY: Because of the safety requirements of this function, the217// field projection is safe.218unsafe { &raw mut (*this).refcount }219}220}221222// SAFETY: Exclusive access is thread-safe for `Request`. `Request` has no `&mut223// self` methods and `&self` methods that mutate `self` are internally224// synchronized.225unsafe impl<T: Operations> Send for Request<T> {}226227// SAFETY: Shared access is thread-safe for `Request`. `&self` methods that228// mutate `self` are internally synchronized`229unsafe impl<T: Operations> Sync for Request<T> {}230231// SAFETY: All instances of `Request<T>` are reference counted. This232// implementation of `AlwaysRefCounted` ensure that increments to the ref count233// keeps the object alive in memory at least until a matching reference count234// decrement is executed.235unsafe impl<T: Operations> AlwaysRefCounted for Request<T> {236fn inc_ref(&self) {237self.wrapper_ref().refcount().inc();238}239240unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {241// SAFETY: The type invariants of `ARef` guarantee that `obj` is valid242// for read.243let wrapper_ptr = unsafe { Self::wrapper_ptr(obj.as_ptr()).as_ptr() };244// SAFETY: The type invariant of `Request` guarantees that the private245// data area is initialized and valid.246let refcount = unsafe { &*RequestDataWrapper::refcount_ptr(wrapper_ptr) };247248#[cfg_attr(not(CONFIG_DEBUG_MISC), allow(unused_variables))]249let is_zero = refcount.dec_and_test();250251#[cfg(CONFIG_DEBUG_MISC)]252if is_zero {253panic!("Request reached refcount zero in Rust abstractions");254}255}256}257258259