Fix folly/ThreadLocal with clang after PthreadKeyUnregister change
[folly.git] / folly / detail / ThreadLocalDetail.h
1 /*
2  * Copyright 2015 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 <mutex>
24 #include <string>
25 #include <vector>
26
27 #include <glog/logging.h>
28
29 #include <folly/Foreach.h>
30 #include <folly/Exception.h>
31 #include <folly/Malloc.h>
32
33 // In general, emutls cleanup is not guaranteed to play nice with the way
34 // StaticMeta mixes direct pthread calls and the use of __thread. This has
35 // caused problems on multiple platforms so don't use __thread there.
36 //
37 // XXX: Ideally we would instead determine if emutls is in use at runtime as it
38 // is possible to configure glibc on Linux to use emutls regardless.
39 #if !__APPLE__ && !__ANDROID__
40 #define FOLLY_TLD_USE_FOLLY_TLS 1
41 #else
42 #undef FOLLY_TLD_USE_FOLLY_TLS
43 #endif
44
45 namespace folly {
46 namespace threadlocal_detail {
47
48 /**
49  * Base class for deleters.
50  */
51 class DeleterBase {
52  public:
53   virtual ~DeleterBase() { }
54   virtual void dispose(void* ptr, TLPDestructionMode mode) const = 0;
55 };
56
57 /**
58  * Simple deleter class that calls delete on the passed-in pointer.
59  */
60 template <class Ptr>
61 class SimpleDeleter : public DeleterBase {
62  public:
63   virtual void dispose(void* ptr, TLPDestructionMode /*mode*/) const {
64     delete static_cast<Ptr>(ptr);
65   }
66 };
67
68 /**
69  * Custom deleter that calls a given callable.
70  */
71 template <class Ptr, class Deleter>
72 class CustomDeleter : public DeleterBase {
73  public:
74   explicit CustomDeleter(Deleter d) : deleter_(d) { }
75   virtual void dispose(void* ptr, TLPDestructionMode mode) const {
76     deleter_(static_cast<Ptr>(ptr), mode);
77   }
78  private:
79   Deleter deleter_;
80 };
81
82
83 /**
84  * POD wrapper around an element (a void*) and an associated deleter.
85  * This must be POD, as we memset() it to 0 and memcpy() it around.
86  */
87 struct ElementWrapper {
88   bool dispose(TLPDestructionMode mode) {
89     if (ptr == nullptr) {
90       return false;
91     }
92
93     DCHECK(deleter != nullptr);
94     deleter->dispose(ptr, mode);
95     cleanup();
96     return true;
97   }
98
99   void* release() {
100     auto retPtr = ptr;
101
102     if (ptr != nullptr) {
103       cleanup();
104     }
105
106     return retPtr;
107   }
108
109   template <class Ptr>
110   void set(Ptr p) {
111     DCHECK(ptr == nullptr);
112     DCHECK(deleter == nullptr);
113
114     if (p) {
115       // We leak a single object here but that is ok.  If we used an
116       // object directly, there is a chance that the destructor will be
117       // called on that static object before any of the ElementWrappers
118       // are disposed and that isn't so nice.
119       static auto d = new SimpleDeleter<Ptr>();
120       ptr = p;
121       deleter = d;
122       ownsDeleter = false;
123     }
124   }
125
126   template <class Ptr, class Deleter>
127   void set(Ptr p, Deleter d) {
128     DCHECK(ptr == nullptr);
129     DCHECK(deleter == nullptr);
130     if (p) {
131       ptr = p;
132       deleter = new CustomDeleter<Ptr,Deleter>(d);
133       ownsDeleter = true;
134     }
135   }
136
137   void cleanup() {
138     if (ownsDeleter) {
139       delete deleter;
140     }
141     ptr = nullptr;
142     deleter = nullptr;
143     ownsDeleter = false;
144   }
145
146   void* ptr;
147   DeleterBase* deleter;
148   bool ownsDeleter;
149 };
150
151 /**
152  * Per-thread entry.  Each thread using a StaticMeta object has one.
153  * This is written from the owning thread only (under the lock), read
154  * from the owning thread (no lock necessary), and read from other threads
155  * (under the lock).
156  */
157 struct ThreadEntry {
158   ElementWrapper* elements;
159   size_t elementsCapacity;
160   ThreadEntry* next;
161   ThreadEntry* prev;
162 };
163
164 constexpr uint32_t kEntryIDInvalid = std::numeric_limits<uint32_t>::max();
165
166 /**
167  * We want to disable onThreadExit call at the end of shutdown, we don't care
168  * about leaking memory at that point.
169  *
170  * Otherwise if ThreadLocal is used in a shared library, onThreadExit may be
171  * called after dlclose().
172  */
173 class PthreadKeyUnregister {
174  public:
175   ~PthreadKeyUnregister() {
176     std::lock_guard<std::mutex> lg(mutex_);
177
178     for (const auto& key: keys_) {
179       pthread_key_delete(key);
180     }
181   }
182
183   static void registerKey(pthread_key_t key) {
184     instance_.registerKeyImpl(key);
185   }
186
187  private:
188   PthreadKeyUnregister() {}
189
190   void registerKeyImpl(pthread_key_t key) {
191     std::lock_guard<std::mutex> lg(mutex_);
192
193     keys_.push_back(key);
194   }
195
196   std::mutex mutex_;
197   std::vector<pthread_key_t> keys_;
198
199   static PthreadKeyUnregister instance_;
200 };
201
202
203 // Held in a singleton to track our global instances.
204 // We have one of these per "Tag", by default one for the whole system
205 // (Tag=void).
206 //
207 // Creating and destroying ThreadLocalPtr objects, as well as thread exit
208 // for threads that use ThreadLocalPtr objects collide on a lock inside
209 // StaticMeta; you can specify multiple Tag types to break that lock.
210 template <class Tag>
211 struct StaticMeta {
212   // Represents an ID of a thread local object. Initially set to the maximum
213   // uint. This representation allows us to avoid a branch in accessing TLS data
214   // (because if you test capacity > id if id = maxint then the test will always
215   // fail). It allows us to keep a constexpr constructor and avoid SIOF.
216   class EntryID {
217    public:
218     std::atomic<uint32_t> value;
219
220     constexpr EntryID() : value(kEntryIDInvalid) {
221     }
222
223     EntryID(EntryID&& other) noexcept : value(other.value.load()) {
224       other.value = kEntryIDInvalid;
225     }
226
227     EntryID& operator=(EntryID&& other) {
228       assert(this != &other);
229       value = other.value.load();
230       other.value = kEntryIDInvalid;
231       return *this;
232     }
233
234     EntryID(const EntryID& other) = delete;
235     EntryID& operator=(const EntryID& other) = delete;
236
237     uint32_t getOrInvalid() {
238       // It's OK for this to be relaxed, even though we're effectively doing
239       // double checked locking in using this value. We only care about the
240       // uniqueness of IDs, getOrAllocate does not modify any other memory
241       // this thread will use.
242       return value.load(std::memory_order_relaxed);
243     }
244
245     uint32_t getOrAllocate() {
246       uint32_t id = getOrInvalid();
247       if (id != kEntryIDInvalid) {
248         return id;
249       }
250       // The lock inside allocate ensures that a single value is allocated
251       return instance().allocate(this);
252     }
253   };
254
255   static StaticMeta<Tag>& instance() {
256     // Leak it on exit, there's only one per process and we don't have to
257     // worry about synchronization with exiting threads.
258     static bool constructed = (inst_ = new StaticMeta<Tag>());
259     (void)constructed; // suppress unused warning
260     return *inst_;
261   }
262
263   uint32_t nextId_;
264   std::vector<uint32_t> freeIds_;
265   std::mutex lock_;
266   pthread_key_t pthreadKey_;
267   ThreadEntry head_;
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 #ifdef FOLLY_TLD_USE_FOLLY_TLS
283   static FOLLY_TLS ThreadEntry threadEntry_;
284 #endif
285   static StaticMeta<Tag>* inst_;
286
287   StaticMeta() : nextId_(1) {
288     head_.next = head_.prev = &head_;
289     int ret = pthread_key_create(&pthreadKey_, &onThreadExit);
290     checkPosixError(ret, "pthread_key_create failed");
291     PthreadKeyUnregister::registerKey(pthreadKey_);
292
293 #if FOLLY_HAVE_PTHREAD_ATFORK
294     ret = pthread_atfork(/*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   ~StaticMeta() {
308     LOG(FATAL) << "StaticMeta lives forever!";
309   }
310
311   static ThreadEntry* getThreadEntry() {
312 #ifdef FOLLY_TLD_USE_FOLLY_TLS
313     return &threadEntry_;
314 #else
315     auto key = instance().pthreadKey_;
316     ThreadEntry* threadEntry =
317       static_cast<ThreadEntry*>(pthread_getspecific(key));
318     if (!threadEntry) {
319         threadEntry = new ThreadEntry();
320         int ret = pthread_setspecific(key, threadEntry);
321         checkPosixError(ret, "pthread_setspecific failed");
322     }
323     return threadEntry;
324 #endif
325   }
326
327   static void preFork(void) {
328     instance().lock_.lock();  // Make sure it's created
329   }
330
331   static void onForkParent(void) {
332     inst_->lock_.unlock();
333   }
334
335   static void onForkChild(void) {
336     // only the current thread survives
337     inst_->head_.next = inst_->head_.prev = &inst_->head_;
338     ThreadEntry* threadEntry = getThreadEntry();
339     // If this thread was in the list before the fork, add it back.
340     if (threadEntry->elementsCapacity != 0) {
341       inst_->push_back(threadEntry);
342     }
343     inst_->lock_.unlock();
344   }
345
346   static void onThreadExit(void* ptr) {
347     auto& meta = instance();
348 #ifdef FOLLY_TLD_USE_FOLLY_TLS
349     ThreadEntry* threadEntry = getThreadEntry();
350
351     DCHECK_EQ(ptr, &meta);
352     DCHECK_GT(threadEntry->elementsCapacity, 0);
353 #else
354     // pthread sets the thread-specific value corresponding
355     // to meta.pthreadKey_ to NULL before calling onThreadExit.
356     // We need to set it back to ptr to enable the correct behaviour
357     // of the subsequent calls of getThreadEntry
358     // (which may happen in user-provided custom deleters)
359     pthread_setspecific(meta.pthreadKey_, ptr);
360     ThreadEntry* threadEntry = static_cast<ThreadEntry*>(ptr);
361 #endif
362     {
363       std::lock_guard<std::mutex> g(meta.lock_);
364       meta.erase(threadEntry);
365       // No need to hold the lock any longer; the ThreadEntry is private to this
366       // thread now that it's been removed from meta.
367     }
368     // NOTE: User-provided deleter / object dtor itself may be using ThreadLocal
369     // with the same Tag, so dispose() calls below may (re)create some of the
370     // elements or even increase elementsCapacity, thus multiple cleanup rounds
371     // may be required.
372     for (bool shouldRun = true; shouldRun; ) {
373       shouldRun = false;
374       FOR_EACH_RANGE(i, 0, threadEntry->elementsCapacity) {
375         if (threadEntry->elements[i].dispose(TLPDestructionMode::THIS_THREAD)) {
376           shouldRun = true;
377         }
378       }
379     }
380     free(threadEntry->elements);
381     threadEntry->elements = nullptr;
382     pthread_setspecific(meta.pthreadKey_, nullptr);
383
384 #ifndef FOLLY_TLD_USE_FOLLY_TLS
385     // Allocated in getThreadEntry() when not using folly TLS; free it
386     delete threadEntry;
387 #endif
388   }
389
390   static uint32_t allocate(EntryID* ent) {
391     uint32_t id;
392     auto & meta = instance();
393     std::lock_guard<std::mutex> g(meta.lock_);
394
395     id = ent->value.load();
396     if (id != kEntryIDInvalid) {
397       return id;
398     }
399
400     if (!meta.freeIds_.empty()) {
401       id = meta.freeIds_.back();
402       meta.freeIds_.pop_back();
403     } else {
404       id = meta.nextId_++;
405     }
406
407     uint32_t old_id = ent->value.exchange(id);
408     DCHECK_EQ(old_id, kEntryIDInvalid);
409     return id;
410   }
411
412   static void destroy(EntryID* ent) {
413     try {
414       auto & meta = instance();
415       // Elements in other threads that use this id.
416       std::vector<ElementWrapper> elements;
417       {
418         std::lock_guard<std::mutex> g(meta.lock_);
419         uint32_t id = ent->value.exchange(kEntryIDInvalid);
420         if (id == kEntryIDInvalid) {
421           return;
422         }
423
424         for (ThreadEntry* e = meta.head_.next; e != &meta.head_; e = e->next) {
425           if (id < e->elementsCapacity && e->elements[id].ptr) {
426             elements.push_back(e->elements[id]);
427
428             /*
429              * Writing another thread's ThreadEntry from here is fine;
430              * the only other potential reader is the owning thread --
431              * from onThreadExit (which grabs the lock, so is properly
432              * synchronized with us) or from get(), which also grabs
433              * the lock if it needs to resize the elements vector.
434              *
435              * We can't conflict with reads for a get(id), because
436              * it's illegal to call get on a thread local that's
437              * destructing.
438              */
439             e->elements[id].ptr = nullptr;
440             e->elements[id].deleter = nullptr;
441             e->elements[id].ownsDeleter = false;
442           }
443         }
444         meta.freeIds_.push_back(id);
445       }
446       // Delete elements outside the lock
447       FOR_EACH(it, elements) {
448         it->dispose(TLPDestructionMode::ALL_THREADS);
449       }
450     } catch (...) { // Just in case we get a lock error or something anyway...
451       LOG(WARNING) << "Destructor discarding an exception that was thrown.";
452     }
453   }
454
455   /**
456    * Reserve enough space in the ThreadEntry::elements for the item
457    * @id to fit in.
458    */
459   static void reserve(EntryID* id) {
460     auto& meta = instance();
461     ThreadEntry* threadEntry = getThreadEntry();
462     size_t prevCapacity = threadEntry->elementsCapacity;
463
464     uint32_t idval = id->getOrAllocate();
465     if (prevCapacity > idval) {
466       return;
467     }
468     // Growth factor < 2, see folly/docs/FBVector.md; + 5 to prevent
469     // very slow start.
470     size_t newCapacity = static_cast<size_t>((idval + 5) * 1.7);
471     assert(newCapacity > prevCapacity);
472     ElementWrapper* reallocated = nullptr;
473
474     // Need to grow. Note that we can't call realloc, as elements is
475     // still linked in meta, so another thread might access invalid memory
476     // after realloc succeeds. We'll copy by hand and update our ThreadEntry
477     // under the lock.
478     if (usingJEMalloc()) {
479       bool success = false;
480       size_t newByteSize = nallocx(newCapacity * sizeof(ElementWrapper), 0);
481
482       // Try to grow in place.
483       //
484       // Note that xallocx(MALLOCX_ZERO) will only zero newly allocated memory,
485       // even if a previous allocation allocated more than we requested.
486       // This is fine; we always use MALLOCX_ZERO with jemalloc and we
487       // always expand our allocation to the real size.
488       if (prevCapacity * sizeof(ElementWrapper) >=
489           jemallocMinInPlaceExpandable) {
490         success = (xallocx(threadEntry->elements, newByteSize, 0, MALLOCX_ZERO)
491                    == newByteSize);
492       }
493
494       // In-place growth failed.
495       if (!success) {
496         success = ((reallocated = static_cast<ElementWrapper*>(
497                     mallocx(newByteSize, MALLOCX_ZERO))) != nullptr);
498       }
499
500       if (success) {
501         // Expand to real size
502         assert(newByteSize / sizeof(ElementWrapper) >= newCapacity);
503         newCapacity = newByteSize / sizeof(ElementWrapper);
504       } else {
505         throw std::bad_alloc();
506       }
507     } else {  // no jemalloc
508       // calloc() is simpler than malloc() followed by memset(), and
509       // potentially faster when dealing with a lot of memory, as it can get
510       // already-zeroed pages from the kernel.
511       reallocated = static_cast<ElementWrapper*>(
512           calloc(newCapacity, sizeof(ElementWrapper)));
513       if (!reallocated) {
514         throw std::bad_alloc();
515       }
516     }
517
518     // Success, update the entry
519     {
520       std::lock_guard<std::mutex> g(meta.lock_);
521
522       if (prevCapacity == 0) {
523         meta.push_back(threadEntry);
524       }
525
526       if (reallocated) {
527        /*
528         * Note: we need to hold the meta lock when copying data out of
529         * the old vector, because some other thread might be
530         * destructing a ThreadLocal and writing to the elements vector
531         * of this thread.
532         */
533         memcpy(reallocated, threadEntry->elements,
534                sizeof(ElementWrapper) * prevCapacity);
535         using std::swap;
536         swap(reallocated, threadEntry->elements);
537       }
538       threadEntry->elementsCapacity = newCapacity;
539     }
540
541     free(reallocated);
542
543 #ifdef FOLLY_TLD_USE_FOLLY_TLS
544     if (prevCapacity == 0) {
545       pthread_setspecific(meta.pthreadKey_, &meta);
546     }
547 #endif
548   }
549
550   static ElementWrapper& get(EntryID* ent) {
551     ThreadEntry* threadEntry = getThreadEntry();
552     uint32_t id = ent->getOrInvalid();
553     // if id is invalid, it is equal to uint32_t's max value.
554     // x <= max value is always true
555     if (UNLIKELY(threadEntry->elementsCapacity <= id)) {
556       reserve(ent);
557       id = ent->getOrInvalid();
558       assert(threadEntry->elementsCapacity > id);
559     }
560     return threadEntry->elements[id];
561   }
562 };
563
564 #ifdef FOLLY_TLD_USE_FOLLY_TLS
565 template <class Tag>
566 FOLLY_TLS ThreadEntry StaticMeta<Tag>::threadEntry_ = {nullptr, 0,
567                                                        nullptr, nullptr};
568 #endif
569 template <class Tag> StaticMeta<Tag>* StaticMeta<Tag>::inst_ = nullptr;
570
571 }  // namespace threadlocal_detail
572 }  // namespace folly
573
574 #endif /* FOLLY_DETAIL_THREADLOCALDETAIL_H_ */