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.
17 #ifndef FOLLY_DETAIL_THREADLOCALDETAIL_H_
18 #define FOLLY_DETAIL_THREADLOCALDETAIL_H_
27 #include <glog/logging.h>
29 #include <folly/Foreach.h>
30 #include <folly/Exception.h>
31 #include <folly/Malloc.h>
33 // In general, emutls cleanup is not guaranteed to play nice with the way
34 // StaticMeta mixes direct pthread calls and the use of __thread. This has
35 // caused problems on multiple platforms so don't use __thread there.
37 // XXX: Ideally we would instead determine if emutls is in use at runtime as it
38 // is possible to configure glibc on Linux to use emutls regardless.
39 #if !__APPLE__ && !__ANDROID__
40 #define FOLLY_TLD_USE_FOLLY_TLS 1
42 #undef FOLLY_TLD_USE_FOLLY_TLS
46 namespace threadlocal_detail {
49 * Base class for deleters.
53 virtual ~DeleterBase() { }
54 virtual void dispose(void* ptr, TLPDestructionMode mode) const = 0;
58 * Simple deleter class that calls delete on the passed-in pointer.
61 class SimpleDeleter : public DeleterBase {
63 virtual void dispose(void* ptr, TLPDestructionMode /*mode*/) const {
64 delete static_cast<Ptr>(ptr);
69 * Custom deleter that calls a given callable.
71 template <class Ptr, class Deleter>
72 class CustomDeleter : public DeleterBase {
74 explicit CustomDeleter(Deleter d) : deleter_(d) { }
75 virtual void dispose(void* ptr, TLPDestructionMode mode) const {
76 deleter_(static_cast<Ptr>(ptr), mode);
84 * POD wrapper around an element (a void*) and an associated deleter.
85 * This must be POD, as we memset() it to 0 and memcpy() it around.
87 struct ElementWrapper {
88 bool dispose(TLPDestructionMode mode) {
93 DCHECK(deleter != nullptr);
94 deleter->dispose(ptr, mode);
102 if (ptr != nullptr) {
111 DCHECK(ptr == nullptr);
112 DCHECK(deleter == nullptr);
115 // We leak a single object here but that is ok. If we used an
116 // object directly, there is a chance that the destructor will be
117 // called on that static object before any of the ElementWrappers
118 // are disposed and that isn't so nice.
119 static auto d = new SimpleDeleter<Ptr>();
126 template <class Ptr, class Deleter>
127 void set(Ptr p, Deleter d) {
128 DCHECK(ptr == nullptr);
129 DCHECK(deleter == nullptr);
132 deleter = new CustomDeleter<Ptr,Deleter>(d);
147 DeleterBase* deleter;
152 * Per-thread entry. Each thread using a StaticMeta object has one.
153 * This is written from the owning thread only (under the lock), read
154 * from the owning thread (no lock necessary), and read from other threads
158 ElementWrapper* elements;
159 size_t elementsCapacity;
166 // Held in a singleton to track our global instances.
167 // We have one of these per "Tag", by default one for the whole system
170 // Creating and destroying ThreadLocalPtr objects, as well as thread exit
171 // for threads that use ThreadLocalPtr objects collide on a lock inside
172 // StaticMeta; you can specify multiple Tag types to break that lock.
175 // Represents an ID of a thread local object. Initially set to the maximum
176 // uint. This representation allows us to avoid a branch in accessing TLS data
177 // (because if you test capacity > id if id = maxint then the test will always
178 // fail). It allows us to keep a constexpr constructor and avoid SIOF.
181 static constexpr uint32_t kInvalid = std::numeric_limits<uint32_t>::max();
182 std::atomic<uint32_t> value;
184 constexpr EntryID() : value(kInvalid) {
187 EntryID(EntryID&& other) noexcept : value(other.value.load()) {
188 other.value = kInvalid;
191 EntryID& operator=(EntryID&& other) {
192 assert(this != &other);
193 value = other.value.load();
194 other.value = kInvalid;
198 EntryID(const EntryID& other) = delete;
199 EntryID& operator=(const EntryID& other) = delete;
201 uint32_t getOrInvalid() {
202 // It's OK for this to be relaxed, even though we're effectively doing
203 // double checked locking in using this value. We only care about the
204 // uniqueness of IDs, getOrAllocate does not modify any other memory
205 // this thread will use.
206 return value.load(std::memory_order_relaxed);
209 uint32_t getOrAllocate() {
210 uint32_t id = getOrInvalid();
211 if (id != kInvalid) {
214 // The lock inside allocate ensures that a single value is allocated
215 return instance().allocate(this);
219 static StaticMeta<Tag>& instance() {
220 // Leak it on exit, there's only one per process and we don't have to
221 // worry about synchronization with exiting threads.
222 static bool constructed = (inst_ = new StaticMeta<Tag>());
223 (void)constructed; // suppress unused warning
228 std::vector<uint32_t> freeIds_;
230 pthread_key_t pthreadKey_;
233 void push_back(ThreadEntry* t) {
235 t->prev = head_.prev;
236 head_.prev->next = t;
240 void erase(ThreadEntry* t) {
241 t->next->prev = t->prev;
242 t->prev->next = t->next;
243 t->next = t->prev = t;
246 #ifdef FOLLY_TLD_USE_FOLLY_TLS
247 static FOLLY_TLS ThreadEntry threadEntry_;
249 static StaticMeta<Tag>* inst_;
251 StaticMeta() : nextId_(1) {
252 head_.next = head_.prev = &head_;
253 int ret = pthread_key_create(&pthreadKey_, &onThreadExit);
254 checkPosixError(ret, "pthread_key_create failed");
256 #if FOLLY_HAVE_PTHREAD_ATFORK
257 ret = pthread_atfork(/*prepare*/ &StaticMeta::preFork,
258 /*parent*/ &StaticMeta::onForkParent,
259 /*child*/ &StaticMeta::onForkChild);
260 checkPosixError(ret, "pthread_atfork failed");
261 #elif !__ANDROID__ && !defined(_MSC_VER)
262 // pthread_atfork is not part of the Android NDK at least as of n9d. If
263 // something is trying to call native fork() directly at all with Android's
264 // process management model, this is probably the least of the problems.
266 // But otherwise, this is a problem.
267 #warning pthread_atfork unavailable
271 LOG(FATAL) << "StaticMeta lives forever!";
274 static ThreadEntry* getThreadEntry() {
275 #ifdef FOLLY_TLD_USE_FOLLY_TLS
276 return &threadEntry_;
278 auto key = instance().pthreadKey_;
279 ThreadEntry* threadEntry =
280 static_cast<ThreadEntry*>(pthread_getspecific(key));
282 threadEntry = new ThreadEntry();
283 int ret = pthread_setspecific(key, threadEntry);
284 checkPosixError(ret, "pthread_setspecific failed");
290 static void preFork(void) {
291 instance().lock_.lock(); // Make sure it's created
294 static void onForkParent(void) {
295 inst_->lock_.unlock();
298 static void onForkChild(void) {
299 // only the current thread survives
300 inst_->head_.next = inst_->head_.prev = &inst_->head_;
301 ThreadEntry* threadEntry = getThreadEntry();
302 // If this thread was in the list before the fork, add it back.
303 if (threadEntry->elementsCapacity != 0) {
304 inst_->push_back(threadEntry);
306 inst_->lock_.unlock();
309 static void onThreadExit(void* ptr) {
310 auto& meta = instance();
311 #ifdef FOLLY_TLD_USE_FOLLY_TLS
312 ThreadEntry* threadEntry = getThreadEntry();
314 DCHECK_EQ(ptr, &meta);
315 DCHECK_GT(threadEntry->elementsCapacity, 0);
317 // pthread sets the thread-specific value corresponding
318 // to meta.pthreadKey_ to NULL before calling onThreadExit.
319 // We need to set it back to ptr to enable the correct behaviour
320 // of the subsequent calls of getThreadEntry
321 // (which may happen in user-provided custom deleters)
322 pthread_setspecific(meta.pthreadKey_, ptr);
323 ThreadEntry* threadEntry = static_cast<ThreadEntry*>(ptr);
326 std::lock_guard<std::mutex> g(meta.lock_);
327 meta.erase(threadEntry);
328 // No need to hold the lock any longer; the ThreadEntry is private to this
329 // thread now that it's been removed from meta.
331 // NOTE: User-provided deleter / object dtor itself may be using ThreadLocal
332 // with the same Tag, so dispose() calls below may (re)create some of the
333 // elements or even increase elementsCapacity, thus multiple cleanup rounds
335 for (bool shouldRun = true; shouldRun; ) {
337 FOR_EACH_RANGE(i, 0, threadEntry->elementsCapacity) {
338 if (threadEntry->elements[i].dispose(TLPDestructionMode::THIS_THREAD)) {
343 free(threadEntry->elements);
344 threadEntry->elements = nullptr;
345 pthread_setspecific(meta.pthreadKey_, nullptr);
347 #ifndef FOLLY_TLD_USE_FOLLY_TLS
348 // Allocated in getThreadEntry() when not using folly TLS; free it
353 static uint32_t allocate(EntryID* ent) {
355 auto & meta = instance();
356 std::lock_guard<std::mutex> g(meta.lock_);
358 id = ent->value.load();
359 if (id != EntryID::kInvalid) {
363 if (!meta.freeIds_.empty()) {
364 id = meta.freeIds_.back();
365 meta.freeIds_.pop_back();
370 uint32_t old_id = ent->value.exchange(id);
371 DCHECK_EQ(old_id, EntryID::kInvalid);
375 static void destroy(EntryID* ent) {
377 auto & meta = instance();
378 // Elements in other threads that use this id.
379 std::vector<ElementWrapper> elements;
381 std::lock_guard<std::mutex> g(meta.lock_);
382 uint32_t id = ent->value.exchange(EntryID::kInvalid);
383 if (id == EntryID::kInvalid) {
387 for (ThreadEntry* e = meta.head_.next; e != &meta.head_; e = e->next) {
388 if (id < e->elementsCapacity && e->elements[id].ptr) {
389 elements.push_back(e->elements[id]);
392 * Writing another thread's ThreadEntry from here is fine;
393 * the only other potential reader is the owning thread --
394 * from onThreadExit (which grabs the lock, so is properly
395 * synchronized with us) or from get(), which also grabs
396 * the lock if it needs to resize the elements vector.
398 * We can't conflict with reads for a get(id), because
399 * it's illegal to call get on a thread local that's
402 e->elements[id].ptr = nullptr;
403 e->elements[id].deleter = nullptr;
404 e->elements[id].ownsDeleter = false;
407 meta.freeIds_.push_back(id);
409 // Delete elements outside the lock
410 FOR_EACH(it, elements) {
411 it->dispose(TLPDestructionMode::ALL_THREADS);
413 } catch (...) { // Just in case we get a lock error or something anyway...
414 LOG(WARNING) << "Destructor discarding an exception that was thrown.";
419 * Reserve enough space in the ThreadEntry::elements for the item
422 static void reserve(EntryID* id) {
423 auto& meta = instance();
424 ThreadEntry* threadEntry = getThreadEntry();
425 size_t prevCapacity = threadEntry->elementsCapacity;
427 uint32_t idval = id->getOrAllocate();
428 if (prevCapacity > idval) {
431 // Growth factor < 2, see folly/docs/FBVector.md; + 5 to prevent
433 size_t newCapacity = static_cast<size_t>((idval + 5) * 1.7);
434 assert(newCapacity > prevCapacity);
435 ElementWrapper* reallocated = nullptr;
437 // Need to grow. Note that we can't call realloc, as elements is
438 // still linked in meta, so another thread might access invalid memory
439 // after realloc succeeds. We'll copy by hand and update our ThreadEntry
441 if (usingJEMalloc()) {
442 bool success = false;
443 size_t newByteSize = nallocx(newCapacity * sizeof(ElementWrapper), 0);
445 // Try to grow in place.
447 // Note that xallocx(MALLOCX_ZERO) will only zero newly allocated memory,
448 // even if a previous allocation allocated more than we requested.
449 // This is fine; we always use MALLOCX_ZERO with jemalloc and we
450 // always expand our allocation to the real size.
451 if (prevCapacity * sizeof(ElementWrapper) >=
452 jemallocMinInPlaceExpandable) {
453 success = (xallocx(threadEntry->elements, newByteSize, 0, MALLOCX_ZERO)
457 // In-place growth failed.
459 success = ((reallocated = static_cast<ElementWrapper*>(
460 mallocx(newByteSize, MALLOCX_ZERO))) != nullptr);
464 // Expand to real size
465 assert(newByteSize / sizeof(ElementWrapper) >= newCapacity);
466 newCapacity = newByteSize / sizeof(ElementWrapper);
468 throw std::bad_alloc();
470 } else { // no jemalloc
471 // calloc() is simpler than malloc() followed by memset(), and
472 // potentially faster when dealing with a lot of memory, as it can get
473 // already-zeroed pages from the kernel.
474 reallocated = static_cast<ElementWrapper*>(
475 calloc(newCapacity, sizeof(ElementWrapper)));
477 throw std::bad_alloc();
481 // Success, update the entry
483 std::lock_guard<std::mutex> g(meta.lock_);
485 if (prevCapacity == 0) {
486 meta.push_back(threadEntry);
491 * Note: we need to hold the meta lock when copying data out of
492 * the old vector, because some other thread might be
493 * destructing a ThreadLocal and writing to the elements vector
496 memcpy(reallocated, threadEntry->elements,
497 sizeof(ElementWrapper) * prevCapacity);
499 swap(reallocated, threadEntry->elements);
501 threadEntry->elementsCapacity = newCapacity;
506 #ifdef FOLLY_TLD_USE_FOLLY_TLS
507 if (prevCapacity == 0) {
508 pthread_setspecific(meta.pthreadKey_, &meta);
513 static ElementWrapper& get(EntryID* ent) {
514 ThreadEntry* threadEntry = getThreadEntry();
515 uint32_t id = ent->getOrInvalid();
516 // if id is invalid, it is equal to uint32_t's max value.
517 // x <= max value is always true
518 if (UNLIKELY(threadEntry->elementsCapacity <= id)) {
520 id = ent->getOrInvalid();
521 assert(threadEntry->elementsCapacity > id);
523 return threadEntry->elements[id];
527 #ifdef FOLLY_TLD_USE_FOLLY_TLS
529 FOLLY_TLS ThreadEntry StaticMeta<Tag>::threadEntry_ = {nullptr, 0,
532 template <class Tag> StaticMeta<Tag>* StaticMeta<Tag>::inst_ = nullptr;
534 } // namespace threadlocal_detail
537 #endif /* FOLLY_DETAIL_THREADLOCALDETAIL_H_ */