Use FOLLY_MOBILE to split some functionality
[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/Exception.h>
32 #include <folly/Foreach.h>
33 #include <folly/Malloc.h>
34 #include <folly/MicroSpinLock.h>
35 #include <folly/Portability.h>
36
37 #include <folly/detail/StaticSingletonManager.h>
38
39 // In general, emutls cleanup is not guaranteed to play nice with the way
40 // StaticMeta mixes direct pthread calls and the use of __thread. This has
41 // caused problems on multiple platforms so don't use __thread there.
42 //
43 // XXX: Ideally we would instead determine if emutls is in use at runtime as it
44 // is possible to configure glibc on Linux to use emutls regardless.
45 #if !FOLLY_MOBILE && !defined(__APPLE__)
46 #define FOLLY_TLD_USE_FOLLY_TLS 1
47 #else
48 #undef FOLLY_TLD_USE_FOLLY_TLS
49 #endif
50
51 namespace folly {
52 namespace threadlocal_detail {
53
54 /**
55  * POD wrapper around an element (a void*) and an associated deleter.
56  * This must be POD, as we memset() it to 0 and memcpy() it around.
57  */
58 struct ElementWrapper {
59   using DeleterFunType = void(void*, TLPDestructionMode);
60
61   bool dispose(TLPDestructionMode mode) {
62     if (ptr == nullptr) {
63       return false;
64     }
65
66     DCHECK(deleter1 != nullptr);
67     ownsDeleter ? (*deleter2)(ptr, mode) : (*deleter1)(ptr, mode);
68     cleanup();
69     return true;
70   }
71
72   void* release() {
73     auto retPtr = ptr;
74
75     if (ptr != nullptr) {
76       cleanup();
77     }
78
79     return retPtr;
80   }
81
82   template <class Ptr>
83   void set(Ptr p) {
84     DCHECK(ptr == nullptr);
85     DCHECK(deleter1 == nullptr);
86
87     if (p) {
88       ptr = p;
89       deleter1 =
90           +[](void* pt, TLPDestructionMode) { delete static_cast<Ptr>(pt); };
91       ownsDeleter = false;
92     }
93   }
94
95   template <class Ptr, class Deleter>
96   void set(Ptr p, Deleter d) {
97     DCHECK(ptr == nullptr);
98     DCHECK(deleter2 == nullptr);
99     if (p) {
100       ptr = p;
101       deleter2 = new std::function<DeleterFunType>(
102           [d](void* pt, TLPDestructionMode mode) {
103             d(static_cast<Ptr>(pt), mode);
104           });
105       ownsDeleter = true;
106     }
107   }
108
109   void cleanup() {
110     if (ownsDeleter) {
111       delete deleter2;
112     }
113     ptr = nullptr;
114     deleter1 = nullptr;
115     ownsDeleter = false;
116   }
117
118   void* ptr;
119   union {
120     DeleterFunType* deleter1;
121     std::function<DeleterFunType>* deleter2;
122   };
123   bool ownsDeleter;
124 };
125
126 struct StaticMetaBase;
127
128 /**
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
132  * (under the lock).
133  */
134 struct ThreadEntry {
135   ElementWrapper* elements{nullptr};
136   size_t elementsCapacity{0};
137   ThreadEntry* next{nullptr};
138   ThreadEntry* prev{nullptr};
139   StaticMetaBase* meta{nullptr};
140 };
141
142 constexpr uint32_t kEntryIDInvalid = std::numeric_limits<uint32_t>::max();
143
144 class PthreadKeyUnregisterTester;
145
146 /**
147  * We want to disable onThreadExit call at the end of shutdown, we don't care
148  * about leaking memory at that point.
149  *
150  * Otherwise if ThreadLocal is used in a shared library, onThreadExit may be
151  * called after dlclose().
152  *
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.
158  */
159 class PthreadKeyUnregister {
160  public:
161   static constexpr size_t kMaxKeys = 1UL << 16;
162
163   ~PthreadKeyUnregister() {
164     MSLGuard lg(lock_);
165     while (size_) {
166       pthread_key_delete(keys_[--size_]);
167     }
168   }
169
170   static void registerKey(pthread_key_t key) {
171     instance_.registerKeyImpl(key);
172   }
173
174  private:
175   /**
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`
178    * usage.
179    */
180   constexpr PthreadKeyUnregister() : lock_(), size_(0), keys_() { }
181   friend class folly::threadlocal_detail::PthreadKeyUnregisterTester;
182
183   void registerKeyImpl(pthread_key_t key) {
184     MSLGuard lg(lock_);
185     if (size_ == kMaxKeys) {
186       throw std::logic_error("pthread_key limit has already been reached");
187     }
188     keys_[size_++] = key;
189   }
190
191   MicroSpinLock lock_;
192   size_t size_;
193   pthread_key_t keys_[kMaxKeys];
194
195   static PthreadKeyUnregister instance_;
196 };
197
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.
203   class EntryID {
204    public:
205     std::atomic<uint32_t> value;
206
207     constexpr EntryID() : value(kEntryIDInvalid) {
208     }
209
210     EntryID(EntryID&& other) noexcept : value(other.value.load()) {
211       other.value = kEntryIDInvalid;
212     }
213
214     EntryID& operator=(EntryID&& other) {
215       assert(this != &other);
216       value = other.value.load();
217       other.value = kEntryIDInvalid;
218       return *this;
219     }
220
221     EntryID(const EntryID& other) = delete;
222     EntryID& operator=(const EntryID& other) = delete;
223
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);
230     }
231
232     uint32_t getOrAllocate(StaticMetaBase& meta) {
233       uint32_t id = getOrInvalid();
234       if (id != kEntryIDInvalid) {
235         return id;
236       }
237       // The lock inside allocate ensures that a single value is allocated
238       return meta.allocate(this);
239     }
240   };
241
242   explicit StaticMetaBase(ThreadEntry* (*threadEntry)());
243
244   ~StaticMetaBase() {
245     LOG(FATAL) << "StaticMeta lives forever!";
246   }
247
248   void push_back(ThreadEntry* t) {
249     t->next = &head_;
250     t->prev = head_.prev;
251     head_.prev->next = t;
252     head_.prev = t;
253   }
254
255   void erase(ThreadEntry* t) {
256     t->next->prev = t->prev;
257     t->prev->next = t->next;
258     t->next = t->prev = t;
259   }
260
261   static void onThreadExit(void* ptr);
262
263   uint32_t allocate(EntryID* ent);
264
265   void destroy(EntryID* ent);
266
267   /**
268    * Reserve enough space in the ThreadEntry::elements for the item
269    * @id to fit in.
270    */
271   void reserve(EntryID* id);
272
273   ElementWrapper& get(EntryID* ent);
274
275   uint32_t nextId_;
276   std::vector<uint32_t> freeIds_;
277   std::mutex lock_;
278   pthread_key_t pthreadKey_;
279   ThreadEntry head_;
280   ThreadEntry* (*threadEntry_)();
281 };
282
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
285 // (Tag=void).
286 //
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.
290 template <class Tag>
291 struct StaticMeta : StaticMetaBase {
292   StaticMeta() : StaticMetaBase(&StaticMeta::getThreadEntry) {
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.
303     //
304     // But otherwise, this is a problem.
305     #warning pthread_atfork unavailable
306 #endif
307   }
308
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>();
313     return *instance;
314   }
315
316   static ThreadEntry* getThreadEntrySlow() {
317     auto& meta = instance();
318     auto key = meta.pthreadKey_;
319     ThreadEntry* threadEntry =
320       static_cast<ThreadEntry*>(pthread_getspecific(key));
321     if (!threadEntry) {
322       threadEntry = new ThreadEntry();
323       threadEntry->meta = &meta;
324       int ret = pthread_setspecific(key, threadEntry);
325       checkPosixError(ret, "pthread_setspecific failed");
326     }
327     return threadEntry;
328   }
329
330   static ThreadEntry* getThreadEntry() {
331 #ifdef FOLLY_TLD_USE_FOLLY_TLS
332     static FOLLY_TLS ThreadEntry* threadEntryCache{nullptr};
333     if (UNLIKELY(threadEntryCache == nullptr)) {
334       threadEntryCache = getThreadEntrySlow();
335     }
336     return threadEntryCache;
337 #else
338     return getThreadEntrySlow();
339 #endif
340   }
341
342   static void preFork(void) {
343     instance().lock_.lock();  // Make sure it's created
344   }
345
346   static void onForkParent(void) { instance().lock_.unlock(); }
347
348   static void onForkChild(void) {
349     // only the current thread survives
350     instance().head_.next = instance().head_.prev = &instance().head_;
351     ThreadEntry* threadEntry = getThreadEntry();
352     // If this thread was in the list before the fork, add it back.
353     if (threadEntry->elementsCapacity != 0) {
354       instance().push_back(threadEntry);
355     }
356     instance().lock_.unlock();
357   }
358 };
359
360 }  // namespace threadlocal_detail
361 }  // namespace folly
362
363 #endif /* FOLLY_DETAIL_THREADLOCALDETAIL_H_ */