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