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