1 //===-- Linux implementation of the call_once function --------------------===// 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-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "config/linux/syscall.h" // For syscall functions. 10 #include "include/sys/syscall.h" // For syscall numbers. 11 #include "include/threads.h" // For call_once related type definition. 12 #include "src/__support/common.h" 13 #include "src/threads/linux/thread_utils.h" 14 15 #include <limits.h> 16 #include <linux/futex.h> 17 #include <stdatomic.h> 18 19 namespace __llvm_libc { 20 21 static constexpr unsigned START = 0x11; 22 static constexpr unsigned WAITING = 0x22; 23 static constexpr unsigned FINISH = 0x33; 24 25 void LLVM_LIBC_ENTRYPOINT(call_once)(once_flag *flag, __call_once_func_t func) { 26 FutexData *futex_word = reinterpret_cast<FutexData *>(flag); 27 unsigned int not_called = ONCE_FLAG_INIT; 28 29 // The C standard wording says: 30 // 31 // The completion of the function func synchronizes with all 32 // previous or subsequent calls to call_once with the same 33 // flag variable. 34 // 35 // What this means is that, the call_once call can return only after 36 // the called function |func| returns. So, we use futexes to synchronize 37 // calls with the same flag value. 38 if (::atomic_compare_exchange_strong(futex_word, ¬_called, START)) { 39 func(); 40 auto status = ::atomic_exchange(futex_word, FINISH); 41 if (status == WAITING) { 42 __llvm_libc::syscall(SYS_futex, futex_word, FUTEX_WAKE_PRIVATE, 43 INT_MAX, // Wake all waiters. 44 0, 0, 0); 45 } 46 return; 47 } 48 49 unsigned int status = START; 50 if (::atomic_compare_exchange_strong(futex_word, &status, WAITING) || 51 status == WAITING) { 52 __llvm_libc::syscall(SYS_futex, futex_word, FUTEX_WAIT_PRIVATE, 53 WAITING, // Block only if status is still |WAITING|. 54 0, 0, 0); 55 } 56 } 57 58 } // namespace __llvm_libc 59