Skip to main content

kernel/block/mq/
request.rs

1// SPDX-License-Identifier: GPL-2.0
2
3//! This module provides a wrapper for the C `struct request` type.
4//!
5//! C header: [`include/linux/blk-mq.h`](srctree/include/linux/blk-mq.h)
6
7use crate::{
8    bindings,
9    block::mq::Operations,
10    prelude::*,
11    sync::{
12        aref::{
13            ARef,
14            AlwaysRefCounted, //
15        },
16        atomic::Relaxed,
17        Refcount, //
18    },
19    types::Opaque, //
20};
21use core::{
22    marker::PhantomData,
23    ptr::NonNull, //
24};
25
26/// A wrapper around a blk-mq [`struct request`]. This represents an IO request.
27///
28/// # Implementation details
29///
30/// There are four states for a request that the Rust bindings care about:
31///
32/// 1. Request is owned by block layer (refcount 0).
33/// 2. Request is owned by driver but with zero [`ARef`]s in existence
34///    (refcount 1).
35/// 3. Request is owned by driver with exactly one [`ARef`] in existence
36///    (refcount 2).
37/// 4. Request is owned by driver with more than one [`ARef`] in existence
38///    (refcount > 2).
39///
40///
41/// We need to track 1 and 2 to ensure we fail tag to request conversions for
42/// requests that are not owned by the driver.
43///
44/// We need to track 3 and 4 to ensure that it is safe to end the request and hand
45/// back ownership to the block layer.
46///
47/// Note that the driver can still obtain new `ARef` even if there is no `ARef`s in existence by
48/// using `tag_to_rq`, hence the need to distinguish B and C.
49///
50/// The states are tracked through the private `refcount` field of
51/// `RequestDataWrapper`. This structure lives in the private data area of the C
52/// [`struct request`].
53///
54/// # Invariants
55///
56/// * `self.0` is a valid [`struct request`] created by the C portion of the
57///   kernel.
58/// * The private data area associated with this request must be an initialized
59///   and valid `RequestDataWrapper<T>`.
60/// * `self` is reference counted by atomic modification of
61///   `self.wrapper_ref().refcount()`.
62///
63/// [`struct request`]: srctree/include/linux/blk-mq.h
64///
65#[repr(transparent)]
66pub struct Request<T>(Opaque<bindings::request>, PhantomData<T>);
67
68impl<T: Operations> Request<T> {
69    /// Create an [`ARef<Request>`] from a [`struct request`] pointer.
70    ///
71    /// # Safety
72    ///
73    /// * The caller must own a refcount on `ptr` that is transferred to the
74    ///   returned [`ARef`].
75    /// * The type invariants for [`Request`] must hold for the pointee of `ptr`.
76    ///
77    /// [`struct request`]: srctree/include/linux/blk-mq.h
78    pub(crate) unsafe fn aref_from_raw(ptr: *mut bindings::request) -> ARef<Self> {
79        // INVARIANT: By the safety requirements of this function, invariants are upheld.
80        // SAFETY: By the safety requirement of this function, we own a
81        // reference count that we can pass to `ARef`.
82        unsafe { ARef::from_raw(NonNull::new_unchecked(ptr.cast())) }
83    }
84
85    /// Notify the block layer that a request is going to be processed now.
86    ///
87    /// The block layer uses this hook to do proper initializations such as
88    /// starting the timeout timer. It is a requirement that block device
89    /// drivers call this function when starting to process a request.
90    ///
91    /// # Safety
92    ///
93    /// The caller must have exclusive ownership of `self`, that is
94    /// `self.wrapper_ref().refcount() == 2`.
95    pub(crate) unsafe fn start_unchecked(this: &ARef<Self>) {
96        // SAFETY: By type invariant, `self.0` is a valid `struct request` and
97        // we have exclusive access.
98        unsafe { bindings::blk_mq_start_request(this.0.get()) };
99    }
100
101    /// Try to take exclusive ownership of `this` by dropping the refcount to 0.
102    /// This fails if `this` is not the only [`ARef`] pointing to the underlying
103    /// [`Request`].
104    ///
105    /// If the operation is successful, [`Ok`] is returned with a pointer to the
106    /// C [`struct request`]. If the operation fails, `this` is returned in the
107    /// [`Err`] variant.
108    ///
109    /// [`struct request`]: srctree/include/linux/blk-mq.h
110    fn try_set_end(this: ARef<Self>) -> Result<*mut bindings::request, ARef<Self>> {
111        // To hand back the ownership, we need the current refcount to be 2.
112        // Since we can race with `TagSet::tag_to_rq`, this needs to atomically reduce
113        // refcount to 0. `Refcount` does not provide a way to do this, so use the underlying
114        // atomics directly.
115        if let Err(_old) = this
116            .wrapper_ref()
117            .refcount()
118            .as_atomic()
119            .cmpxchg(2, 0, Relaxed)
120        {
121            return Err(this);
122        }
123
124        let request_ptr = this.0.get();
125        core::mem::forget(this);
126
127        Ok(request_ptr)
128    }
129
130    /// Notify the block layer that the request has been completed without errors.
131    ///
132    /// This function will return [`Err`] if `this` is not the only [`ARef`]
133    /// referencing the request.
134    pub fn end_ok(this: ARef<Self>) -> Result<(), ARef<Self>> {
135        let request_ptr = Self::try_set_end(this)?;
136
137        // SAFETY: By type invariant, `this.0` was a valid `struct request`. The
138        // success of the call to `try_set_end` guarantees that there are no
139        // `ARef`s pointing to this request. Therefore it is safe to hand it
140        // back to the block layer.
141        unsafe {
142            bindings::blk_mq_end_request(
143                request_ptr,
144                bindings::BLK_STS_OK as bindings::blk_status_t,
145            )
146        };
147
148        Ok(())
149    }
150
151    /// Complete the request by scheduling `Operations::complete` for
152    /// execution.
153    ///
154    /// The function may be scheduled locally, via SoftIRQ or remotely via IPMI.
155    /// See `blk_mq_complete_request_remote` in [`blk-mq.c`] for details.
156    ///
157    /// [`blk-mq.c`]: srctree/block/blk-mq.c
158    pub fn complete(this: ARef<Self>) {
159        let ptr = ARef::into_raw(this).cast::<bindings::request>().as_ptr();
160        // SAFETY: By type invariant, `self.0` is a valid `struct request`
161        if !unsafe { bindings::blk_mq_complete_request_remote(ptr) } {
162            // SAFETY: We released a refcount above that we can reclaim here.
163            let this = unsafe { Request::aref_from_raw(ptr) };
164            T::complete(this);
165        }
166    }
167
168    /// Return a pointer to the [`RequestDataWrapper`] stored in the private area
169    /// of the request structure.
170    ///
171    /// # Safety
172    ///
173    /// - `this` must point to a valid allocation of size at least size of
174    ///   [`Self`] plus size of [`RequestDataWrapper`].
175    pub(crate) unsafe fn wrapper_ptr(this: *mut Self) -> NonNull<RequestDataWrapper> {
176        let request_ptr = this.cast::<bindings::request>();
177        // SAFETY: By safety requirements for this function, `this` is a
178        // valid allocation.
179        let wrapper_ptr =
180            unsafe { bindings::blk_mq_rq_to_pdu(request_ptr).cast::<RequestDataWrapper>() };
181        // SAFETY: By C API contract, `wrapper_ptr` points to a valid allocation
182        // and is not null.
183        unsafe { NonNull::new_unchecked(wrapper_ptr) }
184    }
185
186    /// Return a reference to the [`RequestDataWrapper`] stored in the private
187    /// area of the request structure.
188    pub(crate) fn wrapper_ref(&self) -> &RequestDataWrapper {
189        // SAFETY: By type invariant, `self.0` is a valid allocation. Further,
190        // the private data associated with this request is initialized and
191        // valid. The existence of `&self` guarantees that the private data is
192        // valid as a shared reference.
193        unsafe { Self::wrapper_ptr(core::ptr::from_ref(self).cast_mut()).as_ref() }
194    }
195}
196
197/// A wrapper around data stored in the private area of the C [`struct request`].
198///
199/// [`struct request`]: srctree/include/linux/blk-mq.h
200pub(crate) struct RequestDataWrapper {
201    /// The Rust request refcount has the following states:
202    ///
203    /// - 0: The request is owned by C block layer.
204    /// - 1: The request is owned by Rust abstractions but there are no [`ARef`] references to it.
205    /// - 2+: There are [`ARef`] references to the request.
206    refcount: Refcount,
207}
208
209impl RequestDataWrapper {
210    /// Return a reference to the refcount of the request that is embedding
211    /// `self`.
212    pub(crate) fn refcount(&self) -> &Refcount {
213        &self.refcount
214    }
215
216    /// Return a pointer to the refcount of the request that is embedding the
217    /// pointee of `this`.
218    ///
219    /// # Safety
220    ///
221    /// - `this` must point to a live allocation of at least the size of `Self`.
222    pub(crate) unsafe fn refcount_ptr(this: *mut Self) -> *mut Refcount {
223        // SAFETY: Because of the safety requirements of this function, the
224        // field projection is safe.
225        unsafe { &raw mut (*this).refcount }
226    }
227}
228
229// SAFETY: Exclusive access is thread-safe for `Request`. `Request` has no `&mut
230// self` methods and `&self` methods that mutate `self` are internally
231// synchronized.
232unsafe impl<T: Operations> Send for Request<T> {}
233
234// SAFETY: Shared access is thread-safe for `Request`. `&self` methods that
235// mutate `self` are internally synchronized`
236unsafe impl<T: Operations> Sync for Request<T> {}
237
238// SAFETY: All instances of `Request<T>` are reference counted. This
239// implementation of `AlwaysRefCounted` ensure that increments to the ref count
240// keeps the object alive in memory at least until a matching reference count
241// decrement is executed.
242unsafe impl<T: Operations> AlwaysRefCounted for Request<T> {
243    fn inc_ref(&self) {
244        self.wrapper_ref().refcount().inc();
245    }
246
247    unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
248        // SAFETY: The type invariants of `ARef` guarantee that `obj` is valid
249        // for read.
250        let wrapper_ptr = unsafe { Self::wrapper_ptr(obj.as_ptr()).as_ptr() };
251        // SAFETY: The type invariant of `Request` guarantees that the private
252        // data area is initialized and valid.
253        let refcount = unsafe { &*RequestDataWrapper::refcount_ptr(wrapper_ptr) };
254
255        #[cfg_attr(not(CONFIG_DEBUG_MISC), allow(unused_variables))]
256        let is_zero = refcount.dec_and_test();
257
258        #[cfg(CONFIG_DEBUG_MISC)]
259        if is_zero {
260            panic!("Request reached refcount zero in Rust abstractions");
261        }
262    }
263}