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