xref: /aosp_15_r20/external/llvm-libc/src/pthread/pthread_rwlock_timedwrlock.cpp (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===-- Implementation for Rwlock's timedwrlock 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 "src/pthread/pthread_rwlock_timedwrlock.h"
10 
11 #include "src/__support/common.h"
12 #include "src/__support/libc_assert.h"
13 #include "src/__support/macros/config.h"
14 #include "src/__support/macros/optimization.h"
15 #include "src/__support/threads/linux/rwlock.h"
16 #include "src/__support/time/linux/abs_timeout.h"
17 
18 #include <pthread.h>
19 
20 namespace LIBC_NAMESPACE_DECL {
21 
22 LLVM_LIBC_FUNCTION(int, pthread_rwlock_timedwrlock,
23                    (pthread_rwlock_t *__restrict rwlock,
24                     const struct timespec *__restrict abstime)) {
25   if (!rwlock)
26     return EINVAL;
27   RwLock *rw = reinterpret_cast<RwLock *>(rwlock);
28   LIBC_ASSERT(abstime && "timedwrlock called with a null timeout");
29   auto timeout =
30       internal::AbsTimeout::from_timespec(*abstime, /*is_realtime=*/true);
31   if (LIBC_LIKELY(timeout.has_value()))
32     return static_cast<int>(rw->write_lock(timeout.value()));
33 
34   switch (timeout.error()) {
35   case internal::AbsTimeout::Error::Invalid:
36     return EINVAL;
37   case internal::AbsTimeout::Error::BeforeEpoch:
38     return ETIMEDOUT;
39   }
40   __builtin_unreachable();
41 }
42 
43 } // namespace LIBC_NAMESPACE_DECL
44