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