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