Debian Codegraph @

src/core/lib/event_engine/posix_engine/timer.cc

raw
1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include <grpc/support/port_platform.h>
20
21 #include "src/core/lib/event_engine/posix_engine/timer.h"
22
23 #include <algorithm>
24 #include <atomic>
25 #include <limits>
26 #include <utility>
27
28 #include <grpc/support/cpu.h>
29
30 #include "src/core/lib/event_engine/posix_engine/timer_heap.h"
31 #include "src/core/lib/gpr/useful.h"
32 #include "src/core/lib/gprpp/time.h"
33
34 namespace grpc_event_engine {
35 namespace posix_engine {
36
37 static const size_t kInvalidHeapIndex = std::numeric_limits<size_t>::max();
38 static const double kAddDeadlineScale = 0.33;
39 static const double kMinQueueWindowDuration = 0.01;
40 static const double kMaxQueueWindowDuration = 1.0;
41
42 grpc_core::Timestamp TimerList::Shard::ComputeMinDeadline() {
43 return heap.is_empty()
44 ? queue_deadline_cap + grpc_core::Duration::Epsilon()
45 : grpc_core::Timestamp::FromMillisecondsAfterProcessEpoch(
46 heap.Top()->deadline);
47 }
48
49 TimerList::Shard::Shard() : stats(1.0 / kAddDeadlineScale, 0.1, 0.5) {}
50
51 TimerList::TimerList(TimerListHost* host)
52 : host_(host),
53 num_shards_(grpc_core::Clamp(2 * gpr_cpu_num_cores(), 1u, 32u)),
54 min_timer_(host_->Now().milliseconds_after_process_epoch()),
55 shards_(new Shard[num_shards_]),
56 shard_queue_(new Shard*[num_shards_]) {
57 for (size_t i = 0; i < num_shards_; i++) {
58 Shard& shard = shards_[i];
59 shard.queue_deadline_cap =
60 grpc_core::Timestamp::FromMillisecondsAfterProcessEpoch(
61 min_timer_.load(std::memory_order_relaxed));
62 shard.shard_queue_index = i;
63 shard.list.next = shard.list.prev = &shard.list;
64 shard.min_deadline = shard.ComputeMinDeadline();
65 shard_queue_[i] = &shard;
66 }
67 }
68
69 namespace {
70 /* returns true if the first element in the list */
71 void ListJoin(Timer* head, Timer* timer) {
72 timer->next = head;
73 timer->prev = head->prev;
74 timer->next->prev = timer->prev->next = timer;
75 }
76
77 void ListRemove(Timer* timer) {
78 timer->next->prev = timer->prev;
79 timer->prev->next = timer->next;
80 }
81 } // namespace
82
83 void TimerList::SwapAdjacentShardsInQueue(uint32_t first_shard_queue_index) {
84 Shard* temp;
85 temp = shard_queue_[first_shard_queue_index];
86 shard_queue_[first_shard_queue_index] =
87 shard_queue_[first_shard_queue_index + 1];
88 shard_queue_[first_shard_queue_index + 1] = temp;
89 shard_queue_[first_shard_queue_index]->shard_queue_index =
90 first_shard_queue_index;
91 shard_queue_[first_shard_queue_index + 1]->shard_queue_index =
92 first_shard_queue_index + 1;
93 }
94
95 void TimerList::NoteDeadlineChange(Shard* shard) {
96 while (shard->shard_queue_index > 0 &&
97 shard->min_deadline <
98 shard_queue_[shard->shard_queue_index - 1]->min_deadline) {
99 SwapAdjacentShardsInQueue(shard->shard_queue_index - 1);
100 }
101 while (shard->shard_queue_index < num_shards_ - 1 &&
102 shard->min_deadline >
103 shard_queue_[shard->shard_queue_index + 1]->min_deadline) {
104 SwapAdjacentShardsInQueue(shard->shard_queue_index);
105 }
106 }
107
108 void TimerList::TimerInit(Timer* timer, grpc_core::Timestamp deadline,
109 experimental::EventEngine::Closure* closure) {
110 bool is_first_timer = false;
111 Shard* shard = &shards_[grpc_core::HashPointer(timer, num_shards_)];
112 timer->closure = closure;
113 timer->deadline = deadline.milliseconds_after_process_epoch();
114
115 #ifndef NDEBUG
116 timer->hash_table_next = nullptr;
117 #endif
118
119 {
120 grpc_core::MutexLock lock(&shard->mu);
121 timer->pending = true;
122 grpc_core::Timestamp now = host_->Now();
123 if (deadline <= now) {
124 deadline = now;
125 }
126
127 shard->stats.AddSample((deadline - now).millis() / 1000.0);
128
129 if (deadline < shard->queue_deadline_cap) {
130 is_first_timer = shard->heap.Add(timer);
131 } else {
132 timer->heap_index = kInvalidHeapIndex;
133 ListJoin(&shard->list, timer);
134 }
135 }
136
137 /* Deadline may have decreased, we need to adjust the main queue. Note
138 that there is a potential racy unlocked region here. There could be a
139 reordering of multiple TimerInit calls, at this point, but the < test
140 below should ensure that we err on the side of caution. There could
141 also be a race with TimerCheck, which might beat us to the lock. In
142 that case, it is possible that the timer that we added will have already
143 run by the time we hold the lock, but that too is a safe error.
144 Finally, it's possible that the TimerCheck that intervened failed to
145 trigger the new timer because the min_deadline hadn't yet been reduced.
146 In that case, the timer will simply have to wait for the next
147 TimerCheck. */
148 if (is_first_timer) {
149 grpc_core::MutexLock lock(&mu_);
150 if (deadline < shard->min_deadline) {
151 grpc_core::Timestamp old_min_deadline = shard_queue_[0]->min_deadline;
152 shard->min_deadline = deadline;
153 NoteDeadlineChange(shard);
154 if (shard->shard_queue_index == 0 && deadline < old_min_deadline) {
155 min_timer_.store(deadline.milliseconds_after_process_epoch(),
156 std::memory_order_relaxed);
157 host_->Kick();
158 }
159 }
160 }
161 }
162
163 bool TimerList::TimerCancel(Timer* timer) {
164 Shard* shard = &shards_[grpc_core::HashPointer(timer, num_shards_)];
165 grpc_core::MutexLock lock(&shard->mu);
166
167 if (timer->pending) {
168 timer->pending = false;
169 if (timer->heap_index == kInvalidHeapIndex) {
170 ListRemove(timer);
171 } else {
172 shard->heap.Remove(timer);
173 }
174 return true;
175 }
176
177 return false;
178 }
179
180 /* Rebalances the timer shard by computing a new 'queue_deadline_cap' and moving
181 all relevant timers in shard->list (i.e timers with deadlines earlier than
182 'queue_deadline_cap') into into shard->heap.
183 Returns 'true' if shard->heap has at least ONE element */
184 bool TimerList::Shard::RefillHeap(grpc_core::Timestamp now) {
185 /* Compute the new queue window width and bound by the limits: */
186 double computed_deadline_delta = stats.UpdateAverage() * kAddDeadlineScale;
187 double deadline_delta =
188 grpc_core::Clamp(computed_deadline_delta, kMinQueueWindowDuration,
189 kMaxQueueWindowDuration);
190 Timer *timer, *next;
191
192 /* Compute the new cap and put all timers under it into the queue: */
193 queue_deadline_cap = std::max(now, queue_deadline_cap) +
194 grpc_core::Duration::FromSecondsAsDouble(deadline_delta);
195
196 for (timer = list.next; timer != &list; timer = next) {
197 next = timer->next;
198 auto timer_deadline =
199 grpc_core::Timestamp::FromMillisecondsAfterProcessEpoch(
200 timer->deadline);
201
202 if (timer_deadline < queue_deadline_cap) {
203 ListRemove(timer);
204 heap.Add(timer);
205 }
206 }
207 return !heap.is_empty();
208 }
209
210 /* This pops the next non-cancelled timer with deadline <= now from the
211 queue, or returns NULL if there isn't one. */
212 Timer* TimerList::Shard::PopOne(grpc_core::Timestamp now) {
213 Timer* timer;
214 for (;;) {
215 if (heap.is_empty()) {
216 if (now < queue_deadline_cap) return nullptr;
217 if (!RefillHeap(now)) return nullptr;
218 }
219 timer = heap.Top();
220 auto timer_deadline =
221 grpc_core::Timestamp::FromMillisecondsAfterProcessEpoch(
222 timer->deadline);
223 if (timer_deadline > now) return nullptr;
224 timer->pending = false;
225 heap.Pop();
226 return timer;
227 }
228 }
229
230 void TimerList::Shard::PopTimers(
231 grpc_core::Timestamp now, grpc_core::Timestamp* new_min_deadline,
232 std::vector<experimental::EventEngine::Closure*>* out) {
233 grpc_core::MutexLock lock(&mu);
234 while (Timer* timer = PopOne(now)) {
235 out->push_back(timer->closure);
236 }
237 *new_min_deadline = ComputeMinDeadline();
238 }
239
240 std::vector<experimental::EventEngine::Closure*> TimerList::FindExpiredTimers(
241 grpc_core::Timestamp now, grpc_core::Timestamp* next) {
242 grpc_core::Timestamp min_timer =
243 grpc_core::Timestamp::FromMillisecondsAfterProcessEpoch(
244 min_timer_.load(std::memory_order_relaxed));
245
246 std::vector<experimental::EventEngine::Closure*> done;
247 if (now < min_timer) {
248 if (next != nullptr) *next = std::min(*next, min_timer);
249 return done;
250 }
251
252 grpc_core::MutexLock lock(&mu_);
253
254 while (shard_queue_[0]->min_deadline < now ||
255 (now != grpc_core::Timestamp::InfFuture() &&
256 shard_queue_[0]->min_deadline == now)) {
257 grpc_core::Timestamp new_min_deadline;
258
259 /* For efficiency, we pop as many available timers as we can from the
260 shard. This may violate perfect timer deadline ordering, but that
261 shouldn't be a big deal because we don't make ordering guarantees. */
262 shard_queue_[0]->PopTimers(now, &new_min_deadline, &done);
263
264 /* An TimerInit() on the shard could intervene here, adding a new
265 timer that is earlier than new_min_deadline. However,
266 TimerInit() will block on the mutex before it can call
267 set_min_deadline, so this one will complete first and then the Addtimer
268 will reduce the min_deadline (perhaps unnecessarily). */
269 shard_queue_[0]->min_deadline = new_min_deadline;
270 NoteDeadlineChange(shard_queue_[0]);
271 }
272
273 if (next) {
274 *next = std::min(*next, shard_queue_[0]->min_deadline);
275 }
276
277 min_timer_.store(
278 shard_queue_[0]->min_deadline.milliseconds_after_process_epoch(),
279 std::memory_order_relaxed);
280
281 return done;
282 }
283
284 absl::optional<std::vector<experimental::EventEngine::Closure*>>
285 TimerList::TimerCheck(grpc_core::Timestamp* next) {
286 // prelude
287 grpc_core::Timestamp now = host_->Now();
288
289 /* fetch from a thread-local first: this avoids contention on a globally
290 mutable cacheline in the common case */
291 grpc_core::Timestamp min_timer =
292 grpc_core::Timestamp::FromMillisecondsAfterProcessEpoch(
293 min_timer_.load(std::memory_order_relaxed));
294
295 if (now < min_timer) {
296 if (next != nullptr) {
297 *next = std::min(*next, min_timer);
298 }
299 return std::vector<experimental::EventEngine::Closure*>();
300 }
301
302 if (!checker_mu_.TryLock()) return absl::nullopt;
303 std::vector<experimental::EventEngine::Closure*> run =
304 FindExpiredTimers(now, next);
305 checker_mu_.Unlock();
306
307 return std::move(run);
308 }
309
310 } // namespace posix_engine
311 } // namespace grpc_event_engine