xref: /linux/rust/kernel/list/impl_list_item_mod.rs (revision e71d7e39be6e2aa3fbba34cad12aa72ab853cfb5)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 // Copyright (C) 2024 Google LLC.
4 
5 //! Helpers for implementing list traits safely.
6 
7 use crate::list::ListLinks;
8 
9 /// Declares that this type has a `ListLinks<ID>` field at a fixed offset.
10 ///
11 /// This trait is only used to help implement `ListItem` safely. If `ListItem` is implemented
12 /// manually, then this trait is not needed. Use the [`impl_has_list_links!`] macro to implement
13 /// this trait.
14 ///
15 /// # Safety
16 ///
17 /// All values of this type must have a `ListLinks<ID>` field at the given offset.
18 ///
19 /// The behavior of `raw_get_list_links` must not be changed.
20 pub unsafe trait HasListLinks<const ID: u64 = 0> {
21     /// The offset of the `ListLinks` field.
22     const OFFSET: usize;
23 
24     /// Returns a pointer to the [`ListLinks<T, ID>`] field.
25     ///
26     /// # Safety
27     ///
28     /// The provided pointer must point at a valid struct of type `Self`.
29     ///
30     /// [`ListLinks<T, ID>`]: ListLinks
31     // We don't really need this method, but it's necessary for the implementation of
32     // `impl_has_list_links!` to be correct.
33     #[inline]
34     unsafe fn raw_get_list_links(ptr: *mut Self) -> *mut ListLinks<ID> {
35         // SAFETY: The caller promises that the pointer is valid. The implementer promises that the
36         // `OFFSET` constant is correct.
37         unsafe { ptr.cast::<u8>().add(Self::OFFSET).cast() }
38     }
39 }
40 
41 /// Implements the [`HasListLinks`] trait for the given type.
42 #[macro_export]
43 macro_rules! impl_has_list_links {
44     ($(impl$(<$($implarg:ident),*>)?
45        HasListLinks$(<$id:tt>)?
46        for $self:ty
47        { self$(.$field:ident)* }
48     )*) => {$(
49         // SAFETY: The implementation of `raw_get_list_links` only compiles if the field has the
50         // right type.
51         //
52         // The behavior of `raw_get_list_links` is not changed since the `addr_of_mut!` macro is
53         // equivalent to the pointer offset operation in the trait definition.
54         unsafe impl$(<$($implarg),*>)? $crate::list::HasListLinks$(<$id>)? for $self {
55             const OFFSET: usize = ::core::mem::offset_of!(Self, $($field).*) as usize;
56 
57             #[inline]
58             unsafe fn raw_get_list_links(ptr: *mut Self) -> *mut $crate::list::ListLinks$(<$id>)? {
59                 // SAFETY: The caller promises that the pointer is not dangling. We know that this
60                 // expression doesn't follow any pointers, as the `offset_of!` invocation above
61                 // would otherwise not compile.
62                 unsafe { ::core::ptr::addr_of_mut!((*ptr)$(.$field)*) }
63             }
64         }
65     )*};
66 }
67 pub use impl_has_list_links;
68 
69 /// Declares that the `ListLinks<ID>` field in this struct is inside a `ListLinksSelfPtr<T, ID>`.
70 ///
71 /// # Safety
72 ///
73 /// The `ListLinks<ID>` field of this struct at the offset `HasListLinks<ID>::OFFSET` must be
74 /// inside a `ListLinksSelfPtr<T, ID>`.
75 pub unsafe trait HasSelfPtr<T: ?Sized, const ID: u64 = 0>
76 where
77     Self: HasListLinks<ID>,
78 {
79 }
80 
81 /// Implements the [`HasListLinks`] and [`HasSelfPtr`] traits for the given type.
82 #[macro_export]
83 macro_rules! impl_has_list_links_self_ptr {
84     ($(impl$({$($implarg:tt)*})?
85        HasSelfPtr<$item_type:ty $(, $id:tt)?>
86        for $self:ty
87        { self.$field:ident }
88     )*) => {$(
89         // SAFETY: The implementation of `raw_get_list_links` only compiles if the field has the
90         // right type.
91         unsafe impl$(<$($implarg)*>)? $crate::list::HasSelfPtr<$item_type $(, $id)?> for $self {}
92 
93         unsafe impl$(<$($implarg)*>)? $crate::list::HasListLinks$(<$id>)? for $self {
94             const OFFSET: usize = ::core::mem::offset_of!(Self, $field) as usize;
95 
96             #[inline]
97             unsafe fn raw_get_list_links(ptr: *mut Self) -> *mut $crate::list::ListLinks$(<$id>)? {
98                 // SAFETY: The caller promises that the pointer is not dangling.
99                 let ptr: *mut $crate::list::ListLinksSelfPtr<$item_type $(, $id)?> =
100                     unsafe { ::core::ptr::addr_of_mut!((*ptr).$field) };
101                 ptr.cast()
102             }
103         }
104     )*};
105 }
106 pub use impl_has_list_links_self_ptr;
107 
108 /// Implements the [`ListItem`] trait for the given type.
109 ///
110 /// Requires that the type implements [`HasListLinks`]. Use the [`impl_has_list_links!`] macro to
111 /// implement that trait.
112 ///
113 /// [`ListItem`]: crate::list::ListItem
114 #[macro_export]
115 macro_rules! impl_list_item {
116     (
117         $(impl$({$($generics:tt)*})? ListItem<$num:tt> for $t:ty {
118             using ListLinks;
119         })*
120     ) => {$(
121         // SAFETY: See GUARANTEES comment on each method.
122         unsafe impl$(<$($generics)*>)? $crate::list::ListItem<$num> for $t {
123             // GUARANTEES:
124             // * This returns the same pointer as `prepare_to_insert` because `prepare_to_insert`
125             //   is implemented in terms of `view_links`.
126             // * By the type invariants of `ListLinks`, the `ListLinks` has two null pointers when
127             //   this value is not in a list.
128             unsafe fn view_links(me: *const Self) -> *mut $crate::list::ListLinks<$num> {
129                 // SAFETY: The caller guarantees that `me` points at a valid value of type `Self`.
130                 unsafe {
131                     <Self as $crate::list::HasListLinks<$num>>::raw_get_list_links(me.cast_mut())
132                 }
133             }
134 
135             // GUARANTEES:
136             // * `me` originates from the most recent call to `prepare_to_insert`, which just added
137             //   `offset` to the pointer passed to `prepare_to_insert`. This method subtracts
138             //   `offset` from `me` so it returns the pointer originally passed to
139             //   `prepare_to_insert`.
140             // * The pointer remains valid until the next call to `post_remove` because the caller
141             //   of the most recent call to `prepare_to_insert` promised to retain ownership of the
142             //   `ListArc` containing `Self` until the next call to `post_remove`. The value cannot
143             //   be destroyed while a `ListArc` reference exists.
144             unsafe fn view_value(me: *mut $crate::list::ListLinks<$num>) -> *const Self {
145                 let offset = <Self as $crate::list::HasListLinks<$num>>::OFFSET;
146                 // SAFETY: `me` originates from the most recent call to `prepare_to_insert`, so it
147                 // points at the field at offset `offset` in a value of type `Self`. Thus,
148                 // subtracting `offset` from `me` is still in-bounds of the allocation.
149                 unsafe { (me as *const u8).sub(offset) as *const Self }
150             }
151 
152             // GUARANTEES:
153             // This implementation of `ListItem` will not give out exclusive access to the same
154             // `ListLinks` several times because calls to `prepare_to_insert` and `post_remove`
155             // must alternate and exclusive access is given up when `post_remove` is called.
156             //
157             // Other invocations of `impl_list_item!` also cannot give out exclusive access to the
158             // same `ListLinks` because you can only implement `ListItem` once for each value of
159             // `ID`, and the `ListLinks` fields only work with the specified `ID`.
160             unsafe fn prepare_to_insert(me: *const Self) -> *mut $crate::list::ListLinks<$num> {
161                 // SAFETY: The caller promises that `me` points at a valid value.
162                 unsafe { <Self as $crate::list::ListItem<$num>>::view_links(me) }
163             }
164 
165             // GUARANTEES:
166             // * `me` originates from the most recent call to `prepare_to_insert`, which just added
167             //   `offset` to the pointer passed to `prepare_to_insert`. This method subtracts
168             //   `offset` from `me` so it returns the pointer originally passed to
169             //   `prepare_to_insert`.
170             unsafe fn post_remove(me: *mut $crate::list::ListLinks<$num>) -> *const Self {
171                 let offset = <Self as $crate::list::HasListLinks<$num>>::OFFSET;
172                 // SAFETY: `me` originates from the most recent call to `prepare_to_insert`, so it
173                 // points at the field at offset `offset` in a value of type `Self`. Thus,
174                 // subtracting `offset` from `me` is still in-bounds of the allocation.
175                 unsafe { (me as *const u8).sub(offset) as *const Self }
176             }
177         }
178     )*};
179 
180     (
181         $(impl$({$($generics:tt)*})? ListItem<$num:tt> for $t:ty {
182             using ListLinksSelfPtr;
183         })*
184     ) => {$(
185         // SAFETY: See GUARANTEES comment on each method.
186         unsafe impl$(<$($generics)*>)? $crate::list::ListItem<$num> for $t {
187             // GUARANTEES:
188             // This implementation of `ListItem` will not give out exclusive access to the same
189             // `ListLinks` several times because calls to `prepare_to_insert` and `post_remove`
190             // must alternate and exclusive access is given up when `post_remove` is called.
191             //
192             // Other invocations of `impl_list_item!` also cannot give out exclusive access to the
193             // same `ListLinks` because you can only implement `ListItem` once for each value of
194             // `ID`, and the `ListLinks` fields only work with the specified `ID`.
195             unsafe fn prepare_to_insert(me: *const Self) -> *mut $crate::list::ListLinks<$num> {
196                 // SAFETY: The caller promises that `me` points at a valid value of type `Self`.
197                 let links_field = unsafe { <Self as $crate::list::ListItem<$num>>::view_links(me) };
198 
199                 let spoff = $crate::list::ListLinksSelfPtr::<Self, $num>::LIST_LINKS_SELF_PTR_OFFSET;
200                 // Goes via the offset as the field is private.
201                 //
202                 // SAFETY: The constant is equal to `offset_of!(ListLinksSelfPtr, self_ptr)`, so
203                 // the pointer stays in bounds of the allocation.
204                 let self_ptr = unsafe { (links_field as *const u8).add(spoff) }
205                     as *const $crate::types::Opaque<*const Self>;
206                 let cell_inner = $crate::types::Opaque::cast_into(self_ptr);
207 
208                 // SAFETY: This value is not accessed in any other places than `prepare_to_insert`,
209                 // `post_remove`, or `view_value`. By the safety requirements of those methods,
210                 // none of these three methods may be called in parallel with this call to
211                 // `prepare_to_insert`, so this write will not race with any other access to the
212                 // value.
213                 unsafe { ::core::ptr::write(cell_inner, me) };
214 
215                 links_field
216             }
217 
218             // GUARANTEES:
219             // * This returns the same pointer as `prepare_to_insert` because `prepare_to_insert`
220             //   returns the return value of `view_links`.
221             // * By the type invariants of `ListLinks`, the `ListLinks` has two null pointers when
222             //   this value is not in a list.
223             unsafe fn view_links(me: *const Self) -> *mut $crate::list::ListLinks<$num> {
224                 // SAFETY: The caller promises that `me` points at a valid value of type `Self`.
225                 unsafe { <Self as HasListLinks<$num>>::raw_get_list_links(me.cast_mut()) }
226             }
227 
228             // This function is also used as the implementation of `post_remove`, so the caller
229             // may choose to satisfy the safety requirements of `post_remove` instead of the safety
230             // requirements for `view_value`.
231             //
232             // GUARANTEES: (always)
233             // * This returns the same pointer as the one passed to the most recent call to
234             //   `prepare_to_insert` since that call wrote that pointer to this location. The value
235             //   is only modified in `prepare_to_insert`, so it has not been modified since the
236             //   most recent call.
237             //
238             // GUARANTEES: (only when using the `view_value` safety requirements)
239             // * The pointer remains valid until the next call to `post_remove` because the caller
240             //   of the most recent call to `prepare_to_insert` promised to retain ownership of the
241             //   `ListArc` containing `Self` until the next call to `post_remove`. The value cannot
242             //   be destroyed while a `ListArc` reference exists.
243             unsafe fn view_value(links_field: *mut $crate::list::ListLinks<$num>) -> *const Self {
244                 let spoff = $crate::list::ListLinksSelfPtr::<Self, $num>::LIST_LINKS_SELF_PTR_OFFSET;
245                 // SAFETY: The constant is equal to `offset_of!(ListLinksSelfPtr, self_ptr)`, so
246                 // the pointer stays in bounds of the allocation.
247                 let self_ptr = unsafe { (links_field as *const u8).add(spoff) }
248                     as *const ::core::cell::UnsafeCell<*const Self>;
249                 let cell_inner = ::core::cell::UnsafeCell::raw_get(self_ptr);
250                 // SAFETY: This is not a data race, because the only function that writes to this
251                 // value is `prepare_to_insert`, but by the safety requirements the
252                 // `prepare_to_insert` method may not be called in parallel with `view_value` or
253                 // `post_remove`.
254                 unsafe { ::core::ptr::read(cell_inner) }
255             }
256 
257             // GUARANTEES:
258             // The first guarantee of `view_value` is exactly what `post_remove` guarantees.
259             unsafe fn post_remove(me: *mut $crate::list::ListLinks<$num>) -> *const Self {
260                 // SAFETY: This specific implementation of `view_value` allows the caller to
261                 // promise the safety requirements of `post_remove` instead of the safety
262                 // requirements for `view_value`.
263                 unsafe { <Self as $crate::list::ListItem<$num>>::view_value(me) }
264             }
265         }
266     )*};
267 }
268 pub use impl_list_item;
269