kernel/xarray.rs
1// SPDX-License-Identifier: GPL-2.0
2
3//! XArray abstraction.
4//!
5//! C header: [`include/linux/xarray.h`](srctree/include/linux/xarray.h)
6
7use core::{
8 iter,
9 marker::PhantomData,
10 pin::Pin,
11 ptr::NonNull, //
12};
13use kernel::{
14 alloc,
15 bindings,
16 build_assert::build_assert,
17 error::{
18 Error,
19 Result, //
20 },
21 ffi::c_void,
22 fmt,
23 str::{
24 CStr,
25 CStrExt, //
26 },
27 sync::LockClassKey,
28 types::{
29 ForeignOwnable,
30 NotThreadSafe,
31 Opaque, //
32 }, //
33};
34use pin_init::{
35 pin_data,
36 pin_init,
37 pinned_drop,
38 PinInit, //
39};
40
41/// Creates a [`XArray`] initialiser with the given name and a newly-created lock class.
42///
43/// It uses the name if one is given, otherwise it generates one based on the file name and line
44/// number.
45#[macro_export]
46macro_rules! new_xarray {
47 ($kind:expr $(, $name:literal)? $(,)?) => {
48 $crate::xarray::XArray::new(
49 $kind, $crate::optional_name!($($name)?), $crate::static_lock_class!())
50 };
51}
52pub use new_xarray;
53
54/// An array which efficiently maps sparse integer indices to owned objects.
55///
56/// This is similar to a [`crate::alloc::kvec::Vec<Option<T>>`], but more efficient when there are
57/// holes in the index space, and can be efficiently grown.
58///
59/// # Invariants
60///
61/// `self.xa` is always an initialized and valid [`bindings::xarray`] whose entries are either
62/// `XA_ZERO_ENTRY` or came from `T::into_foreign`.
63///
64/// # Examples
65///
66/// ```rust
67/// use kernel::alloc::KBox;
68/// use kernel::xarray::{new_xarray, AllocKind, XArray};
69///
70/// let xa = KBox::pin_init(new_xarray!(AllocKind::Alloc1), GFP_KERNEL)?;
71///
72/// let dead = KBox::new(0xdead, GFP_KERNEL)?;
73/// let beef = KBox::new(0xbeef, GFP_KERNEL)?;
74///
75/// let mut guard = xa.lock();
76///
77/// assert_eq!(guard.get(0), None);
78///
79/// assert_eq!(guard.store(0, dead, GFP_KERNEL)?.as_deref(), None);
80/// assert_eq!(guard.get(0).copied(), Some(0xdead));
81///
82/// *guard.get_mut(0).unwrap() = 0xffff;
83/// assert_eq!(guard.get(0).copied(), Some(0xffff));
84///
85/// assert_eq!(
86/// guard.store(0, beef, GFP_KERNEL)?.as_deref().copied(),
87/// Some(0xffff)
88/// );
89/// assert_eq!(guard.get(0).copied(), Some(0xbeef));
90///
91/// guard.remove(0);
92/// assert_eq!(guard.get(0), None);
93///
94/// # Ok::<(), Error>(())
95/// ```
96#[pin_data(PinnedDrop)]
97pub struct XArray<T: ForeignOwnable> {
98 #[pin]
99 xa: Opaque<bindings::xarray>,
100 _p: PhantomData<T>,
101}
102
103#[pinned_drop]
104impl<T: ForeignOwnable> PinnedDrop for XArray<T> {
105 fn drop(self: Pin<&mut Self>) {
106 self.iter().for_each(|ptr| {
107 let ptr = ptr.as_ptr();
108 // SAFETY: `ptr` came from `T::into_foreign`.
109 //
110 // INVARIANT: we own the only reference to the array which is being dropped so the
111 // broken invariant is not observable on function exit.
112 drop(unsafe { T::from_foreign(ptr) })
113 });
114
115 // SAFETY: `self.xa` is always valid by the type invariant.
116 unsafe { bindings::xa_destroy(self.xa.get()) };
117 }
118}
119
120/// Flags passed to [`XArray::new`] to configure the array's allocation tracking behavior.
121pub enum AllocKind {
122 /// Consider the first element to be at index 0.
123 Alloc,
124 /// Consider the first element to be at index 1.
125 Alloc1,
126}
127
128impl<T: ForeignOwnable> XArray<T> {
129 /// Creates a new initializer for this type.
130 pub fn new(
131 kind: AllocKind,
132 name: &'static CStr,
133 key: Pin<&'static LockClassKey>,
134 ) -> impl PinInit<Self> {
135 let flags = match kind {
136 AllocKind::Alloc => bindings::XA_FLAGS_ALLOC,
137 AllocKind::Alloc1 => bindings::XA_FLAGS_ALLOC1,
138 };
139 pin_init!(Self {
140 // SAFETY: `xa` is valid while the closure is called.
141 //
142 // INVARIANT: `xa` is initialized here to an empty, valid [`bindings::xarray`].
143 xa <- Opaque::ffi_init(|xa| unsafe {
144 bindings::xa_init_flags_with_key(xa, flags, name.as_char_ptr(), key.as_ptr())
145 }),
146 _p: PhantomData,
147 })
148 }
149
150 fn iter(&self) -> impl Iterator<Item = NonNull<c_void>> + '_ {
151 let mut index = 0;
152
153 // SAFETY: `self.xa` is always valid by the type invariant.
154 iter::once(unsafe {
155 bindings::xa_find(self.xa.get(), &mut index, usize::MAX, bindings::XA_PRESENT)
156 })
157 .chain(iter::from_fn(move || {
158 // SAFETY: `self.xa` is always valid by the type invariant.
159 Some(unsafe {
160 bindings::xa_find_after(self.xa.get(), &mut index, usize::MAX, bindings::XA_PRESENT)
161 })
162 }))
163 .map_while(|ptr| NonNull::new(ptr.cast()))
164 }
165
166 /// Attempts to lock the [`XArray`] for exclusive access.
167 pub fn try_lock(&self) -> Option<Guard<'_, T>> {
168 // SAFETY: `self.xa` is always valid by the type invariant.
169 if (unsafe { bindings::xa_trylock(self.xa.get()) } != 0) {
170 Some(Guard {
171 xa: self,
172 _not_send: NotThreadSafe,
173 })
174 } else {
175 None
176 }
177 }
178
179 /// Locks the [`XArray`] for exclusive access.
180 pub fn lock(&self) -> Guard<'_, T> {
181 // SAFETY: `self.xa` is always valid by the type invariant.
182 unsafe { bindings::xa_lock(self.xa.get()) };
183
184 Guard {
185 xa: self,
186 _not_send: NotThreadSafe,
187 }
188 }
189}
190
191/// A lock guard.
192///
193/// The lock is unlocked when the guard goes out of scope.
194#[must_use = "the lock unlocks immediately when the guard is unused"]
195pub struct Guard<'a, T: ForeignOwnable> {
196 xa: &'a XArray<T>,
197 _not_send: NotThreadSafe,
198}
199
200impl<T: ForeignOwnable> Drop for Guard<'_, T> {
201 fn drop(&mut self) {
202 // SAFETY:
203 // - `self.xa.xa` is always valid by the type invariant.
204 // - The caller holds the lock, so it is safe to unlock it.
205 unsafe { bindings::xa_unlock(self.xa.xa.get()) };
206 }
207}
208
209/// The error returned by [`store`](Guard::store).
210///
211/// Contains the underlying error and the value that was not stored.
212pub struct StoreError<T> {
213 /// The error that occurred.
214 pub error: Error,
215 /// The value that was not stored.
216 pub value: T,
217}
218
219impl<T> fmt::Debug for StoreError<T> {
220 #[inline]
221 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222 f.debug_struct("StoreError")
223 .field("error", &self.error)
224 .finish()
225 }
226}
227
228impl<T> From<StoreError<T>> for Error {
229 #[inline]
230 fn from(value: StoreError<T>) -> Self {
231 value.error
232 }
233}
234
235impl<'a, T: ForeignOwnable> Guard<'a, T> {
236 fn load<F, U>(&self, index: usize, f: F) -> Option<U>
237 where
238 F: FnOnce(NonNull<c_void>) -> U,
239 {
240 // SAFETY: `self.xa.xa` is always valid by the type invariant.
241 let ptr = unsafe { bindings::xa_load(self.xa.xa.get(), index) };
242 let ptr = NonNull::new(ptr.cast())?;
243 Some(f(ptr))
244 }
245
246 /// Provides a reference to the element at the given index.
247 pub fn get(&self, index: usize) -> Option<T::Borrowed<'_>> {
248 self.load(index, |ptr| {
249 // SAFETY: `ptr` came from `T::into_foreign`.
250 unsafe { T::borrow(ptr.as_ptr()) }
251 })
252 }
253
254 /// Provides a mutable reference to the element at the given index.
255 pub fn get_mut(&mut self, index: usize) -> Option<T::BorrowedMut<'_>> {
256 self.load(index, |ptr| {
257 // SAFETY: `ptr` came from `T::into_foreign`.
258 unsafe { T::borrow_mut(ptr.as_ptr()) }
259 })
260 }
261
262 /// Removes and returns the element at the given index.
263 pub fn remove(&mut self, index: usize) -> Option<T> {
264 // SAFETY:
265 // - `self.xa.xa` is always valid by the type invariant.
266 // - The caller holds the lock.
267 let ptr = unsafe { bindings::__xa_erase(self.xa.xa.get(), index) }.cast();
268 // SAFETY:
269 // - `ptr` is either NULL or came from `T::into_foreign`.
270 // - `&mut self` guarantees that the lifetimes of [`T::Borrowed`] and [`T::BorrowedMut`]
271 // borrowed from `self` have ended.
272 unsafe { T::try_from_foreign(ptr) }
273 }
274
275 /// Stores an element at the given index.
276 ///
277 /// May drop the lock if needed to allocate memory, and then reacquire it afterwards.
278 ///
279 /// On success, returns the element which was previously at the given index.
280 ///
281 /// On failure, returns the element which was attempted to be stored.
282 pub fn store(
283 &mut self,
284 index: usize,
285 value: T,
286 gfp: alloc::Flags,
287 ) -> Result<Option<T>, StoreError<T>> {
288 build_assert!(
289 T::FOREIGN_ALIGN >= 4,
290 "pointers stored in XArray must be 4-byte aligned"
291 );
292 let new = value.into_foreign();
293
294 let old = {
295 let new = new.cast();
296 // SAFETY:
297 // - `self.xa.xa` is always valid by the type invariant.
298 // - The caller holds the lock.
299 //
300 // INVARIANT: `new` came from `T::into_foreign`.
301 unsafe { bindings::__xa_store(self.xa.xa.get(), index, new, gfp.as_raw()) }
302 };
303
304 // SAFETY: `__xa_store` returns the old entry at this index on success or `xa_err` if an
305 // error happened.
306 let errno = unsafe { bindings::xa_err(old) };
307 if errno != 0 {
308 // SAFETY: `new` came from `T::into_foreign` and `__xa_store` does not take
309 // ownership of the value on error.
310 let value = unsafe { T::from_foreign(new) };
311 Err(StoreError {
312 value,
313 error: Error::from_errno(errno),
314 })
315 } else {
316 let old = old.cast();
317 // SAFETY: `ptr` is either NULL or came from `T::into_foreign`.
318 //
319 // NB: `XA_ZERO_ENTRY` is never returned by functions belonging to the Normal XArray
320 // API; such entries present as `NULL`.
321 Ok(unsafe { T::try_from_foreign(old) })
322 }
323 }
324}
325
326// SAFETY: `XArray<T>` has no shared mutable state so it is `Send` iff `T` is `Send`.
327unsafe impl<T: ForeignOwnable + Send> Send for XArray<T> {}
328
329// SAFETY: `XArray<T>` serialises the interior mutability it provides so it is `Sync` iff `T` is
330// `Send`.
331unsafe impl<T: ForeignOwnable + Send> Sync for XArray<T> {}