You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

kernel_timeout.h 7.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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. {
  33. ABSL_NAMESPACE_BEGIN
  34. namespace synchronization_internal
  35. {
  36. class Futex;
  37. class Waiter;
  38. class KernelTimeout
  39. {
  40. public:
  41. // A timeout that should expire at <t>. Any value, in the full
  42. // InfinitePast() to InfiniteFuture() range, is valid here and will be
  43. // respected.
  44. explicit KernelTimeout(absl::Time t) :
  45. ns_(MakeNs(t))
  46. {
  47. }
  48. // No timeout.
  49. KernelTimeout() :
  50. ns_(0)
  51. {
  52. }
  53. // A more explicit factory for those who prefer it. Equivalent to {}.
  54. static KernelTimeout Never()
  55. {
  56. return {};
  57. }
  58. // We explicitly do not support other custom formats: timespec, int64_t nanos.
  59. // Unify on this and absl::Time, please.
  60. bool has_timeout() const
  61. {
  62. return ns_ != 0;
  63. }
  64. // Convert to parameter for sem_timedwait/futex/similar. Only for approved
  65. // users. Do not call if !has_timeout.
  66. struct timespec MakeAbsTimespec();
  67. private:
  68. // internal rep, not user visible: ns after unix epoch.
  69. // zero = no timeout.
  70. // Negative we treat as an unlikely (and certainly expired!) but valid
  71. // timeout.
  72. int64_t ns_;
  73. static int64_t MakeNs(absl::Time t)
  74. {
  75. // optimization--InfiniteFuture is common "no timeout" value
  76. // and cheaper to compare than convert.
  77. if (t == absl::InfiniteFuture())
  78. return 0;
  79. int64_t x = ToUnixNanos(t);
  80. // A timeout that lands exactly on the epoch (x=0) needs to be respected,
  81. // so we alter it unnoticably to 1. Negative timeouts are in
  82. // theory supported, but handled poorly by the kernel (long
  83. // delays) so push them forward too; since all such times have
  84. // already passed, it's indistinguishable.
  85. if (x <= 0)
  86. 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)())
  90. x = 0;
  91. return x;
  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
  103. DWord InMillisecondsFromNow() const
  104. {
  105. constexpr DWord kInfinite = (std::numeric_limits<DWord>::max)();
  106. if (!has_timeout())
  107. {
  108. return kInfinite;
  109. }
  110. // The use of absl::Now() to convert from absolute time to
  111. // relative time means that absl::Now() cannot use anything that
  112. // depends on KernelTimeout (for example, Mutex) on Windows.
  113. int64_t now = ToUnixNanos(absl::Now());
  114. if (ns_ >= now)
  115. {
  116. // Round up so that Now() + ms_from_now >= ns_.
  117. constexpr uint64_t max_nanos =
  118. (std::numeric_limits<int64_t>::max)() - 999999u;
  119. uint64_t ms_from_now =
  120. (std::min<uint64_t>(max_nanos, ns_ - now) + 999999u) / 1000000u;
  121. if (ms_from_now > kInfinite)
  122. {
  123. return kInfinite;
  124. }
  125. return static_cast<DWord>(ms_from_now);
  126. }
  127. return 0;
  128. }
  129. #endif
  130. friend class Futex;
  131. friend class Waiter;
  132. };
  133. inline struct timespec KernelTimeout::MakeAbsTimespec()
  134. {
  135. int64_t n = ns_;
  136. static const int64_t kNanosPerSecond = 1000 * 1000 * 1000;
  137. if (n == 0)
  138. {
  139. ABSL_RAW_LOG(
  140. ERROR, "Tried to create a timespec from a non-timeout; never do this."
  141. );
  142. // But we'll try to continue sanely. no-timeout ~= saturated timeout.
  143. n = (std::numeric_limits<int64_t>::max)();
  144. }
  145. // Kernel APIs validate timespecs as being at or after the epoch,
  146. // despite the kernel time type being signed. However, no one can
  147. // tell the difference between a timeout at or before the epoch (since
  148. // all such timeouts have expired!)
  149. if (n < 0)
  150. n = 0;
  151. struct timespec abstime;
  152. int64_t seconds = (std::min)(n / kNanosPerSecond, int64_t{(std::numeric_limits<time_t>::max)()});
  153. abstime.tv_sec = static_cast<time_t>(seconds);
  154. abstime.tv_nsec = static_cast<decltype(abstime.tv_nsec)>(n % kNanosPerSecond);
  155. return abstime;
  156. }
  157. } // namespace synchronization_internal
  158. ABSL_NAMESPACE_END
  159. } // namespace absl
  160. #endif // ABSL_SYNCHRONIZATION_INTERNAL_KERNEL_TIMEOUT_H_