1 //===-- Linux implementation of the mtx_unlock 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 mtx_t definition.
12 #include "src/__support/common.h"
13 #include "src/threads/linux/thread_utils.h"
14 
15 #include <linux/futex.h> // For futex operations.
16 #include <stdatomic.h>   // for atomic_compare_exchange_strong.
17 
18 namespace __llvm_libc {
19 
20 // The implementation currently handles only plain mutexes.
LLVM_LIBC_ENTRYPOINT(mtx_unlock)21 int LLVM_LIBC_ENTRYPOINT(mtx_unlock)(mtx_t *mutex) {
22   FutexData *futex_word = reinterpret_cast<FutexData *>(mutex->__internal_data);
23   while (true) {
24     uint32_t mutex_status = MS_Waiting;
25     if (atomic_compare_exchange_strong(futex_word, &mutex_status, MS_Free)) {
26       // If any thread is waiting to be woken up, then do it.
27       __llvm_libc::syscall(SYS_futex, futex_word, FUTEX_WAKE_PRIVATE, 1, 0, 0,
28                            0);
29       return thrd_success;
30     }
31 
32     if (mutex_status == MS_Locked) {
33       // If nobody was waiting at this point, just free it.
34       if (atomic_compare_exchange_strong(futex_word, &mutex_status, MS_Free))
35         return thrd_success;
36     } else {
37       // This can happen, for example if some thread tries to unlock an already
38       // free mutex.
39       return thrd_error;
40     }
41   }
42 }
43 
44 } // namespace __llvm_libc
45