1 // Copyright 2017 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15
16 // An optional absolute timeout, with nanosecond granularity,
17 // compatible with absl::Time. Suitable for in-register
18 // parameter-passing (e.g. syscalls.)
19 // Constructible from a absl::Time (for a timeout to be respected) or {}
20 // (for "no timeout".)
21 // This is a private low-level API for use by a handful of low-level
22 // components. Higher-level components should build APIs based on
23 // absl::Time and absl::Duration.
24
25 #ifndef ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_
26 #define ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_
27
28 #include <time.h>
29
30 #include <algorithm>
31 #include <cstdint>
32 #include <limits>
33
34 #include "absl/base/internal/raw_logging.h"
35 #include "absl/time/clock.h"
36 #include "absl/time/time.h"
37
38 namespace absl {
39 ABSL_NAMESPACE_BEGIN
40 namespace synchronization_internal {
41
42 class Waiter;
43
44 class KernelTimeout {
45 public:
46 // A timeout that should expire at <t>. Any value, in the full
47 // InfinitePast() to InfiniteFuture() range, is valid here and will be
48 // respected.
KernelTimeout(absl::Time t)49 explicit KernelTimeout(absl::Time t) : ns_(MakeNs(t)) {}
50 // No timeout.
KernelTimeout()51 KernelTimeout() : ns_(0) {}
52
53 // A more explicit factory for those who prefer it. Equivalent to {}.
Never()54 static KernelTimeout Never() { return {}; }
55
56 // We explicitly do not support other custom formats: timespec, int64_t nanos.
57 // Unify on this and absl::Time, please.
58
has_timeout()59 bool has_timeout() const { return ns_ != 0; }
60
61 // Convert to parameter for sem_timedwait/futex/similar. Only for approved
62 // users. Do not call if !has_timeout.
63 struct timespec MakeAbsTimespec() const;
64
65 // Convert to unix epoch nanos. Do not call if !has_timeout.
66 int64_t MakeAbsNanos() const;
67
68 private:
69 // internal rep, not user visible: ns after unix epoch.
70 // zero = no timeout.
71 // Negative we treat as an unlikely (and certainly expired!) but valid
72 // timeout.
73 int64_t ns_;
74
MakeNs(absl::Time t)75 static int64_t MakeNs(absl::Time t) {
76 // optimization--InfiniteFuture is common "no timeout" value
77 // and cheaper to compare than convert.
78 if (t == absl::InfiniteFuture()) return 0;
79 int64_t x = ToUnixNanos(t);
80
81 // A timeout that lands exactly on the epoch (x=0) needs to be respected,
82 // so we alter it unnoticably to 1. Negative timeouts are in
83 // theory supported, but handled poorly by the kernel (long
84 // delays) so push them forward too; since all such times have
85 // already passed, it's indistinguishable.
86 if (x <= 0) x = 1;
87 // A time larger than what can be represented to the kernel is treated
88 // as no timeout.
89 if (x == (std::numeric_limits<int64_t>::max)()) x = 0;
90 return x;
91 }
92
93 #ifdef _WIN32
94 // Converts to milliseconds from now, or INFINITE when
95 // !has_timeout(). For use by SleepConditionVariableSRW on
96 // Windows. Callers should recognize that the return value is a
97 // relative duration (it should be recomputed by calling this method
98 // in the case of a spurious wakeup).
99 // This header file may be included transitively by public header files,
100 // so we define our own DWORD and INFINITE instead of getting them from
101 // <intsafe.h> and <WinBase.h>.
102 typedef unsigned long DWord; // NOLINT
InMillisecondsFromNow()103 DWord InMillisecondsFromNow() const {
104 constexpr DWord kInfinite = (std::numeric_limits<DWord>::max)();
105 if (!has_timeout()) {
106 return kInfinite;
107 }
108 // The use of absl::Now() to convert from absolute time to
109 // relative time means that absl::Now() cannot use anything that
110 // depends on KernelTimeout (for example, Mutex) on Windows.
111 int64_t now = ToUnixNanos(absl::Now());
112 if (ns_ >= now) {
113 // Round up so that Now() + ms_from_now >= ns_.
114 constexpr uint64_t max_nanos =
115 (std::numeric_limits<int64_t>::max)() - 999999u;
116 uint64_t ms_from_now =
117 ((std::min)(max_nanos, static_cast<uint64_t>(ns_ - now)) + 999999u) /
118 1000000u;
119 if (ms_from_now > kInfinite) {
120 return kInfinite;
121 }
122 return static_cast<DWord>(ms_from_now);
123 }
124 return 0;
125 }
126
127 friend class Waiter;
128 #endif
129 };
130
MakeAbsTimespec()131 inline struct timespec KernelTimeout::MakeAbsTimespec() const {
132 int64_t n = ns_;
133 static const int64_t kNanosPerSecond = 1000 * 1000 * 1000;
134 if (n == 0) {
135 ABSL_RAW_LOG(
136 ERROR, "Tried to create a timespec from a non-timeout; never do this.");
137 // But we'll try to continue sanely. no-timeout ~= saturated timeout.
138 n = (std::numeric_limits<int64_t>::max)();
139 }
140
141 // Kernel APIs validate timespecs as being at or after the epoch,
142 // despite the kernel time type being signed. However, no one can
143 // tell the difference between a timeout at or before the epoch (since
144 // all such timeouts have expired!)
145 if (n < 0) n = 0;
146
147 struct timespec abstime;
148 int64_t seconds = (std::min)(n / kNanosPerSecond,
149 int64_t{(std::numeric_limits<time_t>::max)()});
150 abstime.tv_sec = static_cast<time_t>(seconds);
151 abstime.tv_nsec = static_cast<decltype(abstime.tv_nsec)>(n % kNanosPerSecond);
152 return abstime;
153 }
154
MakeAbsNanos()155 inline int64_t KernelTimeout::MakeAbsNanos() const {
156 if (ns_ == 0) {
157 ABSL_RAW_LOG(
158 ERROR, "Tried to create a timeout from a non-timeout; never do this.");
159 // But we'll try to continue sanely. no-timeout ~= saturated timeout.
160 return (std::numeric_limits<int64_t>::max)();
161 }
162
163 return ns_;
164 }
165
166 } // namespace synchronization_internal
167 ABSL_NAMESPACE_END
168 } // namespace absl
169
170 #endif // ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_
171