2 * Copyright 2015 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>
26 #include <folly/Likely.h>
27 #include <folly/Portability.h>
28 #include <folly/experimental/fibers/BoostContextCompatibility.h>
29 #include <folly/experimental/fibers/FiberManager.h>
31 namespace folly { namespace fibers {
34 static const uint64_t kMagic8Bytes = 0xfaceb00cfaceb00c;
36 pid_t localThreadId() {
37 static thread_local pid_t threadId = syscall(SYS_gettid);
41 /* Size of the region from p + nBytes down to the last non-magic value */
42 static size_t nonMagicInBytes(const FContext& context) {
43 uint64_t* begin = static_cast<uint64_t*>(context.stackLimit());
44 uint64_t* end = static_cast<uint64_t*>(context.stackBase());
46 auto firstNonMagic = std::find_if(
49 return val != kMagic8Bytes;
53 return (end - firstNonMagic) * sizeof(uint64_t);
56 } // anonymous namespace
58 void Fiber::setData(intptr_t data) {
59 assert(state_ == AWAITING);
61 state_ = READY_TO_RUN;
63 if (LIKELY(threadId_ == localThreadId())) {
64 fiberManager_.readyFibers_.push_back(*this);
65 fiberManager_.ensureLoopScheduled();
67 fiberManager_.remoteReadyInsert(this);
71 Fiber::Fiber(FiberManager& fiberManager) :
72 fiberManager_(fiberManager) {
74 auto size = fiberManager_.options_.stackSize;
75 auto limit = fiberManager_.stackAllocator_.allocate(size);
77 fcontext_ = makeContext(limit, size, &Fiber::fiberFuncHelper);
80 void Fiber::init(bool recordStackUsed) {
81 recordStackUsed_ = recordStackUsed;
82 if (UNLIKELY(recordStackUsed_ && !stackFilledWithMagic_)) {
83 auto limit = fcontext_.stackLimit();
84 auto base = fcontext_.stackBase();
86 std::fill(static_cast<uint64_t*>(limit),
87 static_cast<uint64_t*>(base),
90 // newer versions of boost allocate context on fiber stack,
91 // need to create a new one
92 auto size = fiberManager_.options_.stackSize;
93 fcontext_ = makeContext(limit, size, &Fiber::fiberFuncHelper);
95 stackFilledWithMagic_ = true;
100 fiberManager_.stackAllocator_.deallocate(
101 static_cast<unsigned char*>(fcontext_.stackLimit()),
102 fiberManager_.options_.stackSize);
105 void Fiber::recordStackPosition() {
107 auto currentPosition = static_cast<size_t>(
108 static_cast<unsigned char*>(fcontext_.stackBase()) -
109 static_cast<unsigned char*>(static_cast<void*>(&stackDummy)));
110 fiberManager_.stackHighWatermark_ =
111 std::max(fiberManager_.stackHighWatermark_, currentPosition);
112 VLOG(4) << "Stack usage: " << currentPosition;
115 void Fiber::fiberFuncHelper(intptr_t fiber) {
116 reinterpret_cast<Fiber*>(fiber)->fiberFunc();
120 * Some weird bug in ASAN causes fiberFunc to allocate boundless amounts of
121 * memory inside __asan_handle_no_return. Work around this in ASAN builds by
122 * tricking the compiler into thinking it may, someday, return.
124 #ifdef FOLLY_SANITIZE_ADDRESS
125 volatile bool loopForever = true;
127 static constexpr bool loopForever = true;
130 void Fiber::fiberFunc() {
131 while (loopForever) {
132 assert(state_ == NOT_STARTED);
134 threadId_ = localThreadId();
139 assert(finallyFunc_);
148 fiberManager_.exceptionCallback_(std::current_exception(),
149 "running Fiber func_/resultFunc_");
152 if (UNLIKELY(recordStackUsed_)) {
153 fiberManager_.stackHighWatermark_ =
154 std::max(fiberManager_.stackHighWatermark_,
155 nonMagicInBytes(fcontext_));
156 VLOG(3) << "Max stack usage: " << fiberManager_.stackHighWatermark_;
157 CHECK(fiberManager_.stackHighWatermark_ <
158 fiberManager_.options_.stackSize - 64) << "Fiber stack overflow";
163 fiberManager_.activeFiber_ = nullptr;
165 auto fiber = reinterpret_cast<Fiber*>(
166 jumpContext(&fcontext_, &fiberManager_.mainContext_, 0));
167 assert(fiber == this);
171 intptr_t Fiber::preempt(State state) {
172 assert(fiberManager_.activeFiber_ == this);
173 assert(state_ == RUNNING);
174 assert(state != RUNNING);
176 fiberManager_.activeFiber_ = nullptr;
179 recordStackPosition();
181 auto ret = jumpContext(&fcontext_, &fiberManager_.mainContext_, 0);
183 assert(fiberManager_.activeFiber_ == this);
184 assert(state_ == READY_TO_RUN);
190 Fiber::LocalData::LocalData(const LocalData& other) : data_(nullptr) {
194 Fiber::LocalData& Fiber::LocalData::operator=(const LocalData& other) {
200 dataSize_ = other.dataSize_;
201 dataType_ = other.dataType_;
202 dataDestructor_ = other.dataDestructor_;
203 dataCopyConstructor_ = other.dataCopyConstructor_;
205 if (dataSize_ <= kBufferSize) {
208 data_ = allocateHeapBuffer(dataSize_);
211 dataCopyConstructor_(data_, other.data_);
216 void Fiber::LocalData::reset() {
221 dataDestructor_(data_);
225 void* Fiber::LocalData::allocateHeapBuffer(size_t size) {
226 return new char[size];
229 void Fiber::LocalData::freeHeapBuffer(void* buffer) {
230 delete[] reinterpret_cast<char*>(buffer);