1 // SPDX-License-Identifier: GPL-2.0 1 // SPDX-License-Identifier: GPL-2.0 2 2 3 //! A reference-counted pointer. 3 //! A reference-counted pointer. 4 //! 4 //! 5 //! This module implements a way for users to 5 //! This module implements a way for users to create reference-counted objects and pointers to 6 //! them. Such a pointer automatically increme 6 //! them. Such a pointer automatically increments and decrements the count, and drops the 7 //! underlying object when it reaches zero. It 7 //! underlying object when it reaches zero. It is also safe to use concurrently from multiple 8 //! threads. 8 //! threads. 9 //! 9 //! 10 //! It is different from the standard library' 10 //! It is different from the standard library's [`Arc`] in a few ways: 11 //! 1. It is backed by the kernel's `refcount_ 11 //! 1. It is backed by the kernel's `refcount_t` type. 12 //! 2. It does not support weak references, wh 12 //! 2. It does not support weak references, which allows it to be half the size. 13 //! 3. It saturates the reference count instea 13 //! 3. It saturates the reference count instead of aborting when it goes over a threshold. 14 //! 4. It does not provide a `get_mut` method, 14 //! 4. It does not provide a `get_mut` method, so the ref counted object is pinned. 15 //! 5. The object in [`Arc`] is pinned implici << 16 //! 15 //! 17 //! [`Arc`]: https://doc.rust-lang.org/std/syn 16 //! [`Arc`]: https://doc.rust-lang.org/std/sync/struct.Arc.html 18 17 19 use crate::{ 18 use crate::{ 20 alloc::{box_ext::BoxExt, AllocError, Flags << 21 bindings, 19 bindings, 22 init::{self, InPlaceInit, Init, PinInit}, !! 20 error::Result, 23 try_init, << 24 types::{ForeignOwnable, Opaque}, 21 types::{ForeignOwnable, Opaque}, 25 }; 22 }; 26 use alloc::boxed::Box; 23 use alloc::boxed::Box; 27 use core::{ 24 use core::{ 28 alloc::Layout, << 29 fmt, << 30 marker::{PhantomData, Unsize}, 25 marker::{PhantomData, Unsize}, 31 mem::{ManuallyDrop, MaybeUninit}, 26 mem::{ManuallyDrop, MaybeUninit}, 32 ops::{Deref, DerefMut}, 27 ops::{Deref, DerefMut}, 33 pin::Pin, 28 pin::Pin, 34 ptr::NonNull, 29 ptr::NonNull, 35 }; 30 }; 36 use macros::pin_data; << 37 << 38 mod std_vendor; << 39 31 40 /// A reference-counted pointer to an instance 32 /// A reference-counted pointer to an instance of `T`. 41 /// 33 /// 42 /// The reference count is incremented when ne 34 /// The reference count is incremented when new instances of [`Arc`] are created, and decremented 43 /// when they are dropped. When the count reac 35 /// when they are dropped. When the count reaches zero, the underlying `T` is also dropped. 44 /// 36 /// 45 /// # Invariants 37 /// # Invariants 46 /// 38 /// 47 /// The reference count on an instance of [`Ar 39 /// The reference count on an instance of [`Arc`] is always non-zero. 48 /// The object pointed to by [`Arc`] is always 40 /// The object pointed to by [`Arc`] is always pinned. 49 /// 41 /// 50 /// # Examples 42 /// # Examples 51 /// 43 /// 52 /// ``` 44 /// ``` 53 /// use kernel::sync::Arc; 45 /// use kernel::sync::Arc; 54 /// 46 /// 55 /// struct Example { 47 /// struct Example { 56 /// a: u32, 48 /// a: u32, 57 /// b: u32, 49 /// b: u32, 58 /// } 50 /// } 59 /// 51 /// 60 /// // Create a refcounted instance of `Exampl !! 52 /// // Create a ref-counted instance of `Example`. 61 /// let obj = Arc::new(Example { a: 10, b: 20 !! 53 /// let obj = Arc::try_new(Example { a: 10, b: 20 })?; 62 /// 54 /// 63 /// // Get a new pointer to `obj` and incremen 55 /// // Get a new pointer to `obj` and increment the refcount. 64 /// let cloned = obj.clone(); 56 /// let cloned = obj.clone(); 65 /// 57 /// 66 /// // Assert that both `obj` and `cloned` poi 58 /// // Assert that both `obj` and `cloned` point to the same underlying object. 67 /// assert!(core::ptr::eq(&*obj, &*cloned)); 59 /// assert!(core::ptr::eq(&*obj, &*cloned)); 68 /// 60 /// 69 /// // Destroy `obj` and decrement its refcoun 61 /// // Destroy `obj` and decrement its refcount. 70 /// drop(obj); 62 /// drop(obj); 71 /// 63 /// 72 /// // Check that the values are still accessi 64 /// // Check that the values are still accessible through `cloned`. 73 /// assert_eq!(cloned.a, 10); 65 /// assert_eq!(cloned.a, 10); 74 /// assert_eq!(cloned.b, 20); 66 /// assert_eq!(cloned.b, 20); 75 /// 67 /// 76 /// // The refcount drops to zero when `cloned 68 /// // The refcount drops to zero when `cloned` goes out of scope, and the memory is freed. 77 /// # Ok::<(), Error>(()) << 78 /// ``` 69 /// ``` 79 /// 70 /// 80 /// Using `Arc<T>` as the type of `self`: 71 /// Using `Arc<T>` as the type of `self`: 81 /// 72 /// 82 /// ``` 73 /// ``` 83 /// use kernel::sync::Arc; 74 /// use kernel::sync::Arc; 84 /// 75 /// 85 /// struct Example { 76 /// struct Example { 86 /// a: u32, 77 /// a: u32, 87 /// b: u32, 78 /// b: u32, 88 /// } 79 /// } 89 /// 80 /// 90 /// impl Example { 81 /// impl Example { 91 /// fn take_over(self: Arc<Self>) { 82 /// fn take_over(self: Arc<Self>) { 92 /// // ... 83 /// // ... 93 /// } 84 /// } 94 /// 85 /// 95 /// fn use_reference(self: &Arc<Self>) { 86 /// fn use_reference(self: &Arc<Self>) { 96 /// // ... 87 /// // ... 97 /// } 88 /// } 98 /// } 89 /// } 99 /// 90 /// 100 /// let obj = Arc::new(Example { a: 10, b: 20 !! 91 /// let obj = Arc::try_new(Example { a: 10, b: 20 })?; 101 /// obj.use_reference(); 92 /// obj.use_reference(); 102 /// obj.take_over(); 93 /// obj.take_over(); 103 /// # Ok::<(), Error>(()) << 104 /// ``` 94 /// ``` 105 /// 95 /// 106 /// Coercion from `Arc<Example>` to `Arc<dyn M 96 /// Coercion from `Arc<Example>` to `Arc<dyn MyTrait>`: 107 /// 97 /// 108 /// ``` 98 /// ``` 109 /// use kernel::sync::{Arc, ArcBorrow}; 99 /// use kernel::sync::{Arc, ArcBorrow}; 110 /// 100 /// 111 /// trait MyTrait { 101 /// trait MyTrait { 112 /// // Trait has a function whose `self` t 102 /// // Trait has a function whose `self` type is `Arc<Self>`. 113 /// fn example1(self: Arc<Self>) {} 103 /// fn example1(self: Arc<Self>) {} 114 /// 104 /// 115 /// // Trait has a function whose `self` t 105 /// // Trait has a function whose `self` type is `ArcBorrow<'_, Self>`. 116 /// fn example2(self: ArcBorrow<'_, Self>) 106 /// fn example2(self: ArcBorrow<'_, Self>) {} 117 /// } 107 /// } 118 /// 108 /// 119 /// struct Example; 109 /// struct Example; 120 /// impl MyTrait for Example {} 110 /// impl MyTrait for Example {} 121 /// 111 /// 122 /// // `obj` has type `Arc<Example>`. 112 /// // `obj` has type `Arc<Example>`. 123 /// let obj: Arc<Example> = Arc::new(Example, !! 113 /// let obj: Arc<Example> = Arc::try_new(Example)?; 124 /// 114 /// 125 /// // `coerced` has type `Arc<dyn MyTrait>`. 115 /// // `coerced` has type `Arc<dyn MyTrait>`. 126 /// let coerced: Arc<dyn MyTrait> = obj; 116 /// let coerced: Arc<dyn MyTrait> = obj; 127 /// # Ok::<(), Error>(()) << 128 /// ``` 117 /// ``` 129 pub struct Arc<T: ?Sized> { 118 pub struct Arc<T: ?Sized> { 130 ptr: NonNull<ArcInner<T>>, 119 ptr: NonNull<ArcInner<T>>, 131 _p: PhantomData<ArcInner<T>>, 120 _p: PhantomData<ArcInner<T>>, 132 } 121 } 133 122 134 #[pin_data] << 135 #[repr(C)] 123 #[repr(C)] 136 struct ArcInner<T: ?Sized> { 124 struct ArcInner<T: ?Sized> { 137 refcount: Opaque<bindings::refcount_t>, 125 refcount: Opaque<bindings::refcount_t>, 138 data: T, 126 data: T, 139 } 127 } 140 128 141 impl<T: ?Sized> ArcInner<T> { << 142 /// Converts a pointer to the contents of << 143 /// << 144 /// # Safety << 145 /// << 146 /// `ptr` must have been returned by a pre << 147 /// not yet have been destroyed. << 148 unsafe fn container_of(ptr: *const T) -> N << 149 let refcount_layout = Layout::new::<bi << 150 // SAFETY: The caller guarantees that << 151 let val_layout = Layout::for_value(uns << 152 // SAFETY: We're computing the layout << 153 // binary, so its layout is not so lar << 154 let val_offset = unsafe { refcount_lay << 155 << 156 // Pointer casts leave the metadata un << 157 // `ArcInner<T>` is the same since `Ar << 158 // << 159 // This is documented at: << 160 // <https://doc.rust-lang.org/std/ptr/ << 161 let ptr = ptr as *const ArcInner<T>; << 162 << 163 // SAFETY: The pointer is in-bounds of << 164 // pointer, since it originates from a << 165 // still valid. << 166 let ptr = unsafe { ptr.byte_sub(val_of << 167 << 168 // SAFETY: The pointer can't be null s << 169 // address. << 170 unsafe { NonNull::new_unchecked(ptr.ca << 171 } << 172 } << 173 << 174 // This is to allow [`Arc`] (and variants) to 129 // This is to allow [`Arc`] (and variants) to be used as the type of `self`. 175 impl<T: ?Sized> core::ops::Receiver for Arc<T> 130 impl<T: ?Sized> core::ops::Receiver for Arc<T> {} 176 131 177 // This is to allow coercion from `Arc<T>` to 132 // This is to allow coercion from `Arc<T>` to `Arc<U>` if `T` can be converted to the 178 // dynamically-sized type (DST) `U`. 133 // dynamically-sized type (DST) `U`. 179 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::o 134 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::CoerceUnsized<Arc<U>> for Arc<T> {} 180 135 181 // This is to allow `Arc<U>` to be dispatched 136 // This is to allow `Arc<U>` to be dispatched on when `Arc<T>` can be coerced into `Arc<U>`. 182 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::o 137 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<Arc<U>> for Arc<T> {} 183 138 184 // SAFETY: It is safe to send `Arc<T>` to anot 139 // SAFETY: It is safe to send `Arc<T>` to another thread when the underlying `T` is `Sync` because 185 // it effectively means sharing `&T` (which is 140 // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs 186 // `T` to be `Send` because any thread that ha !! 141 // `T` to be `Send` because any thread that has an `Arc<T>` may ultimately access `T` directly, for 187 // mutable reference when the reference count !! 142 // example, when the reference count reaches zero and `T` is dropped. 188 unsafe impl<T: ?Sized + Sync + Send> Send for 143 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {} 189 144 190 // SAFETY: It is safe to send `&Arc<T>` to ano !! 145 // SAFETY: It is safe to send `&Arc<T>` to another thread when the underlying `T` is `Sync` for the 191 // because it effectively means sharing `&T` ( !! 146 // same reason as above. `T` needs to be `Send` as well because a thread can clone an `&Arc<T>` 192 // it needs `T` to be `Send` because any threa !! 147 // into an `Arc<T>`, which may lead to `T` being accessed by the same reasoning as above. 193 // `Arc<T>` on that thread, so the thread may << 194 // the reference count reaches zero and `T` is << 195 unsafe impl<T: ?Sized + Sync + Send> Sync for 148 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {} 196 149 197 impl<T> Arc<T> { 150 impl<T> Arc<T> { 198 /// Constructs a new reference counted ins 151 /// Constructs a new reference counted instance of `T`. 199 pub fn new(contents: T, flags: Flags) -> R !! 152 pub fn try_new(contents: T) -> Result<Self> { 200 // INVARIANT: The refcount is initiali 153 // INVARIANT: The refcount is initialised to a non-zero value. 201 let value = ArcInner { 154 let value = ArcInner { 202 // SAFETY: There are no safety req 155 // SAFETY: There are no safety requirements for this FFI call. 203 refcount: Opaque::new(unsafe { bin 156 refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }), 204 data: contents, 157 data: contents, 205 }; 158 }; 206 159 207 let inner = <Box<_> as BoxExt<_>>::new !! 160 let inner = Box::try_new(value)?; 208 161 209 // SAFETY: We just created `inner` wit 162 // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new 210 // `Arc` object. 163 // `Arc` object. 211 Ok(unsafe { Self::from_inner(Box::leak 164 Ok(unsafe { Self::from_inner(Box::leak(inner).into()) }) 212 } 165 } 213 } 166 } 214 167 215 impl<T: ?Sized> Arc<T> { 168 impl<T: ?Sized> Arc<T> { 216 /// Constructs a new [`Arc`] from an exist 169 /// Constructs a new [`Arc`] from an existing [`ArcInner`]. 217 /// 170 /// 218 /// # Safety 171 /// # Safety 219 /// 172 /// 220 /// The caller must ensure that `inner` po 173 /// The caller must ensure that `inner` points to a valid location and has a non-zero reference 221 /// count, one of which will be owned by t 174 /// count, one of which will be owned by the new [`Arc`] instance. 222 unsafe fn from_inner(inner: NonNull<ArcInn 175 unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self { 223 // INVARIANT: By the safety requiremen 176 // INVARIANT: By the safety requirements, the invariants hold. 224 Arc { 177 Arc { 225 ptr: inner, 178 ptr: inner, 226 _p: PhantomData, 179 _p: PhantomData, 227 } 180 } 228 } 181 } 229 182 230 /// Convert the [`Arc`] into a raw pointer << 231 /// << 232 /// The raw pointer has ownership of the r << 233 pub fn into_raw(self) -> *const T { << 234 let ptr = self.ptr.as_ptr(); << 235 core::mem::forget(self); << 236 // SAFETY: The pointer is valid. << 237 unsafe { core::ptr::addr_of!((*ptr).da << 238 } << 239 << 240 /// Recreates an [`Arc`] instance previous << 241 /// << 242 /// # Safety << 243 /// << 244 /// `ptr` must have been returned by a pre << 245 /// must not be called more than once for << 246 pub unsafe fn from_raw(ptr: *const T) -> S << 247 // SAFETY: The caller promises that th << 248 // `Arc` that is still valid. << 249 let ptr = unsafe { ArcInner::container << 250 << 251 // SAFETY: By the safety requirements << 252 // reference count held then will be o << 253 unsafe { Self::from_inner(ptr) } << 254 } << 255 << 256 /// Returns an [`ArcBorrow`] from the give 183 /// Returns an [`ArcBorrow`] from the given [`Arc`]. 257 /// 184 /// 258 /// This is useful when the argument of a 185 /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method 259 /// receiver), but we have an [`Arc`] inst 186 /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised. 260 #[inline] 187 #[inline] 261 pub fn as_arc_borrow(&self) -> ArcBorrow<' 188 pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> { 262 // SAFETY: The constraint that the lif 189 // SAFETY: The constraint that the lifetime of the shared reference must outlive that of 263 // the returned `ArcBorrow` ensures th 190 // the returned `ArcBorrow` ensures that the object remains alive and that no mutable 264 // reference can be created. 191 // reference can be created. 265 unsafe { ArcBorrow::new(self.ptr) } 192 unsafe { ArcBorrow::new(self.ptr) } 266 } 193 } 267 << 268 /// Compare whether two [`Arc`] pointers r << 269 pub fn ptr_eq(this: &Self, other: &Self) - << 270 core::ptr::eq(this.ptr.as_ptr(), other << 271 } << 272 << 273 /// Converts this [`Arc`] into a [`UniqueA << 274 /// << 275 /// When this destroys the `Arc`, it does << 276 /// this method will never call the destru << 277 /// << 278 /// # Examples << 279 /// << 280 /// ``` << 281 /// use kernel::sync::{Arc, UniqueArc}; << 282 /// << 283 /// let arc = Arc::new(42, GFP_KERNEL)?; << 284 /// let unique_arc = arc.into_unique_or_dr << 285 /// << 286 /// // The above conversion should succeed << 287 /// assert!(unique_arc.is_some()); << 288 /// << 289 /// assert_eq!(*(unique_arc.unwrap()), 42) << 290 /// << 291 /// # Ok::<(), Error>(()) << 292 /// ``` << 293 /// << 294 /// ``` << 295 /// use kernel::sync::{Arc, UniqueArc}; << 296 /// << 297 /// let arc = Arc::new(42, GFP_KERNEL)?; << 298 /// let another = arc.clone(); << 299 /// << 300 /// let unique_arc = arc.into_unique_or_dr << 301 /// << 302 /// // The above conversion should fail si << 303 /// assert!(unique_arc.is_none()); << 304 /// << 305 /// # Ok::<(), Error>(()) << 306 /// ``` << 307 pub fn into_unique_or_drop(self) -> Option << 308 // We will manually manage the refcoun << 309 let me = ManuallyDrop::new(self); << 310 // SAFETY: We own a refcount, so the p << 311 let refcount = unsafe { me.ptr.as_ref( << 312 << 313 // If the refcount reaches a non-zero << 314 // return without further touching the << 315 // no other arcs, and we can create a << 316 // << 317 // SAFETY: We own a refcount, so the p << 318 let is_zero = unsafe { bindings::refco << 319 if is_zero { << 320 // SAFETY: We have exclusive acces << 321 // accesses to the refcount. << 322 unsafe { core::ptr::write(refcount << 323 << 324 // INVARIANT: We own the only refc << 325 // must pin the `UniqueArc` becaus << 326 // their values. << 327 Some(Pin::from(UniqueArc { << 328 inner: ManuallyDrop::into_inne << 329 })) << 330 } else { << 331 None << 332 } << 333 } << 334 } 194 } 335 195 336 impl<T: 'static> ForeignOwnable for Arc<T> { 196 impl<T: 'static> ForeignOwnable for Arc<T> { 337 type Borrowed<'a> = ArcBorrow<'a, T>; 197 type Borrowed<'a> = ArcBorrow<'a, T>; 338 198 339 fn into_foreign(self) -> *const core::ffi: 199 fn into_foreign(self) -> *const core::ffi::c_void { 340 ManuallyDrop::new(self).ptr.as_ptr() a 200 ManuallyDrop::new(self).ptr.as_ptr() as _ 341 } 201 } 342 202 343 unsafe fn borrow<'a>(ptr: *const core::ffi 203 unsafe fn borrow<'a>(ptr: *const core::ffi::c_void) -> ArcBorrow<'a, T> { 344 // SAFETY: By the safety requirement o 204 // SAFETY: By the safety requirement of this function, we know that `ptr` came from 345 // a previous call to `Arc::into_forei 205 // a previous call to `Arc::into_foreign`. 346 let inner = NonNull::new(ptr as *mut A 206 let inner = NonNull::new(ptr as *mut ArcInner<T>).unwrap(); 347 207 348 // SAFETY: The safety requirements of 208 // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive 349 // for the lifetime of the returned va !! 209 // for the lifetime of the returned value. Additionally, the safety requirements of >> 210 // `ForeignOwnable::borrow_mut` ensure that no new mutable references are created. 350 unsafe { ArcBorrow::new(inner) } 211 unsafe { ArcBorrow::new(inner) } 351 } 212 } 352 213 353 unsafe fn from_foreign(ptr: *const core::f 214 unsafe fn from_foreign(ptr: *const core::ffi::c_void) -> Self { 354 // SAFETY: By the safety requirement o 215 // SAFETY: By the safety requirement of this function, we know that `ptr` came from 355 // a previous call to `Arc::into_forei 216 // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and 356 // holds a reference count increment t 217 // holds a reference count increment that is transferrable to us. 357 unsafe { Self::from_inner(NonNull::new 218 unsafe { Self::from_inner(NonNull::new(ptr as _).unwrap()) } 358 } 219 } 359 } 220 } 360 221 361 impl<T: ?Sized> Deref for Arc<T> { 222 impl<T: ?Sized> Deref for Arc<T> { 362 type Target = T; 223 type Target = T; 363 224 364 fn deref(&self) -> &Self::Target { 225 fn deref(&self) -> &Self::Target { 365 // SAFETY: By the type invariant, ther 226 // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is 366 // safe to dereference it. 227 // safe to dereference it. 367 unsafe { &self.ptr.as_ref().data } 228 unsafe { &self.ptr.as_ref().data } 368 } 229 } 369 } 230 } 370 231 371 impl<T: ?Sized> AsRef<T> for Arc<T> { << 372 fn as_ref(&self) -> &T { << 373 self.deref() << 374 } << 375 } << 376 << 377 impl<T: ?Sized> Clone for Arc<T> { 232 impl<T: ?Sized> Clone for Arc<T> { 378 fn clone(&self) -> Self { 233 fn clone(&self) -> Self { 379 // INVARIANT: C `refcount_inc` saturat 234 // INVARIANT: C `refcount_inc` saturates the refcount, so it cannot overflow to zero. 380 // SAFETY: By the type invariant, ther 235 // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is 381 // safe to increment the refcount. 236 // safe to increment the refcount. 382 unsafe { bindings::refcount_inc(self.p 237 unsafe { bindings::refcount_inc(self.ptr.as_ref().refcount.get()) }; 383 238 384 // SAFETY: We just incremented the ref 239 // SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`. 385 unsafe { Self::from_inner(self.ptr) } 240 unsafe { Self::from_inner(self.ptr) } 386 } 241 } 387 } 242 } 388 243 389 impl<T: ?Sized> Drop for Arc<T> { 244 impl<T: ?Sized> Drop for Arc<T> { 390 fn drop(&mut self) { 245 fn drop(&mut self) { 391 // SAFETY: By the type invariant, ther 246 // SAFETY: By the type invariant, there is necessarily a reference to the object. We cannot 392 // touch `refcount` after it's decreme 247 // touch `refcount` after it's decremented to a non-zero value because another thread/CPU 393 // may concurrently decrement it to ze 248 // may concurrently decrement it to zero and free it. It is ok to have a raw pointer to 394 // freed/invalid memory as long as it 249 // freed/invalid memory as long as it is never dereferenced. 395 let refcount = unsafe { self.ptr.as_re 250 let refcount = unsafe { self.ptr.as_ref() }.refcount.get(); 396 251 397 // INVARIANT: If the refcount reaches 252 // INVARIANT: If the refcount reaches zero, there are no other instances of `Arc`, and 398 // this instance is being dropped, so 253 // this instance is being dropped, so the broken invariant is not observable. 399 // SAFETY: Also by the type invariant, 254 // SAFETY: Also by the type invariant, we are allowed to decrement the refcount. 400 let is_zero = unsafe { bindings::refco 255 let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) }; 401 if is_zero { 256 if is_zero { 402 // The count reached zero, we must 257 // The count reached zero, we must free the memory. 403 // 258 // 404 // SAFETY: The pointer was initial 259 // SAFETY: The pointer was initialised from the result of `Box::leak`. 405 unsafe { drop(Box::from_raw(self.p !! 260 unsafe { Box::from_raw(self.ptr.as_ptr()) }; 406 } 261 } 407 } 262 } 408 } 263 } 409 264 410 impl<T: ?Sized> From<UniqueArc<T>> for Arc<T> 265 impl<T: ?Sized> From<UniqueArc<T>> for Arc<T> { 411 fn from(item: UniqueArc<T>) -> Self { 266 fn from(item: UniqueArc<T>) -> Self { 412 item.inner 267 item.inner 413 } 268 } 414 } 269 } 415 270 416 impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Ar 271 impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Arc<T> { 417 fn from(item: Pin<UniqueArc<T>>) -> Self { 272 fn from(item: Pin<UniqueArc<T>>) -> Self { 418 // SAFETY: The type invariants of `Arc 273 // SAFETY: The type invariants of `Arc` guarantee that the data is pinned. 419 unsafe { Pin::into_inner_unchecked(ite 274 unsafe { Pin::into_inner_unchecked(item).inner } 420 } 275 } 421 } 276 } 422 277 423 /// A borrowed reference to an [`Arc`] instanc 278 /// A borrowed reference to an [`Arc`] instance. 424 /// 279 /// 425 /// For cases when one doesn't ever need to in 280 /// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler 426 /// to use just `&T`, which we can trivially g !! 281 /// to use just `&T`, which we can trivially get from an `Arc<T>` instance. 427 /// 282 /// 428 /// However, when one may need to increment th 283 /// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>` 429 /// over `&Arc<T>` because the latter results 284 /// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference) 430 /// to a pointer ([`Arc<T>`]) to the object (` !! 285 /// to a pointer (`Arc<T>`) to the object (`T`). An [`ArcBorrow`] eliminates this double 431 /// indirection while still allowing one to in !! 286 /// indirection while still allowing one to increment the refcount and getting an `Arc<T>` when/if 432 /// needed. 287 /// needed. 433 /// 288 /// 434 /// # Invariants 289 /// # Invariants 435 /// 290 /// 436 /// There are no mutable references to the und 291 /// There are no mutable references to the underlying [`Arc`], and it remains valid for the 437 /// lifetime of the [`ArcBorrow`] instance. 292 /// lifetime of the [`ArcBorrow`] instance. 438 /// 293 /// 439 /// # Example 294 /// # Example 440 /// 295 /// 441 /// ``` 296 /// ``` 442 /// use kernel::sync::{Arc, ArcBorrow}; !! 297 /// use crate::sync::{Arc, ArcBorrow}; 443 /// 298 /// 444 /// struct Example; 299 /// struct Example; 445 /// 300 /// 446 /// fn do_something(e: ArcBorrow<'_, Example>) 301 /// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> { 447 /// e.into() 302 /// e.into() 448 /// } 303 /// } 449 /// 304 /// 450 /// let obj = Arc::new(Example, GFP_KERNEL)?; !! 305 /// let obj = Arc::try_new(Example)?; 451 /// let cloned = do_something(obj.as_arc_borro 306 /// let cloned = do_something(obj.as_arc_borrow()); 452 /// 307 /// 453 /// // Assert that both `obj` and `cloned` poi 308 /// // Assert that both `obj` and `cloned` point to the same underlying object. 454 /// assert!(core::ptr::eq(&*obj, &*cloned)); 309 /// assert!(core::ptr::eq(&*obj, &*cloned)); 455 /// # Ok::<(), Error>(()) << 456 /// ``` 310 /// ``` 457 /// 311 /// 458 /// Using `ArcBorrow<T>` as the type of `self` 312 /// Using `ArcBorrow<T>` as the type of `self`: 459 /// 313 /// 460 /// ``` 314 /// ``` 461 /// use kernel::sync::{Arc, ArcBorrow}; !! 315 /// use crate::sync::{Arc, ArcBorrow}; 462 /// 316 /// 463 /// struct Example { 317 /// struct Example { 464 /// a: u32, 318 /// a: u32, 465 /// b: u32, 319 /// b: u32, 466 /// } 320 /// } 467 /// 321 /// 468 /// impl Example { 322 /// impl Example { 469 /// fn use_reference(self: ArcBorrow<'_, S 323 /// fn use_reference(self: ArcBorrow<'_, Self>) { 470 /// // ... 324 /// // ... 471 /// } 325 /// } 472 /// } 326 /// } 473 /// 327 /// 474 /// let obj = Arc::new(Example { a: 10, b: 20 !! 328 /// let obj = Arc::try_new(Example { a: 10, b: 20 })?; 475 /// obj.as_arc_borrow().use_reference(); 329 /// obj.as_arc_borrow().use_reference(); 476 /// # Ok::<(), Error>(()) << 477 /// ``` 330 /// ``` 478 pub struct ArcBorrow<'a, T: ?Sized + 'a> { 331 pub struct ArcBorrow<'a, T: ?Sized + 'a> { 479 inner: NonNull<ArcInner<T>>, 332 inner: NonNull<ArcInner<T>>, 480 _p: PhantomData<&'a ()>, 333 _p: PhantomData<&'a ()>, 481 } 334 } 482 335 483 // This is to allow [`ArcBorrow`] (and variant 336 // This is to allow [`ArcBorrow`] (and variants) to be used as the type of `self`. 484 impl<T: ?Sized> core::ops::Receiver for ArcBor 337 impl<T: ?Sized> core::ops::Receiver for ArcBorrow<'_, T> {} 485 338 486 // This is to allow `ArcBorrow<U>` to be dispa 339 // This is to allow `ArcBorrow<U>` to be dispatched on when `ArcBorrow<T>` can be coerced into 487 // `ArcBorrow<U>`. 340 // `ArcBorrow<U>`. 488 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::o 341 impl<T: ?Sized + Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<ArcBorrow<'_, U>> 489 for ArcBorrow<'_, T> 342 for ArcBorrow<'_, T> 490 { 343 { 491 } 344 } 492 345 493 impl<T: ?Sized> Clone for ArcBorrow<'_, T> { 346 impl<T: ?Sized> Clone for ArcBorrow<'_, T> { 494 fn clone(&self) -> Self { 347 fn clone(&self) -> Self { 495 *self 348 *self 496 } 349 } 497 } 350 } 498 351 499 impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} 352 impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} 500 353 501 impl<T: ?Sized> ArcBorrow<'_, T> { 354 impl<T: ?Sized> ArcBorrow<'_, T> { 502 /// Creates a new [`ArcBorrow`] instance. 355 /// Creates a new [`ArcBorrow`] instance. 503 /// 356 /// 504 /// # Safety 357 /// # Safety 505 /// 358 /// 506 /// Callers must ensure the following for 359 /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance: 507 /// 1. That `inner` remains valid; 360 /// 1. That `inner` remains valid; 508 /// 2. That no mutable references to `inne 361 /// 2. That no mutable references to `inner` are created. 509 unsafe fn new(inner: NonNull<ArcInner<T>>) 362 unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self { 510 // INVARIANT: The safety requirements 363 // INVARIANT: The safety requirements guarantee the invariants. 511 Self { 364 Self { 512 inner, 365 inner, 513 _p: PhantomData, 366 _p: PhantomData, 514 } 367 } 515 } 368 } 516 << 517 /// Creates an [`ArcBorrow`] to an [`Arc`] << 518 /// [`Arc::into_raw`]. << 519 /// << 520 /// # Safety << 521 /// << 522 /// * The provided pointer must originate << 523 /// * For the duration of the lifetime ann << 524 /// not hit zero. << 525 /// * For the duration of the lifetime ann << 526 /// [`UniqueArc`] reference to this valu << 527 pub unsafe fn from_raw(ptr: *const T) -> S << 528 // SAFETY: The caller promises that th << 529 // `Arc` that is still valid. << 530 let ptr = unsafe { ArcInner::container << 531 << 532 // SAFETY: The caller promises that th << 533 // not hit zero, and no mutable refere << 534 // `UniqueArc`. << 535 unsafe { Self::new(ptr) } << 536 } << 537 } 369 } 538 370 539 impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc 371 impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> { 540 fn from(b: ArcBorrow<'_, T>) -> Self { 372 fn from(b: ArcBorrow<'_, T>) -> Self { 541 // SAFETY: The existence of `b` guaran 373 // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop` 542 // guarantees that `drop` isn't called 374 // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the 543 // increment. 375 // increment. 544 ManuallyDrop::new(unsafe { Arc::from_i 376 ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) }) 545 .deref() 377 .deref() 546 .clone() 378 .clone() 547 } 379 } 548 } 380 } 549 381 550 impl<T: ?Sized> Deref for ArcBorrow<'_, T> { 382 impl<T: ?Sized> Deref for ArcBorrow<'_, T> { 551 type Target = T; 383 type Target = T; 552 384 553 fn deref(&self) -> &Self::Target { 385 fn deref(&self) -> &Self::Target { 554 // SAFETY: By the type invariant, the 386 // SAFETY: By the type invariant, the underlying object is still alive with no mutable 555 // references to it, so it is safe to 387 // references to it, so it is safe to create a shared reference. 556 unsafe { &self.inner.as_ref().data } 388 unsafe { &self.inner.as_ref().data } 557 } 389 } 558 } 390 } 559 391 560 /// A refcounted object that is known to have 392 /// A refcounted object that is known to have a refcount of 1. 561 /// 393 /// 562 /// It is mutable and can be converted to an [ 394 /// It is mutable and can be converted to an [`Arc`] so that it can be shared. 563 /// 395 /// 564 /// # Invariants 396 /// # Invariants 565 /// 397 /// 566 /// `inner` always has a reference count of 1. 398 /// `inner` always has a reference count of 1. 567 /// 399 /// 568 /// # Examples 400 /// # Examples 569 /// 401 /// 570 /// In the following example, we make changes 402 /// In the following example, we make changes to the inner object before turning it into an 571 /// `Arc<Test>` object (after which point, it 403 /// `Arc<Test>` object (after which point, it cannot be mutated directly). Note that `x.into()` 572 /// cannot fail. 404 /// cannot fail. 573 /// 405 /// 574 /// ``` 406 /// ``` 575 /// use kernel::sync::{Arc, UniqueArc}; 407 /// use kernel::sync::{Arc, UniqueArc}; 576 /// 408 /// 577 /// struct Example { 409 /// struct Example { 578 /// a: u32, 410 /// a: u32, 579 /// b: u32, 411 /// b: u32, 580 /// } 412 /// } 581 /// 413 /// 582 /// fn test() -> Result<Arc<Example>> { 414 /// fn test() -> Result<Arc<Example>> { 583 /// let mut x = UniqueArc::new(Example { a !! 415 /// let mut x = UniqueArc::try_new(Example { a: 10, b: 20 })?; 584 /// x.a += 1; 416 /// x.a += 1; 585 /// x.b += 1; 417 /// x.b += 1; 586 /// Ok(x.into()) 418 /// Ok(x.into()) 587 /// } 419 /// } 588 /// 420 /// 589 /// # test().unwrap(); 421 /// # test().unwrap(); 590 /// ``` 422 /// ``` 591 /// 423 /// 592 /// In the following example we first allocate !! 424 /// In the following example we first allocate memory for a ref-counted `Example` but we don't 593 /// initialise it on allocation. We do initial 425 /// initialise it on allocation. We do initialise it later with a call to [`UniqueArc::write`], 594 /// followed by a conversion to `Arc<Example>` 426 /// followed by a conversion to `Arc<Example>`. This is particularly useful when allocation happens 595 /// in one context (e.g., sleepable) and initi 427 /// in one context (e.g., sleepable) and initialisation in another (e.g., atomic): 596 /// 428 /// 597 /// ``` 429 /// ``` 598 /// use kernel::sync::{Arc, UniqueArc}; 430 /// use kernel::sync::{Arc, UniqueArc}; 599 /// 431 /// 600 /// struct Example { 432 /// struct Example { 601 /// a: u32, 433 /// a: u32, 602 /// b: u32, 434 /// b: u32, 603 /// } 435 /// } 604 /// 436 /// 605 /// fn test() -> Result<Arc<Example>> { 437 /// fn test() -> Result<Arc<Example>> { 606 /// let x = UniqueArc::new_uninit(GFP_KERN !! 438 /// let x = UniqueArc::try_new_uninit()?; 607 /// Ok(x.write(Example { a: 10, b: 20 }).i 439 /// Ok(x.write(Example { a: 10, b: 20 }).into()) 608 /// } 440 /// } 609 /// 441 /// 610 /// # test().unwrap(); 442 /// # test().unwrap(); 611 /// ``` 443 /// ``` 612 /// 444 /// 613 /// In the last example below, the caller gets 445 /// In the last example below, the caller gets a pinned instance of `Example` while converting to 614 /// `Arc<Example>`; this is useful in scenario 446 /// `Arc<Example>`; this is useful in scenarios where one needs a pinned reference during 615 /// initialisation, for example, when initiali 447 /// initialisation, for example, when initialising fields that are wrapped in locks. 616 /// 448 /// 617 /// ``` 449 /// ``` 618 /// use kernel::sync::{Arc, UniqueArc}; 450 /// use kernel::sync::{Arc, UniqueArc}; 619 /// 451 /// 620 /// struct Example { 452 /// struct Example { 621 /// a: u32, 453 /// a: u32, 622 /// b: u32, 454 /// b: u32, 623 /// } 455 /// } 624 /// 456 /// 625 /// fn test() -> Result<Arc<Example>> { 457 /// fn test() -> Result<Arc<Example>> { 626 /// let mut pinned = Pin::from(UniqueArc:: !! 458 /// let mut pinned = Pin::from(UniqueArc::try_new(Example { a: 10, b: 20 })?); 627 /// // We can modify `pinned` because it i 459 /// // We can modify `pinned` because it is `Unpin`. 628 /// pinned.as_mut().a += 1; 460 /// pinned.as_mut().a += 1; 629 /// Ok(pinned.into()) 461 /// Ok(pinned.into()) 630 /// } 462 /// } 631 /// 463 /// 632 /// # test().unwrap(); 464 /// # test().unwrap(); 633 /// ``` 465 /// ``` 634 pub struct UniqueArc<T: ?Sized> { 466 pub struct UniqueArc<T: ?Sized> { 635 inner: Arc<T>, 467 inner: Arc<T>, 636 } 468 } 637 469 638 impl<T> UniqueArc<T> { 470 impl<T> UniqueArc<T> { 639 /// Tries to allocate a new [`UniqueArc`] 471 /// Tries to allocate a new [`UniqueArc`] instance. 640 pub fn new(value: T, flags: Flags) -> Resu !! 472 pub fn try_new(value: T) -> Result<Self> { 641 Ok(Self { 473 Ok(Self { 642 // INVARIANT: The newly-created ob !! 474 // INVARIANT: The newly-created object has a ref-count of 1. 643 inner: Arc::new(value, flags)?, !! 475 inner: Arc::try_new(value)?, 644 }) 476 }) 645 } 477 } 646 478 647 /// Tries to allocate a new [`UniqueArc`] 479 /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet. 648 pub fn new_uninit(flags: Flags) -> Result< !! 480 pub fn try_new_uninit() -> Result<UniqueArc<MaybeUninit<T>>> { 649 // INVARIANT: The refcount is initiali !! 481 Ok(UniqueArc::<MaybeUninit<T>> { 650 let inner = Box::try_init::<AllocError !! 482 // INVARIANT: The newly-created object has a ref-count of 1. 651 try_init!(ArcInner { !! 483 inner: Arc::try_new(MaybeUninit::uninit())?, 652 // SAFETY: There are no safety << 653 refcount: Opaque::new(unsafe { << 654 data <- init::uninit::<T, Allo << 655 }? AllocError), << 656 flags, << 657 )?; << 658 Ok(UniqueArc { << 659 // INVARIANT: The newly-created ob << 660 // SAFETY: The pointer from the `B << 661 inner: unsafe { Arc::from_inner(Bo << 662 }) 484 }) 663 } 485 } 664 } 486 } 665 487 666 impl<T> UniqueArc<MaybeUninit<T>> { 488 impl<T> UniqueArc<MaybeUninit<T>> { 667 /// Converts a `UniqueArc<MaybeUninit<T>>` 489 /// Converts a `UniqueArc<MaybeUninit<T>>` into a `UniqueArc<T>` by writing a value into it. 668 pub fn write(mut self, value: T) -> Unique 490 pub fn write(mut self, value: T) -> UniqueArc<T> { 669 self.deref_mut().write(value); 491 self.deref_mut().write(value); 670 // SAFETY: We just wrote the value to << 671 unsafe { self.assume_init() } << 672 } << 673 << 674 /// Unsafely assume that `self` is initial << 675 /// << 676 /// # Safety << 677 /// << 678 /// The caller guarantees that the value b << 679 /// *immediate* UB to call this when the v << 680 pub unsafe fn assume_init(self) -> UniqueA << 681 let inner = ManuallyDrop::new(self).in 492 let inner = ManuallyDrop::new(self).inner.ptr; 682 UniqueArc { 493 UniqueArc { 683 // SAFETY: The new `Arc` is taking 494 // SAFETY: The new `Arc` is taking over `ptr` from `self.inner` (which won't be 684 // dropped). The types are compati 495 // dropped). The types are compatible because `MaybeUninit<T>` is compatible with `T`. 685 inner: unsafe { Arc::from_inner(in 496 inner: unsafe { Arc::from_inner(inner.cast()) }, 686 } 497 } 687 } 498 } 688 << 689 /// Initialize `self` using the given init << 690 pub fn init_with<E>(mut self, init: impl I << 691 // SAFETY: The supplied pointer is val << 692 match unsafe { init.__init(self.as_mut << 693 // SAFETY: Initialization complete << 694 Ok(()) => Ok(unsafe { self.assume_ << 695 Err(err) => Err(err), << 696 } << 697 } << 698 << 699 /// Pin-initialize `self` using the given << 700 pub fn pin_init_with<E>( << 701 mut self, << 702 init: impl PinInit<T, E>, << 703 ) -> core::result::Result<Pin<UniqueArc<T> << 704 // SAFETY: The supplied pointer is val << 705 // to ensure it does not move. << 706 match unsafe { init.__pinned_init(self << 707 // SAFETY: Initialization complete << 708 Ok(()) => Ok(unsafe { self.assume_ << 709 Err(err) => Err(err), << 710 } << 711 } << 712 } 499 } 713 500 714 impl<T: ?Sized> From<UniqueArc<T>> for Pin<Uni 501 impl<T: ?Sized> From<UniqueArc<T>> for Pin<UniqueArc<T>> { 715 fn from(obj: UniqueArc<T>) -> Self { 502 fn from(obj: UniqueArc<T>) -> Self { 716 // SAFETY: It is not possible to move/ 503 // SAFETY: It is not possible to move/replace `T` inside a `Pin<UniqueArc<T>>` (unless `T` 717 // is `Unpin`), so it is ok to convert 504 // is `Unpin`), so it is ok to convert it to `Pin<UniqueArc<T>>`. 718 unsafe { Pin::new_unchecked(obj) } 505 unsafe { Pin::new_unchecked(obj) } 719 } 506 } 720 } 507 } 721 508 722 impl<T: ?Sized> Deref for UniqueArc<T> { 509 impl<T: ?Sized> Deref for UniqueArc<T> { 723 type Target = T; 510 type Target = T; 724 511 725 fn deref(&self) -> &Self::Target { 512 fn deref(&self) -> &Self::Target { 726 self.inner.deref() 513 self.inner.deref() 727 } 514 } 728 } 515 } 729 516 730 impl<T: ?Sized> DerefMut for UniqueArc<T> { 517 impl<T: ?Sized> DerefMut for UniqueArc<T> { 731 fn deref_mut(&mut self) -> &mut Self::Targ 518 fn deref_mut(&mut self) -> &mut Self::Target { 732 // SAFETY: By the `Arc` type invariant 519 // SAFETY: By the `Arc` type invariant, there is necessarily a reference to the object, so 733 // it is safe to dereference it. Addit 520 // it is safe to dereference it. Additionally, we know there is only one reference when 734 // it's inside a `UniqueArc`, so it is 521 // it's inside a `UniqueArc`, so it is safe to get a mutable reference. 735 unsafe { &mut self.inner.ptr.as_mut(). 522 unsafe { &mut self.inner.ptr.as_mut().data } 736 } << 737 } << 738 << 739 impl<T: fmt::Display + ?Sized> fmt::Display fo << 740 fn fmt(&self, f: &mut fmt::Formatter<'_>) << 741 fmt::Display::fmt(self.deref(), f) << 742 } << 743 } << 744 << 745 impl<T: fmt::Display + ?Sized> fmt::Display fo << 746 fn fmt(&self, f: &mut fmt::Formatter<'_>) << 747 fmt::Display::fmt(self.deref(), f) << 748 } << 749 } << 750 << 751 impl<T: fmt::Debug + ?Sized> fmt::Debug for Un << 752 fn fmt(&self, f: &mut fmt::Formatter<'_>) << 753 fmt::Debug::fmt(self.deref(), f) << 754 } << 755 } << 756 << 757 impl<T: fmt::Debug + ?Sized> fmt::Debug for Ar << 758 fn fmt(&self, f: &mut fmt::Formatter<'_>) << 759 fmt::Debug::fmt(self.deref(), f) << 760 } 523 } 761 } 524 }
Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.