kernel_timeout.h 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  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. // An optional absolute timeout, with nanosecond granularity,
  16. // compatible with absl::Time. Suitable for in-register
  17. // parameter-passing (e.g. syscalls.)
  18. // Constructible from a absl::Time (for a timeout to be respected) or {}
  19. // (for "no timeout".)
  20. // This is a private low-level API for use by a handful of low-level
  21. // components that are friends of this class. Higher-level components
  22. // should build APIs based on absl::Time and absl::Duration.
  23. #ifndef ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_
  24. #define ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_
  25. #include <time.h>
  26. #include <algorithm>
  27. #include <limits>
  28. #include "absl/base/internal/raw_logging.h"
  29. #include "absl/time/clock.h"
  30. #include "absl/time/time.h"
  31. namespace absl {
  32. ABSL_NAMESPACE_BEGIN
  33. namespace synchronization_internal {
  34. class Futex;
  35. class Waiter;
  36. class KernelTimeout {
  37. public:
  38. // A timeout that should expire at <t>. Any value, in the full
  39. // InfinitePast() to InfiniteFuture() range, is valid here and will be
  40. // respected.
  41. explicit KernelTimeout(absl::Time t) : ns_(MakeNs(t)) {}
  42. // No timeout.
  43. KernelTimeout() : ns_(0) {}
  44. // A more explicit factory for those who prefer it. Equivalent to {}.
  45. static KernelTimeout Never() { return {}; }
  46. // We explicitly do not support other custom formats: timespec, int64_t nanos.
  47. // Unify on this and absl::Time, please.
  48. bool has_timeout() const { return ns_ != 0; }
  49. // Convert to parameter for sem_timedwait/futex/similar. Only for approved
  50. // users. Do not call if !has_timeout.
  51. struct timespec MakeAbsTimespec();
  52. private:
  53. // internal rep, not user visible: ns after unix epoch.
  54. // zero = no timeout.
  55. // Negative we treat as an unlikely (and certainly expired!) but valid
  56. // timeout.
  57. int64_t ns_;
  58. static int64_t MakeNs(absl::Time t) {
  59. // optimization--InfiniteFuture is common "no timeout" value
  60. // and cheaper to compare than convert.
  61. if (t == absl::InfiniteFuture()) return 0;
  62. int64_t x = ToUnixNanos(t);
  63. // A timeout that lands exactly on the epoch (x=0) needs to be respected,
  64. // so we alter it unnoticably to 1. Negative timeouts are in
  65. // theory supported, but handled poorly by the kernel (long
  66. // delays) so push them forward too; since all such times have
  67. // already passed, it's indistinguishable.
  68. if (x <= 0) x = 1;
  69. // A time larger than what can be represented to the kernel is treated
  70. // as no timeout.
  71. if (x == (std::numeric_limits<int64_t>::max)()) x = 0;
  72. return x;
  73. }
  74. #ifdef _WIN32
  75. // Converts to milliseconds from now, or INFINITE when
  76. // !has_timeout(). For use by SleepConditionVariableSRW on
  77. // Windows. Callers should recognize that the return value is a
  78. // relative duration (it should be recomputed by calling this method
  79. // in the case of a spurious wakeup).
  80. // This header file may be included transitively by public header files,
  81. // so we define our own DWORD and INFINITE instead of getting them from
  82. // <intsafe.h> and <WinBase.h>.
  83. typedef unsigned long DWord; // NOLINT
  84. DWord InMillisecondsFromNow() const {
  85. constexpr DWord kInfinite = (std::numeric_limits<DWord>::max)();
  86. if (!has_timeout()) {
  87. return kInfinite;
  88. }
  89. // The use of absl::Now() to convert from absolute time to
  90. // relative time means that absl::Now() cannot use anything that
  91. // depends on KernelTimeout (for example, Mutex) on Windows.
  92. int64_t now = ToUnixNanos(absl::Now());
  93. if (ns_ >= now) {
  94. // Round up so that Now() + ms_from_now >= ns_.
  95. constexpr uint64_t max_nanos =
  96. (std::numeric_limits<int64_t>::max)() - 999999u;
  97. uint64_t ms_from_now =
  98. (std::min<uint64_t>(max_nanos, ns_ - now) + 999999u) / 1000000u;
  99. if (ms_from_now > kInfinite) {
  100. return kInfinite;
  101. }
  102. return static_cast<DWord>(ms_from_now);
  103. }
  104. return 0;
  105. }
  106. #endif
  107. friend class Futex;
  108. friend class Waiter;
  109. };
  110. inline struct timespec KernelTimeout::MakeAbsTimespec() {
  111. int64_t n = ns_;
  112. static const int64_t kNanosPerSecond = 1000 * 1000 * 1000;
  113. if (n == 0) {
  114. ABSL_RAW_LOG(
  115. ERROR, "Tried to create a timespec from a non-timeout; never do this.");
  116. // But we'll try to continue sanely. no-timeout ~= saturated timeout.
  117. n = (std::numeric_limits<int64_t>::max)();
  118. }
  119. // Kernel APIs validate timespecs as being at or after the epoch,
  120. // despite the kernel time type being signed. However, no one can
  121. // tell the difference between a timeout at or before the epoch (since
  122. // all such timeouts have expired!)
  123. if (n < 0) n = 0;
  124. struct timespec abstime;
  125. int64_t seconds = (std::min)(n / kNanosPerSecond,
  126. int64_t{(std::numeric_limits<time_t>::max)()});
  127. abstime.tv_sec = static_cast<time_t>(seconds);
  128. abstime.tv_nsec = static_cast<decltype(abstime.tv_nsec)>(n % kNanosPerSecond);
  129. return abstime;
  130. }
  131. } // namespace synchronization_internal
  132. ABSL_NAMESPACE_END
  133. } // namespace absl
  134. #endif // ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_