13253aba3SAndreas Hindborg // SPDX-License-Identifier: GPL-2.0
23253aba3SAndreas Hindborg
33253aba3SAndreas Hindborg //! This module provides a wrapper for the C `struct request` type.
43253aba3SAndreas Hindborg //!
53253aba3SAndreas Hindborg //! C header: [`include/linux/blk-mq.h`](srctree/include/linux/blk-mq.h)
63253aba3SAndreas Hindborg
73253aba3SAndreas Hindborg use crate::{
83253aba3SAndreas Hindborg bindings,
93253aba3SAndreas Hindborg block::mq::Operations,
103253aba3SAndreas Hindborg error::Result,
113253aba3SAndreas Hindborg types::{ARef, AlwaysRefCounted, Opaque},
123253aba3SAndreas Hindborg };
133253aba3SAndreas Hindborg use core::{
143253aba3SAndreas Hindborg marker::PhantomData,
15*2a571248SAntonio Hickey ptr::NonNull,
163253aba3SAndreas Hindborg sync::atomic::{AtomicU64, Ordering},
173253aba3SAndreas Hindborg };
183253aba3SAndreas Hindborg
1928e84838SFrancesco Zardi /// A wrapper around a blk-mq [`struct request`]. This represents an IO request.
203253aba3SAndreas Hindborg ///
213253aba3SAndreas Hindborg /// # Implementation details
223253aba3SAndreas Hindborg ///
233253aba3SAndreas Hindborg /// There are four states for a request that the Rust bindings care about:
243253aba3SAndreas Hindborg ///
2528e84838SFrancesco Zardi /// 1. Request is owned by block layer (refcount 0).
2628e84838SFrancesco Zardi /// 2. Request is owned by driver but with zero [`ARef`]s in existence
2728e84838SFrancesco Zardi /// (refcount 1).
2828e84838SFrancesco Zardi /// 3. Request is owned by driver with exactly one [`ARef`] in existence
2928e84838SFrancesco Zardi /// (refcount 2).
3028e84838SFrancesco Zardi /// 4. Request is owned by driver with more than one [`ARef`] in existence
3128e84838SFrancesco Zardi /// (refcount > 2).
323253aba3SAndreas Hindborg ///
333253aba3SAndreas Hindborg ///
3428e84838SFrancesco Zardi /// We need to track 1 and 2 to ensure we fail tag to request conversions for
353253aba3SAndreas Hindborg /// requests that are not owned by the driver.
363253aba3SAndreas Hindborg ///
3728e84838SFrancesco Zardi /// We need to track 3 and 4 to ensure that it is safe to end the request and hand
383253aba3SAndreas Hindborg /// back ownership to the block layer.
393253aba3SAndreas Hindborg ///
403253aba3SAndreas Hindborg /// The states are tracked through the private `refcount` field of
413253aba3SAndreas Hindborg /// `RequestDataWrapper`. This structure lives in the private data area of the C
4228e84838SFrancesco Zardi /// [`struct request`].
433253aba3SAndreas Hindborg ///
443253aba3SAndreas Hindborg /// # Invariants
453253aba3SAndreas Hindborg ///
4628e84838SFrancesco Zardi /// * `self.0` is a valid [`struct request`] created by the C portion of the
4728e84838SFrancesco Zardi /// kernel.
483253aba3SAndreas Hindborg /// * The private data area associated with this request must be an initialized
493253aba3SAndreas Hindborg /// and valid `RequestDataWrapper<T>`.
503253aba3SAndreas Hindborg /// * `self` is reference counted by atomic modification of
5128e84838SFrancesco Zardi /// `self.wrapper_ref().refcount()`.
5228e84838SFrancesco Zardi ///
5328e84838SFrancesco Zardi /// [`struct request`]: srctree/include/linux/blk-mq.h
543253aba3SAndreas Hindborg ///
553253aba3SAndreas Hindborg #[repr(transparent)]
563253aba3SAndreas Hindborg pub struct Request<T: Operations>(Opaque<bindings::request>, PhantomData<T>);
573253aba3SAndreas Hindborg
583253aba3SAndreas Hindborg impl<T: Operations> Request<T> {
5928e84838SFrancesco Zardi /// Create an [`ARef<Request>`] from a [`struct request`] pointer.
603253aba3SAndreas Hindborg ///
613253aba3SAndreas Hindborg /// # Safety
623253aba3SAndreas Hindborg ///
633253aba3SAndreas Hindborg /// * The caller must own a refcount on `ptr` that is transferred to the
6428e84838SFrancesco Zardi /// returned [`ARef`].
6528e84838SFrancesco Zardi /// * The type invariants for [`Request`] must hold for the pointee of `ptr`.
6628e84838SFrancesco Zardi ///
6728e84838SFrancesco Zardi /// [`struct request`]: srctree/include/linux/blk-mq.h
aref_from_raw(ptr: *mut bindings::request) -> ARef<Self>683253aba3SAndreas Hindborg pub(crate) unsafe fn aref_from_raw(ptr: *mut bindings::request) -> ARef<Self> {
693253aba3SAndreas Hindborg // INVARIANT: By the safety requirements of this function, invariants are upheld.
703253aba3SAndreas Hindborg // SAFETY: By the safety requirement of this function, we own a
713253aba3SAndreas Hindborg // reference count that we can pass to `ARef`.
723253aba3SAndreas Hindborg unsafe { ARef::from_raw(NonNull::new_unchecked(ptr as *const Self as *mut Self)) }
733253aba3SAndreas Hindborg }
743253aba3SAndreas Hindborg
753253aba3SAndreas Hindborg /// Notify the block layer that a request is going to be processed now.
763253aba3SAndreas Hindborg ///
773253aba3SAndreas Hindborg /// The block layer uses this hook to do proper initializations such as
783253aba3SAndreas Hindborg /// starting the timeout timer. It is a requirement that block device
793253aba3SAndreas Hindborg /// drivers call this function when starting to process a request.
803253aba3SAndreas Hindborg ///
813253aba3SAndreas Hindborg /// # Safety
823253aba3SAndreas Hindborg ///
833253aba3SAndreas Hindborg /// The caller must have exclusive ownership of `self`, that is
843253aba3SAndreas Hindborg /// `self.wrapper_ref().refcount() == 2`.
start_unchecked(this: &ARef<Self>)853253aba3SAndreas Hindborg pub(crate) unsafe fn start_unchecked(this: &ARef<Self>) {
863253aba3SAndreas Hindborg // SAFETY: By type invariant, `self.0` is a valid `struct request` and
873253aba3SAndreas Hindborg // we have exclusive access.
883253aba3SAndreas Hindborg unsafe { bindings::blk_mq_start_request(this.0.get()) };
893253aba3SAndreas Hindborg }
903253aba3SAndreas Hindborg
913253aba3SAndreas Hindborg /// Try to take exclusive ownership of `this` by dropping the refcount to 0.
9228e84838SFrancesco Zardi /// This fails if `this` is not the only [`ARef`] pointing to the underlying
9328e84838SFrancesco Zardi /// [`Request`].
943253aba3SAndreas Hindborg ///
9528e84838SFrancesco Zardi /// If the operation is successful, [`Ok`] is returned with a pointer to the
9628e84838SFrancesco Zardi /// C [`struct request`]. If the operation fails, `this` is returned in the
9728e84838SFrancesco Zardi /// [`Err`] variant.
9828e84838SFrancesco Zardi ///
9928e84838SFrancesco Zardi /// [`struct request`]: srctree/include/linux/blk-mq.h
try_set_end(this: ARef<Self>) -> Result<*mut bindings::request, ARef<Self>>1003253aba3SAndreas Hindborg fn try_set_end(this: ARef<Self>) -> Result<*mut bindings::request, ARef<Self>> {
1013253aba3SAndreas Hindborg // We can race with `TagSet::tag_to_rq`
1023253aba3SAndreas Hindborg if let Err(_old) = this.wrapper_ref().refcount().compare_exchange(
1033253aba3SAndreas Hindborg 2,
1043253aba3SAndreas Hindborg 0,
1053253aba3SAndreas Hindborg Ordering::Relaxed,
1063253aba3SAndreas Hindborg Ordering::Relaxed,
1073253aba3SAndreas Hindborg ) {
1083253aba3SAndreas Hindborg return Err(this);
1093253aba3SAndreas Hindborg }
1103253aba3SAndreas Hindborg
1113253aba3SAndreas Hindborg let request_ptr = this.0.get();
1123253aba3SAndreas Hindborg core::mem::forget(this);
1133253aba3SAndreas Hindborg
1143253aba3SAndreas Hindborg Ok(request_ptr)
1153253aba3SAndreas Hindborg }
1163253aba3SAndreas Hindborg
1173253aba3SAndreas Hindborg /// Notify the block layer that the request has been completed without errors.
1183253aba3SAndreas Hindborg ///
11928e84838SFrancesco Zardi /// This function will return [`Err`] if `this` is not the only [`ARef`]
1203253aba3SAndreas Hindborg /// referencing the request.
end_ok(this: ARef<Self>) -> Result<(), ARef<Self>>1213253aba3SAndreas Hindborg pub fn end_ok(this: ARef<Self>) -> Result<(), ARef<Self>> {
1223253aba3SAndreas Hindborg let request_ptr = Self::try_set_end(this)?;
1233253aba3SAndreas Hindborg
1243253aba3SAndreas Hindborg // SAFETY: By type invariant, `this.0` was a valid `struct request`. The
1253253aba3SAndreas Hindborg // success of the call to `try_set_end` guarantees that there are no
1263253aba3SAndreas Hindborg // `ARef`s pointing to this request. Therefore it is safe to hand it
1273253aba3SAndreas Hindborg // back to the block layer.
1283253aba3SAndreas Hindborg unsafe { bindings::blk_mq_end_request(request_ptr, bindings::BLK_STS_OK as _) };
1293253aba3SAndreas Hindborg
1303253aba3SAndreas Hindborg Ok(())
1313253aba3SAndreas Hindborg }
1323253aba3SAndreas Hindborg
13328e84838SFrancesco Zardi /// Return a pointer to the [`RequestDataWrapper`] stored in the private area
1343253aba3SAndreas Hindborg /// of the request structure.
1353253aba3SAndreas Hindborg ///
1363253aba3SAndreas Hindborg /// # Safety
1373253aba3SAndreas Hindborg ///
1383253aba3SAndreas Hindborg /// - `this` must point to a valid allocation of size at least size of
13928e84838SFrancesco Zardi /// [`Self`] plus size of [`RequestDataWrapper`].
wrapper_ptr(this: *mut Self) -> NonNull<RequestDataWrapper>1403253aba3SAndreas Hindborg pub(crate) unsafe fn wrapper_ptr(this: *mut Self) -> NonNull<RequestDataWrapper> {
1413253aba3SAndreas Hindborg let request_ptr = this.cast::<bindings::request>();
1423253aba3SAndreas Hindborg // SAFETY: By safety requirements for this function, `this` is a
1433253aba3SAndreas Hindborg // valid allocation.
1443253aba3SAndreas Hindborg let wrapper_ptr =
1453253aba3SAndreas Hindborg unsafe { bindings::blk_mq_rq_to_pdu(request_ptr).cast::<RequestDataWrapper>() };
1463253aba3SAndreas Hindborg // SAFETY: By C API contract, wrapper_ptr points to a valid allocation
1473253aba3SAndreas Hindborg // and is not null.
1483253aba3SAndreas Hindborg unsafe { NonNull::new_unchecked(wrapper_ptr) }
1493253aba3SAndreas Hindborg }
1503253aba3SAndreas Hindborg
15128e84838SFrancesco Zardi /// Return a reference to the [`RequestDataWrapper`] stored in the private
1523253aba3SAndreas Hindborg /// area of the request structure.
wrapper_ref(&self) -> &RequestDataWrapper1533253aba3SAndreas Hindborg pub(crate) fn wrapper_ref(&self) -> &RequestDataWrapper {
1543253aba3SAndreas Hindborg // SAFETY: By type invariant, `self.0` is a valid allocation. Further,
1553253aba3SAndreas Hindborg // the private data associated with this request is initialized and
1563253aba3SAndreas Hindborg // valid. The existence of `&self` guarantees that the private data is
1573253aba3SAndreas Hindborg // valid as a shared reference.
1583253aba3SAndreas Hindborg unsafe { Self::wrapper_ptr(self as *const Self as *mut Self).as_ref() }
1593253aba3SAndreas Hindborg }
1603253aba3SAndreas Hindborg }
1613253aba3SAndreas Hindborg
16228e84838SFrancesco Zardi /// A wrapper around data stored in the private area of the C [`struct request`].
16328e84838SFrancesco Zardi ///
16428e84838SFrancesco Zardi /// [`struct request`]: srctree/include/linux/blk-mq.h
1653253aba3SAndreas Hindborg pub(crate) struct RequestDataWrapper {
1663253aba3SAndreas Hindborg /// The Rust request refcount has the following states:
1673253aba3SAndreas Hindborg ///
1683253aba3SAndreas Hindborg /// - 0: The request is owned by C block layer.
16928e84838SFrancesco Zardi /// - 1: The request is owned by Rust abstractions but there are no [`ARef`] references to it.
17028e84838SFrancesco Zardi /// - 2+: There are [`ARef`] references to the request.
1713253aba3SAndreas Hindborg refcount: AtomicU64,
1723253aba3SAndreas Hindborg }
1733253aba3SAndreas Hindborg
1743253aba3SAndreas Hindborg impl RequestDataWrapper {
1753253aba3SAndreas Hindborg /// Return a reference to the refcount of the request that is embedding
1763253aba3SAndreas Hindborg /// `self`.
refcount(&self) -> &AtomicU641773253aba3SAndreas Hindborg pub(crate) fn refcount(&self) -> &AtomicU64 {
1783253aba3SAndreas Hindborg &self.refcount
1793253aba3SAndreas Hindborg }
1803253aba3SAndreas Hindborg
1813253aba3SAndreas Hindborg /// Return a pointer to the refcount of the request that is embedding the
1823253aba3SAndreas Hindborg /// pointee of `this`.
1833253aba3SAndreas Hindborg ///
1843253aba3SAndreas Hindborg /// # Safety
1853253aba3SAndreas Hindborg ///
1863253aba3SAndreas Hindborg /// - `this` must point to a live allocation of at least the size of `Self`.
refcount_ptr(this: *mut Self) -> *mut AtomicU641873253aba3SAndreas Hindborg pub(crate) unsafe fn refcount_ptr(this: *mut Self) -> *mut AtomicU64 {
1883253aba3SAndreas Hindborg // SAFETY: Because of the safety requirements of this function, the
1893253aba3SAndreas Hindborg // field projection is safe.
190*2a571248SAntonio Hickey unsafe { &raw mut (*this).refcount }
1913253aba3SAndreas Hindborg }
1923253aba3SAndreas Hindborg }
1933253aba3SAndreas Hindborg
1943253aba3SAndreas Hindborg // SAFETY: Exclusive access is thread-safe for `Request`. `Request` has no `&mut
1953253aba3SAndreas Hindborg // self` methods and `&self` methods that mutate `self` are internally
1963253aba3SAndreas Hindborg // synchronized.
1973253aba3SAndreas Hindborg unsafe impl<T: Operations> Send for Request<T> {}
1983253aba3SAndreas Hindborg
1993253aba3SAndreas Hindborg // SAFETY: Shared access is thread-safe for `Request`. `&self` methods that
2003253aba3SAndreas Hindborg // mutate `self` are internally synchronized`
2013253aba3SAndreas Hindborg unsafe impl<T: Operations> Sync for Request<T> {}
2023253aba3SAndreas Hindborg
2033253aba3SAndreas Hindborg /// Store the result of `op(target.load())` in target, returning new value of
2043253aba3SAndreas Hindborg /// target.
atomic_relaxed_op_return(target: &AtomicU64, op: impl Fn(u64) -> u64) -> u642053253aba3SAndreas Hindborg fn atomic_relaxed_op_return(target: &AtomicU64, op: impl Fn(u64) -> u64) -> u64 {
2063253aba3SAndreas Hindborg let old = target.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |x| Some(op(x)));
2073253aba3SAndreas Hindborg
2083253aba3SAndreas Hindborg // SAFETY: Because the operation passed to `fetch_update` above always
2093253aba3SAndreas Hindborg // return `Some`, `old` will always be `Ok`.
2103253aba3SAndreas Hindborg let old = unsafe { old.unwrap_unchecked() };
2113253aba3SAndreas Hindborg
2123253aba3SAndreas Hindborg op(old)
2133253aba3SAndreas Hindborg }
2143253aba3SAndreas Hindborg
2153253aba3SAndreas Hindborg /// Store the result of `op(target.load)` in `target` if `target.load() !=
21628e84838SFrancesco Zardi /// pred`, returning [`true`] if the target was updated.
atomic_relaxed_op_unless(target: &AtomicU64, op: impl Fn(u64) -> u64, pred: u64) -> bool2173253aba3SAndreas Hindborg fn atomic_relaxed_op_unless(target: &AtomicU64, op: impl Fn(u64) -> u64, pred: u64) -> bool {
2183253aba3SAndreas Hindborg target
2193253aba3SAndreas Hindborg .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |x| {
2203253aba3SAndreas Hindborg if x == pred {
2213253aba3SAndreas Hindborg None
2223253aba3SAndreas Hindborg } else {
2233253aba3SAndreas Hindborg Some(op(x))
2243253aba3SAndreas Hindborg }
2253253aba3SAndreas Hindborg })
2263253aba3SAndreas Hindborg .is_ok()
2273253aba3SAndreas Hindborg }
2283253aba3SAndreas Hindborg
2293253aba3SAndreas Hindborg // SAFETY: All instances of `Request<T>` are reference counted. This
2303253aba3SAndreas Hindborg // implementation of `AlwaysRefCounted` ensure that increments to the ref count
2313253aba3SAndreas Hindborg // keeps the object alive in memory at least until a matching reference count
2323253aba3SAndreas Hindborg // decrement is executed.
2333253aba3SAndreas Hindborg unsafe impl<T: Operations> AlwaysRefCounted for Request<T> {
inc_ref(&self)2343253aba3SAndreas Hindborg fn inc_ref(&self) {
2353253aba3SAndreas Hindborg let refcount = &self.wrapper_ref().refcount();
2363253aba3SAndreas Hindborg
2373253aba3SAndreas Hindborg #[cfg_attr(not(CONFIG_DEBUG_MISC), allow(unused_variables))]
2383253aba3SAndreas Hindborg let updated = atomic_relaxed_op_unless(refcount, |x| x + 1, 0);
2393253aba3SAndreas Hindborg
2403253aba3SAndreas Hindborg #[cfg(CONFIG_DEBUG_MISC)]
2413253aba3SAndreas Hindborg if !updated {
2423253aba3SAndreas Hindborg panic!("Request refcount zero on clone")
2433253aba3SAndreas Hindborg }
2443253aba3SAndreas Hindborg }
2453253aba3SAndreas Hindborg
dec_ref(obj: core::ptr::NonNull<Self>)2463253aba3SAndreas Hindborg unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
2473253aba3SAndreas Hindborg // SAFETY: The type invariants of `ARef` guarantee that `obj` is valid
2483253aba3SAndreas Hindborg // for read.
2493253aba3SAndreas Hindborg let wrapper_ptr = unsafe { Self::wrapper_ptr(obj.as_ptr()).as_ptr() };
2503253aba3SAndreas Hindborg // SAFETY: The type invariant of `Request` guarantees that the private
2513253aba3SAndreas Hindborg // data area is initialized and valid.
2523253aba3SAndreas Hindborg let refcount = unsafe { &*RequestDataWrapper::refcount_ptr(wrapper_ptr) };
2533253aba3SAndreas Hindborg
2543253aba3SAndreas Hindborg #[cfg_attr(not(CONFIG_DEBUG_MISC), allow(unused_variables))]
2553253aba3SAndreas Hindborg let new_refcount = atomic_relaxed_op_return(refcount, |x| x - 1);
2563253aba3SAndreas Hindborg
2573253aba3SAndreas Hindborg #[cfg(CONFIG_DEBUG_MISC)]
2583253aba3SAndreas Hindborg if new_refcount == 0 {
2593253aba3SAndreas Hindborg panic!("Request reached refcount zero in Rust abstractions");
2603253aba3SAndreas Hindborg }
2613253aba3SAndreas Hindborg }
2623253aba3SAndreas Hindborg }
263