2011-12-19 Sandra Loosemore <sandra@codesourcery.com>
[official-gcc.git] / libitm / beginend.cc
blobbcc8516be05de2211bae45f03e1cb7a79eccc04b
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
14 more details.
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/>. */
25 #include "libitm_i.h"
26 #include <pthread.h>
29 using namespace GTM;
31 #if !defined(HAVE_ARCH_GTM_THREAD) || !defined(HAVE_ARCH_GTM_THREAD_DISP)
32 extern __thread gtm_thread_tls _gtm_thr_tls;
33 #endif
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 atomic<gtm_version> GTM::gtm_clock;
42 /* ??? Move elsewhere when we figure out library initialization. */
43 uint64_t GTM::gtm_spin_count_var = 1000;
45 #ifdef HAVE_64BIT_SYNC_BUILTINS
46 static atomic<_ITM_transactionId_t> global_tid;
47 #else
48 static _ITM_transactionId_t global_tid;
49 static pthread_mutex_t global_tid_lock = PTHREAD_MUTEX_INITIALIZER;
50 #endif
53 // Provides a on-thread-exit callback used to release per-thread data.
54 static pthread_key_t thr_release_key;
55 static pthread_once_t thr_release_once = PTHREAD_ONCE_INIT;
58 /* Allocate a transaction structure. */
59 void *
60 GTM::gtm_thread::operator new (size_t s)
62 void *tx;
64 assert(s == sizeof(gtm_thread));
66 tx = xmalloc (sizeof (gtm_thread), true);
67 memset (tx, 0, sizeof (gtm_thread));
69 return tx;
72 /* Free the given transaction. Raises an error if the transaction is still
73 in use. */
74 void
75 GTM::gtm_thread::operator delete(void *tx)
77 free(tx);
80 static void
81 thread_exit_handler(void *)
83 gtm_thread *thr = gtm_thr();
84 if (thr)
85 delete thr;
86 set_gtm_thr(0);
89 static void
90 thread_exit_init()
92 if (pthread_key_create(&thr_release_key, thread_exit_handler))
93 GTM_fatal("Creating thread release TLS key failed.");
97 GTM::gtm_thread::~gtm_thread()
99 if (nesting > 0)
100 GTM_fatal("Thread exit while a transaction is still active.");
102 // Deregister this transaction.
103 serial_lock.write_lock ();
104 gtm_thread **prev = &list_of_threads;
105 for (; *prev; prev = &(*prev)->next_thread)
107 if (*prev == this)
109 *prev = (*prev)->next_thread;
110 break;
113 number_of_threads--;
114 number_of_threads_changed(number_of_threads + 1, number_of_threads);
115 serial_lock.write_unlock ();
118 GTM::gtm_thread::gtm_thread ()
120 // This object's memory has been set to zero by operator new, so no need
121 // to initialize any of the other primitive-type members that do not have
122 // constructors.
123 shared_state.store(-1, memory_order_relaxed);
125 // Register this transaction with the list of all threads' transactions.
126 serial_lock.write_lock ();
127 next_thread = list_of_threads;
128 list_of_threads = this;
129 number_of_threads++;
130 number_of_threads_changed(number_of_threads - 1, number_of_threads);
131 serial_lock.write_unlock ();
133 if (pthread_once(&thr_release_once, thread_exit_init))
134 GTM_fatal("Initializing thread release TLS key failed.");
135 // Any non-null value is sufficient to trigger destruction of this
136 // transaction when the current thread terminates.
137 if (pthread_setspecific(thr_release_key, this))
138 GTM_fatal("Setting thread release TLS key failed.");
141 static inline uint32_t
142 choose_code_path(uint32_t prop, abi_dispatch *disp)
144 if ((prop & pr_uninstrumentedCode) && disp->can_run_uninstrumented_code())
145 return a_runUninstrumentedCode;
146 else
147 return a_runInstrumentedCode;
150 uint32_t
151 GTM::gtm_thread::begin_transaction (uint32_t prop, const gtm_jmpbuf *jb)
153 static const _ITM_transactionId_t tid_block_size = 1 << 16;
155 gtm_thread *tx;
156 abi_dispatch *disp;
157 uint32_t ret;
159 // ??? pr_undoLogCode is not properly defined in the ABI. Are barriers
160 // omitted because they are not necessary (e.g., a transaction on thread-
161 // local data) or because the compiler thinks that some kind of global
162 // synchronization might perform better?
163 if (unlikely(prop & pr_undoLogCode))
164 GTM_fatal("pr_undoLogCode not supported");
166 tx = gtm_thr();
167 if (unlikely(tx == NULL))
169 // Create the thread object. The constructor will also set up automatic
170 // deletion on thread termination.
171 tx = new gtm_thread();
172 set_gtm_thr(tx);
175 if (tx->nesting > 0)
177 // This is a nested transaction.
178 // Check prop compatibility:
179 // The ABI requires pr_hasNoFloatUpdate, pr_hasNoVectorUpdate,
180 // pr_hasNoIrrevocable, pr_aWBarriersOmitted, pr_RaRBarriersOmitted, and
181 // pr_hasNoSimpleReads to hold for the full dynamic scope of a
182 // transaction. We could check that these are set for the nested
183 // transaction if they are also set for the parent transaction, but the
184 // ABI does not require these flags to be set if they could be set,
185 // so the check could be too strict.
186 // ??? For pr_readOnly, lexical or dynamic scope is unspecified.
188 if (prop & pr_hasNoAbort)
190 // We can use flat nesting, so elide this transaction.
191 if (!(prop & pr_instrumentedCode))
193 if (!(tx->state & STATE_SERIAL) ||
194 !(tx->state & STATE_IRREVOCABLE))
195 tx->serialirr_mode();
197 // Increment nesting level after checking that we have a method that
198 // allows us to continue.
199 tx->nesting++;
200 return choose_code_path(prop, abi_disp());
203 // The transaction might abort, so use closed nesting if possible.
204 // pr_hasNoAbort has lexical scope, so the compiler should really have
205 // generated an instrumented code path.
206 assert(prop & pr_instrumentedCode);
208 // Create a checkpoint of the current transaction.
209 gtm_transaction_cp *cp = tx->parent_txns.push();
210 cp->save(tx);
211 new (&tx->alloc_actions) aa_tree<uintptr_t, gtm_alloc_action>();
213 // Check whether the current method actually supports closed nesting.
214 // If we can switch to another one, do so.
215 // If not, we assume that actual aborts are infrequent, and rather
216 // restart in _ITM_abortTransaction when we really have to.
217 disp = abi_disp();
218 if (!disp->closed_nesting())
220 // ??? Should we elide the transaction if there is no alternative
221 // method that supports closed nesting? If we do, we need to set
222 // some flag to prevent _ITM_abortTransaction from aborting the
223 // wrong transaction (i.e., some parent transaction).
224 abi_dispatch *cn_disp = disp->closed_nesting_alternative();
225 if (cn_disp)
227 disp = cn_disp;
228 set_abi_disp(disp);
232 else
234 // Outermost transaction
235 disp = tx->decide_begin_dispatch (prop);
236 if (disp == dispatch_serialirr() || disp == dispatch_serial())
238 tx->state = STATE_SERIAL;
239 if (disp == dispatch_serialirr())
240 tx->state |= STATE_IRREVOCABLE;
241 serial_lock.write_lock ();
243 else
244 serial_lock.read_lock (tx);
246 set_abi_disp (disp);
249 // Initialization that is common for outermost and nested transactions.
250 tx->prop = prop;
251 tx->nesting++;
253 tx->jb = *jb;
255 // As long as we have not exhausted a previously allocated block of TIDs,
256 // we can avoid an atomic operation on a shared cacheline.
257 if (tx->local_tid & (tid_block_size - 1))
258 tx->id = tx->local_tid++;
259 else
261 #ifdef HAVE_64BIT_SYNC_BUILTINS
262 tx->id = global_tid.fetch_add(tid_block_size, memory_order_relaxed);
263 tx->local_tid = tx->id + 1;
264 #else
265 pthread_mutex_lock (&global_tid_lock);
266 global_tid += tid_block_size;
267 tx->id = global_tid;
268 tx->local_tid = tx->id + 1;
269 pthread_mutex_unlock (&global_tid_lock);
270 #endif
273 // Run dispatch-specific restart code. Retry until we succeed.
274 GTM::gtm_restart_reason rr;
275 while ((rr = disp->begin_or_restart()) != NO_RESTART)
277 tx->decide_retry_strategy(rr);
278 disp = abi_disp();
281 // Determine the code path to run. Only irrevocable transactions cannot be
282 // restarted, so all other transactions need to save live variables.
283 ret = choose_code_path(prop, disp);
284 if (!(tx->state & STATE_IRREVOCABLE))
285 ret |= a_saveLiveVariables;
286 return ret;
290 void
291 GTM::gtm_transaction_cp::save(gtm_thread* tx)
293 // Save everything that we might have to restore on restarts or aborts.
294 jb = tx->jb;
295 undolog_size = tx->undolog.size();
296 memcpy(&alloc_actions, &tx->alloc_actions, sizeof(alloc_actions));
297 user_actions_size = tx->user_actions.size();
298 id = tx->id;
299 prop = tx->prop;
300 cxa_catch_count = tx->cxa_catch_count;
301 cxa_unthrown = tx->cxa_unthrown;
302 disp = abi_disp();
303 nesting = tx->nesting;
306 void
307 GTM::gtm_transaction_cp::commit(gtm_thread* tx)
309 // Restore state that is not persistent across commits. Exception handling,
310 // information, nesting level, and any logs do not need to be restored on
311 // commits of nested transactions. Allocation actions must be committed
312 // before committing the snapshot.
313 tx->jb = jb;
314 memcpy(&tx->alloc_actions, &alloc_actions, sizeof(alloc_actions));
315 tx->id = id;
316 tx->prop = prop;
320 void
321 GTM::gtm_thread::rollback (gtm_transaction_cp *cp, bool aborting)
323 // The undo log is special in that it used for both thread-local and shared
324 // data. Because of the latter, we have to roll it back before any
325 // dispatch-specific rollback (which handles synchronization with other
326 // transactions).
327 rollback_undolog (cp ? cp->undolog_size : 0);
329 // Perform dispatch-specific rollback.
330 abi_disp()->rollback (cp);
332 // Roll back all actions that are supposed to happen around the transaction.
333 rollback_user_actions (cp ? cp->user_actions_size : 0);
334 commit_allocations (true, (cp ? &cp->alloc_actions : 0));
335 revert_cpp_exceptions (cp);
337 if (cp)
339 // We do not yet handle restarts of nested transactions. To do that, we
340 // would have to restore some state (jb, id, prop, nesting) not to the
341 // checkpoint but to the transaction that was started from this
342 // checkpoint (e.g., nesting = cp->nesting + 1);
343 assert(aborting);
344 // Roll back the rest of the state to the checkpoint.
345 jb = cp->jb;
346 id = cp->id;
347 prop = cp->prop;
348 if (cp->disp != abi_disp())
349 set_abi_disp(cp->disp);
350 memcpy(&alloc_actions, &cp->alloc_actions, sizeof(alloc_actions));
351 nesting = cp->nesting;
353 else
355 // Roll back to the outermost transaction.
356 // Restore the jump buffer and transaction properties, which we will
357 // need for the longjmp used to restart or abort the transaction.
358 if (parent_txns.size() > 0)
360 jb = parent_txns[0].jb;
361 id = parent_txns[0].id;
362 prop = parent_txns[0].prop;
364 // Reset the transaction. Do not reset this->state, which is handled by
365 // the callers. Note that if we are not aborting, we reset the
366 // transaction to the point after having executed begin_transaction
367 // (we will return from it), so the nesting level must be one, not zero.
368 nesting = (aborting ? 0 : 1);
369 parent_txns.clear();
372 if (this->eh_in_flight)
374 _Unwind_DeleteException ((_Unwind_Exception *) this->eh_in_flight);
375 this->eh_in_flight = NULL;
379 void ITM_REGPARM
380 _ITM_abortTransaction (_ITM_abortReason reason)
382 gtm_thread *tx = gtm_thr();
384 assert (reason == userAbort || reason == (userAbort | outerAbort));
385 assert ((tx->prop & pr_hasNoAbort) == 0);
387 if (tx->state & gtm_thread::STATE_IRREVOCABLE)
388 abort ();
390 // Roll back to innermost transaction.
391 if (tx->parent_txns.size() > 0 && !(reason & outerAbort))
393 // If the current method does not support closed nesting but we are
394 // nested and must only roll back the innermost transaction, then
395 // restart with a method that supports closed nesting.
396 abi_dispatch *disp = abi_disp();
397 if (!disp->closed_nesting())
398 tx->restart(RESTART_CLOSED_NESTING);
400 // The innermost transaction is a closed nested transaction.
401 gtm_transaction_cp *cp = tx->parent_txns.pop();
402 uint32_t longjmp_prop = tx->prop;
403 gtm_jmpbuf longjmp_jb = tx->jb;
405 tx->rollback (cp, true);
407 // Jump to nested transaction (use the saved jump buffer).
408 GTM_longjmp (a_abortTransaction | a_restoreLiveVariables,
409 &longjmp_jb, longjmp_prop);
411 else
413 // There is no nested transaction or an abort of the outermost
414 // transaction was requested, so roll back to the outermost transaction.
415 tx->rollback (0, true);
417 // Aborting an outermost transaction finishes execution of the whole
418 // transaction. Therefore, reset transaction state.
419 if (tx->state & gtm_thread::STATE_SERIAL)
420 gtm_thread::serial_lock.write_unlock ();
421 else
422 gtm_thread::serial_lock.read_unlock (tx);
423 tx->state = 0;
425 GTM_longjmp (a_abortTransaction | a_restoreLiveVariables,
426 &tx->jb, tx->prop);
430 bool
431 GTM::gtm_thread::trycommit ()
433 nesting--;
435 // Skip any real commit for elided transactions.
436 if (nesting > 0 && (parent_txns.size() == 0 ||
437 nesting > parent_txns[parent_txns.size() - 1].nesting))
438 return true;
440 if (nesting > 0)
442 // Commit of a closed-nested transaction. Remove one checkpoint and add
443 // any effects of this transaction to the parent transaction.
444 gtm_transaction_cp *cp = parent_txns.pop();
445 commit_allocations(false, &cp->alloc_actions);
446 cp->commit(this);
447 return true;
450 // Commit of an outermost transaction.
451 gtm_word priv_time = 0;
452 if (abi_disp()->trycommit (priv_time))
454 // The transaction is now inactive. Everything that we still have to do
455 // will not synchronize with other transactions anymore.
456 if (state & gtm_thread::STATE_SERIAL)
457 gtm_thread::serial_lock.write_unlock ();
458 else
459 gtm_thread::serial_lock.read_unlock (this);
460 state = 0;
462 // We can commit the undo log after dispatch-specific commit and after
463 // making the transaction inactive because we only have to reset
464 // gtm_thread state.
465 commit_undolog ();
466 // Reset further transaction state.
467 cxa_catch_count = 0;
468 cxa_unthrown = NULL;
469 restart_total = 0;
471 // Ensure privatization safety, if necessary.
472 if (priv_time)
474 // TODO Don't just spin but also block using cond vars / futexes
475 // here. Should probably be integrated with the serial lock code.
476 // TODO For C++0x atomics, the loads of other threads' shared_state
477 // should have acquire semantics (together with releases for the
478 // respective updates). But is this unnecessary overhead because
479 // weaker barriers are sufficient?
480 for (gtm_thread *it = gtm_thread::list_of_threads; it != 0;
481 it = it->next_thread)
483 if (it == this) continue;
484 while (it->shared_state.load(memory_order_relaxed) < priv_time)
485 cpu_relax();
489 // After ensuring privatization safety, we execute potentially
490 // privatizing actions (e.g., calling free()). User actions are first.
491 commit_user_actions ();
492 commit_allocations (false, 0);
494 return true;
496 return false;
499 void ITM_NORETURN
500 GTM::gtm_thread::restart (gtm_restart_reason r)
502 // Roll back to outermost transaction. Do not reset transaction state because
503 // we will continue executing this transaction.
504 rollback ();
505 decide_retry_strategy (r);
507 // Run dispatch-specific restart code. Retry until we succeed.
508 abi_dispatch* disp = abi_disp();
509 GTM::gtm_restart_reason rr;
510 while ((rr = disp->begin_or_restart()) != NO_RESTART)
512 decide_retry_strategy(rr);
513 disp = abi_disp();
516 GTM_longjmp (choose_code_path(prop, disp) | a_restoreLiveVariables,
517 &jb, prop);
520 void ITM_REGPARM
521 _ITM_commitTransaction(void)
523 gtm_thread *tx = gtm_thr();
524 if (!tx->trycommit ())
525 tx->restart (RESTART_VALIDATE_COMMIT);
528 void ITM_REGPARM
529 _ITM_commitTransactionEH(void *exc_ptr)
531 gtm_thread *tx = gtm_thr();
532 if (!tx->trycommit ())
534 tx->eh_in_flight = exc_ptr;
535 tx->restart (RESTART_VALIDATE_COMMIT);