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.
16 #include "FiberManager.h"
23 #include <glog/logging.h>
25 #include <folly/fibers/Fiber.h>
26 #include <folly/fibers/LoopController.h>
28 #include <folly/SingletonThreadLocal.h>
29 #include <folly/portability/SysSyscall.h>
30 #include <folly/portability/Unistd.h>
32 #ifdef FOLLY_SANITIZE_ADDRESS
36 static void __asan_enter_fiber_weak(
37 void const* fiber_stack_base,
38 size_t fiber_stack_extent)
39 __attribute__((__weakref__("__asan_enter_fiber")));
40 static void __asan_exit_fiber_weak()
41 __attribute__((__weakref__("__asan_exit_fiber")));
42 static void __asan_unpoison_memory_region_weak(
43 void const /* nolint */ volatile* addr,
44 size_t size) __attribute__((__weakref__("__asan_unpoison_memory_region")));
46 typedef void (*AsanEnterFiberFuncPtr)(void const*, size_t);
47 typedef void (*AsanExitFiberFuncPtr)();
48 typedef void (*AsanUnpoisonMemoryRegionFuncPtr)(
49 void const /* nolint */ volatile*,
55 static AsanEnterFiberFuncPtr getEnterFiberFunc();
56 static AsanExitFiberFuncPtr getExitFiberFunc();
57 static AsanUnpoisonMemoryRegionFuncPtr getUnpoisonMemoryRegionFunc();
66 FOLLY_TLS FiberManager* FiberManager::currentFiberManager_ = nullptr;
68 FiberManager::FiberManager(
69 std::unique_ptr<LoopController> loopController,
73 std::move(loopController),
74 std::move(options)) {}
76 FiberManager::~FiberManager() {
77 if (isLoopScheduled_) {
78 loopController_->cancel();
81 while (!fibersPool_.empty()) {
82 fibersPool_.pop_front_and_dispose([](Fiber* fiber) { delete fiber; });
84 assert(readyFibers_.empty());
85 assert(fibersActive_ == 0);
88 LoopController& FiberManager::loopController() {
89 return *loopController_;
92 const LoopController& FiberManager::loopController() const {
93 return *loopController_;
96 bool FiberManager::hasTasks() const {
97 return fibersActive_ > 0 || !remoteReadyQueue_.empty() ||
98 !remoteTaskQueue_.empty();
101 Fiber* FiberManager::getFiber() {
102 Fiber* fiber = nullptr;
104 if (options_.fibersPoolResizePeriodMs > 0 && !fibersPoolResizerScheduled_) {
105 fibersPoolResizer_();
106 fibersPoolResizerScheduled_ = true;
109 if (fibersPool_.empty()) {
110 fiber = new Fiber(*this);
113 fiber = &fibersPool_.front();
114 fibersPool_.pop_front();
115 assert(fibersPoolSize_ > 0);
119 if (++fibersActive_ > maxFibersActiveLastPeriod_) {
120 maxFibersActiveLastPeriod_ = fibersActive_;
123 bool recordStack = (options_.recordStackEvery != 0) &&
124 (fiberId_ % options_.recordStackEvery == 0);
128 void FiberManager::setExceptionCallback(FiberManager::ExceptionCallback ec) {
130 exceptionCallback_ = std::move(ec);
133 size_t FiberManager::fibersAllocated() const {
134 return fibersAllocated_;
137 size_t FiberManager::fibersPoolSize() const {
138 return fibersPoolSize_;
141 size_t FiberManager::stackHighWatermark() const {
142 return stackHighWatermark_;
145 void FiberManager::remoteReadyInsert(Fiber* fiber) {
147 observer_->runnable(reinterpret_cast<uintptr_t>(fiber));
149 auto insertHead = [&]() { return remoteReadyQueue_.insertHead(fiber); };
150 loopController_->scheduleThreadSafe(std::ref(insertHead));
153 void FiberManager::setObserver(ExecutionObserver* observer) {
154 observer_ = observer;
157 ExecutionObserver* FiberManager::getObserver() {
161 void FiberManager::setPreemptRunner(InlineFunctionRunner* preemptRunner) {
162 preemptRunner_ = preemptRunner;
165 void FiberManager::doFibersPoolResizing() {
166 while (fibersAllocated_ > maxFibersActiveLastPeriod_ &&
167 fibersPoolSize_ > options_.maxFibersPoolSize) {
168 auto fiber = &fibersPool_.front();
169 assert(fiber != nullptr);
170 fibersPool_.pop_front();
176 maxFibersActiveLastPeriod_ = fibersActive_;
179 void FiberManager::FibersPoolResizer::operator()() {
180 fiberManager_.doFibersPoolResizing();
181 fiberManager_.timeoutManager_->registerTimeout(
183 std::chrono::milliseconds(
184 fiberManager_.options_.fibersPoolResizePeriodMs));
187 #ifdef FOLLY_SANITIZE_ADDRESS
189 void FiberManager::registerFiberActivationWithAsan(Fiber* fiber) {
190 auto context = &fiber->fcontext_;
191 void* top = context->stackBase();
192 void* bottom = context->stackLimit();
193 size_t extent = static_cast<char*>(top) - static_cast<char*>(bottom);
195 // Check if we can find a fiber enter function and call it if we find one
196 static AsanEnterFiberFuncPtr fn = getEnterFiberFunc();
198 LOG(FATAL) << "The version of ASAN in use doesn't support fibers";
204 void FiberManager::registerFiberDeactivationWithAsan(Fiber* fiber) {
205 (void)fiber; // currently unused
207 // Check if we can find a fiber exit function and call it if we find one
208 static AsanExitFiberFuncPtr fn = getExitFiberFunc();
210 LOG(FATAL) << "The version of ASAN in use doesn't support fibers";
216 void FiberManager::unpoisonFiberStack(const Fiber* fiber) {
217 auto stack = fiber->getStack();
219 // Check if we can find a fiber enter function and call it if we find one
220 static AsanUnpoisonMemoryRegionFuncPtr fn = getUnpoisonMemoryRegionFunc();
222 LOG(FATAL) << "This version of ASAN doesn't support memory unpoisoning";
224 fn(stack.first, stack.second);
228 static AsanEnterFiberFuncPtr getEnterFiberFunc() {
229 AsanEnterFiberFuncPtr fn{nullptr};
231 // Check whether weak reference points to statically linked enter function
232 if (nullptr != (fn = &::__asan_enter_fiber_weak)) {
236 // Check whether we can find a dynamically linked enter function
238 (fn = (AsanEnterFiberFuncPtr)dlsym(RTLD_DEFAULT, "__asan_enter_fiber"))) {
242 // Couldn't find the function at all
246 static AsanExitFiberFuncPtr getExitFiberFunc() {
247 AsanExitFiberFuncPtr fn{nullptr};
249 // Check whether weak reference points to statically linked exit function
250 if (nullptr != (fn = &::__asan_exit_fiber_weak)) {
254 // Check whether we can find a dynamically linked exit function
256 (fn = (AsanExitFiberFuncPtr)dlsym(RTLD_DEFAULT, "__asan_exit_fiber"))) {
260 // Couldn't find the function at all
264 static AsanUnpoisonMemoryRegionFuncPtr getUnpoisonMemoryRegionFunc() {
265 AsanUnpoisonMemoryRegionFuncPtr fn{nullptr};
267 // Check whether weak reference points to statically linked unpoison function
268 if (nullptr != (fn = &::__asan_unpoison_memory_region_weak)) {
272 // Check whether we can find a dynamically linked unpoison function
273 if (nullptr != (fn = (AsanUnpoisonMemoryRegionFuncPtr)dlsym(
274 RTLD_DEFAULT, "__asan_unpoison_memory_region"))) {
278 // Couldn't find the function at all
282 #endif // FOLLY_SANITIZE_ADDRESS
287 // SIGSTKSZ (8 kB on our architectures) isn't always enough for
288 // folly::symbolizer, so allocate 32 kB.
289 constexpr size_t kAltStackSize = folly::constexpr_max(SIGSTKSZ, 32 * 1024);
291 bool hasAlternateStack() {
293 sigaltstack(nullptr, &ss);
294 return !(ss.ss_flags & SS_DISABLE);
297 int setAlternateStack(char* sp, size_t size) {
302 return sigaltstack(&ss, nullptr);
305 int unsetAlternateStack() {
307 ss.ss_flags = SS_DISABLE;
308 return sigaltstack(&ss, nullptr);
311 class ScopedAlternateSignalStack {
313 ScopedAlternateSignalStack() {
314 if (hasAlternateStack()) {
318 stack_ = folly::make_unique<AltStackBuffer>();
320 setAlternateStack(stack_->data(), stack_->size());
323 ~ScopedAlternateSignalStack() {
325 unsetAlternateStack();
330 using AltStackBuffer = std::array<char, kAltStackSize>;
331 std::unique_ptr<AltStackBuffer> stack_;
335 void FiberManager::registerAlternateSignalStack() {
336 static folly::SingletonThreadLocal<ScopedAlternateSignalStack> singleton;
339 alternateSignalStackRegistered_ = true;