Make ThreadLocalPtr behave sanely around fork()
[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             // Writing another thread's ThreadEntry from here is fine;
249             // the only other potential reader is the owning thread --
250             // from onThreadExit (which grabs the lock, so is properly
251             // synchronized with us) or from get() -- but using get() on a
252             // ThreadLocalPtr object that's being destroyed is a bug, so
253             // undefined behavior is fair game.
254             e->elements[id].ptr = NULL;
255             e->elements[id].deleter = NULL;
256           }
257         }
258         meta.freeIds_.push_back(id);
259       }
260       // Delete elements outside the lock
261       FOR_EACH(it, elements) {
262         it->dispose(TLPDestructionMode::ALL_THREADS);
263       }
264     } catch (...) { // Just in case we get a lock error or something anyway...
265       LOG(WARNING) << "Destructor discarding an exception that was thrown.";
266     }
267   }
268
269   /**
270    * Reserve enough space in the threadEntry_.elements for the item
271    * @id to fit in.
272    */
273   static void reserve(int id) {
274     size_t prevSize = threadEntry_.elementsCapacity;
275     size_t newSize = static_cast<size_t>((id + 5) * 1.7);
276     auto& meta = instance();
277     ElementWrapper* ptr = nullptr;
278     // Rely on jemalloc to zero the memory if possible -- maybe it knows
279     // it's already zeroed and saves us some work.
280     if (!usingJEMalloc() ||
281         prevSize < jemallocMinInPlaceExpandable ||
282         (rallocm(
283           static_cast<void**>(static_cast<void*>(&threadEntry_.elements)),
284           NULL, newSize * sizeof(ElementWrapper), 0,
285           ALLOCM_NO_MOVE | ALLOCM_ZERO) != ALLOCM_SUCCESS)) {
286       // Sigh, must realloc, but we can't call realloc here, as elements is
287       // still linked in meta, so another thread might access invalid memory
288       // after realloc succeeds.  We'll copy by hand and update threadEntry_
289       // under the lock.
290       //
291       // Note that we're using calloc instead of malloc in order to zero
292       // the entire region.  rallocm (ALLOCM_ZERO) will only zero newly
293       // allocated memory, so if a previous allocation allocated more than
294       // we requested, it's our responsibility to guarantee that the tail
295       // is zeroed.  calloc() is simpler than malloc() followed by memset(),
296       // and potentially faster when dealing with a lot of memory, as
297       // it can get already-zeroed pages from the kernel.
298       if ((ptr = static_cast<ElementWrapper*>(
299              calloc(newSize, sizeof(ElementWrapper)))) != nullptr) {
300         memcpy(ptr, threadEntry_.elements, sizeof(ElementWrapper) * prevSize);
301       } else {
302         throw std::bad_alloc();
303       }
304     }
305
306     // Success, update the entry
307     {
308       boost::lock_guard<boost::mutex> g(meta.lock_);
309       if (prevSize == 0) {
310         meta.push_back(&threadEntry_);
311       }
312       if (ptr) {
313         using std::swap;
314         swap(ptr, threadEntry_.elements);
315       }
316       threadEntry_.elementsCapacity = newSize;
317     }
318
319     free(ptr);
320
321     if (prevSize == 0) {
322       pthread_setspecific(meta.pthreadKey_, &meta);
323     }
324   }
325
326   static ElementWrapper& get(int id) {
327     if (UNLIKELY(threadEntry_.elementsCapacity <= id)) {
328       reserve(id);
329     }
330     return threadEntry_.elements[id];
331   }
332 };
333
334 template <class Tag> __thread ThreadEntry StaticMeta<Tag>::threadEntry_ = {0};
335 template <class Tag> StaticMeta<Tag>* StaticMeta<Tag>::inst_ = nullptr;
336
337 }  // namespace threadlocal_detail
338 }  // namespace folly
339
340 #endif /* FOLLY_DETAIL_THREADLOCALDETAIL_H_ */
341