| 1 |
//! Threading utilities. |
| 2 |
|
| 3 |
#![cfg(target_os = "macos")] |
| 4 |
|
| 5 |
use std::{marker::PhantomData, ptr::NonNull, sync::atomic::Ordering::*}; |
| 6 |
|
| 7 |
use libc::pthread_key_t; |
| 8 |
|
| 9 |
use crate::util::sync::Atomic; |
| 10 |
|
| 11 |
const KEY_UNINIT: pthread_key_t = 0; |
| 12 |
|
| 13 |
/// Thread-local key accessed via |
| 14 |
/// [`pthread_getspecific`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_getspecific.html). |
| 15 |
pub(crate) struct PThreadKey<T: 'static> { |
| 16 |
value: AtomicPThreadKey, |
| 17 |
marker: PhantomData<&'static T>, |
| 18 |
} |
| 19 |
|
| 20 |
impl<T> PThreadKey<T> { |
| 21 |
#[inline] |
| 22 |
pub const fn new() -> Self { |
| 23 |
Self { value: AtomicPThreadKey::new(KEY_UNINIT), marker: PhantomData } |
| 24 |
} |
| 25 |
|
| 26 |
#[inline] |
| 27 |
pub fn get(&self) -> Option<NonNull<T>> { |
| 28 |
match self.value.load(Relaxed) { |
| 29 |
KEY_UNINIT => None, |
| 30 |
|
| 31 |
key => unsafe { |
| 32 |
cfg_if::cfg_if! { |
| 33 |
if #[cfg(all( |
| 34 |
not(miri), |
| 35 |
any(target_arch = "x86_64", target_arch = "aarch64"), |
| 36 |
))] { |
| 37 |
let thread_local = fast::get_thread_local(key as usize); |
| 38 |
|
| 39 |
#[cfg(test)] |
| 40 |
assert_eq!(thread_local, libc::pthread_getspecific(key)); |
| 41 |
} else { |
| 42 |
let thread_local = libc::pthread_getspecific(key); |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
NonNull::new(thread_local.cast()) |
| 47 |
}, |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
/// Assigns the value with its destructor. |
| 52 |
#[inline] |
| 53 |
pub fn set<D>(&self, ptr: *const T, _: D) -> bool |
| 54 |
where |
| 55 |
D: FnOnce(NonNull<T>) + Copy, |
| 56 |
{ |
| 57 |
assert_eq!(size_of::<D>(), 0); |
| 58 |
|
| 59 |
unsafe extern "C" fn dtor<T, D>(ptr: *mut libc::c_void) |
| 60 |
where |
| 61 |
T: 'static, |
| 62 |
D: FnOnce(NonNull<T>) + Copy, |
| 63 |
{ |
| 64 |
// SAFETY: The dtor is zero-sized, so we can make one from thin air. |
| 65 |
let dtor: D = unsafe { std::mem::zeroed() }; |
| 66 |
|
| 67 |
// Although we're guaranteed `ptr` is not null, check in case. |
| 68 |
if let Some(ptr) = NonNull::new(ptr) { |
| 69 |
dtor(ptr.cast()); |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
let shared_key = &self.value; |
| 74 |
let mut local_key = shared_key.load(Relaxed); |
| 75 |
|
| 76 |
// Race against other threads to initialize `shared_key`. |
| 77 |
if local_key == KEY_UNINIT { |
| 78 |
if unsafe { libc::pthread_key_create(&mut local_key, Some(dtor::<T, D>)) } == 0 { |
| 79 |
// Race to store our key into the global instance. |
| 80 |
// |
| 81 |
// On failure, delete our key and use the winner's key. |
| 82 |
if let Err(their_key) = |
| 83 |
shared_key.compare_exchange(KEY_UNINIT, local_key, Relaxed, Relaxed) |
| 84 |
{ |
| 85 |
// SAFETY: No other thread is accessing this key. |
| 86 |
unsafe { libc::pthread_key_delete(local_key) }; |
| 87 |
|
| 88 |
local_key = their_key; |
| 89 |
} |
| 90 |
} else { |
| 91 |
// On create failure, check if another thread succeeded. |
| 92 |
local_key = shared_key.load(Relaxed); |
| 93 |
if local_key == KEY_UNINIT { |
| 94 |
return false; |
| 95 |
} |
| 96 |
} |
| 97 |
} |
| 98 |
|
| 99 |
// This is the slow path, so don't bother with writing via |
| 100 |
// `gs`/`tpidrro_el0` register. |
| 101 |
// |
| 102 |
// SAFETY: The key has been created by us or another thread. |
| 103 |
unsafe { libc::pthread_setspecific(local_key, ptr.cast()) == 0 } |
| 104 |
} |
| 105 |
} |
| 106 |
|
| 107 |
/// Alias to the atomic equivalent of `pthread_key_t`. |
| 108 |
pub(crate) type AtomicPThreadKey = Atomic<pthread_key_t>; |
| 109 |
|
| 110 |
/// Optimized alternatives to `pthread_getspecific`. |
| 111 |
pub(crate) mod fast { |
| 112 |
// Apple reserves key 11 (`__PTK_LIBC_RESERVED_WIN64`) for Windows: |
| 113 |
// https://github.com/apple-oss-distributions/libpthread/blob/libpthread-519/private/pthread/tsd_private.h#L99 |
| 114 |
// |
| 115 |
// Key 6 is also reserved for Windows and Go, but we don't use it because |
| 116 |
// it's more well known and likely to be used by more libraries. |
| 117 |
|
| 118 |
/// Returns a pointer to a static thread-local variable. |
| 119 |
#[inline] |
| 120 |
#[cfg(all(not(miri), not(feature = "dyn_thread_local"), target_arch = "x86_64"))] |
| 121 |
pub fn get_static_thread_local<T>() -> *const T { |
| 122 |
unsafe { |
| 123 |
let result; |
| 124 |
std::arch::asm!( |
| 125 |
"mov {}, gs:[88]", |
| 126 |
out(reg) result, |
| 127 |
options(pure, readonly, nostack, preserves_flags), |
| 128 |
); |
| 129 |
result |
| 130 |
} |
| 131 |
} |
| 132 |
|
| 133 |
/// Sets the static thread-local variable. |
| 134 |
/// |
| 135 |
/// # Safety |
| 136 |
/// |
| 137 |
/// If the slot is in use, we will corrupt the other user's memory. |
| 138 |
#[inline] |
| 139 |
#[cfg(all(not(miri), not(feature = "dyn_thread_local"), target_arch = "x86_64"))] |
| 140 |
pub unsafe fn set_static_thread_local<T>(ptr: *const T) { |
| 141 |
unsafe { |
| 142 |
std::arch::asm!( |
| 143 |
"mov gs:[88], {}", |
| 144 |
in(reg) ptr, |
| 145 |
options(nostack, preserves_flags), |
| 146 |
); |
| 147 |
} |
| 148 |
} |
| 149 |
|
| 150 |
/// Returns a pointer to the corresponding thread-local variable. |
| 151 |
/// |
| 152 |
/// The first element is reserved for `pthread_self`. This is widely known |
| 153 |
/// and also mentioned in page 251 of "*OS Internals Volume 1" by Jonathan |
| 154 |
/// Levin. |
| 155 |
/// |
| 156 |
/// It appears that `pthread_key_create` allocates a slot into the buffer |
| 157 |
/// referenced by: |
| 158 |
/// - [`gs` on x86_64](https://github.com/apple-oss-distributions/xnu/blob/xnu-10002.41.9/libsyscall/os/tsd.h#L126) |
| 159 |
/// - [`tpidrro_el0` on AArch64](https://github.com/apple-oss-distributions/xnu/blob/xnu-10002.41.9/libsyscall/os/tsd.h#L163) |
| 160 |
/// |
| 161 |
/// # Safety |
| 162 |
/// |
| 163 |
/// `key` must not cause an out-of-bounds lookup. |
| 164 |
#[inline] |
| 165 |
#[cfg(all(not(miri), any(target_arch = "x86_64", target_arch = "aarch64")))] |
| 166 |
pub unsafe fn get_thread_local(key: usize) -> *mut libc::c_void { |
| 167 |
#[cfg(target_arch = "x86_64")] |
| 168 |
{ |
| 169 |
let result; |
| 170 |
std::arch::asm!( |
| 171 |
"mov {}, gs:[8 * {1}]", |
| 172 |
out(reg) result, |
| 173 |
in(reg) key, |
| 174 |
options(pure, readonly, nostack, preserves_flags), |
| 175 |
); |
| 176 |
result |
| 177 |
} |
| 178 |
|
| 179 |
#[cfg(target_arch = "aarch64")] |
| 180 |
{ |
| 181 |
let result: *const *mut libc::c_void; |
| 182 |
std::arch::asm!( |
| 183 |
"mrs {0}, tpidrro_el0", |
| 184 |
// Clear bottom 3 bits just in case. This was historically the CPU |
| 185 |
// core ID but that changed at some point. |
| 186 |
"and {0}, {0}, #-8", |
| 187 |
out(reg) result, |
| 188 |
options(pure, nomem, nostack, preserves_flags), |
| 189 |
); |
| 190 |
*result.add(key) |
| 191 |
} |
| 192 |
} |
| 193 |
} |