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.
28 #include <glog/logging.h>
30 #include <folly/Exception.h>
31 #include <folly/Foreach.h>
32 #include <folly/Malloc.h>
33 #include <folly/MicroSpinLock.h>
34 #include <folly/Portability.h>
36 #include <folly/detail/StaticSingletonManager.h>
38 // In general, emutls cleanup is not guaranteed to play nice with the way
39 // StaticMeta mixes direct pthread calls and the use of __thread. This has
40 // caused problems on multiple platforms so don't use __thread there.
42 // XXX: Ideally we would instead determine if emutls is in use at runtime as it
43 // is possible to configure glibc on Linux to use emutls regardless.
44 #if !FOLLY_MOBILE && !defined(__APPLE__)
45 #define FOLLY_TLD_USE_FOLLY_TLS 1
47 #undef FOLLY_TLD_USE_FOLLY_TLS
51 namespace threadlocal_detail {
54 * POD wrapper around an element (a void*) and an associated deleter.
55 * This must be POD, as we memset() it to 0 and memcpy() it around.
57 struct ElementWrapper {
58 using DeleterFunType = void(void*, TLPDestructionMode);
60 bool dispose(TLPDestructionMode mode) {
65 DCHECK(deleter1 != nullptr);
66 ownsDeleter ? (*deleter2)(ptr, mode) : (*deleter1)(ptr, mode);
83 DCHECK(ptr == nullptr);
84 DCHECK(deleter1 == nullptr);
88 deleter1 = [](void* pt, TLPDestructionMode) {
89 delete static_cast<Ptr>(pt);
95 template <class Ptr, class Deleter>
96 void set(Ptr p, Deleter d) {
97 DCHECK(ptr == nullptr);
98 DCHECK(deleter2 == nullptr);
101 deleter2 = new std::function<DeleterFunType>(
102 [d](void* pt, TLPDestructionMode mode) {
103 d(static_cast<Ptr>(pt), mode);
120 DeleterFunType* deleter1;
121 std::function<DeleterFunType>* deleter2;
126 struct StaticMetaBase;
129 * Per-thread entry. Each thread using a StaticMeta object has one.
130 * This is written from the owning thread only (under the lock), read
131 * from the owning thread (no lock necessary), and read from other threads
135 ElementWrapper* elements{nullptr};
136 size_t elementsCapacity{0};
137 ThreadEntry* next{nullptr};
138 ThreadEntry* prev{nullptr};
139 StaticMetaBase* meta{nullptr};
142 constexpr uint32_t kEntryIDInvalid = std::numeric_limits<uint32_t>::max();
144 class PthreadKeyUnregisterTester;
147 * We want to disable onThreadExit call at the end of shutdown, we don't care
148 * about leaking memory at that point.
150 * Otherwise if ThreadLocal is used in a shared library, onThreadExit may be
151 * called after dlclose().
153 * This class has one single static instance; however since it's so widely used,
154 * directly or indirectly, by so many classes, we need to take care to avoid
155 * problems stemming from the Static Initialization/Destruction Order Fiascos.
156 * Therefore this class needs to be constexpr-constructible, so as to avoid
157 * the need for this to participate in init/destruction order.
159 class PthreadKeyUnregister {
161 static constexpr size_t kMaxKeys = 1UL << 16;
163 ~PthreadKeyUnregister() {
166 pthread_key_delete(keys_[--size_]);
170 static void registerKey(pthread_key_t key) {
171 instance_.registerKeyImpl(key);
176 * Only one global instance should exist, hence this is private.
177 * See also the important note at the top of this class about `constexpr`
180 constexpr PthreadKeyUnregister() : lock_(), size_(0), keys_() { }
181 friend class folly::threadlocal_detail::PthreadKeyUnregisterTester;
183 void registerKeyImpl(pthread_key_t key) {
185 if (size_ == kMaxKeys) {
186 throw std::logic_error("pthread_key limit has already been reached");
188 keys_[size_++] = key;
193 pthread_key_t keys_[kMaxKeys];
195 static PthreadKeyUnregister instance_;
198 struct StaticMetaBase {
199 // Represents an ID of a thread local object. Initially set to the maximum
200 // uint. This representation allows us to avoid a branch in accessing TLS data
201 // (because if you test capacity > id if id = maxint then the test will always
202 // fail). It allows us to keep a constexpr constructor and avoid SIOF.
205 std::atomic<uint32_t> value;
207 constexpr EntryID() : value(kEntryIDInvalid) {
210 EntryID(EntryID&& other) noexcept : value(other.value.load()) {
211 other.value = kEntryIDInvalid;
214 EntryID& operator=(EntryID&& other) {
215 assert(this != &other);
216 value = other.value.load();
217 other.value = kEntryIDInvalid;
221 EntryID(const EntryID& other) = delete;
222 EntryID& operator=(const EntryID& other) = delete;
224 uint32_t getOrInvalid() {
225 // It's OK for this to be relaxed, even though we're effectively doing
226 // double checked locking in using this value. We only care about the
227 // uniqueness of IDs, getOrAllocate does not modify any other memory
228 // this thread will use.
229 return value.load(std::memory_order_relaxed);
232 uint32_t getOrAllocate(StaticMetaBase& meta) {
233 uint32_t id = getOrInvalid();
234 if (id != kEntryIDInvalid) {
237 // The lock inside allocate ensures that a single value is allocated
238 return meta.allocate(this);
242 explicit StaticMetaBase(ThreadEntry* (*threadEntry)());
245 LOG(FATAL) << "StaticMeta lives forever!";
248 void push_back(ThreadEntry* t) {
250 t->prev = head_.prev;
251 head_.prev->next = t;
255 void erase(ThreadEntry* t) {
256 t->next->prev = t->prev;
257 t->prev->next = t->next;
258 t->next = t->prev = t;
261 static void onThreadExit(void* ptr);
263 uint32_t allocate(EntryID* ent);
265 void destroy(EntryID* ent);
268 * Reserve enough space in the ThreadEntry::elements for the item
271 void reserve(EntryID* id);
273 ElementWrapper& get(EntryID* ent);
276 std::vector<uint32_t> freeIds_;
278 pthread_key_t pthreadKey_;
280 ThreadEntry* (*threadEntry_)();
283 // Held in a singleton to track our global instances.
284 // We have one of these per "Tag", by default one for the whole system
287 // Creating and destroying ThreadLocalPtr objects, as well as thread exit
288 // for threads that use ThreadLocalPtr objects collide on a lock inside
289 // StaticMeta; you can specify multiple Tag types to break that lock.
291 struct StaticMeta : StaticMetaBase {
292 StaticMeta() : StaticMetaBase(&StaticMeta::getThreadEntrySlow) {
293 #if FOLLY_HAVE_PTHREAD_ATFORK
294 int ret = pthread_atfork(
295 /*prepare*/ &StaticMeta::preFork,
296 /*parent*/ &StaticMeta::onForkParent,
297 /*child*/ &StaticMeta::onForkChild);
298 checkPosixError(ret, "pthread_atfork failed");
299 #elif !__ANDROID__ && !defined(_MSC_VER)
300 // pthread_atfork is not part of the Android NDK at least as of n9d. If
301 // something is trying to call native fork() directly at all with Android's
302 // process management model, this is probably the least of the problems.
304 // But otherwise, this is a problem.
305 #warning pthread_atfork unavailable
309 static StaticMeta<Tag>& instance() {
310 // Leak it on exit, there's only one per process and we don't have to
311 // worry about synchronization with exiting threads.
312 static auto instance = detail::createGlobal<StaticMeta<Tag>, void>();
316 ElementWrapper& get(EntryID* ent) {
317 ThreadEntry* threadEntry = getThreadEntry();
318 uint32_t id = ent->getOrInvalid();
319 // if id is invalid, it is equal to uint32_t's max value.
320 // x <= max value is always true
321 if (UNLIKELY(threadEntry->elementsCapacity <= id)) {
323 id = ent->getOrInvalid();
324 assert(threadEntry->elementsCapacity > id);
326 return threadEntry->elements[id];
329 static ThreadEntry* getThreadEntrySlow() {
330 auto& meta = instance();
331 auto key = meta.pthreadKey_;
332 ThreadEntry* threadEntry =
333 static_cast<ThreadEntry*>(pthread_getspecific(key));
335 #ifdef FOLLY_TLD_USE_FOLLY_TLS
336 static FOLLY_TLS ThreadEntry threadEntrySingleton;
337 threadEntry = &threadEntrySingleton;
339 threadEntry = new ThreadEntry();
341 threadEntry->meta = &meta;
342 int ret = pthread_setspecific(key, threadEntry);
343 checkPosixError(ret, "pthread_setspecific failed");
348 inline static ThreadEntry* getThreadEntry() {
349 #ifdef FOLLY_TLD_USE_FOLLY_TLS
350 static FOLLY_TLS ThreadEntry* threadEntryCache{nullptr};
351 if (UNLIKELY(threadEntryCache == nullptr)) {
352 threadEntryCache = instance().threadEntry_();
354 return threadEntryCache;
356 return instance().threadEntry_();
360 static void preFork(void) {
361 instance().lock_.lock(); // Make sure it's created
364 static void onForkParent(void) { instance().lock_.unlock(); }
366 static void onForkChild(void) {
367 // only the current thread survives
368 instance().head_.next = instance().head_.prev = &instance().head_;
369 ThreadEntry* threadEntry = getThreadEntry();
370 // If this thread was in the list before the fork, add it back.
371 if (threadEntry->elementsCapacity != 0) {
372 instance().push_back(threadEntry);
374 instance().lock_.unlock();
378 } // namespace threadlocal_detail