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