Cheaper bumpHandlingTime
[folly.git] / folly / io / async / EventBase.cpp
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #ifndef __STDC_FORMAT_MACROS
18 #define __STDC_FORMAT_MACROS
19 #endif
20
21 #include <folly/io/async/EventBase.h>
22
23 #include <folly/ThreadName.h>
24 #include <folly/io/async/NotificationQueue.h>
25
26 #include <condition_variable>
27 #include <fcntl.h>
28 #include <mutex>
29 #include <pthread.h>
30 #include <unistd.h>
31
32 namespace {
33
34 using folly::EventBase;
35
36 class FunctionLoopCallback : public EventBase::LoopCallback {
37  public:
38   explicit FunctionLoopCallback(EventBase::Func&& function)
39       : function_(std::move(function)) {}
40
41   void runLoopCallback() noexcept override {
42     function_();
43     delete this;
44   }
45
46  private:
47   EventBase::Func function_;
48 };
49 }
50
51 namespace folly {
52
53 /*
54  * EventBase::FunctionRunner
55  */
56
57 class EventBase::FunctionRunner
58     : public NotificationQueue<EventBase::Func>::Consumer {
59  public:
60   void messageAvailable(Func&& msg) override {
61     // In libevent2, internal events do not break the loop.
62     // Most users would expect loop(), followed by runInEventBaseThread(),
63     // to break the loop and check if it should exit or not.
64     // To have similar bejaviour to libevent1.4, tell the loop to break here.
65     // Note that loop() may still continue to loop, but it will also check the
66     // stop_ flag as well as runInLoop callbacks, etc.
67     event_base_loopbreak(getEventBase()->evb_);
68
69     if (!msg) {
70       // terminateLoopSoon() sends a null message just to
71       // wake up the loop.  We can ignore these messages.
72       return;
73     }
74
75     // The function should never throw an exception, because we have no
76     // way of knowing what sort of error handling to perform.
77     //
78     // If it does throw, log a message and abort the program.
79     try {
80       msg();
81     } catch (const std::exception& ex) {
82       LOG(ERROR) << "runInEventBaseThread() function threw a "
83                  << typeid(ex).name() << " exception: " << ex.what();
84       abort();
85     } catch (...) {
86       LOG(ERROR) << "runInEventBaseThread() function threw an exception";
87       abort();
88     }
89   }
90 };
91
92 /*
93  * EventBase::CobTimeout methods
94  */
95
96 void EventBase::CobTimeout::timeoutExpired() noexcept {
97   // For now, we just swallow any exceptions that the callback threw.
98   try {
99     cob_();
100   } catch (const std::exception& ex) {
101     LOG(ERROR) << "EventBase::runAfterDelay() callback threw "
102                << typeid(ex).name() << " exception: " << ex.what();
103   } catch (...) {
104     LOG(ERROR) << "EventBase::runAfterDelay() callback threw non-exception "
105                << "type";
106   }
107
108   // The CobTimeout object was allocated on the heap by runAfterDelay(),
109   // so delete it now that the it has fired.
110   delete this;
111 }
112
113
114 // The interface used to libevent is not thread-safe.  Calls to
115 // event_init() and event_base_free() directly modify an internal
116 // global 'current_base', so a mutex is required to protect this.
117 //
118 // event_init() should only ever be called once.  Subsequent calls
119 // should be made to event_base_new().  We can recognise that
120 // event_init() has already been called by simply inspecting current_base.
121 static std::mutex libevent_mutex_;
122
123 /*
124  * EventBase methods
125  */
126
127 EventBase::EventBase(bool enableTimeMeasurement)
128   : runOnceCallbacks_(nullptr)
129   , stop_(false)
130   , loopThread_()
131   , queue_(nullptr)
132   , fnRunner_(nullptr)
133   , maxLatency_(0)
134   , avgLoopTime_(2000000)
135   , maxLatencyLoopTime_(avgLoopTime_)
136   , enableTimeMeasurement_(enableTimeMeasurement)
137   , nextLoopCnt_(-40)       // Early wrap-around so bugs will manifest soon
138   , latestLoopCnt_(nextLoopCnt_)
139   , startWork_(0)
140   , observer_(nullptr)
141   , observerSampleCount_(0)
142   , executionObserver_(nullptr) {
143   struct event ev;
144   {
145     std::lock_guard<std::mutex> lock(libevent_mutex_);
146
147     // The value 'current_base' (libevent 1) or
148     // 'event_global_current_base_' (libevent 2) is filled in by event_set(),
149     // allowing examination of its value without an explicit reference here.
150     // If ev.ev_base is NULL, then event_init() must be called, otherwise
151     // call event_base_new().
152     event_set(&ev, 0, 0, nullptr, nullptr);
153     if (!ev.ev_base) {
154       evb_ = event_init();
155     }
156   }
157
158   if (ev.ev_base) {
159     evb_ = event_base_new();
160   }
161
162   if (UNLIKELY(evb_ == nullptr)) {
163     LOG(ERROR) << "EventBase(): Failed to init event base.";
164     folly::throwSystemError("error in EventBase::EventBase()");
165   }
166   VLOG(5) << "EventBase(): Created.";
167   initNotificationQueue();
168   RequestContext::saveContext();
169 }
170
171 // takes ownership of the event_base
172 EventBase::EventBase(event_base* evb, bool enableTimeMeasurement)
173   : runOnceCallbacks_(nullptr)
174   , stop_(false)
175   , loopThread_()
176   , evb_(evb)
177   , queue_(nullptr)
178   , fnRunner_(nullptr)
179   , maxLatency_(0)
180   , avgLoopTime_(2000000)
181   , maxLatencyLoopTime_(avgLoopTime_)
182   , enableTimeMeasurement_(enableTimeMeasurement)
183   , nextLoopCnt_(-40)       // Early wrap-around so bugs will manifest soon
184   , latestLoopCnt_(nextLoopCnt_)
185   , startWork_(0)
186   , observer_(nullptr)
187   , observerSampleCount_(0)
188   , executionObserver_(nullptr) {
189   if (UNLIKELY(evb_ == nullptr)) {
190     LOG(ERROR) << "EventBase(): Pass nullptr as event base.";
191     throw std::invalid_argument("EventBase(): event base cannot be nullptr");
192   }
193   initNotificationQueue();
194   RequestContext::saveContext();
195 }
196
197 EventBase::~EventBase() {
198   // Call all destruction callbacks, before we start cleaning up our state.
199   while (!onDestructionCallbacks_.empty()) {
200     LoopCallback* callback = &onDestructionCallbacks_.front();
201     onDestructionCallbacks_.pop_front();
202     callback->runLoopCallback();
203   }
204
205   // Delete any unfired callback objects, so that we don't leak memory
206   // (Note that we don't fire them.  The caller is responsible for cleaning up
207   // its own data structures if it destroys the EventBase with unfired events
208   // remaining.)
209   while (!pendingCobTimeouts_.empty()) {
210     CobTimeout* timeout = &pendingCobTimeouts_.front();
211     delete timeout;
212   }
213
214   while (!runBeforeLoopCallbacks_.empty()) {
215     delete &runBeforeLoopCallbacks_.front();
216   }
217
218   (void) runLoopCallbacks(false);
219
220   if (!fnRunner_->consumeUntilDrained()) {
221     LOG(ERROR) << "~EventBase(): Unable to drain notification queue";
222   }
223
224   // Stop consumer before deleting NotificationQueue
225   fnRunner_->stopConsuming();
226   {
227     std::lock_guard<std::mutex> lock(libevent_mutex_);
228     event_base_free(evb_);
229   }
230
231   while (!runAfterDrainCallbacks_.empty()) {
232     LoopCallback* callback = &runAfterDrainCallbacks_.front();
233     runAfterDrainCallbacks_.pop_front();
234     callback->runLoopCallback();
235   }
236
237   {
238     std::lock_guard<std::mutex> lock(localStorageMutex_);
239     for (auto storage : localStorageToDtor_) {
240       storage->onEventBaseDestruction(*this);
241     }
242   }
243   VLOG(5) << "EventBase(): Destroyed.";
244 }
245
246 int EventBase::getNotificationQueueSize() const {
247   return queue_->size();
248 }
249
250 void EventBase::setMaxReadAtOnce(uint32_t maxAtOnce) {
251   fnRunner_->setMaxReadAtOnce(maxAtOnce);
252 }
253
254 // Set smoothing coefficient for loop load average; input is # of milliseconds
255 // for exp(-1) decay.
256 void EventBase::setLoadAvgMsec(uint32_t ms) {
257   assert(enableTimeMeasurement_);
258   uint64_t us = 1000 * ms;
259   if (ms > 0) {
260     maxLatencyLoopTime_.setTimeInterval(us);
261     avgLoopTime_.setTimeInterval(us);
262   } else {
263     LOG(ERROR) << "non-positive arg to setLoadAvgMsec()";
264   }
265 }
266
267 void EventBase::resetLoadAvg(double value) {
268   assert(enableTimeMeasurement_);
269   avgLoopTime_.reset(value);
270   maxLatencyLoopTime_.reset(value);
271 }
272
273 static std::chrono::milliseconds
274 getTimeDelta(std::chrono::steady_clock::time_point* prev) {
275   auto result = std::chrono::steady_clock::now() - *prev;
276   *prev = std::chrono::steady_clock::now();
277
278   return std::chrono::duration_cast<std::chrono::milliseconds>(result);
279 }
280
281 void EventBase::waitUntilRunning() {
282   while (!isRunning()) {
283     sched_yield();
284   }
285 }
286
287 // enters the event_base loop -- will only exit when forced to
288 bool EventBase::loop() {
289   return loopBody();
290 }
291
292 bool EventBase::loopOnce(int flags) {
293   return loopBody(flags | EVLOOP_ONCE);
294 }
295
296 bool EventBase::loopBody(int flags) {
297   VLOG(5) << "EventBase(): Starting loop.";
298   int res = 0;
299   bool ranLoopCallbacks;
300   bool blocking = !(flags & EVLOOP_NONBLOCK);
301   bool once = (flags & EVLOOP_ONCE);
302
303   // time-measurement variables.
304   std::chrono::steady_clock::time_point prev;
305   int64_t idleStart = 0;
306   int64_t busy;
307   int64_t idle;
308
309   loopThread_.store(pthread_self(), std::memory_order_release);
310
311   if (!name_.empty()) {
312     setThreadName(name_);
313   }
314
315   if (enableTimeMeasurement_) {
316     prev = std::chrono::steady_clock::now();
317     idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
318       std::chrono::steady_clock::now().time_since_epoch()).count();
319   }
320
321   while (!stop_.load(std::memory_order_acquire)) {
322     ++nextLoopCnt_;
323
324     // Run the before loop callbacks
325     LoopCallbackList callbacks;
326     callbacks.swap(runBeforeLoopCallbacks_);
327
328     while(!callbacks.empty()) {
329       auto* item = &callbacks.front();
330       callbacks.pop_front();
331       item->runLoopCallback();
332     }
333
334     // nobody can add loop callbacks from within this thread if
335     // we don't have to handle anything to start with...
336     if (blocking && loopCallbacks_.empty()) {
337       res = event_base_loop(evb_, EVLOOP_ONCE);
338     } else {
339       res = event_base_loop(evb_, EVLOOP_ONCE | EVLOOP_NONBLOCK);
340     }
341
342     ranLoopCallbacks = runLoopCallbacks();
343
344     if (enableTimeMeasurement_) {
345       busy = std::chrono::duration_cast<std::chrono::microseconds>(
346         std::chrono::steady_clock::now().time_since_epoch()).count() -
347         startWork_;
348       idle = startWork_ - idleStart;
349
350       avgLoopTime_.addSample(idle, busy);
351       maxLatencyLoopTime_.addSample(idle, busy);
352
353       if (observer_) {
354         if (observerSampleCount_++ == observer_->getSampleRate()) {
355           observerSampleCount_ = 0;
356           observer_->loopSample(busy, idle);
357         }
358       }
359
360       VLOG(11) << "EventBase "  << this         << " did not timeout "
361         " loop time guess: "    << busy + idle  <<
362         " idle time: "          << idle         <<
363         " busy time: "          << busy         <<
364         " avgLoopTime: "        << avgLoopTime_.get() <<
365         " maxLatencyLoopTime: " << maxLatencyLoopTime_.get() <<
366         " maxLatency_: "        << maxLatency_ <<
367         " notificationQueueSize: " << getNotificationQueueSize() <<
368         " nothingHandledYet(): "<< nothingHandledYet();
369
370       // see if our average loop time has exceeded our limit
371       if ((maxLatency_ > 0) &&
372           (maxLatencyLoopTime_.get() > double(maxLatency_))) {
373         maxLatencyCob_();
374         // back off temporarily -- don't keep spamming maxLatencyCob_
375         // if we're only a bit over the limit
376         maxLatencyLoopTime_.dampen(0.9);
377       }
378
379       // Our loop run did real work; reset the idle timer
380       idleStart = std::chrono::duration_cast<std::chrono::microseconds>(
381         std::chrono::steady_clock::now().time_since_epoch()).count();
382     } else {
383       VLOG(11) << "EventBase " << this << " did not timeout";
384     }
385
386     // If the event loop indicate that there were no more events, and
387     // we also didn't have any loop callbacks to run, there is nothing left to
388     // do.
389     if (res != 0 && !ranLoopCallbacks) {
390       // Since Notification Queue is marked 'internal' some events may not have
391       // run.  Run them manually if so, and continue looping.
392       //
393       if (getNotificationQueueSize() > 0) {
394         fnRunner_->handlerReady(0);
395       } else {
396         break;
397       }
398     }
399
400     if (enableTimeMeasurement_) {
401       VLOG(5) << "EventBase " << this << " loop time: " <<
402         getTimeDelta(&prev).count();
403     }
404
405     if (once) {
406       break;
407     }
408   }
409   // Reset stop_ so loop() can be called again
410   stop_ = false;
411
412   if (res < 0) {
413     LOG(ERROR) << "EventBase: -- error in event loop, res = " << res;
414     return false;
415   } else if (res == 1) {
416     VLOG(5) << "EventBase: ran out of events (exiting loop)!";
417   } else if (res > 1) {
418     LOG(ERROR) << "EventBase: unknown event loop result = " << res;
419     return false;
420   }
421
422   loopThread_.store({}, std::memory_order_release);
423
424   VLOG(5) << "EventBase(): Done with loop.";
425   return true;
426 }
427
428 void EventBase::loopForever() {
429   // Update the notification queue event to treat it as a normal (non-internal)
430   // event.  The notification queue event always remains installed, and the main
431   // loop won't exit with it installed.
432   fnRunner_->stopConsuming();
433   fnRunner_->startConsuming(this, queue_.get());
434
435   bool ret = loop();
436
437   // Restore the notification queue internal flag
438   fnRunner_->stopConsuming();
439   fnRunner_->startConsumingInternal(this, queue_.get());
440
441   if (!ret) {
442     folly::throwSystemError("error in EventBase::loopForever()");
443   }
444 }
445
446 void EventBase::bumpHandlingTime() {
447   if (!enableTimeMeasurement_) {
448     return;
449   }
450
451   VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__ <<
452     " (loop) latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
453   if (nothingHandledYet()) {
454     latestLoopCnt_ = nextLoopCnt_;
455     // set the time
456     startWork_ = std::chrono::duration_cast<std::chrono::microseconds>(
457                      std::chrono::steady_clock::now().time_since_epoch())
458                      .count();
459
460     VLOG(11) << "EventBase " << this << " " << __PRETTY_FUNCTION__
461              << " (loop) startWork_ " << startWork_;
462   }
463 }
464
465 void EventBase::terminateLoopSoon() {
466   VLOG(5) << "EventBase(): Received terminateLoopSoon() command.";
467
468   // Set stop to true, so the event loop will know to exit.
469   // TODO: We should really use an atomic operation here with a release
470   // barrier.
471   stop_ = true;
472
473   // Call event_base_loopbreak() so that libevent will exit the next time
474   // around the loop.
475   event_base_loopbreak(evb_);
476
477   // If terminateLoopSoon() is called from another thread,
478   // the EventBase thread might be stuck waiting for events.
479   // In this case, it won't wake up and notice that stop_ is set until it
480   // receives another event.  Send an empty frame to the notification queue
481   // so that the event loop will wake up even if there are no other events.
482   //
483   // We don't care about the return value of trySendFrame().  If it fails
484   // this likely means the EventBase already has lots of events waiting
485   // anyway.
486   try {
487     queue_->putMessage(nullptr);
488   } catch (...) {
489     // We don't care if putMessage() fails.  This likely means
490     // the EventBase already has lots of events waiting anyway.
491   }
492 }
493
494 void EventBase::runInLoop(LoopCallback* callback, bool thisIteration) {
495   DCHECK(isInEventBaseThread());
496   callback->cancelLoopCallback();
497   callback->context_ = RequestContext::saveContext();
498   if (runOnceCallbacks_ != nullptr && thisIteration) {
499     runOnceCallbacks_->push_back(*callback);
500   } else {
501     loopCallbacks_.push_back(*callback);
502   }
503 }
504
505 void EventBase::runInLoop(Func cob, bool thisIteration) {
506   DCHECK(isInEventBaseThread());
507   auto wrapper = new FunctionLoopCallback(std::move(cob));
508   wrapper->context_ = RequestContext::saveContext();
509   if (runOnceCallbacks_ != nullptr && thisIteration) {
510     runOnceCallbacks_->push_back(*wrapper);
511   } else {
512     loopCallbacks_.push_back(*wrapper);
513   }
514 }
515
516 void EventBase::runAfterDrain(Func cob) {
517   auto callback = new FunctionLoopCallback(std::move(cob));
518   std::lock_guard<std::mutex> lg(runAfterDrainCallbacksMutex_);
519   callback->cancelLoopCallback();
520   runAfterDrainCallbacks_.push_back(*callback);
521 }
522
523 void EventBase::runOnDestruction(LoopCallback* callback) {
524   std::lock_guard<std::mutex> lg(onDestructionCallbacksMutex_);
525   callback->cancelLoopCallback();
526   onDestructionCallbacks_.push_back(*callback);
527 }
528
529 void EventBase::runBeforeLoop(LoopCallback* callback) {
530   DCHECK(isInEventBaseThread());
531   callback->cancelLoopCallback();
532   runBeforeLoopCallbacks_.push_back(*callback);
533 }
534
535 bool EventBase::runInEventBaseThread(Func fn) {
536   // Send the message.
537   // It will be received by the FunctionRunner in the EventBase's thread.
538
539   // We try not to schedule nullptr callbacks
540   if (!fn) {
541     LOG(ERROR) << "EventBase " << this
542                << ": Scheduling nullptr callbacks is not allowed";
543     return false;
544   }
545
546   // Short-circuit if we are already in our event base
547   if (inRunningEventBaseThread()) {
548     runInLoop(std::move(fn));
549     return true;
550
551   }
552
553   try {
554     queue_->putMessage(std::move(fn));
555   } catch (const std::exception& ex) {
556     LOG(ERROR) << "EventBase " << this << ": failed to schedule function "
557                << "for EventBase thread: " << ex.what();
558     return false;
559   }
560
561   return true;
562 }
563
564 bool EventBase::runInEventBaseThreadAndWait(Func fn) {
565   if (inRunningEventBaseThread()) {
566     LOG(ERROR) << "EventBase " << this << ": Waiting in the event loop is not "
567                << "allowed";
568     return false;
569   }
570
571   bool ready = false;
572   std::mutex m;
573   std::condition_variable cv;
574   runInEventBaseThread([&] {
575       SCOPE_EXIT {
576         std::unique_lock<std::mutex> l(m);
577         ready = true;
578         cv.notify_one();
579         // We cannot release the lock before notify_one, because a spurious
580         // wakeup in the waiting thread may lead to cv and m going out of scope
581         // prematurely.
582       };
583       fn();
584   });
585   std::unique_lock<std::mutex> l(m);
586   cv.wait(l, [&] { return ready; });
587
588   return true;
589 }
590
591 bool EventBase::runImmediatelyOrRunInEventBaseThreadAndWait(Func fn) {
592   if (isInEventBaseThread()) {
593     fn();
594     return true;
595   } else {
596     return runInEventBaseThreadAndWait(std::move(fn));
597   }
598 }
599
600 void EventBase::runAfterDelay(
601     Func cob,
602     uint32_t milliseconds,
603     TimeoutManager::InternalEnum in) {
604   if (!tryRunAfterDelay(std::move(cob), milliseconds, in)) {
605     folly::throwSystemError(
606       "error in EventBase::runAfterDelay(), failed to schedule timeout");
607   }
608 }
609
610 bool EventBase::tryRunAfterDelay(
611     Func cob,
612     uint32_t milliseconds,
613     TimeoutManager::InternalEnum in) {
614   CobTimeout* timeout = new CobTimeout(this, std::move(cob), in);
615   if (!timeout->scheduleTimeout(milliseconds)) {
616     delete timeout;
617     return false;
618   }
619   pendingCobTimeouts_.push_back(*timeout);
620   return true;
621 }
622
623 bool EventBase::runLoopCallbacks(bool setContext) {
624   if (!loopCallbacks_.empty()) {
625     bumpHandlingTime();
626     // Swap the loopCallbacks_ list with a temporary list on our stack.
627     // This way we will only run callbacks scheduled at the time
628     // runLoopCallbacks() was invoked.
629     //
630     // If any of these callbacks in turn call runInLoop() to schedule more
631     // callbacks, those new callbacks won't be run until the next iteration
632     // around the event loop.  This prevents runInLoop() callbacks from being
633     // able to start file descriptor and timeout based events.
634     LoopCallbackList currentCallbacks;
635     currentCallbacks.swap(loopCallbacks_);
636     runOnceCallbacks_ = &currentCallbacks;
637
638     while (!currentCallbacks.empty()) {
639       LoopCallback* callback = &currentCallbacks.front();
640       currentCallbacks.pop_front();
641       if (setContext) {
642         RequestContext::setContext(callback->context_);
643       }
644       callback->runLoopCallback();
645     }
646
647     runOnceCallbacks_ = nullptr;
648     return true;
649   }
650   return false;
651 }
652
653 void EventBase::initNotificationQueue() {
654   // Infinite size queue
655   queue_.reset(new NotificationQueue<Func>());
656
657   // We allocate fnRunner_ separately, rather than declaring it directly
658   // as a member of EventBase solely so that we don't need to include
659   // NotificationQueue.h from EventBase.h
660   fnRunner_.reset(new FunctionRunner());
661
662   // Mark this as an internal event, so event_base_loop() will return if
663   // there are no other events besides this one installed.
664   //
665   // Most callers don't care about the internal notification queue used by
666   // EventBase.  The queue is always installed, so if we did count the queue as
667   // an active event, loop() would never exit with no more events to process.
668   // Users can use loopForever() if they do care about the notification queue.
669   // (This is useful for EventBase threads that do nothing but process
670   // runInEventBaseThread() notifications.)
671   fnRunner_->startConsumingInternal(this, queue_.get());
672 }
673
674 void EventBase::SmoothLoopTime::setTimeInterval(uint64_t timeInterval) {
675   expCoeff_ = -1.0/timeInterval;
676   VLOG(11) << "expCoeff_ " << expCoeff_ << " " << __PRETTY_FUNCTION__;
677 }
678
679 void EventBase::SmoothLoopTime::reset(double value) {
680   value_ = value;
681 }
682
683 void EventBase::SmoothLoopTime::addSample(int64_t idle, int64_t busy) {
684     /*
685      * Position at which the busy sample is considered to be taken.
686      * (Allows to quickly skew our average without editing much code)
687      */
688     enum BusySamplePosition {
689       RIGHT = 0,  // busy sample placed at the end of the iteration
690       CENTER = 1, // busy sample placed at the middle point of the iteration
691       LEFT = 2,   // busy sample placed at the beginning of the iteration
692     };
693
694   // See http://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
695   // and D676020 for more info on this calculation.
696   VLOG(11) << "idle " << idle << " oldBusyLeftover_ " << oldBusyLeftover_ <<
697               " idle + oldBusyLeftover_ " << idle + oldBusyLeftover_ <<
698               " busy " << busy << " " << __PRETTY_FUNCTION__;
699   idle += oldBusyLeftover_ + busy;
700   oldBusyLeftover_ = (busy * BusySamplePosition::CENTER) / 2;
701   idle -= oldBusyLeftover_;
702
703   double coeff = exp(idle * expCoeff_);
704   value_ *= coeff;
705   value_ += (1.0 - coeff) * busy;
706 }
707
708 bool EventBase::nothingHandledYet() const noexcept {
709   VLOG(11) << "latest " << latestLoopCnt_ << " next " << nextLoopCnt_;
710   return (nextLoopCnt_ != latestLoopCnt_);
711 }
712
713 void EventBase::attachTimeoutManager(AsyncTimeout* obj,
714                                       InternalEnum internal) {
715
716   struct event* ev = obj->getEvent();
717   assert(ev->ev_base == nullptr);
718
719   event_base_set(getLibeventBase(), ev);
720   if (internal == AsyncTimeout::InternalEnum::INTERNAL) {
721     // Set the EVLIST_INTERNAL flag
722     event_ref_flags(ev) |= EVLIST_INTERNAL;
723   }
724 }
725
726 void EventBase::detachTimeoutManager(AsyncTimeout* obj) {
727   cancelTimeout(obj);
728   struct event* ev = obj->getEvent();
729   ev->ev_base = nullptr;
730 }
731
732 bool EventBase::scheduleTimeout(AsyncTimeout* obj,
733                                  TimeoutManager::timeout_type timeout) {
734   assert(isInEventBaseThread());
735   // Set up the timeval and add the event
736   struct timeval tv;
737   tv.tv_sec = timeout.count() / 1000LL;
738   tv.tv_usec = (timeout.count() % 1000LL) * 1000LL;
739
740   struct event* ev = obj->getEvent();
741   if (event_add(ev, &tv) < 0) {
742     LOG(ERROR) << "EventBase: failed to schedule timeout: " << strerror(errno);
743     return false;
744   }
745
746   return true;
747 }
748
749 void EventBase::cancelTimeout(AsyncTimeout* obj) {
750   assert(isInEventBaseThread());
751   struct event* ev = obj->getEvent();
752   if (EventUtil::isEventRegistered(ev)) {
753     event_del(ev);
754   }
755 }
756
757 void EventBase::setName(const std::string& name) {
758   assert(isInEventBaseThread());
759   name_ = name;
760
761   if (isRunning()) {
762     setThreadName(loopThread_.load(std::memory_order_relaxed),
763                   name_);
764   }
765 }
766
767 const std::string& EventBase::getName() {
768   assert(isInEventBaseThread());
769   return name_;
770 }
771
772 const char* EventBase::getLibeventVersion() { return event_get_version(); }
773 const char* EventBase::getLibeventMethod() { return event_get_method(); }
774
775 } // folly