use core::ffi::{c_char, c_int, c_void};
use core::sync::atomic::{AtomicPtr, AtomicU8, AtomicU32, Ordering};
use core::time::Duration;
use crate::sys::errno;
use crate::{Error, Result};
const UL_COMPARE_AND_WAIT: u32 = 1;
const ULF_WAKE_ALL: u32 = 0x0000_0100;
const ULF_NO_ERRNO: u32 = 0x0100_0000;
const OS_SYNC_NONE: u32 = 0;
const OS_CLOCK_MACH_ABSOLUTE_TIME: u32 = 32;
const RTLD_DEFAULT: *mut c_void = -2isize as *mut c_void;
const MAX_TIMEOUT_NANOS: u64 = i64::MAX as u64;
unsafe extern "C" {
fn __ulock_wait2(
operation: u32,
addr: *mut c_void,
value: u64,
timeout: u64,
value2: u64,
) -> c_int;
fn __ulock_wake(operation: u32, addr: *mut c_void, wake_value: u64) -> c_int;
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
fn __error() -> *mut c_int;
}
type WaitFn = unsafe extern "C" fn(addr: *mut c_void, value: u64, size: usize, flags: u32) -> c_int;
type WaitTimeoutFn = unsafe extern "C" fn(
addr: *mut c_void,
value: u64,
size: usize,
flags: u32,
clock_id: u32,
timeout_ns: u64,
) -> c_int;
type WakeFn = unsafe extern "C" fn(addr: *mut c_void, size: usize, flags: u32) -> c_int;
#[derive(Clone, Copy)]
struct OsSync {
wait: WaitFn,
wait_with_timeout: WaitTimeoutFn,
wake_any: WakeFn,
wake_all: WakeFn,
}
const UNRESOLVED: u8 = 0;
const DOCUMENTED: u8 = 1;
const ULOCK: u8 = 2;
static FAMILY: AtomicU8 = AtomicU8::new(UNRESOLVED);
static SYMBOLS: [AtomicPtr<c_void>; 4] = [const { AtomicPtr::new(core::ptr::null_mut()) }; 4];
const NAMES: [&core::ffi::CStr; 4] = [
c"os_sync_wait_on_address",
c"os_sync_wait_on_address_with_timeout",
c"os_sync_wake_by_address_any",
c"os_sync_wake_by_address_all",
];
fn os_sync() -> Option<OsSync> {
let symbols = match FAMILY.load(Ordering::Acquire) {
DOCUMENTED => SYMBOLS
.each_ref()
.map(|symbol| symbol.load(Ordering::Relaxed)),
ULOCK => return None,
_ => {
let symbols = NAMES.map(|name| unsafe { dlsym(RTLD_DEFAULT, name.as_ptr()) });
if symbols.iter().any(|symbol| symbol.is_null()) {
FAMILY.store(ULOCK, Ordering::Release);
return None;
}
for (cached, symbol) in SYMBOLS.iter().zip(symbols) {
cached.store(symbol, Ordering::Relaxed);
}
FAMILY.store(DOCUMENTED, Ordering::Release);
symbols
}
};
Some(unsafe {
OsSync {
wait: core::mem::transmute::<*mut c_void, WaitFn>(symbols[0]),
wait_with_timeout: core::mem::transmute::<*mut c_void, WaitTimeoutFn>(symbols[1]),
wake_any: core::mem::transmute::<*mut c_void, WakeFn>(symbols[2]),
wake_all: core::mem::transmute::<*mut c_void, WakeFn>(symbols[3]),
}
})
}
fn documented(call: impl FnOnce() -> c_int) -> c_int {
let errno = unsafe { __error() };
let saved = unsafe { *errno };
if call() >= 0 {
return 0;
}
unsafe {
let code = *errno;
*errno = saved;
code
}
}
pub(crate) fn wait(atomic: &AtomicU32, expected: u32, timeout: Option<Duration>) -> Result<bool> {
let timeout = match timeout {
None => 0,
Some(Duration::ZERO) => return Ok(atomic.load(Ordering::SeqCst) != expected),
Some(timeout) => match u64::try_from(timeout.as_nanos()) {
Ok(nanos) if nanos <= MAX_TIMEOUT_NANOS => nanos,
_ => 0,
},
};
let addr = atomic.as_ptr().cast::<c_void>();
let value = u64::from(expected);
let code = match os_sync() {
Some(os_sync) => {
documented(|| unsafe {
if timeout == 0 {
(os_sync.wait)(addr, value, size_of::<u32>(), OS_SYNC_NONE)
} else {
(os_sync.wait_with_timeout)(
addr,
value,
size_of::<u32>(),
OS_SYNC_NONE,
OS_CLOCK_MACH_ABSOLUTE_TIME,
timeout,
)
}
})
}
None => {
let ret = unsafe {
__ulock_wait2(UL_COMPARE_AND_WAIT | ULF_NO_ERRNO, addr, value, timeout, 0)
};
if ret >= 0 { 0 } else { -ret }
}
};
match code {
0 => Ok(true),
errno::EINTR | errno::EFAULT => Ok(true),
errno::ETIMEDOUT => Ok(false),
code => Err(Error::from_raw_os_error(code)),
}
}
pub(crate) fn wake(atomic: &AtomicU32, all: bool) {
let addr = atomic.as_ptr().cast::<c_void>();
let os_sync = os_sync();
loop {
let code = match os_sync {
Some(os_sync) => {
let wake = if all {
os_sync.wake_all
} else {
os_sync.wake_any
};
documented(|| unsafe { wake(addr, size_of::<u32>(), OS_SYNC_NONE) })
}
None => {
let flags = if all { ULF_WAKE_ALL } else { 0 };
let ret =
unsafe { __ulock_wake(UL_COMPARE_AND_WAIT | ULF_NO_ERRNO | flags, addr, 0) };
if ret >= 0 { 0 } else { -ret }
}
};
if code != errno::EINTR {
return;
}
}
}