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