#include "Futex.h"
#include "include/sys/syscall.h"
#include "include/threads.h"
#include "src/__support/CPP/atomic.h"
#include "src/__support/OSUtil/syscall.h"
#include "src/__support/common.h"
#include "src/threads/call_once.h"
#include "src/threads/linux/Futex.h"
#include <limits.h>
#include <linux/futex.h>
namespace __llvm_libc {
static constexpr FutexWordType START = 0x11;
static constexpr FutexWordType WAITING = 0x22;
static constexpr FutexWordType FINISH = 0x33;
static constexpr once_flag ONCE_FLAG_INIT_VAL = ONCE_FLAG_INIT;
LLVM_LIBC_FUNCTION(void, call_once,
(once_flag * flag, __call_once_func_t func)) {
auto *futex_word = reinterpret_cast<cpp::Atomic<FutexWordType> *>(flag);
static_assert(sizeof(*futex_word) == sizeof(once_flag));
FutexWordType not_called = ONCE_FLAG_INIT_VAL.__word;
if (futex_word->compare_exchange_strong(not_called, START)) {
func();
auto status = futex_word->exchange(FINISH);
if (status == WAITING) {
__llvm_libc::syscall(SYS_futex, &futex_word->val, FUTEX_WAKE_PRIVATE,
INT_MAX,
0, 0, 0);
}
return;
}
FutexWordType status = START;
if (futex_word->compare_exchange_strong(status, WAITING) ||
status == WAITING) {
__llvm_libc::syscall(SYS_futex, &futex_word->val, FUTEX_WAIT_PRIVATE,
WAITING,
0, 0, 0);
}
}
}