19d4b19835f35c73b3716a284be853536d23c5b9
[folly.git] / folly / experimental / fibers / Fiber.cpp
1 /*
2  * Copyright 2015 Facebook, Inc.
3  *
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
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16 #include "Fiber.h"
17
18 #include <sys/syscall.h>
19 #include <unistd.h>
20
21 #include <algorithm>
22 #include <cassert>
23 #include <cstring>
24 #include <stdexcept>
25
26 #include <folly/Likely.h>
27 #include <folly/Portability.h>
28 #include <folly/experimental/fibers/BoostContextCompatibility.h>
29 #include <folly/experimental/fibers/FiberManager.h>
30
31 namespace folly { namespace fibers {
32
33 namespace {
34 static const uint64_t kMagic8Bytes = 0xfaceb00cfaceb00c;
35
36 pid_t localThreadId() {
37   static thread_local pid_t threadId = syscall(SYS_gettid);
38   return threadId;
39 }
40
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());
45
46   auto firstNonMagic = std::find_if(
47     begin, end,
48     [](uint64_t val) {
49       return val != kMagic8Bytes;
50     }
51   );
52
53   return (end - firstNonMagic) * sizeof(uint64_t);
54 }
55
56 }  // anonymous namespace
57
58 void Fiber::setData(intptr_t data) {
59   assert(state_ == AWAITING);
60   data_ = data;
61   state_ = READY_TO_RUN;
62
63   if (LIKELY(threadId_ == localThreadId())) {
64     fiberManager_.readyFibers_.push_back(*this);
65     fiberManager_.ensureLoopScheduled();
66   } else {
67     fiberManager_.remoteReadyInsert(this);
68   }
69 }
70
71 Fiber::Fiber(FiberManager& fiberManager) :
72     fiberManager_(fiberManager) {
73
74   auto size = fiberManager_.options_.stackSize;
75   auto limit = fiberManager_.stackAllocator_.allocate(size);
76
77   fcontext_ = makeContext(limit, size, &Fiber::fiberFuncHelper);
78 }
79
80 void Fiber::init(bool recordStackUsed) {
81   recordStackUsed_ = recordStackUsed;
82   if (UNLIKELY(recordStackUsed_ && !stackFilledWithMagic_)) {
83     auto limit = fcontext_.stackLimit();
84     auto base = fcontext_.stackBase();
85
86     std::fill(static_cast<uint64_t*>(limit),
87               static_cast<uint64_t*>(base),
88               kMagic8Bytes);
89
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);
94
95     stackFilledWithMagic_ = true;
96   }
97 }
98
99 Fiber::~Fiber() {
100   fiberManager_.stackAllocator_.deallocate(
101     static_cast<unsigned char*>(fcontext_.stackLimit()),
102     fiberManager_.options_.stackSize);
103 }
104
105 void Fiber::recordStackPosition() {
106   int stackDummy;
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;
113 }
114
115 void Fiber::fiberFuncHelper(intptr_t fiber) {
116   reinterpret_cast<Fiber*>(fiber)->fiberFunc();
117 }
118
119 /*
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.
123  */
124 #ifdef FOLLY_SANITIZE_ADDRESS
125 volatile bool loopForever = true;
126 #else
127 static constexpr bool loopForever = true;
128 #endif
129
130 void Fiber::fiberFunc() {
131   while (loopForever) {
132     assert(state_ == NOT_STARTED);
133
134     threadId_ = localThreadId();
135     state_ = RUNNING;
136
137     try {
138       if (resultFunc_) {
139         assert(finallyFunc_);
140         assert(!func_);
141
142         resultFunc_();
143       } else {
144         assert(func_);
145         func_();
146       }
147     } catch (...) {
148       fiberManager_.exceptionCallback_(std::current_exception(),
149                                        "running Fiber func_/resultFunc_");
150     }
151
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";
159     }
160
161     state_ = INVALID;
162
163     fiberManager_.activeFiber_ = nullptr;
164
165     auto fiber = reinterpret_cast<Fiber*>(
166       jumpContext(&fcontext_, &fiberManager_.mainContext_, 0));
167     assert(fiber == this);
168   }
169 }
170
171 intptr_t Fiber::preempt(State state) {
172   assert(fiberManager_.activeFiber_ == this);
173   assert(state_ == RUNNING);
174   assert(state != RUNNING);
175
176   fiberManager_.activeFiber_ = nullptr;
177   state_ = state;
178
179   recordStackPosition();
180
181   auto ret = jumpContext(&fcontext_, &fiberManager_.mainContext_, 0);
182
183   assert(fiberManager_.activeFiber_ == this);
184   assert(state_ == READY_TO_RUN);
185   state_ = RUNNING;
186
187   return ret;
188 }
189
190 Fiber::LocalData::LocalData(const LocalData& other) : data_(nullptr) {
191   *this = other;
192 }
193
194 Fiber::LocalData& Fiber::LocalData::operator=(const LocalData& other) {
195   reset();
196   if (!other.data_) {
197     return *this;
198   }
199
200   dataSize_ = other.dataSize_;
201   dataType_ = other.dataType_;
202   dataDestructor_ = other.dataDestructor_;
203   dataCopyConstructor_ = other.dataCopyConstructor_;
204
205   if (dataSize_ <= kBufferSize) {
206     data_ = &buffer_;
207   } else {
208     data_ = allocateHeapBuffer(dataSize_);
209   }
210
211   dataCopyConstructor_(data_, other.data_);
212
213   return *this;
214 }
215
216 void Fiber::LocalData::reset() {
217   if (!data_) {
218     return;
219   }
220
221   dataDestructor_(data_);
222   data_ = nullptr;
223 }
224
225 void* Fiber::LocalData::allocateHeapBuffer(size_t size) {
226   return new char[size];
227 }
228
229 void Fiber::LocalData::freeHeapBuffer(void* buffer) {
230   delete[] reinterpret_cast<char*>(buffer);
231 }
232
233 }}