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