1 // SPDX-License-Identifier: GPL-2.0
3 //! This module provides a wrapper for the C `struct request` type.
5 //! C header: [`include/linux/blk-mq.h`](srctree/include/linux/blk-mq.h)
11 types::{ARef, AlwaysRefCounted, Opaque},
15 ptr::{addr_of_mut, NonNull},
16 sync::atomic::{AtomicU64, Ordering},
19 /// A wrapper around a blk-mq [`struct request`]. This represents an IO request.
21 /// # Implementation details
23 /// There are four states for a request that the Rust bindings care about:
25 /// 1. Request is owned by block layer (refcount 0).
26 /// 2. Request is owned by driver but with zero [`ARef`]s in existence
28 /// 3. Request is owned by driver with exactly one [`ARef`] in existence
30 /// 4. Request is owned by driver with more than one [`ARef`] in existence
34 /// We need to track 1 and 2 to ensure we fail tag to request conversions for
35 /// requests that are not owned by the driver.
37 /// We need to track 3 and 4 to ensure that it is safe to end the request and hand
38 /// back ownership to the block layer.
40 /// The states are tracked through the private `refcount` field of
41 /// `RequestDataWrapper`. This structure lives in the private data area of the C
42 /// [`struct request`].
46 /// * `self.0` is a valid [`struct request`] created by the C portion of the
48 /// * The private data area associated with this request must be an initialized
49 /// and valid `RequestDataWrapper<T>`.
50 /// * `self` is reference counted by atomic modification of
51 /// `self.wrapper_ref().refcount()`.
53 /// [`struct request`]: srctree/include/linux/blk-mq.h
56 pub struct Request<T: Operations>(Opaque<bindings::request>, PhantomData<T>);
58 impl<T: Operations> Request<T> {
59 /// Create an [`ARef<Request>`] from a [`struct request`] pointer.
63 /// * The caller must own a refcount on `ptr` that is transferred to the
64 /// returned [`ARef`].
65 /// * The type invariants for [`Request`] must hold for the pointee of `ptr`.
67 /// [`struct request`]: srctree/include/linux/blk-mq.h
68 pub(crate) unsafe fn aref_from_raw(ptr: *mut bindings::request) -> ARef<Self> {
69 // INVARIANT: By the safety requirements of this function, invariants are upheld.
70 // SAFETY: By the safety requirement of this function, we own a
71 // reference count that we can pass to `ARef`.
72 unsafe { ARef::from_raw(NonNull::new_unchecked(ptr as *const Self as *mut Self)) }
75 /// Notify the block layer that a request is going to be processed now.
77 /// The block layer uses this hook to do proper initializations such as
78 /// starting the timeout timer. It is a requirement that block device
79 /// drivers call this function when starting to process a request.
83 /// The caller must have exclusive ownership of `self`, that is
84 /// `self.wrapper_ref().refcount() == 2`.
85 pub(crate) unsafe fn start_unchecked(this: &ARef<Self>) {
86 // SAFETY: By type invariant, `self.0` is a valid `struct request` and
87 // we have exclusive access.
88 unsafe { bindings::blk_mq_start_request(this.0.get()) };
91 /// Try to take exclusive ownership of `this` by dropping the refcount to 0.
92 /// This fails if `this` is not the only [`ARef`] pointing to the underlying
95 /// If the operation is successful, [`Ok`] is returned with a pointer to the
96 /// C [`struct request`]. If the operation fails, `this` is returned in the
99 /// [`struct request`]: srctree/include/linux/blk-mq.h
100 fn try_set_end(this: ARef<Self>) -> Result<*mut bindings::request, ARef<Self>> {
101 // We can race with `TagSet::tag_to_rq`
102 if let Err(_old) = this.wrapper_ref().refcount().compare_exchange(
111 let request_ptr = this.0.get();
112 core::mem::forget(this);
117 /// Notify the block layer that the request has been completed without errors.
119 /// This function will return [`Err`] if `this` is not the only [`ARef`]
120 /// referencing the request.
121 pub fn end_ok(this: ARef<Self>) -> Result<(), ARef<Self>> {
122 let request_ptr = Self::try_set_end(this)?;
124 // SAFETY: By type invariant, `this.0` was a valid `struct request`. The
125 // success of the call to `try_set_end` guarantees that there are no
126 // `ARef`s pointing to this request. Therefore it is safe to hand it
127 // back to the block layer.
128 unsafe { bindings::blk_mq_end_request(request_ptr, bindings::BLK_STS_OK as _) };
133 /// Return a pointer to the [`RequestDataWrapper`] stored in the private area
134 /// of the request structure.
138 /// - `this` must point to a valid allocation of size at least size of
139 /// [`Self`] plus size of [`RequestDataWrapper`].
140 pub(crate) unsafe fn wrapper_ptr(this: *mut Self) -> NonNull<RequestDataWrapper> {
141 let request_ptr = this.cast::<bindings::request>();
142 // SAFETY: By safety requirements for this function, `this` is a
145 unsafe { bindings::blk_mq_rq_to_pdu(request_ptr).cast::<RequestDataWrapper>() };
146 // SAFETY: By C API contract, wrapper_ptr points to a valid allocation
148 unsafe { NonNull::new_unchecked(wrapper_ptr) }
151 /// Return a reference to the [`RequestDataWrapper`] stored in the private
152 /// area of the request structure.
153 pub(crate) fn wrapper_ref(&self) -> &RequestDataWrapper {
154 // SAFETY: By type invariant, `self.0` is a valid allocation. Further,
155 // the private data associated with this request is initialized and
156 // valid. The existence of `&self` guarantees that the private data is
157 // valid as a shared reference.
158 unsafe { Self::wrapper_ptr(self as *const Self as *mut Self).as_ref() }
162 /// A wrapper around data stored in the private area of the C [`struct request`].
164 /// [`struct request`]: srctree/include/linux/blk-mq.h
165 pub(crate) struct RequestDataWrapper {
166 /// The Rust request refcount has the following states:
168 /// - 0: The request is owned by C block layer.
169 /// - 1: The request is owned by Rust abstractions but there are no [`ARef`] references to it.
170 /// - 2+: There are [`ARef`] references to the request.
174 impl RequestDataWrapper {
175 /// Return a reference to the refcount of the request that is embedding
177 pub(crate) fn refcount(&self) -> &AtomicU64 {
181 /// Return a pointer to the refcount of the request that is embedding the
182 /// pointee of `this`.
186 /// - `this` must point to a live allocation of at least the size of `Self`.
187 pub(crate) unsafe fn refcount_ptr(this: *mut Self) -> *mut AtomicU64 {
188 // SAFETY: Because of the safety requirements of this function, the
189 // field projection is safe.
190 unsafe { addr_of_mut!((*this).refcount) }
194 // SAFETY: Exclusive access is thread-safe for `Request`. `Request` has no `&mut
195 // self` methods and `&self` methods that mutate `self` are internally
197 unsafe impl<T: Operations> Send for Request<T> {}
199 // SAFETY: Shared access is thread-safe for `Request`. `&self` methods that
200 // mutate `self` are internally synchronized`
201 unsafe impl<T: Operations> Sync for Request<T> {}
203 /// Store the result of `op(target.load())` in target, returning new value of
205 fn atomic_relaxed_op_return(target: &AtomicU64, op: impl Fn(u64) -> u64) -> u64 {
206 let old = target.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |x| Some(op(x)));
208 // SAFETY: Because the operation passed to `fetch_update` above always
209 // return `Some`, `old` will always be `Ok`.
210 let old = unsafe { old.unwrap_unchecked() };
215 /// Store the result of `op(target.load)` in `target` if `target.load() !=
216 /// pred`, returning [`true`] if the target was updated.
217 fn atomic_relaxed_op_unless(target: &AtomicU64, op: impl Fn(u64) -> u64, pred: u64) -> bool {
219 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |x| {
229 // SAFETY: All instances of `Request<T>` are reference counted. This
230 // implementation of `AlwaysRefCounted` ensure that increments to the ref count
231 // keeps the object alive in memory at least until a matching reference count
232 // decrement is executed.
233 unsafe impl<T: Operations> AlwaysRefCounted for Request<T> {
235 let refcount = &self.wrapper_ref().refcount();
237 #[cfg_attr(not(CONFIG_DEBUG_MISC), allow(unused_variables))]
238 let updated = atomic_relaxed_op_unless(refcount, |x| x + 1, 0);
240 #[cfg(CONFIG_DEBUG_MISC)]
242 panic!("Request refcount zero on clone")
246 unsafe fn dec_ref(obj: core::ptr::NonNull<Self>) {
247 // SAFETY: The type invariants of `ARef` guarantee that `obj` is valid
249 let wrapper_ptr = unsafe { Self::wrapper_ptr(obj.as_ptr()).as_ptr() };
250 // SAFETY: The type invariant of `Request` guarantees that the private
251 // data area is initialized and valid.
252 let refcount = unsafe { &*RequestDataWrapper::refcount_ptr(wrapper_ptr) };
254 #[cfg_attr(not(CONFIG_DEBUG_MISC), allow(unused_variables))]
255 let new_refcount = atomic_relaxed_op_return(refcount, |x| x - 1);
257 #[cfg(CONFIG_DEBUG_MISC)]
258 if new_refcount == 0 {
259 panic!("Request reached refcount zero in Rust abstractions");