• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/threading/thread_local_storage.h"
6 
7 #include "base/atomicops.h"
8 #include "base/logging.h"
9 #include "base/synchronization/lock.h"
10 #include "build/build_config.h"
11 
12 using base::internal::PlatformThreadLocalStorage;
13 
14 // Chrome Thread Local Storage (TLS)
15 //
16 // This TLS system allows Chrome to use a single OS level TLS slot process-wide,
17 // and allows us to control the slot limits instead of being at the mercy of the
18 // platform. To do this, Chrome TLS replicates an array commonly found in the OS
19 // thread metadata.
20 //
21 // Overview:
22 //
23 // OS TLS Slots       Per-Thread                 Per-Process Global
24 //     ...
25 //     []             Chrome TLS Array           Chrome TLS Metadata
26 //     [] ----------> [][][][][ ][][][][]        [][][][][ ][][][][]
27 //     []                      |                          |
28 //     ...                     V                          V
29 //                      Metadata Version           Slot Information
30 //                         Your Data!
31 //
32 // Using a single OS TLS slot, Chrome TLS allocates an array on demand for the
33 // lifetime of each thread that requests Chrome TLS data. Each per-thread TLS
34 // array matches the length of the per-process global metadata array.
35 //
36 // A per-process global TLS metadata array tracks information about each item in
37 // the per-thread array:
38 //   * Status: Tracks if the slot is allocated or free to assign.
39 //   * Destructor: An optional destructor to call on thread destruction for that
40 //                 specific slot.
41 //   * Version: Tracks the current version of the TLS slot. Each TLS slot
42 //              allocation is associated with a unique version number.
43 //
44 //              Most OS TLS APIs guarantee that a newly allocated TLS slot is
45 //              initialized to 0 for all threads. The Chrome TLS system provides
46 //              this guarantee by tracking the version for each TLS slot here
47 //              on each per-thread Chrome TLS array entry. Threads that access
48 //              a slot with a mismatched version will receive 0 as their value.
49 //              The metadata version is incremented when the client frees a
50 //              slot. The per-thread metadata version is updated when a client
51 //              writes to the slot. This scheme allows for constant time
52 //              invalidation and avoids the need to iterate through each Chrome
53 //              TLS array to mark the slot as zero.
54 //
55 // Just like an OS TLS API, clients of the Chrome TLS are responsible for
56 // managing any necessary lifetime of the data in their slots. The only
57 // convenience provided is automatic destruction when a thread ends. If a client
58 // frees a slot, that client is responsible for destroying the data in the slot.
59 
60 namespace {
61 // In order to make TLS destructors work, we need to keep around a function
62 // pointer to the destructor for each slot. We keep this array of pointers in a
63 // global (static) array.
64 // We use the single OS-level TLS slot (giving us one pointer per thread) to
65 // hold a pointer to a per-thread array (table) of slots that we allocate to
66 // Chromium consumers.
67 
68 // g_native_tls_key is the one native TLS that we use. It stores our table.
69 base::subtle::Atomic32 g_native_tls_key =
70     PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES;
71 
72 // The OS TLS slot has three states:
73 //   * kUninitialized: Any call to Slot::Get()/Set() will create the base
74 //     per-thread TLS state. On POSIX, kUninitialized must be 0.
75 //   * [Memory Address]: Raw pointer to the base per-thread TLS state.
76 //   * kDestroyed: The base per-thread TLS state has been freed.
77 //
78 // Final States:
79 //   * Windows: kDestroyed. Windows does not iterate through the OS TLS to clean
80 //     up the values.
81 //   * POSIX: kUninitialized. POSIX iterates through TLS until all slots contain
82 //     nullptr.
83 //
84 // More details on this design:
85 //   We need some type of thread-local state to indicate that the TLS system has
86 //   been destroyed. To do so, we leverage the multi-pass nature of destruction
87 //   of pthread_key.
88 //
89 //    a) After destruction of TLS system, we set the pthread_key to a sentinel
90 //       kDestroyed.
91 //    b) All calls to Slot::Get() DCHECK that the state is not kDestroyed, and
92 //       any system which might potentially invoke Slot::Get() after destruction
93 //       of TLS must check ThreadLocalStorage::ThreadIsBeingDestroyed().
94 //    c) After a full pass of the pthread_keys, on the next invocation of
95 //       ConstructTlsVector(), we'll then set the key to nullptr.
96 //    d) At this stage, the TLS system is back in its uninitialized state.
97 //    e) If in the second pass of destruction of pthread_keys something were to
98 //       re-initialize TLS [this should never happen! Since the only code which
99 //       uses Chrome TLS is Chrome controlled, we should really be striving for
100 //       single-pass destruction], then TLS will be re-initialized and then go
101 //       through the 2-pass destruction system again. Everything should just
102 //       work (TM).
103 
104 // The consumers of kUninitialized and kDestroyed expect void*, since that's
105 // what the API exposes on both POSIX and Windows.
106 void* const kUninitialized = nullptr;
107 
108 // A sentinel value to indicate that the TLS system has been destroyed.
109 void* const kDestroyed = reinterpret_cast<void*>(1);
110 
111 // The maximum number of slots in our thread local storage stack.
112 constexpr int kThreadLocalStorageSize = 256;
113 
114 enum TlsStatus {
115   FREE,
116   IN_USE,
117 };
118 
119 struct TlsMetadata {
120   TlsStatus status;
121   base::ThreadLocalStorage::TLSDestructorFunc destructor;
122   uint32_t version;
123 };
124 
125 struct TlsVectorEntry {
126   void* data;
127   uint32_t version;
128 };
129 
130 // This lock isn't needed until after we've constructed the per-thread TLS
131 // vector, so it's safe to use.
GetTLSMetadataLock()132 base::Lock* GetTLSMetadataLock() {
133   static auto* lock = new base::Lock();
134   return lock;
135 }
136 TlsMetadata g_tls_metadata[kThreadLocalStorageSize];
137 size_t g_last_assigned_slot = 0;
138 
139 // The maximum number of times to try to clear slots by calling destructors.
140 // Use pthread naming convention for clarity.
141 constexpr int kMaxDestructorIterations = kThreadLocalStorageSize;
142 
143 // This function is called to initialize our entire Chromium TLS system.
144 // It may be called very early, and we need to complete most all of the setup
145 // (initialization) before calling *any* memory allocator functions, which may
146 // recursively depend on this initialization.
147 // As a result, we use Atomics, and avoid anything (like a singleton) that might
148 // require memory allocations.
ConstructTlsVector()149 TlsVectorEntry* ConstructTlsVector() {
150   PlatformThreadLocalStorage::TLSKey key =
151       base::subtle::NoBarrier_Load(&g_native_tls_key);
152   if (key == PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES) {
153     CHECK(PlatformThreadLocalStorage::AllocTLS(&key));
154 
155     // The TLS_KEY_OUT_OF_INDEXES is used to find out whether the key is set or
156     // not in NoBarrier_CompareAndSwap, but Posix doesn't have invalid key, we
157     // define an almost impossible value be it.
158     // If we really get TLS_KEY_OUT_OF_INDEXES as value of key, just alloc
159     // another TLS slot.
160     if (key == PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES) {
161       PlatformThreadLocalStorage::TLSKey tmp = key;
162       CHECK(PlatformThreadLocalStorage::AllocTLS(&key) &&
163             key != PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES);
164       PlatformThreadLocalStorage::FreeTLS(tmp);
165     }
166     // Atomically test-and-set the tls_key. If the key is
167     // TLS_KEY_OUT_OF_INDEXES, go ahead and set it. Otherwise, do nothing, as
168     // another thread already did our dirty work.
169     if (PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES !=
170         static_cast<PlatformThreadLocalStorage::TLSKey>(
171             base::subtle::NoBarrier_CompareAndSwap(
172                 &g_native_tls_key,
173                 PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES, key))) {
174       // We've been shortcut. Another thread replaced g_native_tls_key first so
175       // we need to destroy our index and use the one the other thread got
176       // first.
177       PlatformThreadLocalStorage::FreeTLS(key);
178       key = base::subtle::NoBarrier_Load(&g_native_tls_key);
179     }
180   }
181   CHECK_EQ(PlatformThreadLocalStorage::GetTLSValue(key), kUninitialized);
182 
183   // Some allocators, such as TCMalloc, make use of thread local storage. As a
184   // result, any attempt to call new (or malloc) will lazily cause such a system
185   // to initialize, which will include registering for a TLS key. If we are not
186   // careful here, then that request to create a key will call new back, and
187   // we'll have an infinite loop. We avoid that as follows: Use a stack
188   // allocated vector, so that we don't have dependence on our allocator until
189   // our service is in place. (i.e., don't even call new until after we're
190   // setup)
191   TlsVectorEntry stack_allocated_tls_data[kThreadLocalStorageSize];
192   memset(stack_allocated_tls_data, 0, sizeof(stack_allocated_tls_data));
193   // Ensure that any rentrant calls change the temp version.
194   PlatformThreadLocalStorage::SetTLSValue(key, stack_allocated_tls_data);
195 
196   // Allocate an array to store our data.
197   TlsVectorEntry* tls_data = new TlsVectorEntry[kThreadLocalStorageSize];
198   memcpy(tls_data, stack_allocated_tls_data, sizeof(stack_allocated_tls_data));
199   PlatformThreadLocalStorage::SetTLSValue(key, tls_data);
200   return tls_data;
201 }
202 
OnThreadExitInternal(TlsVectorEntry * tls_data)203 void OnThreadExitInternal(TlsVectorEntry* tls_data) {
204   // This branch is for POSIX, where this function is called twice. The first
205   // pass calls dtors and sets state to kDestroyed. The second pass sets
206   // kDestroyed to kUninitialized.
207   if (tls_data == kDestroyed) {
208     PlatformThreadLocalStorage::TLSKey key =
209         base::subtle::NoBarrier_Load(&g_native_tls_key);
210     PlatformThreadLocalStorage::SetTLSValue(key, kUninitialized);
211     return;
212   }
213 
214   DCHECK(tls_data);
215   // Some allocators, such as TCMalloc, use TLS. As a result, when a thread
216   // terminates, one of the destructor calls we make may be to shut down an
217   // allocator. We have to be careful that after we've shutdown all of the known
218   // destructors (perchance including an allocator), that we don't call the
219   // allocator and cause it to resurrect itself (with no possibly destructor
220   // call to follow). We handle this problem as follows: Switch to using a stack
221   // allocated vector, so that we don't have dependence on our allocator after
222   // we have called all g_tls_metadata destructors. (i.e., don't even call
223   // delete[] after we're done with destructors.)
224   TlsVectorEntry stack_allocated_tls_data[kThreadLocalStorageSize];
225   memcpy(stack_allocated_tls_data, tls_data, sizeof(stack_allocated_tls_data));
226   // Ensure that any re-entrant calls change the temp version.
227   PlatformThreadLocalStorage::TLSKey key =
228       base::subtle::NoBarrier_Load(&g_native_tls_key);
229   PlatformThreadLocalStorage::SetTLSValue(key, stack_allocated_tls_data);
230   delete[] tls_data;  // Our last dependence on an allocator.
231 
232   // Snapshot the TLS Metadata so we don't have to lock on every access.
233   TlsMetadata tls_metadata[kThreadLocalStorageSize];
234   {
235     base::AutoLock auto_lock(*GetTLSMetadataLock());
236     memcpy(tls_metadata, g_tls_metadata, sizeof(g_tls_metadata));
237   }
238 
239   int remaining_attempts = kMaxDestructorIterations;
240   bool need_to_scan_destructors = true;
241   while (need_to_scan_destructors) {
242     need_to_scan_destructors = false;
243     // Try to destroy the first-created-slot (which is slot 1) in our last
244     // destructor call. That user was able to function, and define a slot with
245     // no other services running, so perhaps it is a basic service (like an
246     // allocator) and should also be destroyed last. If we get the order wrong,
247     // then we'll iterate several more times, so it is really not that critical
248     // (but it might help).
249     for (int slot = 0; slot < kThreadLocalStorageSize ; ++slot) {
250       void* tls_value = stack_allocated_tls_data[slot].data;
251       if (!tls_value || tls_metadata[slot].status == TlsStatus::FREE ||
252           stack_allocated_tls_data[slot].version != tls_metadata[slot].version)
253         continue;
254 
255       base::ThreadLocalStorage::TLSDestructorFunc destructor =
256           tls_metadata[slot].destructor;
257       if (!destructor)
258         continue;
259       stack_allocated_tls_data[slot].data = nullptr;  // pre-clear the slot.
260       destructor(tls_value);
261       // Any destructor might have called a different service, which then set a
262       // different slot to a non-null value. Hence we need to check the whole
263       // vector again. This is a pthread standard.
264       need_to_scan_destructors = true;
265     }
266     if (--remaining_attempts <= 0) {
267       NOTREACHED();  // Destructors might not have been called.
268       break;
269     }
270   }
271 
272   // Remove our stack allocated vector.
273   PlatformThreadLocalStorage::SetTLSValue(key, kDestroyed);
274 }
275 
276 }  // namespace
277 
278 namespace base {
279 
280 namespace internal {
281 
282 #if defined(OS_WIN)
OnThreadExit()283 void PlatformThreadLocalStorage::OnThreadExit() {
284   PlatformThreadLocalStorage::TLSKey key =
285       base::subtle::NoBarrier_Load(&g_native_tls_key);
286   if (key == PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES)
287     return;
288   void *tls_data = GetTLSValue(key);
289 
290   // On Windows, thread destruction callbacks are only invoked once per module,
291   // so there should be no way that this could be invoked twice.
292   DCHECK_NE(tls_data, kDestroyed);
293 
294   // Maybe we have never initialized TLS for this thread.
295   if (tls_data == kUninitialized)
296     return;
297   OnThreadExitInternal(static_cast<TlsVectorEntry*>(tls_data));
298 }
299 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
300 void PlatformThreadLocalStorage::OnThreadExit(void* value) {
301   OnThreadExitInternal(static_cast<TlsVectorEntry*>(value));
302 }
303 
304 // static
305 void PlatformThreadLocalStorage::ForceFreeTLS() {
306   PlatformThreadLocalStorage::TLSKey key =
307       base::subtle::NoBarrier_AtomicExchange(
308           &g_native_tls_key,
309           PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES);
310   if (key == PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES)
311     return;
312   PlatformThreadLocalStorage::FreeTLS(key);
313 }
314 #endif  // defined(OS_WIN)
315 
316 }  // namespace internal
317 
HasBeenDestroyed()318 bool ThreadLocalStorage::HasBeenDestroyed() {
319   PlatformThreadLocalStorage::TLSKey key =
320       base::subtle::NoBarrier_Load(&g_native_tls_key);
321   if (key == PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES)
322     return false;
323   return PlatformThreadLocalStorage::GetTLSValue(key) == kDestroyed;
324 }
325 
Initialize(TLSDestructorFunc destructor)326 void ThreadLocalStorage::Slot::Initialize(TLSDestructorFunc destructor) {
327   PlatformThreadLocalStorage::TLSKey key =
328       base::subtle::NoBarrier_Load(&g_native_tls_key);
329   if (key == PlatformThreadLocalStorage::TLS_KEY_OUT_OF_INDEXES ||
330       PlatformThreadLocalStorage::GetTLSValue(key) == kUninitialized) {
331     ConstructTlsVector();
332   }
333 
334   // Grab a new slot.
335   {
336     base::AutoLock auto_lock(*GetTLSMetadataLock());
337     for (int i = 0; i < kThreadLocalStorageSize; ++i) {
338       // Tracking the last assigned slot is an attempt to find the next
339       // available slot within one iteration. Under normal usage, slots remain
340       // in use for the lifetime of the process (otherwise before we reclaimed
341       // slots, we would have run out of slots). This makes it highly likely the
342       // next slot is going to be a free slot.
343       size_t slot_candidate =
344           (g_last_assigned_slot + 1 + i) % kThreadLocalStorageSize;
345       if (g_tls_metadata[slot_candidate].status == TlsStatus::FREE) {
346         g_tls_metadata[slot_candidate].status = TlsStatus::IN_USE;
347         g_tls_metadata[slot_candidate].destructor = destructor;
348         g_last_assigned_slot = slot_candidate;
349         DCHECK_EQ(kInvalidSlotValue, slot_);
350         slot_ = slot_candidate;
351         version_ = g_tls_metadata[slot_candidate].version;
352         break;
353       }
354     }
355   }
356   CHECK_NE(slot_, kInvalidSlotValue);
357   CHECK_LT(slot_, kThreadLocalStorageSize);
358 }
359 
Free()360 void ThreadLocalStorage::Slot::Free() {
361   DCHECK_NE(slot_, kInvalidSlotValue);
362   DCHECK_LT(slot_, kThreadLocalStorageSize);
363   {
364     base::AutoLock auto_lock(*GetTLSMetadataLock());
365     g_tls_metadata[slot_].status = TlsStatus::FREE;
366     g_tls_metadata[slot_].destructor = nullptr;
367     ++(g_tls_metadata[slot_].version);
368   }
369   slot_ = kInvalidSlotValue;
370 }
371 
Get() const372 void* ThreadLocalStorage::Slot::Get() const {
373   TlsVectorEntry* tls_data = static_cast<TlsVectorEntry*>(
374       PlatformThreadLocalStorage::GetTLSValue(
375           base::subtle::NoBarrier_Load(&g_native_tls_key)));
376   DCHECK_NE(tls_data, kDestroyed);
377   if (!tls_data)
378     return nullptr;
379   DCHECK_NE(slot_, kInvalidSlotValue);
380   DCHECK_LT(slot_, kThreadLocalStorageSize);
381   // Version mismatches means this slot was previously freed.
382   if (tls_data[slot_].version != version_)
383     return nullptr;
384   return tls_data[slot_].data;
385 }
386 
Set(void * value)387 void ThreadLocalStorage::Slot::Set(void* value) {
388   TlsVectorEntry* tls_data = static_cast<TlsVectorEntry*>(
389       PlatformThreadLocalStorage::GetTLSValue(
390           base::subtle::NoBarrier_Load(&g_native_tls_key)));
391   DCHECK_NE(tls_data, kDestroyed);
392   if (!tls_data)
393     tls_data = ConstructTlsVector();
394   DCHECK_NE(slot_, kInvalidSlotValue);
395   DCHECK_LT(slot_, kThreadLocalStorageSize);
396   tls_data[slot_].data = value;
397   tls_data[slot_].version = version_;
398 }
399 
Slot(TLSDestructorFunc destructor)400 ThreadLocalStorage::Slot::Slot(TLSDestructorFunc destructor) {
401   Initialize(destructor);
402 }
403 
~Slot()404 ThreadLocalStorage::Slot::~Slot() {
405   Free();
406 }
407 
408 }  // namespace base
409