175021534caaa0f27b92a8ba58edb39ad22d1e47
[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 <cstring>
23 #include <stdexcept>
24 #include <glog/logging.h>
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 #include <folly/portability/Syscall.h>
31
32 namespace folly { namespace fibers {
33
34 namespace {
35 static const uint64_t kMagic8Bytes = 0xfaceb00cfaceb00c;
36
37 pid_t localThreadId() {
38   // __thread doesn't allow non-const initialization.
39   // OSX doesn't support thread_local.
40   static FOLLY_TLS pid_t threadId = 0;
41   if (UNLIKELY(threadId == 0)) {
42     threadId = syscall(FOLLY_SYS_gettid);
43   }
44   return threadId;
45 }
46
47 /* Size of the region from p + nBytes down to the last non-magic value */
48 static size_t nonMagicInBytes(const FContext& context) {
49   uint64_t* begin = static_cast<uint64_t*>(context.stackLimit());
50   uint64_t* end = static_cast<uint64_t*>(context.stackBase());
51
52   auto firstNonMagic = std::find_if(
53     begin, end,
54     [](uint64_t val) {
55       return val != kMagic8Bytes;
56     }
57   );
58
59   return (end - firstNonMagic) * sizeof(uint64_t);
60 }
61
62 }  // anonymous namespace
63
64 void Fiber::setData(intptr_t data) {
65   DCHECK_EQ(state_, AWAITING);
66   data_ = data;
67   state_ = READY_TO_RUN;
68
69   if (fiberManager_.observer_) {
70     fiberManager_.observer_->runnable(reinterpret_cast<uintptr_t>(this));
71   }
72
73   if (LIKELY(threadId_ == localThreadId())) {
74     fiberManager_.readyFibers_.push_back(*this);
75     fiberManager_.ensureLoopScheduled();
76   } else {
77     fiberManager_.remoteReadyInsert(this);
78   }
79 }
80
81 Fiber::Fiber(FiberManager& fiberManager) :
82     fiberManager_(fiberManager) {
83
84   auto size = fiberManager_.options_.stackSize;
85   auto limit = fiberManager_.stackAllocator_.allocate(size);
86
87   fcontext_ = makeContext(limit, size, &Fiber::fiberFuncHelper);
88 }
89
90 void Fiber::init(bool recordStackUsed) {
91 // It is necessary to disable the logic for ASAN because we change
92 // the fiber's stack.
93 #ifndef FOLLY_SANITIZE_ADDRESS
94   recordStackUsed_ = recordStackUsed;
95   if (UNLIKELY(recordStackUsed_ && !stackFilledWithMagic_)) {
96     auto limit = fcontext_.stackLimit();
97     auto base = fcontext_.stackBase();
98
99     std::fill(static_cast<uint64_t*>(limit),
100               static_cast<uint64_t*>(base),
101               kMagic8Bytes);
102
103     // newer versions of boost allocate context on fiber stack,
104     // need to create a new one
105     auto size = fiberManager_.options_.stackSize;
106     fcontext_ = makeContext(limit, size, &Fiber::fiberFuncHelper);
107
108     stackFilledWithMagic_ = true;
109   }
110 #endif
111 }
112
113 Fiber::~Fiber() {
114   fiberManager_.stackAllocator_.deallocate(
115     static_cast<unsigned char*>(fcontext_.stackLimit()),
116     fiberManager_.options_.stackSize);
117 }
118
119 void Fiber::recordStackPosition() {
120   int stackDummy;
121   auto currentPosition = static_cast<size_t>(
122      static_cast<unsigned char*>(fcontext_.stackBase()) -
123      static_cast<unsigned char*>(static_cast<void*>(&stackDummy)));
124   fiberManager_.stackHighWatermark_ =
125     std::max(fiberManager_.stackHighWatermark_, currentPosition);
126   VLOG(4) << "Stack usage: " << currentPosition;
127 }
128
129 void Fiber::fiberFuncHelper(intptr_t fiber) {
130   reinterpret_cast<Fiber*>(fiber)->fiberFunc();
131 }
132
133 /*
134  * Some weird bug in ASAN causes fiberFunc to allocate boundless amounts of
135  * memory inside __asan_handle_no_return.  Work around this in ASAN builds by
136  * tricking the compiler into thinking it may, someday, return.
137  */
138 #ifdef FOLLY_SANITIZE_ADDRESS
139 volatile bool loopForever = true;
140 #else
141 static constexpr bool loopForever = true;
142 #endif
143
144 void Fiber::fiberFunc() {
145   while (loopForever) {
146     DCHECK_EQ(state_, NOT_STARTED);
147
148     threadId_ = localThreadId();
149     state_ = RUNNING;
150
151     try {
152       if (resultFunc_) {
153         DCHECK(finallyFunc_);
154         DCHECK(!func_);
155
156         resultFunc_();
157       } else {
158         DCHECK(func_);
159         func_();
160       }
161     } catch (...) {
162       fiberManager_.exceptionCallback_(std::current_exception(),
163                                        "running Fiber func_/resultFunc_");
164     }
165
166     if (UNLIKELY(recordStackUsed_)) {
167       fiberManager_.stackHighWatermark_ =
168         std::max(fiberManager_.stackHighWatermark_,
169                  nonMagicInBytes(fcontext_));
170       VLOG(3) << "Max stack usage: " << fiberManager_.stackHighWatermark_;
171       CHECK(fiberManager_.stackHighWatermark_ <
172               fiberManager_.options_.stackSize - 64) << "Fiber stack overflow";
173     }
174
175     state_ = INVALID;
176
177     fiberManager_.activeFiber_ = nullptr;
178
179     auto context = jumpContext(&fcontext_, &fiberManager_.mainContext_, 0);
180     DCHECK_EQ(reinterpret_cast<Fiber*>(context), this);
181   }
182 }
183
184 intptr_t Fiber::preempt(State state) {
185   intptr_t ret;
186
187   auto preemptImpl = [&]() mutable {
188     DCHECK_EQ(fiberManager_.activeFiber_, this);
189     DCHECK_EQ(state_, RUNNING);
190     DCHECK_NE(state, RUNNING);
191
192     fiberManager_.activeFiber_ = nullptr;
193     state_ = state;
194
195     recordStackPosition();
196
197     ret = jumpContext(&fcontext_, &fiberManager_.mainContext_, 0);
198
199     DCHECK_EQ(fiberManager_.activeFiber_, this);
200     DCHECK_EQ(state_, READY_TO_RUN);
201     state_ = RUNNING;
202   };
203
204   if (fiberManager_.preemptRunner_) {
205     fiberManager_.preemptRunner_->run(std::ref(preemptImpl));
206   } else {
207     preemptImpl();
208   }
209
210   return ret;
211 }
212
213 Fiber::LocalData::LocalData(const LocalData& other) : data_(nullptr) {
214   *this = other;
215 }
216
217 Fiber::LocalData& Fiber::LocalData::operator=(const LocalData& other) {
218   reset();
219   if (!other.data_) {
220     return *this;
221   }
222
223   dataSize_ = other.dataSize_;
224   dataType_ = other.dataType_;
225   dataDestructor_ = other.dataDestructor_;
226   dataCopyConstructor_ = other.dataCopyConstructor_;
227
228   if (dataSize_ <= kBufferSize) {
229     data_ = &buffer_;
230   } else {
231     data_ = allocateHeapBuffer(dataSize_);
232   }
233
234   dataCopyConstructor_(data_, other.data_);
235
236   return *this;
237 }
238
239 void Fiber::LocalData::reset() {
240   if (!data_) {
241     return;
242   }
243
244   dataDestructor_(data_);
245   data_ = nullptr;
246 }
247
248 void* Fiber::LocalData::allocateHeapBuffer(size_t size) {
249   return new char[size];
250 }
251
252 void Fiber::LocalData::freeHeapBuffer(void* buffer) {
253   delete[] reinterpret_cast<char*>(buffer);
254 }
255
256 }}