2 * Copyright 2017 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.
22 #include <type_traits>
24 #include <unordered_set>
27 #include <folly/AtomicIntrusiveLinkedList.h>
28 #include <folly/CPortability.h>
29 #include <folly/Executor.h>
30 #include <folly/IntrusiveList.h>
31 #include <folly/Likely.h>
32 #include <folly/Try.h>
33 #include <folly/io/async/Request.h>
35 #include <folly/experimental/ExecutionObserver.h>
36 #include <folly/fibers/BoostContextCompatibility.h>
37 #include <folly/fibers/Fiber.h>
38 #include <folly/fibers/GuardPageAllocator.h>
39 #include <folly/fibers/TimeoutController.h>
40 #include <folly/fibers/traits.h>
52 class TimeoutController;
57 class InlineFunctionRunner {
59 virtual ~InlineFunctionRunner() {}
62 * func must be executed inline and only once.
64 virtual void run(folly::Function<void()> func) = 0;
69 * @brief Single-threaded task execution engine.
71 * FiberManager allows semi-parallel task execution on the same thread. Each
72 * task can notify FiberManager that it is blocked on something (via await())
73 * call. This will pause execution of this task and it will be resumed only
74 * when it is unblocked (via setData()).
76 class FiberManager : public ::folly::Executor {
79 static constexpr size_t kDefaultStackSize{16 * 1024};
82 * Maximum stack size for fibers which will be used for executing all the
85 size_t stackSize{kDefaultStackSize};
88 * Record exact amount of stack used.
90 * This is fairly expensive: we fill each newly allocated stack
91 * with some known value and find the boundary of unused stack
92 * with linear search every time we surrender the stack back to fibersPool.
93 * 0 disables stack recording.
95 size_t recordStackEvery{0};
98 * Keep at most this many free fibers in the pool.
99 * This way the total number of fibers in the system is always bounded
100 * by the number of active fibers + maxFibersPoolSize.
102 size_t maxFibersPoolSize{1000};
105 * Protect limited amount of fiber stacks with guard pages.
107 bool useGuardPages{true};
110 * Free unnecessary fibers in the fibers pool every fibersPoolResizePeriodMs
111 * milliseconds. If value is 0, periodic resizing of the fibers pool is
114 uint32_t fibersPoolResizePeriodMs{0};
116 constexpr Options() {}
119 using ExceptionCallback =
120 folly::Function<void(std::exception_ptr, std::string)>;
122 FiberManager(const FiberManager&) = delete;
123 FiberManager& operator=(const FiberManager&) = delete;
126 * Initializes, but doesn't start FiberManager loop
128 * @param loopController
129 * @param options FiberManager options
131 explicit FiberManager(
132 std::unique_ptr<LoopController> loopController,
133 Options options = Options());
136 * Initializes, but doesn't start FiberManager loop
138 * @param loopController
139 * @param options FiberManager options
140 * @tparam LocalT only local of this type may be stored on fibers.
141 * Locals of other types will be considered thread-locals.
143 template <typename LocalT>
146 std::unique_ptr<LoopController> loopController,
147 Options options = Options());
154 LoopController& loopController();
155 const LoopController& loopController() const;
158 * Keeps running ready tasks until the list of ready tasks is empty.
160 void loopUntilNoReady();
163 * This should only be called by a LoopController.
165 void loopUntilNoReadyImpl();
168 * @return true if there are outstanding tasks.
170 bool hasTasks() const;
173 * Sets exception callback which will be called if any of the tasks throws an
178 void setExceptionCallback(ExceptionCallback ec);
181 * Add a new task to be executed. Must be called from FiberManager's thread.
183 * @param func Task functor; must have a signature of `void func()`.
184 * The object will be destroyed once task execution is complete.
186 template <typename F>
187 void addTask(F&& func);
190 * Add a new task to be executed and return a future that will be set on
191 * return from func. Must be called from FiberManager's thread.
193 * @param func Task functor; must have a signature of `void func()`.
194 * The object will be destroyed once task execution is complete.
196 template <typename F>
197 auto addTaskFuture(F&& func) -> folly::Future<
198 typename folly::Unit::Lift<typename std::result_of<F()>::type>::type>;
200 * Add a new task to be executed. Safe to call from other threads.
202 * @param func Task function; must have a signature of `void func()`.
203 * The object will be destroyed once task execution is complete.
205 template <typename F>
206 void addTaskRemote(F&& func);
209 * Add a new task to be executed and return a future that will be set on
210 * return from func. Safe to call from other threads.
212 * @param func Task function; must have a signature of `void func()`.
213 * The object will be destroyed once task execution is complete.
215 template <typename F>
216 auto addTaskRemoteFuture(F&& func) -> folly::Future<
217 typename folly::Unit::Lift<typename std::result_of<F()>::type>::type>;
219 // Executor interface calls addTaskRemote
220 void add(folly::Func f) override {
221 addTaskRemote(std::move(f));
225 * Add a new task. When the task is complete, execute finally(Try<Result>&&)
226 * on the main context.
228 * @param func Task functor; must have a signature of `T func()` for some T.
229 * @param finally Finally functor; must have a signature of
230 * `void finally(Try<T>&&)` and will be passed
231 * the result of func() (including the exception if occurred).
233 template <typename F, typename G>
234 void addTaskFinally(F&& func, G&& finally);
237 * If called from a fiber, immediately switches to the FiberManager's context
238 * and runs func(), going back to the Fiber's context after completion.
239 * Outside a fiber, just calls func() directly.
241 * @return value returned by func().
243 template <typename F>
244 typename std::result_of<F()>::type runInMainContext(F&& func);
247 * Returns a refference to a fiber-local context for given Fiber. Should be
248 * always called with the same T for each fiber. Fiber-local context is lazily
249 * default-constructed on first request.
250 * When new task is scheduled via addTask / addTaskRemote from a fiber its
251 * fiber-local context is copied into the new fiber.
253 template <typename T>
256 template <typename T>
257 FOLLY_EXPORT static T& localThread();
260 * @return How many fiber objects (and stacks) has this manager allocated.
262 size_t fibersAllocated() const;
265 * @return How many of the allocated fiber objects are currently
268 size_t fibersPoolSize() const;
271 * return true if running activeFiber_ is not nullptr.
273 bool hasActiveFiber() const;
276 * @return The currently running fiber or null if no fiber is executing.
278 Fiber* currentFiber() const {
279 return currentFiber_;
283 * @return What was the most observed fiber stack usage (in bytes).
285 size_t stackHighWatermark() const;
288 * Yield execution of the currently running fiber. Must only be called from a
289 * fiber executing on this FiberManager. The calling fiber will be scheduled
290 * when all other fibers have had a chance to run and the event loop is
296 * Setup fibers execution observation/instrumentation. Fiber locals are
297 * available to observer.
299 * @param observer Fiber's execution observer.
301 void setObserver(ExecutionObserver* observer);
304 * @return Current observer for this FiberManager. Returns nullptr
305 * if no observer has been set.
307 ExecutionObserver* getObserver();
310 * Setup fibers preempt runner.
312 void setPreemptRunner(InlineFunctionRunner* preemptRunner);
315 * Returns an estimate of the number of fibers which are waiting to run (does
316 * not include fibers or tasks scheduled remotely).
318 size_t runQueueSize() const {
319 return readyFibers_.size() + yieldedFibers_.size();
322 static FiberManager& getFiberManager();
323 static FiberManager* getFiberManagerUnsafe();
328 template <typename F>
329 struct AddTaskHelper;
330 template <typename F, typename G>
331 struct AddTaskFinallyHelper;
334 template <typename F>
335 explicit RemoteTask(F&& f)
336 : func(std::forward<F>(f)), rcontext(RequestContext::saveContext()) {}
337 template <typename F>
338 RemoteTask(F&& f, const Fiber::LocalData& localData_)
339 : func(std::forward<F>(f)),
340 localData(std::make_unique<Fiber::LocalData>(localData_)),
341 rcontext(RequestContext::saveContext()) {}
342 folly::Function<void()> func;
343 std::unique_ptr<Fiber::LocalData> localData;
344 std::shared_ptr<RequestContext> rcontext;
345 AtomicIntrusiveLinkedListHook<RemoteTask> nextRemoteTask;
348 void activateFiber(Fiber* fiber);
349 void deactivateFiber(Fiber* fiber);
351 typedef folly::IntrusiveList<Fiber, &Fiber::listHook_> FiberTailQueue;
352 typedef folly::IntrusiveList<Fiber, &Fiber::globalListHook_>
353 GlobalFiberTailQueue;
355 Fiber* activeFiber_{nullptr}; /**< active fiber, nullptr on main context */
357 * Same as active fiber, but also set for functions run from fiber on main
360 Fiber* currentFiber_{nullptr};
362 FiberTailQueue readyFibers_; /**< queue of fibers ready to be executed */
363 FiberTailQueue yieldedFibers_; /**< queue of fibers which have yielded
365 FiberTailQueue fibersPool_; /**< pool of uninitialized Fiber objects */
367 GlobalFiberTailQueue allFibers_; /**< list of all Fiber objects owned */
369 size_t fibersAllocated_{0}; /**< total number of fibers allocated */
370 size_t fibersPoolSize_{0}; /**< total number of fibers in the free pool */
371 size_t fibersActive_{0}; /**< number of running or blocked fibers */
372 size_t fiberId_{0}; /**< id of last fiber used */
375 * Maximum number of active fibers in the last period lasting
376 * Options::fibersPoolResizePeriod milliseconds.
378 size_t maxFibersActiveLastPeriod_{0};
380 std::unique_ptr<LoopController> loopController_;
381 bool isLoopScheduled_{false}; /**< was the ready loop scheduled to run? */
384 * When we are inside FiberManager loop this points to FiberManager. Otherwise
387 static FOLLY_TLS FiberManager* currentFiberManager_;
390 * Allocator used to allocate stack for Fibers in the pool.
391 * Allocates stack on the stack of the main context.
393 GuardPageAllocator stackAllocator_;
395 const Options options_; /**< FiberManager options */
398 * Largest observed individual Fiber stack usage in bytes.
400 size_t stackHighWatermark_{0};
403 * Schedules a loop with loopController (unless already scheduled before).
405 void ensureLoopScheduled();
408 * @return An initialized Fiber object from the pool
413 * Sets local data for given fiber if all conditions are met.
415 void initLocalData(Fiber& fiber);
418 * Function passed to the await call.
420 folly::Function<void(Fiber&)> awaitFunc_;
423 * Function passed to the runInMainContext call.
425 folly::Function<void()> immediateFunc_;
430 InlineFunctionRunner* preemptRunner_{nullptr};
433 * Fiber's execution observer.
435 ExecutionObserver* observer_{nullptr};
437 ExceptionCallback exceptionCallback_; /**< task exception callback */
439 folly::AtomicIntrusiveLinkedList<Fiber, &Fiber::nextRemoteReady_>
442 folly::AtomicIntrusiveLinkedList<RemoteTask, &RemoteTask::nextRemoteTask>
445 std::shared_ptr<TimeoutController> timeoutManager_;
447 struct FibersPoolResizer {
448 explicit FibersPoolResizer(FiberManager& fm) : fiberManager_(fm) {}
452 FiberManager& fiberManager_;
455 FibersPoolResizer fibersPoolResizer_;
456 bool fibersPoolResizerScheduled_{false};
458 void doFibersPoolResizing();
461 * Only local of this type will be available for fibers.
463 std::type_index localType_;
465 void runReadyFiber(Fiber* fiber);
466 void remoteReadyInsert(Fiber* fiber);
468 #ifdef FOLLY_SANITIZE_ADDRESS
470 // These methods notify ASAN when a fiber is entered/exited so that ASAN can
471 // find the right stack extents when it needs to poison/unpoison the stack.
473 void registerStartSwitchStackWithAsan(
474 void** saveFakeStack,
475 const void* stackBase,
477 void registerFinishSwitchStackWithAsan(
479 const void** saveStackBase,
480 size_t* saveStackSize);
481 void freeFakeStack(void* fakeStack);
482 void unpoisonFiberStack(const Fiber* fiber);
484 #endif // FOLLY_SANITIZE_ADDRESS
487 bool alternateSignalStackRegistered_{false};
489 void registerAlternateSignalStack();
494 * @return true iff we are running in a fiber's context
496 inline bool onFiber() {
497 auto fm = FiberManager::getFiberManagerUnsafe();
498 return fm ? fm->hasActiveFiber() : false;
502 * Add a new task to be executed.
504 * @param func Task functor; must have a signature of `void func()`.
505 * The object will be destroyed once task execution is complete.
507 template <typename F>
508 inline void addTask(F&& func) {
509 return FiberManager::getFiberManager().addTask(std::forward<F>(func));
513 * Add a new task. When the task is complete, execute finally(Try<Result>&&)
514 * on the main context.
515 * Task functor is run and destroyed on the fiber context.
516 * Finally functor is run and destroyed on the main context.
518 * @param func Task functor; must have a signature of `T func()` for some T.
519 * @param finally Finally functor; must have a signature of
520 * `void finally(Try<T>&&)` and will be passed
521 * the result of func() (including the exception if occurred).
523 template <typename F, typename G>
524 inline void addTaskFinally(F&& func, G&& finally) {
525 return FiberManager::getFiberManager().addTaskFinally(
526 std::forward<F>(func), std::forward<G>(finally));
530 * Blocks task execution until given promise is fulfilled.
532 * Calls function passing in a Promise<T>, which has to be fulfilled.
534 * @return data which was used to fulfill the promise.
536 template <typename F>
537 typename FirstArgOf<F>::type::value_type inline await(F&& func);
540 * If called from a fiber, immediately switches to the FiberManager's context
541 * and runs func(), going back to the Fiber's context after completion.
542 * Outside a fiber, just calls func() directly.
544 * @return value returned by func().
546 template <typename F>
547 typename std::result_of<F()>::type inline runInMainContext(F&& func) {
548 auto fm = FiberManager::getFiberManagerUnsafe();
549 if (UNLIKELY(fm == nullptr)) {
552 return fm->runInMainContext(std::forward<F>(func));
556 * Returns a refference to a fiber-local context for given Fiber. Should be
557 * always called with the same T for each fiber. Fiber-local context is lazily
558 * default-constructed on first request.
559 * When new task is scheduled via addTask / addTaskRemote from a fiber its
560 * fiber-local context is copied into the new fiber.
562 template <typename T>
564 auto fm = FiberManager::getFiberManagerUnsafe();
566 return fm->local<T>();
568 return FiberManager::localThread<T>();
571 inline void yield() {
572 auto fm = FiberManager::getFiberManagerUnsafe();
576 std::this_thread::yield();
582 #include <folly/fibers/FiberManagerInternal-inl.h>