// 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::{atomic::Relaxed, Refcount},11types::{ARef, AlwaysRefCounted, Opaque},12};13use core::{marker::PhantomData, ptr::NonNull};1415/// A wrapper around a blk-mq [`struct request`]. This represents an IO request.16///17/// # Implementation details18///19/// There are four states for a request that the Rust bindings care about:20///21/// 1. Request is owned by block layer (refcount 0).22/// 2. Request is owned by driver but with zero [`ARef`]s in existence23/// (refcount 1).24/// 3. Request is owned by driver with exactly one [`ARef`] in existence25/// (refcount 2).26/// 4. Request is owned by driver with more than one [`ARef`] in existence27/// (refcount > 2).28///29///30/// We need to track 1 and 2 to ensure we fail tag to request conversions for31/// requests that are not owned by the driver.32///33/// We need to track 3 and 4 to ensure that it is safe to end the request and hand34/// back ownership to the block layer.35///36/// Note that the driver can still obtain new `ARef` even if there is no `ARef`s in existence by37/// using `tag_to_rq`, hence the need to distinguish B and C.38///39/// The states are tracked through the private `refcount` field of40/// `RequestDataWrapper`. This structure lives in the private data area of the C41/// [`struct request`].42///43/// # Invariants44///45/// * `self.0` is a valid [`struct request`] created by the C portion of the46/// kernel.47/// * The private data area associated with this request must be an initialized48/// and valid `RequestDataWrapper<T>`.49/// * `self` is reference counted by atomic modification of50/// `self.wrapper_ref().refcount()`.51///52/// [`struct request`]: srctree/include/linux/blk-mq.h53///54#[repr(transparent)]55pub struct Request<T>(Opaque<bindings::request>, PhantomData<T>);5657impl<T: Operations> Request<T> {58/// Create an [`ARef<Request>`] from a [`struct request`] pointer.59///60/// # Safety61///62/// * The caller must own a refcount on `ptr` that is transferred to the63/// returned [`ARef`].64/// * The type invariants for [`Request`] must hold for the pointee of `ptr`.65///66/// [`struct request`]: srctree/include/linux/blk-mq.h67pub(crate) unsafe fn aref_from_raw(ptr: *mut bindings::request) -> ARef<Self> {68// INVARIANT: By the safety requirements of this function, invariants are upheld.69// SAFETY: By the safety requirement of this function, we own a70// reference count that we can pass to `ARef`.71unsafe { ARef::from_raw(NonNull::new_unchecked(ptr.cast())) }72}7374/// Notify the block layer that a request is going to be processed now.75///76/// The block layer uses this hook to do proper initializations such as77/// starting the timeout timer. It is a requirement that block device78/// drivers call this function when starting to process a request.79///80/// # Safety81///82/// The caller must have exclusive ownership of `self`, that is83/// `self.wrapper_ref().refcount() == 2`.84pub(crate) unsafe fn start_unchecked(this: &ARef<Self>) {85// SAFETY: By type invariant, `self.0` is a valid `struct request` and86// we have exclusive access.87unsafe { bindings::blk_mq_start_request(this.0.get()) };88}8990/// Try to take exclusive ownership of `this` by dropping the refcount to 0.91/// This fails if `this` is not the only [`ARef`] pointing to the underlying92/// [`Request`].93///94/// If the operation is successful, [`Ok`] is returned with a pointer to the95/// C [`struct request`]. If the operation fails, `this` is returned in the96/// [`Err`] variant.97///98/// [`struct request`]: srctree/include/linux/blk-mq.h99fn try_set_end(this: ARef<Self>) -> Result<*mut bindings::request, ARef<Self>> {100// To hand back the ownership, we need the current refcount to be 2.101// Since we can race with `TagSet::tag_to_rq`, this needs to atomically reduce102// refcount to 0. `Refcount` does not provide a way to do this, so use the underlying103// atomics directly.104if let Err(_old) = this105.wrapper_ref()106.refcount()107.as_atomic()108.cmpxchg(2, 0, Relaxed)109{110return Err(this);111}112113let request_ptr = this.0.get();114core::mem::forget(this);115116Ok(request_ptr)117}118119/// Notify the block layer that the request has been completed without errors.120///121/// This function will return [`Err`] if `this` is not the only [`ARef`]122/// referencing the request.123pub fn end_ok(this: ARef<Self>) -> Result<(), ARef<Self>> {124let request_ptr = Self::try_set_end(this)?;125126// SAFETY: By type invariant, `this.0` was a valid `struct request`. The127// success of the call to `try_set_end` guarantees that there are no128// `ARef`s pointing to this request. Therefore it is safe to hand it129// back to the block layer.130unsafe {131bindings::blk_mq_end_request(132request_ptr,133bindings::BLK_STS_OK as bindings::blk_status_t,134)135};136137Ok(())138}139140/// Complete the request by scheduling `Operations::complete` for141/// execution.142///143/// The function may be scheduled locally, via SoftIRQ or remotely via IPMI.144/// See `blk_mq_complete_request_remote` in [`blk-mq.c`] for details.145///146/// [`blk-mq.c`]: srctree/block/blk-mq.c147pub fn complete(this: ARef<Self>) {148let ptr = ARef::into_raw(this).cast::<bindings::request>().as_ptr();149// SAFETY: By type invariant, `self.0` is a valid `struct request`150if !unsafe { bindings::blk_mq_complete_request_remote(ptr) } {151// SAFETY: We released a refcount above that we can reclaim here.152let this = unsafe { Request::aref_from_raw(ptr) };153T::complete(this);154}155}156157/// Return a pointer to the [`RequestDataWrapper`] stored in the private area158/// of the request structure.159///160/// # Safety161///162/// - `this` must point to a valid allocation of size at least size of163/// [`Self`] plus size of [`RequestDataWrapper`].164pub(crate) unsafe fn wrapper_ptr(this: *mut Self) -> NonNull<RequestDataWrapper> {165let request_ptr = this.cast::<bindings::request>();166// SAFETY: By safety requirements for this function, `this` is a167// valid allocation.168let wrapper_ptr =169unsafe { bindings::blk_mq_rq_to_pdu(request_ptr).cast::<RequestDataWrapper>() };170// SAFETY: By C API contract, `wrapper_ptr` points to a valid allocation171// and is not null.172unsafe { NonNull::new_unchecked(wrapper_ptr) }173}174175/// Return a reference to the [`RequestDataWrapper`] stored in the private176/// area of the request structure.177pub(crate) fn wrapper_ref(&self) -> &RequestDataWrapper {178// SAFETY: By type invariant, `self.0` is a valid allocation. Further,179// the private data associated with this request is initialized and180// valid. The existence of `&self` guarantees that the private data is181// valid as a shared reference.182unsafe { Self::wrapper_ptr(core::ptr::from_ref(self).cast_mut()).as_ref() }183}184}185186/// A wrapper around data stored in the private area of the C [`struct request`].187///188/// [`struct request`]: srctree/include/linux/blk-mq.h189pub(crate) struct RequestDataWrapper {190/// The Rust request refcount has the following states:191///192/// - 0: The request is owned by C block layer.193/// - 1: The request is owned by Rust abstractions but there are no [`ARef`] references to it.194/// - 2+: There are [`ARef`] references to the request.195refcount: Refcount,196}197198impl RequestDataWrapper {199/// Return a reference to the refcount of the request that is embedding200/// `self`.201pub(crate) fn refcount(&self) -> &Refcount {202&self.refcount203}204205/// Return a pointer to the refcount of the request that is embedding the206/// pointee of `this`.207///208/// # Safety209///210/// - `this` must point to a live allocation of at least the size of `Self`.211pub(crate) unsafe fn refcount_ptr(this: *mut Self) -> *mut Refcount {212// SAFETY: Because of the safety requirements of this function, the213// field projection is safe.214unsafe { &raw mut (*this).refcount }215}216}217218// SAFETY: Exclusive access is thread-safe for `Request`. `Request` has no `&mut219// self` methods and `&self` methods that mutate `self` are internally220// synchronized.221unsafe impl<T: Operations> Send for Request<T> {}222223// SAFETY: Shared access is thread-safe for `Request`. `&self` methods that224// mutate `self` are internally synchronized`225unsafe impl<T: Operations> Sync for Request<T> {}226227// SAFETY: All instances of `Request<T>` are reference counted. This228// implementation of `AlwaysRefCounted` ensure that increments to the ref count229// keeps the object alive in memory at least until a matching reference count230// decrement is executed.231unsafe impl<T: Operations> AlwaysRefCounted for Request<T> {232fn inc_ref(&self) {233self.wrapper_ref().refcount().inc();234}235236unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {237// SAFETY: The type invariants of `ARef` guarantee that `obj` is valid238// for read.239let wrapper_ptr = unsafe { Self::wrapper_ptr(obj.as_ptr()).as_ptr() };240// SAFETY: The type invariant of `Request` guarantees that the private241// data area is initialized and valid.242let refcount = unsafe { &*RequestDataWrapper::refcount_ptr(wrapper_ptr) };243244#[cfg_attr(not(CONFIG_DEBUG_MISC), allow(unused_variables))]245let is_zero = refcount.dec_and_test();246247#[cfg(CONFIG_DEBUG_MISC)]248if is_zero {249panic!("Request reached refcount zero in Rust abstractions");250}251}252}253254255