1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
use core::fmt::{self, Pointer, Formatter}; use core::marker::PhantomData; use core::mem; use core::ptr::{self, NonNull}; use core::sync::atomic; use core::sync::atomic::Ordering::{Acquire, Relaxed, Release, SeqCst}; use crate::block::{self, Block}; use crate::alloc::{AllocTag, Hold, Holder, HoldError, Stow, TryClone}; use crate::lease::{arc, ArcHeader, ArcError, Lease, Mut, Ref, Hard}; use crate::resident::{Resident, ResidentStow}; /// A thread-safe, atomically counted, undereferenceable soft reference to a /// `Resident` occupying a shared, `Hold`-allocated memory block. pub struct Soft<'a, R: Resident> { /// Pointer to the resident memory block. data: NonNull<R::Data>, /// Variant over ArcHeader<R::Meta>, with drop check. meta_lifetime: PhantomData<ArcHeader<R::Meta>>, /// Variant over 'a. hold_lifetime: PhantomData<&'a ()>, } unsafe impl<'a, R: Resident> Send for Soft<'a, R> where R::Data: Send, R::Meta: Send { } unsafe impl<'a, R: Resident> Sync for Soft<'a, R> where R::Data: Sync, R::Meta: Sync { } impl<'a, R: Resident> Soft<'a, R> { /// Constructs a `Soft` lease from a raw pointer returned by `Soft::into_raw`. #[inline] pub unsafe fn from_raw(data: *mut R::Data) -> Soft<'a, R> { Soft { data: NonNull::new_unchecked(data), meta_lifetime: PhantomData, hold_lifetime: PhantomData, } } /// Returns a pointer to the `ArcHeader` preceding the shared resident. #[inline] fn header(&self) -> *mut ArcHeader<R::Meta> { arc::header::<R>(self.data.as_ptr()) } /// Returns the number of hard references to the shared resident. /// Does not traverse relocations. #[inline] pub fn hard_count(&self) -> usize { unsafe { (*self.header()).hard_count() } } /// Returns the number of soft references to the shared resident. /// Does not traverse relocations. #[inline] pub fn soft_count(&self) -> usize { unsafe { (*self.header()).soft_count() } } /// Returns the number of immutable references to the shared resident. /// Does not traverse relocations. #[inline] pub fn ref_count(&self) -> usize { unsafe { (*self.header()).ref_count() } } /// Returns `true` if the shared resident is mutably referenced. /// Does not traverse relocations. #[inline] pub fn is_mut(&self) -> bool { unsafe { (*self.header()).is_mut() } } /// Returns `true` if the shared resident has relocated to a new arc. #[inline] pub fn is_relocated(&self) -> bool { unsafe { (*self.header()).is_relocated() } } /// Returns `true` if the shared resident is immutably or mutably referenced. /// Does not traverse relocations. #[inline] pub fn is_aliased(&self) -> bool { unsafe { (*self.header()).is_aliased() } } /// Returns a new mutable lease to the shared resident, traversing any /// completed moves, and returning an error if the reisdent is currently /// being relocated, or if there are any outstanding mutable or immutable /// leases, or if the shared resident has already been dropped, or if there /// is atomic operation contention, or if obtaining the lease would cause /// a reference count overflow. /// /// # Safety /// /// Mutable leases can coexist with hard and soft leases to the same /// resident. This can cause a future deadlock if a thread holding a /// mutable lease to a resident attempts to convert another hard or soft /// lease to the same resident into a mutable or immutable lease. pub unsafe fn poll_mut(&self) -> Result<Mut<'a, R>, ArcError> { // Get a pointer to the shared resident. let data = self.data.as_ptr(); // Get a pointer to the arc header preceding the resident. let header = arc::header::<R>(data); // Load the status field; synchronized by subsequent CAS. let old_status = (*header).status.load(Relaxed); // Check if the shared resident can be mutably referenced. if old_status & arc::READ_LOCKED_MASK == 0 { // Extract the hard reference count from the status field. let old_hard_count = old_status & arc::HARD_COUNT_MASK; // Check if the boxed value is still live. if old_hard_count == 0 { // The shared resident has already been dropped. return Err(ArcError::Cleared); } // Increment the hard reference count. let new_hard_count = old_hard_count.wrapping_add(1); // Check if the incremented hard reference count overflows its bit field. if new_hard_count > arc::HARD_COUNT_MAX { return Err(ArcError::HardCountOverflow); } // Clear the hard reference count bit field. let new_status = old_status & !arc::HARD_COUNT_MASK; // Splice the incremented hard reference count into the status field, and set the mut flag. let new_status = new_status | new_hard_count | arc::MUT_FLAG; // Atomically update the status field, synchronizing with reference releases. match (*header).status.compare_exchange(old_status, new_status, Acquire, Relaxed) { // CAS succeeded; return a new Mut lease. Ok(_) => return Ok(Mut::from_raw(data)), // CAS failed. Err(_) => (), } } else if old_status & arc::RELOCATED_FLAG != 0 { // Synchronize with relocation initiation. atomic::fence(Release); // Get a fat pointer to the relocated resident, synchronizing with relocation completion. let relocation = block::set_address(data, (*header).relocation.load(Acquire)); // Check if the relocation has completed. if !relocation.is_null() { // Temporarily reify the arc's relocation lease. let relocation = mem::transmute::<*mut R::Data, Hard<'a, R>>(relocation); // Recurse into the relocated lease. let lease = relocation.poll_mut(); // Discard the borrowed relocation lease. mem::forget(relocation); // Return the newly acquired lease. return lease; } } // Unable to acquire a mutable lease at this time. Err(ArcError::Contended) } /// Returns a new mutable lease to the shared resident, traversing any /// completed moves, waiting for any concurrent relocation to complete /// and for any outstanding mutable or immutable leases to drop, and /// returning an error if the shared resident has already been dropped, /// or if obtaining the lease would cause a reference count overflow. /// /// # Safety /// /// Deadlocks if the current thread already holds a mutable or immutable /// lease to the shared resident. Can cause a future deadlock if a thread /// holding a mutable lease to a resident attempts to convert another hard /// or soft lease to the same resident into a mutable or immutable lease. pub unsafe fn try_to_mut(&self) -> Result<Mut<'a, R>, ArcError> { // Get a pointer to the shared resident. let data = self.data.as_ptr(); // Get a pointer to the arc header preceding the resident. let header = arc::header::<R>(data); // Load the status field; synchronized by subsequent CAS. let mut old_status = (*header).status.load(Relaxed); // Spin until a mutable reference is acquired. loop { // Check if the shared resident can be mutably referenced. if old_status & arc::READ_LOCKED_MASK == 0 { // Extract the hard reference count from the status field. let old_hard_count = old_status & arc::HARD_COUNT_MASK; // Check if the shared resident is still alive. if old_hard_count == 0 { // The shared resident has already been dropped. return Err(ArcError::Cleared); } // Increment the hard reference count. let new_hard_count = old_hard_count.wrapping_add(1); // Check if the incremented hard reference count overflows its bit field. if new_hard_count > arc::HARD_COUNT_MAX { return Err(ArcError::HardCountOverflow); } // Clear the hard reference count bit field. let new_status = old_status & !arc::HARD_COUNT_MASK; // Splice the incremented hard reference count into the status field, and set the mut flag. let new_status = new_status | new_hard_count | arc::MUT_FLAG; // Atomically update the status field, synchronizing with reference releases. match (*header).status.compare_exchange_weak(old_status, new_status, Acquire, Relaxed) { // CAS succeeded; return a new Mut lease. Ok(_) => return Ok(Mut::from_raw(data)), // CAS failed; update the status field and try again. Err(status) => old_status = status, } } else { // Check if the shared resident has relocated. if old_status & arc::RELOCATED_FLAG != 0 { // Synchronize with relocation initiation. atomic::fence(Release); // Get a fat pointer to the relocated resident, synchronizing with relocation completion. let relocation = block::set_address(data, (*header).relocation.load(Acquire)); // Check if the relocation has completed. if !relocation.is_null() { // Temporarily reify the arc's relocation lease. let relocation = mem::transmute::<*mut R::Data, Hard<'a, R>>(relocation); // Recurse into the relocated lease. let lease = relocation.try_to_mut(); // Discard the borrowed relocation lease. mem::forget(relocation); // Return the newly acquired lease. return lease; } } // Reload the status field and spin. old_status = (*header).status.load(Relaxed); } } } /// Returns a new mutable lease to the shared resident, traversing any /// completed moves, and waiting for any concurrent relocation to complete /// and for any outstanding mutable or immutable leases to drop. /// /// # Safety /// /// Deadlocks if the current thread already holds a mutable or immutable /// lease to the shared resident. Can cause a future deadlock if a thread /// holding a mutable lease to a resident attempts to convert another hard /// or soft lease to the same resident into a mutable or immutable lease. /// /// # Panics /// /// Panics if the shared resident has already been dropped, or if obtaining /// the lease would cause a reference count overflow. pub unsafe fn to_mut(&self) -> Mut<'a, R> { self.try_to_mut().unwrap() } /// Converts this soft lease into a mutable lease to the shared resident, /// traversing any completed moves, waiting for any concurrnet relocation /// to complete and for any outstanding mutable or immutable leases to drop, /// and returning an error if the shared resident has already been dropped, /// or if obtaining the lease would cause a reference count overflow. /// /// # Safety /// /// Deadlocks if the current thread already holds a mutable or immutable /// lease to the shared resident. Can cause a future deadlock if a thread /// holding a mutable lease to a resident attempts to convert another hard /// or soft lease to the same resident into a mutable or immutable lease. pub unsafe fn try_into_mut(self) -> Result<Mut<'a, R>, ArcError> { // Get a pointer to the shared resident. let data = self.data.as_ptr(); // Get a pointer to the arc header preceding the resident. let header = arc::header::<R>(data); // Load the status field; synchronized by subsequent CAS. let mut old_status = (*header).status.load(Relaxed); // Spin until a mutable reference is acquired. loop { // Check if the shared resident can be mutably referenced. if old_status & arc::READ_LOCKED_MASK == 0 { // Extract the hard reference count from the status field. let old_hard_count = old_status & arc::HARD_COUNT_MASK; // Check if the shared resident is still alive. if old_hard_count == 0 { // The shared resident has already been dropped. return Err(ArcError::Cleared); } // Increment the hard reference count. let new_hard_count = old_hard_count.wrapping_add(1); // Check if the incremented hard reference count overflows its bit field. if new_hard_count > arc::HARD_COUNT_MAX { return Err(ArcError::HardCountOverflow); } // Extract the soft reference count from the status field. let old_soft_count = (old_status & arc::SOFT_COUNT_MASK) >> arc::SOFT_COUNT_SHIFT; // Decrement the soft reference count, checking for underflow. let new_soft_count = match old_soft_count.checked_sub(1) { Some(soft_count) => soft_count, None => panic!("soft count underflow"), }; // Clear the hard and soft reference count fields. let new_status = old_status & !(arc::HARD_COUNT_MASK | arc::SOFT_COUNT_MASK); // Splice the incremented hard and decremented soft reference counts into the status field, // and set the mut flag. let new_status = new_status | new_hard_count | new_soft_count << arc::SOFT_COUNT_SHIFT | arc::MUT_FLAG; // Atomically update the status field, synchronizing with reference acquires and releases. match (*header).status.compare_exchange_weak(old_status, new_status, Acquire, Relaxed) { // CAS succeeded. Ok(_) => { // Discard the original lease, whose soft reference we took. mem::forget(self); // Return a new Mut lease. return Ok(Mut::from_raw(data)); }, // CAS failed; update the status field and try again. Err(status) => old_status = status, } } else { // Check if the shared resident has relocated. if old_status & arc::RELOCATED_FLAG != 0 { // Synchronize with relocation initiation. atomic::fence(Release); // Get a fat pointer to the relocated resident, synchronizing with relocation completion. let relocation = block::set_address(data, (*header).relocation.load(Acquire)); // Check if the relocation has completed. if !relocation.is_null() { // Temporarily reify the arc's relocation lease. let relocation = mem::transmute::<*mut R::Data, Hard<'a, R>>(relocation); // Recurse into the relocated lease. let lease = relocation.try_to_mut(); // Discard the borrowed relocation lease. mem::forget(relocation); // Return the newly acquired lease. return lease; } } // Reload the status field and spin. old_status = (*header).status.load(Relaxed); } } } /// Converts this soft lease into a mutable lease to the shared resident, /// traversing any completed moves, waiting for any concurrnet relocation /// to complete and for any outstanding mutable or immutable leases to drop, /// and returning an error if the shared resident has already been dropped, /// or if obtaining the lease would cause a reference count overflow. /// /// # Safety /// /// Deadlocks if the current thread already holds a mutable or immutable /// lease to the shared resident. Can cause a future deadlock if a thread /// holding a mutable lease to a resident attempts to convert another hard /// or soft lease to the same resident into a mutable or immutable lease. /// /// # Panics /// /// Panics if the shared resident has already been dropped, or if obtaining /// the lease would cause a reference count overflow. pub unsafe fn into_mut(self) -> Mut<'a, R> { self.try_into_mut().unwrap() } /// Returns a new immutable lease to the shared resident, traversing any /// completed moves, and returning an error if the resident is currently /// being relocated, or if there is an outstanding mutable lease, or if /// the shared resident has already been dropped, or if there is atomic /// operation contention, or if obtaining the lease would cause a reference /// count overflow. pub fn poll_ref(&self) -> Result<Ref<'a, R>, ArcError> { unsafe { // Get a pointer to the shared resident. let data = self.data.as_ptr(); // Get a pointer to the arc header preceding the resident. let header = arc::header::<R>(data); // Load the status field; synchronized by subsequent CAS. let old_status = (*header).status.load(Relaxed); // Check if the shared resident is not mutably referenced, and is not concurrently relocating. if old_status & arc::WRITE_LOCKED_MASK == 0 { // Extract the hard reference count from the status field. let old_hard_count = old_status & arc::HARD_COUNT_MASK; // Check if the shared resident is still alive. if old_hard_count == 0 { // The shared resident has already been dropped. return Err(ArcError::Cleared); } // Increment the hard reference count. let new_hard_count = old_hard_count.wrapping_add(1); // Check if the incremented hard reference count overflows its bit field. if new_hard_count > arc::HARD_COUNT_MAX { return Err(ArcError::HardCountOverflow); } // Extract the immutable reference count from the status field. let old_ref_count = (old_status & arc::REF_COUNT_MASK) >> arc::REF_COUNT_SHIFT; // Increment the immutable reference count. let new_ref_count = old_ref_count.wrapping_add(1); // Check if the incremented immutable reference count overflows its bit field. if new_ref_count > arc::REF_COUNT_MAX { return Err(ArcError::RefCountOverflow); } // Clear the hard and immutable reference count bit fields. let new_status = old_status & !(arc::HARD_COUNT_MASK | arc::REF_COUNT_MASK); // Splice the incremented hard and immutable reference counts into the status field. let new_status = new_status | new_hard_count | new_ref_count << arc::REF_COUNT_SHIFT; // Atomically update the status field, synchronizing with reference releases. match (*header).status.compare_exchange(old_status, new_status, Acquire, Relaxed) { // CAS succeeded; return a new Ref lease. Ok(_) => return Ok(Ref::from_raw(data)), // CAS failed. Err(_) => (), } } else if old_status & arc::RELOCATED_FLAG != 0 { // Synchronize with relocation initiation. atomic::fence(Release); // Get a fat pointer to the relocated resident, synchronizing with relocation completion. let relocation = block::set_address(data, (*header).relocation.load(Acquire)); // Check if the relocation has completed. if !relocation.is_null() { // Temporarily reify the arc's relocation lease. let relocation = mem::transmute::<*mut R::Data, Hard<'a, R>>(relocation); // Recurse into the relocated lease. let lease = relocation.poll_ref(); // Discard the borrowed relocation lease. mem::forget(relocation); // Return the newly acquired lease. return lease; } } // Unable to acquire an immutable lease at this time. Err(ArcError::Contended) } } /// Returns a new immutable lease to the shared resident, traversing any /// completed moves, waiting for any concurrent relocation to complete /// and for any outstanding mutable lease to drop, and returning an error /// if the shared resident has already been dropped, or if obtaining the /// lease would cause a reference count overflow. pub fn try_to_ref(&self) -> Result<Ref<'a, R>, ArcError> { unsafe { // Get a pointer to the shared resident. let data = self.data.as_ptr(); // Get a pointer to the arc header preceding the resident. let header = arc::header::<R>(data); // Load the status field; synchronized by subsequent CAS. let mut old_status = (*header).status.load(Relaxed); // Spin until an immutable reference is acquired. loop { // Check if the shared resident is not mutably referenced, and is not concurrently relocating. if old_status & arc::WRITE_LOCKED_MASK == 0 { // Extract the hard reference count from the status field. let old_hard_count = old_status & arc::HARD_COUNT_MASK; // Check if the shared resident is still alive. if old_hard_count == 0 { // The shared resident has already been dropped. return Err(ArcError::Cleared); } // Increment the hard reference count. let new_hard_count = old_hard_count.wrapping_add(1); // Check if the incremented hard reference count overflows its bit field. if new_hard_count > arc::HARD_COUNT_MAX { return Err(ArcError::HardCountOverflow); } // Extract the immutable reference count from the status field. let old_ref_count = (old_status & arc::REF_COUNT_MASK) >> arc::REF_COUNT_SHIFT; // Increment the immutable reference count. let new_ref_count = old_ref_count.wrapping_add(1); // Check if the incremented immutable reference count overflows its bit field. if new_ref_count > arc::REF_COUNT_MAX { return Err(ArcError::RefCountOverflow); } // Clear the hard and immutable reference count bit fields. let new_status = old_status & !(arc::HARD_COUNT_MASK | arc::REF_COUNT_MASK); // Splice the incremented hard and immutable reference counts into the status field. let new_status = new_status | new_hard_count | new_ref_count << arc::REF_COUNT_SHIFT; // Atomically update the status field, synchronizing with reference releases. match (*header).status.compare_exchange_weak(old_status, new_status, Acquire, Relaxed) { // CAS succeeded; return a new Ref lease. Ok(_) => return Ok(Ref::from_raw(data)), // CAS failed; update the status field and trye again. Err(status) => old_status = status, } } else { // Check if the shared resident has relocated. if old_status & arc::RELOCATED_FLAG != 0 { // Synchronize with relocation initiation. atomic::fence(Release); // Get a fat pointer to the relocated resident, synchronizing with relocation completion. let relocation = block::set_address(data, (*header).relocation.load(Acquire)); // Check if the relocation has completed. if !relocation.is_null() { // Temporarily reify the arc's relocation lease. let relocation = mem::transmute::<*mut R::Data, Hard<'a, R>>(relocation); // Recurse into the relocated lease. let lease = relocation.try_to_ref(); // Discard the borrowed relocation lease. mem::forget(relocation); // Return the newly acquired lease. return lease; } } // Reload the status field and spin. old_status = (*header).status.load(Relaxed); } } } } /// Returns a new immutable lease to the shared resident, traversing any /// completed moves, and waiting for any concurrent relocation to complete /// and for any outstanding mutable lease to drop. /// /// # Panics /// /// Panics if the shared resident has already been dropped, or if obtaining /// the lease would cause a reference count overflow. pub fn to_ref(&self) -> Ref<'a, R> { self.try_to_ref().unwrap() } /// Converts this soft lease into an immutable lease to the shared resident, /// traversing any completed moves, waiting for any concurrent relocation to /// complete and for any outstanding mutable lease to drop, and returning an /// error if the shared resident has already been dropped, or if obtaining /// the lease would cause a reference count overflow. pub fn try_into_ref(self) -> Result<Ref<'a, R>, ArcError> { unsafe { // Get a pointer to the shared resident. let data = self.data.as_ptr(); // Get a pointer to the arc header preceding the resident. let header = arc::header::<R>(data); // Load the status field; synchronized by subsequent CAS. let mut old_status = (*header).status.load(Relaxed); // Spin until an immutable reference is acquired. loop { // Check if the shared resident is not mutably referenced, and is not concurrently relocating. if old_status & arc::WRITE_LOCKED_MASK == 0 { // Extract the hard reference count from the status field. let old_hard_count = old_status & arc::HARD_COUNT_MASK; // Check if the shared resident is still alive. if old_hard_count == 0 { // The shared resident has already been dropped. return Err(ArcError::Cleared); } // Increment the hard reference count. let new_hard_count = old_hard_count.wrapping_add(1); // Check if the incremented hard reference count overflows its bit field. if new_hard_count > arc::HARD_COUNT_MAX { return Err(ArcError::HardCountOverflow); } // Extract the soft reference count from the status field. let old_soft_count = (old_status & arc::SOFT_COUNT_MASK) >> arc::SOFT_COUNT_SHIFT; // Decrement the soft reference count, checking for underflow. let new_soft_count = match old_soft_count.checked_sub(1) { Some(soft_count) => soft_count, None => panic!("soft count underflow"), }; // Extract the immutable reference count from the status field. let old_ref_count = (old_status & arc::REF_COUNT_MASK) >> arc::REF_COUNT_SHIFT; // Increment the immutable reference count. let new_ref_count = old_ref_count.wrapping_add(1); // Check if the incremented immutable reference count overflows its bit field. if new_ref_count > arc::REF_COUNT_MAX { return Err(ArcError::RefCountOverflow); } // Clear the hard, soft, and immutable reference count bit fields. let new_status = old_status & !(arc::HARD_COUNT_MASK | arc::SOFT_COUNT_MASK | arc::REF_COUNT_MASK); // Splice the incremented hard, decremented soft, and incremented immutable reference counts // into the status field. let new_status = new_status | new_hard_count | new_soft_count << arc::SOFT_COUNT_SHIFT | new_ref_count << arc::REF_COUNT_SHIFT; // Atomically update the status field, synchronizing with reference acquires and releases. match (*header).status.compare_exchange_weak(old_status, new_status, SeqCst, Relaxed) { // CAS succeeded. Ok(_) => { // Discard the original lease, whose soft reference we released. mem::forget(self); // Return a new Ref lease. return Ok(Ref::from_raw(data)); }, // CAS failed; update the status field and try again. Err(status) => old_status = status, } } else { // Check if the shared resident has relocated. if old_status & arc::RELOCATED_FLAG != 0 { // Synchronize with relocation initiation. atomic::fence(Release); // Get a fat pointer to the relocated resident, synchronizing with relocation completion. let relocation = block::set_address(data, (*header).relocation.load(Acquire)); // Check if the relocation has completed. if !relocation.is_null() { // Temporarily reify the arc's relocation lease. let relocation = mem::transmute::<*mut R::Data, Hard<'a, R>>(relocation); // Recurse into the relocated lease. let lease = relocation.try_to_ref(); // Discard the borrowed relocation lease. mem::forget(relocation); // Return the newly acquired lease. return lease; } } // Reload the status field and spin. old_status = (*header).status.load(Relaxed); } } } } /// Converts this soft lease into an immutable lease to the shared resident, /// traversing any completed moves, and waiting for any concurrent /// relocation to complete and for any outstanding mutable lease to drop. /// /// # Panics /// /// Panics if the shared resident has already been dropped, or if obtaining /// the lease would cause a reference count overflow. pub fn into_ref(self) -> Ref<'a, R> { self.try_into_ref().unwrap() } /// Returns a new hard lease to the shared resident, without traversing /// any moves, returning an error if the shared resident has already been /// dropped or if obtaining the lease would cause a reference count /// overflow. pub fn try_to_hard(&self) -> Result<Hard<'a, R>, ArcError> { unsafe { // Get a pointer to the shared resident. let data = self.data.as_ptr(); // Get a pointer to the arc header preceding the resident. let header = arc::header::<R>(data); // Load the status field; synchronized by subsequent CAS. let mut old_status = (*header).status.load(Relaxed); // Spin until a hard reference is acquired. loop { // Extract the hard reference count from the status field. let old_hard_count = old_status & arc::HARD_COUNT_MASK; // Check if the shared resident is still alive. if old_hard_count == 0 { // The shared resident has already been dropped. return Err(ArcError::Cleared); } // Increment the hard reference count. let new_hard_count = old_hard_count.wrapping_add(1); // Check if the incremented hard reference count overflows its bit field. if new_hard_count > arc::HARD_COUNT_MAX { return Err(ArcError::HardCountOverflow); } // Clear the hard reference count bit field. let new_status = old_status & !arc::HARD_COUNT_MASK; // Splice the incremented hard reference count into the status field. let new_status = new_status | new_hard_count; // Atomically update the status field, synchronizing with reference releases. match (*header).status.compare_exchange_weak(old_status, new_status, Acquire, Relaxed) { // CAS succeeded; return a new Hard lease. Ok(_) => return Ok(Hard::from_raw(data)), // CAS failed; update the status field and try again. Err(status) => old_status = status, } } } } /// Returns a new hard lease to the shared resident, without traversing /// any moves. /// /// # Panics /// /// Panics if the shared resident has already been dropped or if obtaining /// the lease would cause a reference count overflow. pub fn to_hard(&self) -> Hard<'a, R> { self.try_to_hard().unwrap() } /// Converts this soft lease into a hard lease, without traversing any /// moves, returning an error if the shared resident has already been /// dropped, or if obtaining the lease would cause a reference count /// overflow. pub fn try_into_hard(self) -> Result<Hard<'a, R>, ArcError> { unsafe { // Get a pointer to the shared resident. let data = self.data.as_ptr(); // Get a pointer to the arc header preceding the resident. let header = arc::header::<R>(data); // Load the status field; synchronized by subsequent CAS. let mut old_status = (*header).status.load(Relaxed); // Spin until a hard reference is acquired. loop { // Extract the hard reference count from the status field. let old_hard_count = old_status & arc::HARD_COUNT_MASK; // Check if the shared resident is still alive. if old_hard_count == 0 { // The shared resident has already been dropped. return Err(ArcError::Cleared); } // Increment the hard reference count. let new_hard_count = old_hard_count.wrapping_add(1); // Check if the incremented hard reference count overflows its bit field. if new_hard_count > arc::HARD_COUNT_MAX { return Err(ArcError::HardCountOverflow); } // Extract the soft reference count from the status field. let old_soft_count = (old_status & arc::SOFT_COUNT_MASK) >> arc::SOFT_COUNT_SHIFT; // Decrement the soft reference count, checking for underflow. let new_soft_count = match old_soft_count.checked_sub(1) { Some(soft_count) => soft_count, None => panic!("soft count underflow"), }; // Clear the hard and soft reference count bit fields. let new_status = old_status & !(arc::HARD_COUNT_MASK | arc::SOFT_COUNT_MASK); // Splice the incremented hard and decremented soft reference counts into the status field. let new_status = new_status | new_hard_count | new_soft_count << arc::SOFT_COUNT_SHIFT; // Atomically update the status field, synchronizing with reference acquires and releases. match (*header).status.compare_exchange_weak(old_status, new_status, SeqCst, Relaxed) { // CAS succeeded. Ok(_) => { // Discard the original lease, whose soft reference we released. mem::forget(self); // Return a new Hard lease. return Ok(Hard::from_raw(data)); }, // CAS failed; update the status field and try again. Err(status) => old_status = status, } } } } /// Converts this soft lease into a hard lease, without traversing /// any moves. /// /// # Panics /// /// Panics if the shared resident has already been dropped, or if obtaining /// the lease would cause a reference count overflow. pub fn into_hard(self) -> Hard<'a, R> { self.try_into_hard().unwrap() } /// Converts this soft lease into a raw pointer to the shared resident. /// Use `Soft::from_raw` to reconstitute the returned pointer back into /// a soft lease. /// /// # Safety /// /// The shared resident is not pinned to the returned memory address, and /// may be concurrently relocation at any time. The resident may not be /// hard referenced, and could be dropped at any time. A memory leak will /// occur unless the returned pointer is eventually converted back into a /// soft lease and dropped. #[inline] pub unsafe fn into_raw(self) -> *mut R::Data { let data = self.data.as_ptr(); mem::forget(self); data } /// Returns a raw pointer to the shared resident. /// /// # Safety /// /// The shared resident may be uninitialized, or mutably aliased, /// or may have been relocated, or dropped. #[inline] pub unsafe fn as_ptr_unchecked(&self) -> *mut R::Data { self.data.as_ptr() } } impl<'a, R: Resident> Holder<'a> for Soft<'a, R> { #[inline] fn holder(&self) -> &'a dyn Hold<'a> { AllocTag::from_ptr(self.header() as *mut u8).holder() } } impl<'a, R: Resident> Lease for Soft<'a, R> { type Data = R::Data; type Meta = R::Meta; #[inline] fn data(&self) -> *mut R::Data { self.data.as_ptr() } #[inline] fn meta(&self) -> *mut R::Meta { unsafe { &mut (*self.header()).meta } } } impl<'a, R: Resident> TryClone for Soft<'a, R> { fn try_clone(&self) -> Result<Soft<'a, R>, HoldError> { unsafe { // Get a pointer to the shared resident. let data = self.data.as_ptr(); // Get a pointer to the arc header preceding the resident. let header = arc::header::<R>(data); // Load the status field; synchronized by subsequent CAS. let mut old_status = (*header).status.load(Relaxed); // Spin until a soft reference is acquired. loop { // Extract the soft reference count from the status field. let old_soft_count = (old_status & arc::SOFT_COUNT_MASK) >> arc::SOFT_COUNT_SHIFT; // Increment the soft reference count. let new_soft_count = old_soft_count.wrapping_add(1); // Check if the incremented soft reference count overflows its bit field. if new_soft_count > arc::SOFT_COUNT_MAX { return Err(HoldError::Unsupported("soft count overflow")); } // Clear the soft reference count field. let new_status = old_status & !arc::SOFT_COUNT_MASK; // Splice the incremented soft reference count into the status field. let new_status = new_status | new_soft_count << arc::SOFT_COUNT_SHIFT; // Atomically update the status field, synchronizing with reference releases. match (*header).status.compare_exchange_weak(old_status, new_status, Acquire, Relaxed) { // CAS succeeded; return a new Soft lease. Ok(_) => return Ok(Soft::from_raw(data)), // CAS failed; update the status field and try again. Err(status) => old_status = status, } } } } } impl<'a, R: Resident> Clone for Soft<'a, R> { fn clone(&self) -> Soft<'a, R> { self.try_clone().unwrap() } } impl<'a, 'b, R: ResidentStow<'b, Hard<'a, R>, Hard<'b, R>>> Stow<'b, Soft<'b, R>> for Soft<'a, R> { unsafe fn stow(src: *mut Soft<'a, R>, dst: *mut Soft<'b, R>, hold: &Hold<'b>) -> Result<(), HoldError> { // Try to acquire a hard lease to the shared resident. match (*src).try_to_hard() { // Hard lease acquired. Ok(mut hard_src) => { let mut hard_dst = mem::uninitialized::<Hard<'b, R>>(); // Try to stow the hard lease. match R::resident_stow(&mut hard_src, &mut hard_dst, hold) { // Stow succeeded. Ok(_) => { // Convert the stowed destination into a soft lease. match hard_dst.try_into_soft() { Ok(soft_dst) => { // Write the stowed soft least to the destination address. ptr::write(dst, soft_dst); Ok(()) }, Err(error) => Err(HoldError::from(error)), } }, // Stow failed. Err(error) => { mem::forget(hard_dst); Err(error) }, } }, // Failed to acquire a hard reference. Err(error) => Err(HoldError::from(error)), } } unsafe fn unstow(src: *mut Soft<'a, R>, dst: *mut Soft<'b, R>) { R::resident_unstow(&mut *(src as *mut Hard<'a, R>), &mut *(dst as *mut Hard<'b, R>)); } } unsafe impl<'a, #[may_dangle] R: Resident> Drop for Soft<'a, R> { fn drop(&mut self) { unsafe { // Get a pointer to the shared resident. let data = self.data.as_ptr(); // Get the alignment of the resident. let align = mem::align_of_val(&*data); // Get the offset of the resident in the arc structure by rounding up // the size of the arc header to the alignment of the resident. let offset = mem::size_of::<ArcHeader<R::Meta>>() .wrapping_add(align).wrapping_sub(1) & !align.wrapping_sub(1); // Get a pointer to the arc header by subtracting the resident's // offset in the arc structure. let header = (data as *mut u8).wrapping_sub(offset) as *mut ArcHeader<R::Meta>; // Compute the total size of the arc structure. let size = offset.wrapping_add(R::resident_size(data, &mut (*header).meta)); // Load the status field; synchronized by subsequent CAS. let mut old_status = (*header).status.load(Relaxed); // Spin until the soft reference has been released. loop { // Extract the soft reference count from the status field. let old_soft_count = (old_status & arc::SOFT_COUNT_MASK) >> arc::SOFT_COUNT_SHIFT; // Decrement the soft reference count, checking for underflow. let new_soft_count = match old_soft_count.checked_sub(1) { Some(soft_count) => soft_count, None => panic!("soft count underflow"), }; // Clear the soft reference count bit field. let new_status = old_status & !arc::SOFT_COUNT_MASK; // Splice the decremented soft reference count into the status field. let new_status = new_status | new_soft_count << arc::SOFT_COUNT_SHIFT; // Atomically update the status field, synchronizing with reference acquires. match (*header).status.compare_exchange_weak(old_status, new_status, Release, Relaxed) { // CAS succeeded. Ok(_) => { // Check if all references to the shared resident have been released. if new_status & arc::REFERENCED_MASK == 0 { // Shared resident has already been dropped; drop the arc header. (*header).drop::<R>(data); // Get the block of memory containing the arc structure. let block = Block::from_raw_parts(header as *mut u8, size); // Deallocate the block. AllocTag::from_ptr(header as *mut u8).dealloc(block); } return; }, // CAS failed; update the status field and try again. Err(status) => old_status = status, } } } } } impl<'a, R: Resident> Pointer for Soft<'a, R> { #[inline] fn fmt(&self, f: &mut Formatter) -> fmt::Result { Pointer::fmt(&self.data.as_ptr(), f) } }