2 * Copyright 2014 Facebook, Inc.
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
21 #include <folly/io/async/HHWheelTimer.h>
22 #include <folly/io/async/Request.h>
24 #include <folly/ScopeGuard.h>
28 using std::chrono::milliseconds;
33 * We want to select the default interval carefully.
34 * An interval of 10ms will give us 10ms * WHEEL_SIZE^WHEEL_BUCKETS
35 * for the largest timeout possible, or about 497 days.
37 * For a lower bound, we want a reasonable limit on local IO, 10ms
40 * A shorter interval also has CPU implications, less than 1ms might
41 * start showing up in cpu perf. Also, it might not be possible to set
42 * tick interval less than 10ms on older kernels.
44 int HHWheelTimer::DEFAULT_TICK_INTERVAL = 10;
46 HHWheelTimer::Callback::~Callback() {
52 void HHWheelTimer::Callback::setScheduled(HHWheelTimer* wheel,
53 std::chrono::milliseconds timeout) {
54 assert(wheel_ == nullptr);
55 assert(expiration_ == milliseconds(0));
59 // Only update the now_ time if we're not in a timeout expired callback
60 if (wheel_->count_ == 0 && !wheel_->processingCallbacksGuard_) {
61 wheel_->now_ = getCurTime();
64 expiration_ = wheel_->now_ + timeout;
67 void HHWheelTimer::Callback::cancelTimeoutImpl() {
68 if (--wheel_->count_ <= 0) {
69 assert(wheel_->count_ == 0);
70 wheel_->AsyncTimeout::cancelTimeout();
75 expiration_ = milliseconds(0);
78 HHWheelTimer::HHWheelTimer(folly::EventBase* eventBase,
79 std::chrono::milliseconds intervalMS)
80 : AsyncTimeout(eventBase)
81 , interval_(intervalMS)
84 , catchupEveryN_(DEFAULT_CATCHUP_EVERY_N)
85 , expirationsSinceCatchup_(0)
86 , processingCallbacksGuard_(false)
90 HHWheelTimer::~HHWheelTimer() {
93 void HHWheelTimer::destroy() {
95 DelayedDestruction::destroy();
98 void HHWheelTimer::scheduleTimeoutImpl(Callback* callback,
99 std::chrono::milliseconds timeout) {
100 int64_t due = timeToWheelTicks(timeout) + nextTick_;
101 int64_t diff = due - nextTick_;
105 list = &buckets_[0][nextTick_ & WHEEL_MASK];
106 } else if (diff < WHEEL_SIZE) {
107 list = &buckets_[0][due & WHEEL_MASK];
108 } else if (diff < 1 << (2 * WHEEL_BITS)) {
109 list = &buckets_[1][(due >> WHEEL_BITS) & WHEEL_MASK];
110 } else if (diff < 1 << (3 * WHEEL_BITS)) {
111 list = &buckets_[2][(due >> 2 * WHEEL_BITS) & WHEEL_MASK];
113 /* in largest slot */
114 if (diff > LARGEST_SLOT) {
116 due = diff + nextTick_;
118 list = &buckets_[3][(due >> 3 * WHEEL_BITS) & WHEEL_MASK];
120 list->push_back(*callback);
123 void HHWheelTimer::scheduleTimeout(Callback* callback,
124 std::chrono::milliseconds timeout) {
125 // Cancel the callback if it happens to be scheduled already.
126 callback->cancelTimeout();
128 callback->context_ = RequestContext::saveContext();
130 if (count_ == 0 && !processingCallbacksGuard_) {
131 this->AsyncTimeout::scheduleTimeout(interval_.count());
134 callback->setScheduled(this, timeout);
135 scheduleTimeoutImpl(callback, timeout);
139 bool HHWheelTimer::cascadeTimers(int bucket, int tick) {
141 cbs.swap(buckets_[bucket][tick]);
142 while (!cbs.empty()) {
143 auto* cb = &cbs.front();
145 scheduleTimeoutImpl(cb, cb->getTimeRemaining(now_));
148 // If tick is zero, timeoutExpired will cascade the next bucket.
152 void HHWheelTimer::timeoutExpired() noexcept {
153 // If destroy() is called inside timeoutExpired(), delay actual destruction
154 // until timeoutExpired() returns
155 DestructorGuard dg(this);
156 // If scheduleTimeout is called from a callback in this function, it may
157 // cause inconsistencies in the state of this object. As such, we need
158 // to treat these calls slightly differently.
159 processingCallbacksGuard_ = true;
160 auto reEntryGuard = folly::makeGuard([&] {
161 processingCallbacksGuard_ = false;
164 // timeoutExpired() can only be invoked directly from the event base loop.
165 // It should never be invoked recursively.
167 milliseconds catchup = now_ + interval_;
168 // If catchup is enabled, we may have missed multiple intervals, use
169 // currentTime() to check exactly.
170 if (++expirationsSinceCatchup_ >= catchupEveryN_) {
171 catchup = std::chrono::duration_cast<milliseconds>(
172 std::chrono::steady_clock::now().time_since_epoch());
173 expirationsSinceCatchup_ = 0;
175 while (now_ < catchup) {
178 int idx = nextTick_ & WHEEL_MASK;
181 if (cascadeTimers(1, (nextTick_ >> WHEEL_BITS) & WHEEL_MASK) &&
182 cascadeTimers(2, (nextTick_ >> (2 * WHEEL_BITS)) & WHEEL_MASK)) {
183 cascadeTimers(3, (nextTick_ >> (3 * WHEEL_BITS)) & WHEEL_MASK);
188 CallbackList* cbs = &buckets_[0][idx];
189 while (!cbs->empty()) {
190 auto* cb = &cbs->front();
193 cb->wheel_ = nullptr;
194 cb->expiration_ = milliseconds(0);
196 RequestContext::setContext(cb->context_);
197 cb->timeoutExpired();
198 RequestContext::setContext(old_ctx);
202 this->AsyncTimeout::scheduleTimeout(interval_.count());
206 size_t HHWheelTimer::cancelAll() {
207 decltype(buckets_) buckets;
208 std::swap(buckets, buckets_);
211 for (auto& tick : buckets) {
212 for (auto& bucket : tick) {
213 while (!bucket.empty()) {
214 auto& cb = bucket.front();
216 cb.callbackCanceled();