Improve folly::ThreadLocal perf
[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/Malloc.h>
33 #include <folly/MicroSpinLock.h>
34 #include <folly/Portability.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 !FOLLY_MOBILE && !defined(__APPLE__)
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 = [](void* pt, TLPDestructionMode) {
89         delete static_cast<Ptr>(pt);
90       };
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::getThreadEntrySlow) {
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   ElementWrapper& get(EntryID* ent) {
317     ThreadEntry* threadEntry = getThreadEntry();
318     uint32_t id = ent->getOrInvalid();
319     // if id is invalid, it is equal to uint32_t's max value.
320     // x <= max value is always true
321     if (UNLIKELY(threadEntry->elementsCapacity <= id)) {
322       reserve(ent);
323       id = ent->getOrInvalid();
324       assert(threadEntry->elementsCapacity > id);
325     }
326     return threadEntry->elements[id];
327   }
328
329   static ThreadEntry* getThreadEntrySlow() {
330     auto& meta = instance();
331     auto key = meta.pthreadKey_;
332     ThreadEntry* threadEntry =
333       static_cast<ThreadEntry*>(pthread_getspecific(key));
334     if (!threadEntry) {
335 #ifdef FOLLY_TLD_USE_FOLLY_TLS
336       static FOLLY_TLS ThreadEntry threadEntrySingleton;
337       threadEntry = &threadEntrySingleton;
338 #else
339       threadEntry = new ThreadEntry();
340 #endif
341       threadEntry->meta = &meta;
342       int ret = pthread_setspecific(key, threadEntry);
343       checkPosixError(ret, "pthread_setspecific failed");
344     }
345     return threadEntry;
346   }
347
348   inline static ThreadEntry* getThreadEntry() {
349 #ifdef FOLLY_TLD_USE_FOLLY_TLS
350     static FOLLY_TLS ThreadEntry* threadEntryCache{nullptr};
351     if (UNLIKELY(threadEntryCache == nullptr)) {
352       threadEntryCache = instance().threadEntry_();
353     }
354     return threadEntryCache;
355 #else
356     return instance().threadEntry_();
357 #endif
358   }
359
360   static void preFork(void) {
361     instance().lock_.lock();  // Make sure it's created
362   }
363
364   static void onForkParent(void) { instance().lock_.unlock(); }
365
366   static void onForkChild(void) {
367     // only the current thread survives
368     instance().head_.next = instance().head_.prev = &instance().head_;
369     ThreadEntry* threadEntry = getThreadEntry();
370     // If this thread was in the list before the fork, add it back.
371     if (threadEntry->elementsCapacity != 0) {
372       instance().push_back(threadEntry);
373     }
374     instance().lock_.unlock();
375   }
376 };
377
378 }  // namespace threadlocal_detail
379 }  // namespace folly