xref: /aosp_15_r20/external/llvm-libc/src/__support/time/linux/monotonicity.h (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
1 //===--- timeout linux implementation ---------------------------*- C++ -*-===//
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 #ifndef LLVM_LIBC_SRC___SUPPORT_TIME_LINUX_MONOTONICITY_H
10 #define LLVM_LIBC_SRC___SUPPORT_TIME_LINUX_MONOTONICITY_H
11 
12 #include "hdr/time_macros.h"
13 #include "src/__support/libc_assert.h"
14 #include "src/__support/macros/config.h"
15 #include "src/__support/time/linux/abs_timeout.h"
16 #include "src/__support/time/linux/clock_conversion.h"
17 namespace LIBC_NAMESPACE_DECL {
18 namespace internal {
19 // This function is separated from abs_timeout.
20 // This function pulls in the dependency to clock_conversion.h,
21 // which may transitively depend on vDSO hence futex. However, this structure
22 // would be passed to futex, so we need to avoid cyclic dependencies.
23 // This function is going to be used in timed locks. Pthread generally uses
24 // realtime clocks for timeouts. However, due to non-monotoncity, realtime
25 // clocks reportedly lead to undesired behaviors. Therefore, we also provide a
26 // method to convert the timespec to a monotonic clock relative to the time of
27 // function call.
ensure_monotonicity(AbsTimeout & timeout)28 LIBC_INLINE void ensure_monotonicity(AbsTimeout &timeout) {
29   if (timeout.is_realtime()) {
30     auto res = AbsTimeout::from_timespec(
31         convert_clock(timeout.get_timespec(), CLOCK_REALTIME, CLOCK_MONOTONIC),
32         false);
33 
34     LIBC_ASSERT(res.has_value());
35     if (!res.has_value())
36       __builtin_unreachable();
37 
38     timeout = *res;
39   }
40 }
41 } // namespace internal
42 } // namespace LIBC_NAMESPACE_DECL
43 
44 #endif // LLVM_LIBC_SRC___SUPPORT_TIME_LINUX_MONOTONICITY_H
45