Revert "Fix folly::ThreadLocal to work in a shared library"
[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 // Held in a singleton to track our global instances.
167 // We have one of these per "Tag", by default one for the whole system
168 // (Tag=void).
169 //
170 // Creating and destroying ThreadLocalPtr objects, as well as thread exit
171 // for threads that use ThreadLocalPtr objects collide on a lock inside
172 // StaticMeta; you can specify multiple Tag types to break that lock.
173 template <class Tag>
174 struct StaticMeta {
175   // Represents an ID of a thread local object. Initially set to the maximum
176   // uint. This representation allows us to avoid a branch in accessing TLS data
177   // (because if you test capacity > id if id = maxint then the test will always
178   // fail). It allows us to keep a constexpr constructor and avoid SIOF.
179   class EntryID {
180    public:
181     std::atomic<uint32_t> value;
182
183     constexpr EntryID() : value(kEntryIDInvalid) {
184     }
185
186     EntryID(EntryID&& other) noexcept : value(other.value.load()) {
187       other.value = kEntryIDInvalid;
188     }
189
190     EntryID& operator=(EntryID&& other) {
191       assert(this != &other);
192       value = other.value.load();
193       other.value = kEntryIDInvalid;
194       return *this;
195     }
196
197     EntryID(const EntryID& other) = delete;
198     EntryID& operator=(const EntryID& other) = delete;
199
200     uint32_t getOrInvalid() {
201       // It's OK for this to be relaxed, even though we're effectively doing
202       // double checked locking in using this value. We only care about the
203       // uniqueness of IDs, getOrAllocate does not modify any other memory
204       // this thread will use.
205       return value.load(std::memory_order_relaxed);
206     }
207
208     uint32_t getOrAllocate() {
209       uint32_t id = getOrInvalid();
210       if (id != kEntryIDInvalid) {
211         return id;
212       }
213       // The lock inside allocate ensures that a single value is allocated
214       return instance().allocate(this);
215     }
216   };
217
218   static StaticMeta<Tag>& instance() {
219     // Leak it on exit, there's only one per process and we don't have to
220     // worry about synchronization with exiting threads.
221     static bool constructed = (inst_ = new StaticMeta<Tag>());
222     (void)constructed; // suppress unused warning
223     return *inst_;
224   }
225
226   uint32_t nextId_;
227   std::vector<uint32_t> freeIds_;
228   std::mutex lock_;
229   pthread_key_t pthreadKey_;
230   ThreadEntry head_;
231
232   void push_back(ThreadEntry* t) {
233     t->next = &head_;
234     t->prev = head_.prev;
235     head_.prev->next = t;
236     head_.prev = t;
237   }
238
239   void erase(ThreadEntry* t) {
240     t->next->prev = t->prev;
241     t->prev->next = t->next;
242     t->next = t->prev = t;
243   }
244
245 #ifdef FOLLY_TLD_USE_FOLLY_TLS
246   static FOLLY_TLS ThreadEntry threadEntry_;
247 #endif
248   static StaticMeta<Tag>* inst_;
249
250   StaticMeta() : nextId_(1) {
251     head_.next = head_.prev = &head_;
252     int ret = pthread_key_create(&pthreadKey_, &onThreadExit);
253     checkPosixError(ret, "pthread_key_create failed");
254
255 #if FOLLY_HAVE_PTHREAD_ATFORK
256     ret = pthread_atfork(/*prepare*/ &StaticMeta::preFork,
257                          /*parent*/ &StaticMeta::onForkParent,
258                          /*child*/ &StaticMeta::onForkChild);
259     checkPosixError(ret, "pthread_atfork failed");
260 #elif !__ANDROID__ && !defined(_MSC_VER)
261     // pthread_atfork is not part of the Android NDK at least as of n9d. If
262     // something is trying to call native fork() directly at all with Android's
263     // process management model, this is probably the least of the problems.
264     //
265     // But otherwise, this is a problem.
266     #warning pthread_atfork unavailable
267 #endif
268   }
269   ~StaticMeta() {
270     LOG(FATAL) << "StaticMeta lives forever!";
271   }
272
273   static ThreadEntry* getThreadEntry() {
274 #ifdef FOLLY_TLD_USE_FOLLY_TLS
275     return &threadEntry_;
276 #else
277     auto key = instance().pthreadKey_;
278     ThreadEntry* threadEntry =
279       static_cast<ThreadEntry*>(pthread_getspecific(key));
280     if (!threadEntry) {
281         threadEntry = new ThreadEntry();
282         int ret = pthread_setspecific(key, threadEntry);
283         checkPosixError(ret, "pthread_setspecific failed");
284     }
285     return threadEntry;
286 #endif
287   }
288
289   static void preFork(void) {
290     instance().lock_.lock();  // Make sure it's created
291   }
292
293   static void onForkParent(void) {
294     inst_->lock_.unlock();
295   }
296
297   static void onForkChild(void) {
298     // only the current thread survives
299     inst_->head_.next = inst_->head_.prev = &inst_->head_;
300     ThreadEntry* threadEntry = getThreadEntry();
301     // If this thread was in the list before the fork, add it back.
302     if (threadEntry->elementsCapacity != 0) {
303       inst_->push_back(threadEntry);
304     }
305     inst_->lock_.unlock();
306   }
307
308   static void onThreadExit(void* ptr) {
309     auto& meta = instance();
310 #ifdef FOLLY_TLD_USE_FOLLY_TLS
311     ThreadEntry* threadEntry = getThreadEntry();
312
313     DCHECK_EQ(ptr, &meta);
314     DCHECK_GT(threadEntry->elementsCapacity, 0);
315 #else
316     // pthread sets the thread-specific value corresponding
317     // to meta.pthreadKey_ to NULL before calling onThreadExit.
318     // We need to set it back to ptr to enable the correct behaviour
319     // of the subsequent calls of getThreadEntry
320     // (which may happen in user-provided custom deleters)
321     pthread_setspecific(meta.pthreadKey_, ptr);
322     ThreadEntry* threadEntry = static_cast<ThreadEntry*>(ptr);
323 #endif
324     {
325       std::lock_guard<std::mutex> g(meta.lock_);
326       meta.erase(threadEntry);
327       // No need to hold the lock any longer; the ThreadEntry is private to this
328       // thread now that it's been removed from meta.
329     }
330     // NOTE: User-provided deleter / object dtor itself may be using ThreadLocal
331     // with the same Tag, so dispose() calls below may (re)create some of the
332     // elements or even increase elementsCapacity, thus multiple cleanup rounds
333     // may be required.
334     for (bool shouldRun = true; shouldRun; ) {
335       shouldRun = false;
336       FOR_EACH_RANGE(i, 0, threadEntry->elementsCapacity) {
337         if (threadEntry->elements[i].dispose(TLPDestructionMode::THIS_THREAD)) {
338           shouldRun = true;
339         }
340       }
341     }
342     free(threadEntry->elements);
343     threadEntry->elements = nullptr;
344     pthread_setspecific(meta.pthreadKey_, nullptr);
345
346 #ifndef FOLLY_TLD_USE_FOLLY_TLS
347     // Allocated in getThreadEntry() when not using folly TLS; free it
348     delete threadEntry;
349 #endif
350   }
351
352   static uint32_t allocate(EntryID* ent) {
353     uint32_t id;
354     auto & meta = instance();
355     std::lock_guard<std::mutex> g(meta.lock_);
356
357     id = ent->value.load();
358     if (id != kEntryIDInvalid) {
359       return id;
360     }
361
362     if (!meta.freeIds_.empty()) {
363       id = meta.freeIds_.back();
364       meta.freeIds_.pop_back();
365     } else {
366       id = meta.nextId_++;
367     }
368
369     uint32_t old_id = ent->value.exchange(id);
370     DCHECK_EQ(old_id, kEntryIDInvalid);
371     return id;
372   }
373
374   static void destroy(EntryID* ent) {
375     try {
376       auto & meta = instance();
377       // Elements in other threads that use this id.
378       std::vector<ElementWrapper> elements;
379       {
380         std::lock_guard<std::mutex> g(meta.lock_);
381         uint32_t id = ent->value.exchange(kEntryIDInvalid);
382         if (id == kEntryIDInvalid) {
383           return;
384         }
385
386         for (ThreadEntry* e = meta.head_.next; e != &meta.head_; e = e->next) {
387           if (id < e->elementsCapacity && e->elements[id].ptr) {
388             elements.push_back(e->elements[id]);
389
390             /*
391              * Writing another thread's ThreadEntry from here is fine;
392              * the only other potential reader is the owning thread --
393              * from onThreadExit (which grabs the lock, so is properly
394              * synchronized with us) or from get(), which also grabs
395              * the lock if it needs to resize the elements vector.
396              *
397              * We can't conflict with reads for a get(id), because
398              * it's illegal to call get on a thread local that's
399              * destructing.
400              */
401             e->elements[id].ptr = nullptr;
402             e->elements[id].deleter = nullptr;
403             e->elements[id].ownsDeleter = false;
404           }
405         }
406         meta.freeIds_.push_back(id);
407       }
408       // Delete elements outside the lock
409       FOR_EACH(it, elements) {
410         it->dispose(TLPDestructionMode::ALL_THREADS);
411       }
412     } catch (...) { // Just in case we get a lock error or something anyway...
413       LOG(WARNING) << "Destructor discarding an exception that was thrown.";
414     }
415   }
416
417   /**
418    * Reserve enough space in the ThreadEntry::elements for the item
419    * @id to fit in.
420    */
421   static void reserve(EntryID* id) {
422     auto& meta = instance();
423     ThreadEntry* threadEntry = getThreadEntry();
424     size_t prevCapacity = threadEntry->elementsCapacity;
425
426     uint32_t idval = id->getOrAllocate();
427     if (prevCapacity > idval) {
428       return;
429     }
430     // Growth factor < 2, see folly/docs/FBVector.md; + 5 to prevent
431     // very slow start.
432     size_t newCapacity = static_cast<size_t>((idval + 5) * 1.7);
433     assert(newCapacity > prevCapacity);
434     ElementWrapper* reallocated = nullptr;
435
436     // Need to grow. Note that we can't call realloc, as elements is
437     // still linked in meta, so another thread might access invalid memory
438     // after realloc succeeds. We'll copy by hand and update our ThreadEntry
439     // under the lock.
440     if (usingJEMalloc()) {
441       bool success = false;
442       size_t newByteSize = nallocx(newCapacity * sizeof(ElementWrapper), 0);
443
444       // Try to grow in place.
445       //
446       // Note that xallocx(MALLOCX_ZERO) will only zero newly allocated memory,
447       // even if a previous allocation allocated more than we requested.
448       // This is fine; we always use MALLOCX_ZERO with jemalloc and we
449       // always expand our allocation to the real size.
450       if (prevCapacity * sizeof(ElementWrapper) >=
451           jemallocMinInPlaceExpandable) {
452         success = (xallocx(threadEntry->elements, newByteSize, 0, MALLOCX_ZERO)
453                    == newByteSize);
454       }
455
456       // In-place growth failed.
457       if (!success) {
458         success = ((reallocated = static_cast<ElementWrapper*>(
459                     mallocx(newByteSize, MALLOCX_ZERO))) != nullptr);
460       }
461
462       if (success) {
463         // Expand to real size
464         assert(newByteSize / sizeof(ElementWrapper) >= newCapacity);
465         newCapacity = newByteSize / sizeof(ElementWrapper);
466       } else {
467         throw std::bad_alloc();
468       }
469     } else {  // no jemalloc
470       // calloc() is simpler than malloc() followed by memset(), and
471       // potentially faster when dealing with a lot of memory, as it can get
472       // already-zeroed pages from the kernel.
473       reallocated = static_cast<ElementWrapper*>(
474           calloc(newCapacity, sizeof(ElementWrapper)));
475       if (!reallocated) {
476         throw std::bad_alloc();
477       }
478     }
479
480     // Success, update the entry
481     {
482       std::lock_guard<std::mutex> g(meta.lock_);
483
484       if (prevCapacity == 0) {
485         meta.push_back(threadEntry);
486       }
487
488       if (reallocated) {
489        /*
490         * Note: we need to hold the meta lock when copying data out of
491         * the old vector, because some other thread might be
492         * destructing a ThreadLocal and writing to the elements vector
493         * of this thread.
494         */
495         memcpy(reallocated, threadEntry->elements,
496                sizeof(ElementWrapper) * prevCapacity);
497         using std::swap;
498         swap(reallocated, threadEntry->elements);
499       }
500       threadEntry->elementsCapacity = newCapacity;
501     }
502
503     free(reallocated);
504
505 #ifdef FOLLY_TLD_USE_FOLLY_TLS
506     if (prevCapacity == 0) {
507       pthread_setspecific(meta.pthreadKey_, &meta);
508     }
509 #endif
510   }
511
512   static ElementWrapper& get(EntryID* ent) {
513     ThreadEntry* threadEntry = getThreadEntry();
514     uint32_t id = ent->getOrInvalid();
515     // if id is invalid, it is equal to uint32_t's max value.
516     // x <= max value is always true
517     if (UNLIKELY(threadEntry->elementsCapacity <= id)) {
518       reserve(ent);
519       id = ent->getOrInvalid();
520       assert(threadEntry->elementsCapacity > id);
521     }
522     return threadEntry->elements[id];
523   }
524 };
525
526 #ifdef FOLLY_TLD_USE_FOLLY_TLS
527 template <class Tag>
528 FOLLY_TLS ThreadEntry StaticMeta<Tag>::threadEntry_ = {nullptr, 0,
529                                                        nullptr, nullptr};
530 #endif
531 template <class Tag> StaticMeta<Tag>* StaticMeta<Tag>::inst_ = nullptr;
532
533 }  // namespace threadlocal_detail
534 }  // namespace folly
535
536 #endif /* FOLLY_DETAIL_THREADLOCALDETAIL_H_ */