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>
35 namespace folly { namespace fibers {
39 inline FiberManager::Options preprocessOptions(FiberManager::Options opts) {
40 #ifdef FOLLY_SANITIZE_ADDRESS
41 /* ASAN needs a lot of extra stack space.
42 16x is a conservative estimate, 8x also worked with tests
43 where it mattered. Note that overallocating here does not necessarily
44 increase RSS, since unused memory is pretty much free. */
52 inline void FiberManager::ensureLoopScheduled() {
53 if (isLoopScheduled_) {
57 isLoopScheduled_ = true;
58 loopController_->schedule();
61 inline void FiberManager::runReadyFiber(Fiber* fiber) {
63 assert(currentFiber_ == nullptr);
64 assert(activeFiber_ == nullptr);
67 assert(fiber->state_ == Fiber::NOT_STARTED ||
68 fiber->state_ == Fiber::READY_TO_RUN);
69 currentFiber_ = fiber;
70 fiber->rcontext_ = RequestContext::setContext(std::move(fiber->rcontext_));
72 observer_->starting(reinterpret_cast<uintptr_t>(fiber));
75 while (fiber->state_ == Fiber::NOT_STARTED ||
76 fiber->state_ == Fiber::READY_TO_RUN) {
78 jumpContext(&mainContext_, &fiber->fcontext_, fiber->data_);
79 if (fiber->state_ == Fiber::AWAITING_IMMEDIATE) {
83 exceptionCallback_(std::current_exception(), "running immediateFunc_");
85 immediateFunc_ = nullptr;
86 fiber->state_ = Fiber::READY_TO_RUN;
90 if (fiber->state_ == Fiber::AWAITING) {
94 observer_->stopped(reinterpret_cast<uintptr_t>(fiber));
96 currentFiber_ = nullptr;
97 fiber->rcontext_ = RequestContext::setContext(std::move(fiber->rcontext_));
98 } else if (fiber->state_ == Fiber::INVALID) {
99 assert(fibersActive_ > 0);
101 // Making sure that task functor is deleted once task is complete.
102 // NOTE: we must do it on main context, as the fiber is not
103 // running at this point.
104 fiber->func_ = nullptr;
105 fiber->resultFunc_ = nullptr;
106 if (fiber->finallyFunc_) {
108 fiber->finallyFunc_();
110 exceptionCallback_(std::current_exception(), "running finallyFunc_");
112 fiber->finallyFunc_ = nullptr;
114 // Make sure LocalData is not accessible from its destructor
116 observer_->stopped(reinterpret_cast<uintptr_t>(fiber));
118 currentFiber_ = nullptr;
119 fiber->rcontext_ = RequestContext::setContext(std::move(fiber->rcontext_));
120 fiber->localData_.reset();
121 fiber->rcontext_.reset();
123 if (fibersPoolSize_ < options_.maxFibersPoolSize ||
124 options_.fibersPoolResizePeriodMs > 0) {
125 fibersPool_.push_front(*fiber);
129 assert(fibersAllocated_ > 0);
132 } else if (fiber->state_ == Fiber::YIELDED) {
134 observer_->stopped(reinterpret_cast<uintptr_t>(fiber));
136 currentFiber_ = nullptr;
137 fiber->rcontext_ = RequestContext::setContext(std::move(fiber->rcontext_));
138 fiber->state_ = Fiber::READY_TO_RUN;
139 yieldedFibers_.push_back(*fiber);
143 inline bool FiberManager::loopUntilNoReady() {
145 isLoopScheduled_ = false;
146 if (!readyFibers_.empty()) {
147 ensureLoopScheduled();
149 currentFiberManager_ = nullptr;
152 currentFiberManager_ = this;
154 bool hadRemoteFiber = true;
155 while (hadRemoteFiber) {
156 hadRemoteFiber = false;
158 while (!readyFibers_.empty()) {
159 auto& fiber = readyFibers_.front();
160 readyFibers_.pop_front();
161 runReadyFiber(&fiber);
164 remoteReadyQueue_.sweep(
165 [this, &hadRemoteFiber] (Fiber* fiber) {
166 runReadyFiber(fiber);
167 hadRemoteFiber = true;
171 remoteTaskQueue_.sweep(
172 [this, &hadRemoteFiber] (RemoteTask* taskPtr) {
173 std::unique_ptr<RemoteTask> task(taskPtr);
174 auto fiber = getFiber();
175 if (task->localData) {
176 fiber->localData_ = *task->localData;
178 fiber->rcontext_ = std::move(task->rcontext);
180 fiber->setFunction(std::move(task->func));
181 fiber->data_ = reinterpret_cast<intptr_t>(fiber);
183 observer_->runnable(reinterpret_cast<uintptr_t>(fiber));
185 runReadyFiber(fiber);
186 hadRemoteFiber = true;
192 for (auto& yielded : yieldedFibers_) {
193 observer_->runnable(reinterpret_cast<uintptr_t>(&yielded));
196 readyFibers_.splice(readyFibers_.end(), yieldedFibers_);
198 return fibersActive_ > 0;
201 // We need this to be in a struct, not inlined in addTask, because clang crashes
203 template <typename F>
204 struct FiberManager::AddTaskHelper {
207 static constexpr bool allocateInBuffer =
208 sizeof(Func) <= Fiber::kUserBufferSize;
212 Func(F&& func, FiberManager& fm) :
213 func_(std::forward<F>(func)), fm_(fm) {}
219 fm_.exceptionCallback_(std::current_exception(),
220 "running Func functor");
222 if (allocateInBuffer) {
235 template <typename F>
236 void FiberManager::addTask(F&& func) {
237 typedef AddTaskHelper<F> Helper;
239 auto fiber = getFiber();
240 initLocalData(*fiber);
242 if (Helper::allocateInBuffer) {
243 auto funcLoc = static_cast<typename Helper::Func*>(fiber->getUserBuffer());
244 new (funcLoc) typename Helper::Func(std::forward<F>(func), *this);
246 fiber->setFunction(std::ref(*funcLoc));
248 auto funcLoc = new typename Helper::Func(std::forward<F>(func), *this);
250 fiber->setFunction(std::ref(*funcLoc));
253 fiber->data_ = reinterpret_cast<intptr_t>(fiber);
254 readyFibers_.push_back(*fiber);
256 observer_->runnable(reinterpret_cast<uintptr_t>(fiber));
259 ensureLoopScheduled();
262 template <typename F>
263 auto FiberManager::addTaskFuture(F&& func)
264 -> folly::Future<typename std::result_of<F()>::type> {
265 using T = typename std::result_of<F()>::type;
267 auto f = p.getFuture();
268 addTaskFinally([func = std::forward<F>(func)]() mutable { return func(); },
269 [p = std::move(p)](folly::Try<T> && t) mutable {
270 p.setTry(std::move(t));
275 template <typename F>
276 void FiberManager::addTaskRemote(F&& func) {
277 // addTaskRemote indirectly requires wrapping the function in a
278 // std::function, which must be copyable. As move-only lambdas may be
279 // passed in we wrap it first in a move wrapper and then capture the wrapped
281 auto functionWrapper = [f = folly::makeMoveWrapper(
282 std::forward<F>(func))]() mutable {
286 auto currentFm = getFiberManagerUnsafe();
288 currentFm->currentFiber_ &&
289 currentFm->localType_ == localType_) {
290 return folly::make_unique<RemoteTask>(
291 std::move(functionWrapper), currentFm->currentFiber_->localData_);
293 return folly::make_unique<RemoteTask>(std::move(functionWrapper));
296 [&]() { return remoteTaskQueue_.insertHead(task.release()); };
297 loopController_->scheduleThreadSafe(std::ref(insertHead));
300 template <typename F>
301 auto FiberManager::addTaskRemoteFuture(F&& func)
302 -> folly::Future<typename std::result_of<F()>::type> {
303 folly::Promise<typename std::result_of<F()>::type> p;
304 auto f = p.getFuture();
306 [ p = std::move(p), func = std::forward<F>(func), this ]() mutable {
307 auto t = folly::makeTryWith(std::forward<F>(func));
308 runInMainContext([&]() { p.setTry(std::move(t)); });
313 template <typename X>
314 struct IsRvalueRefTry { static const bool value = false; };
315 template <typename T>
316 struct IsRvalueRefTry<folly::Try<T>&&> { static const bool value = true; };
318 // We need this to be in a struct, not inlined in addTaskFinally, because clang
319 // crashes otherwise.
320 template <typename F, typename G>
321 struct FiberManager::AddTaskFinallyHelper {
325 typedef typename std::result_of<F()>::type Result;
327 static constexpr bool allocateInBuffer =
328 sizeof(Func) + sizeof(Finally) <= Fiber::kUserBufferSize;
334 finally_(std::move(finally)),
340 finally_(std::move(*result_));
342 fm_.exceptionCallback_(std::current_exception(),
343 "running Finally functor");
346 if (allocateInBuffer) {
357 folly::Optional<folly::Try<Result>> result_;
363 Func(F&& func, Finally& finally) :
364 func_(std::move(func)), result_(finally.result_) {}
367 result_ = folly::makeTryWith(std::move(func_));
369 if (allocateInBuffer) {
378 folly::Optional<folly::Try<Result>>& result_;
382 template <typename F, typename G>
383 void FiberManager::addTaskFinally(F&& func, G&& finally) {
384 typedef typename std::result_of<F()>::type Result;
387 IsRvalueRefTry<typename FirstArgOf<G>::type>::value,
388 "finally(arg): arg must be Try<T>&&");
392 typename std::remove_reference<
393 typename FirstArgOf<G>::type
394 >::type::element_type
396 "finally(Try<T>&&): T must be convertible from func()'s return type");
398 auto fiber = getFiber();
399 initLocalData(*fiber);
401 typedef AddTaskFinallyHelper<F,G> Helper;
403 if (Helper::allocateInBuffer) {
404 auto funcLoc = static_cast<typename Helper::Func*>(
405 fiber->getUserBuffer());
406 auto finallyLoc = static_cast<typename Helper::Finally*>(
407 static_cast<void*>(funcLoc + 1));
409 new (finallyLoc) typename Helper::Finally(std::move(finally), *this);
410 new (funcLoc) typename Helper::Func(std::move(func), *finallyLoc);
412 fiber->setFunctionFinally(std::ref(*funcLoc), std::ref(*finallyLoc));
414 auto finallyLoc = new typename Helper::Finally(std::move(finally), *this);
415 auto funcLoc = new typename Helper::Func(std::move(func), *finallyLoc);
417 fiber->setFunctionFinally(std::ref(*funcLoc), std::ref(*finallyLoc));
420 fiber->data_ = reinterpret_cast<intptr_t>(fiber);
421 readyFibers_.push_back(*fiber);
423 observer_->runnable(reinterpret_cast<uintptr_t>(fiber));
426 ensureLoopScheduled();
429 template <typename F>
430 typename std::result_of<F()>::type
431 FiberManager::runInMainContext(F&& func) {
432 if (UNLIKELY(activeFiber_ == nullptr)) {
436 typedef typename std::result_of<F()>::type Result;
438 folly::Try<Result> result;
439 auto f = [&func, &result]() mutable {
440 result = folly::makeTryWith(std::forward<F>(func));
443 immediateFunc_ = std::ref(f);
444 activeFiber_->preempt(Fiber::AWAITING_IMMEDIATE);
446 return std::move(result).value();
449 inline FiberManager& FiberManager::getFiberManager() {
450 assert(currentFiberManager_ != nullptr);
451 return *currentFiberManager_;
454 inline FiberManager* FiberManager::getFiberManagerUnsafe() {
455 return currentFiberManager_;
458 inline bool FiberManager::hasActiveFiber() const {
459 return activeFiber_ != nullptr;
462 inline void FiberManager::yield() {
463 assert(currentFiberManager_ == this);
464 assert(activeFiber_ != nullptr);
465 assert(activeFiber_->state_ == Fiber::RUNNING);
466 activeFiber_->preempt(Fiber::YIELDED);
469 template <typename T>
470 T& FiberManager::local() {
471 if (std::type_index(typeid(T)) == localType_ && currentFiber_) {
472 return currentFiber_->localData_.get<T>();
474 return localThread<T>();
477 template <typename T>
478 T& FiberManager::localThread() {
480 static thread_local T t;
482 #else // osx doesn't support thread_local
483 static ThreadLocal<T> t;
488 inline void FiberManager::initLocalData(Fiber& fiber) {
489 auto fm = getFiberManagerUnsafe();
490 if (fm && fm->currentFiber_ && fm->localType_ == localType_) {
491 fiber.localData_ = fm->currentFiber_->localData_;
493 fiber.rcontext_ = RequestContext::saveContext();
496 template <typename LocalT>
497 FiberManager::FiberManager(
499 std::unique_ptr<LoopController> loopController__,
501 loopController_(std::move(loopController__)),
502 stackAllocator_(options.useGuardPages),
503 options_(preprocessOptions(std::move(options))),
504 exceptionCallback_([](std::exception_ptr eptr, std::string context) {
506 std::rethrow_exception(eptr);
507 } catch (const std::exception& e) {
508 LOG(DFATAL) << "Exception " << typeid(e).name()
509 << " with message '" << e.what() << "' was thrown in "
510 << "FiberManager with context '" << context << "'";
513 LOG(DFATAL) << "Unknown exception was thrown in FiberManager with "
514 << "context '" << context << "'";
518 timeoutManager_(std::make_shared<TimeoutController>(*loopController_)),
519 fibersPoolResizer_(*this),
520 localType_(typeid(LocalT)) {
521 loopController_->setFiberManager(this);
524 template <typename F>
525 typename FirstArgOf<F>::type::value_type
526 inline await(F&& func) {
527 typedef typename FirstArgOf<F>::type::value_type Result;
529 folly::Try<Result> result;
532 baton.wait([&func, &result, &baton]() mutable {
533 func(Promise<Result>(result, baton));
536 return folly::moveFromTry(result);