280 lines · cpp
1//===----------------------------------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include <__thread/timed_backoff_policy.h>10#include <atomic>11#include <climits>12#include <functional>13#include <thread>14 15#include "include/apple_availability.h"16 17#ifdef __linux__18 19# include <linux/futex.h>20# include <sys/syscall.h>21# include <unistd.h>22 23// libc++ uses SYS_futex as a universal syscall name. However, on 32 bit architectures24// with a 64 bit time_t, we need to specify SYS_futex_time64.25# if !defined(SYS_futex) && defined(SYS_futex_time64)26# define SYS_futex SYS_futex_time6427# endif28# define _LIBCPP_FUTEX(...) syscall(SYS_futex, __VA_ARGS__)29 30#elif defined(__FreeBSD__)31 32# include <sys/types.h>33# include <sys/umtx.h>34 35# define _LIBCPP_FUTEX(...) syscall(SYS_futex, __VA_ARGS__)36 37#elif defined(__OpenBSD__)38 39# include <sys/futex.h>40 41// OpenBSD has no indirect syscalls42# define _LIBCPP_FUTEX(...) futex(__VA_ARGS__)43 44#elif defined(_WIN32)45 46# include <memory>47# include <windows.h>48 49#else // <- Add other operating systems here50 51// Baseline needs no new headers52 53# define _LIBCPP_FUTEX(...) syscall(SYS_futex, __VA_ARGS__)54 55#endif56 57_LIBCPP_BEGIN_NAMESPACE_STD58 59#ifdef __linux__60 61static void62__libcpp_platform_wait_on_address(__cxx_atomic_contention_t const volatile* __ptr, __cxx_contention_t __val) {63 static constexpr timespec __timeout = {2, 0};64 _LIBCPP_FUTEX(__ptr, FUTEX_WAIT_PRIVATE, __val, &__timeout, 0, 0);65}66 67static void __libcpp_platform_wake_by_address(__cxx_atomic_contention_t const volatile* __ptr, bool __notify_one) {68 _LIBCPP_FUTEX(__ptr, FUTEX_WAKE_PRIVATE, __notify_one ? 1 : INT_MAX, 0, 0, 0);69}70 71#elif defined(__APPLE__) && defined(_LIBCPP_USE_ULOCK)72 73extern "C" int __ulock_wait(74 uint32_t operation, void* addr, uint64_t value, uint32_t timeout); /* timeout is specified in microseconds */75extern "C" int __ulock_wake(uint32_t operation, void* addr, uint64_t wake_value);76 77// https://github.com/apple/darwin-xnu/blob/2ff845c2e033bd0ff64b5b6aa6063a1f8f65aa32/bsd/sys/ulock.h#L8278# define UL_COMPARE_AND_WAIT64 579# define ULF_WAKE_ALL 0x0000010080 81static void82__libcpp_platform_wait_on_address(__cxx_atomic_contention_t const volatile* __ptr, __cxx_contention_t __val) {83 static_assert(sizeof(__cxx_atomic_contention_t) == 8, "Waiting on 8 bytes value");84 __ulock_wait(UL_COMPARE_AND_WAIT64, const_cast<__cxx_atomic_contention_t*>(__ptr), __val, 0);85}86 87static void __libcpp_platform_wake_by_address(__cxx_atomic_contention_t const volatile* __ptr, bool __notify_one) {88 static_assert(sizeof(__cxx_atomic_contention_t) == 8, "Waking up on 8 bytes value");89 __ulock_wake(90 UL_COMPARE_AND_WAIT64 | (__notify_one ? 0 : ULF_WAKE_ALL), const_cast<__cxx_atomic_contention_t*>(__ptr), 0);91}92 93#elif defined(__FreeBSD__) && __SIZEOF_LONG__ == 894/*95 * Since __cxx_contention_t is int64_t even on 32bit FreeBSD96 * platforms, we have to use umtx ops that work on the long type, and97 * limit its use to architectures where long and int64_t are synonyms.98 */99 100static void101__libcpp_platform_wait_on_address(__cxx_atomic_contention_t const volatile* __ptr, __cxx_contention_t __val) {102 _umtx_op(const_cast<__cxx_atomic_contention_t*>(__ptr), UMTX_OP_WAIT, __val, nullptr, nullptr);103}104 105static void __libcpp_platform_wake_by_address(__cxx_atomic_contention_t const volatile* __ptr, bool __notify_one) {106 _umtx_op(const_cast<__cxx_atomic_contention_t*>(__ptr), UMTX_OP_WAKE, __notify_one ? 1 : INT_MAX, nullptr, nullptr);107}108 109#elif defined(_WIN32)110 111static void* win32_get_synch_api_function(const char* function_name) {112 // Attempt to load the API set. Note that as per the Microsoft STL implementation, we assume this API is already113 // loaded and accessible. While this isn't explicitly guaranteed by publicly available Win32 API documentation, it is114 // true in practice, and may be guaranteed by internal documentation not released publicly. In any case the fact that115 // the Microsoft STL made this assumption is reasonable basis to say that we can too. The alternative to this would be116 // to use LoadLibrary, but then leak the module handle. We can't call FreeLibrary, as this would have to be triggered117 // by a global static destructor, which would hang off DllMain, and calling FreeLibrary from DllMain is explicitly118 // mentioned as not being allowed:119 // https://learn.microsoft.com/en-us/windows/win32/dlls/dllmain120 // Given the range of bad options here, we have chosen to mirror what Microsoft did, as it seems fair to assume that121 // Microsoft will guarantee compatibility for us, as we are exposed to the same conditions as all existing Windows122 // apps using the Microsoft STL VS2015/2017/2019/2022 runtimes, where Windows 7 support has not been excluded at123 // compile time.124 static auto module_handle = GetModuleHandleW(L"api-ms-win-core-synch-l1-2-0.dll");125 if (module_handle == nullptr) {126 return nullptr;127 }128 129 // Attempt to locate the function in the API and return the result to the caller. Note that the NULL return from this130 // method is documented as being interchangeable with nullptr.131 // https://devblogs.microsoft.com/oldnewthing/20180307-00/?p=98175132 return reinterpret_cast<void*>(GetProcAddress(module_handle, function_name));133}134 135static void136__libcpp_platform_wait_on_address(__cxx_atomic_contention_t const volatile* __ptr, __cxx_contention_t __val) {137 // WaitOnAddress was added in Windows 8 (build 9200)138 static auto wait_on_address = reinterpret_cast<BOOL(WINAPI*)(volatile void*, PVOID, SIZE_T, DWORD)>(139 win32_get_synch_api_function("WaitOnAddress"));140 if (wait_on_address != nullptr) {141 wait_on_address(const_cast<__cxx_atomic_contention_t*>(__ptr), &__val, sizeof(__val), INFINITE);142 } else {143 __libcpp_thread_poll_with_backoff(144 [=]() -> bool { return !__cxx_nonatomic_compare_equal(__cxx_atomic_load(__ptr, memory_order_relaxed), __val); },145 __libcpp_timed_backoff_policy());146 }147}148 149static void __libcpp_platform_wake_by_address(__cxx_atomic_contention_t const volatile* __ptr, bool __notify_one) {150 if (__notify_one) {151 // WakeByAddressSingle was added in Windows 8 (build 9200)152 static auto wake_by_address_single =153 reinterpret_cast<void(WINAPI*)(PVOID)>(win32_get_synch_api_function("WakeByAddressSingle"));154 if (wake_by_address_single != nullptr) {155 wake_by_address_single(const_cast<__cxx_atomic_contention_t*>(__ptr));156 } else {157 // The fallback implementation of waking does nothing, as the fallback wait implementation just does polling, so158 // there's nothing to do here.159 }160 } else {161 // WakeByAddressAll was added in Windows 8 (build 9200)162 static auto wake_by_address_all =163 reinterpret_cast<void(WINAPI*)(PVOID)>(win32_get_synch_api_function("WakeByAddressAll"));164 if (wake_by_address_all != nullptr) {165 wake_by_address_all(const_cast<__cxx_atomic_contention_t*>(__ptr));166 } else {167 // The fallback implementation of waking does nothing, as the fallback wait implementation just does polling, so168 // there's nothing to do here.169 }170 }171}172 173#else // <- Add other operating systems here174 175// Baseline is just a timed backoff176 177static void178__libcpp_platform_wait_on_address(__cxx_atomic_contention_t const volatile* __ptr, __cxx_contention_t __val) {179 __libcpp_thread_poll_with_backoff(180 [=]() -> bool { return !__cxx_nonatomic_compare_equal(__cxx_atomic_load(__ptr, memory_order_relaxed), __val); },181 __libcpp_timed_backoff_policy());182}183 184static void __libcpp_platform_wake_by_address(__cxx_atomic_contention_t const volatile*, bool) {}185 186#endif // __linux__187 188static constexpr size_t __libcpp_contention_table_size = (1 << 8); /* < there's no magic in this number */189 190struct alignas(64) /* aim to avoid false sharing */ __libcpp_contention_table_entry {191 __cxx_atomic_contention_t __contention_state;192 __cxx_atomic_contention_t __platform_state;193 inline constexpr __libcpp_contention_table_entry() : __contention_state(0), __platform_state(0) {}194};195 196static __libcpp_contention_table_entry __libcpp_contention_table[__libcpp_contention_table_size];197 198static hash<void const volatile*> __libcpp_contention_hasher;199 200static __libcpp_contention_table_entry* __libcpp_contention_state(void const volatile* p) {201 return &__libcpp_contention_table[__libcpp_contention_hasher(p) & (__libcpp_contention_table_size - 1)];202}203 204/* Given an atomic to track contention and an atomic to actually wait on, which may be205 the same atomic, we try to detect contention to avoid spuriously calling the platform. */206 207static void __libcpp_contention_notify(__cxx_atomic_contention_t volatile* __contention_state,208 __cxx_atomic_contention_t const volatile* __platform_state,209 bool __notify_one) {210 if (0 != __cxx_atomic_load(__contention_state, memory_order_seq_cst))211 // We only call 'wake' if we consumed a contention bit here.212 __libcpp_platform_wake_by_address(__platform_state, __notify_one);213}214static __cxx_contention_t215__libcpp_contention_monitor_for_wait(__cxx_atomic_contention_t volatile* /*__contention_state*/,216 __cxx_atomic_contention_t const volatile* __platform_state) {217 // We will monitor this value.218 return __cxx_atomic_load(__platform_state, memory_order_acquire);219}220static void __libcpp_contention_wait(__cxx_atomic_contention_t volatile* __contention_state,221 __cxx_atomic_contention_t const volatile* __platform_state,222 __cxx_contention_t __old_value) {223 __cxx_atomic_fetch_add(__contention_state, __cxx_contention_t(1), memory_order_relaxed);224 // https://llvm.org/PR109290225 // There are no platform guarantees of a memory barrier in the platform wait implementation226 __cxx_atomic_thread_fence(memory_order_seq_cst);227 // We sleep as long as the monitored value hasn't changed.228 __libcpp_platform_wait_on_address(__platform_state, __old_value);229 __cxx_atomic_fetch_sub(__contention_state, __cxx_contention_t(1), memory_order_release);230}231 232/* When the incoming atomic is the wrong size for the platform wait size, need to233 launder the value sequence through an atomic from our table. */234 235static void __libcpp_atomic_notify(void const volatile* __location) {236 auto const __entry = __libcpp_contention_state(__location);237 // The value sequence laundering happens on the next line below.238 __cxx_atomic_fetch_add(&__entry->__platform_state, __cxx_contention_t(1), memory_order_seq_cst);239 __libcpp_contention_notify(240 &__entry->__contention_state,241 &__entry->__platform_state,242 false /* when laundering, we can't handle notify_one */);243}244_LIBCPP_EXPORTED_FROM_ABI void __cxx_atomic_notify_one(void const volatile* __location) noexcept {245 __libcpp_atomic_notify(__location);246}247_LIBCPP_EXPORTED_FROM_ABI void __cxx_atomic_notify_all(void const volatile* __location) noexcept {248 __libcpp_atomic_notify(__location);249}250_LIBCPP_EXPORTED_FROM_ABI __cxx_contention_t __libcpp_atomic_monitor(void const volatile* __location) noexcept {251 auto const __entry = __libcpp_contention_state(__location);252 return __libcpp_contention_monitor_for_wait(&__entry->__contention_state, &__entry->__platform_state);253}254_LIBCPP_EXPORTED_FROM_ABI void255__libcpp_atomic_wait(void const volatile* __location, __cxx_contention_t __old_value) noexcept {256 auto const __entry = __libcpp_contention_state(__location);257 __libcpp_contention_wait(&__entry->__contention_state, &__entry->__platform_state, __old_value);258}259 260/* When the incoming atomic happens to be the platform wait size, we still need to use the261 table for the contention detection, but we can use the atomic directly for the wait. */262 263_LIBCPP_EXPORTED_FROM_ABI void __cxx_atomic_notify_one(__cxx_atomic_contention_t const volatile* __location) noexcept {264 __libcpp_contention_notify(&__libcpp_contention_state(__location)->__contention_state, __location, true);265}266_LIBCPP_EXPORTED_FROM_ABI void __cxx_atomic_notify_all(__cxx_atomic_contention_t const volatile* __location) noexcept {267 __libcpp_contention_notify(&__libcpp_contention_state(__location)->__contention_state, __location, false);268}269// This function is never used, but still exported for ABI compatibility.270_LIBCPP_EXPORTED_FROM_ABI __cxx_contention_t271__libcpp_atomic_monitor(__cxx_atomic_contention_t const volatile* __location) noexcept {272 return __libcpp_contention_monitor_for_wait(&__libcpp_contention_state(__location)->__contention_state, __location);273}274_LIBCPP_EXPORTED_FROM_ABI void275__libcpp_atomic_wait(__cxx_atomic_contention_t const volatile* __location, __cxx_contention_t __old_value) noexcept {276 __libcpp_contention_wait(&__libcpp_contention_state(__location)->__contention_state, __location, __old_value);277}278 279_LIBCPP_END_NAMESPACE_STD280