2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 #include <folly/CPortability.h>
21 #include <folly/Memory.h>
22 #include <folly/Optional.h>
23 #include <folly/Portability.h>
24 #include <folly/ScopeGuard.h>
26 #include <folly/ThreadLocal.h>
28 #include <folly/experimental/fibers/Baton.h>
29 #include <folly/experimental/fibers/Fiber.h>
30 #include <folly/experimental/fibers/LoopController.h>
31 #include <folly/experimental/fibers/Promise.h>
32 #include <folly/futures/Promise.h>
33 #include <folly/futures/Try.h>
40 inline FiberManager::Options preprocessOptions(FiberManager::Options opts) {
41 #ifdef FOLLY_SANITIZE_ADDRESS
42 /* ASAN needs a lot of extra stack space.
43 16x is a conservative estimate, 8x also worked with tests
44 where it mattered. Note that overallocating here does not necessarily
45 increase RSS, since unused memory is pretty much free. */
53 inline void FiberManager::ensureLoopScheduled() {
54 if (isLoopScheduled_) {
58 isLoopScheduled_ = true;
59 loopController_->schedule();
62 inline intptr_t FiberManager::activateFiber(Fiber* fiber) {
63 DCHECK_EQ(activeFiber_, (Fiber*)nullptr);
65 #ifdef FOLLY_SANITIZE_ADDRESS
66 registerFiberActivationWithAsan(fiber);
70 return jumpContext(&mainContext_, &fiber->fcontext_, fiber->data_);
73 inline intptr_t FiberManager::deactivateFiber(Fiber* fiber) {
74 DCHECK_EQ(activeFiber_, fiber);
76 #ifdef FOLLY_SANITIZE_ADDRESS
77 registerFiberDeactivationWithAsan(fiber);
80 activeFiber_ = nullptr;
81 return jumpContext(&fiber->fcontext_, &mainContext_, 0);
84 inline void FiberManager::runReadyFiber(Fiber* fiber) {
86 assert(currentFiber_ == nullptr);
87 assert(activeFiber_ == nullptr);
91 fiber->state_ == Fiber::NOT_STARTED ||
92 fiber->state_ == Fiber::READY_TO_RUN);
93 currentFiber_ = fiber;
94 fiber->rcontext_ = RequestContext::setContext(std::move(fiber->rcontext_));
96 observer_->starting(reinterpret_cast<uintptr_t>(fiber));
99 while (fiber->state_ == Fiber::NOT_STARTED ||
100 fiber->state_ == Fiber::READY_TO_RUN) {
101 activateFiber(fiber);
102 if (fiber->state_ == Fiber::AWAITING_IMMEDIATE) {
106 exceptionCallback_(std::current_exception(), "running immediateFunc_");
108 immediateFunc_ = nullptr;
109 fiber->state_ = Fiber::READY_TO_RUN;
113 if (fiber->state_ == Fiber::AWAITING) {
115 awaitFunc_ = nullptr;
117 observer_->stopped(reinterpret_cast<uintptr_t>(fiber));
119 currentFiber_ = nullptr;
120 fiber->rcontext_ = RequestContext::setContext(std::move(fiber->rcontext_));
121 } else if (fiber->state_ == Fiber::INVALID) {
122 assert(fibersActive_ > 0);
124 // Making sure that task functor is deleted once task is complete.
125 // NOTE: we must do it on main context, as the fiber is not
126 // running at this point.
127 fiber->func_ = nullptr;
128 fiber->resultFunc_ = nullptr;
129 if (fiber->finallyFunc_) {
131 fiber->finallyFunc_();
133 exceptionCallback_(std::current_exception(), "running finallyFunc_");
135 fiber->finallyFunc_ = nullptr;
137 // Make sure LocalData is not accessible from its destructor
139 observer_->stopped(reinterpret_cast<uintptr_t>(fiber));
141 currentFiber_ = nullptr;
142 fiber->rcontext_ = RequestContext::setContext(std::move(fiber->rcontext_));
143 fiber->localData_.reset();
144 fiber->rcontext_.reset();
146 if (fibersPoolSize_ < options_.maxFibersPoolSize ||
147 options_.fibersPoolResizePeriodMs > 0) {
148 fibersPool_.push_front(*fiber);
152 assert(fibersAllocated_ > 0);
155 } else if (fiber->state_ == Fiber::YIELDED) {
157 observer_->stopped(reinterpret_cast<uintptr_t>(fiber));
159 currentFiber_ = nullptr;
160 fiber->rcontext_ = RequestContext::setContext(std::move(fiber->rcontext_));
161 fiber->state_ = Fiber::READY_TO_RUN;
162 yieldedFibers_.push_back(*fiber);
166 inline bool FiberManager::loopUntilNoReady() {
167 if (UNLIKELY(!alternateSignalStackRegistered_)) {
168 registerAlternateSignalStack();
171 // Support nested FiberManagers
172 auto originalFiberManager = this;
173 std::swap(currentFiberManager_, originalFiberManager);
176 isLoopScheduled_ = false;
177 if (!readyFibers_.empty()) {
178 ensureLoopScheduled();
180 std::swap(currentFiberManager_, originalFiberManager);
181 CHECK_EQ(this, originalFiberManager);
184 bool hadRemoteFiber = true;
185 while (hadRemoteFiber) {
186 hadRemoteFiber = false;
188 while (!readyFibers_.empty()) {
189 auto& fiber = readyFibers_.front();
190 readyFibers_.pop_front();
191 runReadyFiber(&fiber);
194 remoteReadyQueue_.sweep([this, &hadRemoteFiber](Fiber* fiber) {
195 runReadyFiber(fiber);
196 hadRemoteFiber = true;
199 remoteTaskQueue_.sweep([this, &hadRemoteFiber](RemoteTask* taskPtr) {
200 std::unique_ptr<RemoteTask> task(taskPtr);
201 auto fiber = getFiber();
202 if (task->localData) {
203 fiber->localData_ = *task->localData;
205 fiber->rcontext_ = std::move(task->rcontext);
207 fiber->setFunction(std::move(task->func));
208 fiber->data_ = reinterpret_cast<intptr_t>(fiber);
210 observer_->runnable(reinterpret_cast<uintptr_t>(fiber));
212 runReadyFiber(fiber);
213 hadRemoteFiber = true;
218 for (auto& yielded : yieldedFibers_) {
219 observer_->runnable(reinterpret_cast<uintptr_t>(&yielded));
222 readyFibers_.splice(readyFibers_.end(), yieldedFibers_);
224 return fibersActive_ > 0;
227 // We need this to be in a struct, not inlined in addTask, because clang crashes
229 template <typename F>
230 struct FiberManager::AddTaskHelper {
233 static constexpr bool allocateInBuffer =
234 sizeof(Func) <= Fiber::kUserBufferSize;
238 Func(F&& func, FiberManager& fm) : func_(std::forward<F>(func)), fm_(fm) {}
244 fm_.exceptionCallback_(
245 std::current_exception(), "running Func functor");
247 if (allocateInBuffer) {
260 template <typename F>
261 void FiberManager::addTask(F&& func) {
262 typedef AddTaskHelper<F> Helper;
264 auto fiber = getFiber();
265 initLocalData(*fiber);
267 if (Helper::allocateInBuffer) {
268 auto funcLoc = static_cast<typename Helper::Func*>(fiber->getUserBuffer());
269 new (funcLoc) typename Helper::Func(std::forward<F>(func), *this);
271 fiber->setFunction(std::ref(*funcLoc));
273 auto funcLoc = new typename Helper::Func(std::forward<F>(func), *this);
275 fiber->setFunction(std::ref(*funcLoc));
278 fiber->data_ = reinterpret_cast<intptr_t>(fiber);
279 readyFibers_.push_back(*fiber);
281 observer_->runnable(reinterpret_cast<uintptr_t>(fiber));
284 ensureLoopScheduled();
287 template <typename F>
288 auto FiberManager::addTaskFuture(F&& func) -> folly::Future<
289 typename folly::Unit::Lift<typename std::result_of<F()>::type>::type> {
290 using T = typename std::result_of<F()>::type;
291 using FutureT = typename folly::Unit::Lift<T>::type;
293 folly::Promise<FutureT> p;
294 auto f = p.getFuture();
296 [func = std::forward<F>(func)]() mutable { return func(); },
297 [p = std::move(p)](folly::Try<T> && t) mutable {
298 p.setTry(std::move(t));
303 template <typename F>
304 void FiberManager::addTaskRemote(F&& func) {
306 auto currentFm = getFiberManagerUnsafe();
307 if (currentFm && currentFm->currentFiber_ &&
308 currentFm->localType_ == localType_) {
309 return folly::make_unique<RemoteTask>(
310 std::forward<F>(func), currentFm->currentFiber_->localData_);
312 return folly::make_unique<RemoteTask>(std::forward<F>(func));
314 auto insertHead = [&]() {
315 return remoteTaskQueue_.insertHead(task.release());
317 loopController_->scheduleThreadSafe(std::ref(insertHead));
320 template <typename F>
321 auto FiberManager::addTaskRemoteFuture(F&& func) -> folly::Future<
322 typename folly::Unit::Lift<typename std::result_of<F()>::type>::type> {
324 typename folly::Unit::Lift<typename std::result_of<F()>::type>::type>
326 auto f = p.getFuture();
328 [ p = std::move(p), func = std::forward<F>(func), this ]() mutable {
329 auto t = folly::makeTryWith(std::forward<F>(func));
330 runInMainContext([&]() { p.setTry(std::move(t)); });
335 template <typename X>
336 struct IsRvalueRefTry {
337 static const bool value = false;
339 template <typename T>
340 struct IsRvalueRefTry<folly::Try<T>&&> {
341 static const bool value = true;
344 // We need this to be in a struct, not inlined in addTaskFinally, because clang
345 // crashes otherwise.
346 template <typename F, typename G>
347 struct FiberManager::AddTaskFinallyHelper {
350 typedef typename std::result_of<F()>::type Result;
354 Finally(G finally, FiberManager& fm)
355 : finally_(std::move(finally)), fm_(fm) {}
359 finally_(std::move(*result_));
361 fm_.exceptionCallback_(
362 std::current_exception(), "running Finally functor");
365 if (allocateInBuffer) {
376 folly::Optional<folly::Try<Result>> result_;
382 Func(F func, Finally& finally)
383 : func_(std::move(func)), result_(finally.result_) {}
386 result_ = folly::makeTryWith(std::move(func_));
388 if (allocateInBuffer) {
397 folly::Optional<folly::Try<Result>>& result_;
400 static constexpr bool allocateInBuffer =
401 sizeof(Func) + sizeof(Finally) <= Fiber::kUserBufferSize;
404 template <typename F, typename G>
405 void FiberManager::addTaskFinally(F&& func, G&& finally) {
406 typedef typename std::result_of<F()>::type Result;
409 IsRvalueRefTry<typename FirstArgOf<G>::type>::value,
410 "finally(arg): arg must be Try<T>&&");
414 typename std::remove_reference<
415 typename FirstArgOf<G>::type>::type::element_type>::value,
416 "finally(Try<T>&&): T must be convertible from func()'s return type");
418 auto fiber = getFiber();
419 initLocalData(*fiber);
421 typedef AddTaskFinallyHelper<
422 typename std::decay<F>::type,
423 typename std::decay<G>::type>
426 if (Helper::allocateInBuffer) {
427 auto funcLoc = static_cast<typename Helper::Func*>(fiber->getUserBuffer());
429 static_cast<typename Helper::Finally*>(static_cast<void*>(funcLoc + 1));
431 new (finallyLoc) typename Helper::Finally(std::forward<G>(finally), *this);
432 new (funcLoc) typename Helper::Func(std::forward<F>(func), *finallyLoc);
434 fiber->setFunctionFinally(std::ref(*funcLoc), std::ref(*finallyLoc));
437 new typename Helper::Finally(std::forward<G>(finally), *this);
439 new typename Helper::Func(std::forward<F>(func), *finallyLoc);
441 fiber->setFunctionFinally(std::ref(*funcLoc), std::ref(*finallyLoc));
444 fiber->data_ = reinterpret_cast<intptr_t>(fiber);
445 readyFibers_.push_back(*fiber);
447 observer_->runnable(reinterpret_cast<uintptr_t>(fiber));
450 ensureLoopScheduled();
453 template <typename F>
454 typename std::result_of<F()>::type FiberManager::runInMainContext(F&& func) {
455 if (UNLIKELY(activeFiber_ == nullptr)) {
459 typedef typename std::result_of<F()>::type Result;
461 folly::Try<Result> result;
462 auto f = [&func, &result]() mutable {
463 result = folly::makeTryWith(std::forward<F>(func));
466 immediateFunc_ = std::ref(f);
467 activeFiber_->preempt(Fiber::AWAITING_IMMEDIATE);
469 return std::move(result).value();
472 inline FiberManager& FiberManager::getFiberManager() {
473 assert(currentFiberManager_ != nullptr);
474 return *currentFiberManager_;
477 inline FiberManager* FiberManager::getFiberManagerUnsafe() {
478 return currentFiberManager_;
481 inline bool FiberManager::hasActiveFiber() const {
482 return activeFiber_ != nullptr;
485 inline void FiberManager::yield() {
486 assert(currentFiberManager_ == this);
487 assert(activeFiber_ != nullptr);
488 assert(activeFiber_->state_ == Fiber::RUNNING);
489 activeFiber_->preempt(Fiber::YIELDED);
492 template <typename T>
493 T& FiberManager::local() {
494 if (std::type_index(typeid(T)) == localType_ && currentFiber_) {
495 return currentFiber_->localData_.get<T>();
497 return localThread<T>();
500 template <typename T>
501 T& FiberManager::localThread() {
503 static thread_local T t;
505 #else // osx doesn't support thread_local
506 static ThreadLocal<T> t;
511 inline void FiberManager::initLocalData(Fiber& fiber) {
512 auto fm = getFiberManagerUnsafe();
513 if (fm && fm->currentFiber_ && fm->localType_ == localType_) {
514 fiber.localData_ = fm->currentFiber_->localData_;
516 fiber.rcontext_ = RequestContext::saveContext();
519 template <typename LocalT>
520 FiberManager::FiberManager(
522 std::unique_ptr<LoopController> loopController__,
524 : loopController_(std::move(loopController__)),
525 stackAllocator_(options.useGuardPages),
526 options_(preprocessOptions(std::move(options))),
527 exceptionCallback_([](std::exception_ptr eptr, std::string context) {
529 std::rethrow_exception(eptr);
530 } catch (const std::exception& e) {
531 LOG(DFATAL) << "Exception " << typeid(e).name() << " with message '"
532 << e.what() << "' was thrown in "
533 << "FiberManager with context '" << context << "'";
535 LOG(DFATAL) << "Unknown exception was thrown in FiberManager with "
536 << "context '" << context << "'";
539 timeoutManager_(std::make_shared<TimeoutController>(*loopController_)),
540 fibersPoolResizer_(*this),
541 localType_(typeid(LocalT)) {
542 loopController_->setFiberManager(this);
545 template <typename F>
546 typename FirstArgOf<F>::type::value_type inline await(F&& func) {
547 typedef typename FirstArgOf<F>::type::value_type Result;
549 folly::Try<Result> result;
552 baton.wait([&func, &result, &baton]() mutable {
553 func(Promise<Result>(result, baton));
556 return folly::moveFromTry(result);