blob: d6ac5db0af109847f383293b457868f8c912bf3c [file] [log] [blame]
mistergc2e75482017-09-19 16:54:40 -04001// 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//
nik727338b70432019-03-08 10:27:53 -05007// https://www.apache.org/licenses/LICENSE-2.0
mistergc2e75482017-09-19 16:54:40 -04008//
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 that are friends of this class. Higher-level components
23// should build APIs based on absl::Time and absl::Duration.
24
25#ifndef ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_
26#define ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_
27
mistergc2e75482017-09-19 16:54:40 -040028#include <time.h>
29#include <algorithm>
30#include <limits>
31
32#include "absl/base/internal/raw_logging.h"
33#include "absl/time/clock.h"
34#include "absl/time/time.h"
35
36namespace absl {
Abseil Team12bc53e2019-12-12 10:36:03 -080037ABSL_NAMESPACE_BEGIN
mistergc2e75482017-09-19 16:54:40 -040038namespace synchronization_internal {
39
Abseil Team9e94e482017-11-10 06:33:50 -080040class Futex;
mistergc2e75482017-09-19 16:54:40 -040041class Waiter;
42
43class KernelTimeout {
44 public:
45 // A timeout that should expire at <t>. Any value, in the full
46 // InfinitePast() to InfiniteFuture() range, is valid here and will be
47 // respected.
48 explicit KernelTimeout(absl::Time t) : ns_(MakeNs(t)) {}
49 // No timeout.
50 KernelTimeout() : ns_(0) {}
51
52 // A more explicit factory for those who prefer it. Equivalent to {}.
53 static KernelTimeout Never() { return {}; }
54
55 // We explicitly do not support other custom formats: timespec, int64_t nanos.
56 // Unify on this and absl::Time, please.
Abseil Teambf294702019-03-19 11:14:01 -070057
mistergc2e75482017-09-19 16:54:40 -040058 bool has_timeout() const { return ns_ != 0; }
59
60 private:
61 // internal rep, not user visible: ns after unix epoch.
62 // zero = no timeout.
63 // Negative we treat as an unlikely (and certainly expired!) but valid
64 // timeout.
65 int64_t ns_;
66
67 static int64_t MakeNs(absl::Time t) {
68 // optimization--InfiniteFuture is common "no timeout" value
69 // and cheaper to compare than convert.
70 if (t == absl::InfiniteFuture()) return 0;
71 int64_t x = ToUnixNanos(t);
72
73 // A timeout that lands exactly on the epoch (x=0) needs to be respected,
74 // so we alter it unnoticably to 1. Negative timeouts are in
75 // theory supported, but handled poorly by the kernel (long
76 // delays) so push them forward too; since all such times have
77 // already passed, it's indistinguishable.
78 if (x <= 0) x = 1;
79 // A time larger than what can be represented to the kernel is treated
80 // as no timeout.
Abseil Teama4c3fff2018-10-29 15:53:34 -070081 if (x == (std::numeric_limits<int64_t>::max)()) x = 0;
mistergc2e75482017-09-19 16:54:40 -040082 return x;
83 }
84
85 // Convert to parameter for sem_timedwait/futex/similar. Only for approved
86 // users. Do not call if !has_timeout.
87 struct timespec MakeAbsTimespec() {
88 int64_t n = ns_;
89 static const int64_t kNanosPerSecond = 1000 * 1000 * 1000;
90 if (n == 0) {
91 ABSL_RAW_LOG(
92 ERROR,
93 "Tried to create a timespec from a non-timeout; never do this.");
94 // But we'll try to continue sanely. no-timeout ~= saturated timeout.
Abseil Teama4c3fff2018-10-29 15:53:34 -070095 n = (std::numeric_limits<int64_t>::max)();
mistergc2e75482017-09-19 16:54:40 -040096 }
97
98 // Kernel APIs validate timespecs as being at or after the epoch,
99 // despite the kernel time type being signed. However, no one can
100 // tell the difference between a timeout at or before the epoch (since
101 // all such timeouts have expired!)
102 if (n < 0) n = 0;
103
104 struct timespec abstime;
Abseil Team284378a2018-12-05 12:37:41 -0800105 int64_t seconds = (std::min)(n / kNanosPerSecond,
106 int64_t{(std::numeric_limits<time_t>::max)()});
mistergc2e75482017-09-19 16:54:40 -0400107 abstime.tv_sec = static_cast<time_t>(seconds);
108 abstime.tv_nsec =
109 static_cast<decltype(abstime.tv_nsec)>(n % kNanosPerSecond);
110 return abstime;
111 }
112
113#ifdef _WIN32
114 // Converts to milliseconds from now, or INFINITE when
115 // !has_timeout(). For use by SleepConditionVariableSRW on
116 // Windows. Callers should recognize that the return value is a
117 // relative duration (it should be recomputed by calling this method
118 // in the case of a spurious wakeup).
Loo Rong Jie44976eb2018-07-13 07:48:27 +0800119 // This header file may be included transitively by public header files,
120 // so we define our own DWORD and INFINITE instead of getting them from
Loo Rong Jie407252f2018-07-18 09:53:05 +0800121 // <intsafe.h> and <WinBase.h>.
Abseil Team2c5af552018-07-18 11:29:01 -0700122 typedef unsigned long DWord; // NOLINT
Loo Rong Jie44976eb2018-07-13 07:48:27 +0800123 DWord InMillisecondsFromNow() const {
Abseil Teama4c3fff2018-10-29 15:53:34 -0700124 constexpr DWord kInfinite = (std::numeric_limits<DWord>::max)();
mistergc2e75482017-09-19 16:54:40 -0400125 if (!has_timeout()) {
Loo Rong Jiea105cad2018-07-12 13:27:31 +0800126 return kInfinite;
mistergc2e75482017-09-19 16:54:40 -0400127 }
128 // The use of absl::Now() to convert from absolute time to
129 // relative time means that absl::Now() cannot use anything that
130 // depends on KernelTimeout (for example, Mutex) on Windows.
131 int64_t now = ToUnixNanos(absl::Now());
132 if (ns_ >= now) {
133 // Round up so that Now() + ms_from_now >= ns_.
134 constexpr uint64_t max_nanos =
Abseil Teama4c3fff2018-10-29 15:53:34 -0700135 (std::numeric_limits<int64_t>::max)() - 999999u;
mistergc2e75482017-09-19 16:54:40 -0400136 uint64_t ms_from_now =
137 (std::min<uint64_t>(max_nanos, ns_ - now) + 999999u) / 1000000u;
Loo Rong Jie22baa382018-07-18 09:55:24 +0800138 if (ms_from_now > kInfinite) {
Loo Rong Jiea105cad2018-07-12 13:27:31 +0800139 return kInfinite;
mistergc2e75482017-09-19 16:54:40 -0400140 }
Loo Rong Jie44976eb2018-07-13 07:48:27 +0800141 return static_cast<DWord>(ms_from_now);
mistergc2e75482017-09-19 16:54:40 -0400142 }
143 return 0;
144 }
145#endif
146
Abseil Team9e94e482017-11-10 06:33:50 -0800147 friend class Futex;
mistergc2e75482017-09-19 16:54:40 -0400148 friend class Waiter;
149};
150
151} // namespace synchronization_internal
Abseil Team12bc53e2019-12-12 10:36:03 -0800152ABSL_NAMESPACE_END
mistergc2e75482017-09-19 16:54:40 -0400153} // namespace absl
Abseil Teambf294702019-03-19 11:14:01 -0700154
mistergc2e75482017-09-19 16:54:40 -0400155#endif // ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_