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::InPlaceInit, 23 try_init, 24 types::{ForeignOwnable, Opaque}, 25 }; 26 use core::{ 27 alloc::Layout, 28 borrow::{Borrow, BorrowMut}, 29 fmt, 30 marker::PhantomData, 31 mem::{ManuallyDrop, MaybeUninit}, 32 ops::{Deref, DerefMut}, 33 pin::Pin, 34 ptr::NonNull, 35 }; 36 use pin_init::{self, pin_data, InPlaceWrite, Init, PinInit}; 37 38 mod std_vendor; 39 40 /// A reference-counted pointer to an instance of `T`. 41 /// 42 /// The reference count is incremented when new instances of [`Arc`] are created, and decremented 43 /// when they are dropped. When the count reaches zero, the underlying `T` is also dropped. 44 /// 45 /// # Invariants 46 /// 47 /// The reference count on an instance of [`Arc`] is always non-zero. 48 /// The object pointed to by [`Arc`] is always pinned. 49 /// 50 /// # Examples 51 /// 52 /// ``` 53 /// use kernel::sync::Arc; 54 /// 55 /// struct Example { 56 /// a: u32, 57 /// b: u32, 58 /// } 59 /// 60 /// // Create a refcounted instance of `Example`. 61 /// let obj = Arc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?; 62 /// 63 /// // Get a new pointer to `obj` and increment the refcount. 64 /// let cloned = obj.clone(); 65 /// 66 /// // Assert that both `obj` and `cloned` point to the same underlying object. 67 /// assert!(core::ptr::eq(&*obj, &*cloned)); 68 /// 69 /// // Destroy `obj` and decrement its refcount. 70 /// drop(obj); 71 /// 72 /// // Check that the values are still accessible through `cloned`. 73 /// assert_eq!(cloned.a, 10); 74 /// assert_eq!(cloned.b, 20); 75 /// 76 /// // The refcount drops to zero when `cloned` goes out of scope, and the memory is freed. 77 /// # Ok::<(), Error>(()) 78 /// ``` 79 /// 80 /// Using `Arc<T>` as the type of `self`: 81 /// 82 /// ``` 83 /// use kernel::sync::Arc; 84 /// 85 /// struct Example { 86 /// a: u32, 87 /// b: u32, 88 /// } 89 /// 90 /// impl Example { 91 /// fn take_over(self: Arc<Self>) { 92 /// // ... 93 /// } 94 /// 95 /// fn use_reference(self: &Arc<Self>) { 96 /// // ... 97 /// } 98 /// } 99 /// 100 /// let obj = Arc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?; 101 /// obj.use_reference(); 102 /// obj.take_over(); 103 /// # Ok::<(), Error>(()) 104 /// ``` 105 /// 106 /// Coercion from `Arc<Example>` to `Arc<dyn MyTrait>`: 107 /// 108 /// ``` 109 /// use kernel::sync::{Arc, ArcBorrow}; 110 /// 111 /// trait MyTrait { 112 /// // Trait has a function whose `self` type is `Arc<Self>`. 113 /// fn example1(self: Arc<Self>) {} 114 /// 115 /// // Trait has a function whose `self` type is `ArcBorrow<'_, Self>`. 116 /// fn example2(self: ArcBorrow<'_, Self>) {} 117 /// } 118 /// 119 /// struct Example; 120 /// impl MyTrait for Example {} 121 /// 122 /// // `obj` has type `Arc<Example>`. 123 /// let obj: Arc<Example> = Arc::new(Example, GFP_KERNEL)?; 124 /// 125 /// // `coerced` has type `Arc<dyn MyTrait>`. 126 /// let coerced: Arc<dyn MyTrait> = obj; 127 /// # Ok::<(), Error>(()) 128 /// ``` 129 #[repr(transparent)] 130 #[cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, derive(core::marker::CoercePointee))] 131 pub struct Arc<T: ?Sized> { 132 ptr: NonNull<ArcInner<T>>, 133 // NB: this informs dropck that objects of type `ArcInner<T>` may be used in `<Arc<T> as 134 // Drop>::drop`. Note that dropck already assumes that objects of type `T` may be used in 135 // `<Arc<T> as Drop>::drop` and the distinction between `T` and `ArcInner<T>` is not presently 136 // meaningful with respect to dropck - but this may change in the future so this is left here 137 // out of an abundance of caution. 138 // 139 // See <https://doc.rust-lang.org/nomicon/phantom-data.html#generic-parameters-and-drop-checking> 140 // for more detail on the semantics of dropck in the presence of `PhantomData`. 141 _p: PhantomData<ArcInner<T>>, 142 } 143 144 #[doc(hidden)] 145 #[pin_data] 146 #[repr(C)] 147 pub struct ArcInner<T: ?Sized> { 148 refcount: Opaque<bindings::refcount_t>, 149 data: T, 150 } 151 152 impl<T: ?Sized> ArcInner<T> { 153 /// Converts a pointer to the contents of an [`Arc`] into a pointer to the [`ArcInner`]. 154 /// 155 /// # Safety 156 /// 157 /// `ptr` must have been returned by a previous call to [`Arc::into_raw`], and the `Arc` must 158 /// not yet have been destroyed. 159 unsafe fn container_of(ptr: *const T) -> NonNull<ArcInner<T>> { 160 let refcount_layout = Layout::new::<bindings::refcount_t>(); 161 // SAFETY: The caller guarantees that the pointer is valid. 162 let val_layout = Layout::for_value(unsafe { &*ptr }); 163 // SAFETY: We're computing the layout of a real struct that existed when compiling this 164 // binary, so its layout is not so large that it can trigger arithmetic overflow. 165 let val_offset = unsafe { refcount_layout.extend(val_layout).unwrap_unchecked().1 }; 166 167 // Pointer casts leave the metadata unchanged. This is okay because the metadata of `T` and 168 // `ArcInner<T>` is the same since `ArcInner` is a struct with `T` as its last field. 169 // 170 // This is documented at: 171 // <https://doc.rust-lang.org/std/ptr/trait.Pointee.html>. 172 let ptr = ptr as *const ArcInner<T>; 173 174 // SAFETY: The pointer is in-bounds of an allocation both before and after offsetting the 175 // pointer, since it originates from a previous call to `Arc::into_raw` on an `Arc` that is 176 // still valid. 177 let ptr = unsafe { ptr.byte_sub(val_offset) }; 178 179 // SAFETY: The pointer can't be null since you can't have an `ArcInner<T>` value at the null 180 // address. 181 unsafe { NonNull::new_unchecked(ptr.cast_mut()) } 182 } 183 } 184 185 // This is to allow coercion from `Arc<T>` to `Arc<U>` if `T` can be converted to the 186 // dynamically-sized type (DST) `U`. 187 #[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))] 188 impl<T: ?Sized + core::marker::Unsize<U>, U: ?Sized> core::ops::CoerceUnsized<Arc<U>> for Arc<T> {} 189 190 // This is to allow `Arc<U>` to be dispatched on when `Arc<T>` can be coerced into `Arc<U>`. 191 #[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))] 192 impl<T: ?Sized + core::marker::Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<Arc<U>> for Arc<T> {} 193 194 // SAFETY: It is safe to send `Arc<T>` to another thread when the underlying `T` is `Sync` because 195 // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs 196 // `T` to be `Send` because any thread that has an `Arc<T>` may ultimately access `T` using a 197 // mutable reference when the reference count reaches zero and `T` is dropped. 198 unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {} 199 200 // SAFETY: It is safe to send `&Arc<T>` to another thread when the underlying `T` is `Sync` 201 // because it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, 202 // it needs `T` to be `Send` because any thread that has a `&Arc<T>` may clone it and get an 203 // `Arc<T>` on that thread, so the thread may ultimately access `T` using a mutable reference when 204 // the reference count reaches zero and `T` is dropped. 205 unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {} 206 207 impl<T> InPlaceInit<T> for Arc<T> { 208 type PinnedSelf = Self; 209 210 #[inline] 211 fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Self::PinnedSelf, E> 212 where 213 E: From<AllocError>, 214 { 215 UniqueArc::try_pin_init(init, flags).map(|u| u.into()) 216 } 217 218 #[inline] 219 fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E> 220 where 221 E: From<AllocError>, 222 { 223 UniqueArc::try_init(init, flags).map(|u| u.into()) 224 } 225 } 226 227 impl<T> Arc<T> { 228 /// Constructs a new reference counted instance of `T`. 229 pub fn new(contents: T, flags: Flags) -> Result<Self, AllocError> { 230 // INVARIANT: The refcount is initialised to a non-zero value. 231 let value = ArcInner { 232 // SAFETY: There are no safety requirements for this FFI call. 233 refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }), 234 data: contents, 235 }; 236 237 let inner = KBox::new(value, flags)?; 238 let inner = KBox::leak(inner).into(); 239 240 // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new 241 // `Arc` object. 242 Ok(unsafe { Self::from_inner(inner) }) 243 } 244 } 245 246 impl<T: ?Sized> Arc<T> { 247 /// Constructs a new [`Arc`] from an existing [`ArcInner`]. 248 /// 249 /// # Safety 250 /// 251 /// The caller must ensure that `inner` points to a valid location and has a non-zero reference 252 /// count, one of which will be owned by the new [`Arc`] instance. 253 unsafe fn from_inner(inner: NonNull<ArcInner<T>>) -> Self { 254 // INVARIANT: By the safety requirements, the invariants hold. 255 Arc { 256 ptr: inner, 257 _p: PhantomData, 258 } 259 } 260 261 /// Convert the [`Arc`] into a raw pointer. 262 /// 263 /// The raw pointer has ownership of the refcount that this Arc object owned. 264 pub fn into_raw(self) -> *const T { 265 let ptr = self.ptr.as_ptr(); 266 core::mem::forget(self); 267 // SAFETY: The pointer is valid. 268 unsafe { core::ptr::addr_of!((*ptr).data) } 269 } 270 271 /// Return a raw pointer to the data in this arc. 272 pub fn as_ptr(this: &Self) -> *const T { 273 let ptr = this.ptr.as_ptr(); 274 275 // SAFETY: As `ptr` points to a valid allocation of type `ArcInner`, 276 // field projection to `data`is within bounds of the allocation. 277 unsafe { core::ptr::addr_of!((*ptr).data) } 278 } 279 280 /// Recreates an [`Arc`] instance previously deconstructed via [`Arc::into_raw`]. 281 /// 282 /// # Safety 283 /// 284 /// `ptr` must have been returned by a previous call to [`Arc::into_raw`]. Additionally, it 285 /// must not be called more than once for each previous call to [`Arc::into_raw`]. 286 pub unsafe fn from_raw(ptr: *const T) -> Self { 287 // SAFETY: The caller promises that this pointer originates from a call to `into_raw` on an 288 // `Arc` that is still valid. 289 let ptr = unsafe { ArcInner::container_of(ptr) }; 290 291 // SAFETY: By the safety requirements we know that `ptr` came from `Arc::into_raw`, so the 292 // reference count held then will be owned by the new `Arc` object. 293 unsafe { Self::from_inner(ptr) } 294 } 295 296 /// Returns an [`ArcBorrow`] from the given [`Arc`]. 297 /// 298 /// This is useful when the argument of a function call is an [`ArcBorrow`] (e.g., in a method 299 /// receiver), but we have an [`Arc`] instead. Getting an [`ArcBorrow`] is free when optimised. 300 #[inline] 301 pub fn as_arc_borrow(&self) -> ArcBorrow<'_, T> { 302 // SAFETY: The constraint that the lifetime of the shared reference must outlive that of 303 // the returned `ArcBorrow` ensures that the object remains alive and that no mutable 304 // reference can be created. 305 unsafe { ArcBorrow::new(self.ptr) } 306 } 307 308 /// Compare whether two [`Arc`] pointers reference the same underlying object. 309 pub fn ptr_eq(this: &Self, other: &Self) -> bool { 310 core::ptr::eq(this.ptr.as_ptr(), other.ptr.as_ptr()) 311 } 312 313 /// Converts this [`Arc`] into a [`UniqueArc`], or destroys it if it is not unique. 314 /// 315 /// When this destroys the `Arc`, it does so while properly avoiding races. This means that 316 /// this method will never call the destructor of the value. 317 /// 318 /// # Examples 319 /// 320 /// ``` 321 /// use kernel::sync::{Arc, UniqueArc}; 322 /// 323 /// let arc = Arc::new(42, GFP_KERNEL)?; 324 /// let unique_arc = arc.into_unique_or_drop(); 325 /// 326 /// // The above conversion should succeed since refcount of `arc` is 1. 327 /// assert!(unique_arc.is_some()); 328 /// 329 /// assert_eq!(*(unique_arc.unwrap()), 42); 330 /// 331 /// # Ok::<(), Error>(()) 332 /// ``` 333 /// 334 /// ``` 335 /// use kernel::sync::{Arc, UniqueArc}; 336 /// 337 /// let arc = Arc::new(42, GFP_KERNEL)?; 338 /// let another = arc.clone(); 339 /// 340 /// let unique_arc = arc.into_unique_or_drop(); 341 /// 342 /// // The above conversion should fail since refcount of `arc` is >1. 343 /// assert!(unique_arc.is_none()); 344 /// 345 /// # Ok::<(), Error>(()) 346 /// ``` 347 pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> { 348 // We will manually manage the refcount in this method, so we disable the destructor. 349 let me = ManuallyDrop::new(self); 350 // SAFETY: We own a refcount, so the pointer is still valid. 351 let refcount = unsafe { me.ptr.as_ref() }.refcount.get(); 352 353 // If the refcount reaches a non-zero value, then we have destroyed this `Arc` and will 354 // return without further touching the `Arc`. If the refcount reaches zero, then there are 355 // no other arcs, and we can create a `UniqueArc`. 356 // 357 // SAFETY: We own a refcount, so the pointer is not dangling. 358 let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) }; 359 if is_zero { 360 // SAFETY: We have exclusive access to the arc, so we can perform unsynchronized 361 // accesses to the refcount. 362 unsafe { core::ptr::write(refcount, bindings::REFCOUNT_INIT(1)) }; 363 364 // INVARIANT: We own the only refcount to this arc, so we may create a `UniqueArc`. We 365 // must pin the `UniqueArc` because the values was previously in an `Arc`, and they pin 366 // their values. 367 Some(Pin::from(UniqueArc { 368 inner: ManuallyDrop::into_inner(me), 369 })) 370 } else { 371 None 372 } 373 } 374 } 375 376 // SAFETY: The `into_foreign` function returns a pointer that is well-aligned. 377 unsafe impl<T: 'static> ForeignOwnable for Arc<T> { 378 type PointedTo = ArcInner<T>; 379 type Borrowed<'a> = ArcBorrow<'a, T>; 380 type BorrowedMut<'a> = Self::Borrowed<'a>; 381 382 fn into_foreign(self) -> *mut Self::PointedTo { 383 ManuallyDrop::new(self).ptr.as_ptr() 384 } 385 386 unsafe fn from_foreign(ptr: *mut Self::PointedTo) -> Self { 387 // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous 388 // call to `Self::into_foreign`. 389 let inner = unsafe { NonNull::new_unchecked(ptr) }; 390 391 // SAFETY: By the safety requirement of this function, we know that `ptr` came from 392 // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and 393 // holds a reference count increment that is transferrable to us. 394 unsafe { Self::from_inner(inner) } 395 } 396 397 unsafe fn borrow<'a>(ptr: *mut Self::PointedTo) -> ArcBorrow<'a, T> { 398 // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous 399 // call to `Self::into_foreign`. 400 let inner = unsafe { NonNull::new_unchecked(ptr) }; 401 402 // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive 403 // for the lifetime of the returned value. 404 unsafe { ArcBorrow::new(inner) } 405 } 406 407 unsafe fn borrow_mut<'a>(ptr: *mut Self::PointedTo) -> ArcBorrow<'a, T> { 408 // SAFETY: The safety requirements for `borrow_mut` are a superset of the safety 409 // requirements for `borrow`. 410 unsafe { <Self as ForeignOwnable>::borrow(ptr) } 411 } 412 } 413 414 impl<T: ?Sized> Deref for Arc<T> { 415 type Target = T; 416 417 fn deref(&self) -> &Self::Target { 418 // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is 419 // safe to dereference it. 420 unsafe { &self.ptr.as_ref().data } 421 } 422 } 423 424 impl<T: ?Sized> AsRef<T> for Arc<T> { 425 fn as_ref(&self) -> &T { 426 self.deref() 427 } 428 } 429 430 /// # Examples 431 /// 432 /// ``` 433 /// # use core::borrow::Borrow; 434 /// # use kernel::sync::Arc; 435 /// struct Foo<B: Borrow<u32>>(B); 436 /// 437 /// // Owned instance. 438 /// let owned = Foo(1); 439 /// 440 /// // Shared instance. 441 /// let arc = Arc::new(1, GFP_KERNEL)?; 442 /// let shared = Foo(arc.clone()); 443 /// 444 /// let i = 1; 445 /// // Borrowed from `i`. 446 /// let borrowed = Foo(&i); 447 /// # Ok::<(), Error>(()) 448 /// ``` 449 impl<T: ?Sized> Borrow<T> for Arc<T> { 450 fn borrow(&self) -> &T { 451 self.deref() 452 } 453 } 454 455 impl<T: ?Sized> Clone for Arc<T> { 456 fn clone(&self) -> Self { 457 // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is 458 // safe to dereference it. 459 let refcount = unsafe { self.ptr.as_ref() }.refcount.get(); 460 461 // INVARIANT: C `refcount_inc` saturates the refcount, so it cannot overflow to zero. 462 // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is 463 // safe to increment the refcount. 464 unsafe { bindings::refcount_inc(refcount) }; 465 466 // SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`. 467 unsafe { Self::from_inner(self.ptr) } 468 } 469 } 470 471 impl<T: ?Sized> Drop for Arc<T> { 472 fn drop(&mut self) { 473 // SAFETY: By the type invariant, there is necessarily a reference to the object. We cannot 474 // touch `refcount` after it's decremented to a non-zero value because another thread/CPU 475 // may concurrently decrement it to zero and free it. It is ok to have a raw pointer to 476 // freed/invalid memory as long as it is never dereferenced. 477 let refcount = unsafe { self.ptr.as_ref() }.refcount.get(); 478 479 // INVARIANT: If the refcount reaches zero, there are no other instances of `Arc`, and 480 // this instance is being dropped, so the broken invariant is not observable. 481 // SAFETY: Also by the type invariant, we are allowed to decrement the refcount. 482 let is_zero = unsafe { bindings::refcount_dec_and_test(refcount) }; 483 if is_zero { 484 // The count reached zero, we must free the memory. 485 // 486 // SAFETY: The pointer was initialised from the result of `KBox::leak`. 487 unsafe { drop(KBox::from_raw(self.ptr.as_ptr())) }; 488 } 489 } 490 } 491 492 impl<T: ?Sized> From<UniqueArc<T>> for Arc<T> { 493 fn from(item: UniqueArc<T>) -> Self { 494 item.inner 495 } 496 } 497 498 impl<T: ?Sized> From<Pin<UniqueArc<T>>> for Arc<T> { 499 fn from(item: Pin<UniqueArc<T>>) -> Self { 500 // SAFETY: The type invariants of `Arc` guarantee that the data is pinned. 501 unsafe { Pin::into_inner_unchecked(item).inner } 502 } 503 } 504 505 /// A borrowed reference to an [`Arc`] instance. 506 /// 507 /// For cases when one doesn't ever need to increment the refcount on the allocation, it is simpler 508 /// to use just `&T`, which we can trivially get from an [`Arc<T>`] instance. 509 /// 510 /// However, when one may need to increment the refcount, it is preferable to use an `ArcBorrow<T>` 511 /// over `&Arc<T>` because the latter results in a double-indirection: a pointer (shared reference) 512 /// to a pointer ([`Arc<T>`]) to the object (`T`). An [`ArcBorrow`] eliminates this double 513 /// indirection while still allowing one to increment the refcount and getting an [`Arc<T>`] when/if 514 /// needed. 515 /// 516 /// # Invariants 517 /// 518 /// There are no mutable references to the underlying [`Arc`], and it remains valid for the 519 /// lifetime of the [`ArcBorrow`] instance. 520 /// 521 /// # Examples 522 /// 523 /// ``` 524 /// use kernel::sync::{Arc, ArcBorrow}; 525 /// 526 /// struct Example; 527 /// 528 /// fn do_something(e: ArcBorrow<'_, Example>) -> Arc<Example> { 529 /// e.into() 530 /// } 531 /// 532 /// let obj = Arc::new(Example, GFP_KERNEL)?; 533 /// let cloned = do_something(obj.as_arc_borrow()); 534 /// 535 /// // Assert that both `obj` and `cloned` point to the same underlying object. 536 /// assert!(core::ptr::eq(&*obj, &*cloned)); 537 /// # Ok::<(), Error>(()) 538 /// ``` 539 /// 540 /// Using `ArcBorrow<T>` as the type of `self`: 541 /// 542 /// ``` 543 /// use kernel::sync::{Arc, ArcBorrow}; 544 /// 545 /// struct Example { 546 /// a: u32, 547 /// b: u32, 548 /// } 549 /// 550 /// impl Example { 551 /// fn use_reference(self: ArcBorrow<'_, Self>) { 552 /// // ... 553 /// } 554 /// } 555 /// 556 /// let obj = Arc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?; 557 /// obj.as_arc_borrow().use_reference(); 558 /// # Ok::<(), Error>(()) 559 /// ``` 560 #[repr(transparent)] 561 #[cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, derive(core::marker::CoercePointee))] 562 pub struct ArcBorrow<'a, T: ?Sized + 'a> { 563 inner: NonNull<ArcInner<T>>, 564 _p: PhantomData<&'a ()>, 565 } 566 567 // This is to allow `ArcBorrow<U>` to be dispatched on when `ArcBorrow<T>` can be coerced into 568 // `ArcBorrow<U>`. 569 #[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))] 570 impl<T: ?Sized + core::marker::Unsize<U>, U: ?Sized> core::ops::DispatchFromDyn<ArcBorrow<'_, U>> 571 for ArcBorrow<'_, T> 572 { 573 } 574 575 impl<T: ?Sized> Clone for ArcBorrow<'_, T> { 576 fn clone(&self) -> Self { 577 *self 578 } 579 } 580 581 impl<T: ?Sized> Copy for ArcBorrow<'_, T> {} 582 583 impl<T: ?Sized> ArcBorrow<'_, T> { 584 /// Creates a new [`ArcBorrow`] instance. 585 /// 586 /// # Safety 587 /// 588 /// Callers must ensure the following for the lifetime of the returned [`ArcBorrow`] instance: 589 /// 1. That `inner` remains valid; 590 /// 2. That no mutable references to `inner` are created. 591 unsafe fn new(inner: NonNull<ArcInner<T>>) -> Self { 592 // INVARIANT: The safety requirements guarantee the invariants. 593 Self { 594 inner, 595 _p: PhantomData, 596 } 597 } 598 599 /// Creates an [`ArcBorrow`] to an [`Arc`] that has previously been deconstructed with 600 /// [`Arc::into_raw`] or [`Arc::as_ptr`]. 601 /// 602 /// # Safety 603 /// 604 /// * The provided pointer must originate from a call to [`Arc::into_raw`] or [`Arc::as_ptr`]. 605 /// * For the duration of the lifetime annotated on this `ArcBorrow`, the reference count must 606 /// not hit zero. 607 /// * For the duration of the lifetime annotated on this `ArcBorrow`, there must not be a 608 /// [`UniqueArc`] reference to this value. 609 pub unsafe fn from_raw(ptr: *const T) -> Self { 610 // SAFETY: The caller promises that this pointer originates from a call to `into_raw` on an 611 // `Arc` that is still valid. 612 let ptr = unsafe { ArcInner::container_of(ptr) }; 613 614 // SAFETY: The caller promises that the value remains valid since the reference count must 615 // not hit zero, and no mutable reference will be created since that would involve a 616 // `UniqueArc`. 617 unsafe { Self::new(ptr) } 618 } 619 } 620 621 impl<T: ?Sized> From<ArcBorrow<'_, T>> for Arc<T> { 622 fn from(b: ArcBorrow<'_, T>) -> Self { 623 // SAFETY: The existence of `b` guarantees that the refcount is non-zero. `ManuallyDrop` 624 // guarantees that `drop` isn't called, so it's ok that the temporary `Arc` doesn't own the 625 // increment. 626 ManuallyDrop::new(unsafe { Arc::from_inner(b.inner) }) 627 .deref() 628 .clone() 629 } 630 } 631 632 impl<T: ?Sized> Deref for ArcBorrow<'_, T> { 633 type Target = T; 634 635 fn deref(&self) -> &Self::Target { 636 // SAFETY: By the type invariant, the underlying object is still alive with no mutable 637 // references to it, so it is safe to create a shared reference. 638 unsafe { &self.inner.as_ref().data } 639 } 640 } 641 642 /// A refcounted object that is known to have a refcount of 1. 643 /// 644 /// It is mutable and can be converted to an [`Arc`] so that it can be shared. 645 /// 646 /// # Invariants 647 /// 648 /// `inner` always has a reference count of 1. 649 /// 650 /// # Examples 651 /// 652 /// In the following example, we make changes to the inner object before turning it into an 653 /// `Arc<Test>` object (after which point, it cannot be mutated directly). Note that `x.into()` 654 /// cannot fail. 655 /// 656 /// ``` 657 /// use kernel::sync::{Arc, UniqueArc}; 658 /// 659 /// struct Example { 660 /// a: u32, 661 /// b: u32, 662 /// } 663 /// 664 /// fn test() -> Result<Arc<Example>> { 665 /// let mut x = UniqueArc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?; 666 /// x.a += 1; 667 /// x.b += 1; 668 /// Ok(x.into()) 669 /// } 670 /// 671 /// # test().unwrap(); 672 /// ``` 673 /// 674 /// In the following example we first allocate memory for a refcounted `Example` but we don't 675 /// initialise it on allocation. We do initialise it later with a call to [`UniqueArc::write`], 676 /// followed by a conversion to `Arc<Example>`. This is particularly useful when allocation happens 677 /// in one context (e.g., sleepable) and initialisation in another (e.g., atomic): 678 /// 679 /// ``` 680 /// use kernel::sync::{Arc, UniqueArc}; 681 /// 682 /// struct Example { 683 /// a: u32, 684 /// b: u32, 685 /// } 686 /// 687 /// fn test() -> Result<Arc<Example>> { 688 /// let x = UniqueArc::new_uninit(GFP_KERNEL)?; 689 /// Ok(x.write(Example { a: 10, b: 20 }).into()) 690 /// } 691 /// 692 /// # test().unwrap(); 693 /// ``` 694 /// 695 /// In the last example below, the caller gets a pinned instance of `Example` while converting to 696 /// `Arc<Example>`; this is useful in scenarios where one needs a pinned reference during 697 /// initialisation, for example, when initialising fields that are wrapped in locks. 698 /// 699 /// ``` 700 /// use kernel::sync::{Arc, UniqueArc}; 701 /// 702 /// struct Example { 703 /// a: u32, 704 /// b: u32, 705 /// } 706 /// 707 /// fn test() -> Result<Arc<Example>> { 708 /// let mut pinned = Pin::from(UniqueArc::new(Example { a: 10, b: 20 }, GFP_KERNEL)?); 709 /// // We can modify `pinned` because it is `Unpin`. 710 /// pinned.as_mut().a += 1; 711 /// Ok(pinned.into()) 712 /// } 713 /// 714 /// # test().unwrap(); 715 /// ``` 716 pub struct UniqueArc<T: ?Sized> { 717 inner: Arc<T>, 718 } 719 720 impl<T> InPlaceInit<T> for UniqueArc<T> { 721 type PinnedSelf = Pin<Self>; 722 723 #[inline] 724 fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Self::PinnedSelf, E> 725 where 726 E: From<AllocError>, 727 { 728 UniqueArc::new_uninit(flags)?.write_pin_init(init) 729 } 730 731 #[inline] 732 fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E> 733 where 734 E: From<AllocError>, 735 { 736 UniqueArc::new_uninit(flags)?.write_init(init) 737 } 738 } 739 740 impl<T> InPlaceWrite<T> for UniqueArc<MaybeUninit<T>> { 741 type Initialized = UniqueArc<T>; 742 743 fn write_init<E>(mut self, init: impl Init<T, E>) -> Result<Self::Initialized, E> { 744 let slot = self.as_mut_ptr(); 745 // SAFETY: When init errors/panics, slot will get deallocated but not dropped, 746 // slot is valid. 747 unsafe { init.__init(slot)? }; 748 // SAFETY: All fields have been initialized. 749 Ok(unsafe { self.assume_init() }) 750 } 751 752 fn write_pin_init<E>(mut self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> { 753 let slot = self.as_mut_ptr(); 754 // SAFETY: When init errors/panics, slot will get deallocated but not dropped, 755 // slot is valid and will not be moved, because we pin it later. 756 unsafe { init.__pinned_init(slot)? }; 757 // SAFETY: All fields have been initialized. 758 Ok(unsafe { self.assume_init() }.into()) 759 } 760 } 761 762 impl<T> UniqueArc<T> { 763 /// Tries to allocate a new [`UniqueArc`] instance. 764 pub fn new(value: T, flags: Flags) -> Result<Self, AllocError> { 765 Ok(Self { 766 // INVARIANT: The newly-created object has a refcount of 1. 767 inner: Arc::new(value, flags)?, 768 }) 769 } 770 771 /// Tries to allocate a new [`UniqueArc`] instance whose contents are not initialised yet. 772 pub fn new_uninit(flags: Flags) -> Result<UniqueArc<MaybeUninit<T>>, AllocError> { 773 // INVARIANT: The refcount is initialised to a non-zero value. 774 let inner = KBox::try_init::<AllocError>( 775 try_init!(ArcInner { 776 // SAFETY: There are no safety requirements for this FFI call. 777 refcount: Opaque::new(unsafe { bindings::REFCOUNT_INIT(1) }), 778 data <- pin_init::uninit::<T, AllocError>(), 779 }? AllocError), 780 flags, 781 )?; 782 Ok(UniqueArc { 783 // INVARIANT: The newly-created object has a refcount of 1. 784 // SAFETY: The pointer from the `KBox` is valid. 785 inner: unsafe { Arc::from_inner(KBox::leak(inner).into()) }, 786 }) 787 } 788 } 789 790 impl<T> UniqueArc<MaybeUninit<T>> { 791 /// Converts a `UniqueArc<MaybeUninit<T>>` into a `UniqueArc<T>` by writing a value into it. 792 pub fn write(mut self, value: T) -> UniqueArc<T> { 793 self.deref_mut().write(value); 794 // SAFETY: We just wrote the value to be initialized. 795 unsafe { self.assume_init() } 796 } 797 798 /// Unsafely assume that `self` is initialized. 799 /// 800 /// # Safety 801 /// 802 /// The caller guarantees that the value behind this pointer has been initialized. It is 803 /// *immediate* UB to call this when the value is not initialized. 804 pub unsafe fn assume_init(self) -> UniqueArc<T> { 805 let inner = ManuallyDrop::new(self).inner.ptr; 806 UniqueArc { 807 // SAFETY: The new `Arc` is taking over `ptr` from `self.inner` (which won't be 808 // dropped). The types are compatible because `MaybeUninit<T>` is compatible with `T`. 809 inner: unsafe { Arc::from_inner(inner.cast()) }, 810 } 811 } 812 813 /// Initialize `self` using the given initializer. 814 pub fn init_with<E>(mut self, init: impl Init<T, E>) -> core::result::Result<UniqueArc<T>, E> { 815 // SAFETY: The supplied pointer is valid for initialization. 816 match unsafe { init.__init(self.as_mut_ptr()) } { 817 // SAFETY: Initialization completed successfully. 818 Ok(()) => Ok(unsafe { self.assume_init() }), 819 Err(err) => Err(err), 820 } 821 } 822 823 /// Pin-initialize `self` using the given pin-initializer. 824 pub fn pin_init_with<E>( 825 mut self, 826 init: impl PinInit<T, E>, 827 ) -> core::result::Result<Pin<UniqueArc<T>>, E> { 828 // SAFETY: The supplied pointer is valid for initialization and we will later pin the value 829 // to ensure it does not move. 830 match unsafe { init.__pinned_init(self.as_mut_ptr()) } { 831 // SAFETY: Initialization completed successfully. 832 Ok(()) => Ok(unsafe { self.assume_init() }.into()), 833 Err(err) => Err(err), 834 } 835 } 836 } 837 838 impl<T: ?Sized> From<UniqueArc<T>> for Pin<UniqueArc<T>> { 839 fn from(obj: UniqueArc<T>) -> Self { 840 // SAFETY: It is not possible to move/replace `T` inside a `Pin<UniqueArc<T>>` (unless `T` 841 // is `Unpin`), so it is ok to convert it to `Pin<UniqueArc<T>>`. 842 unsafe { Pin::new_unchecked(obj) } 843 } 844 } 845 846 impl<T: ?Sized> Deref for UniqueArc<T> { 847 type Target = T; 848 849 fn deref(&self) -> &Self::Target { 850 self.inner.deref() 851 } 852 } 853 854 impl<T: ?Sized> DerefMut for UniqueArc<T> { 855 fn deref_mut(&mut self) -> &mut Self::Target { 856 // SAFETY: By the `Arc` type invariant, there is necessarily a reference to the object, so 857 // it is safe to dereference it. Additionally, we know there is only one reference when 858 // it's inside a `UniqueArc`, so it is safe to get a mutable reference. 859 unsafe { &mut self.inner.ptr.as_mut().data } 860 } 861 } 862 863 /// # Examples 864 /// 865 /// ``` 866 /// # use core::borrow::Borrow; 867 /// # use kernel::sync::UniqueArc; 868 /// struct Foo<B: Borrow<u32>>(B); 869 /// 870 /// // Owned instance. 871 /// let owned = Foo(1); 872 /// 873 /// // Owned instance using `UniqueArc`. 874 /// let arc = UniqueArc::new(1, GFP_KERNEL)?; 875 /// let shared = Foo(arc); 876 /// 877 /// let i = 1; 878 /// // Borrowed from `i`. 879 /// let borrowed = Foo(&i); 880 /// # Ok::<(), Error>(()) 881 /// ``` 882 impl<T: ?Sized> Borrow<T> for UniqueArc<T> { 883 fn borrow(&self) -> &T { 884 self.deref() 885 } 886 } 887 888 /// # Examples 889 /// 890 /// ``` 891 /// # use core::borrow::BorrowMut; 892 /// # use kernel::sync::UniqueArc; 893 /// struct Foo<B: BorrowMut<u32>>(B); 894 /// 895 /// // Owned instance. 896 /// let owned = Foo(1); 897 /// 898 /// // Owned instance using `UniqueArc`. 899 /// let arc = UniqueArc::new(1, GFP_KERNEL)?; 900 /// let shared = Foo(arc); 901 /// 902 /// let mut i = 1; 903 /// // Borrowed from `i`. 904 /// let borrowed = Foo(&mut i); 905 /// # Ok::<(), Error>(()) 906 /// ``` 907 impl<T: ?Sized> BorrowMut<T> for UniqueArc<T> { 908 fn borrow_mut(&mut self) -> &mut T { 909 self.deref_mut() 910 } 911 } 912 913 impl<T: fmt::Display + ?Sized> fmt::Display for UniqueArc<T> { 914 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 915 fmt::Display::fmt(self.deref(), f) 916 } 917 } 918 919 impl<T: fmt::Display + ?Sized> fmt::Display for Arc<T> { 920 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 921 fmt::Display::fmt(self.deref(), f) 922 } 923 } 924 925 impl<T: fmt::Debug + ?Sized> fmt::Debug for UniqueArc<T> { 926 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 927 fmt::Debug::fmt(self.deref(), f) 928 } 929 } 930 931 impl<T: fmt::Debug + ?Sized> fmt::Debug for Arc<T> { 932 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 933 fmt::Debug::fmt(self.deref(), f) 934 } 935 } 936