1 /* Copyright (C) 2008, 2009, 2011 Free Software Foundation, Inc.
2 Contributed by Richard Henderson <rth@redhat.com>.
4 This file is part of the GNU Transactional Memory Library (libitm).
6 Libitm is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3 of the License, or
9 (at your option) any later version.
11 Libitm is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13 FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 Under Section 7 of GPL version 3, you are granted additional
17 permissions described in the GCC Runtime Library Exception, version
18 3.1, as published by the Free Software Foundation.
20 You should have received a copy of the GNU General Public License and
21 a copy of the GCC Runtime Library Exception along with this program;
22 see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 <http://www.gnu.org/licenses/>. */
31 #if !defined(HAVE_ARCH_GTM_THREAD) || !defined(HAVE_ARCH_GTM_THREAD_DISP)
32 extern __thread gtm_thread_tls _gtm_thr_tls;
35 gtm_rwlock GTM::gtm_thread::serial_lock;
36 gtm_thread *GTM::gtm_thread::list_of_threads = 0;
37 unsigned GTM::gtm_thread::number_of_threads = 0;
39 gtm_stmlock GTM::gtm_stmlock_array[LOCK_ARRAY_SIZE];
40 gtm_version GTM::gtm_clock;
42 /* ??? Move elsewhere when we figure out library initialization. */
43 uint64_t GTM::gtm_spin_count_var = 1000;
45 static _ITM_transactionId_t global_tid;
47 // Provides a on-thread-exit callback used to release per-thread data.
48 static pthread_key_t thr_release_key;
49 static pthread_once_t thr_release_once = PTHREAD_ONCE_INIT;
52 /* Allocate a transaction structure. */
54 GTM::gtm_thread::operator new (size_t s)
58 assert(s == sizeof(gtm_thread));
60 tx = xmalloc (sizeof (gtm_thread), true);
61 memset (tx, 0, sizeof (gtm_thread));
66 /* Free the given transaction. Raises an error if the transaction is still
69 GTM::gtm_thread::operator delete(void *tx)
75 thread_exit_handler(void *)
77 gtm_thread *thr = gtm_thr();
86 if (pthread_key_create(&thr_release_key, thread_exit_handler))
87 GTM_fatal("Creating thread release TLS key failed.");
91 GTM::gtm_thread::~gtm_thread()
94 GTM_fatal("Thread exit while a transaction is still active.");
96 // Deregister this transaction.
97 serial_lock.write_lock ();
98 gtm_thread **prev = &list_of_threads;
99 for (; *prev; prev = &(*prev)->next_thread)
103 *prev = (*prev)->next_thread;
108 number_of_threads_changed(number_of_threads + 1, number_of_threads);
109 serial_lock.write_unlock ();
112 GTM::gtm_thread::gtm_thread ()
114 // This object's memory has been set to zero by operator new, so no need
115 // to initialize any of the other primitive-type members that do not have
117 shared_state = ~(typeof shared_state)0;
119 // Register this transaction with the list of all threads' transactions.
120 serial_lock.write_lock ();
121 next_thread = list_of_threads;
122 list_of_threads = this;
124 number_of_threads_changed(number_of_threads - 1, number_of_threads);
125 serial_lock.write_unlock ();
127 if (pthread_once(&thr_release_once, thread_exit_init))
128 GTM_fatal("Initializing thread release TLS key failed.");
129 // Any non-null value is sufficient to trigger destruction of this
130 // transaction when the current thread terminates.
131 if (pthread_setspecific(thr_release_key, this))
132 GTM_fatal("Setting thread release TLS key failed.");
137 #ifndef HAVE_64BIT_SYNC_BUILTINS
138 static pthread_mutex_t global_tid_lock = PTHREAD_MUTEX_INITIALIZER;
141 static inline uint32_t choose_code_path(uint32_t prop, abi_dispatch *disp)
143 if ((prop & pr_uninstrumentedCode) && disp->can_run_uninstrumented_code())
144 return a_runUninstrumentedCode;
146 return a_runInstrumentedCode;
150 GTM::gtm_thread::begin_transaction (uint32_t prop, const gtm_jmpbuf *jb)
152 static const _ITM_transactionId_t tid_block_size = 1 << 16;
158 // ??? pr_undoLogCode is not properly defined in the ABI. Are barriers
159 // omitted because they are not necessary (e.g., a transaction on thread-
160 // local data) or because the compiler thinks that some kind of global
161 // synchronization might perform better?
162 if (unlikely(prop & pr_undoLogCode))
163 GTM_fatal("pr_undoLogCode not supported");
166 if (unlikely(tx == NULL))
168 // Create the thread object. The constructor will also set up automatic
169 // deletion on thread termination.
170 tx = new gtm_thread();
176 // This is a nested transaction.
177 // Check prop compatibility:
178 // The ABI requires pr_hasNoFloatUpdate, pr_hasNoVectorUpdate,
179 // pr_hasNoIrrevocable, pr_aWBarriersOmitted, pr_RaRBarriersOmitted, and
180 // pr_hasNoSimpleReads to hold for the full dynamic scope of a
181 // transaction. We could check that these are set for the nested
182 // transaction if they are also set for the parent transaction, but the
183 // ABI does not require these flags to be set if they could be set,
184 // so the check could be too strict.
185 // ??? For pr_readOnly, lexical or dynamic scope is unspecified.
187 if (prop & pr_hasNoAbort)
189 // We can use flat nesting, so elide this transaction.
190 if (!(prop & pr_instrumentedCode))
192 if (!(tx->state & STATE_SERIAL) ||
193 !(tx->state & STATE_IRREVOCABLE))
194 tx->serialirr_mode();
196 // Increment nesting level after checking that we have a method that
197 // allows us to continue.
199 return choose_code_path(prop, abi_disp());
202 // The transaction might abort, so use closed nesting if possible.
203 // pr_hasNoAbort has lexical scope, so the compiler should really have
204 // generated an instrumented code path.
205 assert(prop & pr_instrumentedCode);
207 // Create a checkpoint of the current transaction.
208 gtm_transaction_cp *cp = tx->parent_txns.push();
210 new (&tx->alloc_actions) aa_tree<uintptr_t, gtm_alloc_action>();
212 // Check whether the current method actually supports closed nesting.
213 // If we can switch to another one, do so.
214 // If not, we assume that actual aborts are infrequent, and rather
215 // restart in _ITM_abortTransaction when we really have to.
217 if (!disp->closed_nesting())
219 // ??? Should we elide the transaction if there is no alternative
220 // method that supports closed nesting? If we do, we need to set
221 // some flag to prevent _ITM_abortTransaction from aborting the
222 // wrong transaction (i.e., some parent transaction).
223 abi_dispatch *cn_disp = disp->closed_nesting_alternative();
233 // Outermost transaction
234 disp = tx->decide_begin_dispatch (prop);
235 if (disp == dispatch_serialirr() || disp == dispatch_serial())
237 tx->state = STATE_SERIAL;
238 if (disp == dispatch_serialirr())
239 tx->state |= STATE_IRREVOCABLE;
240 serial_lock.write_lock ();
243 serial_lock.read_lock (tx);
248 // Initialization that is common for outermost and nested transactions.
254 // As long as we have not exhausted a previously allocated block of TIDs,
255 // we can avoid an atomic operation on a shared cacheline.
256 if (tx->local_tid & (tid_block_size - 1))
257 tx->id = tx->local_tid++;
260 #ifdef HAVE_64BIT_SYNC_BUILTINS
261 tx->id = __sync_add_and_fetch (&global_tid, tid_block_size);
262 tx->local_tid = tx->id + 1;
264 pthread_mutex_lock (&global_tid_lock);
265 global_tid += tid_block_size;
267 tx->local_tid = tx->id + 1;
268 pthread_mutex_unlock (&global_tid_lock);
272 // Run dispatch-specific restart code. Retry until we succeed.
273 GTM::gtm_restart_reason rr;
274 while ((rr = disp->begin_or_restart()) != NO_RESTART)
276 tx->decide_retry_strategy(rr);
280 // Determine the code path to run. Only irrevocable transactions cannot be
281 // restarted, so all other transactions need to save live variables.
282 ret = choose_code_path(prop, disp);
283 if (!(tx->state & STATE_IRREVOCABLE))
284 ret |= a_saveLiveVariables;
290 GTM::gtm_transaction_cp::save(gtm_thread* tx)
292 // Save everything that we might have to restore on restarts or aborts.
294 undolog_size = tx->undolog.size();
295 memcpy(&alloc_actions, &tx->alloc_actions, sizeof(alloc_actions));
296 user_actions_size = tx->user_actions.size();
299 cxa_catch_count = tx->cxa_catch_count;
300 cxa_unthrown = tx->cxa_unthrown;
302 nesting = tx->nesting;
306 GTM::gtm_transaction_cp::commit(gtm_thread* tx)
308 // Restore state that is not persistent across commits. Exception handling,
309 // information, nesting level, and any logs do not need to be restored on
310 // commits of nested transactions. Allocation actions must be committed
311 // before committing the snapshot.
313 memcpy(&tx->alloc_actions, &alloc_actions, sizeof(alloc_actions));
320 GTM::gtm_thread::rollback (gtm_transaction_cp *cp, bool aborting)
322 // The undo log is special in that it used for both thread-local and shared
323 // data. Because of the latter, we have to roll it back before any
324 // dispatch-specific rollback (which handles synchronization with other
326 rollback_undolog (cp ? cp->undolog_size : 0);
328 // Perform dispatch-specific rollback.
329 abi_disp()->rollback (cp);
331 // Roll back all actions that are supposed to happen around the transaction.
332 rollback_user_actions (cp ? cp->user_actions_size : 0);
333 commit_allocations (true, (cp ? &cp->alloc_actions : 0));
334 revert_cpp_exceptions (cp);
338 // We do not yet handle restarts of nested transactions. To do that, we
339 // would have to restore some state (jb, id, prop, nesting) not to the
340 // checkpoint but to the transaction that was started from this
341 // checkpoint (e.g., nesting = cp->nesting + 1);
343 // Roll back the rest of the state to the checkpoint.
347 if (cp->disp != abi_disp())
348 set_abi_disp(cp->disp);
349 memcpy(&alloc_actions, &cp->alloc_actions, sizeof(alloc_actions));
350 nesting = cp->nesting;
354 // Roll back to the outermost transaction.
355 // Restore the jump buffer and transaction properties, which we will
356 // need for the longjmp used to restart or abort the transaction.
357 if (parent_txns.size() > 0)
359 jb = parent_txns[0].jb;
360 id = parent_txns[0].id;
361 prop = parent_txns[0].prop;
363 // Reset the transaction. Do not reset this->state, which is handled by
364 // the callers. Note that if we are not aborting, we reset the
365 // transaction to the point after having executed begin_transaction
366 // (we will return from it), so the nesting level must be one, not zero.
367 nesting = (aborting ? 0 : 1);
371 if (this->eh_in_flight)
373 _Unwind_DeleteException ((_Unwind_Exception *) this->eh_in_flight);
374 this->eh_in_flight = NULL;
379 _ITM_abortTransaction (_ITM_abortReason reason)
381 gtm_thread *tx = gtm_thr();
383 assert (reason == userAbort || reason == (userAbort | outerAbort));
384 assert ((tx->prop & pr_hasNoAbort) == 0);
386 if (tx->state & gtm_thread::STATE_IRREVOCABLE)
389 // Roll back to innermost transaction.
390 if (tx->parent_txns.size() > 0 && !(reason & outerAbort))
392 // If the current method does not support closed nesting but we are
393 // nested and must only roll back the innermost transaction, then
394 // restart with a method that supports closed nesting.
395 abi_dispatch *disp = abi_disp();
396 if (!disp->closed_nesting())
397 tx->restart(RESTART_CLOSED_NESTING);
399 // The innermost transaction is a closed nested transaction.
400 gtm_transaction_cp *cp = tx->parent_txns.pop();
401 uint32_t longjmp_prop = tx->prop;
402 gtm_jmpbuf longjmp_jb = tx->jb;
404 tx->rollback (cp, true);
406 // Jump to nested transaction (use the saved jump buffer).
407 GTM_longjmp (a_abortTransaction | a_restoreLiveVariables,
408 &longjmp_jb, longjmp_prop);
412 // There is no nested transaction or an abort of the outermost
413 // transaction was requested, so roll back to the outermost transaction.
414 tx->rollback (0, true);
416 // Aborting an outermost transaction finishes execution of the whole
417 // transaction. Therefore, reset transaction state.
418 if (tx->state & gtm_thread::STATE_SERIAL)
419 gtm_thread::serial_lock.write_unlock ();
421 gtm_thread::serial_lock.read_unlock (tx);
424 GTM_longjmp (a_abortTransaction | a_restoreLiveVariables,
430 GTM::gtm_thread::trycommit ()
434 // Skip any real commit for elided transactions.
435 if (nesting > 0 && (parent_txns.size() == 0 ||
436 nesting > parent_txns[parent_txns.size() - 1].nesting))
441 // Commit of a closed-nested transaction. Remove one checkpoint and add
442 // any effects of this transaction to the parent transaction.
443 gtm_transaction_cp *cp = parent_txns.pop();
444 commit_allocations(false, &cp->alloc_actions);
449 // Commit of an outermost transaction.
450 gtm_word priv_time = 0;
451 if (abi_disp()->trycommit (priv_time))
453 // The transaction is now inactive. Everything that we still have to do
454 // will not synchronize with other transactions anymore.
455 if (state & gtm_thread::STATE_SERIAL)
456 gtm_thread::serial_lock.write_unlock ();
458 gtm_thread::serial_lock.read_unlock (this);
461 // We can commit the undo log after dispatch-specific commit and after
462 // making the transaction inactive because we only have to reset
465 // Reset further transaction state.
470 // Ensure privatization safety, if necessary.
473 // TODO Don't just spin but also block using cond vars / futexes
474 // here. Should probably be integrated with the serial lock code.
475 // TODO For C++0x atomics, the loads of other threads' shared_state
476 // should have acquire semantics (together with releases for the
477 // respective updates). But is this unnecessary overhead because
478 // weaker barriers are sufficient?
479 for (gtm_thread *it = gtm_thread::list_of_threads; it != 0;
480 it = it->next_thread)
482 if (it == this) continue;
483 while (it->shared_state < priv_time)
488 // After ensuring privatization safety, we execute potentially
489 // privatizing actions (e.g., calling free()). User actions are first.
490 commit_user_actions ();
491 commit_allocations (false, 0);
499 GTM::gtm_thread::restart (gtm_restart_reason r)
501 // Roll back to outermost transaction. Do not reset transaction state because
502 // we will continue executing this transaction.
504 decide_retry_strategy (r);
506 // Run dispatch-specific restart code. Retry until we succeed.
507 abi_dispatch* disp = abi_disp();
508 GTM::gtm_restart_reason rr;
509 while ((rr = disp->begin_or_restart()) != NO_RESTART)
511 decide_retry_strategy(rr);
515 GTM_longjmp (choose_code_path(prop, disp) | a_restoreLiveVariables,
520 _ITM_commitTransaction(void)
522 gtm_thread *tx = gtm_thr();
523 if (!tx->trycommit ())
524 tx->restart (RESTART_VALIDATE_COMMIT);
528 _ITM_commitTransactionEH(void *exc_ptr)
530 gtm_thread *tx = gtm_thr();
531 if (!tx->trycommit ())
533 tx->eh_in_flight = exc_ptr;
534 tx->restart (RESTART_VALIDATE_COMMIT);