Fix a ThreadLocal bug: hold the meta lock when resizing the element vector
[folly.git] / folly / detail / ThreadLocalDetail.h
1 /*
2  * Copyright 2013 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 #include <list>
23 #include <string>
24 #include <vector>
25
26 #include <boost/thread/locks.hpp>
27 #include <boost/thread/mutex.hpp>
28 #include <boost/thread/locks.hpp>
29
30 #include <glog/logging.h>
31
32 #include "folly/Exception.h"
33 #include "folly/Foreach.h"
34 #include "folly/Malloc.h"
35
36 namespace folly {
37 namespace threadlocal_detail {
38
39 /**
40  * Base class for deleters.
41  */
42 class DeleterBase {
43  public:
44   virtual ~DeleterBase() { }
45   virtual void dispose(void* ptr, TLPDestructionMode mode) const = 0;
46 };
47
48 /**
49  * Simple deleter class that calls delete on the passed-in pointer.
50  */
51 template <class Ptr>
52 class SimpleDeleter : public DeleterBase {
53  public:
54   virtual void dispose(void* ptr, TLPDestructionMode mode) const {
55     delete static_cast<Ptr>(ptr);
56   }
57 };
58
59 /**
60  * Custom deleter that calls a given callable.
61  */
62 template <class Ptr, class Deleter>
63 class CustomDeleter : public DeleterBase {
64  public:
65   explicit CustomDeleter(Deleter d) : deleter_(d) { }
66   virtual void dispose(void* ptr, TLPDestructionMode mode) const {
67     deleter_(static_cast<Ptr>(ptr), mode);
68   }
69  private:
70   Deleter deleter_;
71 };
72
73
74 /**
75  * POD wrapper around an element (a void*) and an associated deleter.
76  * This must be POD, as we memset() it to 0 and memcpy() it around.
77  */
78 struct ElementWrapper {
79   void dispose(TLPDestructionMode mode) {
80     if (ptr != NULL) {
81       DCHECK(deleter != NULL);
82       deleter->dispose(ptr, mode);
83       if (ownsDeleter) {
84         delete deleter;
85       }
86       ptr = NULL;
87       deleter = NULL;
88       ownsDeleter = false;
89     }
90   }
91
92   template <class Ptr>
93   void set(Ptr p) {
94     DCHECK(ptr == NULL);
95     DCHECK(deleter == NULL);
96
97     if (p) {
98       // We leak a single object here but that is ok.  If we used an
99       // object directly, there is a chance that the destructor will be
100       // called on that static object before any of the ElementWrappers
101       // are disposed and that isn't so nice.
102       static auto d = new SimpleDeleter<Ptr>();
103       ptr = p;
104       deleter = d;
105       ownsDeleter = false;
106     }
107   }
108
109   template <class Ptr, class Deleter>
110   void set(Ptr p, Deleter d) {
111     DCHECK(ptr == NULL);
112     DCHECK(deleter == NULL);
113     if (p) {
114       ptr = p;
115       deleter = new CustomDeleter<Ptr,Deleter>(d);
116       ownsDeleter = true;
117     }
118   }
119
120   void* ptr;
121   DeleterBase* deleter;
122   bool ownsDeleter;
123 };
124
125 /**
126  * Per-thread entry.  Each thread using a StaticMeta object has one.
127  * This is written from the owning thread only (under the lock), read
128  * from the owning thread (no lock necessary), and read from other threads
129  * (under the lock).
130  */
131 struct ThreadEntry {
132   ElementWrapper* elements;
133   size_t elementsCapacity;
134   ThreadEntry* next;
135   ThreadEntry* prev;
136 };
137
138 // Held in a singleton to track our global instances.
139 // We have one of these per "Tag", by default one for the whole system
140 // (Tag=void).
141 //
142 // Creating and destroying ThreadLocalPtr objects, as well as thread exit
143 // for threads that use ThreadLocalPtr objects collide on a lock inside
144 // StaticMeta; you can specify multiple Tag types to break that lock.
145 template <class Tag>
146 struct StaticMeta {
147   static StaticMeta<Tag>& instance() {
148     // Leak it on exit, there's only one per process and we don't have to
149     // worry about synchronization with exiting threads.
150     static bool constructed = (inst_ = new StaticMeta<Tag>());
151     (void)constructed; // suppress unused warning
152     return *inst_;
153   }
154
155   int nextId_;
156   std::vector<int> freeIds_;
157   boost::mutex lock_;
158   pthread_key_t pthreadKey_;
159   ThreadEntry head_;
160
161   void push_back(ThreadEntry* t) {
162     t->next = &head_;
163     t->prev = head_.prev;
164     head_.prev->next = t;
165     head_.prev = t;
166   }
167
168   void erase(ThreadEntry* t) {
169     t->next->prev = t->prev;
170     t->prev->next = t->next;
171     t->next = t->prev = t;
172   }
173
174   static __thread ThreadEntry threadEntry_;
175   static StaticMeta<Tag>* inst_;
176
177   StaticMeta() : nextId_(1) {
178     head_.next = head_.prev = &head_;
179     int ret = pthread_key_create(&pthreadKey_, &onThreadExit);
180     checkPosixError(ret, "pthread_key_create failed");
181
182     ret = pthread_atfork(/*prepare*/ &StaticMeta::preFork,
183                          /*parent*/ &StaticMeta::onForkParent,
184                          /*child*/ &StaticMeta::onForkChild);
185     checkPosixError(ret, "pthread_atfork failed");
186   }
187   ~StaticMeta() {
188     LOG(FATAL) << "StaticMeta lives forever!";
189   }
190
191   static void preFork(void) {
192     instance().lock_.lock();  // Make sure it's created
193   }
194
195   static void onForkParent(void) {
196     inst_->lock_.unlock();
197   }
198
199   static void onForkChild(void) {
200     inst_->head_.next = inst_->head_.prev = &inst_->head_;
201     inst_->push_back(&threadEntry_);  // only the current thread survives
202     inst_->lock_.unlock();
203   }
204
205   static void onThreadExit(void* ptr) {
206     auto & meta = instance();
207     DCHECK_EQ(ptr, &meta);
208     // We wouldn't call pthread_setspecific unless we actually called get()
209     DCHECK_NE(threadEntry_.elementsCapacity, 0);
210     {
211       boost::lock_guard<boost::mutex> g(meta.lock_);
212       meta.erase(&threadEntry_);
213       // No need to hold the lock any longer; threadEntry_ is private to this
214       // thread now that it's been removed from meta.
215     }
216     FOR_EACH_RANGE(i, 0, threadEntry_.elementsCapacity) {
217       threadEntry_.elements[i].dispose(TLPDestructionMode::THIS_THREAD);
218     }
219     free(threadEntry_.elements);
220     threadEntry_.elements = NULL;
221     pthread_setspecific(meta.pthreadKey_, NULL);
222   }
223
224   static int create() {
225     int id;
226     auto & meta = instance();
227     boost::lock_guard<boost::mutex> g(meta.lock_);
228     if (!meta.freeIds_.empty()) {
229       id = meta.freeIds_.back();
230       meta.freeIds_.pop_back();
231     } else {
232       id = meta.nextId_++;
233     }
234     return id;
235   }
236
237   static void destroy(int id) {
238     try {
239       auto & meta = instance();
240       // Elements in other threads that use this id.
241       std::vector<ElementWrapper> elements;
242       {
243         boost::lock_guard<boost::mutex> g(meta.lock_);
244         for (ThreadEntry* e = meta.head_.next; e != &meta.head_; e = e->next) {
245           if (id < e->elementsCapacity && e->elements[id].ptr) {
246             elements.push_back(e->elements[id]);
247
248             /*
249              * Writing another thread's ThreadEntry from here is fine;
250              * the only other potential reader is the owning thread --
251              * from onThreadExit (which grabs the lock, so is properly
252              * synchronized with us) or from get(), which also grabs
253              * the lock if it needs to resize the elements vector.
254              *
255              * We can't conflict with reads for a get(id), because
256              * it's illegal to call get on a thread local that's
257              * destructing.
258              */
259             e->elements[id].ptr = nullptr;
260             e->elements[id].deleter = nullptr;
261             e->elements[id].ownsDeleter = false;
262           }
263         }
264         meta.freeIds_.push_back(id);
265       }
266       // Delete elements outside the lock
267       FOR_EACH(it, elements) {
268         it->dispose(TLPDestructionMode::ALL_THREADS);
269       }
270     } catch (...) { // Just in case we get a lock error or something anyway...
271       LOG(WARNING) << "Destructor discarding an exception that was thrown.";
272     }
273   }
274
275   /**
276    * Reserve enough space in the threadEntry_.elements for the item
277    * @id to fit in.
278    */
279   static void reserve(int id) {
280     size_t prevSize = threadEntry_.elementsCapacity;
281     size_t newSize = static_cast<size_t>((id + 5) * 1.7);
282     auto& meta = instance();
283     ElementWrapper* ptr = nullptr;
284
285     // Rely on jemalloc to zero the memory if possible -- maybe it knows
286     // it's already zeroed and saves us some work.
287     if (!usingJEMalloc() ||
288         prevSize < jemallocMinInPlaceExpandable ||
289         (rallocm(
290           static_cast<void**>(static_cast<void*>(&threadEntry_.elements)),
291           nullptr, newSize * sizeof(ElementWrapper), 0,
292           ALLOCM_NO_MOVE | ALLOCM_ZERO) != ALLOCM_SUCCESS)) {
293       // Sigh, must realloc, but we can't call realloc here, as elements is
294       // still linked in meta, so another thread might access invalid memory
295       // after realloc succeeds.  We'll copy by hand and update threadEntry_
296       // under the lock.
297       //
298       // Note that we're using calloc instead of malloc in order to zero
299       // the entire region.  rallocm (ALLOCM_ZERO) will only zero newly
300       // allocated memory, so if a previous allocation allocated more than
301       // we requested, it's our responsibility to guarantee that the tail
302       // is zeroed.  calloc() is simpler than malloc() followed by memset(),
303       // and potentially faster when dealing with a lot of memory, as
304       // it can get already-zeroed pages from the kernel.
305       ptr = static_cast<ElementWrapper*>(
306         calloc(newSize, sizeof(ElementWrapper))
307       );
308       if (!ptr) throw std::bad_alloc();
309     }
310
311     // Success, update the entry
312     {
313       boost::lock_guard<boost::mutex> g(meta.lock_);
314
315       if (prevSize == 0) {
316         meta.push_back(&threadEntry_);
317       }
318
319       if (ptr) {
320        /*
321         * Note: we need to hold the meta lock when copying data out of
322         * the old vector, because some other thread might be
323         * destructing a ThreadLocal and writing to the elements vector
324         * of this thread.
325         */
326         memcpy(ptr, threadEntry_.elements, sizeof(ElementWrapper) * prevSize);
327         using std::swap;
328         swap(ptr, threadEntry_.elements);
329         threadEntry_.elementsCapacity = newSize;
330       }
331     }
332
333     free(ptr);
334
335     if (prevSize == 0) {
336       pthread_setspecific(meta.pthreadKey_, &meta);
337     }
338   }
339
340   static ElementWrapper& get(int id) {
341     if (UNLIKELY(threadEntry_.elementsCapacity <= id)) {
342       reserve(id);
343     }
344     return threadEntry_.elements[id];
345   }
346 };
347
348 template <class Tag> __thread ThreadEntry StaticMeta<Tag>::threadEntry_ = {0};
349 template <class Tag> StaticMeta<Tag>* StaticMeta<Tag>::inst_ = nullptr;
350
351 }  // namespace threadlocal_detail
352 }  // namespace folly
353
354 #endif /* FOLLY_DETAIL_THREADLOCALDETAIL_H_ */
355