2f6f10e85739258f43f6b8d9ea74c733e211e0a7
[folly.git] / folly / detail / ThreadLocalDetail.h
1 /*
2  * Copyright 2017 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
17 #pragma once
18
19 #include <limits.h>
20
21 #include <atomic>
22 #include <functional>
23 #include <mutex>
24 #include <string>
25 #include <vector>
26
27 #include <glog/logging.h>
28
29 #include <folly/Exception.h>
30 #include <folly/Function.h>
31 #include <folly/MicroSpinLock.h>
32 #include <folly/Portability.h>
33 #include <folly/ScopeGuard.h>
34 #include <folly/SharedMutex.h>
35 #include <folly/container/Foreach.h>
36 #include <folly/memory/Malloc.h>
37 #include <folly/portability/PThread.h>
38
39 #include <folly/detail/StaticSingletonManager.h>
40
41 // In general, emutls cleanup is not guaranteed to play nice with the way
42 // StaticMeta mixes direct pthread calls and the use of __thread. This has
43 // caused problems on multiple platforms so don't use __thread there.
44 //
45 // XXX: Ideally we would instead determine if emutls is in use at runtime as it
46 // is possible to configure glibc on Linux to use emutls regardless.
47 #if !FOLLY_MOBILE && !defined(__APPLE__) && !defined(_MSC_VER)
48 #define FOLLY_TLD_USE_FOLLY_TLS 1
49 #else
50 #undef FOLLY_TLD_USE_FOLLY_TLS
51 #endif
52
53 namespace folly {
54
55 enum class TLPDestructionMode { THIS_THREAD, ALL_THREADS };
56 struct AccessModeStrict {};
57
58 namespace threadlocal_detail {
59
60 /**
61  * POD wrapper around an element (a void*) and an associated deleter.
62  * This must be POD, as we memset() it to 0 and memcpy() it around.
63  */
64 struct ElementWrapper {
65   using DeleterFunType = void(void*, TLPDestructionMode);
66
67   bool dispose(TLPDestructionMode mode) {
68     if (ptr == nullptr) {
69       return false;
70     }
71
72     DCHECK(deleter1 != nullptr);
73     ownsDeleter ? (*deleter2)(ptr, mode) : (*deleter1)(ptr, mode);
74     cleanup();
75     return true;
76   }
77
78   void* release() {
79     auto retPtr = ptr;
80
81     if (ptr != nullptr) {
82       cleanup();
83     }
84
85     return retPtr;
86   }
87
88   template <class Ptr>
89   void set(Ptr p) {
90     auto guard = makeGuard([&] { delete p; });
91     DCHECK(ptr == nullptr);
92     DCHECK(deleter1 == nullptr);
93
94     if (p) {
95       ptr = p;
96       deleter1 = [](void* pt, TLPDestructionMode) {
97         delete static_cast<Ptr>(pt);
98       };
99       ownsDeleter = false;
100       guard.dismiss();
101     }
102   }
103
104   template <class Ptr, class Deleter>
105   void set(Ptr p, const Deleter& d) {
106     auto guard = makeGuard([&] {
107       if (p) {
108         d(p, TLPDestructionMode::THIS_THREAD);
109       }
110     });
111     DCHECK(ptr == nullptr);
112     DCHECK(deleter2 == nullptr);
113     if (p) {
114       ptr = p;
115       auto d2 = d; // gcc-4.8 doesn't decay types correctly in lambda captures
116       deleter2 = new std::function<DeleterFunType>(
117           [d2](void* pt, TLPDestructionMode mode) {
118             d2(static_cast<Ptr>(pt), mode);
119           });
120       ownsDeleter = true;
121       guard.dismiss();
122     }
123   }
124
125   void cleanup() {
126     if (ownsDeleter) {
127       delete deleter2;
128     }
129     ptr = nullptr;
130     deleter1 = nullptr;
131     ownsDeleter = false;
132   }
133
134   void* ptr;
135   union {
136     DeleterFunType* deleter1;
137     std::function<DeleterFunType>* deleter2;
138   };
139   bool ownsDeleter;
140 };
141
142 struct StaticMetaBase;
143
144 /**
145  * Per-thread entry.  Each thread using a StaticMeta object has one.
146  * This is written from the owning thread only (under the lock), read
147  * from the owning thread (no lock necessary), and read from other threads
148  * (under the lock).
149  */
150 struct ThreadEntry {
151   ElementWrapper* elements{nullptr};
152   size_t elementsCapacity{0};
153   ThreadEntry* next{nullptr};
154   ThreadEntry* prev{nullptr};
155   StaticMetaBase* meta{nullptr};
156 };
157
158 constexpr uint32_t kEntryIDInvalid = std::numeric_limits<uint32_t>::max();
159
160 struct PthreadKeyUnregisterTester;
161
162 /**
163  * We want to disable onThreadExit call at the end of shutdown, we don't care
164  * about leaking memory at that point.
165  *
166  * Otherwise if ThreadLocal is used in a shared library, onThreadExit may be
167  * called after dlclose().
168  *
169  * This class has one single static instance; however since it's so widely used,
170  * directly or indirectly, by so many classes, we need to take care to avoid
171  * problems stemming from the Static Initialization/Destruction Order Fiascos.
172  * Therefore this class needs to be constexpr-constructible, so as to avoid
173  * the need for this to participate in init/destruction order.
174  */
175 class PthreadKeyUnregister {
176  public:
177   static constexpr size_t kMaxKeys = 1UL << 16;
178
179   ~PthreadKeyUnregister() {
180     // If static constructor priorities are not supported then
181     // ~PthreadKeyUnregister logic is not safe.
182 #if !defined(__APPLE__) && !defined(_MSC_VER)
183     MSLGuard lg(lock_);
184     while (size_) {
185       pthread_key_delete(keys_[--size_]);
186     }
187 #endif
188   }
189
190   static void registerKey(pthread_key_t key) {
191     instance_.registerKeyImpl(key);
192   }
193
194  private:
195   /**
196    * Only one global instance should exist, hence this is private.
197    * See also the important note at the top of this class about `constexpr`
198    * usage.
199    */
200   constexpr PthreadKeyUnregister() : lock_(), size_(0), keys_() { }
201   friend struct folly::threadlocal_detail::PthreadKeyUnregisterTester;
202
203   void registerKeyImpl(pthread_key_t key) {
204     MSLGuard lg(lock_);
205     if (size_ == kMaxKeys) {
206       throw std::logic_error("pthread_key limit has already been reached");
207     }
208     keys_[size_++] = key;
209   }
210
211   MicroSpinLock lock_;
212   size_t size_;
213   pthread_key_t keys_[kMaxKeys];
214
215   static PthreadKeyUnregister instance_;
216 };
217
218 struct StaticMetaBase {
219   // Represents an ID of a thread local object. Initially set to the maximum
220   // uint. This representation allows us to avoid a branch in accessing TLS data
221   // (because if you test capacity > id if id = maxint then the test will always
222   // fail). It allows us to keep a constexpr constructor and avoid SIOF.
223   class EntryID {
224    public:
225     std::atomic<uint32_t> value;
226
227     constexpr EntryID() : value(kEntryIDInvalid) {
228     }
229
230     EntryID(EntryID&& other) noexcept : value(other.value.load()) {
231       other.value = kEntryIDInvalid;
232     }
233
234     EntryID& operator=(EntryID&& other) {
235       assert(this != &other);
236       value = other.value.load();
237       other.value = kEntryIDInvalid;
238       return *this;
239     }
240
241     EntryID(const EntryID& other) = delete;
242     EntryID& operator=(const EntryID& other) = delete;
243
244     uint32_t getOrInvalid() {
245       // It's OK for this to be relaxed, even though we're effectively doing
246       // double checked locking in using this value. We only care about the
247       // uniqueness of IDs, getOrAllocate does not modify any other memory
248       // this thread will use.
249       return value.load(std::memory_order_relaxed);
250     }
251
252     uint32_t getOrAllocate(StaticMetaBase& meta) {
253       uint32_t id = getOrInvalid();
254       if (id != kEntryIDInvalid) {
255         return id;
256       }
257       // The lock inside allocate ensures that a single value is allocated
258       return meta.allocate(this);
259     }
260   };
261
262   StaticMetaBase(ThreadEntry* (*threadEntry)(), bool strict);
263
264   [[noreturn]] ~StaticMetaBase() {
265     folly::assume_unreachable();
266   }
267
268   void push_back(ThreadEntry* t) {
269     t->next = &head_;
270     t->prev = head_.prev;
271     head_.prev->next = t;
272     head_.prev = t;
273   }
274
275   void erase(ThreadEntry* t) {
276     t->next->prev = t->prev;
277     t->prev->next = t->next;
278     t->next = t->prev = t;
279   }
280
281   static void onThreadExit(void* ptr);
282
283   uint32_t allocate(EntryID* ent);
284
285   void destroy(EntryID* ent);
286
287   /**
288    * Reserve enough space in the ThreadEntry::elements for the item
289    * @id to fit in.
290    */
291   void reserve(EntryID* id);
292
293   ElementWrapper& getElement(EntryID* ent);
294
295   static void initAtFork();
296   static void registerAtFork(
297       folly::Function<void()> prepare,
298       folly::Function<void()> parent,
299       folly::Function<void()> child);
300
301   uint32_t nextId_;
302   std::vector<uint32_t> freeIds_;
303   std::mutex lock_;
304   SharedMutex accessAllThreadsLock_;
305   pthread_key_t pthreadKey_;
306   ThreadEntry head_;
307   ThreadEntry* (*threadEntry_)();
308   bool strict_;
309 };
310
311 // Held in a singleton to track our global instances.
312 // We have one of these per "Tag", by default one for the whole system
313 // (Tag=void).
314 //
315 // Creating and destroying ThreadLocalPtr objects, as well as thread exit
316 // for threads that use ThreadLocalPtr objects collide on a lock inside
317 // StaticMeta; you can specify multiple Tag types to break that lock.
318 template <class Tag, class AccessMode>
319 struct StaticMeta : StaticMetaBase {
320   StaticMeta()
321       : StaticMetaBase(
322             &StaticMeta::getThreadEntrySlow,
323             std::is_same<AccessMode, AccessModeStrict>::value) {
324     registerAtFork(
325         /*prepare*/ &StaticMeta::preFork,
326         /*parent*/ &StaticMeta::onForkParent,
327         /*child*/ &StaticMeta::onForkChild);
328   }
329
330   static StaticMeta<Tag, AccessMode>& instance() {
331     // Leak it on exit, there's only one per process and we don't have to
332     // worry about synchronization with exiting threads.
333     /* library-local */ static auto instance =
334         detail::createGlobal<StaticMeta<Tag, AccessMode>, void>();
335     return *instance;
336   }
337
338   FOLLY_ALWAYS_INLINE static ElementWrapper& get(EntryID* ent) {
339     uint32_t id = ent->getOrInvalid();
340 #ifdef FOLLY_TLD_USE_FOLLY_TLS
341     static FOLLY_TLS ThreadEntry* threadEntry{};
342     static FOLLY_TLS size_t capacity{};
343     // Eliminate as many branches and as much extra code as possible in the
344     // cached fast path, leaving only one branch here and one indirection below.
345     if (UNLIKELY(capacity <= id)) {
346       getSlowReserveAndCache(ent, id, threadEntry, capacity);
347     }
348 #else
349     ThreadEntry* threadEntry{};
350     size_t capacity{};
351     getSlowReserveAndCache(ent, id, threadEntry, capacity);
352 #endif
353     return threadEntry->elements[id];
354   }
355
356   static void getSlowReserveAndCache(
357       EntryID* ent,
358       uint32_t& id,
359       ThreadEntry*& threadEntry,
360       size_t& capacity) {
361     auto& inst = instance();
362     threadEntry = inst.threadEntry_();
363     if (UNLIKELY(threadEntry->elementsCapacity <= id)) {
364       inst.reserve(ent);
365       id = ent->getOrInvalid();
366     }
367     capacity = threadEntry->elementsCapacity;
368     assert(capacity > id);
369   }
370
371   static ThreadEntry* getThreadEntrySlow() {
372     auto& meta = instance();
373     auto key = meta.pthreadKey_;
374     ThreadEntry* threadEntry =
375       static_cast<ThreadEntry*>(pthread_getspecific(key));
376     if (!threadEntry) {
377 #ifdef FOLLY_TLD_USE_FOLLY_TLS
378       static FOLLY_TLS ThreadEntry threadEntrySingleton;
379       threadEntry = &threadEntrySingleton;
380 #else
381       threadEntry = new ThreadEntry();
382 #endif
383       threadEntry->meta = &meta;
384       int ret = pthread_setspecific(key, threadEntry);
385       checkPosixError(ret, "pthread_setspecific failed");
386     }
387     return threadEntry;
388   }
389
390   static void preFork() {
391     instance().lock_.lock();  // Make sure it's created
392   }
393
394   static void onForkParent() {
395     instance().lock_.unlock();
396   }
397
398   static void onForkChild() {
399     // only the current thread survives
400     instance().head_.next = instance().head_.prev = &instance().head_;
401     ThreadEntry* threadEntry = instance().threadEntry_();
402     // If this thread was in the list before the fork, add it back.
403     if (threadEntry->elementsCapacity != 0) {
404       instance().push_back(threadEntry);
405     }
406     instance().lock_.unlock();
407   }
408 };
409 } // namespace threadlocal_detail
410 } // namespace folly