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.
18 #include <sys/syscall.h>
21 #include <glog/logging.h>
26 #include <folly/Likely.h>
27 #include <folly/Portability.h>
28 #include <folly/fibers/BoostContextCompatibility.h>
29 #include <folly/fibers/FiberManager.h>
30 #include <folly/portability/SysSyscall.h>
36 static const uint64_t kMagic8Bytes = 0xfaceb00cfaceb00c;
38 std::thread::id localThreadId() {
39 return std::this_thread::get_id();
42 /* Size of the region from p + nBytes down to the last non-magic value */
43 static size_t nonMagicInBytes(const FContext& context) {
44 uint64_t* begin = static_cast<uint64_t*>(context.stackLimit());
45 uint64_t* end = static_cast<uint64_t*>(context.stackBase());
47 auto firstNonMagic = std::find_if(
48 begin, end, [](uint64_t val) { return val != kMagic8Bytes; });
50 return (end - firstNonMagic) * sizeof(uint64_t);
53 } // anonymous namespace
55 void Fiber::setData(intptr_t data) {
56 DCHECK_EQ(state_, AWAITING);
58 state_ = READY_TO_RUN;
60 if (fiberManager_.observer_) {
61 fiberManager_.observer_->runnable(reinterpret_cast<uintptr_t>(this));
64 if (LIKELY(threadId_ == localThreadId())) {
65 fiberManager_.readyFibers_.push_back(*this);
66 fiberManager_.ensureLoopScheduled();
68 fiberManager_.remoteReadyInsert(this);
72 Fiber::Fiber(FiberManager& fiberManager) : fiberManager_(fiberManager) {
73 auto size = fiberManager_.options_.stackSize;
74 auto limit = fiberManager_.stackAllocator_.allocate(size);
76 fcontext_ = makeContext(limit, size, &Fiber::fiberFuncHelper);
78 fiberManager_.allFibers_.push_back(*this);
81 void Fiber::init(bool recordStackUsed) {
82 // It is necessary to disable the logic for ASAN because we change
84 #ifndef FOLLY_SANITIZE_ADDRESS
85 recordStackUsed_ = recordStackUsed;
86 if (UNLIKELY(recordStackUsed_ && !stackFilledWithMagic_)) {
87 auto limit = fcontext_.stackLimit();
88 auto base = fcontext_.stackBase();
91 static_cast<uint64_t*>(limit),
92 static_cast<uint64_t*>(base),
95 // newer versions of boost allocate context on fiber stack,
96 // need to create a new one
97 auto size = fiberManager_.options_.stackSize;
98 fcontext_ = makeContext(limit, size, &Fiber::fiberFuncHelper);
100 stackFilledWithMagic_ = true;
103 (void)recordStackUsed;
108 #ifdef FOLLY_SANITIZE_ADDRESS
109 fiberManager_.unpoisonFiberStack(this);
111 fiberManager_.stackAllocator_.deallocate(
112 static_cast<unsigned char*>(fcontext_.stackLimit()),
113 fiberManager_.options_.stackSize);
116 void Fiber::recordStackPosition() {
118 auto currentPosition = static_cast<size_t>(
119 static_cast<unsigned char*>(fcontext_.stackBase()) -
120 static_cast<unsigned char*>(static_cast<void*>(&stackDummy)));
121 fiberManager_.stackHighWatermark_ =
122 std::max(fiberManager_.stackHighWatermark_, currentPosition);
123 VLOG(4) << "Stack usage: " << currentPosition;
126 void Fiber::fiberFuncHelper(intptr_t fiber) {
127 reinterpret_cast<Fiber*>(fiber)->fiberFunc();
130 void Fiber::fiberFunc() {
132 DCHECK_EQ(state_, NOT_STARTED);
134 threadId_ = localThreadId();
139 DCHECK(finallyFunc_);
148 fiberManager_.exceptionCallback_(
149 std::current_exception(), "running Fiber func_/resultFunc_");
152 if (UNLIKELY(recordStackUsed_)) {
153 fiberManager_.stackHighWatermark_ = std::max(
154 fiberManager_.stackHighWatermark_, nonMagicInBytes(fcontext_));
155 VLOG(3) << "Max stack usage: " << fiberManager_.stackHighWatermark_;
157 fiberManager_.stackHighWatermark_ <
158 fiberManager_.options_.stackSize - 64)
159 << "Fiber stack overflow";
164 auto context = fiberManager_.deactivateFiber(this);
166 DCHECK_EQ(reinterpret_cast<Fiber*>(context), this);
170 intptr_t Fiber::preempt(State state) {
173 auto preemptImpl = [&]() mutable {
174 DCHECK_EQ(fiberManager_.activeFiber_, this);
175 DCHECK_EQ(state_, RUNNING);
176 DCHECK_NE(state, RUNNING);
180 recordStackPosition();
182 ret = fiberManager_.deactivateFiber(this);
184 DCHECK_EQ(fiberManager_.activeFiber_, this);
185 DCHECK_EQ(state_, READY_TO_RUN);
189 if (fiberManager_.preemptRunner_) {
190 fiberManager_.preemptRunner_->run(std::ref(preemptImpl));
198 Fiber::LocalData::LocalData(const LocalData& other) : data_(nullptr) {
202 Fiber::LocalData& Fiber::LocalData::operator=(const LocalData& other) {
208 dataSize_ = other.dataSize_;
209 dataType_ = other.dataType_;
210 dataDestructor_ = other.dataDestructor_;
211 dataCopyConstructor_ = other.dataCopyConstructor_;
213 if (dataSize_ <= kBufferSize) {
216 data_ = allocateHeapBuffer(dataSize_);
219 dataCopyConstructor_(data_, other.data_);
224 void Fiber::LocalData::reset() {
229 dataDestructor_(data_);
233 void* Fiber::LocalData::allocateHeapBuffer(size_t size) {
234 return new char[size];
237 void Fiber::LocalData::freeHeapBuffer(void* buffer) {
238 delete[] reinterpret_cast<char*>(buffer);