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 LLVM_LIBC_FUNCTION(void, call_once, 26 (once_flag * flag, __call_once_func_t func)) { 27 FutexData *futex_word = reinterpret_cast<FutexData *>(flag); 28 unsigned int not_called = ONCE_FLAG_INIT; 29 30 // The C standard wording says: 31 // 32 // The completion of the function func synchronizes with all 33 // previous or subsequent calls to call_once with the same 34 // flag variable. 35 // 36 // What this means is that, the call_once call can return only after 37 // the called function |func| returns. So, we use futexes to synchronize 38 // calls with the same flag value. 39 if (::atomic_compare_exchange_strong(futex_word, ¬_called, START)) { 40 func(); 41 auto status = ::atomic_exchange(futex_word, FINISH); 42 if (status == WAITING) { 43 __llvm_libc::syscall(SYS_futex, futex_word, FUTEX_WAKE_PRIVATE, 44 INT_MAX, // Wake all waiters. 45 0, 0, 0); 46 } 47 return; 48 } 49 50 unsigned int status = START; 51 if (::atomic_compare_exchange_strong(futex_word, &status, WAITING) || 52 status == WAITING) { 53 __llvm_libc::syscall(SYS_futex, futex_word, FUTEX_WAIT_PRIVATE, 54 WAITING, // Block only if status is still |WAITING|. 55 0, 0, 0); 56 } 57 } 58 59 } // namespace __llvm_libc 60