HHWheelTimer::cancelAll
[folly.git] / folly / io / async / HHWheelTimer.cpp
1 /*
2  * Copyright 2014 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/ScopeGuard.h>
25
26 #include <cassert>
27
28 using std::chrono::milliseconds;
29
30 namespace folly {
31
32 /**
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.
36  *
37  * For a lower bound, we want a reasonable limit on local IO, 10ms
38  * seems short enough
39  *
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.
43  */
44 int HHWheelTimer::DEFAULT_TICK_INTERVAL = 10;
45
46 HHWheelTimer::Callback::~Callback() {
47   if (isScheduled()) {
48     cancelTimeout();
49   }
50 }
51
52 void HHWheelTimer::Callback::setScheduled(HHWheelTimer* wheel,
53                                           std::chrono::milliseconds timeout) {
54   assert(wheel_ == nullptr);
55   assert(expiration_ == milliseconds(0));
56
57   wheel_ = wheel;
58
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();
62   }
63
64   expiration_ = wheel_->now_ + timeout;
65 }
66
67 void HHWheelTimer::Callback::cancelTimeoutImpl() {
68   if (--wheel_->count_ <= 0) {
69     assert(wheel_->count_ == 0);
70     wheel_->AsyncTimeout::cancelTimeout();
71   }
72   hook_.unlink();
73
74   wheel_ = nullptr;
75   expiration_ = milliseconds(0);
76 }
77
78 HHWheelTimer::HHWheelTimer(folly::EventBase* eventBase,
79                            std::chrono::milliseconds intervalMS)
80   : AsyncTimeout(eventBase)
81   , interval_(intervalMS)
82   , nextTick_(1)
83   , count_(0)
84   , catchupEveryN_(DEFAULT_CATCHUP_EVERY_N)
85   , expirationsSinceCatchup_(0)
86   , processingCallbacksGuard_(false)
87 {
88 }
89
90 HHWheelTimer::~HHWheelTimer() {
91 }
92
93 void HHWheelTimer::destroy() {
94   assert(count_ == 0);
95   DelayedDestruction::destroy();
96 }
97
98 void HHWheelTimer::scheduleTimeoutImpl(Callback* callback,
99                                        std::chrono::milliseconds timeout) {
100   int64_t due = timeToWheelTicks(timeout) + nextTick_;
101   int64_t diff = due - nextTick_;
102   CallbackList* list;
103
104   if (diff < 0) {
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];
112   } else {
113     /* in largest slot */
114     if (diff > LARGEST_SLOT) {
115       diff = LARGEST_SLOT;
116       due = diff + nextTick_;
117     }
118     list = &buckets_[3][(due >> 3 * WHEEL_BITS) & WHEEL_MASK];
119   }
120   list->push_back(*callback);
121 }
122
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();
127
128   callback->context_ = RequestContext::saveContext();
129
130   if (count_ == 0 && !processingCallbacksGuard_) {
131     this->AsyncTimeout::scheduleTimeout(interval_.count());
132   }
133
134   callback->setScheduled(this, timeout);
135   scheduleTimeoutImpl(callback, timeout);
136   count_++;
137 }
138
139 bool HHWheelTimer::cascadeTimers(int bucket, int tick) {
140   CallbackList cbs;
141   cbs.swap(buckets_[bucket][tick]);
142   while (!cbs.empty()) {
143     auto* cb = &cbs.front();
144     cbs.pop_front();
145     scheduleTimeoutImpl(cb, cb->getTimeRemaining(now_));
146   }
147
148   // If tick is zero, timeoutExpired will cascade the next bucket.
149   return tick == 0;
150 }
151
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;
162   });
163
164   // timeoutExpired() can only be invoked directly from the event base loop.
165   // It should never be invoked recursively.
166   //
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;
174   }
175   while (now_ < catchup) {
176     now_ += interval_;
177
178     int idx = nextTick_ & WHEEL_MASK;
179     if (0 == idx) {
180       // Cascade timers
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);
184       }
185     }
186
187     nextTick_++;
188     CallbackList* cbs = &buckets_[0][idx];
189     while (!cbs->empty()) {
190       auto* cb = &cbs->front();
191       cbs->pop_front();
192       count_--;
193       cb->wheel_ = nullptr;
194       cb->expiration_ = milliseconds(0);
195       auto old_ctx =
196         RequestContext::setContext(cb->context_);
197       cb->timeoutExpired();
198       RequestContext::setContext(old_ctx);
199     }
200   }
201   if (count_ > 0) {
202     this->AsyncTimeout::scheduleTimeout(interval_.count());
203   }
204 }
205
206 size_t HHWheelTimer::cancelAll() {
207   decltype(buckets_) buckets;
208   std::swap(buckets, buckets_);
209   size_t count = 0;
210
211   for (auto& tick : buckets) {
212     for (auto& bucket : tick) {
213       while (!bucket.empty()) {
214         auto& cb = bucket.front();
215         cb.cancelTimeout();
216         cb.callbackCanceled();
217         count++;
218       }
219     }
220   }
221
222   return count;
223 }
224
225 } // folly