cd9f5c7ed28b39ab644d10b341017ddca6bb5736
[folly.git] / folly / io / async / HHWheelTimer.cpp
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
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
11  *
12  *   http://www.apache.org/licenses/LICENSE-2.0
13  *
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
19  * under the License.
20  */
21 #include <folly/io/async/HHWheelTimer.h>
22 #include <folly/io/async/Request.h>
23
24 #include <folly/Optional.h>
25 #include <folly/ScopeGuard.h>
26
27 #include <cassert>
28
29 using std::chrono::milliseconds;
30
31 namespace folly {
32
33 /**
34  * We want to select the default interval carefully.
35  * An interval of 10ms will give us 10ms * WHEEL_SIZE^WHEEL_BUCKETS
36  * for the largest timeout possible, or about 497 days.
37  *
38  * For a lower bound, we want a reasonable limit on local IO, 10ms
39  * seems short enough
40  *
41  * A shorter interval also has CPU implications, less than 1ms might
42  * start showing up in cpu perf.  Also, it might not be possible to set
43  * tick interval less than 10ms on older kernels.
44  */
45 int HHWheelTimer::DEFAULT_TICK_INTERVAL = 10;
46
47 HHWheelTimer::Callback::~Callback() {
48   if (isScheduled()) {
49     cancelTimeout();
50   }
51 }
52
53 void HHWheelTimer::Callback::setScheduled(HHWheelTimer* wheel,
54                                           std::chrono::milliseconds timeout) {
55   assert(wheel_ == nullptr);
56   assert(expiration_ == milliseconds(0));
57
58   wheelGuard_ = DestructorGuard(wheel);
59   wheel_ = wheel;
60
61   // Only update the now_ time if we're not in a timeout expired callback
62   if (wheel_->count_  == 0 && !wheel_->processingCallbacksGuard_) {
63     wheel_->now_ = getCurTime();
64   }
65
66   expiration_ = wheel_->now_ + timeout;
67 }
68
69 void HHWheelTimer::Callback::cancelTimeoutImpl() {
70   if (--wheel_->count_ <= 0) {
71     assert(wheel_->count_ == 0);
72     wheel_->AsyncTimeout::cancelTimeout();
73   }
74   hook_.unlink();
75
76   wheel_ = nullptr;
77   wheelGuard_ = folly::none;
78   expiration_ = milliseconds(0);
79 }
80
81 HHWheelTimer::HHWheelTimer(folly::EventBase* eventBase,
82                            std::chrono::milliseconds intervalMS,
83                            AsyncTimeout::InternalEnum internal,
84                            std::chrono::milliseconds defaultTimeoutMS)
85   : AsyncTimeout(eventBase, internal)
86   , interval_(intervalMS)
87   , defaultTimeout_(defaultTimeoutMS)
88   , nextTick_(1)
89   , count_(0)
90   , catchupEveryN_(DEFAULT_CATCHUP_EVERY_N)
91   , expirationsSinceCatchup_(0)
92   , processingCallbacksGuard_(false)
93 {
94 }
95
96 HHWheelTimer::~HHWheelTimer() {
97   CHECK(count_ == 0);
98 }
99
100 void HHWheelTimer::destroy() {
101   assert(count_ == 0);
102   cancelAll();
103   DelayedDestruction::destroy();
104 }
105
106 void HHWheelTimer::scheduleTimeoutImpl(Callback* callback,
107                                        std::chrono::milliseconds timeout) {
108   int64_t due = timeToWheelTicks(timeout) + nextTick_;
109   int64_t diff = due - nextTick_;
110   CallbackList* list;
111
112   if (diff < 0) {
113     list = &buckets_[0][nextTick_ & WHEEL_MASK];
114   } else if (diff < WHEEL_SIZE) {
115     list = &buckets_[0][due & WHEEL_MASK];
116   } else if (diff < 1 << (2 * WHEEL_BITS)) {
117     list = &buckets_[1][(due >> WHEEL_BITS) & WHEEL_MASK];
118   } else if (diff < 1 << (3 * WHEEL_BITS)) {
119     list = &buckets_[2][(due >> 2 * WHEEL_BITS) & WHEEL_MASK];
120   } else {
121     /* in largest slot */
122     if (diff > LARGEST_SLOT) {
123       diff = LARGEST_SLOT;
124       due = diff + nextTick_;
125     }
126     list = &buckets_[3][(due >> 3 * WHEEL_BITS) & WHEEL_MASK];
127   }
128   list->push_back(*callback);
129 }
130
131 void HHWheelTimer::scheduleTimeout(Callback* callback,
132                                    std::chrono::milliseconds timeout) {
133   // Cancel the callback if it happens to be scheduled already.
134   callback->cancelTimeout();
135
136   callback->context_ = RequestContext::saveContext();
137
138   if (count_ == 0 && !processingCallbacksGuard_) {
139     this->AsyncTimeout::scheduleTimeout(interval_.count());
140   }
141
142   callback->setScheduled(this, timeout);
143   scheduleTimeoutImpl(callback, timeout);
144   count_++;
145 }
146
147 void HHWheelTimer::scheduleTimeout(Callback* callback) {
148   CHECK(std::chrono::milliseconds(-1) != defaultTimeout_)
149       << "Default timeout was not initialized";
150   scheduleTimeout(callback, defaultTimeout_);
151 }
152
153 bool HHWheelTimer::cascadeTimers(int bucket, int tick) {
154   CallbackList cbs;
155   cbs.swap(buckets_[bucket][tick]);
156   while (!cbs.empty()) {
157     auto* cb = &cbs.front();
158     cbs.pop_front();
159     scheduleTimeoutImpl(cb, cb->getTimeRemaining(now_));
160   }
161
162   // If tick is zero, timeoutExpired will cascade the next bucket.
163   return tick == 0;
164 }
165
166 void HHWheelTimer::timeoutExpired() noexcept {
167   // If destroy() is called inside timeoutExpired(), delay actual destruction
168   // until timeoutExpired() returns
169   DestructorGuard dg(this);
170   // If scheduleTimeout is called from a callback in this function, it may
171   // cause inconsistencies in the state of this object. As such, we need
172   // to treat these calls slightly differently.
173   processingCallbacksGuard_ = true;
174   auto reEntryGuard = folly::makeGuard([&] {
175     processingCallbacksGuard_ = false;
176   });
177
178   // timeoutExpired() can only be invoked directly from the event base loop.
179   // It should never be invoked recursively.
180   //
181   milliseconds catchup = now_ + interval_;
182   // If catchup is enabled, we may have missed multiple intervals, use
183   // currentTime() to check exactly.
184   if (++expirationsSinceCatchup_ >= catchupEveryN_) {
185     catchup = std::chrono::duration_cast<milliseconds>(
186       std::chrono::steady_clock::now().time_since_epoch());
187     expirationsSinceCatchup_ = 0;
188   }
189   while (now_ < catchup) {
190     now_ += interval_;
191
192     int idx = nextTick_ & WHEEL_MASK;
193     if (0 == idx) {
194       // Cascade timers
195       if (cascadeTimers(1, (nextTick_ >> WHEEL_BITS) & WHEEL_MASK) &&
196           cascadeTimers(2, (nextTick_ >> (2 * WHEEL_BITS)) & WHEEL_MASK)) {
197         cascadeTimers(3, (nextTick_ >> (3 * WHEEL_BITS)) & WHEEL_MASK);
198       }
199     }
200
201     nextTick_++;
202     CallbackList* cbs = &buckets_[0][idx];
203     while (!cbs->empty()) {
204       auto* cb = &cbs->front();
205       cbs->pop_front();
206       count_--;
207       cb->wheel_ = nullptr;
208       cb->expiration_ = milliseconds(0);
209       auto old_ctx =
210         RequestContext::setContext(cb->context_);
211       cb->timeoutExpired();
212       RequestContext::setContext(old_ctx);
213     }
214   }
215   if (count_ > 0) {
216     this->AsyncTimeout::scheduleTimeout(interval_.count());
217   }
218 }
219
220 size_t HHWheelTimer::cancelAll() {
221   size_t count = 0;
222
223   if (count_ != 0) {
224     decltype(buckets_) buckets;
225
226 // Work around std::swap() bug in libc++
227 //
228 // http://llvm.org/bugs/show_bug.cgi?id=22106
229 #if FOLLY_USE_LIBCPP
230     for (size_t i = 0; i < WHEEL_BUCKETS; ++i) {
231       for (size_t ii = 0; ii < WHEEL_SIZE; ++ii) {
232         std::swap(buckets_[i][ii], buckets[i][ii]);
233       }
234     }
235 #else
236     std::swap(buckets, buckets_);
237 #endif
238
239     for (auto& tick : buckets) {
240       for (auto& bucket : tick) {
241         while (!bucket.empty()) {
242           auto& cb = bucket.front();
243           cb.cancelTimeout();
244           cb.callbackCanceled();
245           count++;
246         }
247       }
248     }
249   }
250
251   return count;
252 }
253
254 } // folly