move StaticMeta::onThreadExit into libfolly_thread_local.so
[folly.git] / folly / detail / ThreadLocalDetail.cpp
1 /*
2  * Copyright 2016 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 #include <folly/ThreadLocal.h>
17
18 namespace folly { namespace threadlocal_detail {
19
20 StaticMetaBase::StaticMetaBase(ThreadEntry* (*threadEntry)())
21     : nextId_(1), threadEntry_(threadEntry) {
22   head_.next = head_.prev = &head_;
23   int ret = pthread_key_create(&pthreadKey_, &onThreadExit);
24   checkPosixError(ret, "pthread_key_create failed");
25   PthreadKeyUnregister::registerKey(pthreadKey_);
26 }
27
28 void StaticMetaBase::onThreadExit(void* ptr) {
29   std::unique_ptr<ThreadEntry> threadEntry(static_cast<ThreadEntry*>(ptr));
30   DCHECK_GT(threadEntry->elementsCapacity, 0);
31   auto& meta = *threadEntry->meta;
32   {
33     std::lock_guard<std::mutex> g(meta.lock_);
34     meta.erase(threadEntry.get());
35     // No need to hold the lock any longer; the ThreadEntry is private to this
36     // thread now that it's been removed from meta.
37   }
38   // NOTE: User-provided deleter / object dtor itself may be using ThreadLocal
39   // with the same Tag, so dispose() calls below may (re)create some of the
40   // elements or even increase elementsCapacity, thus multiple cleanup rounds
41   // may be required.
42   for (bool shouldRun = true; shouldRun;) {
43     shouldRun = false;
44     FOR_EACH_RANGE (i, 0, threadEntry->elementsCapacity) {
45       if (threadEntry->elements[i].dispose(TLPDestructionMode::THIS_THREAD)) {
46         shouldRun = true;
47       }
48     }
49   }
50   free(threadEntry->elements);
51   threadEntry->elements = nullptr;
52   threadEntry->meta = nullptr;
53 }
54
55 uint32_t StaticMetaBase::allocate(EntryID* ent) {
56   uint32_t id;
57   auto& meta = *this;
58   std::lock_guard<std::mutex> g(meta.lock_);
59
60   id = ent->value.load();
61   if (id != kEntryIDInvalid) {
62     return id;
63   }
64
65   if (!meta.freeIds_.empty()) {
66     id = meta.freeIds_.back();
67     meta.freeIds_.pop_back();
68   } else {
69     id = meta.nextId_++;
70   }
71
72   uint32_t old_id = ent->value.exchange(id);
73   DCHECK_EQ(old_id, kEntryIDInvalid);
74   return id;
75 }
76
77 void StaticMetaBase::destroy(EntryID* ent) {
78   try {
79     auto& meta = *this;
80     // Elements in other threads that use this id.
81     std::vector<ElementWrapper> elements;
82     {
83       std::lock_guard<std::mutex> g(meta.lock_);
84       uint32_t id = ent->value.exchange(kEntryIDInvalid);
85       if (id == kEntryIDInvalid) {
86         return;
87       }
88
89       for (ThreadEntry* e = meta.head_.next; e != &meta.head_; e = e->next) {
90         if (id < e->elementsCapacity && e->elements[id].ptr) {
91           elements.push_back(e->elements[id]);
92
93           /*
94            * Writing another thread's ThreadEntry from here is fine;
95            * the only other potential reader is the owning thread --
96            * from onThreadExit (which grabs the lock, so is properly
97            * synchronized with us) or from get(), which also grabs
98            * the lock if it needs to resize the elements vector.
99            *
100            * We can't conflict with reads for a get(id), because
101            * it's illegal to call get on a thread local that's
102            * destructing.
103            */
104           e->elements[id].ptr = nullptr;
105           e->elements[id].deleter1 = nullptr;
106           e->elements[id].ownsDeleter = false;
107         }
108       }
109       meta.freeIds_.push_back(id);
110     }
111     // Delete elements outside the lock
112     for (ElementWrapper& elem : elements) {
113       elem.dispose(TLPDestructionMode::ALL_THREADS);
114     }
115   } catch (...) { // Just in case we get a lock error or something anyway...
116     LOG(WARNING) << "Destructor discarding an exception that was thrown.";
117   }
118 }
119
120 /**
121  * Reserve enough space in the ThreadEntry::elements for the item
122  * @id to fit in.
123  */
124 void StaticMetaBase::reserve(EntryID* id) {
125   auto& meta = *this;
126   ThreadEntry* threadEntry = (*threadEntry_)();
127   size_t prevCapacity = threadEntry->elementsCapacity;
128
129   uint32_t idval = id->getOrAllocate(meta);
130   if (prevCapacity > idval) {
131     return;
132   }
133   // Growth factor < 2, see folly/docs/FBVector.md; + 5 to prevent
134   // very slow start.
135   size_t newCapacity = static_cast<size_t>((idval + 5) * 1.7);
136   assert(newCapacity > prevCapacity);
137   ElementWrapper* reallocated = nullptr;
138
139   // Need to grow. Note that we can't call realloc, as elements is
140   // still linked in meta, so another thread might access invalid memory
141   // after realloc succeeds. We'll copy by hand and update our ThreadEntry
142   // under the lock.
143   if (usingJEMalloc()) {
144     bool success = false;
145     size_t newByteSize = nallocx(newCapacity * sizeof(ElementWrapper), 0);
146
147     // Try to grow in place.
148     //
149     // Note that xallocx(MALLOCX_ZERO) will only zero newly allocated memory,
150     // even if a previous allocation allocated more than we requested.
151     // This is fine; we always use MALLOCX_ZERO with jemalloc and we
152     // always expand our allocation to the real size.
153     if (prevCapacity * sizeof(ElementWrapper) >= jemallocMinInPlaceExpandable) {
154       success =
155           (xallocx(threadEntry->elements, newByteSize, 0, MALLOCX_ZERO) ==
156            newByteSize);
157     }
158
159     // In-place growth failed.
160     if (!success) {
161       success =
162           ((reallocated = static_cast<ElementWrapper*>(
163                 mallocx(newByteSize, MALLOCX_ZERO))) != nullptr);
164     }
165
166     if (success) {
167       // Expand to real size
168       assert(newByteSize / sizeof(ElementWrapper) >= newCapacity);
169       newCapacity = newByteSize / sizeof(ElementWrapper);
170     } else {
171       throw std::bad_alloc();
172     }
173   } else { // no jemalloc
174     // calloc() is simpler than malloc() followed by memset(), and
175     // potentially faster when dealing with a lot of memory, as it can get
176     // already-zeroed pages from the kernel.
177     reallocated = static_cast<ElementWrapper*>(
178         calloc(newCapacity, sizeof(ElementWrapper)));
179     if (!reallocated) {
180       throw std::bad_alloc();
181     }
182   }
183
184   // Success, update the entry
185   {
186     std::lock_guard<std::mutex> g(meta.lock_);
187
188     if (prevCapacity == 0) {
189       meta.push_back(threadEntry);
190     }
191
192     if (reallocated) {
193       /*
194        * Note: we need to hold the meta lock when copying data out of
195        * the old vector, because some other thread might be
196        * destructing a ThreadLocal and writing to the elements vector
197        * of this thread.
198        */
199       if (prevCapacity != 0) {
200         memcpy(
201             reallocated,
202             threadEntry->elements,
203             sizeof(*reallocated) * prevCapacity);
204       }
205       std::swap(reallocated, threadEntry->elements);
206     }
207     threadEntry->elementsCapacity = newCapacity;
208   }
209
210   free(reallocated);
211 }
212
213 ElementWrapper& StaticMetaBase::get(EntryID* ent) {
214   ThreadEntry* threadEntry = (*threadEntry_)();
215   uint32_t id = ent->getOrInvalid();
216   // if id is invalid, it is equal to uint32_t's max value.
217   // x <= max value is always true
218   if (UNLIKELY(threadEntry->elementsCapacity <= id)) {
219     reserve(ent);
220     id = ent->getOrInvalid();
221     assert(threadEntry->elementsCapacity > id);
222   }
223   return threadEntry->elements[id];
224 }
225
226 MAX_STATIC_CONSTRUCTOR_PRIORITY
227 PthreadKeyUnregister PthreadKeyUnregister::instance_;
228 }}